hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
list
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
list
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
list
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
list
cell_types
list
cell_type_groups
list
cbdcf4b78953d52f4f95c6f66d8b3e3e3d116311
4,270
ipynb
Jupyter Notebook
ex0-nb.ipynb
WolfgangFahl/ploomberexample
6f45ebe329a7b4e7b5dc516747ce4637128b0875
[ "Apache-2.0" ]
null
null
null
ex0-nb.ipynb
WolfgangFahl/ploomberexample
6f45ebe329a7b4e7b5dc516747ce4637128b0875
[ "Apache-2.0" ]
null
null
null
ex0-nb.ipynb
WolfgangFahl/ploomberexample
6f45ebe329a7b4e7b5dc516747ce4637128b0875
[ "Apache-2.0" ]
null
null
null
25.416667
104
0.535597
[ [ [ "# declare a list tasks whose products you want to use as inputs\nupstream = None\n", "_____no_output_____" ], [ "# Parameters\nproduct = {\"nb\": \"/Users/wf/source/jupyter/ploomberexample/ex0-nb.ipynb\"}\n", "_____no_output_____" ], [ "from IPython.display import HTML\nHTML(filename='header.html')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cbdcf596b47a7f4cf3a259c45f41208634f0a4d9
1,841
ipynb
Jupyter Notebook
softmax.ipynb
prateeksawhney97/Introduction-to-TensorFlow
c0941853f9b108489e445eb9a7e0198ca6ccb125
[ "MIT" ]
null
null
null
softmax.ipynb
prateeksawhney97/Introduction-to-TensorFlow
c0941853f9b108489e445eb9a7e0198ca6ccb125
[ "MIT" ]
null
null
null
softmax.ipynb
prateeksawhney97/Introduction-to-TensorFlow
c0941853f9b108489e445eb9a7e0198ca6ccb125
[ "MIT" ]
null
null
null
21.658824
77
0.491581
[ [ [ "# Solution is available in the other \"solution.ipynb\" \nimport tensorflow as tf\n\n\ndef run():\n output = None\n logit_data = [2.0, 1.0, 0.1]\n logits = tf.placeholder(tf.float32)\n \n # TODO: Calculate the softmax of the logits\n softmax = tf.nn.softmax(logits) \n \n with tf.Session() as sess:\n output = sess.run(softmax, feed_dict = {logits: logit_data})\n # TODO: Feed in the logit data\n # output = sess.run(softmax, )\n\n return output", "_____no_output_____" ], [ "### DON'T MODIFY ANYTHING BELOW ###\n### Be sure to run all cells above before running this cell ###\nimport grader\n\ntry:\n grader.run_grader(run)\nexcept Exception as err:\n print(str(err))", "That's the correct softmax!\n\n\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
cbdd05a1b3919a3e3c502ad8bd7d3528b8f583b8
25,030
ipynb
Jupyter Notebook
Assingments/module05/students/module6_ir/practices/Practice_06.01_Classification.ipynb
tonysulfaro/MI-250
e746fd261107531e100a5cb98d6b6c90bd9234d8
[ "MIT" ]
null
null
null
Assingments/module05/students/module6_ir/practices/Practice_06.01_Classification.ipynb
tonysulfaro/MI-250
e746fd261107531e100a5cb98d6b6c90bd9234d8
[ "MIT" ]
null
null
null
Assingments/module05/students/module6_ir/practices/Practice_06.01_Classification.ipynb
tonysulfaro/MI-250
e746fd261107531e100a5cb98d6b6c90bd9234d8
[ "MIT" ]
null
null
null
76.310976
1,364
0.645825
[ [ [ "\n## Practice: Sentiment Analysis Classification\n\nIn this notebook we will try to solve a classification problem where the goal is to classify movie reviews based on sentiment, negative or positive. This notebook presents the problem in its simplest terms unlike the sophisticated sentiment analysis which is done based on the presence or absence of specific words. We will use scikit learn data loading functionality to build training and testing data.\n\nThe notebook is partially complete. Look for \"Your code here\" to complete the partial code.\n\n-----", "_____no_output_____" ], [ "**Activity 1: ** Load the data from '../../../datasets/movie_reviews' into the mvr variable", "_____no_output_____" ] ], [ [ "import nltk\nmvr = nltk.corpus.movie_reviews\n\nfrom sklearn.datasets import load_files\n\ndata_dir = '../../datasets/movie_reviews'\n# <Your code here to load the movie reviews data in above path>\nmvr = load_files(data_dir)\n\n#help(mvr)\n\n# <Your code here to print the number of reviews>\nprint('Number of Reviews: {0}'.format(len(mvr['data'])))", "Number of Reviews: 2000\n" ] ], [ [ "**Activity 2: ** Split the data in mvr.data into train(mvr_train) and test(mvr_test) datasets", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\n\nmvr_train, mvr_test, y_train, y_test = train_test_split(\n mvr.data, \n mvr.target, \n test_size=0.25, random_state=23)", "_____no_output_____" ] ], [ [ "-----\n\nNow that the training and testing data have been loaded into the notebook, we can build a simple pipeline by using a `CountVectorizer` and `MultinomialNB` to build a document-term matrix and to perform a Naive Bayes classification.\n\n-----", "_____no_output_____" ], [ "**Activity 3: ** Build a pipeline by using a `CountVectorizer` and `MultinomialNB` to build a document-term matrix and to perform a Naive Bayes classification. Print the metrics of classification result.", "_____no_output_____" ] ], [ [ "# Build simple pipeline\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn import metrics\n\npipeline = Pipeline([('cv', CountVectorizer()), ('nb', MultinomialNB())])\n\n# Build DTM and classify data\npipeline.fit(mvr_train, y_train)\n\n# Predict the reviews on mvr_test data\ny_pred = pipeline.predict(mvr_test)\n\n# Print the prediction results\nprint(metrics.classification_report(y_test, y_pred, target_names = mvr.target_names))", " precision recall f1-score support\n\n neg 0.78 0.81 0.80 235\n pos 0.83 0.80 0.81 265\n\n micro avg 0.81 0.81 0.81 500\n macro avg 0.81 0.81 0.81 500\nweighted avg 0.81 0.81 0.81 500\n\n" ] ], [ [ "**Activity 4: ** Use stop words in above `CountVectorizer`. Build the document-term matrix and perform a Naive Bayes classification again. Print the metrics of the new classification results.", "_____no_output_____" ] ], [ [ "pipeline = Pipeline([\n ('vect', CountVectorizer()),\n ('clf', MultinomialNB()),\n])\n\npipeline.set_params(tf__stop_words = 'english')\n\n# Build DTM and classify data\npipeline.fit(mvr_train, y_train)\ny_pred = pipeline.predict(mvr_test)\nprint(metrics.classification_report(y_test, y_pred, target_names = mvr.target_names))", "_____no_output_____" ] ], [ [ "**Activity 5: ** Change the vectorizer to TF-IDF. Perform a Naive Bayes classification again. Print the metrics of new classification results.", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction.text import TfidfVectorizer\n\npipeline = Pipeline([('tfidf',TfidfVectorizer()),('nb', MultinomialNB())])\n\npipeline.set_params(tf__stop_words = 'english')\n\n\n# Build DTM and classify data\nclf.fit(mvr_train, y_train)\ny_pred = clf.predict(mvr_test)\nprint(metrics.classification_report(y_test, y_pred, target_names = mvr.target_names))", "_____no_output_____" ] ], [ [ "**Activity 6: ** Change the TF-IDF parameters, such as `max_features` and `lowercase`. perform a Naive Bayes classification again. Print the metrics of the new classification results.\n\nNote: Find the documentation for [TfidfVectorizer here](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html) to find the right values for max_features and lowercase. Play around with the parameter to see how results are changing.", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction.text import TfidfVectorizer\n\ntools = [('tf', TfidfVectorizer()), ('nb', MultinomialNB())]\nclf = Pipeline(tools)\nclf.<Your code to use max_features and lowercase with TfidfVectorizer>\n\n\n# Build DTM and classify data\nclf.fit(mvr_train, y_train)\ny_pred = clf.predict(mvr_test)\nprint(metrics.classification_report(y_test, y_pred, target_names = mvr.target_names))", "_____no_output_____" ] ], [ [ "**Activity 7: ** Change the classifier to the logistic regression algorithm. Print the results metrics.", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\n\n\ntools = [('vect', CountVectorizer(stop_words = 'english')),\n ('tfidf', TfidfVectorizer()),\n ('lr', LogisticRegression())]\nclf = Pipeline(tools)\nclf.set_params(tf__stop_words = 'english')\n\n\n# Build DTM and classify data\nclf.fit(mvr_train, y_train)\ny_pred = clf.predict(mvr_test)\nprint(metrics.classification_report(y_test, y_pred, target_names = mvr.target_names))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbdd0883b9030455a31603935df4d79a81df93c5
222,500
ipynb
Jupyter Notebook
notebooks/Prophet_QuickStart_Example.ipynb
ajrader/timeseries
fc84dc0d4699570ae0c39a81ba2af41600a96ba4
[ "Apache-2.0" ]
null
null
null
notebooks/Prophet_QuickStart_Example.ipynb
ajrader/timeseries
fc84dc0d4699570ae0c39a81ba2af41600a96ba4
[ "Apache-2.0" ]
null
null
null
notebooks/Prophet_QuickStart_Example.ipynb
ajrader/timeseries
fc84dc0d4699570ae0c39a81ba2af41600a96ba4
[ "Apache-2.0" ]
null
null
null
505.681818
141,974
0.927676
[ [ [ "# Working with FB Prophet\n## begin with [Quick Start](https://facebookincubator.github.io/prophet/docs/quick_start.html) example from FB page \n\nLok at time series of daily page views fro the Wikipedia page for Peyton Manning. The csv is available [here](https://github.com/facebookincubator/prophet/blob/master/examples/example_wp_peyton_manning.csv)", "_____no_output_____" ] ], [ [ "peyton_dataset_url = 'https://github.com/facebookincubator/prophet/blob/master/examples/example_wp_peyton_manning.csv'\npeyton_filename = '../datasets/example_wp_peyton_manning.csv'", "_____no_output_____" ], [ "import pandas as pd\nimport numpy as np\nfrom fbprophet import Prophet", "_____no_output_____" ], [ "# NB: this didn't work as of 8/22/17\n#import io\n#import requests\n#s=requests.get(peyton_dataset_url).content\n#df=pd.read_csv(io.StringIO(s.decode('utf-8')))#df = pd.read_csv(peyton_dataset_url)", "_____no_output_____" ], [ "df = pd.read_csv(peyton_filename)", "_____no_output_____" ], [ "# transform to log scale\ndf['y']=np.log(df['y'])\ndf.head()", "_____no_output_____" ] ], [ [ "Fit the model by instantiating a new `Prophet` object. Any settings required for the forecasting procedure are passed to this object upon construction. You then can call this object's `fit` method and pass in the historical dataframe. Fitting should take 1-5 seconds.", "_____no_output_____" ] ], [ [ "m = Prophet()\nm.fit(df);", "_____no_output_____" ] ], [ [ "Predictions are then made on a dataframe with a column `ds` containing the dates for which a prediction is to be made. You can get a suitable dataframe that extends into the future a specified number of days using the helper method `Prophet.make_future_dataframe`. By default it will also include the dates from the history, so we will see the model fit as well.", "_____no_output_____" ] ], [ [ "future = m.make_future_dataframe(periods=365)\nfuture.tail()", "_____no_output_____" ] ], [ [ "The `predict` method will assign each row in `future` a predicted value which it names `yhat`. If you pass in historical dates, it will provide an in-sample fit. The `forecast` object here is a new dataframe that includes a column `yhat` with the forecast, as well as columns for components and uncertainty intervals.", "_____no_output_____" ] ], [ [ "forecast = m.predict(future)\nforecast[['ds','yhat','yhat_lower','yhat_upper']].tail()", "_____no_output_____" ] ], [ [ "You can plot the forecast by calling the `Prophet.plot` method and passing in your forecast dataframe", "_____no_output_____" ] ], [ [ "m.plot(forecast)", "_____no_output_____" ] ], [ [ "If you want to see the forecast components, you can use the `Prophet.plot_components` method. By default you’ll see the trend, yearly seasonality, and weekly seasonality of the time series. \nIf you include holidays, you’ll see those here, too.", "_____no_output_____" ] ], [ [ "m.plot_components(forecast)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbdd0b927dea07c27c0e2891edfc1c80d14f55c6
4,924
ipynb
Jupyter Notebook
tutorials/tutorial04_visualize.ipynb
weizi-li/flow
958b64ece8af6db715e6fb3b6042035b05b93bc2
[ "MIT" ]
null
null
null
tutorials/tutorial04_visualize.ipynb
weizi-li/flow
958b64ece8af6db715e6fb3b6042035b05b93bc2
[ "MIT" ]
null
null
null
tutorials/tutorial04_visualize.ipynb
weizi-li/flow
958b64ece8af6db715e6fb3b6042035b05b93bc2
[ "MIT" ]
null
null
null
29.309524
401
0.624289
[ [ [ "# Tutorial 04: Visualizing Experiment Results", "_____no_output_____" ], [ "This tutorial describes the process of visualizing and replaying the results of Flow experiments run using RL. The process of visualizing results breaks down into two main components:\n\n- reward plotting\n\n- policy replay\n\nNote that this tutorial only talks about visualization using sumo, and not other simulators like Aimsun. ", "_____no_output_____" ], [ "<hr>\n\n## Visualization with RLlib", "_____no_output_____" ], [ "### Plotting Reward\n\nSimilarly to how rllab handles reward plotting, RLlib supports reward visualization over the period of training using `tensorboard`. `tensorboard` takes one command-line input, `--logdir`, which is an rllib result directory (usually located within an experiment directory inside your `ray_results` directory). An example function call is below.", "_____no_output_____" ] ], [ [ "! tensorboard --logdir /ray_results/dirthatcontainsallcheckpoints/", "_____no_output_____" ] ], [ [ "If you do not wish to use `tensorboard`, you can also use the `flow/visualize/plot_ray_results.py` file. It takes as arguments the path to the `progress.csv` file located inside your experiment results directory, and the name(s) of the column(s) to plot. If you do not know what the name of the columns are, simply do not put any and a list of all available columns will be displayed to you. \n\nExample usage:", "_____no_output_____" ] ], [ [ "! plot_ray_results.py /ray_results/experiment_dir/progress.csv training/return-average training/return-min", "_____no_output_____" ] ], [ [ "### Replaying a Trained Policy", "_____no_output_____" ], [ "The tool to replay a policy trained using RLlib is located in `flow/visualize/visualizer_rllib.py`. It takes as argument, first the path to the experiment results, and second the number of the checkpoint you wish to visualize. \n\nThere are other optional parameters which you can learn about by running `visualizer_rllib.py --help`. ", "_____no_output_____" ] ], [ [ "! python ../../flow/visualize/visualizer_rllib.py /ray_results/dirthatcontainsallcheckpoints/ 1", "_____no_output_____" ] ], [ [ "<hr>\n\n## Data Collection and Analysis\nAny Flow experiment can output its results to a CSV file containing the contents of SUMO's built-in `emission.xml` files, specifying speed, position, time, fuel consumption, and many other metrics for all vehicles in a network over time. \n\nThis section describes how to generate those `emission.csv` files when replaying and analyzing a trained policy.", "_____no_output_____" ], [ "### RLlib", "_____no_output_____" ] ], [ [ "# --emission_to_csv does the same as above\n! python ../../flow/visualize/visualizer_rllib.py results/sample_checkpoint 1 --gen_emission", "_____no_output_____" ] ], [ [ "As in the rllab case, the `emission.csv` file can be found in `test_time_rollout/` and used from there.", "_____no_output_____" ], [ "### SUMO\nSUMO-only experiments can generate emission CSV files as well, based on an argument to the `experiment.run` method. `run` takes in arguments `(num_runs, num_steps, rl_actions=None, convert_to_csv=False)`. To generate an `emission.csv` file, pass in `convert_to_csv=True` in the Python file running your SUMO experiment.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cbdd1c256381155c469f90a319aaf30493381572
12,461
ipynb
Jupyter Notebook
docs/Extending.ipynb
tchampet/jupyterlab-lsp
f5f77bf0b66bb7fdc26e19281c0e864fd6b4bc69
[ "BSD-3-Clause" ]
null
null
null
docs/Extending.ipynb
tchampet/jupyterlab-lsp
f5f77bf0b66bb7fdc26e19281c0e864fd6b4bc69
[ "BSD-3-Clause" ]
null
null
null
docs/Extending.ipynb
tchampet/jupyterlab-lsp
f5f77bf0b66bb7fdc26e19281c0e864fd6b4bc69
[ "BSD-3-Clause" ]
null
null
null
40.196774
132
0.644009
[ [ [ "## Extend jupyterlab-lsp", "_____no_output_____" ], [ "> Note: the API is likely to change in the future; your suggestions are welcome!\n\n### How to add a new LSP feature?\n\nFeatures (as well as other parts of the frontend) reuse the\n[JupyterLab plugins system](https://jupyterlab.readthedocs.io/en/stable/developer/extension_dev.html#plugins).\nEach plugin is a [TypeScript](https://www.typescriptlang.org/) package exporting\none or more `JupyterFrontEndPlugin`s (see\n[the JupyterLab extesion developer tutorial](https://jupyterlab.readthedocs.io/en/stable/developer/extension_tutorial.html)\nfor an overview). Each feature has to register itself with the `FeatureManager`\n(which is provided after requesting `ILSPFeatureManager` token) using\n`register(options: IFeatureOptions)` method.\n\nYour feature specification should follow the `IFeature` interface, which can be\ndivided into three major parts:\n\n- `editorIntegrationFactory`: constructors for the feature-CodeEditor\n integrators (implementing the `IFeatureEditorIntegration` interface), one for\n each supported CodeEditor (e.g. CodeMirror or Monaco); for CodeMirror\n integration you can base your feature integration on the abstract\n `CodeMirrorIntegration` class.\n- `labIntegration`: an optional object integrating feature with the JupyterLab\n interface\n- optional fields for easy integration of some of the common JupyterLab systems,\n such as:\n - settings system\n - commands system (including context menu)\n\nFor further integration with the JupyterLab, you can request additional\nJupyterLab tokens (consult JupyterLab documentation on\n[core tokens](https://jupyterlab.readthedocs.io/en/stable/developer/extension_dev.html#core-tokens)).\n\n#### How to override the default implementation of a feature?\n\nYou can specify a list of extensions to be disabled the the feature manager\npassing their plugin identifiers in `supersedes` field of `IFeatureOptions`.", "_____no_output_____" ], [ "### How to integrate a new code editor implementation?\n\n`CodeMirrorEditor` code editor is supported by default, but any JupyterLab\neditor implementing the `CodeEditor.IEditor` interface can be adapted for the\nuse with the LSP extension. To add your custom code editor (e.g. Monaco) after\nimplementing a `CodeEditor.IEditor` interface wrapper (which you would have\nanyways for the JupyterLab integration), you need to also implement a virtual\neditor (`IVirtualEditor` interface) for it.\n\n#### Why virtual editor?\n\nThe virtual editor takes multiple instances of your editor (e.g. in a notebook)\nand makes them act like a single editor. For example, when \"onKeyPress\" event is\nbound on the VirtualEditor instance, it should be bound onto each actual code\neditor; this allows the features to be implemented without the knowledge about\nthe number of editor instances on the page.\n\n#### How to register the implementation?\n\nA `virtualEditorManager` will be provided if you request\n`ILSPVirtualEditorManager` token; use\n`registerEditorType(options: IVirtualEditorType<IEditor>)` method passing a name\nthat you will also use to identify the code editor, the editor class, and your\nVirtualEditor constructor.", "_____no_output_____" ], [ "### How to integrate a new `DocumentWidget`?\n\nJupyterLab editor widgets (such as _Notebook_ or _File Editor_) implement\n`IDocumentWidget` interface. Each such widget has to adapted by a\n`WidgetAdapter` to enable its use with the LSP extension. The role of the\n`WidgetAdapter` is to extract the document metadata (language, mimetype) and the\nunderlying code editor (e.g. CodeMirror or Monaco) instances so that other parts\nof the LSP extension can interface with them without knowing about the\nimplementation details of the DocumentWidget (or even about the existence of a\nNotebook construct!).\n\nYour custom `WidgetAdapter` implementation has to register itself with\n`WidgetAdapterManager` (which can be requested with `ILSPAdapterManager` token),\ncalling `registerAdapterType(options: IAdapterTypeOptions)` method. Among the\noptions, in addition to the custom `WidgetAdapter`, you need to provide a\ntracker (`IWidgetTracker`) which will notify the extension via a signal when a\nnew instance of your document widget is getting created.", "_____no_output_____" ], [ "### How to add a custom magic or foreign extractor?\n\nIt is now possible to register custom code replacements using\n`ILSPCodeOverridesManager` token and to register custom foreign code extractors\nusing `ILSPCodeExtractorsManager` token, however this API is considered\nprovisional and subject to change.\n\n#### Future plans for transclusions handling\n\nWe will strive to make it possible for kernels to register their custom\nsyntax/code transformations easily, but the frontend API will remain available\nfor the end-users who write their custom syntax modifications with actionable\nside-effects (e.g. a custom IPython magic which copies a variable from the host\ndocument to the embedded document).", "_____no_output_____" ], [ "### How to add custom icons for the completer?\n\n1. Prepare the icons in the SVG format (we use 16 x 16 pixels, but you should be\n fine with up to 24 x 24). You can load them for webpack in typescript using\n imports if you include a `typings.d.ts` file with the following content:\n\n ```typescript\n declare module '*.svg' {\n const script: string;\n export default script;\n }\n ```\n\n in your `src/`. You should probably keep the icons in your `style/`\n directory.\n\n2. Prepare `CompletionKind` → `IconSvgString` mapping for the light (and\n optionally dark) theme, implementing the `ICompletionIconSet` interface. We\n have an additional `Kernel` completion kind that is used for completions\n provided by kernel that had no recognizable type provided.\n\n3. Provide all other metadata required by the `ICompletionTheme` interface and\n register it on `ILSPCompletionThemeManager` instance using `register_theme()`\n method.\n\n4. Provide any additional CSS styling targeting the JupyterLab completer\n elements inside of `.lsp-completer-theme-{id}`, e.g.\n `.lsp-completer-theme-material .jp-Completer-icon svg` for the material\n theme. Remember to include the styles by importing the in one of the source\n files.\n\nFor an example of a complete theme see\n[theme-vscode](https://github.com/krassowski/jupyterlab-lsp/tree/master/packages/theme-vscode).", "_____no_output_____" ], [ "## Extend jupyter-lsp\n\n### Language Server Specs\n\nLanguage Server Specs can be [configured](./Configuring.ipynb) by Jupyter users,\nor distributed by third parties as python or JSON files. Since we'd like to see\nas many Language Servers work out of the box as possible, consider\n[contributing a spec](./Contributing.ipynb#specs), if it works well for you!", "_____no_output_____" ], [ "### Message Listeners\n\nMessage listeners may choose to receive LSP messages immediately after being\nreceived from the client (e.g. `jupyterlab-lsp`) or a language server. All\nlisteners of a message are scheduled concurrently, and the message is passed\nalong **once all listeners return** (or fail). This allows listeners to, for\nexample, modify files on disk before the language server reads them.\n\nIf a listener is going to perform an expensive activity that _shouldn't_ block\ndelivery of a message, a non-blocking technique like\n[IOLoop.add_callback][add_callback] and/or a\n[queue](https://www.tornadoweb.org/en/stable/queues.html) should be used.\n\n[add_callback]:\n https://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.add_callback", "_____no_output_____" ], [ "#### Add a Listener with `entry_points`\n\nListeners can be added via [entry_points][] by a package installed in the same\nenvironment as `notebook`:\n\n```toml\n## setup.cfg\n\n[options.entry_points]\njupyter_lsp_listener_all_v1 =\n some-unique-name = some.module:some_function\njupyter_lsp_listener_client_v1 =\n some-other-unique-name = some.module:some_other_function\njupyter_lsp_listener_server_v1 =\n yet-another-unique-name = some.module:yet_another_function\n```\n\nAt present, the entry point names generally have no impact on functionality\naside from logging in the event of an error on import.\n\n[entry_points]: https://packaging.python.org/specifications/entry-points/", "_____no_output_____" ], [ "##### Add a Listener with Jupyter Configuration\n\nListeners can be added via `traitlets` configuration, e.g.\n\n```yaml\n## jupyter_notebook_config.jsons\n{\n 'LanguageServerManager':\n {\n 'all_listeners': ['some.module.some_function'],\n 'client_listeners': ['some.module.some_other_function'],\n 'server_listeners': ['some.module.yet_another_function'],\n },\n}\n```", "_____no_output_____" ], [ "##### Add a listener with the Python API\n\n`lsp_message_listener` can be used as a decorator, accessed as part of a\n`serverextension`.\n\nThis listener receives _all_ messages from the client and server, and prints\nthem out.\n\n```python\nfrom jupyter_lsp import lsp_message_listener\n\ndef load_jupyter_server_extension(nbapp):\n\n @lsp_message_listener(\"all\")\n async def my_listener(scope, message, language_server, manager):\n print(\"received a {} {} message from {}\".format(\n scope, message[\"method\"], language_server\n ))\n```\n\n`scope` is one of `client`, `server` or `all`, and is required.", "_____no_output_____" ], [ "##### Listener options\n\nFine-grained controls are available as part of the Python API. Pass these as\nnamed arguments to `lsp_message_listener`.\n\n- `language_server`: a regular expression of language servers\n- `method`: a regular expression of LSP JSON-RPC method names", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cbdd2777be52f869704873db5e5ebf15be26b7bf
435,004
ipynb
Jupyter Notebook
code/tutorial.ipynb
chaonan99/merge_sim
0a96685b261c94ffe7d73abec3a488ef02b48cd0
[ "MIT" ]
null
null
null
code/tutorial.ipynb
chaonan99/merge_sim
0a96685b261c94ffe7d73abec3a488ef02b48cd0
[ "MIT" ]
null
null
null
code/tutorial.ipynb
chaonan99/merge_sim
0a96685b261c94ffe7d73abec3a488ef02b48cd0
[ "MIT" ]
null
null
null
1,150.804233
128,666
0.942037
[ [ [ "# merge_sim&copy; Tutorial\n* This tutorial shows how to use merge_sim to reproduce the result in my graduate thesis.\n* Author: [chaonan99](chaonan99.github.io)\n* Date: 2017/06/10\n* Code for this tutorial and the project is under MIT license. See the license file for detail.", "_____no_output_____" ] ], [ [ "from game import Case1VehicleGenerator, MainHigherSpeedVG, GameLoop\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Case 1\nThis simulate the simple case in original paper, where 2 cars in each lane start at the same speed.", "_____no_output_____" ] ], [ [ "vehicle_generator = Case1VehicleGenerator()\ngame = GameLoop(vehicle_generator)\ngame.play()\ngame.draw_result_pyplot()", "Calculating tm for v0=13.4, vt=25.0, p0=-400.0, pt=0, tm=21.162899486487618\nCalculating tm for v0=13.4, vt=25.0, p0=-400.0, pt=0, tm=21.162899486487618\nAverage merging time: 21.64499999999974 s\nTraffic flow: 0.15420200462606 vehicle/s\nAverage speed: 71.53096270421067 km/h\nAverage fuel consumption: 7.946694797022417 ml/vehicle\n" ] ], [ [ "## Case 2\nIn this case, the main lane starts with a higher speed.", "_____no_output_____" ] ], [ [ "vehicle_generator = MainHigherSpeedVG()\ngame = GameLoop(vehicle_generator)\ngame.play()\ngame.draw_result_pyplot()", "Calculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nAverage merging time: 19.75888888888942 s\nTraffic flow: 0.4663212435232938 vehicle/s\nAverage speed: 78.40311215246113 km/h\nAverage fuel consumption: 8.324185841472211 ml/vehicle\n" ] ], [ [ "## OTM order\nLet's now implement OTM order. This can be easily fulfilled using the `SpeedIDAssigner` provided in `VehicleGeneratorBase`.", "_____no_output_____" ] ], [ [ "from common import config, VehicleState\nfrom helper import Helper\nfrom game import VehicleGeneratorBase, VehicleBuilder, OnBoardVehicle\nimport numpy as np\n\nclass MainHigherSpeedVGOTM(VehicleGeneratorBase):\n def __init__(self):\n super(MainHigherSpeedVGOTM, self).__init__()\n\n def buildSchedule(self):\n # lane0 (main road)\n t0_lane0 = np.arange(10, 30.1, 2.0) # generate a vehicle every 2.0 seconds from 10 s\n t0_lane1 = np.arange(9, 30.1, 3.1) # generate a vehicle every 3.1 seconds from 9 s \n v0_lane0 = 25.0 # v_0 on the main lane\n v0_lane1 = 15.0 # v_0 on the auxiliary lane\n for ti0 in t0_lane0:\n v = VehicleBuilder(-1)\\\n .setSpeed(v0_lane0)\\\n .setPosition(-config.control_len)\\\n .setAcceleration(0)\\\n .setLane(0).build()\n # The schedule is the actual vehicle queue used to generate vehicle in the game loop.\n # Append the built vehicle to the schedule.\n self.schedule.append(OnBoardVehicle(v, ti0, Helper.getTc(v)))\n for ti0 in t0_lane1:\n v = VehicleBuilder(-1)\\\n .setSpeed(v0_lane1)\\\n .setPosition(-config.control_len)\\\n .setAcceleration(0)\\\n .setLane(1).build()\n self.schedule.append(OnBoardVehicle(v, ti0, Helper.getTc(v)))\n # Use speed ID Assigner to get OTM order.\n self.SpeedIDAssigner()", "_____no_output_____" ] ], [ [ "### Hard $t_\\mathrm{m}$ recalculate\nThe `SpeedGameLoop` implement the hard OTM order stated in the original paper.", "_____no_output_____" ] ], [ [ "from game import SpeedGameLoop\nvehicle_generator = MainHigherSpeedVGOTM()\ngame = SpeedGameLoop(vehicle_generator)\ngame.play()\ngame.draw_result_pyplot()", "Calculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nAverage merging time: 16.082222222222327 s\nTraffic flow: 0.5235602094240633 vehicle/s\nAverage speed: 96.26539858493342 km/h\nAverage fuel consumption: 15.88115297928556 ml/vehicle\n" ] ], [ [ "### Soft $t_\\mathrm{m}$ recalculate\nWe relieve $t_\\mathrm{m}$ on the auxiliary lane. The alternative is provided in `Helper.getTm`.", "_____no_output_____" ] ], [ [ "class SpeedSoftGameLoop(GameLoop):\n def __init__(self, vscd):\n super(SpeedSoftGameLoop, self).__init__(vscd)\n self.on_board_vehicles = []\n\n def nextStep(self):\n self.ctime += config.time_meta\n t = self.ctime\n ove_t = self.vscd.getAtTime(t)\n for v in ove_t:\n tmp_v_stack = []\n while len(self.on_board_vehicles) > 0 and self.on_board_vehicles[-1].vehicle.ID > v.vehicle.ID:\n tmpv = self.on_board_vehicles.pop()\n # tmpv.t0 = t\n # tmpv.min_pass_time = max(tmpv.min_pass_time, Helper.getTmOptimal2(tmpv.vehicle.speed,\n # config.case_speed['speed_merge'], tmpv.vehicle.position, 0))\n tmp_v_stack.append(tmpv)\n\n # Get t_m\n if len(self.on_board_vehicles) == 0 and len(self.finished_vehicels) == 0:\n v.tm = v.t0 + max(config.min_pass_time, v.min_pass_time)\n elif len(self.on_board_vehicles) > 0:\n v.tm = Helper.getTm(v, self.on_board_vehicles[-1], 'soft')\n else:\n v.tm = Helper.getTm(v, self.finished_vehicels[-1], 'soft')\n tmp_v_stack.append(v)\n prevve = None\n for i in reversed(range(len(tmp_v_stack))):\n ve = tmp_v_stack[i]\n if prevve is not None:\n ve.tm = Helper.getTm(ve, prevve, 'soft')\n self.on_board_vehicles.append(ve)\n TimeM = Helper.getTimeMatrix(t, ve.tm)\n ConfV = Helper.getConfigVec(ve)\n # from IPython import embed; embed()\n ve.ParaV = np.dot(np.linalg.inv(TimeM), ConfV)\n ve.state = VehicleState.ON_RAMP\n prevve = ve\n # print(\"ID {}\".format(prevve.vehicle.ID))\n\n for v in self.on_board_vehicles:\n Helper.updateAVP(v, t)\n if v.vehicle.position >= 0:\n v.state = VehicleState.ON_MERGING\n\n while not self.isEmpty() and self.on_board_vehicles[0].vehicle.position >= config.merging_len:\n self.on_board_vehicles[0].state = VehicleState.FINISHED\n self.finished_vehicels.append((self.on_board_vehicles.pop(0)))", "_____no_output_____" ], [ "vehicle_generator = MainHigherSpeedVGOTM()\ngame = SpeedSoftGameLoop(vehicle_generator)\ngame.play()\ngame.draw_result_pyplot()", "Calculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=25.0, vt=25.0, p0=-400.0, pt=0, tm=15.999935266382314\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nCalculating tm for v0=15.0, vt=25.0, p0=-400.0, pt=0, tm=20.213959120616735\nAverage merging time: 18.625555555556005 s\nTraffic flow: 0.46153846153843714 vehicle/s\nAverage speed: 83.13909754833116 km/h\nAverage fuel consumption: 9.298591158702889 ml/vehicle\n" ] ], [ [ "## Exercise\nTry to implement a random vehicle generator, which the time interval between two consecutive vehicle on the same lane obeying the exponential distribution and the speed in each lane obeying normal distribution. The answer can be found in `game.py` file.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cbdd3217c4034ac202c9cda9942fdafb1c881d70
144,963
ipynb
Jupyter Notebook
notebooks/data-prep/UCI-Dodgers.ipynb
HPI-Information-Systems/TimeEval
9b2717b89decd57dd09e04ad94c120f13132d7b8
[ "MIT" ]
2
2022-01-29T03:46:31.000Z
2022-02-14T14:06:35.000Z
notebooks/data-prep/UCI-Dodgers.ipynb
HPI-Information-Systems/TimeEval
9b2717b89decd57dd09e04ad94c120f13132d7b8
[ "MIT" ]
null
null
null
notebooks/data-prep/UCI-Dodgers.ipynb
HPI-Information-Systems/TimeEval
9b2717b89decd57dd09e04ad94c120f13132d7b8
[ "MIT" ]
null
null
null
249.936207
126,912
0.896829
[ [ [ "# UCI Dodgers dataset", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport os\nfrom pathlib import Path\nfrom config import data_raw_folder, data_processed_folder\nfrom timeeval import Datasets\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "%matplotlib inline\nplt.rcParams['figure.figsize'] = (20, 10)", "_____no_output_____" ], [ "dataset_collection_name = \"Dodgers\"\nsource_folder = Path(data_raw_folder) / \"UCI ML Repository/Dodgers\"\ntarget_folder = Path(data_processed_folder)\n\nprint(f\"Looking for source datasets in {source_folder.absolute()} and\\nsaving processed datasets in {target_folder.absolute()}\")", "Looking for source datasets in /home/projects/akita/data/benchmark-data/data-raw/UCI ML Repository/Dodgers and\nsaving processed datasets in /home/projects/akita/data/benchmark-data/data-processed\n" ], [ "dataset_name = \"101-freeway-traffic\"\ntrain_type = \"unsupervised\"\ntrain_is_normal = False\ninput_type = \"univariate\"\ndatetime_index = True\ndataset_type = \"real\"\n\n# create target directory\ndataset_subfolder = Path(input_type) / dataset_collection_name\ntarget_subfolder = target_folder / dataset_subfolder\ntry:\n os.makedirs(target_subfolder)\n print(f\"Created directories {target_subfolder}\")\nexcept FileExistsError:\n print(f\"Directories {target_subfolder} already exist\")\n pass\n\ndm = Datasets(target_folder)", "Directories /home/projects/akita/data/benchmark-data/data-processed/univariate/Dodgers already exist\n" ], [ "data_file = source_folder / \"Dodgers.data\"\nevents_file = source_folder / \"Dodgers.events\"\n\n# transform data\ndf = pd.read_csv(data_file, header=None, encoding=\"latin1\", parse_dates=[0], infer_datetime_format=True)\ndf.columns = [\"timestamp\", \"count\"]\n#df[\"count\"] = df[\"count\"].replace(-1, np.nan)\n\n# read and add labels\ndf_events = pd.read_csv(events_file, header=None, encoding=\"latin1\")\ndf_events.columns = [\"date\", \"begin\", \"end\", \"game attendance\" ,\"away team\", \"game score\"]\ndf_events.insert(0, \"begin_timestamp\", pd.to_datetime(df_events[\"date\"] + \" \" + df_events[\"begin\"]))\ndf_events.insert(1, \"end_timestamp\", pd.to_datetime(df_events[\"date\"] + \" \" + df_events[\"end\"]))\ndf_events = df_events.drop(columns=[\"date\", \"begin\", \"end\", \"game attendance\" ,\"away team\", \"game score\"])\n# labelling\ndf[\"is_anomaly\"] = 0\nfor _, (t1, t2) in df_events.iterrows():\n tmp = df[df[\"timestamp\"] >= t1]\n tmp = tmp[tmp[\"timestamp\"] <= t2]\n df.loc[tmp.index, \"is_anomaly\"] = 1\n# mark missing values as anomaly as well\ndf.loc[df[\"count\"] == -1, \"is_anomaly\"] = 1\n\nfilename = f\"{dataset_name}.test.csv\"\npath = os.path.join(dataset_subfolder, filename)\ntarget_filepath = os.path.join(target_subfolder, filename)\ndataset_length = len(df)\ndf.to_csv(target_filepath, index=False)\nprint(f\"Processed dataset {dataset_name} -> {target_filepath}\")\n\n# save metadata\ndm.add_dataset((dataset_collection_name, dataset_name),\n train_path = None,\n test_path = path,\n dataset_type = dataset_type,\n datetime_index = datetime_index,\n split_at = None,\n train_type = train_type,\n train_is_normal = train_is_normal,\n input_type = input_type,\n dataset_length = dataset_length\n)\n\ndm.save()", "Processed dataset 101-freeway-traffic -> /home/projects/akita/data/benchmark-data/data-processed/univariate/Dodgers/101-freeway-traffic.test.csv\n" ], [ "dm.refresh()\ndm.df().loc[(slice(dataset_collection_name,dataset_collection_name), slice(None))]", "_____no_output_____" ] ], [ [ "## Experimentation", "_____no_output_____" ] ], [ [ "data_file = source_folder / \"Dodgers.data\"\ndf = pd.read_csv(data_file, header=None, encoding=\"latin1\", parse_dates=[0], infer_datetime_format=True)\ndf.columns = [\"timestamp\", \"count\"]\n#df[\"count\"] = df[\"count\"].replace(-1, np.nan)\ndf", "_____no_output_____" ], [ "events_file = source_folder / \"Dodgers.events\"\ndf_events = pd.read_csv(events_file, header=None, encoding=\"latin1\")\ndf_events.columns = [\"date\", \"begin\", \"end\", \"game attendance\" ,\"away team\", \"game score\"]\ndf_events.insert(0, \"begin_timestamp\", pd.to_datetime(df_events[\"date\"] + \" \" + df_events[\"begin\"]))\ndf_events.insert(1, \"end_timestamp\", pd.to_datetime(df_events[\"date\"] + \" \" + df_events[\"end\"]))\ndf_events = df_events.drop(columns=[\"date\", \"begin\", \"end\", \"game attendance\" ,\"away team\", \"game score\"])\ndf_events", "_____no_output_____" ], [ "# labelling\ndf[\"is_anomaly\"] = 0\nfor _, (t1, t2) in df_events.iterrows():\n tmp = df[df[\"timestamp\"] >= t1]\n tmp = tmp[tmp[\"timestamp\"] <= t2]\n df.loc[tmp.index, \"is_anomaly\"] = 1\ndf.loc[df[\"count\"] == -1, \"is_anomaly\"] = 1", "_____no_output_____" ], [ "df.iloc[15000:20000].plot(x=\"timestamp\", y=[\"count\", \"is_anomaly\"])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cbdd348b75ba05e47ca433e1928f1865a9a94220
45,766
ipynb
Jupyter Notebook
examples/tutorials/03_ready_to_use_model_tf.ipynb
abrikoseg/batchflow
f1060f452b9407477ac61cea2a658792deca29a6
[ "Apache-2.0" ]
87
2018-11-16T08:04:12.000Z
2022-03-24T20:08:44.000Z
examples/tutorials/03_ready_to_use_model_tf.ipynb
abrikoseg/batchflow
f1060f452b9407477ac61cea2a658792deca29a6
[ "Apache-2.0" ]
243
2018-11-29T02:03:55.000Z
2022-02-21T08:28:29.000Z
examples/tutorials/03_ready_to_use_model_tf.ipynb
abrikoseg/batchflow
f1060f452b9407477ac61cea2a658792deca29a6
[ "Apache-2.0" ]
35
2019-01-29T14:26:14.000Z
2021-12-30T01:39:02.000Z
112.171569
35,804
0.872045
[ [ [ "# Train a ready to use TensorFlow model with a simple pipeline", "_____no_output_____" ] ], [ [ "import os\nimport sys\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# the following line is not required if BatchFlow is installed as a python package.\nsys.path.append(\"../..\")\nfrom batchflow import Pipeline, B, C, D, F, V\nfrom batchflow.opensets import MNIST, CIFAR10, CIFAR100\nfrom batchflow.models.tf import ResNet18", "_____no_output_____" ] ], [ [ "BATCH_SIZE might be increased for modern GPUs with lots of memory (4GB and higher).", "_____no_output_____" ] ], [ [ "BATCH_SIZE = 64", "_____no_output_____" ] ], [ [ "# Create a dataset", "_____no_output_____" ], [ "[MNIST](http://yann.lecun.com/exdb/mnist/) is a dataset of handwritten digits frequently used as a baseline for machine learning tasks.\n\nDownloading MNIST database might take a few minutes to complete.", "_____no_output_____" ] ], [ [ "dataset = MNIST(bar=True)", "100%|██████████| 8/8 [00:08<00:00, 2.57s/it]\n" ] ], [ [ "There are also predefined CIFAR10 and CIFAR100 datasets.", "_____no_output_____" ], [ "# Define a pipeline config", "_____no_output_____" ], [ "Config allows to create flexible pipelines which take parameters.\n\nFor instance, if you put a model type into config, you can run a pipeline against different models.\n\nSee [a list of available models](https://analysiscenter.github.io/batchflow/intro/tf_models.html#ready-to-use-models) to choose the one which fits you best.", "_____no_output_____" ] ], [ [ "config = dict(model=ResNet18)", "_____no_output_____" ] ], [ [ "# Create a template pipeline", "_____no_output_____" ], [ "A template pipeline is not linked to any dataset. It's just an abstract sequence of actions, so it cannot be executed, but it serves as a convenient building block.", "_____no_output_____" ] ], [ [ "train_template = (Pipeline()\n .init_variable('loss_history', [])\n .init_model('conv_nn', C('model'), 'dynamic',\n config={'inputs/images/shape': B.image_shape,\n 'inputs/labels/classes': D.num_classes,\n 'initial_block/inputs': 'images'})\n .to_array()\n .train_model('conv_nn', fetches='loss', images=B.images, labels=B.labels,\n save_to=V('loss_history', mode='a'))\n)", "_____no_output_____" ] ], [ [ "# Train the model", "_____no_output_____" ], [ "Apply a dataset and a config to a template pipeline to create a runnable pipeline:", "_____no_output_____" ] ], [ [ "train_pipeline = (train_template << dataset.train) << config", "_____no_output_____" ] ], [ [ "Run the pipeline (it might take from a few minutes to a few hours depending on your hardware)", "_____no_output_____" ] ], [ [ "train_pipeline.run(BATCH_SIZE, shuffle=True, n_epochs=1, drop_last=True, bar=True, prefetch=1)", "100%|██████████| 937/937 [16:51<00:00, 1.08s/it]\n" ] ], [ [ "Note that the progress bar often increments by 2 at a time - that's prefetch in action.", "_____no_output_____" ], [ "It does not give much here, though, since almost all time is spent in model training which is performed under a thread-lock one batch after another without any parallelism (otherwise the model would not learn anything as different batches would rewrite one another's model weights updates).", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(15, 5))\nplt.plot(train_pipeline.v('loss_history'))\nplt.xlabel(\"Iterations\"), plt.ylabel(\"Loss\")\nplt.show()", "_____no_output_____" ] ], [ [ "# Test the model", "_____no_output_____" ], [ "It is much faster than training, but if you don't have GPU it would take some patience.", "_____no_output_____" ] ], [ [ "test_pipeline = (dataset.test.p\n .import_model('conv_nn', train_pipeline)\n .init_variable('predictions') \n .init_variable('metrics') \n .to_array()\n .predict_model('conv_nn', fetches='predictions', images=B.images, save_to=V('predictions'))\n .gather_metrics('class', targets=B.labels, predictions=V('predictions'),\n fmt='logits', axis=-1, save_to=V('metrics', mode='a'))\n .run(BATCH_SIZE, shuffle=True, n_epochs=1, drop_last=False, bar=True)\n)", " 99%|█████████▉| 156/157 [00:08<00:00, 19.16it/s]\n" ] ], [ [ "Let's get the accumulated [metrics information](https://analysiscenter.github.io/batchflow/intro/models.html#model-metrics)", "_____no_output_____" ] ], [ [ "metrics = test_pipeline.get_variable('metrics')", "_____no_output_____" ] ], [ [ "Or a shorter version: `metrics = test_pipeline.v('metrics')`", "_____no_output_____" ], [ "Now we can easiliy calculate any metrics we need", "_____no_output_____" ] ], [ [ "metrics.evaluate('accuracy')", "_____no_output_____" ], [ "metrics.evaluate(['false_positive_rate', 'false_negative_rate'], multiclass=None)", "_____no_output_____" ] ], [ [ "# Save the model\nAfter learning the model, you may need to save it. It's easy to do this.", "_____no_output_____" ] ], [ [ "train_pipeline.save_model_now('conv_nn', path='path/to/save')", "_____no_output_____" ] ], [ [ "## What's next?", "_____no_output_____" ], [ "See [the image augmentation tutorial](./06_image_augmentation.ipynb) or return to the [table of contents](./00_description.ipynb).", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cbdd3960390f750ecb515e3d4eb7d0646e45a93f
2,154
ipynb
Jupyter Notebook
pyomo_NLP.ipynb
PEESEgroup/SysEn6800
cd33776ca6dc2e89267f44ac49d2d4edb1a259b3
[ "MIT" ]
null
null
null
pyomo_NLP.ipynb
PEESEgroup/SysEn6800
cd33776ca6dc2e89267f44ac49d2d4edb1a259b3
[ "MIT" ]
null
null
null
pyomo_NLP.ipynb
PEESEgroup/SysEn6800
cd33776ca6dc2e89267f44ac49d2d4edb1a259b3
[ "MIT" ]
null
null
null
19.232143
73
0.514856
[ [ [ "from pyomo.environ import *", "_____no_output_____" ], [ "model = ConcreteModel()\nmodel.x1 = Var(initialize=4, within=NonNegativeReals)\nmodel.x2 = Var(initialize=5, within=NonNegativeReals)", "_____no_output_____" ], [ "model.c = ConstraintList()\nmodel.c.add(model.x1 - 2*model.x2 <= -1)\nmodel.c.add(model.x1 + 2*model.x2 <= 4)", "_____no_output_____" ], [ "def objrule(model):\n return model.x1**2 + model.x2**2 - 3*model.x1 - 4*model.x2 + 10", "_____no_output_____" ], [ "model.obj = Objective(rule=objrule, sense=minimize)", "_____no_output_____" ], [ "model.pprint()", "_____no_output_____" ], [ "solver = SolverFactory('ipopt')\nsolver.solve(model)", "_____no_output_____" ], [ "print(model.x1())\nprint(model.x2())\nprint(model.obj())", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdd3997a44ed176b89e32d3cca084fdde8926d8
162,395
ipynb
Jupyter Notebook
car-model-recog/carmodel-bilinear-resnet.ipynb
vicdoja/ComputerVision-Labs
c937c18dca87209435fe980e178c385ac0f9857c
[ "MIT" ]
null
null
null
car-model-recog/carmodel-bilinear-resnet.ipynb
vicdoja/ComputerVision-Labs
c937c18dca87209435fe980e178c385ac0f9857c
[ "MIT" ]
null
null
null
car-model-recog/carmodel-bilinear-resnet.ipynb
vicdoja/ComputerVision-Labs
c937c18dca87209435fe980e178c385ac0f9857c
[ "MIT" ]
null
null
null
305.828625
127,504
0.886388
[ [ [ "from __future__ import print_function\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Lambda\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers.normalization import BatchNormalization as BN\nfrom keras.layers import GaussianNoise as GN\nfrom keras.optimizers import SGD\nfrom keras.models import Model\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nfrom keras.callbacks import LearningRateScheduler as LRS\nfrom keras.preprocessing.image import ImageDataGenerator", "_____no_output_____" ], [ "#### LOAD AND TRANSFORM\n\n## Download: ONLY ONCE!\n#os.system('wget https://www.dropbox.com/s/sakfqp6o8pbgasm/data.tgz')\n#os.system('tar xvzf data.tgz')\n#####\n\n# Load \nx_train = np.load('x_train.npy')\nx_test = np.load('x_test.npy')\n\ny_train = np.load('y_train.npy')\ny_test = np.load('y_test.npy')\n\n# Stats\nprint(x_train.shape)\nprint(y_train.shape)\n\nprint(x_test.shape)\nprint(y_test.shape)", "(791, 250, 250, 3)\n(791,)\n(784, 250, 250, 3)\n(784,)\n" ], [ "## View some images\nplt.imshow(x_train[3,:,:,: ] )\nplt.show()", "_____no_output_____" ], [ "## Transforms\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\n\ny_train = y_train.astype('float32')\ny_test = y_test.astype('float32')\n\nx_train = keras.applications.vgg16.preprocess_input(x_train)\nx_test = keras.applications.vgg16.preprocess_input(x_test)", "_____no_output_____" ], [ "batch_size = 32\nnum_classes = 20\nepochs = 150\n\n## Labels\ny_train=y_train-1\n\ny_test=y_test-1\n\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\ndatagen = ImageDataGenerator(\n width_shift_range=0.3,\n height_shift_range=0.3,\n rotation_range=45,\n zoom_range=[1.0,1.2],\n horizontal_flip=True\n)", "_____no_output_____" ], [ "vgg16 = keras.applications.VGG16(\n include_top=False,\n weights=\"imagenet\",\n input_shape=(250, 250, 3),\n classes=1000,\n classifier_activation=\"softmax\"\n)", "_____no_output_____" ], [ "vgg16.summary()", "Model: \"vgg16\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 250, 250, 3)] 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, 250, 250, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 250, 250, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 125, 125, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 125, 125, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 125, 125, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 62, 62, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 62, 62, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 62, 62, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 62, 62, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 31, 31, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 31, 31, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 31, 31, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 31, 31, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 15, 15, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 15, 15, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 15, 15, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 15, 15, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 7, 7, 512) 0 \n=================================================================\nTotal params: 14,714,688\nTrainable params: 14,714,688\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "#############################\n### BILINEAR ####\n#############################\n\n# DEFINE A LEARNING RATE SCHEDULER\ndef scheduler(epoch):\n if epoch < 25:\n return .1\n elif epoch < 50:\n return 0.01\n else:\n return 0.001\n \ndef scheduler_fine(epoch):\n if epoch < 25:\n return .0001\n elif epoch < 50:\n return 0.00001\n else:\n return 0.000001\n\nset_lr = LRS(scheduler)\nset_lr_fine = LRS(scheduler_fine)\n\ndef outer_product(x):\n phi_I = tf.einsum('ijkm,ijkn->imn',x[0],x[1])\t\t# Einstein Notation [batch,31,31,depth] x [batch,31,31,depth] -> [batch,depth,depth]\n phi_I = tf.reshape(phi_I,[-1,x[0].shape[3]**2])\t # Reshape from [batch_size,depth,depth] to [batch_size, depth*depth]\n phi_I = tf.divide(phi_I,x[0].shape[1]**2)\t\t\t\t\t\t\t\t # Divide by feature map size [sizexsize]\n\n y_ssqrt = tf.multiply(tf.sign(phi_I),tf.sqrt(tf.abs(phi_I)+1e-12))\t\t# Take signed square root of phi_I\n z_l2 = tf.nn.l2_normalize(y_ssqrt)\t\t\t\t\t\t\t\t # Apply l2 normalization\n return z_l2", "_____no_output_____" ], [ "conv = vgg16.get_layer('block4_pool') \nd1 = Dropout(0.5)(conv.output) ## Why??\nd2 = Dropout(0.5)(conv.output) ## Why??\n\nx = Lambda(outer_product, name='outer_product')([d1,d2])\n\npredictions = Dense(num_classes, activation='softmax', name='predictions')(x)\n\nmodel = Model(inputs=vgg16.input, outputs=predictions)\n \nmodel.summary()", "Model: \"model\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) [(None, 250, 250, 3) 0 \n__________________________________________________________________________________________________\nblock1_conv1 (Conv2D) (None, 250, 250, 64) 1792 input_1[0][0] \n__________________________________________________________________________________________________\nblock1_conv2 (Conv2D) (None, 250, 250, 64) 36928 block1_conv1[0][0] \n__________________________________________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 125, 125, 64) 0 block1_conv2[0][0] \n__________________________________________________________________________________________________\nblock2_conv1 (Conv2D) (None, 125, 125, 128 73856 block1_pool[0][0] \n__________________________________________________________________________________________________\nblock2_conv2 (Conv2D) (None, 125, 125, 128 147584 block2_conv1[0][0] \n__________________________________________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 62, 62, 128) 0 block2_conv2[0][0] \n__________________________________________________________________________________________________\nblock3_conv1 (Conv2D) (None, 62, 62, 256) 295168 block2_pool[0][0] \n__________________________________________________________________________________________________\nblock3_conv2 (Conv2D) (None, 62, 62, 256) 590080 block3_conv1[0][0] \n__________________________________________________________________________________________________\nblock3_conv3 (Conv2D) (None, 62, 62, 256) 590080 block3_conv2[0][0] \n__________________________________________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 31, 31, 256) 0 block3_conv3[0][0] \n__________________________________________________________________________________________________\nblock4_conv1 (Conv2D) (None, 31, 31, 512) 1180160 block3_pool[0][0] \n__________________________________________________________________________________________________\nblock4_conv2 (Conv2D) (None, 31, 31, 512) 2359808 block4_conv1[0][0] \n__________________________________________________________________________________________________\nblock4_conv3 (Conv2D) (None, 31, 31, 512) 2359808 block4_conv2[0][0] \n__________________________________________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 15, 15, 512) 0 block4_conv3[0][0] \n__________________________________________________________________________________________________\ndropout (Dropout) (None, 15, 15, 512) 0 block4_pool[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 15, 15, 512) 0 block4_pool[0][0] \n__________________________________________________________________________________________________\nouter_product (Lambda) (None, 262144) 0 dropout[0][0] \n dropout_1[0][0] \n__________________________________________________________________________________________________\npredictions (Dense) (None, 20) 5242900 outer_product[0][0] \n==================================================================================================\nTotal params: 12,878,164\nTrainable params: 12,878,164\nNon-trainable params: 0\n__________________________________________________________________________________________________\n" ], [ "vgg16.trainable = False\n\nmodel.compile(\n loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy']\n) \n\n## TRAINING with DA and LRA\nhistory=model.fit_generator(\n datagen.flow(x_train, y_train,batch_size=batch_size),\n steps_per_epoch=len(x_train) / batch_size, \n epochs=10,\n validation_data=(x_test, y_test),\n callbacks=[set_lr],\n verbose=1\n)\n\nvgg16.trainable = True\n\nmodel.compile(\n loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy']\n) \n\n## TRAINING with DA and LRA\nhistory=model.fit_generator(\n datagen.flow(x_train, y_train,batch_size=batch_size),\n steps_per_epoch=len(x_train) / batch_size, \n epochs=epochs-10,\n validation_data=(x_test, y_test),\n callbacks=[set_lr_fine],\n verbose=1\n)", "/home/vicdoja/anaconda3/envs/tf_env/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:1844: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n warnings.warn('`Model.fit_generator` is deprecated and '\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdd4b84bdb8486f80b74dbd5ebea27ea387a154
316,284
ipynb
Jupyter Notebook
Notebooks/Text Analytics/TextAnalytics-Autosummarize_RuleBased.ipynb
microsoft/AutoTuneML
34e5a2b05c5dc38c61584570d1dd7dd19fa52faa
[ "MIT" ]
5
2021-11-16T16:16:49.000Z
2022-03-17T10:21:48.000Z
Notebooks/Text Analytics/TextAnalytics-Autosummarize_RuleBased.ipynb
microsoft/AutoTuneML
34e5a2b05c5dc38c61584570d1dd7dd19fa52faa
[ "MIT" ]
null
null
null
Notebooks/Text Analytics/TextAnalytics-Autosummarize_RuleBased.ipynb
microsoft/AutoTuneML
34e5a2b05c5dc38c61584570d1dd7dd19fa52faa
[ "MIT" ]
3
2021-09-15T01:40:48.000Z
2021-09-28T19:26:37.000Z
158,142
316,283
0.745877
[ [ [ "%pip install bs4\n%pip install lxml\n%pip install nltk\n%pip install textblob", "_____no_output_____" ], [ "import urllib.request as ur\nfrom bs4 import BeautifulSoup", "_____no_output_____" ] ], [ [ "## STEP 1: Read data from HTML and parse it to clean string", "_____no_output_____" ] ], [ [ "#We would extract the abstract from this HTML page article\narticleURL = \"https://www.washingtonpost.com/news/the-switch/wp/2016/10/18/the-pentagons-massive-new-telescope-is-designed-to-track-space-junk-and-watch-out-for-killer-asteroids/\"", "_____no_output_____" ], [ "#HTML contains extra tags in a tree like structure\npage = ur.urlopen(articleURL).read().decode('utf8','ignore') \nsoup = BeautifulSoup(page,\"lxml\")\nsoup", "_____no_output_____" ], [ "#We want the article or base text only\nsoup.find('article')", "_____no_output_____" ], [ "#Remove the article tags and get the plain text\nsoup.find('article').text", "_____no_output_____" ], [ "#Take all the articles from the page using find_all and combine together into a single string with a \" \"\ntext = ' '.join(map(lambda p: p.text, soup.find_all('article')))\ntext", "_____no_output_____" ], [ "#The encode() method encodes the string using the specified encoding. Convert back the encoded version to string by using decode() \n#Replace special encoded characters with a '?', further replace question mark with a blank char to get plain text from encoded article text.\ntext.encode('ascii', errors='replace').decode('utf8').replace(\"?\",\" \")", "_____no_output_____" ], [ "#All above steps encapsulated- to read and parse data from HTMl text\nimport urllib.request as ur\nfrom bs4 import BeautifulSoup\ndef getTextWaPo(url):\n page = ur.urlopen(url).read().decode('utf8')\n soup = BeautifulSoup(page,\"lxml\")\n text = ' '.join(map(lambda p: p.text, soup.find_all('article')))\n return text.encode('ascii', errors='replace').decode('utf8').replace(\"?\",\" \")", "_____no_output_____" ], [ "#calling function\narticleURL= \"https://www.washingtonpost.com/news/the-switch/wp/2016/10/18/the-pentagons-massive-new-telescope-is-designed-to-track-space-junk-and-watch-out-for-killer-asteroids/\"\ntext = getTextWaPo(articleURL)\ntext", "_____no_output_____" ] ], [ [ "## STEP 2: Extract summary", "_____no_output_____" ] ], [ [ "import nltk\nfrom nltk.tokenize import sent_tokenize,word_tokenize\nfrom nltk.corpus import stopwords\nfrom string import punctuation", "_____no_output_____" ], [ "#Strip all se4ntences in the text\n# A sentence is identified by a period or full stop. A space has to be accompanied by the full-stop else both sentences would be treated as a single sentence\nnltk.download('punkt')\nsents = sent_tokenize(text)\nsents", "_____no_output_____" ], [ "#Strip all words/tokens in the text\nword_sent = word_tokenize(text.lower())\nword_sent", "_____no_output_____" ], [ "#Get all english stop words and punctuation marks\nnltk.download('stopwords')\n_stopwords = set(stopwords.words('english') + list(punctuation))\n_stopwords", "_____no_output_____" ], [ "#Filter stop words from our list of words in text\nword_sent=[word for word in word_sent if word not in _stopwords]\nword_sent", "_____no_output_____" ], [ "#Use build in function to determine the frequency or the number of times each word occurs in the text\n#The higher the frequency, more is the importance of word\nfrom nltk.probability import FreqDist\nfreq = FreqDist(word_sent)\nfreq", "_____no_output_____" ], [ "#The nlargest () function of the Python module heapq returns the specified number of largest elements from a Python iterable like a list, tuple and others. \n#heapq.nlargest(n, iterable, key=sorting_key, here used the dict.get function to get the value(frequency for a word) from key:value pair)\n\nfrom heapq import nlargest\nnlargest(10, freq, key=freq.get)\n#To check if these most important words match with the central theme of the article 'Space asteroid attack'", "_____no_output_____" ], [ "#Now that we have the Word importance, we can calculate the significance score for each sentence\n#Word_Imp=Frequency of word in corpus\n#Sentence_Significance_score=SUM(Word_Imp for Words in the sentence)\n\nfrom collections import defaultdict\nranking = defaultdict(int)\n\nfor i,sent in enumerate(sents):\n for w in word_tokenize(sent.lower()):\n if w in freq:\n ranking[i] += freq[w]\n \nranking\n#{Index of sentence : Sentence significance score}", "_____no_output_____" ], [ "#Top most important 4 sentences - having maximum sentence significance score\nsents_idx = nlargest(4, ranking, key=ranking.get)\nsents_idx", "_____no_output_____" ], [ "#Get the sentences from the top indices\nsummary_1=[sents[j] for j in sorted(sents_idx)]\nsummary_1", "_____no_output_____" ], [ "#Concat most important sentences to form the summary\nsummary=\"\"\nfor i in range(len(summary_1)):\n summary=summary + summary_1[i]\n \nsummary", "_____no_output_____" ], [ "def summarize(text, n):\n sents = sent_tokenize(text)\n \n assert n <= len(sents) #Check if the sentences list have atleast n sentences\n word_sent = word_tokenize(text.lower())\n _stopwords = set(stopwords.words('english') + list(punctuation))\n \n word_sent=[word for word in word_sent if word not in _stopwords]\n freq = FreqDist(word_sent)\n \n \n ranking = defaultdict(int)\n \n for i,sent in enumerate(sents):\n for w in word_tokenize(sent.lower()):\n if w in freq:\n ranking[i] += freq[w]\n \n \n sents_idx = nlargest(n, ranking, key=ranking.get)\n summary_1= [sents[j] for j in sorted(sents_idx)]\n summary=\"\"\n for i in range(len(summary_1)):\n summary=summary + summary_1[i]\n return summary", "_____no_output_____" ], [ "#calling\nsummarize(text,4)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdd5a90ea2f5e856979bd4bd163f63c05ad5a6a
11,750
ipynb
Jupyter Notebook
notebooks/import.ipynb
Geethen/geospatial-modeling-course-jupyter
f30a2e042abce9552170fdd4dad5f6c4b406e09c
[ "BSD-2-Clause" ]
null
null
null
notebooks/import.ipynb
Geethen/geospatial-modeling-course-jupyter
f30a2e042abce9552170fdd4dad5f6c4b406e09c
[ "BSD-2-Clause" ]
null
null
null
notebooks/import.ipynb
Geethen/geospatial-modeling-course-jupyter
f30a2e042abce9552170fdd4dad5f6c4b406e09c
[ "BSD-2-Clause" ]
2
2019-03-13T08:07:18.000Z
2021-02-01T17:08:04.000Z
34.057971
155
0.630298
[ [ [ "## Import and export of data from different sources in GRASS GIS\n\nGRASS GIS Location can contain data only in one coordinate reference system (CRS)\nin order to have full control over reprojection\nand avoid issues coming from on-the-fly reprojection.\n\n\nWhen starting a project, decide which CRS you will use. Create\na new Location using Location Wizard (accessible from GRASS GIS start-up page).\nSpecify desired CRS either by providing\nEPSG code (can be found e.g. at [epsg.io](http://epsg.io/))\nor by providing a georeferenced file (such as Shapefile) which has\nthe CRS you want.\n\n### Importing data in common vector and raster formats\n\n\nFor basic import of raster and vector files, use _r.import_\nand _v.import_, respectively.\nThese modules will reproject the input data if necessary.\nIf the input data's CRS matches the Location's CRS, we can use\n_r.in.gdal_ or _v.in.ogr_\nfor importing raster and vector.\n\n\nAlternatively, you can use a two-step approach\nfor the cases when the data's CRS doesn't match the Location's CRS.\nFirst create a new temporary Location\nbased on the CRS of the data you want to import, switch to this Location\nand then use _r.in.gdal_ or _v.in.ogr_\nto import raster and vector data, respectively. Then switch to the Location\nof your project and use\n_r.proj_ and _v.proj_\nto reproject data from the temporary Location to your project Location.\nThis approach is necessary for formats which are not supported by\n_r.import_ and _v.import_ modules.\nModules _r.proj_ and _v.proj_\ncan be also used for bringing raster and vector maps from one Location to another.\n\n\nModules _r.in.gdal_ and _v.in.ogr_\ncheck whether the CRS of the imported data matches the Location's CRS.\nSometimes the CRS of imported data is not specified correctly\nor is missing and therefore import fails.\nIf you know that the actual CRS matches the Location's CRS,\nit is appropriate to use _r.in.gdal_'s\nor _v.in.ogr_'s -o flag to overwrite the projection\ncheck and import the data as they are.\n\n\nIf you zoom to raster or vector in GRASS GUI and it does not fit with\nthe rest of the data, it means that it was imported with wrong projection\ninformation (or with the -o flag when the coordinates in fact don't match).\nYou can use r.info and v.info to get the information\nabout the extents of (already imported) rasters and vectors.\n\n### Importing CSV and other ASCII data\n\n\nThere are many formats of plain text files. In the context of GIS we usually\ntalk about ASCII formats and CSV files. CSV files usually hold only\ncoordinates and sometimes attributes of points.\nThese files usually don't have CRS information attached to them,\nso we must be very careful and import the data only if the coordinates\nare in the CRS of the Location we are using.\n\n\nLet's create a CSV file called `points.txt`\nusing a text editor (Notepad++, TextEdit, MS Notepad), for example:\n\n```\n637803.6,223804.7\n641835.5,223761.2\n643056.0,217419.0\n```\n\nThe coordinates we entered are in EPSG:3358 and we assume that the\nGRASS Location is using this CRS as well.\nThis file can be imported to GRASS GIS using:", "_____no_output_____" ] ], [ [ "!v.in.ascii input=points.txt output=test_ascii separator=comma x=1 y=2", "_____no_output_____" ] ], [ [ "Notice, we have to specify the column number where the X and Y (optionally Z)\ncoordinates are stored. In this example, X coordinates are in the first column\nY in the second one. Don't forget to specify correct column delimiter.\n\nIf the data are not in the CRS we are using, create a new Location\nwith matching CRS,\nimport the data and use _v.proj_ as described above.\n\n\n### Importing lidar point clouds\n\nLidar point clouds can be imported in two ways: as raster maps using binning\nor as vector points. However, one must explore the dataset first.\n\n\nIn command line, we can check the projection information and other metadata\nabout a LAS file using _lasinfo_ tool:", "_____no_output_____" ] ], [ [ "!lasinfo tile_0793_016_spm.las", "_____no_output_____" ] ], [ [ "_r.in.lidar_ module can be used to scan the spatial extent\nof the dataset:", "_____no_output_____" ] ], [ [ "!r.in.lidar input=tile_0793_016_spm.las -s", "_____no_output_____" ] ], [ [ "#### Binning\n\nBefore creating the actual raster with elevation, we need to decide the extent\nand the resolution we will use for the binning. We can use\n_r.in.lidar_ module for that by setting the resolution\ndirectly and using a -e flag to use dataset extent instead of taking it from\nthe computational region.\nWe are interested in the density of points, so we use `method=n`:", "_____no_output_____" ] ], [ [ "!r.in.lidar input=tile_0793_016_spm.las output=tile_0793_016_n method=n -e resolution=2", "_____no_output_____" ] ], [ [ "After determining the optimal resolution for binning and the desired area,\nwe can use _g.region_ to set the computational region.\n_r.in.lidar_ without the additional parameters above\nwill create a raster map from points using binning with resolution and extent\ntaken from the computational region:", "_____no_output_____" ] ], [ [ "!r.in.lidar input=tile_0793_016_spm.las output=tile_0793_016", "_____no_output_____" ] ], [ [ "#### Interpolation\n\nWhen the result of binning contains a lot of NULL cells or when it is not\nsmooth enough for further analysis, we can import the point cloud as vector\npoints and interpolate a raster.\n\n\nSupposing that we already determined the desired extent and resolution\n(using _r.in.lidar_ as described above) we can use\n_v.in.lidar_ lidar for import (and using class filter\nto get only ground points):", "_____no_output_____" ] ], [ [ "!v.in.lidar input=tile_0793_016_spm.las output=tile_0793_016 class=2 -r -t -b", "_____no_output_____" ] ], [ [ "This import only the points of class 2 (ground)\nin the current computational region\nwithout the attribute table and building the topology.\nThen we follow with interpolation using,\ne.g. _v.surf.rst_ module:", "_____no_output_____" ] ], [ [ "!v.surf.rst input=tile_0793_016 elevation=tile_0793_016_elevation slope=tile_0793_016_slope aspect=tile_0793_016_aspect npmin=100 tension=20 smooth=1", "_____no_output_____" ] ], [ [ "#### Importing data in different CRS\n\nIn case the CRS of the file doesn't match the CRS\nused in the GRASS Location, reprojection can be done before importing\nusing _las2las_ tool.\n\n\nThe following example command is for reprojecting tiles\nin NAD83/North Carolina in feet (EPSG:2264)\ninto NAD83/North Carolina in meters (EPSG:3358):", "_____no_output_____" ] ], [ [ "!las2las --a_srs=EPSG:2264 --t_srs=EPSG:3358 -i input_spf.las -o output_spm.las", "_____no_output_____" ] ], [ [ "#### Importing data with broken projection information\n\nModules _r.in.lidar_ and _v.in.lidar_\ncheck whether the CRS of the imported data matches the Location's CRS.\nSometimes the CRS of imported data is not specified correctly\nor is missing and therefore import fails.\nIf you know that the actual CRS matches the Location's CRS,\nit is appropriate to use _r.in.lidar_'s\nor _v.in.lidar_'s -o flag to overwrite the projection\ncheck and import the data as they are.", "_____no_output_____" ] ], [ [ "!r.in.lidar input=tile_0793_016_spm.las -s -o", "_____no_output_____" ] ], [ [ "### Transferring GRASS GIS data between two computers\n\nIf two GRASS GIS users want to exchange data, they can use GRASS GIS native\nexchange format -- _packed map_. A vector or raster map can be\nexported from a GRASS Location in this format using\n_v.pack_ or _r.pack_ respectively.\nThis format preserves everything for a map in a way as it is stored in\na GRASS Database. _Projection of the source and target GRASS Locations\nmust be the same._\n\n\nIf GRASS GIS users wish to exchange GRASS Mapsets, they can do so as long as\nthe source and target GRASS Locations have the same projection.\nThe PERMANENT Mapset should not be usually exchanged as it is a crucial part\nof the given Location.\nLocations can be easily transferred in between GRASS Database directories\non different computers as they carry all data and projection information\nwithin them and the storage format used in the background is platform independent.\nLocations as well as whole GRASS Databases can be copied and moved\nin the same way as any other directories on the computer.\n\n\n### Further resources\n\n\n \n* [GRASS GIS manual](http://grass.osgeo.org/grass72/manuals)\n \n* [About GRASS GIS Database structure](https://grass.osgeo.org/grass72/manuals/grass_database.html)\n \n* [GRASS GIS for ArcGIS users](https://grasswiki.osgeo.org/wiki/GRASS_GIS_for_ArcGIS_users)\n \n* [epsg.io](http://epsg.io/) (Repository of EPSG codes)", "_____no_output_____" ] ], [ [ "# end the GRASS session\nos.remove(rcfile)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbdd623ef31a5e06d2dae9e3f76bf68bc9e25244
56,677
ipynb
Jupyter Notebook
neg_0416.ipynb
funnybomb/neg_data_creation
79cc9ecfcedf073c4e438ad1ed77bda25af3d5a4
[ "MIT" ]
null
null
null
neg_0416.ipynb
funnybomb/neg_data_creation
79cc9ecfcedf073c4e438ad1ed77bda25af3d5a4
[ "MIT" ]
null
null
null
neg_0416.ipynb
funnybomb/neg_data_creation
79cc9ecfcedf073c4e438ad1ed77bda25af3d5a4
[ "MIT" ]
null
null
null
35.203106
160
0.429045
[ [ [ "from Bio import pairwise2 as pw\nfrom Bio import Seq\nfrom Bio import SeqIO \nimport Bio\nfrom Bio.Alphabet import IUPAC\nimport numpy as np\nimport pandas as pd\nimport re", "_____no_output_____" ], [ "import time\nfrom functools import wraps\n \ndef fn_timer(function):\n @wraps(function)\n def function_timer(*args, **kwargs):\n t0 = time.time()\n result = function(*args, **kwargs)\n t1 = time.time()\n print (\"Total time running %s: %s seconds\" %\n (function.__name__, str(t1-t0))\n )\n return result\n return function_timer", "_____no_output_____" ], [ "uniprot = list(SeqIO.parse('uniprot-proteome_human.fasta','fasta'))", "_____no_output_____" ], [ "for seq in uniprot: #\n x = seq.id\n seq.id = x.split(\"|\")[1]", "_____no_output_____" ], [ "ids = [seq.id for seq in uniprot]\nnames = [seq.name for seq in uniprot]", "_____no_output_____" ], [ "uni_dict = {}\nfor i in uniprot:\n uni_dict[i.id] =i", "_____no_output_____" ], [ "grist = pd.read_table('gristone_positive_data.txt')", "_____no_output_____" ], [ "grist.columns", "_____no_output_____" ], [ "grist.loc[[1,3,5]]", "_____no_output_____" ], [ "#@fn_timer\ndef calc_identity_score(seq1,seq2,gap=-0.5,extend=-0.1):\n \"\"\"\n return seq1 seq1 pairwise identiy score\n seq1 is positive \n seq1 seq2 is string\n\n Bio.pairwise2.format_alignment output:\n MPKGKKAKG------\n ||||||| \n --KGKKAKGKKVAPA\n Score=7\n \n alignment output: [('MPKGKKAKG------', '--KGKKAKGKKVAPA', 7.0, 0, 15)]\n score = ali[0][2] = 7\n \"\"\"\n ali = pw.align.globalxs(seq1,seq2,gap,extend,score_only=True)\n # gap penalty = -0.5 in case of cak caak score =3\n return ali/min(len(seq1),len(seq2)) # 返回短序列的值,防止substring", "_____no_output_____" ], [ "#@fn_timer\ndef window_generator(seq, window_lenth=7,step=1):\n \"\"\"\n return list of seq window slide\n seq is string\n \"\"\"\n if len(seq) >= window_lenth:\n return [seq[i:i+window_lenth] for i in range(0,len(seq)-window_lenth+1,step)]\n else:\n return []", "_____no_output_____" ], [ "window_generator('123',3)", "_____no_output_____" ], [ "from Bio.pairwise2 import format_alignment", "_____no_output_____" ], [ "def flat(nums):\n res = []\n for i in nums:\n if isinstance(i, list):\n res.extend(flat(i))\n else:\n res.append(i)\n return res", "_____no_output_____" ], [ "#@fn_timer\ndef slide_with_flank(seq,full,step=1,up_flank=6,down_flank=6,flags=0):\n \"\"\"\n return window slide result as list for a full str given potential sub seq and it's flank removed\n seq=abc, full = 01234abc45678abc1234 up=1 down=1 step =1\n result is ['012', '123', '567', '234']\n 生成一个str full 的滑动窗口自片段,去除了seq和其上下游的部分\n \"\"\"\n res = []\n window_len = len(seq)\n coords = [i.span() for i in re.finditer(seq,full,flags)] # = search_all\n # 处理首尾情况\n if len(coords) == 0:\n res.append(window_generator(full,window_lenth=window_len,step=step))\n\n elif len(coords) == 1:\n if (coords[0][0]-up_flank) >= 0:\n res.append(window_generator(full[0:coords[0][0]-up_flank],\n window_lenth=window_len,step=step))\n if (coords[0][1]+down_flank) <= len(full):\n res.append(window_generator(full[coords[0][1]+up_flank:],\n window_lenth=window_len,step=step))\n else: # len(coords) >1 \n if (coords[0][0]-up_flank) >= 0:\n res.append(window_generator(full[0:coords[0][0]-up_flank],\n window_lenth=window_len,step=step))\n for i in range(1,len(coords)):\n ## 处理 1 2 之间的东西\n if coords[i][0] - coords[i-1][1] > up_flank+down_flank+window_len:\n res.append(window_generator(full[coords[i-1][1]+up_flank:coords[i][0]-down_flank],\n window_lenth=window_len,step=step))\n \n if (coords[-1][1]+down_flank) <= len(full):\n res.append(window_generator(full[coords[-1][1]+down_flank:],\n window_lenth=window_len,step=step)) \n \n return flat(res)", "_____no_output_____" ], [ "slide_with_flank('abc','01234abc456raa78abc7779',up_flank=2,down_flank=2)", "_____no_output_____" ], [ "###### @fn_timer\ndef filter_with_identity_affinity(seq,full,identity_cutoff=0.5,step=1,up=6,down=6,flags=0):\n filtered = {}\n slides = slide_with_flank(seq,full,step=step,up_flank=up,down_flank=down,flags=flags)\n for s in slides:\n identity_score = calc_identity_score(seq,s)\n if identity_score <= identity_cutoff:\n #if s in filtered.keys(): #已经有score, 寸大值表明有大片段\n filtered[s] = identity_score\n return filtered", "_____no_output_____" ], [ "grist['neg1'] =np.full_like(grist['peptide'],'o')\nt0 = time.process_time()\nfor i in range(0,len(grist)):\n#for i in range(0,10000):\n g = grist.iloc[i]\n if g['uniport_id'] in ids:\n pep = str(g['left_flanking']) + str(g['peptide']) + str(g['right_flanking'])\n full = str(uni_dict[g['uniport_id']].seq)\n res_local = filter_with_identity_affinity(pep,full,step=10)\n# res_full = {}\n# for win in res_local.keys(): # 过滤掉阳性集在window结果中 identity>0.5的\n# for pep in np.random.choice(grist['peptide'],100):#.remove(g['peptide']):\n# score = calc_identity_score(win,pep)\n# if score <0.5:\n# res_full[win] = score\n# else:\n# break\n# res_full_key = sorted(res_full.keys(),key=lambda x:(res_local[x],res_full[x]))\n k=sorted(res_local.keys(),key=lambda x:res_local[x])\n if len(k):\n grist.loc[i,'neg1'] = k[0] \n \nprint(time.process_time()-t0)\n#grist[grist['neg1'] != 'o'].to_csv('testdata0401.txt',index = False)", "_____no_output_____" ], [ "grist[['left_flanking','right_flanking']]", "_____no_output_____" ], [ "a=grist['neg1'][0]\n#gri", "_____no_output_____" ], [ "grist.loc?", "_____no_output_____" ], [ "a", "_____no_output_____" ], [ "grist.loc?", "_____no_output_____" ], [ "grist.head()", "_____no_output_____" ], [ "\npersons={'ZhangSan':'male',\n 'LiSi':'male',\n 'WangHong':'female'}\n\n#找出所有男性\nmales = filter(lambda x:'male'== x[1], persons.items())\n\nfor (key,value) in males:\n print('%s : %s' % (key,value))\n", "ZhangSan : male\nLiSi : male\n" ], [ "grist.to_csv?", "_____no_output_____" ], [ "%%writefile train.py", "UsageError: %%writefile is a cell magic, but the cell body is empty.\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdd65c8b1e887c594ea66233dcc5c59c9b2d560
7,853
ipynb
Jupyter Notebook
src/proto.ipynb
oxinabox/RESTful.jl
8052069f228265f77308b2d08e04f445e1d73a62
[ "MIT" ]
2
2018-04-25T19:42:36.000Z
2019-06-08T08:25:21.000Z
src/proto.ipynb
oxinabox/RESTful.jl
8052069f228265f77308b2d08e04f445e1d73a62
[ "MIT" ]
null
null
null
src/proto.ipynb
oxinabox/RESTful.jl
8052069f228265f77308b2d08e04f445e1d73a62
[ "MIT" ]
1
2020-02-08T11:50:24.000Z
2020-02-08T11:50:24.000Z
30.437984
558
0.47485
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cbdd67a58f170f4d0f26152f636fb82a7662a2fa
5,382
ipynb
Jupyter Notebook
Opencv Assignments/Tanya/Line Detection.ipynb
hp77-creator/CalNet
052a973fc0a7fc9ff6bf044627fd6e8c49fb03ed
[ "MIT" ]
2
2021-08-29T17:28:40.000Z
2021-08-30T08:27:50.000Z
Opencv Assignments/Tanya/Line Detection.ipynb
hp77-creator/CalNet
052a973fc0a7fc9ff6bf044627fd6e8c49fb03ed
[ "MIT" ]
3
2021-08-29T10:18:50.000Z
2021-09-09T21:34:58.000Z
Opencv Assignments/Tanya/Line Detection.ipynb
hp77-creator/CalNet
052a973fc0a7fc9ff6bf044627fd6e8c49fb03ed
[ "MIT" ]
13
2021-08-29T08:40:19.000Z
2021-09-03T05:34:25.000Z
26.643564
83
0.308807
[ [ [ "import cv2 \nimport numpy as np", "_____no_output_____" ], [ "image = cv2.imread(r'C:\\Users\\Tanya srivastava\\Downloads\\sudoko.jpeg')\ncv2.imshow('lines',image)\ncv2.waitKey(0)\ngray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(gray,100,170,apertureSize = 3)\n\nlines = cv2.HoughLines(edges,1,np.pi/180,220)\n\nfor line in lines:\n rho,theta = line[0]\n a=np.cos(theta)\n b=np.sin(theta)\n x0=a*rho\n y0=b*rho\n x1=int(x0+1000*(-b))\n y1=int(y0+1000*(a))\n x2=int(x0-1000*(-b))\n y2=int(y0-1000*(a))\n cv2.line(image,(x1,y1),(x2,y2),(0,0,255),2)\n \ncv2.imshow('hough lines',image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()", "_____no_output_____" ], [ "lines", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cbdd6bb294988f30402554ad2ba1cfcb71f2c6fe
444,186
ipynb
Jupyter Notebook
numba/numba-cpu/Numba_Cpu.ipynb
lento234/PythonHPC
dcb3db3e46d86bccea64fb6222dd80add5fa2546
[ "BSD-3-Clause" ]
65
2019-11-15T18:13:25.000Z
2022-03-14T17:59:53.000Z
numba/numba-cpu/Numba_Cpu.ipynb
lento234/PythonHPC
dcb3db3e46d86bccea64fb6222dd80add5fa2546
[ "BSD-3-Clause" ]
1
2020-01-07T14:23:05.000Z
2020-07-07T10:59:11.000Z
numba/numba-cpu/Numba_Cpu.ipynb
lento234/PythonHPC
dcb3db3e46d86bccea64fb6222dd80add5fa2546
[ "BSD-3-Clause" ]
37
2019-11-11T15:29:00.000Z
2022-02-27T05:08:57.000Z
477.106337
208,372
0.937078
[ [ [ "# Just-in-time Compilation with [Numba](http://numba.pydata.org/) ", "_____no_output_____" ], [ "## Numba is a JIT compiler which translates Python code in native machine language\n\n* Using special decorators on Python functions Numba compiles them on the fly to machine code using LLVM\n* Numba is compatible with Numpy arrays which are the basis of many scientific packages in Python\n* It enables parallelization of machine code so that all the CPU cores are used", "_____no_output_____" ] ], [ [ "import math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numba", "_____no_output_____" ] ], [ [ "## Using `numba.jit`\n\nNumba offers `jit` which can used to decorate Python functions.", "_____no_output_____" ] ], [ [ "def is_prime(n):\n if n <= 1:\n raise ArithmeticError('\"%s\" <= 1' % n)\n if n == 2 or n == 3:\n return True\n elif n % 2 == 0:\n return False\n else:\n n_sqrt = math.ceil(math.sqrt(n))\n for i in range(3, n_sqrt):\n if n % i == 0:\n return False\n \n return True", "_____no_output_____" ], [ "n = np.random.randint(2, 10000000, dtype=np.int64) # Get a random integer between 2 and 10000000\nprint(n, is_prime(n))", "9166285 False\n" ], [ "#is_prime(1)", "_____no_output_____" ], [ "@numba.jit\ndef is_prime_jitted(n):\n if n <= 1:\n raise ArithmeticError('\"%s\" <= 1' % n)\n if n == 2 or n == 3:\n return True\n elif n % 2 == 0:\n return False\n else:\n n_sqrt = math.ceil(math.sqrt(n))\n for i in range(3, n_sqrt):\n if n % i == 0:\n return False\n\n return True", "_____no_output_____" ], [ "numbers = np.random.randint(2, 100000, dtype=np.int64, size=10000)\n%time p1 = [is_prime(n) for n in numbers]\n%time p2 = [is_prime_jitted(n) for n in numbers]", "CPU times: user 99.8 ms, sys: 58 µs, total: 99.9 ms\nWall time: 99.4 ms\n" ] ], [ [ "## Using `numba.jit` with `nopython=True`", "_____no_output_____" ] ], [ [ "@numba.jit(nopython=True)\ndef is_prime_njitted(n):\n if n <= 1:\n raise ArithmeticError('\"%s\" <= 1' % n)\n if n == 2 or n == 3:\n return True\n elif n % 2 == 0:\n return False\n else:\n n_sqrt = math.ceil(math.sqrt(n))\n for i in range(3, n_sqrt):\n if n % i == 0:\n return False\n\n return True", "_____no_output_____" ], [ "numbers = np.random.randint(2, 100000, dtype=np.int64, size=1000)\n%time p1 = [is_prime_jitted(n) for n in numbers]\n%time p2 = [is_prime_njitted(n) for n in numbers]", "CPU times: user 9.06 ms, sys: 4.55 ms, total: 13.6 ms\nWall time: 13.5 ms\n" ] ], [ [ "## Using ` @numba.jit(nopython=True)` is equivalent to using ` @numba.njit`", "_____no_output_____" ] ], [ [ "@numba.njit\ndef is_prime_njitted(n):\n if n <= 1:\n raise ArithmeticError('n <= 1')\n if n == 2 or n == 3:\n return True\n elif n % 2 == 0:\n return False\n else:\n n_sqrt = math.ceil(math.sqrt(n))\n for i in range(3, n_sqrt):\n if n % i == 0:\n return False\n\n return True", "_____no_output_____" ], [ "numbers = np.random.randint(2, 100000, dtype=np.int64, size=1000)\n%time p = [is_prime_jitted(n) for n in numbers]\n%time p = [is_prime_njitted(n) for n in numbers]", "CPU times: user 11.9 ms, sys: 0 ns, total: 11.9 ms\nWall time: 11.9 ms\nCPU times: user 74.7 ms, sys: 5.06 ms, total: 79.7 ms\nWall time: 88.7 ms\n" ] ], [ [ "## Use `cache=True` to cache the compiled function", "_____no_output_____" ] ], [ [ "import math\nfrom numba import njit\n\n@njit(cache=True)\ndef is_prime_njitted_cached(n):\n if n <= 1:\n raise ArithmeticError('n <= 1')\n if n == 2 or n == 3:\n return True\n elif n % 2 == 0:\n return False\n else:\n n_sqrt = math.ceil(math.sqrt(n))\n for i in range(3, n_sqrt):\n if n % i == 0:\n return False\n\n return True", "_____no_output_____" ], [ "numbers = np.random.randint(2, 100000, dtype=np.int64, size=1000)\n%time p = [is_prime_njitted(n) for n in numbers]\n%time p = [is_prime_njitted_cached(n) for n in numbers]", "CPU times: user 916 µs, sys: 0 ns, total: 916 µs\nWall time: 922 µs\nCPU times: user 80.8 ms, sys: 8.15 ms, total: 89 ms\nWall time: 90.3 ms\n" ] ], [ [ "## Vector Triad Benchmark Python vs Numpy vs Numba", "_____no_output_____" ] ], [ [ "from timeit import default_timer as timer\n\ndef vecTriad(a, b, c, d):\n for j in range(a.shape[0]):\n a[j] = b[j] + c[j] * d[j]\n \ndef vecTriadNumpy(a, b, c, d):\n a[:] = b + c * d\n\[email protected]()\ndef vecTriadNumba(a, b, c, d):\n for j in range(a.shape[0]):\n a[j] = b[j] + c[j] * d[j]\n\n \n# Initialize Vectors\nn = 10000 # Vector size\nr = 100 # Iterations\na = np.zeros(n, dtype=np.float64)\nb = np.empty_like(a)\nb[:] = 1.0\nc = np.empty_like(a)\nc[:] = 1.0\nd = np.empty_like(a)\nd[:] = 1.0\n\n\n# Python version\nstart = timer()\n\nfor i in range(r):\n vecTriad(a, b, c, d)\n \nend = timer()\nmflops = 2.0 * r * n / ((end - start) * 1.0e6) \nprint(f'Python: Mflops/sec: {mflops}')\n\n\n# Numpy version\nstart = timer()\n\nfor i in range(r):\n vecTriadNumpy(a, b, c, d)\n \nend = timer()\nmflops = 2.0 * r * n / ((end - start) * 1.0e6) \nprint(f'Numpy: Mflops/sec: {mflops}')\n\n\n# Numba version\nvecTriadNumba(a, b, c, d) # Run once to avoid measuring the compilation overhead\n\nstart = timer()\n\nfor i in range(r):\n vecTriadNumba(a, b, c, d)\n \nend = timer()\nmflops = 2.0 * r * n / ((end - start) * 1.0e6) \nprint(f'Numba: Mflops/sec: {mflops}')", "Python: Mflops/sec: 4.054391116396938\nNumpy: Mflops/sec: 1440.7789426876857\nNumba: Mflops/sec: 3981.287948188027\n" ] ], [ [ "## Eager compilation using function signatures", "_____no_output_____" ] ], [ [ "import math\nfrom numba import njit\n\n@njit(['boolean(int64)', 'boolean(int32)'])\ndef is_prime_njitted_eager(n):\n if n <= 1:\n raise ArithmeticError('n <= 1')\n if n == 2 or n == 3:\n return True\n elif n % 2 == 0:\n return False\n else:\n n_sqrt = math.ceil(math.sqrt(n))\n for i in range(3, n_sqrt):\n if n % i == 0:\n return False\n\n return True", "_____no_output_____" ], [ "numbers = np.random.randint(2, 1000000, dtype=np.int64, size=1000)\n\n# Run twice aft\n%time p1 = [is_prime_njitted_eager(n) for n in numbers]\n%time p2 = [is_prime_njitted_eager(n) for n in numbers]", "CPU times: user 450 µs, sys: 0 ns, total: 450 µs\nWall time: 453 µs\nCPU times: user 449 µs, sys: 0 ns, total: 449 µs\nWall time: 452 µs\n" ], [ "p1 = [is_prime_njitted_eager(n) for n in numbers.astype(np.int32)]\n#p2 = [is_prime_njitted_eager(n) for n in numbers.astype(np.float64)]", "_____no_output_____" ] ], [ [ "## Calculating and plotting the [Mandelbrot set](https://en.wikipedia.org/wiki/Mandelbrot_set)", "_____no_output_____" ] ], [ [ "X, Y = np.meshgrid(np.linspace(-2.0, 1, 1000), np.linspace(-1.0, 1.0, 1000))\n\ndef mandelbrot(X, Y, itermax):\n mandel = np.empty(shape=X.shape, dtype=np.int32)\n for i in range(X.shape[0]):\n for j in range(X.shape[1]):\n it = 0\n cx = X[i, j]\n cy = Y[i, j]\n x = 0.0\n y = 0.0\n while x * x + y * y < 4.0 and it < itermax:\n x, y = x * x - y * y + cx, 2.0 * x * y + cy\n it += 1\n mandel[i, j] = it\n \n return mandel", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\nax = fig.add_subplot(111)\n\n%time m = mandelbrot(X, Y, 100)\n \nax.imshow(np.log(1 + m), extent=[-2.0, 1, -1.0, 1.0]);\nax.set_aspect('equal')\nax.set_ylabel('Im[c]')\nax.set_xlabel('Re[c]');", "CPU times: user 26 s, sys: 43.9 ms, total: 26.1 s\nWall time: 26.1 s\n" ], [ "@numba.njit(parallel=True)\ndef mandelbrot_jitted(X, Y, radius2, itermax):\n mandel = np.empty(shape=X.shape, dtype=np.int32)\n for i in numba.prange(X.shape[0]):\n for j in range(X.shape[1]):\n it = 0\n cx = X[i, j]\n cy = Y[i, j]\n x = cx\n y = cy\n while x * x + y * y < 4.0 and it < itermax:\n x, y = x * x - y * y + cx, 2.0 * x * y + cy\n it += 1\n mandel[i, j] = it\n \n return mandel", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\nax = fig.add_subplot(111)\n\n\n%time m = mandelbrot_jitted(X, Y, 4.0, 100)\n \nax.imshow(np.log(1 + m), extent=[-2.0, 1, -1.0, 1.0]);\nax.set_aspect('equal')\nax.set_ylabel('Im[c]')\nax.set_xlabel('Re[c]');", "CPU times: user 517 ms, sys: 0 ns, total: 517 ms\nWall time: 367 ms\n" ] ], [ [ "### Getting parallelization information", "_____no_output_____" ] ], [ [ "mandelbrot_jitted.parallel_diagnostics(level=3)", " \n================================================================================\n Parallel Accelerator Optimizing: Function mandelbrot_jitted, <ipython-\ninput-19-238a75aae604> (1) \n================================================================================\n\n\nParallel loop listing for Function mandelbrot_jitted, <ipython-input-19-238a75aae604> (1) \n---------------------------------------------------------------|loop #ID\[email protected](parallel=True) | \ndef mandelbrot_jitted(X, Y, radius2, itermax): | \n mandel = np.empty(shape=X.shape, dtype=np.int32) | \n for i in numba.prange(X.shape[0]):-------------------------| #0\n for j in range(X.shape[1]): | \n it = 0 | \n cx = X[i, j] | \n cy = Y[i, j] | \n x = cx | \n y = cy | \n while x * x + y * y < 4.0 and it < itermax: | \n x, y = x * x - y * y + cx, 2.0 * x * y + cy | \n it += 1 | \n mandel[i, j] = it | \n | \n return mandel | \n--------------------------------- Fusing loops ---------------------------------\nAttempting fusion of parallel loops (combines loops with similar properties)...\nFollowing the attempted fusion of parallel for-loops there are 1 parallel for-\nloop(s) (originating from loops labelled: #0).\n--------------------------------------------------------------------------------\n----------------------------- Before Optimisation ------------------------------\n--------------------------------------------------------------------------------\n------------------------------ After Optimisation ------------------------------\nParallel structure is already optimal.\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n \n---------------------------Loop invariant code motion---------------------------\nAllocation hoisting:\nNo allocation hoisting found\n" ] ], [ [ "## Creating `ufuncs` using `numba.vectorize`", "_____no_output_____" ] ], [ [ "from math import sin\nfrom numba import float64, int64\n\ndef my_numpy_sin(a, b):\n return np.sin(a) + np.sin(b)\n\[email protected]\ndef my_sin(a, b):\n return sin(a) + sin(b)\n\[email protected]([float64(float64, float64), int64(int64, int64)], target='parallel')\ndef my_sin_numba(a, b):\n return np.sin(a) + np.sin(b)", "_____no_output_____" ], [ "x = np.random.randint(0, 100, size=9000000)\ny = np.random.randint(0, 100, size=9000000)\n\n%time _ = my_numpy_sin(x, y)\n%time _ = my_sin(x, y)\n%time _ = my_sin_numba(x, y)", "CPU times: user 293 ms, sys: 296 ms, total: 589 ms\nWall time: 591 ms\nCPU times: user 2.14 s, sys: 229 ms, total: 2.37 s\nWall time: 2.37 s\nCPU times: user 2.69 s, sys: 1.12 s, total: 3.82 s\nWall time: 377 ms\n" ] ], [ [ "### Vectorize the testing of prime numbers ", "_____no_output_____" ] ], [ [ "@numba.vectorize('boolean(int64)')\ndef is_prime_v(n):\n if n <= 1:\n raise ArithmeticError(f'\"0\" <= 1')\n if n == 2 or n == 3:\n return True\n elif n % 2 == 0:\n return False\n else:\n n_sqrt = math.ceil(math.sqrt(n))\n for i in range(3, n_sqrt):\n if n % i == 0:\n return False\n \n return True", "_____no_output_____" ], [ "numbers = np.random.randint(2, 10000000000, dtype=np.int64, size=100000)\n%time p = is_prime_v(numbers)", "CPU times: user 2.19 s, sys: 0 ns, total: 2.19 s\nWall time: 2.19 s\n" ] ], [ [ "### Parallelize the vectorized function", "_____no_output_____" ] ], [ [ "@numba.vectorize(['boolean(int64)', 'boolean(int32)'],\n target='parallel')\ndef is_prime_vp(n):\n if n <= 1:\n raise ArithmeticError('n <= 1')\n if n == 2 or n == 3:\n return True\n elif n % 2 == 0:\n return False\n else:\n n_sqrt = math.ceil(math.sqrt(n))\n for i in range(3, n_sqrt):\n if n % i == 0:\n return False\n \n return True", "_____no_output_____" ], [ "numbers = np.random.randint(2, 10000000000, dtype=np.int64, size=100000)\n%time p1 = is_prime_v(numbers)\n%time p2 = is_prime_vp(numbers)", "CPU times: user 2.16 s, sys: 0 ns, total: 2.16 s\nWall time: 2.16 s\nCPU times: user 3.29 s, sys: 242 µs, total: 3.29 s\nWall time: 289 ms\n" ], [ "# Print the largest primes from to 1 and 10 millions\nnumbers = np.arange(1000000, 10000001, dtype=np.int32)\n%time p1 = is_prime_vp(numbers)\nprimes = numbers[p1]\n\nfor n in primes[-10:]:\n print(n)", "CPU times: user 9.85 s, sys: 1.73 ms, total: 9.85 s\nWall time: 836 ms\n9999889\n9999901\n9999907\n9999929\n9999931\n9999937\n9999943\n9999971\n9999973\n9999991\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cbdd7550cbb48cb63982baeb5704c7315e174a0f
80,295
ipynb
Jupyter Notebook
notebook/save_image_embeddings.ipynb
jingxuanyang/Shopee-Product-Matching
703087a6bbb87340766bee5ccd38a7ffbdab0b06
[ "MIT" ]
13
2021-05-28T12:49:03.000Z
2022-03-15T19:38:03.000Z
notebook/save_image_embeddings.ipynb
jingxuanyang/Shopee-Product-Matching
703087a6bbb87340766bee5ccd38a7ffbdab0b06
[ "MIT" ]
2
2021-12-20T08:36:08.000Z
2021-12-21T12:44:56.000Z
notebook/save_image_embeddings.ipynb
jingxuanyang/Shopee-Product-Matching
703087a6bbb87340766bee5ccd38a7ffbdab0b06
[ "MIT" ]
4
2021-07-31T14:54:48.000Z
2021-12-16T14:27:18.000Z
29.476872
138
0.52758
[ [ [ "import sys\n\nsys.path.append('../input/shopee-competition-utils')\nsys.path.insert(0,'../input/pytorch-image-models')", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\n\nimport torch\nfrom torch import nn\nfrom torch.nn import Parameter\nfrom torch.nn import functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\nimport albumentations\nfrom albumentations.pytorch.transforms import ToTensorV2\n\nfrom custom_scheduler import ShopeeScheduler\nfrom custom_activation import replace_activations, Mish\nfrom custom_optimizer import Ranger\n\nimport math\nimport cv2\nimport timm\nimport os\nimport random\nimport gc\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import GroupKFold\nfrom sklearn.neighbors import NearestNeighbors\nfrom tqdm.notebook import tqdm", "_____no_output_____" ], [ "class CFG: \n \n DATA_DIR = '../input/shopee-product-matching/train_images'\n TRAIN_CSV = '../input/shopee-product-matching/train.csv'\n\n # data augmentation\n IMG_SIZE = 512\n MEAN = [0.485, 0.456, 0.406]\n STD = [0.229, 0.224, 0.225]\n\n SEED = 2021\n\n # data split\n N_SPLITS = 5\n TEST_FOLD = 0\n VALID_FOLD = 1\n\n EPOCHS = 8\n BATCH_SIZE = 8\n\n NUM_WORKERS = 4\n DEVICE = 'cuda:0'\n\n CLASSES = 6609 \n SCALE = 30\n MARGINS = [0.5,0.6,0.7,0.8,0.9]\n MARGIN = 0.5\n\n BEST_THRESHOLD = 0.19\n BEST_THRESHOLD_MIN2 = 0.225\n\n MODEL_NAME = 'resnet50'\n MODEL_NAMES = ['resnet50','resnext50_32x4d','densenet121','efficientnet_b3','eca_nfnet_l0']\n LOSS_MODULE = 'arc'\n LOSS_MODULES = ['arc','curricular']\n USE_ARCFACE = True\n MODEL_PATH = f'{MODEL_NAME}_{LOSS_MODULE}_face_epoch_8_bs_8_margin_{MARGIN}.pt'\n FC_DIM = 512\n SCHEDULER_PARAMS = {\n \"lr_start\": 1e-5,\n \"lr_max\": 1e-5 * 32,\n \"lr_min\": 1e-6,\n \"lr_ramp_ep\": 5,\n \"lr_sus_ep\": 0,\n \"lr_decay\": 0.8,\n }", "_____no_output_____" ], [ "def seed_everything(seed):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = True # set True to be faster\n\nseed_everything(CFG.SEED)", "_____no_output_____" ], [ "def get_test_transforms():\n return albumentations.Compose(\n [\n albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),\n albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),\n ToTensorV2(p=1.0)\n ]\n )", "_____no_output_____" ], [ "class ShopeeImageDataset(torch.utils.data.Dataset):\n \"\"\"for validating and test\n \"\"\"\n def __init__(self,df, transform = None):\n self.df = df \n self.root_dir = CFG.DATA_DIR\n self.transform = transform\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self,idx):\n\n row = self.df.iloc[idx]\n\n img_path = os.path.join(self.root_dir,row.image)\n image = cv2.imread(img_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n label = row.label_group\n\n if self.transform:\n augmented = self.transform(image=image)\n image = augmented['image'] \n \n return image,torch.tensor(1)", "_____no_output_____" ] ], [ [ "## ArcMarginProduct", "_____no_output_____" ] ], [ [ "class ArcMarginProduct(nn.Module):\n r\"\"\"Implement of large margin arc distance: :\n Args:\n in_features: size of each input sample\n out_features: size of each output sample\n s: norm of input feature\n m: margin\n cos(theta + m)\n \"\"\"\n def __init__(self, in_features, out_features, s=30.0, m=0.50, easy_margin=False, ls_eps=0.0):\n print('Using Arc Face')\n super(ArcMarginProduct, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.s = s\n self.m = m\n self.ls_eps = ls_eps # label smoothing\n self.weight = Parameter(torch.FloatTensor(out_features, in_features))\n nn.init.xavier_uniform_(self.weight)\n\n self.easy_margin = easy_margin\n self.cos_m = math.cos(m)\n self.sin_m = math.sin(m)\n self.th = math.cos(math.pi - m)\n self.mm = math.sin(math.pi - m) * m\n\n def forward(self, input, label):\n # --------------------------- cos(theta) & phi(theta) ---------------------------\n cosine = F.linear(F.normalize(input), F.normalize(self.weight))\n sine = torch.sqrt(1.0 - torch.pow(cosine, 2))\n phi = cosine * self.cos_m - sine * self.sin_m\n if self.easy_margin:\n phi = torch.where(cosine > 0, phi, cosine)\n else:\n phi = torch.where(cosine > self.th, phi, cosine - self.mm)\n # --------------------------- convert label to one-hot ---------------------------\n # one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda')\n one_hot = torch.zeros(cosine.size(), device=CFG.DEVICE)\n one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n if self.ls_eps > 0:\n one_hot = (1 - self.ls_eps) * one_hot + self.ls_eps / self.out_features\n # -------------torch.where(out_i = {x_i if condition_i else y_i) -------------\n output = (one_hot * phi) + ((1.0 - one_hot) * cosine)\n output *= self.s\n\n return output, nn.CrossEntropyLoss()(output,label)", "_____no_output_____" ] ], [ [ "## CurricularFace", "_____no_output_____" ] ], [ [ "'''\ncredit : https://github.com/HuangYG123/CurricularFace/blob/8b2f47318117995aa05490c05b455b113489917e/head/metrics.py#L70\n'''\n\ndef l2_norm(input, axis = 1):\n norm = torch.norm(input, 2, axis, True)\n output = torch.div(input, norm)\n\n return output\n\nclass CurricularFace(nn.Module):\n def __init__(self, in_features, out_features, s = 30, m = 0.50):\n super(CurricularFace, self).__init__()\n\n print('Using Curricular Face')\n\n self.in_features = in_features\n self.out_features = out_features\n self.m = m\n self.s = s\n self.cos_m = math.cos(m)\n self.sin_m = math.sin(m)\n self.threshold = math.cos(math.pi - m)\n self.mm = math.sin(math.pi - m) * m\n self.kernel = nn.Parameter(torch.Tensor(in_features, out_features))\n self.register_buffer('t', torch.zeros(1))\n nn.init.normal_(self.kernel, std=0.01)\n\n def forward(self, embbedings, label):\n embbedings = l2_norm(embbedings, axis = 1)\n kernel_norm = l2_norm(self.kernel, axis = 0)\n cos_theta = torch.mm(embbedings, kernel_norm)\n cos_theta = cos_theta.clamp(-1, 1) # for numerical stability\n with torch.no_grad():\n origin_cos = cos_theta.clone()\n target_logit = cos_theta[torch.arange(0, embbedings.size(0)), label].view(-1, 1)\n\n sin_theta = torch.sqrt(1.0 - torch.pow(target_logit, 2))\n cos_theta_m = target_logit * self.cos_m - sin_theta * self.sin_m #cos(target+margin)\n mask = cos_theta > cos_theta_m\n final_target_logit = torch.where(target_logit > self.threshold, cos_theta_m, target_logit - self.mm)\n\n hard_example = cos_theta[mask]\n with torch.no_grad():\n self.t = target_logit.mean() * 0.01 + (1 - 0.01) * self.t\n cos_theta[mask] = hard_example * (self.t + hard_example)\n cos_theta.scatter_(1, label.view(-1, 1).long(), final_target_logit)\n output = cos_theta * self.s\n return output, nn.CrossEntropyLoss()(output,label)", "_____no_output_____" ], [ "class ShopeeModel(nn.Module):\n\n def __init__(\n self,\n n_classes = CFG.CLASSES,\n model_name = CFG.MODEL_NAME,\n fc_dim = CFG.FC_DIM,\n margin = CFG.MARGIN,\n scale = CFG.SCALE,\n use_fc = True,\n pretrained = True,\n use_arcface = CFG.USE_ARCFACE):\n\n super(ShopeeModel,self).__init__()\n print(f'Building Model Backbone for {model_name} model, margin = {margin}')\n\n self.backbone = timm.create_model(model_name, pretrained=pretrained)\n\n if 'efficientnet' in model_name:\n final_in_features = self.backbone.classifier.in_features\n self.backbone.classifier = nn.Identity()\n self.backbone.global_pool = nn.Identity()\n \n elif 'resnet' in model_name:\n final_in_features = self.backbone.fc.in_features\n self.backbone.fc = nn.Identity()\n self.backbone.global_pool = nn.Identity()\n\n elif 'resnext' in model_name:\n final_in_features = self.backbone.fc.in_features\n self.backbone.fc = nn.Identity()\n self.backbone.global_pool = nn.Identity()\n\n elif 'densenet' in model_name:\n final_in_features = self.backbone.classifier.in_features\n self.backbone.classifier = nn.Identity()\n self.backbone.global_pool = nn.Identity()\n\n elif 'nfnet' in model_name:\n final_in_features = self.backbone.head.fc.in_features\n self.backbone.head.fc = nn.Identity()\n self.backbone.head.global_pool = nn.Identity()\n\n self.pooling = nn.AdaptiveAvgPool2d(1)\n\n self.use_fc = use_fc\n\n if use_fc:\n self.dropout = nn.Dropout(p=0.0)\n self.fc = nn.Linear(final_in_features, fc_dim)\n self.bn = nn.BatchNorm1d(fc_dim)\n self._init_params()\n final_in_features = fc_dim\n\n if use_arcface:\n self.final = ArcMarginProduct(final_in_features, \n n_classes, \n s=scale, \n m=margin)\n else:\n self.final = CurricularFace(final_in_features, \n n_classes, \n s=scale, \n m=margin)\n\n def _init_params(self):\n nn.init.xavier_normal_(self.fc.weight)\n nn.init.constant_(self.fc.bias, 0)\n nn.init.constant_(self.bn.weight, 1)\n nn.init.constant_(self.bn.bias, 0)\n\n def forward(self, image, label):\n feature = self.extract_feat(image)\n logits = self.final(feature,label)\n return logits\n\n def extract_feat(self, x):\n batch_size = x.shape[0]\n x = self.backbone(x)\n x = self.pooling(x).view(batch_size, -1)\n\n if self.use_fc:\n x = self.dropout(x)\n x = self.fc(x)\n x = self.bn(x)\n return x\n", "_____no_output_____" ], [ "def read_dataset():\n df = pd.read_csv(CFG.TRAIN_CSV)\n df['matches'] = df.label_group.map(df.groupby('label_group').posting_id.agg('unique').to_dict())\n df['matches'] = df['matches'].apply(lambda x: ' '.join(x))\n\n gkf = GroupKFold(n_splits=CFG.N_SPLITS)\n df['fold'] = -1\n for i, (train_idx, valid_idx) in enumerate(gkf.split(X=df, groups=df['label_group'])):\n df.loc[valid_idx, 'fold'] = i\n\n labelencoder= LabelEncoder()\n df['label_group'] = labelencoder.fit_transform(df['label_group'])\n\n train_df = df[df['fold']!=CFG.TEST_FOLD].reset_index(drop=True)\n train_df = train_df[train_df['fold']!=CFG.VALID_FOLD].reset_index(drop=True)\n valid_df = df[df['fold']==CFG.VALID_FOLD].reset_index(drop=True)\n test_df = df[df['fold']==CFG.TEST_FOLD].reset_index(drop=True)\n\n train_df['label_group'] = labelencoder.fit_transform(train_df['label_group'])\n\n return train_df, valid_df, test_df", "_____no_output_____" ], [ "def precision_score(y_true, y_pred):\n y_true = y_true.apply(lambda x: set(x.split()))\n y_pred = y_pred.apply(lambda x: set(x.split()))\n intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])\n len_y_pred = y_pred.apply(lambda x: len(x)).values\n precision = intersection / len_y_pred\n return precision\n\ndef recall_score(y_true, y_pred):\n y_true = y_true.apply(lambda x: set(x.split()))\n y_pred = y_pred.apply(lambda x: set(x.split()))\n intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])\n len_y_true = y_true.apply(lambda x: len(x)).values\n recall = intersection / len_y_true\n return recall\n\ndef f1_score(y_true, y_pred):\n y_true = y_true.apply(lambda x: set(x.split()))\n y_pred = y_pred.apply(lambda x: set(x.split()))\n intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])\n len_y_pred = y_pred.apply(lambda x: len(x)).values\n len_y_true = y_true.apply(lambda x: len(x)).values\n f1 = 2 * intersection / (len_y_pred + len_y_true)\n return f1", "_____no_output_____" ], [ "def get_image_embeddings(df, model):\n\n image_dataset = ShopeeImageDataset(df,transform=get_test_transforms())\n image_loader = torch.utils.data.DataLoader(\n image_dataset,\n batch_size=CFG.BATCH_SIZE,\n pin_memory=True,\n num_workers = CFG.NUM_WORKERS,\n drop_last=False\n )\n\n embeds = []\n with torch.no_grad():\n for img,label in tqdm(image_loader): \n img = img.to(CFG.DEVICE)\n label = label.to(CFG.DEVICE)\n feat,_ = model(img,label)\n image_embeddings = feat.detach().cpu().numpy()\n embeds.append(image_embeddings)\n \n del model\n image_embeddings = np.concatenate(embeds)\n print(f'Our image embeddings shape is {image_embeddings.shape}')\n del embeds\n gc.collect()\n return image_embeddings", "_____no_output_____" ], [ "def get_image_neighbors(df, embeddings, threshold = 0.2, min2 = False):\n\n nbrs = NearestNeighbors(n_neighbors = 50, metric = 'cosine')\n nbrs.fit(embeddings)\n distances, indices = nbrs.kneighbors(embeddings)\n\n predictions = []\n for k in range(embeddings.shape[0]):\n if min2:\n idx = np.where(distances[k,] < CFG.BEST_THRESHOLD)[0]\n ids = indices[k,idx]\n if len(ids) <= 1 and distances[k,1] < threshold:\n ids = np.append(ids,indices[k,1])\n else:\n idx = np.where(distances[k,] < threshold)[0]\n ids = indices[k,idx]\n posting_ids = ' '.join(df['posting_id'].iloc[ids].values)\n predictions.append(posting_ids)\n \n df['pred_matches'] = predictions\n df['f1'] = f1_score(df['matches'], df['pred_matches'])\n df['recall'] = recall_score(df['matches'], df['pred_matches'])\n df['precision'] = precision_score(df['matches'], df['pred_matches'])\n \n del nbrs, distances, indices\n gc.collect()\n return df", "_____no_output_____" ], [ "def search_best_threshold(valid_df,model):\n search_space = np.arange(10, 50, 1)\n valid_embeddings = get_image_embeddings(valid_df, model)\n\n print(\"Searching best threshold...\")\n best_f1_valid = 0.\n best_threshold = 0.\n for i in search_space:\n threshold = i / 100\n valid_df = get_image_neighbors(valid_df, valid_embeddings, threshold=threshold)\n valid_f1 = valid_df.f1.mean()\n valid_recall = valid_df.recall.mean()\n valid_precision = valid_df.precision.mean()\n print(f\"threshold = {threshold} -> f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}\")\n if (valid_f1 > best_f1_valid):\n best_f1_valid = valid_f1\n best_threshold = threshold\n\n print(\"Best threshold =\", best_threshold)\n print(\"Best f1 score =\", best_f1_valid)\n CFG.BEST_THRESHOLD = best_threshold\n\n # phase 2 search\n print(\"Searching best min2 threshold...\")\n search_space = np.arange(CFG.BEST_THRESHOLD * 100, CFG.BEST_THRESHOLD * 100 + 20, 0.5)\n\n best_f1_valid = 0.\n best_threshold = 0.\n\n for i in search_space:\n threshold = i / 100\n valid_df = get_image_neighbors(valid_df, valid_embeddings, threshold=threshold,min2=True)\n\n valid_f1 = valid_df.f1.mean()\n valid_recall = valid_df.recall.mean()\n valid_precision = valid_df.precision.mean()\n\n print(f\"min2 threshold = {threshold} -> f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}\")\n\n if (valid_f1 > best_f1_valid):\n best_f1_valid = valid_f1\n best_threshold = threshold\n\n print(\"Best min2 threshold =\", best_threshold)\n print(\"Best f1 score after min2 =\", best_f1_valid)\n CFG.BEST_THRESHOLD_MIN2 = best_threshold\n", "_____no_output_____" ], [ "def save_embeddings():\n \"\"\"Save valid and test image embeddings.\n \"\"\"\n train_df, valid_df, test_df = read_dataset()\n PATH_PREFIX = '../input/image-model-trained/'\n for i in range(len(CFG.LOSS_MODULES)):\n CFG.LOSS_MODULE = CFG.LOSS_MODULES[i]\n if 'arc' in CFG.LOSS_MODULE:\n CFG.USE_ARCFACE = True\n else:\n CFG.USE_ARCFACE = False\n for j in range(len(CFG.MODEL_NAMES)):\n CFG.MODEL_NAME = CFG.MODEL_NAMES[j]\n for k in range(len(CFG.MARGINS)):\n CFG.MARGIN = CFG.MARGINS[k]\n model = ShopeeModel(model_name = CFG.MODEL_NAME,\n margin = CFG.MARGIN,\n use_arcface = CFG.USE_ARCFACE)\n model.eval()\n model = replace_activations(model, torch.nn.SiLU, Mish())\n CFG.MODEL_PATH = f'{CFG.MODEL_NAME}_{CFG.LOSS_MODULE}_face_epoch_8_bs_8_margin_{CFG.MARGIN}.pt'\n MODEL_PATH = PATH_PREFIX + CFG.MODEL_PATH\n model.load_state_dict(torch.load(MODEL_PATH))\n model = model.to(CFG.DEVICE)\n\n valid_embeddings = get_image_embeddings(valid_df, model)\n VALID_EMB_PATH = '../input/image-embeddings/' + CFG.MODEL_PATH[:-3] + '_valid_embed.csv'\n np.savetxt(VALID_EMB_PATH, valid_embeddings, delimiter=',')\n\n TEST_EMB_PATH = '../input/image-embeddings/' + CFG.MODEL_PATH[:-3] + '_test_embed.csv'\n test_embeddings = get_image_embeddings(test_df, model)\n np.savetxt(TEST_EMB_PATH, test_embeddings, delimiter=',')\n", "_____no_output_____" ], [ "save_embeddings()", "Building Model Backbone for resnet50 model, margin = 0.5\nUsing Arc Face\n" ] ], [ [ "## Run test\n\nParameters:\n+ `CFG.MARGIN = [0.5,0.6,0.7,0.8,0.9]`\n+ `CFG.MODEL_NAME = ['resnet50','resnext50_32x4d','densenet121','efficientnet_b3','eca_nfnet_l0']`\n+ `CFG.LOSS_MODULE = ['arc','curricular']`", "_____no_output_____" ], [ "## save and load embeddings\n\n+ `np.savetxt('tf_efficientnet_b5_ns.csv', image_embeddings1, delimiter=',')`\n+ `image_embeddings4 = np.loadtxt(CFG.image_embeddings4_path, delimiter=',')`\n+ `image_embeddings4_path = '../input/image-embeddings/efficientnet_b3.csv'`", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
cbdd86a1d247b940338b7c231779cefb87a606cf
1,985
ipynb
Jupyter Notebook
Prelim Exam.ipynb
Krystiandres/OOP-58001
aa61a61bf986d325011ca27bacb94acce0761b76
[ "Apache-2.0" ]
null
null
null
Prelim Exam.ipynb
Krystiandres/OOP-58001
aa61a61bf986d325011ca27bacb94acce0761b76
[ "Apache-2.0" ]
null
null
null
Prelim Exam.ipynb
Krystiandres/OOP-58001
aa61a61bf986d325011ca27bacb94acce0761b76
[ "Apache-2.0" ]
null
null
null
29.191176
235
0.497229
[ [ [ "<a href=\"https://colab.research.google.com/github/Krystiandres/OOP-58001/blob/main/Prelim%20%20Exam.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "class Student:\n def __init__ (self, name, studentnum, age, school, course):\n self.studentnum = studentnum\n self.name= name\n self.age= age\n self.school = school\n self.course = course\n\n def self(self):\n return self.name + self.studentnum + self.age + self.school + self.course\n def data(self):\n print(self.self())\n\nMyself = Student (\"Andres, Lance Krystian \", \"202114719 \", \"19 \", \"Adamson University \", \" BS Computer Engineering\")\nMyself.data()\n", "Andres, Lance Krystian 202114719 19 Adamson University BS Computer Engineering\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
cbdd88183092ad17b9f91e9297d3d9173d4374cf
56,346
ipynb
Jupyter Notebook
eload/ea07.ipynb
horverno/sze-academic-python
3ac8f2c62b827822f529dc600eef91713e82d551
[ "MIT" ]
4
2019-06-24T17:01:03.000Z
2021-11-09T21:48:32.000Z
eload/ea07.ipynb
horverno/sze-academic-python
3ac8f2c62b827822f529dc600eef91713e82d551
[ "MIT" ]
null
null
null
eload/ea07.ipynb
horverno/sze-academic-python
3ac8f2c62b827822f529dc600eef91713e82d551
[ "MIT" ]
6
2018-07-24T10:08:14.000Z
2021-09-11T20:40:47.000Z
41.370044
19,544
0.685053
[ [ [ "# 7. előadás\n*Tartalom:* Függvények, pár további hasznos library (import from ... import ... as szintaktika, time, random, math, regex (regular expressions), os, sys)\n\n### Függvények\n\nTalálkozhattunk már függvényekkel más programnyelvek kapcsán. \n\nDe valójában mik is azok a függvények? A függvények:\n\n • újrahasználható kódok\n • valamilyen specifikus feladatot végeznek el\n • flexibilisek\n • egyszer definiálandók\n • nem csinálnak semmit, amíg nem hívjuk meg őket\n\nHogyan definiálunk egy függvényt?\n\n\n``` python\ndef fuggveny_neve(parameter1, parameter2, stb):\n # ide írjuk a kódot\n return visszatérési_érték_lista1, v_2, v_3 # opcionális! \n```\n\nEzt hívni a következőképp lehet:\n\n``` python\na, b, c = fuggveny_neve(parameter1, parameter2 …)\n# vagy, ha nem vagyunk kiváncsiak az összes visszatérési értékre\na, _, _ = fuggveny_neve(parameter1, parameter2 …)\n```\n\n\nKezdjük egy egyszerű függvénnyel! Írjunk egy olyan függvényt, amely a `\"Helló, <név>\"` sztringet adja vissza:\n", "_____no_output_____" ] ], [ [ "def udvozlet(nev):\n print(\"Hello,\", nev, end=\"!\")\n\nudvozlet(\"Tamás\")", "Hello, Tamás!" ] ], [ [ "Egyes függvényeknek van paraméterük/argumentumuk, másoknak azonban nincs. Egyes esetekben a paraméteres függvények bizonyulhatnak megfelelőnek, pont a paraméterek nyújtotta flexibilitás miatt, más esetekben pedig pont a paraméter nélküli függvények használata szükséges.\nEgyes függvényeknek sok visszatérési érékük van, másoknál elhagyható a `return`. \n\nÍrjunk egy olyan `adat_generalas` függvényt, amely 3 paramétert fogad: a generálandó listák darabszámát, lépésközét és opcionálisan egy eltolás értéket, amit hozzáadunk a generált adatokhoz. Amenyyiben nem adjuk meg a 3. paramétert, az eltolást, úgy az alapértelmezett érték legyen `0`. A 3 visszatérsi érték az `X` adat, valamint a 2 `Y` adat (koszinusz és színusz).", "_____no_output_____" ] ], [ [ "import math\n\ndef adat_generalas(darab, lepes, eltolas = 0):\n x = [x * lepes for x in range(0, darab)]\n y_sin = [math.sin(x * lepes) + eltolas for x in range(0, darab)]\n y_cos = [math.cos(x * lepes) + eltolas for x in range(0, darab)]\n return x, y_sin, y_cos", "_____no_output_____" ] ], [ [ "Próbáljuk ki a fenti függvényt és jelezzük ki `plot`-ként.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\nx1, y1, y2 = adat_generalas(80, 0.1)\nx2, y3, _ = adat_generalas(400, 0.02, 0.2)\n\nplt.plot(x1, y1, \"*\")\nplt.plot(x1, y2, \"*\")\nplt.plot(x2, y3, \"*\")\nplt.show()", "_____no_output_____" ] ], [ [ "A paraméterekkel rendelkező függvényeknél nagyon fontos a paraméterek sorrendje. Nem mindegy, hogy függvényhíváskor milyen sorrendben adjuk meg a paramétereket. Pl.:", "_____no_output_____" ] ], [ [ "def upload_events(events_file, location):\n # … (feltehetően a kód jön ide) …\n return\n\n# Helytelen hívás!!!\nupload_events(\"New York\", \"events.csv\")\n# Helyes hívás!!!\nupload_events(\"events.csv\", \"New York\")", "_____no_output_____" ] ], [ [ "Ha azonban nem kedveljük ezt a szabályt, akár át is hághatjuk úgy, hogy megmondjuk a függvénynek, melyik érték, melyik változóhoz tartozik!", "_____no_output_____" ] ], [ [ "# Így is helyes!!!\nupload_events(location=\"New York\", events_file=\"events.csv\")", "_____no_output_____" ] ], [ [ "Fontos még megemlíteni a függvények visszatérési értékét. A függvények egy vagy több értéket adhatnak vissza a **return** parancsszó meghívásával. A nem meghatározott visszatérési érték az ún. **None**. Ezen kívül visszatérési érték lehet *szám, karakter, sztring, lista, könyvtár, TRUE, FALSE,* vagy bármilyen más típus.", "_____no_output_____" ] ], [ [ "# Egy érték vissza adása\ndef product(x, y):\n return x*y\n\nproduct(5,6)", "_____no_output_____" ], [ "# Több érték vissza adása\ndef get_attendees(filename):\n # Ide jön a kód, amely vissza adja a „teacher”, „assistants” és „students” értékeket.\n #teacher, assistants, students = get_attendees(\"file.csv\")\n return", "_____no_output_____" ] ], [ [ "## További hasznos könyvtárak:\n\n#### Az *import* szintakszis\n\nAhhoz, hogy beépített függvényeket használjunk a kódban, szükség van azok elérésére. Ezek általában modulokban, vagy csomagokban találhatók. Ezeket az **import** kulcsszóval tudjuk beépíteni. Amikor a Python importálja pl. a *hello* nevű modult, akkor az interpreter először végig listázza a beépített modulokat, és ha nem találja ezek között, akkor elkezdi keresni a *hello.py* nevű fájlt azokban a mappákban, amelyeknek listáját a **sys.path** változótól kapja meg. Az importálás alapvető szintaktikája az **import** kulcsszóból és a beillesztendő modul nevéből áll.\n\n**import hello**", "_____no_output_____" ], [ "Mikor importálunk egy modult, elérhetővé tesszük azt a kódunkban, mint egy különálló névteret (*namespace*). Ez azt jelenti, hogy amikor meghívunk egy függvényt, pont (.) jellel kell összekapcsolnunk a modulnévvel így: [modul].[függvény]", "_____no_output_____" ] ], [ [ "import random\n\nrandom.randint(0,5) #meghívja a randint függvényt, ami egy random egész számot ad vissza", "_____no_output_____" ] ], [ [ "Nézzünk erre egy példát, amely 10 véletlenszerű egész számot ír ki!", "_____no_output_____" ] ], [ [ "import random\n\nfor i in range(10):\n print(random.randint(1, 25))", "5\n16\n20\n8\n12\n14\n15\n23\n17\n4\n" ] ], [ [ "#### A *from … import …* szintakszis\n\nÁltalában akkor használjuk, mikor hivatkozni akarunk egy konkrét függvényre a modulból, így elkerüljük a ponttal való referálást. Nézzük az előző példát ezzel a megoldással:", "_____no_output_____" ] ], [ [ "from random import randint\n\nfor i in range(10):\n print(randint(1, 25))", "7\n19\n3\n14\n18\n3\n8\n7\n16\n5\n" ] ], [ [ "#### Aliasok használata, az *import … as …* szintakszis\n\nPythonban lehetőség van a modulok és azok függvényeinek átnevezésére az **as** kulcsszó segítségével, _ilyet már régebben is használtunk_. Pl.:", "_____no_output_____" ] ], [ [ "import math as m", "_____no_output_____" ] ], [ [ "Egyes hosszú nevű modulok helyett pl. általánosan megszokott az aliasok használata. Ilyet régóta használunk pl.:", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "### A *time* és *datetime* könyvtárak:\n\nA **time** modul alapvető idővel és dátummal kapcsolatos függvényeket tartalmaz. Két különböző megjelenítési formát használ és számos függvény segít ezeknek az oda-vissza konvertálásában:\n\n - **float** másodpercek száma – ez a UNIX belső megjelenítési formája. Ebben a megjelenítési formában az egyes időpontok között eltelt idő egy lebegőpontos szám.\n - **struct_time** oblektum – ez kilenc attribútummal rendelkezik egy időpont megjelenítésére, a Gergely naptár szerinti dátumkövetést alkalmazva. Ebben a formában nincs lehetőség két időpont között eltelt idő megjelenítésére, ilyenkor oda-vissza kell konvertálnunk a **float** és **struct_time** között.\n\nA **datetime** modul tartalmaz minden szükséges objektumot és metódust, amelyek szükségesek lehetnek a Gergely naptár szerinti időszámítás helyes kezeléséhez. A **datetime** csak egyfajta időpont megjelenítési formát tartalmaz, ellenben négy olyan osztállyal rendelkezik, amelyekkel könnyedén kezelhetjük a dátumokat és időpontokat:\n\n - **datetime.time** – négy attribítummal rendelkezik, ezek az óra, perc, másodperc és a századmásodperc.\n - **datetime.date** – három attribútuma van, ezek az év, hónap és a nap.\n - **datetime.datetime** – ez kombinálni képes a **datetime.time** és **datetime.date** osztályokat.\n - **datetime.timedelta** – ez az eltelt időt mutatja meg két **date**, **time** vagy **datetime** között. Az értékei megjeleníthetők napokban, másodpercekben vagy századmásodpercekben.\n\nNézzünk néhány példát:", "_____no_output_____" ] ], [ [ "from datetime import date\nprint(date.today()) # aktuális napi dátum", "2018-11-03\n" ], [ "from datetime import datetime\nprint(datetime.now()) # pillanatnyi idő", "2018-11-03 18:00:12.616984\n" ] ], [ [ "Próbáljuk ki, hogy amennyiben két időpont között várunk 2 másodpercet, az ténylegesen pontosan mennyi eltelt időt jelent.", "_____no_output_____" ] ], [ [ "from datetime import timedelta\nfrom time import sleep\n\nt1 = datetime.now()\nprint(t1)\nsleep(2) # várjunk 2 másodpercet\nt2 = datetime.now()\nprint(t2)\n\nprint(\"Ténylegesen eltelt idő:\", timedelta(minutes=(t2-t1).total_seconds())) # valamilyen eltelt idő", "2018-11-03 18:00:12.672979\n2018-11-03 18:00:14.674316\nTénylegesen eltelt idő: 0:02:00.080220\n" ], [ "import time\ntime.clock() # másodpercek lebegőpontos ábrázolása. UNIX rendszeren a processzor időt, Windowson a függvény első hívásától eltelt időt mutatja fali óra szerint.", "_____no_output_____" ] ], [ [ "### A *random* könytár:\n\nEz a könyvtár pszeudó-random generátorokat képes létrehozni. Nézzünk néhány konkrét példát:", "_____no_output_____" ] ], [ [ "from random import random\nrandom() #random float [0, 1) között", "_____no_output_____" ], [ "from random import uniform\nuniform(2.5, 10.0) #random float [2.5, 10.0) között", "_____no_output_____" ], [ "from random import expovariate\nexpovariate(1/10) # 1 osztva egy nem nulla értékű középértékkel", "_____no_output_____" ], [ "from random import randrange\nnum1=randrange(10) # [0,9] közé eső random integer: randrange(stop)\nnum2=randrange(0, 101, 2) # [0,100] közé eső páros integer: randrange(start, stop, step)\nnum1, num2", "_____no_output_____" ], [ "from random import choice\nchoice(['win', 'lose', 'draw']) # egy lista egyik random eleme", "_____no_output_____" ], [ "from random import shuffle\ndeck = 'ace two three four'.split()\nshuffle(deck) # elemek összekeverése\ndeck", "_____no_output_____" ], [ "from random import sample\nsample([10, 20, 30, 40, 50, 60, 70], k=4) #k=n darab elemet ad vissza a halmazból", "_____no_output_____" ], [ "from random import randint\nrandint(1,10) # random integert ad [1,10] intervallumban", "_____no_output_____" ] ], [ [ "### A *math* könyvtár\n\nMatematikai függvények használatát teszi lehetővé C szabvány alapján. Néhány konkrét példa:", "_____no_output_____" ] ], [ [ "import math\nmath.ceil(5.6) # lebegőpontos számok felkerekítése egész típusú számmá", "_____no_output_____" ], [ "math.factorial(10) # fatoriális számítás", "_____no_output_____" ], [ "math.floor(5.6) # lebegőpontos számok lefele kerekítése egész típusú számmá", "_____no_output_____" ], [ "math.gcd(122, 6) # visszaadja a két szám legnyagyobb közös osztóját", "_____no_output_____" ], [ "math.exp(2) # Euler-féle szám az x hatványra emelve", "_____no_output_____" ] ], [ [ "Ennek pythonban nem sok értelme van, ahatványozás megy a `**` művelettel is. (`2 ** 3`).", "_____no_output_____" ] ], [ [ "math.pow(2, 3) # pow(x,y): x az y hatványra emelve, rövidebben 2**3", "_____no_output_____" ], [ "math.sqrt(36) # négyzetgyökvonás, rövidebben 36**0.5", "_____no_output_____" ], [ "math.cos(0.5) # cosinus függvény radiánokban kifejezve, ugyanígy működik a math.sin(x) is.", "_____no_output_____" ], [ "math.degrees(1) # radián-fok konverzió, ugyanígy math.radian(x) fok-radián átalakító.", "_____no_output_____" ] ], [ [ "Matematikai állandók:", "_____no_output_____" ] ], [ [ "print(math.pi) # Pi\nprint(math.e) # Euler-szám\nprint(math.inf) # végtelen\nprint(math.nan) # nem szám (not a number)", "3.141592653589793\n2.718281828459045\ninf\nnan\n" ] ], [ [ "### Az *OS* könyvtár\n\nAz OS modul alapvetően olyan függvényeket tartalmaz melyek az operációs rendszerrel kapcsolatos műveleteket támogatja. A modul beszúrása az **`import os`** paranccsal történik. Nézzünk néhány ilyen metódust:", "_____no_output_____" ] ], [ [ "import os\nos.system(\"dir\") # shell parancsot hajt végre, ha a parancs hatással van a kimentre, akkor ez nem jelenik meg", "_____no_output_____" ] ], [ [ "Visszatérésként csak `0`-t ad, ha sikeres és `1`-et, ha nem sikeres a művelet. De a konzolon megjelenik minden kimenet: \n\n```python\n\nDirectory of C:\\Users\\herno\\Documents\\GitHub\\sze-academic-python\\eload\n\n2018-11-03 16:42 <DIR> .\n2018-11-03 16:42 <DIR> ..\n2018-10-24 06:16 <DIR> .ipynb_checkpoints\n2018-10-24 11:02 <DIR> data\n2018-10-24 06:16 5,846 ea00.md\n2018-11-03 15:30 18,775 ea01.ipynb\n2018-07-31 17:41 21,838 ea02.ipynb\n2018-07-31 17:41 26,484 ea03.ipynb\n2018-09-10 15:23 293,223 ea04.ipynb\n2018-10-24 06:16 128,088 ea05.ipynb\n2018-07-17 11:01 34,838 ea06.ipynb\n2018-11-03 16:42 49,489 ea07.ipynb\n2018-11-03 15:30 10,384 ea08.ipynb\n2018-11-03 15:30 401,267 ea10.ipynb\n```", "_____no_output_____" ] ], [ [ "os.getcwd() # kiírja az ektuális munkakönytárat", "_____no_output_____" ], [ "os.getpid() # ez a futó folyamat ID-jét írja ki", "_____no_output_____" ] ], [ [ "A további példák nem kerülnek lefuttatásra, csak felsoroljuk őket:\n\n1) `os.chroot(path)` - a folyamat root könytárának megváltoztatása `'path'` elérésre\n\n2) `os.listdir(path)` - belépések száma az adott könytárba\n\n3) `os.mkdir(path)` - könyvtár létrehozása a `'path'` útvonalon\n\n4) `os.remove(path)` - a `'path'`-ban levő fájl törlése\n\n5) `os.removedirs(path)` - könyvtárak rekurzív törlése\n\n6) `os.rename(src, dst)` - az `'src'` átnevezése `'dst'`-re, ez lehet fájl vagy könyvtár", "_____no_output_____" ], [ "### A *sys* könyvtár\n\nA **sys** modul különféle információval szolgál az egyes Python interptreterrel kapcsolatos konstansokról, függvényekről és metódusokról. ", "_____no_output_____" ] ], [ [ "import sys\n\nsys.stderr.write('Ez egy stderr szoveg\\n') # stderr kimenetre küld hibaüzenetet\nsys.stderr.flush() # a pufferben eltárolt tartalmat flush-olja a kimenetre\nsys.stdout.write('Ez egy stdout szoveg\\n') # szöveget küld az stdout-ra", "Ez egy stderr szoveg\n" ], [ "print (\"script name is\", sys.argv[0]) # az 'argv' tartalmazza a parancssori argumentumokat,\n # ezen belül az argv[0] maga a szkript neve", "script name is c:\\users\\herno\\appdata\\local\\programs\\python\\python35\\lib\\site-packages\\ipykernel_launcher.py\n" ], [ "print (\"Az elérési útvonalon\", len(sys.path), \"elem van.\") # lekérdezzük a 'path'-ban levő elemek számát\nsys.path # kiíratjuk a 'path'-ban levő elemeket", "Az elérési útvonalon 8 elem van.\n" ] ], [ [ "``` python\nprint(sys.modules.keys()) # kiíratjuk az importált modulok neveit\n```\n```\ndict_keys(['pkgutil', '__future__', 'filecmp', 'mpl_toolkits', 'platform', 'distutils.debug', 'jedi.evaluate.context', 'ctypes._endian', 'msvcrt', 'parso.pgen2.parse', '_stat', 'jedi.evaluate', '_pickle', 'parso.python.pep8', 'jedi.evaluate.context.module', 'distutils.log', 'collections', \n......\n```", "_____no_output_____" ] ], [ [ "print (sys.platform) # lekérdezzük a platformunk típusát", "win32\n" ] ], [ [ "``` python\nprint(\"hello\")\n\nsys.exit(1) # nem lép ki egyből, hanem meghívja a 'SystemExit' kivételt. Ennek kezelésére látsd a következő példát.\n\nprint(\"there\")\n\nOutput:\nhello\nSystemExit: 1\n``` ", "_____no_output_____" ] ], [ [ "print (\"hello\")\n\ntry: # 'try'-al kezeljük a 'SystemExit' kivételt\n sys.exit(1)\nexcept SystemExit:\n pass\n\nprint (\"there\")", "hello\nthere\n" ] ], [ [ "### A reguláris kifejezések: *regex*\n\n\nSzámos helyzetben kell sztringeket feldolgoznunk. Ezek a sztringek azonban nem mindig érkeznek egyből értelmezhető formában, vagy nem követnek semmilyen mintát. Ilyenkor elég nehéz ezek feldolgozása. Erre nyújt egy elfogadható megoldást a reguláris kifejezések alkalmazása. A **reguláris kifejezés** tehát egy minta, vagy mintasorozat, amelynek segítségével könnyebben feldolgozhatjuk az egy adott halmazhoz tartozó adatokat, melyeknek egy közös mintát kellene követniük. Nézzünk egy példát!\n\nHa pl. a minta szabályom az \"aba\" szócska, akkor minden olyan sztring, amely megfelel az \"aba\" formátumnak, beletartozik a halmazba. Egy ilyen egyszerű szabály azonban csak egyszerű sztringeket képes kezelni.\n\nEgy összetettebb szabály, mint pl. a \"ab&ast;a\" már sokkal több kimeneti lehetőséget nyújt. Lényegében, sztringek végtelen halmazát képes generálni, olyanokat mint: \"aa\", \"aba\", \"abba\", stb. Itt már kicsit nehezebb ellenőrizni, hogy a generált sztring ebből a szabályból származik-e. \n\n#### Néhány alapszabályt a reguláris kifejezések létrehozásával kapcsolatban\n\n- Bármely hagyományos karakter, akár önmagában is reguláris kifejezést alkothat\n- A '.' karakter bármely egyedülálló karakternek megfelelhet. Pl. az \"x.y\"-nak megfelelhet a \"xay\", \"xby\", stb., de a \"xaby\" már NEM.\n- A szögletes zárójelek [...] olyan szabályt definiálnak, amely alapján az adott elem megfelel a zárójelben levő halmaznak. Pl. a \"x[abc]z\"-nak megfelelhet az \"xaz\", \"xbz\" és az \"xcz\" is. Vagy pl. az \"x[a-z]z\" mintában a középső karakter az ABC bármely betűje lehet. Ilyenkor az intervallumot kötőjellel '-' jelöljük meg.\n- A '^' jellel módosított szögletes zárójelek [^...] azt jelentik, hogy a reguláris kifejezésben a zárójelben felsoroltakon kívűl minden más szerepelhet. Pl. a \"1[^2-8]2\" kifejezésben a zárójel helyén csak '1' és '9' lehet, mert a \"2-8\" közötti intervallumot kizártuk.\n- Több reguláris kifejezést csoportosíthatunk zárójelek (...) segítségével. Pl. a \"(ab)c\" szabály az \"ab\" és 'c' reguláris kifejezések csoportosítása.\n- A reguláris kifejezések ismétlődhetnek. Pl. a \"x&ast;\" megismételheti a 'x'-t nullászor, vagy ennél többször, a \"x+\" megismétli az 'x'-t 1 vagy annál többször, a \"x?\" megismétli 'x'-t 0 vagy 1 alkalommal. Konkrét példa: a \"1(abc)&ast;2\" kifejezésnek megfelelhet a \"12\", \"1abc2\", és akár a \"1abcabcabc2\" is.\n- Ha valamilyen szabály a sor elején kezdődik, akkor azt \"^\" mintával jelöljük, ha a sor végén található, akkor pedig a \"^&dollar;\" mintával.\n\n#### A reguláris kifejezések alkalmazása Pythonban\n\nA reguláris kifejezések alkalmazásához be kell szúrnunk a **re** könyvtárat. Nézzünk ezzel kapcsolatban néhány konkrét feladatot:", "_____no_output_____" ] ], [ [ "import re\nszov1 = \"2019 november 12\"\nprint(\"Minden szám:\", re.findall(\"\\d+\", szov1))\nprint(\"Minden egyéb:\", re.findall(\"[^\\d+]\", szov1))\nprint(\"Angol a-z A-Z:\", re.findall(\"[a-zA-Z]+\", szov1))", "Minden szám: ['2019', '12']\nMinden egyéb: [' ', 'n', 'o', 'v', 'e', 'm', 'b', 'e', 'r', ' ']\nAngol a-z A-Z: ['november']\n" ], [ "szov2 = \"<body>Ez egy példa<br></body>\"\nprint(re.findall(\"<.*?>\", szov2))", "['<body>', '<br>', '</body>']\n" ], [ "szov3 = \"sör sört sár sír sátor Pártol Piros Sanyi Peti Pite Pete \"\nprint(\"s.r :\", re.findall(\"s.r\", szov3))\nprint(\"s.r. :\", re.findall(\"s.r.\", szov3))\nprint(\"s[áí]r :\", re.findall(\"s[áí]r\", szov3))\nprint(\"P.t. :\", re.findall(\"P.t.\", szov3))\nprint(\"P.*t. :\", re.findall(\"P.*t.\", szov3))\nprint(\"P.{0,3}t.:\", re.findall(\"P.{0,3}t.\", szov3))", "s.r : ['sör', 'sör', 'sár', 'sír']\ns.r. : ['sör ', 'sört', 'sár ', 'sír ']\ns[áí]r : ['sár', 'sír']\nP.t. : ['Peti', 'Pite', 'Pete']\nP.*t. : ['Pártol Piros Sanyi Peti Pite Pete']\nP.{0,3}t.: ['Párto', 'Peti', 'Pite', 'Pete']\n" ] ], [ [ "Nézzünk egy összetettebb példát:", "_____no_output_____" ] ], [ [ "fajl_lista = [ \"valami_S015_y001.png\",\n \"valami_S015_y001.npy\",\n \"valami_S014_y001.png\",\n \"valami_S014_y001.npy\",\n \"valami_S013_y001.png\",\n \"valami_S013_y001.npy\",\n \"_S999999_y999.npy\"]\n\nr1 = re.compile(r\"_S\\d+_y\\d+\\.png\")\nr2 = re.compile(r\"_S\\d+_y\\d+\\..*\")\nf1 = list(filter(r1.search, fajl_lista))\nf2 = list(filter(r2.search, fajl_lista))\nprint(\"_S\\d+_y\\d+\\.png \\n---------------\")\nfor f in f1: print(f)\nprint(\"\"); print(\"_S\\d+_y\\d+\\..* \\n---------------\")\nfor f in f2: print(f)\n", "_S\\d+_y\\d+\\.png \n---------------\nvalami_S015_y001.png\nvalami_S014_y001.png\nvalami_S013_y001.png\n\n_S\\d+_y\\d+\\..* \n---------------\nvalami_S015_y001.png\nvalami_S015_y001.npy\nvalami_S014_y001.png\nvalami_S014_y001.npy\nvalami_S013_y001.png\nvalami_S013_y001.npy\n_S999999_y999.npy\n" ] ], [ [ "További információt a reguláris kifejezésekkel kapcsolatban [ITT](https://www.regular-expressions.info/index.html) találnak.", "_____no_output_____" ], [ "## _Used sources_ / Felhasznált források:\n - [Shannon Turner: Python lessons repository](https://github.com/shannonturner/python-lessons) MIT license (c) Shannon Turner 2013-2014,\n - [Siki Zoltán: Python mogyoróhéjban](http://www.agt.bme.hu/gis/python/python_oktato.pdf) GNU FDL license (c) Siki Zoltán,\n - [BME AUT](https://github.com/bmeaut) MIT License Copyright (c) BME AUT 2016-2018,\n - [Python Software Foundation documents](https://docs.python.org/3/) Copyright (c), Python Software Foundation, 2001-2018,\n - [Regular expressions](https://www.regular-expressions.info/index.html) Copyright (c) 2003-2018 Jan Goyvaerts. All rights reserved.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cbdd90313d42855b43842a720c280b54d702f3e8
574,419
ipynb
Jupyter Notebook
notebooks/phase_diagram.ipynb
sanksha76/neural-tangents
dff0a7e079c5bd283ec7cbe086107452c2934ca1
[ "ECL-2.0", "Apache-2.0" ]
1
2020-04-30T14:18:57.000Z
2020-04-30T14:18:57.000Z
notebooks/phase_diagram.ipynb
xyhcelia/neural-tangents
dff0a7e079c5bd283ec7cbe086107452c2934ca1
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
notebooks/phase_diagram.ipynb
xyhcelia/neural-tangents
dff0a7e079c5bd283ec7cbe086107452c2934ca1
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
1,071.677239
165,374
0.732565
[ [ [ "<a href=\"https://colab.research.google.com/github/google/neural-tangents/blob/master/notebooks/phase_diagram.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "Copyright 2020 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.", "_____no_output_____" ], [ "### Imports & Utils", "_____no_output_____" ] ], [ [ "!pip install -q git+https://www.github.com/google/neural-tangents", "/bin/sh: pip: command not found\n" ], [ "import jax.numpy as np\n\nfrom jax.experimental import optimizers\nfrom jax.api import grad, jit, vmap\nfrom jax import lax\nfrom jax.config import config\nconfig.update('jax_enable_x64', True)\n\nfrom functools import partial\n\n\n\n\nimport neural_tangents as nt\nfrom neural_tangents import stax\n\n_Kernel = nt.utils.kernel.Kernel\n\ndef Kernel(K):\n \"\"\"Create an input Kernel object out of an np.ndarray.\"\"\"\n return _Kernel(cov1=np.diag(K), nngp=K, cov2=None, \n ntk=None, is_gaussian=True, is_reversed=False,\n diagonal_batch=True, diagonal_spatial=False,\n shape1=(K.shape[0], 1024), shape2=(K.shape[1], 1024),\n x1_is_x2=True, is_input=True, batch_axis=0, channel_axis=1) \n \ndef fixed_point(f, initial_value, threshold):\n \"\"\"Find fixed-points of a function f:R->R using Newton's method.\"\"\"\n g = lambda x: f(x) - x\n dg = grad(g)\n\n def cond_fn(x):\n x, last_x = x\n return np.abs(x - last_x) > threshold\n\n def body_fn(x):\n x, _ = x\n return x - g(x) / dg(x), x\n \n return lax.while_loop(cond_fn, body_fn, (initial_value, 0.0))[0]", "_____no_output_____" ], [ "from IPython.display import set_matplotlib_formats\nset_matplotlib_formats('pdf', 'svg')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(style='white')\n\ndef format_plot(x='', y='', grid=True): \n ax = plt.gca()\n \n plt.grid(grid)\n plt.xlabel(x, fontsize=20)\n plt.ylabel(y, fontsize=20)\n \ndef finalize_plot(shape=(1, 1)):\n plt.gcf().set_size_inches(\n shape[0] * 1.5 * plt.gcf().get_size_inches()[1], \n shape[1] * 1.5 * plt.gcf().get_size_inches()[1])\n plt.tight_layout()", "_____no_output_____" ] ], [ [ "# Phase Diagram", "_____no_output_____" ], [ "We will reproduce the phase diagram described in [Poole et al.](https://papers.nips.cc/paper/6322-exponential-expressivity-in-deep-neural-networks-through-transient-chaos) and [Schoenholz et al.](https://arxiv.org/abs/1611.01232) using Neural Tangents. In these and subsequent papers, it was found that deep neural networks can exhibit a phase transition as a function of the variance of their weights ($\\sigma_w^2$) and biases ($\\sigma_b^2$). For networks with $\\tanh$ activation functions, this phase transition is between an \"ordered\" phase and a \"chaotic\" phase. In the ordered phase, pairs of inputs collapse to a single point as they propagate through the network. By contrast, in the chaotic phase, nearby inputs become increasingly dissimilar in later layers of the network. This phase diagram is shown below. A number of properties of neural networks - such as trainability, mode-collapse, and maximum learing rate - have now been related to this phase diagram over many papers (recently e.g. [Yang et al.](https://arxiv.org/abs/1902.08129), [Jacot et al.](https://arxiv.org/abs/1907.05715), [Hayou et al.](https://arxiv.org/abs/1905.13654), and [Xiao et al.](https://arxiv.org/abs/1912.13053)).\n\n\\\n\n![Phase Diagram](https://raw.githubusercontent.com/google/neural-tangents/master/notebooks/figures/pennington_phase_diagram.svg?sanitize=true)\n\n> Phase diagram for $\\tanh$ neural networks (appeared in [Pennington et al.](https://arxiv.org/abs/1802.09979)).\n\n\\\n\nConsider two inputs to a neural network, $x_1$ and $x_2$, normalized such that $\\|x_1\\| = \\|x_2\\| = q^0$. We can compute the cosine-angle between the inputs, $c^0 = \\cos\\theta_{12} = \\frac{x_1 \\cdot x_2}{q^0}$. Additionally, we can keep track of the norm and cosine angle of the resulting pre-activations ($q^l$ and $c^l$ respectively) as signal passes through layers of the neural network. In the wide-network limit there are deterministic functions, called the $\\mathcal Q$-map and the $\\mathcal{C}$-map, such that $q^{l+1} = \\mathcal Q(q^l)$ and $c^{l+1} = \\mathcal C(q^l, c^l)$. \n\n\\\n\nIn fully-connected networks with $\\tanh$-like activation functions, both the $\\mathcal Q$-map and $\\mathcal C$-map have unique stable-fixed-points, $q^*$ and $c^*$, such that $q^* = \\mathcal Q(q^*)$ and $c^* = \\mathcal C(q^*, c^*)$. To simplify the discussion, we typically choose to normalize our inputs so that $q^0 = q^*$ and we can restrict our study to the $\\mathcal C$-map. The $\\mathcal C$-map always has a fixed point at $c^* = 1$ since two identical inputs will remain identical as they pass through the network. However, this fixed point is not always stable and two points that start out very close together will often separate. Indeed, the ordered and chaotic phases are characterized by the stability of the $c^* = 1$ fixed point. In the ordered phase $c^* = 1$ is stable and pairs of inputs converge to one another as they pass through the network. In the chaotic phase the $c^* = 1$ point is unstable and a new, stable, fixed point with $c^* < 1$ emerges. The phase boundary is defined as the point where $c^* = 1$ is marginally stable.\n\n\\\n\nTo understand the stability of a fixed point, $c^*$, we will use the standard technique in Dynamical Systems theory and expand the $\\mathcal C$-map in $\\epsilon^l = c^l - c^*$ which implies that $\\epsilon^{l+1} = \\chi(c^*)\\epsilon^l$ where $\\chi = \\frac{\\partial\\mathcal C}{\\partial C}$. This implies that sufficiently close to a fixed point of the dynamics, $\\epsilon^l = \\chi(c^*)^l$. If $\\chi(c^*) < 1$ then the fixed point is stable and points move towards the fixed point exponentially quickly. If $\\chi(c^*) > 1$ then points move away from the fixed point exponentially quickly. This implies that the phase boundary, being defined by the marginal stability of $c^* = 1$, will be where $\\chi_1 = \\chi(1) = 1$. \n\n\\\n\nTo reproduce these results in Neural Tangents, we notice first that the $\\mathcal{C}$-map described above is intimately related to the NNGP kernel, $K^l$, of [Lee et al.](https://arxiv.org/abs/1711.00165), [Matthews et al.](https://arxiv.org/abs/1804.11271), and [Novak et al.](https://arxiv.org/abs/1810.05148). The core of Neural Tangents is a map $\\mathcal T$ for a wide range of architectures such that $K^{l + 1} = \\mathcal T(K^l)$. Since $C^l$ can be written in terms of the NNGP kernel as $C^l = K^l_{12} / q^*$ this implies that Neural Tangents provides a way of computing the $\\mathcal{C}$-map for a wide range of network architectures.\n\n\\\n\nTo produce the phase diagam above, we must compute $q^*$ and $c^*$ as well as $\\chi_1$. We will use a fully-connected network with $\\text{Erf}$ activation functions since they admit an analytic kernel function and are very similar to $\\tanh$ networks. We will first define the $\\mathcal Q$-map by noting that the $\\mathcal Q$-map will be identical to $\\mathcal T$ if the covariance matrix has only a single entry. We will use Newton's method to find $q^*$ given the $\\mathcal Q$-map. Next we will use the relationship above to define the $\\mathcal C$-map in terms of $\\mathcal T$. We will again use Newton's method to find the stable $c^*$ fixed point. We can define $\\chi$ by using JAX's automatic differentiation to compute the derivative of the $\\mathcal C$-map. This can be written relatively concisely below.\n\n\\\n\nNote: this particular phase diagram holds for a wide range of neural networks but, emphatically, not for ReLUs. The ReLU phase diagram is somewhat different and could be investigated using Neural Tangents. However, we will save it for a followup notebook.", "_____no_output_____" ] ], [ [ "def c_map(W_var, b_var):\n W_std = np.sqrt(W_var)\n b_std = np.sqrt(b_var)\n\n # Create a single layer of a network as an affine transformation composed\n # with an Erf nonlinearity.\n kernel_fn = stax.serial(stax.Dense(1024, W_std, b_std), stax.Erf())[2]\n\n def q_map_fn(q):\n return kernel_fn(Kernel(np.array([[q]]))).nngp[0, 0]\n \n qstar = fixed_point(q_map_fn, 1.0, 1e-7)\n\n def c_map_fn(c):\n K = np.array([[qstar, qstar * c], [qstar * c, qstar]])\n K_out = kernel_fn(Kernel(K)).nngp\n return K_out[1, 0] / qstar\n\n return c_map_fn\n\nc_star = lambda W_var, b_var: fixed_point(c_map(W_var, b_var), 0.1, 1e-7)\nchi = lambda c, W_var, b_var: grad(c_map(W_var, b_var))(c)\nchi_1 = partial(chi, 1.)", "_____no_output_____" ] ], [ [ "To generate the phase diagram above, we would like to compute the fixed-point correlation not only at a single value of $(\\sigma_w^2,\\sigma_b^2)$ but on a whole mesh. We can use JAX's `vmap` functionality to do this. Here we define vectorized versions of the above functions.", "_____no_output_____" ] ], [ [ "def vectorize_over_sw_sb(fn):\n # Vectorize over the weight variance.\n fn = vmap(fn, (0, None))\n # Vectorize over the bias variance.\n fn = vmap(fn, (None, 0))\n\n return fn\n\nc_star = jit(vectorize_over_sw_sb(c_star))\nchi_1 = jit(vectorize_over_sw_sb(chi_1))", "_____no_output_____" ] ], [ [ "We can use these functions to plot $c^*$ as a function of the weight and bias variance. As expected, we see a region where $c^* = 1$ and a region where $c^* < 1$.", "_____no_output_____" ] ], [ [ "W_var = np.arange(0, 3, 0.01)\nb_var = np.arange(0., 0.25, 0.001)\n\nplt.contourf(W_var, b_var, c_star(W_var, b_var))\nplt.colorbar()\nplt.title('$C^*$ as a function of weight and bias variance', fontsize=14)\n\nformat_plot('$\\\\sigma_w^2$', '$\\\\sigma_b^2$')\nfinalize_plot((1.15, 1))", "_____no_output_____" ] ], [ [ "We can, of course, threshold on $c^*$ to get a cleaner definition of the phase diagram.", "_____no_output_____" ] ], [ [ "plt.contourf(W_var, b_var, c_star(W_var, b_var) > 0.999, \n levels=3, \n colors=[[1.0, 0.89, 0.811], [0.85, 0.85, 1]])\nplt.title('Phase diagram in terms of weight and bias variance', fontsize=14)\n\nformat_plot('$\\\\sigma_w^2$', '$\\\\sigma_b^2$')\nfinalize_plot((1, 1))", "_____no_output_____" ] ], [ [ "As described above, the boundary between the two phases should be defined by $\\chi_1(\\sigma_w^2, \\sigma_b^2) = 1$ where $\\chi_1$ is given by the derivative of the $\\mathcal C$-map.", "_____no_output_____" ] ], [ [ "plt.contourf(W_var, b_var, chi_1(W_var, b_var))\nplt.colorbar()\nplt.title(r'$\\chi^1$ as a function of weight and bias variance', fontsize=14)\n\nformat_plot('$\\\\sigma_w^2$', '$\\\\sigma_b^2$')\nfinalize_plot((1.15, 1))", "_____no_output_____" ] ], [ [ "We can see that the boundary where $\\chi_1$ crosses 1 corresponds to the phase boundary we observe above.", "_____no_output_____" ] ], [ [ "plt.contourf(W_var, b_var, c_star(W_var, b_var) > 0.999, \n levels=3, \n colors=[[1.0, 0.89, 0.811], [0.85, 0.85, 1]])\nplt.contourf(W_var, b_var, \n np.abs(chi_1(W_var, b_var) - 1) < 0.003, \n levels=[0.5, 1], \n colors=[[0, 0, 0]])\n\nplt.title('Phase diagram in terms of weight and bias variance', fontsize=14)\n\nformat_plot('$\\\\sigma_w^2$', '$\\\\sigma_b^2$')\nfinalize_plot((1, 1))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbddb5a63d75e0bf344be7997aae236eb959de7e
31,927
ipynb
Jupyter Notebook
Labs/Lab-03_before.ipynb
aksyuk/MTML
b411eb67fac2a0dd62093b5598be662ae455bd03
[ "MIT" ]
null
null
null
Labs/Lab-03_before.ipynb
aksyuk/MTML
b411eb67fac2a0dd62093b5598be662ae455bd03
[ "MIT" ]
null
null
null
Labs/Lab-03_before.ipynb
aksyuk/MTML
b411eb67fac2a0dd62093b5598be662ae455bd03
[ "MIT" ]
null
null
null
28.430098
355
0.558023
[ [ [ "`Дисциплина: Методы и технологии машинного обучения` \n`Уровень подготовки: бакалавриат` \n`Направление подготовки: 01.03.02 Прикладная математика и информатика` \n`Семестр: осень 2021/2022` \n\n\n\n\n# Лабораторная работа №3: Линейные модели. Кросс-валидация. \n\nВ практических примерах ниже показано: \n\n* как пользоваться инструментами предварительного анализа для поиска линейных взаимосвязей \n* как строить и интерпретировать линейные модели с логарифмами \n* как оценивать точность моделей с перекрёстной проверкой (LOOCV, проверка по блокам)\n\n*Модели*: множественная линейная регрессия \n*Данные*: `insurance` (источник: <https://www.kaggle.com/mirichoi0218/insurance/version/1>)", "_____no_output_____" ] ], [ [ "# настройка ширины страницы блокнота .......................................\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:80% !important; }</style>\"))", "_____no_output_____" ] ], [ [ "# Указания к выполнению\n\n\n## Загружаем пакеты", "_____no_output_____" ] ], [ [ "# загрузка пакетов: инструменты --------------------------------------------\n# работа с массивами\nimport numpy as np\n# фреймы данных\nimport pandas as pd\n# графики\nimport matplotlib as mpl\n# стили и шаблоны графиков на основе matplotlib\nimport seaborn as sns\n# перекодировка категориальных переменных\nfrom sklearn.preprocessing import LabelEncoder\n# тест Шапиро-Уилка на нормальность распределения\nfrom scipy.stats import shapiro\n# для таймера\nimport time\n\n# загрузка пакетов: модели -------------------------------------------------\n# линейные модели\nimport sklearn.linear_model as skl_lm\n# расчёт MSE\nfrom sklearn.metrics import mean_squared_error\n# кросс-валидация\nfrom sklearn.model_selection import train_test_split, LeaveOneOut \nfrom sklearn.model_selection import KFold, cross_val_score\n# полиномиальные модели\nfrom sklearn.preprocessing import PolynomialFeatures", "_____no_output_____" ], [ "# константы\n# ядро для генератора случайных чисел\nmy_seed = 9212\n# создаём псевдоним для короткого обращения к графикам\nplt = mpl.pyplot\n# настройка стиля и отображения графиков\n# примеры стилей и шаблонов графиков: \n# http://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html\nmpl.style.use('seaborn-whitegrid')\nsns.set_palette(\"Set2\")\n# раскомментируйте следующую строку, чтобы посмотреть палитру\n# sns.color_palette(\"Set2\")", "_____no_output_____" ] ], [ [ "## Загружаем данные\n\nНабор данных `insurance` в формате .csv доступен для загрузки по адресу: <https://raw.githubusercontent.com/aksyuk/MTML/main/Labs/data/insurance.csv>. Справочник к данным: <https://github.com/aksyuk/MTML/blob/main/Labs/data/CodeBook_insurance.md>. \nЗагружаем данные во фрейм и кодируем категориальные переменные. ", "_____no_output_____" ] ], [ [ "# читаем таблицу из файла .csv во фрейм\nfileURL = 'https://raw.githubusercontent.com/aksyuk/MTML/main/Labs/data/insurance.csv'\nDF_raw = \n\n# выясняем размерность фрейма\nprint('Число строк и столбцов в наборе данных:\\n', DF_raw.shape)", "_____no_output_____" ], [ "# первые 5 строк фрейма\n", "_____no_output_____" ], [ "# типы столбцов фрейма\n", "_____no_output_____" ] ], [ [ "Проверим, нет ли в таблице пропусков. ", "_____no_output_____" ] ], [ [ "# считаем пропуски в каждом столбце\n", "_____no_output_____" ] ], [ [ "Пропусков не обнаружено. ", "_____no_output_____" ] ], [ [ "# кодируем категориальные переменные\n# пол\nsex_dict = \nDF_raw['sexFemale'] = \n\n# курильщик\nyn_dict = \nDF_raw['smokerYes'] = \n\n# находим уникальные регионы\n", "_____no_output_____" ], [ "# добавляем фиктивные на регион: число фиктивных = число уникальных - 1\ndf_dummy = \ndf_dummy.head(5)", "_____no_output_____" ], [ "# объединяем с исходным фреймом\nDF_all = \n\n# сколько теперь столбцов\nDF_all.shape", "_____no_output_____" ], [ "# смотрим первые 8 столбцов\nDF_all.iloc[:, :8].head(5)", "_____no_output_____" ], [ "# смотрим последние 5 столбцов\nDF_all.iloc[:, 8:].head(5)", "_____no_output_____" ], [ "# оставляем в наборе данных только то, что нужно \n# (плюс метки регионов для графиков)\nDF_all = DF_all[['charges', 'age', 'sexFemale', 'bmi', 'children', 'smokerYes', \n 'region_northwest', 'region_southeast',\n 'region_southwest', 'region']]\n\n# перекодируем регион в числовой фактор, \n# чтобы использовать на графиках\nclass_le = \nDF_all['region'] = \n\nDF_all.columns", "_____no_output_____" ], [ "DF_all.dtypes", "_____no_output_____" ], [ "# удаляем фрейм-исходник\n", "_____no_output_____" ] ], [ [ "Прежде чем переходить к анализу данных, разделим фрейм на две части: одна (90%) станет основой для обучения моделей, на вторую (10%) мы сделаем прогноз по лучшей модели. ", "_____no_output_____" ] ], [ [ "# данные для построения моделей\nDF = \n\n# данные для прогнозов\nDF_predict = ", "_____no_output_____" ] ], [ [ "## Предварительный анализ данных \n\n### Считаем описательные статистики \n\nРассчитаем описательные статистики для непрерывных переменных. Из таблицы ниже можно видеть, что переменная `charges`, которая является зависимой переменной модели, сильно отличается по масштабу от всех остальных. Также заметим, что из всех объясняющих только переменная `children` принимает нулевые значения. Остальные показатели положительны. ", "_____no_output_____" ] ], [ [ "# описательные статистики для непрерывных переменных\n", "_____no_output_____" ] ], [ [ "### Строим графики \n\nПосмотрим на графики взаимного разброса непрерывных переменных. ", "_____no_output_____" ] ], [ [ "# матричный график разброса с линиями регрессии\n\nplt.show()", "_____no_output_____" ] ], [ [ "Судя по этим графикам: \n* распределение зависимой `charges` не является нормальным; \n* из всех объясняющих нормально распределена только `bmi`; \n* имеется три уровня стоимости страховки, что заметно на графиках разброса `charges` от `age`; \n* облако наблюдений на графике `charges` от `bmi` делится на две неравные части; \n* объясняющая `children` дискретна, что очевидно из её смысла: количество детей; \n* разброс значений `charges` у застрахованных с количеством детей 5 (максимум из таблицы выше) намного меньше, чем у остальных застрахованных. \n\nНаблюдаемые закономерности могут объясняться влиянием одной или нескольких из фиктивных объясняющих переменных. Построим график, раскрасив точки цветом в зависимости от пола застрахованного лица. ", "_____no_output_____" ] ], [ [ "# матричный график разброса с цветом по полу\n\n\nplt.show()", "_____no_output_____" ] ], [ [ "Теперь покажем цветом на графиках отношение застрахованых лиц к курению.", "_____no_output_____" ] ], [ [ "# матричный график разброса с цветом по smokerYes\n\n\nplt.show()", "_____no_output_____" ] ], [ [ "Покажем с помощью цвета на графиках регионы.", "_____no_output_____" ] ], [ [ "# матричный график разброса с цветом по region\n\n\nplt.show()", "_____no_output_____" ] ], [ [ "Нарисуем график отдельно по `region_southeast`. ", "_____no_output_____" ] ], [ [ "# матричный график разброса с цветом по региону southeast\n\n\nplt.show()", "_____no_output_____" ] ], [ [ "Посмотрим на корреляционные матрицы непрерывных переменных фрейма. ", "_____no_output_____" ] ], [ [ "# корреляционная матрица по всем наблюдениям\ncorr_mat = \ncorr_mat.style.background_gradient(cmap='coolwarm').set_precision(2)", "_____no_output_____" ] ], [ [ "Посчитаем корреляционные матрицы для курящих и некурящих застрахованных лиц. ", "_____no_output_____" ] ], [ [ "# корреляционная матрица по классу курильщиков\ncorr_mat =\n\ncorr_mat.style.background_gradient(cmap='coolwarm').set_precision(2)", "_____no_output_____" ], [ "# корреляционная матрица по классу не курильщиков\ncorr_mat = \n\ncorr_mat.style.background_gradient(cmap='coolwarm').set_precision(2)", "_____no_output_____" ] ], [ [ "\n\n### Логарифмируем зависимую переменную \n\nВажным допущением линейной регрессии является нормальность зависимой переменной. Чтобы добиться нормального распределения, используют логарифмирование либо преобразование Бокса-Кокса. В этой лабораторной остановимся на логарифмировании. ", "_____no_output_____" ] ], [ [ "# логарифмируем зависимую переменную\nDF['log_charges'] = \n\n# описательные статистики для непрерывных показателей\nDF[['charges', 'log_charges', 'age', 'bmi', 'children']].describe()", "_____no_output_____" ] ], [ [ "Проведём формальные тесты на нормальность. ", "_____no_output_____" ] ], [ [ "# тестируем на нормальность\nfor col in ['charges', 'log_charges']:\n stat, p = shapiro(DF[col])\n print(col, 'Statistics=%.2f, p=%.4f' % (stat, p))\n # интерпретация\n alpha = 0.05\n if p > alpha:\n print('Распределение нормально (H0 не отклоняется)\\n')\n else:\n print('Распределение не нормально (H0 отклоняется)\\n')", "_____no_output_____" ] ], [ [ "Логарифмирование меняет взаимосвязи между переменными. ", "_____no_output_____" ] ], [ [ "# матричный график разброса с цветом по smokerYes\nsns.pairplot(DF[['log_charges', 'age', 'bmi', 'children', \n 'smokerYes']], hue='smokerYes')\nplt.show()", "_____no_output_____" ], [ "# корреляционная матрица по классу не курильщиков\ncorr_mat = DF.loc[DF['smokerYes'] == 0][['log_charges', 'age', \n 'bmi', 'children']].corr()\ncorr_mat.style.background_gradient(cmap='coolwarm').set_precision(2)", "_____no_output_____" ], [ "# корреляционная матрица по классу курильщиков\ncorr_mat = DF.loc[DF['smokerYes'] == 1][['log_charges', 'age', \n 'bmi', 'children']].corr()\ncorr_mat.style.background_gradient(cmap='coolwarm').set_precision(2)", "_____no_output_____" ] ], [ [ "## Строим модели регрессии\n\n### Спецификация моделей \nПо итогам предварительного анализа данных можно предложить следующие спецификации линейных регрессионных моделей: \n\n1. `fit_lm_1`: $\\hat{charges} = \\hat{\\beta_0} + \\hat{\\beta_1} \\cdot smokerYes + \\hat{\\beta_2} \\cdot age + \\hat{\\beta_3} \\cdot bmi$\n1. `fit_lm_2`: $\\hat{charges} = \\hat{\\beta_0} + \\hat{\\beta_1} \\cdot smokerYes + \\hat{\\beta_2} \\cdot age \\cdot smokerYes + \\hat{\\beta_3} \\cdot bmi$\n1. `fit_lm_3`: $\\hat{charges} = \\hat{\\beta_0} + \\hat{\\beta_1} \\cdot smokerYes + \\hat{\\beta_2} \\cdot bmi \\cdot smokerYes + \\hat{\\beta_3} \\cdot age$\n1. `fit_lm_4`: $\\hat{charges} = \\hat{\\beta_0} + \\hat{\\beta_1} \\cdot smokerYes + \\hat{\\beta_2} \\cdot bmi \\cdot smokerYes + \\hat{\\beta_3} \\cdot age \\cdot smokerYes$\n\n1. `fit_lm_1_log`: то же, что `fit_lm_1`, но для зависимой $\\hat{log\\_charges}$ \n1. `fit_lm_2_log`: то же, что `fit_lm_2`, но для зависимой $\\hat{log\\_charges}$\n1. `fit_lm_3_log`: то же, что `fit_lm_3`, но для зависимой $\\hat{log\\_charges}$\n1. `fit_lm_4_log`: то же, что `fit_lm_4`, но для зависимой $\\hat{log\\_charges}$\n\nКроме того, добавим в сравнение модели зависимости `charges` и `log_sharges` от всех объясняющих переменных: `fit_lm_0` и `fit_lm_0_log` соответственно. \n\n\n### Обучение и интерпретация \n\nСоздаём матрицы значений объясняющих переменных ( $X$ ) и вектора значений зависимой ( $y$ ) для всех моделей. ", "_____no_output_____" ] ], [ [ "# данные для моделей 1, 5\ndf1 = DF[['charges', 'smokerYes', 'age', 'bmi']]\n\n# данные для моделей 2, 6\ndf2 = DF[['charges', 'smokerYes', 'age', 'bmi']]\ndf2.loc[:, 'age_smokerYes'] = \ndf2 = \n\n# данные для моделей 3, 7\ndf3 = DF[['charges', 'smokerYes', 'age', 'bmi']]\ndf3.loc[:, 'bmi_smokerYes'] = \ndf3 = \n\n# данные для моделей 4, 8\ndf4 = DF[['charges', 'smokerYes', 'age', 'bmi']]\ndf4.loc[:, 'age_smokerYes'] = \ndf4.loc[:, 'bmi_smokerYes'] = \ndf4 = \n\n# данные для моделей 9, 10\ndf0 = ", "_____no_output_____" ] ], [ [ "Построим модели от всех объясняющих переменных на всех наблюдениях `DF`, чтобы проинтерпретировать параметры. В модели для зависимой переменной `charges` интерпретация стандартная: \n\n1. Константа – базовый уровень зависимой переменной, когда все объясняющие равны 0. \n2. Коэффициент при объясняющей переменной $X$ показывает, на сколько своих единиц измерения изменится $Y$, если $X$ увеличится на одну свою единицу измерения. ", "_____no_output_____" ] ], [ [ "lm = skl_lm.LinearRegression()\n\n# модель со всеми объясняющими, y\nX = \ny = \nfit_lm_0 = \nprint('модель fit_lm_0:\\n', \n 'константа ', np.around(fit_lm_0.intercept_, 3),\n '\\n объясняющие ', list(X.columns.values),\n '\\n коэффициенты ', np.around(fit_lm_0.coef_, 3))", "_____no_output_____" ], [ "# оценим MSE на обучающей\n# прогнозы\ny_pred = \nMSE = \nMSE", "_____no_output_____" ] ], [ [ "С интрпретацией модели на логарифме $Y$ дела обстоят сложнее: \n1. Константу сначала надо экспоненциировать, далее интерпретировать как для обычной модели регрессии. \n1. Коэффициент при $X$ нужно экспоненциировать, затем вычесть из получившегося числа 1, затем умножить на 100. Результат показывает, на сколько процентов изменится (увеличится, если коэффициент положительный, и уменьшится, если отрицательный) зависимая переменная, если $X$ увеличится на одну свою единицу измерения. ", "_____no_output_____" ] ], [ [ "# модель со всеми объясняющими, y_log\nX = df0.drop(['charges'], axis=1)\ny = np.log(df0.charges).values.reshape(-1, 1)\nfit_lm_0_log = lm.fit(X, y)\nprint('модель fit_lm_0_log:\\n', \n 'константа ', np.around(fit_lm_0_log.intercept_, 3),\n '\\n объясняющие ', list(X.columns.values),\n '\\n коэффициенты ', np.around(fit_lm_0_log.coef_, 3))", "_____no_output_____" ], [ "# пересчёт коэффициентов для их интерпретации\n", "_____no_output_____" ], [ "# оценим MSE на обучающей\n# прогнозы\ny_pred = fit_lm_0_log.predict(X)\nMSE_log = sum((np.exp(y) - np.exp(y_pred).reshape(-1, 1))**2) / len(y)\nMSE_log", "_____no_output_____" ], [ "print('MSE_train модели для charges меньше MSE_train',\n 'модели для log(charges) в ', np.around(MSE_log / MSE, 1), 'раз')", "_____no_output_____" ] ], [ [ "### Оценка точности\n\n#### LOOCV \n\nСделаем перекрёстную проверку точности моделей по одному наблюдению. ", "_____no_output_____" ] ], [ [ "# LeaveOneOut CV\nloo = \n\n# модели для y\nscores = list()\n# таймер\ntic = \nfor df in [df0, df1, df2, df3, df4] :\n \n X = \n y = \n score = \n \n scores.append(score)\n\n# таймер\ntoc = \nprint(f\"Расчёты методом LOOCV заняли {} секунд\")", "_____no_output_____" ], [ "# модели для y_log\nscores_log = list()\n# таймер\ntic = time.perf_counter()\nfor df in [df0, df1, df2, df3, df4] :\n loo.get_n_splits(df)\n X = df.drop(['charges'], axis=1)\n y = np.log(df.charges)\n score = cross_val_score(lm, X, y, cv=loo, n_jobs=1,\n scoring='neg_mean_squared_error').mean()\n scores_log.append(score)\n\n# таймер\ntoc = time.perf_counter()\nprint(f\"Расчёты методом LOOCV заняли {toc - tic:0.2f} секунд\")", "_____no_output_____" ] ], [ [ "Сравним ошибки для моделей на исходных значениях `charges` с ошибками моделей на логарифме. ", "_____no_output_____" ] ], [ [ "[np.around(-x, 2) for x in scores]", "_____no_output_____" ], [ "[np.around(-x, 3) for x in scores_log]", "_____no_output_____" ] ], [ [ "Определим самые точные модели отдельно на `charges` и на `log_charges`. ", "_____no_output_____" ] ], [ [ "# самая точная на charges\nfits = ['fit_lm_0', 'fit_lm_1', 'fit_lm_2', 'fit_lm_3', 'fit_lm_4']\nprint('Наименьшая ошибка на тестовой с LOOCV у модели',\n fits[scores.index(max(scores))], \n ':\\nMSE_loocv =', np.around(-max(scores), 0))", "_____no_output_____" ], [ "# самая точная на log(charges)\nfits = ['fit_lm_0_log', 'fit_lm_1_log', 'fit_lm_2_log', \n 'fit_lm_3_log', 'fit_lm_4_log']\nprint('Наименьшая ошибка на тестовой с LOOCV у модели',\n fits[scores_log.index(max(scores_log))], \n ':\\nMSE_loocv =', np.around(-max(scores_log), 3))", "_____no_output_____" ] ], [ [ "#### Перекрёстная проверка по блокам \n\nТеоретически этот метод менее затратен, чем LOOCV. Проверим на наших моделях. ", "_____no_output_____" ] ], [ [ "# Перекрёстная проверка по 10 блокам\nfolds = \n\n# ядра для разбиений перекрёстной проверкой\nr_state = \n\n# модели для y\nscores = list()\n# таймер\ntic = time.perf_counter()\ni = 0\nfor df in [df0, df1, df2, df3, df4] :\n X = df.drop(['charges'], axis=1)\n y = df.charges\n kf_10 = \n \n score = cross_val_score(lm, X, y, cv=kf_10,\n scoring='neg_mean_squared_error').mean()\n scores.append(score)\n i+=1\n\n# таймер\ntoc = time.perf_counter()\nprint(f\"Расчёты методом CV по 10 блокам заняли {toc - tic:0.2f} секунд\")", "_____no_output_____" ], [ "# Перекрёстная проверка по 10 блокам\nfolds = 10\n\n# ядра для разбиений перекрёстной проверкой\nr_state = np.arange(my_seed, my_seed + 9)\n\n# модели для y\nscores_log = list()\n# таймер\ntic = time.perf_counter()\ni = 0\nfor df in [df0, df1, df2, df3, df4] :\n X = df.drop(['charges'], axis=1)\n y = np.log(df.charges)\n kf_10 = KFold(n_splits=folds, random_state=r_state[i],\n shuffle=True)\n score = cross_val_score(lm, X, y, cv=kf_10,\n scoring='neg_mean_squared_error').mean()\n scores_log.append(score)\n i+=1\n\n# таймер\ntoc = time.perf_counter()\nprint(f\"Расчёты методом CV по 10 блокам заняли {toc - tic:0.2f} секунд\")", "_____no_output_____" ], [ "# самая точная на charges\nfits = ['fit_lm_0', 'fit_lm_1', 'fit_lm_2', 'fit_lm_3', 'fit_lm_4']\nprint('Наименьшая ошибка на тестовой с k-fold10 у модели',\n fits[scores.index(max(scores))], \n ':\\nMSE_kf10 =', np.around(-max(scores), 0))", "_____no_output_____" ], [ "# самая точная на log(charges)\nfits = ['fit_lm_0_log', 'fit_lm_1_log', 'fit_lm_2_log', \n 'fit_lm_3_log', 'fit_lm_4_log']\nprint('Наименьшая ошибка на тестовой с k-fold10 у модели',\n fits[scores_log.index(max(scores_log))], \n ':\\nMSE_kf10 =', np.around(-max(scores_log), 3))", "_____no_output_____" ] ], [ [ "Можно убедиться, что оценка MSE методом перекрёстной проверки по 10 блокам даёт результаты, практически идентичные методу LOOCV. При этом скорость у первого метода при 1204 наблюдениях выше на два порядка.", "_____no_output_____" ], [ "Самой точной среди моделей для `charges` оказалась `fit_lm_3`, а среди моделей для `charges_log` – `fit_lm_0_log`. Оценим точность прогноза по этим моделям на отложенные наблюдения. ", "_____no_output_____" ] ], [ [ "# прогноз по fit_lm_3\n# модель на всех обучающих наблюдениях\nX = df3.drop(['charges'], axis=1)\ny = df3.charges.values.reshape(-1, 1)\nfit_lm_3 = \n\n# значения y на отложенных наблюдениях\ny = DF_predict[['charges']].values.reshape(-1, 1)\n# матрица объясняющих на отложенных наблюдениях\nX = DF_predict[['smokerYes', 'age', 'bmi']]\nX.loc[:, 'bmi_smokerYes'] = X.loc[:, 'bmi'] * X.loc[:, 'smokerYes']\nX = X.drop(['bmi'], axis=1)\n# прогнозы\ny_pred = \n\n# ошибка\nMSE = \nprint('MSE модели fit_lm_3 на отложенных наблюдениях = %.2f' % MSE)", "_____no_output_____" ], [ "# прогноз по fit_lm_log_0\n# модель\nX = df0.drop(['charges'], axis=1)\ny = np.log(df0.charges).values.reshape(-1, 1)\nfit_lm_0_log = \n\n# значения y на отложенных наблюдениях\ny = np.log(DF_predict[['charges']].values.reshape(-1, 1))\n# матрица объясняющих на отложенных наблюдениях\nX = DF_predict.drop(['charges', 'region'], axis=1)\n\n# прогнозы\ny_pred = \n\n# ошибка\nMSE_log = \nprint('MSE модели fit_lm_0_log на отложенных наблюдениях = %.2f' % MSE_log)", "_____no_output_____" ] ], [ [ "Очевидно, на выборке для прогноза точнее модель `fit_lm_3`: \n$\\hat{charges} = \\hat{\\beta_0} + \\hat{\\beta_1} \\cdot smokerYes + \\hat{\\beta_2} \\cdot bmi \\cdot smokerYes + \\hat{\\beta_3} \\cdot age$", "_____no_output_____" ] ], [ [ "print('модель fit_lm_3:\\n', \n 'константа ', np.around(fit_lm_3.intercept_, 3),\n '\\n объясняющие ', list(df3.drop(['charges'], axis=1).columns.values),\n '\\n коэффициенты ', np.around(fit_lm_3.coef_, 3))", "_____no_output_____" ] ], [ [ "# Источники \n\n1. *James G., Witten D., Hastie T. and Tibshirani R.* An Introduction to Statistical Learning with Applications in R. URL: [http://www-bcf.usc.edu/~gareth/ISL/ISLR%20First%20Printing.pdf](https://drive.google.com/file/d/15PdWDMf9hkfP8mrCzql_cNiX2eckLDRw/view?usp=sharing) \n1. Рашка С. Python и машинное обучение: крайне необходимое пособие по новейшей предсказательной аналитике, обязательное для более глубокого понимания методологии машинного обучения / пер. с англ. А.В. Логунова. – М.: ДМК Пресс, 2017. – 418 с.: ил.\n1. Interpreting Log Transformations in a Linear Model / virginia.edu. URL: <https://data.library.virginia.edu/interpreting-log-transformations-in-a-linear-model/> \n1. Python Timer Functions: Three Ways to Monitor Your Code / realpython.com. URL: <https://realpython.com/python-timer/> ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbddbbf9ce0c77234d4a37273df6ef9d61ccfe7c
10,137
ipynb
Jupyter Notebook
movingAverage.ipynb
sakr-m/mongo-spark-jupyter
7cad10b1439f4a3dfef230730f63f0099f28c2d9
[ "Apache-1.1" ]
null
null
null
movingAverage.ipynb
sakr-m/mongo-spark-jupyter
7cad10b1439f4a3dfef230730f63f0099f28c2d9
[ "Apache-1.1" ]
null
null
null
movingAverage.ipynb
sakr-m/mongo-spark-jupyter
7cad10b1439f4a3dfef230730f63f0099f28c2d9
[ "Apache-1.1" ]
1
2021-02-19T01:13:29.000Z
2021-02-19T01:13:29.000Z
43.13617
138
0.494722
[ [ [ "from pyspark.sql import SparkSession\n\nspark = SparkSession.\\\n builder.\\\n appName(\"pyspark-notebook2\").\\\n master(\"spark://spark-master:7077\").\\\n config(\"spark.executor.memory\", \"1g\").\\\n config(\"spark.mongodb.input.uri\",\"mongodb://mongo1:27017,mongo2:27018,mongo3:27019/Stocks.Source?replicaSet=rs0\").\\\n config(\"spark.mongodb.output.uri\",\"mongodb://mongo1:27017,mongo2:27018,mongo3:27019/Stocks.Source?replicaSet=rs0\").\\\n config(\"spark.jars.packages\", \"org.mongodb.spark:mongo-spark-connector_2.12:3.0.0\").\\\n getOrCreate()", "_____no_output_____" ], [ "#reading dataframes from MongoDB\ndf = spark.read.format(\"mongo\").load()\n\ndf.printSchema()", "root\n |-- _id: struct (nullable = true)\n | |-- oid: string (nullable = true)\n |-- company_name: string (nullable = true)\n |-- company_symbol: string (nullable = true)\n |-- price: double (nullable = true)\n |-- tx_time: string (nullable = true)\n\n" ], [ "#let's change the data type to a timestamp\ndf = df.withColumn(\"tx_time\", df.tx_time.cast(\"timestamp\"))", "_____no_output_____" ], [ "#Here we are calculating a moving average\nfrom pyspark.sql.window import Window\nfrom pyspark.sql import functions as F\n\nmovAvg = df.withColumn(\"movingAverage\", F.avg(\"price\").over( Window.partitionBy(\"company_symbol\").rowsBetween(-1,1)) )\nmovAvg.show()", "+--------------------+--------------------+--------------+-----+-------------------+------------------+\n| _id| company_name|company_symbol|price| tx_time| movingAverage|\n+--------------------+--------------------+--------------+-----+-------------------+------------------+\n|[5f527ac32f6a1552...|ITCHY ACRE CORPOR...| IAC|43.39|2020-09-04 13:34:59| 43.405|\n|[5f527ac42f6a1552...|ITCHY ACRE CORPOR...| IAC|43.42|2020-09-04 13:35:00|43.419999999999995|\n|[5f527ac52f6a1552...|ITCHY ACRE CORPOR...| IAC|43.45|2020-09-04 13:35:01|43.443333333333335|\n|[5f527ac62f6a1552...|ITCHY ACRE CORPOR...| IAC|43.46|2020-09-04 13:35:02| 43.46|\n|[5f527ac72f6a1552...|ITCHY ACRE CORPOR...| IAC|43.47|2020-09-04 13:35:03| 43.47666666666667|\n|[5f527ac82f6a1552...|ITCHY ACRE CORPOR...| IAC| 43.5|2020-09-04 13:35:04| 43.49666666666667|\n|[5f527ac92f6a1552...|ITCHY ACRE CORPOR...| IAC|43.52|2020-09-04 13:35:05| 43.52|\n|[5f527aca2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.54|2020-09-04 13:35:06| 43.53666666666667|\n|[5f527acb2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.55|2020-09-04 13:35:07| 43.54|\n|[5f527acc2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.53|2020-09-04 13:35:08| 43.53666666666667|\n|[5f527acd2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.53|2020-09-04 13:35:09| 43.49666666666667|\n|[5f527ada2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.43|2020-09-04 13:35:22| 43.45000000000001|\n|[5f527adb2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.39|2020-09-04 13:35:23| 43.39333333333334|\n|[5f527adc2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.36|2020-09-04 13:35:24| 43.35666666666666|\n|[5f527adf2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.32|2020-09-04 13:35:27| 43.32|\n|[5f527ae02f6a1552...|ITCHY ACRE CORPOR...| IAC|43.28|2020-09-04 13:35:28| 43.29333333333333|\n|[5f527ae12f6a1552...|ITCHY ACRE CORPOR...| IAC|43.28|2020-09-04 13:35:29| 43.28666666666667|\n|[5f527ae22f6a1552...|ITCHY ACRE CORPOR...| IAC| 43.3|2020-09-04 13:35:30| 43.30666666666667|\n|[5f527ae32f6a1552...|ITCHY ACRE CORPOR...| IAC|43.34|2020-09-04 13:35:31| 43.34|\n|[5f527ac22f6a1552...|ITCHY ACRE CORPOR...| IAC|43.38|2020-09-04 13:34:58|43.416666666666664|\n+--------------------+--------------------+--------------+-----+-------------------+------------------+\nonly showing top 20 rows\n\n" ], [ "#Saving Dataframes to MongoDB\nmovAvg.write.format(\"mongo\").option(\"replaceDocument\", \"true\").mode(\"append\").save()", "_____no_output_____" ], [ "#Reading Dataframes from the Aggregation Pipeline in MongoDB\npipeline = \"[{'$group': {_id:'$company_name', 'maxprice': {$max:'$price'}}},{$sort:{'maxprice':-1}}]\"\naggPipelineDF = spark.read.format(\"mongo\").option(\"pipeline\", pipeline).load()\naggPipelineDF.show()", "+--------------------+--------+\n| _id|maxprice|\n+--------------------+--------+\n|FRUSTRATING CHAOS...| 87.6|\n|HOMELY KIOSK UNLI...| 86.48|\n| CREEPY GIT HOLDINGS| 83.4|\n|GREASY CHAMPION C...| 81.76|\n|COMBATIVE TOWNSHI...| 72.18|\n|FROTHY MIDNIGHT P...| 66.81|\n|ITCHY ACRE CORPOR...| 44.42|\n|LACKADAISICAL SAV...| 42.34|\n|CORNY PRACTITIONE...| 38.55|\n|TRITE JACKFRUIT P...| 22.62|\n+--------------------+--------+\n\n" ], [ "#using SparkSQL with MongoDB\nmovAvg.createOrReplaceTempView(\"avgs\")\n\nsqlDF=spark.sql(\"SELECT * FROM avgs WHERE movingAverage > 43.0\")\n\nsqlDF.show()", "+--------------------+--------------------+--------------+-----+-------+------------------+\n| _id| company_name|company_symbol|price|tx_time| movingAverage|\n+--------------------+--------------------+--------------+-----+-------+------------------+\n|[5f527ac32f6a1552...|ITCHY ACRE CORPOR...| IAC|43.39| null| 43.405|\n|[5f527ac42f6a1552...|ITCHY ACRE CORPOR...| IAC|43.42| null|43.419999999999995|\n|[5f527ac52f6a1552...|ITCHY ACRE CORPOR...| IAC|43.45| null|43.443333333333335|\n|[5f527ac62f6a1552...|ITCHY ACRE CORPOR...| IAC|43.46| null| 43.46|\n|[5f527ac72f6a1552...|ITCHY ACRE CORPOR...| IAC|43.47| null| 43.47666666666667|\n|[5f527ac82f6a1552...|ITCHY ACRE CORPOR...| IAC| 43.5| null| 43.49666666666667|\n|[5f527ac92f6a1552...|ITCHY ACRE CORPOR...| IAC|43.52| null| 43.52|\n|[5f527aca2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.54| null| 43.53666666666667|\n|[5f527acb2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.55| null| 43.54|\n|[5f527acc2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.53| null| 43.53666666666667|\n|[5f527acd2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.53| null| 43.49666666666667|\n|[5f527ada2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.43| null| 43.45000000000001|\n|[5f527adb2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.39| null| 43.39333333333334|\n|[5f527adc2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.36| null| 43.35666666666666|\n|[5f527adf2f6a1552...|ITCHY ACRE CORPOR...| IAC|43.32| null| 43.32|\n|[5f527ae02f6a1552...|ITCHY ACRE CORPOR...| IAC|43.28| null| 43.29333333333333|\n|[5f527ae12f6a1552...|ITCHY ACRE CORPOR...| IAC|43.28| null| 43.28666666666667|\n|[5f527ae22f6a1552...|ITCHY ACRE CORPOR...| IAC| 43.3| null| 43.30666666666667|\n|[5f527ae32f6a1552...|ITCHY ACRE CORPOR...| IAC|43.34| null| 43.34|\n|[5f527ac22f6a1552...|ITCHY ACRE CORPOR...| IAC|43.38| null|43.416666666666664|\n+--------------------+--------------------+--------------+-----+-------+------------------+\nonly showing top 20 rows\n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
cbddbf04056e80ed110fed09af535337e2c61682
27,485
ipynb
Jupyter Notebook
ECE314/lab12/Lab 12.ipynb
debugevent90901/courseArchive
1585c9a0f4a1884c143973dcdf416514eb30aded
[ "MIT" ]
null
null
null
ECE314/lab12/Lab 12.ipynb
debugevent90901/courseArchive
1585c9a0f4a1884c143973dcdf416514eb30aded
[ "MIT" ]
null
null
null
ECE314/lab12/Lab 12.ipynb
debugevent90901/courseArchive
1585c9a0f4a1884c143973dcdf416514eb30aded
[ "MIT" ]
null
null
null
49.080357
1,421
0.598872
[ [ [ "# Lab 12: Epidemics, or the Spread of Viruses", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\nimport numpy as np\nimport scipy as sp\nimport scipy.stats as st\nimport networkx as nx\nfrom scipy.integrate import odeint\nfrom operator import itemgetter\nprint ('Modules Imported!')", "_____no_output_____" ] ], [ [ "## Epidemics, or the Spread of Viruses:", "_____no_output_____" ], [ "The study of how viruses spread through populations began well over a hundred years ago. The original studies concerned biological viruses, but the principles found application in modeling the spread of ideas or practices in social networks (such as what seeds farmers use) even before the advent of computers. More recently, computer networks, and in particular, on-line social networks, have stimulated renewed attention on the theory, to model, for example, the spread of computer viruses through networks, the adoption of new technology, and the spread of such things as ideas and emotional states through social networks.\n\nOne of the simplest models for the spread of infection is the discrete-time Reed Frost model, proposed in the 1920s. It goes as follows. Suppose the individuals that can be infected are the nodes of an undirected graph. An edge between two nodes indicates a pathway for the virus to spread from one node to the other node. The Reed Frost model assumes that each node is in one of three states at each integer time $t\\geq 0:$ susceptible, infected, or removed. This is thus called an SIR model. At $t=0$, each individual is either susceptible or infected. The evolution over one time step is the following. A susceptible node has a chance $\\beta$ to become infected by each of its infected neighbors, with the chances from different neighbors being independent. Thus if a susceptible node has $k$ infected neighbors at time $t,$ the probability the node is *not* infected at time $t+1$ (i.e. it remains susceptible) is $(1-\\beta)^k,$ and the probability the node is infected at time $t+1$ is $1-(1-\\beta)^k.$ It is assumed that a node is removed one time step after being infected, and once a node is removed, it remains removed forever. In applications, removed could mean the node has recovered and has gained immunity, so infection is no longer spread by that node. To summarize, the model is completely determined by the graph, the initial states of the nodes, and the parameter $\\beta.$\n\nOne question of interest is how likely is the virus to infect a large fraction of nodes, and how quickly will it spread. Other questions are to find the effect of well connected clusters in the graph, or the impact of nodes of large degree, on the spread of the virus. If the virus represents adoption of a new technology, the sponsoring company might be interested in finding a placement of initially infected nodes (achieved by free product placements) to maximize the chances that most nodes become infected. Below is code that uses the Networkx package to simulate the spread of a virus. \n\nA simple special case, and the one considered first historically, is if the virus can spread from any node to any other node. This corresponds to a tightly clustered population; the graph is the complete graph. For this case, the system can be modeled by a three dimensional Markov process $(X_t)$ with a state $(S,I,R),$ denoting the numbers of susceptible, infected, and removed, nodes, respectively. Given $X_t=(S,I,R),$ the distribution of $X_{t+1}$ is determined by generating the number of newly infected nodes, which has the binomial distribution with parameters $S$ and $p=1-(1-\\beta)^I$ (because each of the susceptible nodes is independently infected with probability $p.$)", "_____no_output_____" ] ], [ [ "# Simulation of Reed Frost model for fully connected graph (aka mean field model)\n# X[t,:]=[number susceptible, number infected, number removed] at time t\n# Since odeint wants t first in trajectories X[t,i], let's do that consistently\n\nn=100 # Number of nodes\nI_init=6 # Number of nodes initially infected, the others are initially susceptible\n\nc=2.0 # Use a decimal point when specifying c.\nbeta=c/n # Note that if n nodes each get infected with probability beta=c/n,\n # then c, on average, are infected. \n\nT=100 # maximum simulation time\nX = np.zeros((T+1,3),dtype=np.int)\n\n\nX[0,0], X[0,1] = n-I_init, I_init\n\nt=0\nwhile t<T and X[t,1]>0: # continue (up to time T) as long as there exist infected nodes\n newI=np.random.binomial(X[t,0],1.0-(1.0-beta)**X[t,1]) # number of new infected nodes\n X[t+1,0]=X[t,0]-newI\n X[t+1,1]=newI\n X[t+1,2]=X[t,1]+X[t,2]\n t=t+1\n\nplt.figure()\nplt.plot(X[0:t,0], 'g', label='susceptible')\nplt.plot(X[0:t,1], 'r', label='infected')\nplt.plot(X[0:t,2], 'b', label='removed')\nplt.title('SIR Model for complete graph')\nplt.xlabel('time')\nplt.ylabel('number of nodes')\nplt.legend()", "_____no_output_____" ] ], [ [ "Run the code a few times to get an idea of the variations that can occur. Then try increasing n to 1000 or 10,000 and running the simulation a few more times. Note that the code scales down the infection parmeter $\\beta$ inversely with respect to the population size, that is: $\\beta = c/n$ for a constant $c.$ If, instead, $\\beta$ didn't depend on $n,$ then the infection would spread much faster for large $n$ and the fully connected graph. A key principle of the spread of viruses (or branching processes) is that the number infected will tend to increase if the mean number, $F,$ of new infections caused by each infected node satisfies $F>1.$ \n<br>\n**<SPAN style=\"BACKGROUND-COLOR: #C0C0C0\">Problem 1:</SPAN>** In the simulation with $n$ large you should see the number of infected nodes increase and then decrease at some *turnaround time.* Determine how the turnaround time depends on the fraction of nodes that are susceptible. How does the constant $c$ enter into this relationship? It may be helpful to change the value of $c$ a few times and view how it effects the graph. (You do not need to write code for this problem--you can write your answer in a markdown cell).", "_____no_output_____" ], [ "__Answer:__ (Your answer here)", "_____no_output_____" ], [ "**<SPAN style=\"BACKGROUND-COLOR: #C0C0C0\">End of Problem 1</SPAN>** ", "_____no_output_____" ], [ "**<SPAN style=\"BACKGROUND-COLOR: #C0C0C0\">Problem 2:</SPAN>** We have assumed that an infected node is removed from the population after a single time step. If you were modeling the spread of a tweet this might be a good idea. If a tweet doesn't get retweeted immediately the probability that it does later is very close to 0. However, with something like a virus, an individual tends to be infected for more than a single day. Suppose $\\gamma$ represents the probability an individual that is infected in one time step is removed from the population by the next time step. So the number of time slots an individual is infected has the geometric distribution with mean $1/\\gamma$.\n\n<ol>\n <li> Modify the code above to include $\\gamma = .25$. \n <li> Determine how allowing nodes to remain infected for multiple time slots (according to $\\gamma$) changes the answer to the previous problem.\n</ol>", "_____no_output_____" ] ], [ [ "# Your code here", "_____no_output_____" ] ], [ [ "__Answer:__ (Your answer here)", "_____no_output_____" ], [ "**<SPAN style=\"BACKGROUND-COLOR: #C0C0C0\">End of Problem 2</SPAN>** ", "_____no_output_____" ], [ "If you run your previous code for n larger than 1000 the output should be nearly the same on each run (depending on the choice of $c$ and $\\gamma$). In fact, for $n$ large the trajectory should follow the ode (based on the same principles explored in the previous lab):\n\n$\\frac{dS}{dt} = -\\beta IS $ \n\n$\\frac{dI}{dt} = \\beta IS - \\gamma I$ \n\n$\\frac{dR}{dt} = \\gamma I$ \n\nThe ode is derived based on condidering the expected value of the Makov process at a time $t+1,$ given the state is $(S,I,R)$\nat time $t.$ Specifically, each of $I$ infected nodes has a chance to infect each of $S$ susceptible nodes, yielding an expected\nnumber of new infected nodes $\\beta I S.$ (This equation overcounts the expected number of infections because a node can simultaneously be infected by two of its neighbors, but the extent of overcounting is small if $\\beta$ is small.) Those nodes cause a decrease in $S$ and an increase in $I.$ Similarly, the expected number of susceptible nodes becoming removed is $\\gamma I.$\n \n\n**<SPAN style=\"BACKGROUND-COLOR: #C0C0C0\">Problem 3:</SPAN>** Use the odeint method (as in Lab 11) to integrate this three dimensional ode and graph the results vs. time. Try to match the plot you generated for the previous problem for the parameter values $n=1000,$ $\\gamma = 0.25,$ and $\\beta=c/n$ with $c=2.0.$ To get the best match, plot your solution for about the same length of time as the stochastic simulation takes.", "_____no_output_____" ] ], [ [ "# Your code here", "_____no_output_____" ] ], [ [ "**<SPAN style=\"BACKGROUND-COLOR: #C0C0C0\">End of Problem 3</SPAN>** ", "_____no_output_____" ], [ "The above simulations and calculations did not involve graphical structure. The following code simulates the Reed Frost model for a geometric random graph (we encountered such graphs in Lab 7. Since each node has only a few neighbors, we no longer scale the parameter $\\beta$ down with the total number of nodes.", "_____no_output_____" ] ], [ [ "## Reed Frost simulation over a random geometric graph\n## (used at beginning of graph section in Lab 7)\n## X is no longer Markov, the state of the network is comprised of the states of all nodes\n\nd=0.16 # distance threshold, pairs of nodes within distance d are connected by an edge\nG=nx.random_geometric_graph(100,d) #100 nodes in unit square, distance threshold d determines edges\n# position is stored as node attribute data for random_geometric_graph, pull it out for plotting\npos=nx.get_node_attributes(G,'pos')\n\n\n\n######################################\ndef my_display(t, X, show):\n \"\"\" The function puts numbers of nodes in states S,I,R into X[t,:]\n If (show==1 and no nodes are infected) or if show==2, G is plotted with node colors for S,I,R.\n Returns value 0 if no nodes are infected\n \"\"\"\n susceptible=[]\n infected=[]\n removed=[]\n for u in G.nodes():\n if G.nodes[u]['state']=='S':\n susceptible.append(u)\n elif G.nodes[u]['state']=='I':\n infected.append(u)\n elif G.nodes[u]['state']=='R':\n removed.append(u)\n \n X[t,0] = np.size(susceptible)\n X[t,1] = np.size(infected)\n X[t,2] = np.size(removed)\n \n # show: 0=don't graph, 1 = show graph once at end, 2=show graph after each iteration\n if (show==1 and X[t,1]==0) or show==2:\n print (\"Nodes infected at time\",t,\":\",infected)\n plt.figure(figsize=(8,8))\n nx.draw_networkx_edges(G,pos,alpha=0.4) #All edges are drawn alpha specifies edge transparency\n nx.draw_networkx_nodes(G,pos,nodelist=susceptible,\n node_size=80,\n node_color='g')\n nx.draw_networkx_nodes(G,pos,nodelist=infected,\n node_size=80,\n node_color='r')\n nx.draw_networkx_nodes(G,pos,nodelist=removed,\n node_size=80,\n node_color='b')\n\n plt.xlim(-0.05,1.05)\n plt.ylim(-0.05,1.05)\n plt.axis('off')\n plt.show()\n \n if X[t,1]==0:\n return 0; # No infected nodes\n else:\n return 1; # At least one node is infected\n#####################################\n\nbeta=0.3\ngamma=.5\nT = 40\nX = np.zeros((T,3))\n\nprint (\"Infection probability parameter beta=\", beta) \n\nfor u in G.nodes(): # Set the state of each node to susceptible\n G.nodes[u]['state']='S' \n \nG.nodes[0]['state']='I' # Change state of node 0 to infected\n\n\nt=0\nshow=2 # show: 0=don't graph, 1 = show graph once at end, 2=show graph after each iteration \nwhile t<T and my_display(t, X,show): # Plot graph, fill in X[t,:], and go through loop if some node is infected\n \n for u in G.nodes(): # This loop counts number of infected neighbors of each node\n G.nodes[u]['num_infected_nbrs']=0\n for v in G.neighbors(u):\n if G.nodes[v]['state']=='I':\n G.nodes[u]['num_infected_nbrs']+=1\n \n for u in G.nodes(): # This loop updates node states\n if G.nodes[u]['state']=='I' and np.random.random() < gamma:\n G.nodes[u]['state']='R'\n elif G.nodes[u]['state']=='S' and np.random.random() > np.power(1.0-beta,G.nodes[u]['num_infected_nbrs']):\n G.nodes[u]['state']='I'\n t=t+1\n\nplt.figure()\nplt.plot(X[0:t,0], 'g', label='susceptible')\nplt.plot(X[0:t,1], 'r', label='infected')\nplt.plot(X[0:t,2], 'b', label='removed')\nplt.title('SIR Model')\nplt.xlabel('time')\nplt.ylabel('number of nodes')\nplt.legend()\n###################################", "_____no_output_____" ] ], [ [ "Now let's try simulating the spread of a virus of a network obtained from real world data. Think of each node as a blog. It's neighbors are all the other blogs that it contains links to. Additionally, each blog contains a value (0,1) which represents a political party. So you can imagine a network with two large clusters (one for each party) with a smaller number of links going between the clusters. Specifically, we upload the graph from the file pblogs.gml. (This data can be used freely though its source should be cited: Lada A. Adamic and Natalie Glance, \"The political blogosphere and the 2004 US Election\", in Proceedings of the WWW-2005 Workshop on the Weblogging Ecosystem (2005).) It may take a while to load the graph, so we write the code in a box by itself so that you only need to load the graph once. ", "_____no_output_____" ] ], [ [ "### Load G from polblogs.gml file and convert from directed to undirected graph. May take 20 seconds.\nG = nx.read_gml('polblogs.gml') # node labels are web addresses (as unicode strings)\nG=G.to_undirected(reciprocal=False)\nfor u in G.nodes(): # Copy node labels (i.e. the urls of websites) to url values\n G.nodes[u]['url']= u\nG=nx.convert_node_labels_to_integers(G) # Replace node labels by numbers 0,1,2, ...\nprint (\"G loaded from polblogs.gml and converted to undirected graph\")", "G loaded from polblogs.gml and converted to undirected graph\n" ], [ "#Here are some methods for exploring properties of the graph\n#uncomment next line to see attributes of all nodes of G\n#print (G.nodes(data=True)) # note, for example, that node 1 has url rightrainbow.com\n#uncomment next line to see (node,degree) pairs sorted by decreasing degree\n#print (sorted(G.degree(),key=itemgetter(1),reverse=True))\n#uncomment to see the neighbors of node 6\n#print (G.neighbors(6))", "_____no_output_____" ], [ "######### Simulate Reed Frost dynamics over undirected graph G, assuming G is loaded\n\ndef my_count(t, X):\n \"\"\" The function puts numbers of nodes in states S,I,R into X[t,:]\n Returns value 0 if no nodes are infected\n \"\"\"\n susceptible=[]\n infected=[]\n removed=[]\n for u in G.nodes():\n if G.node[u]['state']=='S':\n susceptible.append(u)\n elif G.node[u]['state']=='I':\n infected.append(u)\n elif G.node[u]['state']=='R':\n removed.append(u)\n \n X[t,0] = np.size(susceptible)\n X[t,1] = np.size(infected)\n X[t,2] = np.size(removed)\n \n if X[t,1]==0:\n return 0; # No infected nodes\n else:\n return 1; # At least one node is infected\n#####################################\n\nbeta=0.3\ngamma=.5\nT = 40\nX = np.zeros((T,3))\n\nprint (\"Infection probability parameter beta=\", beta) \n\nfor u in G.nodes(): # Set the state of each node to susceptible\n G.node[u]['state']='S' \n \nG.node[1]['state']='I' # Change state of node 1 to infected\n\n\nt=0\nwhile t<T and my_count(t, X): # Fill in X[t,:], and go through loop if some node is infected\n \n for u in G.nodes(): # This loop counts number of infected neighbors of each node\n G.node[u]['num_infected_nbrs']=0\n for v in G.neighbors(u):\n if G.node[v]['state']=='I':\n G.node[u]['num_infected_nbrs']+=1\n \n for u in G.nodes(): # This loop updates node states\n if G.node[u]['state']=='I' and np.random.random() < gamma:\n G.node[u]['state']='R'\n elif G.node[u]['state']=='S' and np.random.random() > np.power(1.0-beta,G.node[u]['num_infected_nbrs']):\n G.node[u]['state']='I'\n t=t+1\n \nplt.figure()\nplt.plot(X[0:t,0], 'g', label='susceptible')\nplt.plot(X[0:t,1], 'r', label='infected')\nplt.plot(X[0:t,2], 'b', label='removed')\nplt.title('SIR Model')\nplt.xlabel('time')\nplt.ylabel('number of nodes')\nplt.legend()", "_____no_output_____" ] ], [ [ "Run the code above a few times to see the variation. This graph has a much larger variation of degrees of the nodes than the random geometric graphs we simulated earlier.<br><br>\n**<SPAN style=\"BACKGROUND-COLOR: #C0C0C0\">Problem 4:</SPAN>** \n\n1. Adapt the code in the previous cell to run N=100 times and calculate the average number of susceptible nodes remaining after no infected nodes are left. Also, to get an idea of how accurately your average predicts the true mean, compute the sample standard deviation divided by sqrt(N). See <A href=http://en.wikipedia.org/wiki/Standard_deviation#Corrected_sample_standard_deviation> wikipedia </A> for definitions of sample mean and sample standard deviation (use either corrected or uncorrected version of sample standard variance) or use numpy.mean() and numpy.std(). Dividing the standard deviation of the samples by sqrt(N) estimates the standard deviation of your estimate of the mean. So if you were to increase N, your observed standard deviation wouldn't change by much, but your observed mean will be more accurate.\n2. Now, you must let node 1 be initially infected, but you may remove ten carefully selected nodes before starting the simulations. Try to think of a good choice of which nodes to remove so as to best reduce the number of nodes that become infected. (You could use the method G.remove_node(n) to remove node $n$ from the graph $G$, but it would run faster to just initialize the state variable for the removed nodes to R but leave the node in $G.$) Then again compute the mean and estimated accuracy as before, for the number of nodes that are susceptible at the end of the simulation runs. Explain the reasoning you used. Ideally you should be able to increase the number of remaining susceptible nodes by at least ten percent for this example.", "_____no_output_____" ] ], [ [ "# Your code here", "_____no_output_____" ] ], [ [ "__Answer:__ (Your answer here)", "_____no_output_____" ], [ "**<SPAN style=\"BACKGROUND-COLOR: #C0C0C0\">End of Problem 4</SPAN>** ", "_____no_output_____" ] ], [ [ "### LEFTOVER CODE : READ IF INTERESTED BUT THERE IS NO LAB QUESTION FOR THIS\n### Each node of the graph G loaded from polblogs.gml has a value,\n### either 0 or 1, indicating whether the node corresponds to\n### a politically liberal website or a politically conservative website.\n### For fun, this code does the Reed Frost simulation (without gamma)\n### and breaks down each of the S,I,R counts into the two values.\n### An idea was to see if we could cluster the nodes by infecting one\n### node and then seeing if other nodes in the same cluster are more\n### likely to be infected. Indeed, in the simulation we see nodes\n### with the same value as node 1 getting infected sooner. By the end,\n### though, the number infected from the other value catch up.\n\n\n#####################################\ndef my_print(t):\n numS=np.array([0,0])\n numI=np.array([0,0])\n numR=np.array([0,0])\n for u in G.nodes():\n if G.node[u]['state']=='S':\n numS[G.node[u]['value']]+=1\n elif G.node[u]['state']=='I':\n numI[G.node[u]['value']]+=1\n elif G.node[u]['state']=='R':\n numR[G.node[u]['value']]+=1\n print (\"{0:3d}: {1:5d} {2:5d} {3:5d} {4:5d} {5:5d} {6:5d}\"\\\n .format(t,numS[0], numS[1], numI[0],numI[1],numR[0],numR[1]))\n if np.sum(numI)==0:\n return 0; # No infected nodes\n else:\n return 1; # At least one node is infected\n#####################################\n\nbeta=0.3\nprint (\"Infection probability parameter beta=\", beta) \nprint (\" t Susceptible Infected Removed\")\n\nfor u in G.nodes(): # Set the state of each nodes to susceptible\n G.node[u]['state']='S' \n \nG.node[1]['state']='I' # Change state of node 1 to infected\nt=0\n\nwhile my_print(t): # Plot graph and go through loop if some node is infected\n \n for u in G.nodes(): # This loop counts number of infected neighbors of each node\n G.node[u]['num_infected_nbrs']=0\n for v in G.neighbors(u):\n if G.node[v]['state']=='I':\n G.node[u]['num_infected_nbrs']+=1\n \n for u in G.nodes(): # This loop updates node states\n if G.node[u]['state']=='I':\n G.node[u]['state']='R'\n elif G.node[u]['state']=='S' and np.random.random() > np.power(1.0-beta,G.node[u]['num_infected_nbrs']):\n G.node[u]['state']='I'\n t=t+1\nprint (\"finished\")", "_____no_output_____" ] ], [ [ "## Lab Questions:", "_____no_output_____" ], [ "For this weeks lab, please answer all questions 1-4.", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-warning\"> \n## Academic Integrity Statement ##\n\nBy submitting the lab with this statement, you declare you have written up the lab entirely by yourself, including both code and markdown cells. You also agree that you should not share your code with anyone else. Any violation of the academic integrity requirement may cause an academic integrity report to be filed that could go into your student record. See <a href=\"https://provost.illinois.edu/policies/policies/academic-integrity/students-quick-reference-guide-to-academic-integrity/\">Students' Quick Reference Guide to Academic Integrity</a> for more information. ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
cbddce0a78e75b6ff57d8a148a9046ba4909d113
3,973
ipynb
Jupyter Notebook
GOING_DEEPER_CV/Node_15/[CV-15] Only_LMS_Code_Blocks.ipynb
HRPzz/AIFFEL
9fa865cc49b08f15ac5930b8e0821538865da2ef
[ "MIT" ]
4
2022-01-27T08:37:17.000Z
2022-03-16T15:04:23.000Z
GOING_DEEPER_CV/Node_15/[CV-15] Only_LMS_Code_Blocks.ipynb
HRPzz/AIFFEL
9fa865cc49b08f15ac5930b8e0821538865da2ef
[ "MIT" ]
null
null
null
GOING_DEEPER_CV/Node_15/[CV-15] Only_LMS_Code_Blocks.ipynb
HRPzz/AIFFEL
9fa865cc49b08f15ac5930b8e0821538865da2ef
[ "MIT" ]
2
2022-01-13T15:38:05.000Z
2022-03-16T15:06:55.000Z
24.078788
118
0.553486
[ [ [ "# 15. 사람의 몸짓을 읽어보자\n\n**Human pose estimation에 대해 그동안 발표된 논문을 기반으로 아이디어의 흐름이 발전해 온 내역을 자세히 살펴본다.**", "_____no_output_____" ], [ "## 15-1. 들어가며", "_____no_output_____" ], [ "## 15-2. body language, 몸으로 하는 대화", "_____no_output_____" ], [ "## 15-3. Pose 는 face landmark 랑 비슷해요", "_____no_output_____" ], [ "## 15-4. human keypoint detection (1)", "_____no_output_____" ], [ "## 15-5. human keypoint detection (2)", "_____no_output_____" ], [ "## 15-6. 코드로 이해하는 pose estimation", "_____no_output_____" ] ], [ [ "import os\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nresnet = tf.keras.applications.resnet.ResNet50(include_top=False, weights='imagenet')", "_____no_output_____" ], [ "upconv1 = tf.keras.layers.Conv2DTranspose(256, kernel_size=(4,4), strides=(2,2), padding='same')\nbn1 = tf.keras.layers.BatchNormalization()\nrelu1 = tf.keras.layers.ReLU()\nupconv2 = tf.keras.layers.Conv2DTranspose(256, kernel_size=(4,4), strides=(2,2), padding='same')\nbn2 = tf.keras.layers.BatchNormalization()\nrelu2 = tf.keras.layers.ReLU()\nupconv3 = tf.keras.layers.Conv2DTranspose(256, kernel_size=(4,4), strides=(2,2), padding='same')\nbn3 = tf.keras.layers.BatchNormalization()\nrelu3 = tf.keras.layers.ReLU()", "_____no_output_____" ], [ "def _make_deconv_layer(num_deconv_layers):\n seq_model = tf.keras.models.Sequential()\n for i in range(num_deconv_layers):\n seq_model.add(tf.keras.layers.Conv2DTranspose(256, kernel_size=(4,4), strides=(2,2), padding='same'))\n seq_model.add(tf.keras.layers.BatchNormalization())\n seq_model.add(tf.keras.layers.ReLU())\n return seq_model\n\nupconv = _make_deconv_layer(3)", "_____no_output_____" ], [ "final_layer = tf.keras.layers.Conv2D(17, kernel_size=(1,1), padding='same')", "_____no_output_____" ], [ "inputs = keras.Input(shape=(256, 192, 3))\nx = resnet(inputs)\nx = upconv(x)\nout = final_layer(x)\nmodel = keras.Model(inputs, out)\n\nmodel.summary()", "_____no_output_____" ], [ "np_input = np.zeros((1,256,192,3), dtype=np.float32)\ntf_input = tf.convert_to_tensor(np_input, dtype=tf.float32)\nprint('input shape')\nprint (tf_input.shape)\nprint('\\n')\n\ntf_output = model(tf_input)\nprint('output shape')\nprint (tf_output.shape)\nprint (tf_output[0,:10,:10,:10])", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
cbdde445e7025a76845c84479139e4e352013cc1
41,412
ipynb
Jupyter Notebook
09_NLP/04_Character_Level_RNN/02_Names_Generation_Character_level_RNN.ipynb
CrispenGari/pytorch-python
e5e8f8d48aa17ed4eb2236e53cbea78d6beeacf6
[ "MIT" ]
1
2021-11-08T07:37:16.000Z
2021-11-08T07:37:16.000Z
09_NLP/04_Character_Level_RNN/02_Names_Generation_Character_level_RNN.ipynb
CrispenGari/pytorch-python
e5e8f8d48aa17ed4eb2236e53cbea78d6beeacf6
[ "MIT" ]
null
null
null
09_NLP/04_Character_Level_RNN/02_Names_Generation_Character_level_RNN.ipynb
CrispenGari/pytorch-python
e5e8f8d48aa17ed4eb2236e53cbea78d6beeacf6
[ "MIT" ]
1
2021-11-22T17:52:50.000Z
2021-11-22T17:52:50.000Z
55.142477
17,914
0.697068
[ [ [ "### Genarating names with character-level RNN\n\nIn this notebook we are going to follow the previous notebook wher we classified name's nationalities based on a character level RNN. This time around we are going to generate names using character level RNN. Example: _given a nationality and three starting characters we want to generate some names based on those characters_\n\nWe will be following [this pytorch tutorial](https://pytorch.org/tutorials/intermediate/char_rnn_generation_tutorial.html).\n\n\nThe difference between this notebook and the previous notebook is that we instead of predicting the class where the name belongs, we are going to output one letter at a time until we generate a name. This can be done on a word level but we will do this on a character based level in our case.", "_____no_output_____" ], [ "### Data preparation\n\nThe dataset that we are going to use was downloaded [here](https://download.pytorch.org/tutorial/data.zip). This dataset has nationality as a file name and inside the files we will see the names that belongs to that nationality. I've uploaded this dataset on my google drive so that we can load it eaisly. \n\n### Mounting the drive\n", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "Mounted at /content/drive\n" ], [ "data_path = '/content/drive/My Drive/NLP Data/names-dataset/names'", "_____no_output_____" ] ], [ [ "### Imports", "_____no_output_____" ] ], [ [ "from __future__ import unicode_literals, print_function, division\nimport os, string, unicodedata, random\n\nimport torch \nfrom torch import nn\nfrom torch.nn import functional as F\n\ntorch.__version__", "_____no_output_____" ], [ "all_letters = string.ascii_letters + \" .,;'-\"\nn_letters = len(all_letters) + 1 # Plus EOS marker", "_____no_output_____" ] ], [ [ "A function that converts all unicodes to ASCII.", "_____no_output_____" ] ], [ [ "def unicodeToAscii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n and c in all_letters\n )", "_____no_output_____" ], [ "def read_lines(filename):\n with open(filename, encoding='utf-8') as some_file:\n return [unicodeToAscii(line.strip()) for line in some_file]", "_____no_output_____" ], [ "# Build the category_lines dictionary, a list of lines per category\ncategory_lines = {}\nall_categories = []\n\nfor filename in os.listdir(data_path):\n category = filename.split(\".\")[0]\n all_categories.append(category)\n lines = read_lines(os.path.join(data_path, filename))\n category_lines[category] = lines\n\nn_categories = len(all_categories)\nprint('# categories:', n_categories, all_categories)", "# categories: 18 ['Italian', 'Vietnamese', 'Scottish', 'German', 'Dutch', 'Spanish', 'English', 'Portuguese', 'Russian', 'Chinese', 'Irish', 'Greek', 'Korean', 'Japanese', 'Czech', 'French', 'Arabic', 'Polish']\n" ] ], [ [ "### Creating the Network\n\nThis network extends from the previous notebook with an etra argumeny for the category tensor which is concatenated along with others. The category tensor is one-hot vector just like the letter input.\n\nWe will output the most probable letter and used it as input to the next letter.\n\n\n\n![img](https://i.imgur.com/jzVrf7f.png)\n\n", "_____no_output_____" ] ], [ [ "class RNN(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n self.hidden_size = hidden_size\n\n self.i2h = nn.Linear(n_categories + input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(n_categories + input_size + hidden_size, output_size)\n self.o2o = nn.Linear(hidden_size + output_size, output_size)\n self.dropout = nn.Dropout(0.1)\n self.softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, category, input, hidden):\n input_combined = torch.cat((category, input, hidden), 1)\n hidden = self.i2h(input_combined)\n output = self.i2o(input_combined)\n output_combined = torch.cat((hidden, output), 1)\n output = self.o2o(output_combined)\n output = self.dropout(output)\n output = self.softmax(output)\n return output, hidden\n\n def initHidden(self):\n return torch.zeros(1, self.hidden_size)\n", "_____no_output_____" ] ], [ [ "### Training\n\nFirst of all, helper functions to get random pairs of (category, line):\n", "_____no_output_____" ] ], [ [ "# Random item from a list\ndef randomChoice(l):\n return l[random.randint(0, len(l) - 1)]\n\n# Get a random category and random line from that category\ndef randomTrainingPair():\n category = randomChoice(all_categories)\n line = randomChoice(category_lines[category])\n return category, line", "_____no_output_____" ], [ "line, cate = randomTrainingPair()\nline, cate", "_____no_output_____" ] ], [ [ "For each timestep (that is, for each letter in a training word) the inputs of the network will be ``(category, current letter, hidden state)`` and the outputs will be ``(next letter, next hidden state)``. So for each training set, we’ll need the category, a set of input letters, and a set of output/target letters.\n\nSince we are predicting the next letter from the current letter for each timestep, the letter pairs are groups of consecutive letters from the line - e.g. for `\"ABCD<EOS>\"` we would create (“A”, “B”), (“B”, “C”), (“C”, “D”), (“D”, “EOS”).\n\n![img](https://i.imgur.com/JH58tXY.png)\n\nThe category tensor is a one-hot tensor of size `<1 x n_categories>`. When training we feed it to the network at every timestep - this is a design choice, it could have been included as part of initial hidden state or some other strategy.", "_____no_output_____" ] ], [ [ "def category_tensor(category):\n li = all_categories.index(category)\n tensor = torch.zeros(1, n_categories)\n tensor[0][li] = 1\n return tensor\n\n# out = 3\ndef input_tensor(line):\n tensor = torch.zeros(len(line), 1, n_letters)\n for li in range(len(line)):\n letter = line[li]\n tensor[li][0][all_letters.find(letter)] = 1\n return tensor\n\ndef target_tensor(line):\n letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))]\n letter_indexes.append(n_letters - 1) # EOS\n return torch.LongTensor(letter_indexes)\n", "_____no_output_____" ] ], [ [ "For convenience during training we’ll make a `randomTrainingExample` function that fetches a random (category, line) pair and turns them into the required (category, input, target) tensors.", "_____no_output_____" ] ], [ [ "# Make category, input, and target tensors from a random category, line pair\ndef randomTrainingExample():\n category, line = randomTrainingPair()\n category_t = category_tensor(category)\n input_line_tensor = input_tensor(line)\n target_line_tensor = target_tensor(line)\n return category_t, input_line_tensor, target_line_tensor\n", "_____no_output_____" ] ], [ [ "### Training the Network\n\nIn contrast to classification, where only the last output is used, we are making a prediction at every step, so we are calculating loss at every step.\n\nThe magic of autograd allows you to simply sum these losses at each step and call backward at the end.", "_____no_output_____" ] ], [ [ "criterion = nn.NLLLoss()\n\nlearning_rate = 0.0005\n\ndef train(category_tensor, input_line_tensor, target_line_tensor):\n target_line_tensor.unsqueeze_(-1)\n hidden = rnn.initHidden()\n rnn.zero_grad()\n loss = 0\n for i in range(input_line_tensor.size(0)):\n output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)\n l = criterion(output, target_line_tensor[i])\n loss += l\n loss.backward()\n\n for p in rnn.parameters():\n p.data.add_(p.grad.data, alpha=-learning_rate)\n \n return output, loss.item() / input_line_tensor.size(0)", "_____no_output_____" ] ], [ [ "To keep track of how long training takes I am adding a `time_since(timestamp)` function which returns a human readable string:", "_____no_output_____" ] ], [ [ "import time, math\n\ndef time_since(since):\n now = time.time()\n s = now - since\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)", "_____no_output_____" ] ], [ [ "Training is business as usual - call train a bunch of times and wait a few minutes, printing the current time and loss every `print_every` examples, and keeping store of an average loss per `plot_every` examples in `all_losses` for plotting later.", "_____no_output_____" ] ], [ [ "rnn = RNN(n_letters, 128, n_letters)\n\nn_iters = 100000\nprint_every = 5000\nplot_every = 500\nall_losses = []\ntotal_loss = 0 # Reset every plot_every iters\n\nstart = time.time()\n\nfor iter in range(1, n_iters + 1):\n output, loss = train(*randomTrainingExample())\n total_loss += loss\n\n if iter % print_every == 0:\n print('%s (%d %d%%) %.4f' % (time_since(start), iter, iter / n_iters * 100, loss))\n\n if iter % plot_every == 0:\n all_losses.append(total_loss / plot_every)\n total_loss = 0\n", "0m 17s (5000 5%) 3.5449\n0m 34s (10000 10%) 3.2120\n0m 52s (15000 15%) 2.6916\n1m 9s (20000 20%) 2.8286\n1m 26s (25000 25%) 2.5112\n1m 43s (30000 30%) 3.1578\n2m 1s (35000 35%) 2.6247\n2m 18s (40000 40%) 1.9059\n2m 36s (45000 45%) 3.0486\n2m 53s (50000 50%) 2.4448\n3m 11s (55000 55%) 2.7774\n3m 28s (60000 60%) 2.7981\n3m 45s (65000 65%) 2.1292\n4m 2s (70000 70%) 3.0557\n4m 20s (75000 75%) 3.0763\n4m 37s (80000 80%) 1.8526\n4m 55s (85000 85%) 2.0696\n5m 12s (90000 90%) 1.4502\n5m 30s (95000 95%) 2.7539\n5m 47s (100000 100%) 2.1774\n" ] ], [ [ "### Plotting the losses\n\n* Plotting the historical loss from all_losses shows the network learning:", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\nplt.figure()\nplt.plot(all_losses)\nplt.show()", "_____no_output_____" ] ], [ [ "#### Sampling the network\n\nTo sample we give the network a letter and ask what the next one is, feed that in as the next letter, and repeat until the `EOS` token.\n\n* Create tensors for input category, starting letter, and empty hidden state\n* Create a string output_name with the starting letter\n* Up to a maximum output length,\n * Feed the current letter to the network\n * Get the next letter from highest output, and next hidden state\n * If the letter is EOS, stop here\n * If a regular letter, add to output_name and continue\n* Return the final name\n\n\n> Rather than having to give it a starting letter, another strategy would have been to include a “start of string” token in training and have the network choose its own starting letter.", "_____no_output_____" ] ], [ [ "max_length = 20\n\n# Sample from a category and starting letter\ndef sample(category, start_letter='A'):\n with torch.no_grad(): # no need to track history in sampling\n category_t = category_tensor(category)\n input = input_tensor(start_letter)\n hidden = rnn.initHidden()\n\n output_name = start_letter\n\n for i in range(max_length):\n output, hidden = rnn(category_t, input[0], hidden)\n topv, topi = output.topk(1)\n topi = topi[0][0]\n if topi == n_letters - 1: #eos\n break\n else:\n letter = all_letters[topi]\n output_name += letter\n input = input_tensor(letter)\n\n return output_name\n\n# Get multiple samples from one category and multiple starting letters\ndef samples(category, start_letters='ABC'):\n for start_letter in start_letters:\n print(sample(category, start_letter))\n\nsamples('Russian', 'RUS')\n", "Rovell\nUakin\nShillin\n" ], [ "samples('German', 'GER')", "Gerte\nEren\nRour\n" ], [ "samples('Spanish', 'SPA')\n", "Saler\nPalla\nAlan\n" ], [ "samples('Chinese', 'CHI')", "Cha\nHan\nIan\n" ] ], [ [ "### Ref\n\n* [pytorch tutorial](https://pytorch.org/tutorials/intermediate/char_rnn_generation_tutorial.html)\n* [Understanding LSTM Networks](https://colah.github.io/posts/2015-08-Understanding-LSTMs/)\n* [The Unreasonable Effectiveness of Recurrent Neural Networks](https://karpathy.github.io/2015/05/21/rnn-effectiveness/)", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cbde0ce8e1e7c593d75d9270e91e8ea23545d1d3
527,321
ipynb
Jupyter Notebook
Task 5.ipynb
ShashankVSonar/Data-Science-and-Business-Analytics-The-Sparks-Foundation
db6e8d42ac113a5d912caa451106c6f1edcc8e93
[ "MIT" ]
1
2021-05-17T18:58:10.000Z
2021-05-17T18:58:10.000Z
Task 5.ipynb
ShashankVSonar/Graduate-Rotational-Internship-Program-The-Sparks-Foundation
db6e8d42ac113a5d912caa451106c6f1edcc8e93
[ "MIT" ]
null
null
null
Task 5.ipynb
ShashankVSonar/Graduate-Rotational-Internship-Program-The-Sparks-Foundation
db6e8d42ac113a5d912caa451106c6f1edcc8e93
[ "MIT" ]
1
2021-07-22T06:24:48.000Z
2021-07-22T06:24:48.000Z
75.895366
32,340
0.698112
[ [ [ "# Shashank V. Sonar", "_____no_output_____" ], [ "## Task 5: Exploratory Data Analysis - Sports", "_____no_output_____" ], [ "### Step -1: Importing the required Libraries ", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\n%matplotlib inline\nfrom sklearn.cluster import KMeans\nfrom sklearn import datasets\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport os\nimport mpl_toolkits\nimport json\nprint('Libraries are imported Successfully')", "Libraries are imported Successfully\n" ] ], [ [ "### Step-2: Importing the dataset\n", "_____no_output_____" ] ], [ [ "#Reading deliveries dataset\ndf_deliveries=pd.read_csv('C:/Users/91814/Desktop/GRIP/Task 5/ipl/deliveries.csv',low_memory=False)\nprint('Data Read Successfully')", "Data Read Successfully\n" ], [ "#Displaying the deliveries dataset\ndf_deliveries\n", "_____no_output_____" ], [ "#reading matches dataset\ndf_matches=pd.read_csv('C:/Users/91814/Desktop/GRIP/Task 5/ipl/df_matches.csv',low_memory=False)\nprint('Data Read Successfully')", "Data Read Successfully\n" ], [ "#displaying matches dataset\ndf_matches", "_____no_output_____" ] ], [ [ "### Step-3 Pre processing of Data", "_____no_output_____" ] ], [ [ "#displaying the first five rows of the matches dataset\ndf_matches.head()", "_____no_output_____" ], [ "df_matches.tail()#displaying the last five rows of the matches dataset", "_____no_output_____" ], [ "df_matches['team1'].unique() #displaying team 1", "_____no_output_____" ], [ "df_matches['team2'].unique() #displaying team 2", "_____no_output_____" ], [ "df_deliveries['batting_team'].unique() #displaying the batting team", "_____no_output_____" ], [ "df_deliveries['bowling_team'].unique() #displaying the bowling team", "_____no_output_____" ], [ "#replacing with short team names in matches dataset\ndf_matches.replace(['Royal Challengers Bangalore', 'Sunrisers Hyderabad',\n 'Rising Pune Supergiant', 'Mumbai Indians',\n 'Kolkata Knight Riders', 'Gujarat Lions', 'Kings XI Punjab',\n 'Delhi Daredevils', 'Chennai Super Kings', 'Rajasthan Royals',\n 'Deccan Chargers', 'Kochi Tuskers Kerala', 'Pune Warriors',\n 'Rising Pune Supergiants', 'Delhi Capitals'], ['RCB', 'SRH', 'PW', 'MI', 'KKR', 'GL', 'KXIP', 'DD','CSK','RR', 'DC', 'KTK','PW','RPS','DC'],inplace =True)", "_____no_output_____" ], [ "#replacing with short team names in deliveries dataset\n\ndf_deliveries.replace(['Royal Challengers Bangalore', 'Sunrisers Hyderabad',\n 'Rising Pune Supergiant', 'Mumbai Indians',\n 'Kolkata Knight Riders', 'Gujarat Lions', 'Kings XI Punjab',\n 'Delhi Daredevils', 'Chennai Super Kings', 'Rajasthan Royals',\n 'Deccan Chargers', 'Kochi Tuskers Kerala', 'Pune Warriors',\n 'Rising Pune Supergiants', 'Delhi Capitals'], ['RCB', 'SRH', 'PW', 'MI', 'KKR', 'GL', 'KXIP', 'DD','CSK','RR', 'DC', 'KTK','PW','RPS','DC'],inplace =True)", "_____no_output_____" ], [ "print('Total Matches played:',df_matches.shape[0])\nprint('\\n Venues played at:', df_matches['city'].unique())\nprint('\\n Teams:', df_matches['team1'].unique)", "Total Matches played: 756\n\n Venues played at: ['Hyderabad' 'Pune' 'Rajkot' 'Indore' 'Bangalore' 'Mumbai' 'Kolkata'\n 'Delhi' 'Chandigarh' 'Kanpur' 'Jaipur' 'Chennai' 'Cape Town'\n 'Port Elizabeth' 'Durban' 'Centurion' 'East London' 'Johannesburg'\n 'Kimberley' 'Bloemfontein' 'Ahmedabad' 'Cuttack' 'Nagpur' 'Dharamsala'\n 'Kochi' 'Visakhapatnam' 'Raipur' 'Ranchi' 'Abu Dhabi' 'Sharjah' nan\n 'Mohali' 'Bengaluru']\n\n Teams: <bound method Series.unique of 0 SRH\n1 MI\n2 GL\n3 PW\n4 RCB\n ... \n751 KKR\n752 CSK\n753 SRH\n754 DC\n755 MI\nName: team1, Length: 756, dtype: object>\n" ], [ "print('Total venues playes at:', df_matches['city'].nunique())\nprint('\\n Total umpires:', df_matches['umpire1'].nunique())", "Total venues playes at: 32\n\n Total umpires: 61\n" ], [ "print((df_matches['player_of_match'].value_counts()).idxmax(), ':has most man of the match awards')\nprint((df_matches['winner'].value_counts()).idxmax(), ':has the highest number of match wins')\n", "CH Gayle :has most man of the match awards\nMI :has the highest number of match wins\n" ], [ "df_matches.dtypes", "_____no_output_____" ], [ "df_matches.nunique()", "_____no_output_____" ] ], [ [ "### Full Data Summary", "_____no_output_____" ] ], [ [ "df_matches.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 756 entries, 0 to 755\nData columns (total 18 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 id 756 non-null int64 \n 1 season 756 non-null int64 \n 2 city 749 non-null object\n 3 date 756 non-null object\n 4 team1 756 non-null object\n 5 team2 756 non-null object\n 6 toss_winner 756 non-null object\n 7 toss_decision 756 non-null object\n 8 result 756 non-null object\n 9 dl_applied 756 non-null int64 \n 10 winner 752 non-null object\n 11 win_by_runs 756 non-null int64 \n 12 win_by_wickets 756 non-null int64 \n 13 player_of_match 752 non-null object\n 14 venue 756 non-null object\n 15 umpire1 754 non-null object\n 16 umpire2 754 non-null object\n 17 umpire3 119 non-null object\ndtypes: int64(5), object(13)\nmemory usage: 106.4+ KB\n" ] ], [ [ "### Statistical Summary of Data", "_____no_output_____" ] ], [ [ "df_matches.describe()", "_____no_output_____" ] ], [ [ "### Observations", "_____no_output_____" ] ], [ [ "# The .csv file has data of ipl matches starting from the season 2008 to 2019.\n# The biggest margin of victory for the team batting first(win by runs) is 146.\n# The biggest victory of the team batting second(win by wickets) is by 10 Wickets.\n# 75% of the victorious teams that bat first won by the margin of 19 runs.\n# 75% of the victorious teams that bat second won by a margin of 6 Wickets.\n# There were 756 Ipl matches hosted from 2008 to 2019.", "_____no_output_____" ] ], [ [ "### Columns in the data", "_____no_output_____" ] ], [ [ "df_matches.columns", "_____no_output_____" ] ], [ [ "### Getting Unique values of each column", "_____no_output_____" ] ], [ [ "for col in df_matches:\n print(df_matches[col].unique())", "[ 1 2 3 4 5 6 7 8 9 10 11 12\n 13 14 15 16 17 18 19 20 21 22 23 24\n 25 26 27 28 29 30 31 32 33 34 35 36\n 37 38 39 40 41 42 43 44 45 46 47 48\n 49 50 51 52 53 54 55 56 57 58 59 60\n 61 62 63 64 65 66 67 68 69 70 71 72\n 73 74 75 76 77 78 79 80 81 82 83 84\n 85 86 87 88 89 90 91 92 93 94 95 96\n 97 98 99 100 101 102 103 104 105 106 107 108\n 109 110 111 112 113 114 115 116 117 118 119 120\n 121 122 123 124 125 126 127 128 129 130 131 132\n 133 134 135 136 137 138 139 140 141 142 143 144\n 145 146 147 148 149 150 151 152 153 154 155 156\n 157 158 159 160 161 162 163 164 165 166 167 168\n 169 170 171 172 173 174 175 176 177 178 179 180\n 181 182 183 184 185 186 187 188 189 190 191 192\n 193 194 195 196 197 198 199 200 201 202 203 204\n 205 206 207 208 209 210 211 212 213 214 215 216\n 217 218 219 220 221 222 223 224 225 226 227 228\n 229 230 231 232 233 234 235 236 237 238 239 240\n 241 242 243 244 245 246 247 248 249 250 251 252\n 253 254 255 256 257 258 259 260 261 262 263 264\n 265 266 267 268 269 270 271 272 273 274 275 276\n 277 278 279 280 281 282 283 284 285 286 287 288\n 289 290 291 292 293 294 295 296 297 298 299 300\n 301 302 303 304 305 306 307 308 309 310 311 312\n 313 314 315 316 317 318 319 320 321 322 323 324\n 325 326 327 328 329 330 331 332 333 334 335 336\n 337 338 339 340 341 342 343 344 345 346 347 348\n 349 350 351 352 353 354 355 356 357 358 359 360\n 361 362 363 364 365 366 367 368 369 370 371 372\n 373 374 375 376 377 378 379 380 381 382 383 384\n 385 386 387 388 389 390 391 392 393 394 395 396\n 397 398 399 400 401 402 403 404 405 406 407 408\n 409 410 411 412 413 414 415 416 417 418 419 420\n 421 422 423 424 425 426 427 428 429 430 431 432\n 433 434 435 436 437 438 439 440 441 442 443 444\n 445 446 447 448 449 450 451 452 453 454 455 456\n 457 458 459 460 461 462 463 464 465 466 467 468\n 469 470 471 472 473 474 475 476 477 478 479 480\n 481 482 483 484 485 486 487 488 489 490 491 492\n 493 494 495 496 497 498 499 500 501 502 503 504\n 505 506 507 508 509 510 511 512 513 514 515 516\n 517 518 519 520 521 522 523 524 525 526 527 528\n 529 530 531 532 533 534 535 536 537 538 539 540\n 541 542 543 544 545 546 547 548 549 550 551 552\n 553 554 555 556 557 558 559 560 561 562 563 564\n 565 566 567 568 569 570 571 572 573 574 575 576\n 577 578 579 580 581 582 583 584 585 586 587 588\n 589 590 591 592 593 594 595 596 597 598 599 600\n 601 602 603 604 605 606 607 608 609 610 611 612\n 613 614 615 616 617 618 619 620 621 622 623 624\n 625 626 627 628 629 630 631 632 633 634 635 636\n 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905\n 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917\n 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929\n 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941\n 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953\n 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148\n 11149 11150 11151 11152 11153 11309 11310 11311 11312 11313 11314 11315\n 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327\n 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339\n 11340 11341 11342 11343 11344 11345 11346 11347 11412 11413 11414 11415]\n[2017 2008 2009 2010 2011 2012 2013 2014 2015 2016 2018 2019]\n['Hyderabad' 'Pune' 'Rajkot' 'Indore' 'Bangalore' 'Mumbai' 'Kolkata'\n 'Delhi' 'Chandigarh' 'Kanpur' 'Jaipur' 'Chennai' 'Cape Town'\n 'Port Elizabeth' 'Durban' 'Centurion' 'East London' 'Johannesburg'\n 'Kimberley' 'Bloemfontein' 'Ahmedabad' 'Cuttack' 'Nagpur' 'Dharamsala'\n 'Kochi' 'Visakhapatnam' 'Raipur' 'Ranchi' 'Abu Dhabi' 'Sharjah' nan\n 'Mohali' 'Bengaluru']\n['2017-04-05' '2017-04-06' '2017-04-07' '2017-04-08' '2017-04-09'\n '2017-04-10' '2017-04-11' '2017-04-12' '2017-04-13' '2017-04-14'\n '2017-04-15' '2017-04-16' '2017-04-17' '2017-04-18' '2017-04-19'\n '2017-04-20' '2017-04-21' '2017-04-22' '2017-04-23' '2017-04-24'\n '2017-04-26' '2017-04-27' '2017-04-28' '2017-04-29' '2017-04-30'\n '2017-05-01' '2017-05-02' '2017-05-03' '2017-05-04' '2017-05-05'\n '2017-05-06' '2017-05-07' '2017-05-08' '2017-05-09' '2017-05-10'\n '2017-05-11' '2017-05-12' '2017-05-13' '2017-05-14' '2017-05-16'\n '2017-05-17' '2017-05-19' '2017-05-21' '2008-04-18' '2008-04-19'\n '2008-04-20' '2008-04-21' '2008-04-22' '2008-04-23' '2008-04-24'\n '2008-04-25' '2008-04-26' '2008-04-27' '2008-04-28' '2008-04-29'\n '2008-04-30' '2008-05-01' '2008-05-02' '2008-05-25' '2008-05-03'\n '2008-05-04' '2008-05-05' '2008-05-06' '2008-05-07' '2008-05-08'\n '2008-05-09' '2008-05-28' '2008-05-10' '2008-05-11' '2008-05-12'\n '2008-05-13' '2008-05-14' '2008-05-15' '2008-05-16' '2008-05-17'\n '2008-05-18' '2008-05-19' '2008-05-20' '2008-05-21' '2008-05-23'\n '2008-05-24' '2008-05-26' '2008-05-27' '2008-05-30' '2008-05-31'\n '2008-06-01' '2009-04-18' '2009-04-19' '2009-04-20' '2009-04-21'\n '2009-04-22' '2009-04-23' '2009-04-24' '2009-04-25' '2009-04-26'\n '2009-04-27' '2009-04-28' '2009-04-29' '2009-04-30' '2009-05-01'\n '2009-05-02' '2009-05-03' '2009-05-04' '2009-05-05' '2009-05-06'\n '2009-05-07' '2009-05-08' '2009-05-09' '2009-05-10' '2009-05-11'\n '2009-05-12' '2009-05-13' '2009-05-14' '2009-05-15' '2009-05-16'\n '2009-05-17' '2009-05-18' '2009-05-19' '2009-05-20' '2009-05-21'\n '2009-05-22' '2009-05-23' '2009-05-24' '2010-03-12' '2010-03-13'\n '2010-03-14' '2010-03-15' '2010-03-16' '2010-03-17' '2010-03-18'\n '2010-03-19' '2010-03-20' '2010-03-21' '2010-03-22' '2010-03-23'\n '2010-03-24' '2010-03-25' '2010-03-26' '2010-03-27' '2010-03-28'\n '2010-03-29' '2010-03-30' '2010-03-31' '2010-04-01' '2010-04-02'\n '2010-04-03' '2010-04-04' '2010-04-05' '2010-04-06' '2010-04-07'\n '2010-04-08' '2010-04-09' '2010-04-10' '2010-04-11' '2010-04-12'\n '2010-04-13' '2010-04-14' '2010-04-15' '2010-04-16' '2010-04-17'\n '2010-04-18' '2010-04-19' '2010-04-21' '2010-04-22' '2010-04-24'\n '2010-04-25' '2011-04-08' '2011-04-09' '2011-04-10' '2011-04-11'\n '2011-04-12' '2011-04-13' '2011-04-14' '2011-04-15' '2011-04-16'\n '2011-04-17' '2011-04-18' '2011-04-19' '2011-04-20' '2011-04-21'\n '2011-04-22' '2011-04-23' '2011-04-24' '2011-04-25' '2011-04-26'\n '2011-04-27' '2011-04-28' '2011-04-29' '2011-04-30' '2011-05-01'\n '2011-05-02' '2011-05-03' '2011-05-04' '2011-05-05' '2011-05-06'\n '2011-05-07' '2011-05-08' '2011-05-09' '2011-05-10' '2011-05-11'\n '2011-05-12' '2011-05-13' '2011-05-14' '2011-05-15' '2011-05-16'\n '2011-05-17' '2011-05-18' '2011-05-19' '2011-05-20' '2011-05-21'\n '2011-05-22' '2011-05-24' '2011-05-25' '2011-05-27' '2011-05-28'\n '2012-04-04' '2012-04-05' '2012-04-06' '2012-04-07' '2012-04-08'\n '2012-04-09' '2012-04-10' '2012-04-11' '2012-04-12' '2012-04-13'\n '2012-04-19' '2012-04-14' '2012-04-15' '2012-04-16' '2012-04-17'\n '2012-04-18' '2012-05-10' '2012-04-20' '2012-04-21' '2012-04-22'\n '2012-04-23' '2012-04-24' '2012-04-25' '2012-04-26' '2012-04-27'\n '2012-04-28' '2012-04-29' '2012-04-30' '2012-05-01' '2012-05-02'\n '2012-05-03' '2012-05-04' '2012-05-05' '2012-05-06' '2012-05-07'\n '2012-05-08' '2012-05-09' '2012-05-11' '2012-05-12' '2012-05-13'\n '2012-05-14' '2012-05-15' '2012-05-16' '2012-05-17' '2012-05-18'\n '2012-05-19' '2012-05-20' '2012-05-22' '2012-05-23' '2012-05-25'\n '2012-05-27' '2013-04-03' '2013-04-04' '2013-04-05' '2013-04-06'\n '2013-04-07' '2013-04-08' '2013-04-09' '2013-04-10' '2013-04-11'\n '2013-04-12' '2013-04-13' '2013-04-14' '2013-04-15' '2013-04-16'\n '2013-04-17' '2013-04-18' '2013-04-19' '2013-04-20' '2013-04-21'\n '2013-04-22' '2013-04-23' '2013-05-16' '2013-04-24' '2013-04-25'\n '2013-04-26' '2013-04-27' '2013-04-28' '2013-04-29' '2013-04-30'\n '2013-05-01' '2013-05-02' '2013-05-03' '2013-05-04' '2013-05-14'\n '2013-05-05' '2013-05-07' '2013-05-08' '2013-05-09' '2013-05-10'\n '2013-05-11' '2013-05-12' '2013-05-13' '2013-05-15' '2013-05-06'\n '2013-05-17' '2013-05-18' '2013-05-19' '2013-05-21' '2013-05-22'\n '2013-05-24' '2013-05-26' '2014-04-16' '2014-04-17' '2014-04-18'\n '2014-04-19' '2014-04-20' '2014-04-21' '2014-04-22' '2014-04-23'\n '2014-04-24' '2014-04-25' '2014-04-26' '2014-04-27' '2014-04-28'\n '2014-04-29' '2014-04-30' '2014-05-02' '2014-05-03' '2014-05-04'\n '2014-05-05' '2014-05-06' '2014-05-07' '2014-05-08' '2014-05-09'\n '2014-05-10' '2014-05-11' '2014-05-12' '2014-05-13' '2014-05-14'\n '2014-05-15' '2014-05-18' '2014-05-19' '2014-05-20' '2014-05-21'\n '2014-05-22' '2014-05-23' '2014-05-24' '2014-05-25' '2014-05-27'\n '2014-05-28' '2014-05-30' '2014-06-01' '2015-04-08' '2015-04-09'\n '2015-04-10' '2015-04-11' '2015-04-12' '2015-04-13' '2015-04-14'\n '2015-04-30' '2015-04-15' '2015-04-16' '2015-04-17' '2015-04-18'\n '2015-04-19' '2015-04-20' '2015-04-21' '2015-04-22' '2015-04-23'\n '2015-04-24' '2015-04-25' '2015-04-26' '2015-04-27' '2015-05-07'\n '2015-04-29' '2015-04-28' '2015-05-01' '2015-05-02' '2015-05-03'\n '2015-05-04' '2015-05-05' '2015-05-06' '2015-05-08' '2015-05-09'\n '2015-05-10' '2015-05-11' '2015-05-12' '2015-05-13' '2015-05-14'\n '2015-05-15' '2015-05-16' '2015-05-17' '2015-05-19' '2015-05-20'\n '2015-05-22' '2015-05-24' '2016-04-09' '2016-04-10' '2016-04-11'\n '2016-04-12' '2016-04-13' '2016-04-14' '2016-04-15' '2016-04-16'\n '2016-04-17' '2016-04-18' '2016-04-19' '2016-04-20' '2016-04-21'\n '2016-04-22' '2016-04-23' '2016-04-24' '2016-04-25' '2016-04-26'\n '2016-04-27' '2016-04-28' '2016-04-29' '2016-04-30' '2016-05-01'\n '2016-05-02' '2016-05-03' '2016-05-04' '2016-05-05' '2016-05-06'\n '2016-05-07' '2016-05-08' '2016-05-09' '2016-05-10' '2016-05-11'\n '2016-05-12' '2016-05-13' '2016-05-14' '2016-05-15' '2016-05-16'\n '2016-05-17' '2016-05-18' '2016-05-19' '2016-05-20' '2016-05-21'\n '2016-05-22' '2016-05-24' '2016-05-25' '2016-05-27' '2016-05-29'\n '07/04/18' '08/04/18' '09/04/18' '10/04/18' '11/04/18' '12/04/18'\n '13/04/18' '14/04/18' '15/04/18' '16/04/18' '17/04/18' '18/04/18'\n '19/04/18' '20/04/18' '21/04/18' '22/04/18' '23/04/18' '24/04/18'\n '25/04/18' '26/04/18' '27/04/18' '28/04/18' '29/04/18' '30/04/18'\n '01/05/18' '02/05/18' '03/05/18' '04/05/18' '05/05/18' '06/05/18'\n '07/05/18' '08/05/18' '09/05/18' '10/05/18' '11/05/18' '12/05/18'\n '13/05/18' '14/05/18' '15/05/18' '16/05/18' '17/05/18' '18/05/18'\n '19/05/18' '20/05/18' '22/05/18' '23/05/18' '25/05/18' '27/05/18'\n '23/03/19' '24/03/19' '25/03/19' '26/03/19' '27/03/19' '28/03/19'\n '29/03/19' '30/03/19' '31/03/19' '01/04/19' '02/04/19' '03/04/19'\n '04/04/19' '05/04/19' '06/04/19' '07/04/19' '08/04/19' '09/04/19'\n '10/04/19' '11/04/19' '12/04/19' '13/04/19' '14/04/19' '15/04/19'\n '16/04/19' '17/04/19' '18/04/19' '19/04/19' '20/04/19' '21/04/19'\n '22/04/19' '23/04/19' '24/04/19' '25/04/19' '26/04/19' '27/04/19'\n '28/04/19' '29/04/19' '30/04/19' '01/05/19' '02/05/19' '03/05/19'\n '04/05/19' '05/05/19' '07/05/19' '08/05/19' '10/05/19' '12/05/19']\n['SRH' 'MI' 'GL' 'PW' 'RCB' 'KKR' 'DD' 'KXIP' 'CSK' 'RR' 'DC' 'KTK' 'RPS']\n['RCB' 'PW' 'KKR' 'KXIP' 'DD' 'SRH' 'MI' 'GL' 'RR' 'CSK' 'DC' 'KTK' 'RPS']\n['RCB' 'PW' 'KKR' 'KXIP' 'SRH' 'MI' 'GL' 'DD' 'CSK' 'RR' 'DC' 'KTK' 'RPS']\n['field' 'bat']\n['normal' 'tie' 'no result']\n[0 1]\n['SRH' 'PW' 'KKR' 'KXIP' 'RCB' 'MI' 'DD' 'GL' 'CSK' 'RR' 'DC' 'KTK' nan\n 'RPS']\n[ 35 0 15 97 17 51 27 5 21 14 26 82 3 61 48 19 12 146\n 7 9 10 20 1 140 33 6 66 13 45 29 18 23 41 65 25 105\n 75 92 11 24 38 8 78 16 53 2 4 31 55 98 34 36 39 40\n 67 63 37 57 22 85 32 76 111 43 58 28 74 42 59 46 47 86\n 44 87 130 60 77 30 50 93 72 62 138 71 144 80 64 102 118]\n[ 0 7 10 6 9 4 8 5 2 3 1]\n['Yuvraj Singh' 'SPD Smith' 'CA Lynn' 'GJ Maxwell' 'KM Jadhav'\n 'Rashid Khan' 'N Rana' 'AR Patel' 'SV Samson' 'JJ Bumrah' 'SP Narine'\n 'KA Pollard' 'AJ Tye' 'RV Uthappa' 'CJ Anderson' 'BA Stokes'\n 'NM Coulter-Nile' 'B Kumar' 'CH Gayle' 'KS Williamson' 'JC Buttler'\n 'SK Raina' 'MJ McClenaghan' 'MS Dhoni' 'HM Amla' 'G Gambhir'\n 'LH Ferguson' 'KH Pandya' 'Sandeep Sharma' 'DA Warner' 'RG Sharma'\n 'Mohammed Shami' 'RA Tripathi' 'RR Pant' 'JD Unadkat' 'LMP Simmons'\n 'DR Smith' 'S Dhawan' 'MM Sharma' 'SS Iyer' 'WP Saha' 'KK Nair'\n 'Mohammed Siraj' 'AT Rayudu' 'HV Patel' 'Washington Sundar' 'KV Sharma'\n 'BB McCullum' 'MEK Hussey' 'MF Maharoof' 'MV Boucher' 'DJ Hussey'\n 'SR Watson' 'V Sehwag' 'ML Hayden' 'YK Pathan' 'KC Sangakkara' 'JDP Oram'\n 'AC Gilchrist' 'SM Katich' 'ST Jayasuriya' 'GD McGrath' 'SE Marsh'\n 'SA Asnodkar' 'R Vinay Kumar' 'IK Pathan' 'SM Pollock' 'Sohail Tanvir'\n 'S Sreesanth' 'A Nehra' 'SC Ganguly' 'CRD Fernando' 'L Balaji'\n 'Shoaib Akhtar' 'A Mishra' 'DPMD Jayawardene' 'GC Smith' 'DJ Bravo'\n 'M Ntini' 'SP Goswami' 'A Kumble' 'KD Karthik' 'JA Morkel' 'P Kumar'\n 'Umar Gul' 'SR Tendulkar' 'R Dravid' 'DL Vettori' 'RP Singh'\n 'M Muralitharan' 'AB de Villiers' 'RS Bopara' 'PP Ojha' 'TM Dilshan'\n 'HH Gibbs' 'DP Nannes' 'JP Duminy' 'SB Jakati' 'JH Kallis' 'A Singh'\n 'S Badrinath' 'LRPL Taylor' 'Harbhajan Singh' 'R Bhatia' 'SK Warne'\n 'B Lee' 'BJ Hodge' 'LR Shukla' 'MK Pandey' 'AD Mathews' 'MK Tiwary'\n 'WPUJC Vaas' 'A Symonds' 'AA Jhunjhunwala' 'J Theron' 'AC Voges'\n 'NV Ojha' 'SL Malinga' 'M Vijay' 'KP Pietersen' 'PD Collingwood'\n 'MJ Lumb' 'TL Suman' 'RJ Harris' 'PP Chawla' 'Harmeet Singh' 'R Ashwin'\n 'R McLaren' 'M Kartik' 'DE Bollinger' 'S Anirudha' 'SK Trivedi' 'SB Wagh'\n 'PC Valthaty' 'MD Mishra' 'DW Steyn' 'S Sohal' 'MM Patel' 'V Kohli'\n 'I Sharma' 'J Botha' 'Iqbal Abdulla' 'P Parameswaran' 'R Sharma'\n 'MR Marsh' 'BA Bhatt' 'S Aravind' nan 'JEC Franklin' 'RE Levi'\n 'AM Rahane' 'RA Jadeja' 'MN Samuels' 'M Morkel' 'F du Plessis'\n 'AD Mascarenhas' 'Shakib Al Hasan' 'JD Ryder' 'S Nadeem'\n 'KMDN Kulasekara' 'CL White' 'Mandeep Singh' 'P Negi' 'Azhar Mahmood'\n 'BW Hilfenhaus' 'A Chandila' 'UT Yadav' 'MS Bisla' 'M Vohra' 'GH Vihari'\n 'AJ Finch' 'JP Faulkner' 'MS Gony' 'DA Miller' 'DJG Sammy' 'MG Johnson'\n 'KK Cooper' 'PA Patel' 'AP Tare' 'LJ Wright' 'YS Chahal' 'PV Tambe'\n 'DJ Hooda' 'GJ Bailey' 'AD Russell' 'MA Agarwal' 'MA Starc' 'VR Aaron'\n 'TA Boult' 'EJG Morgan' 'HH Pandya' 'MC Henriques' 'Z Khan' 'Q de Kock'\n 'Mustafizur Rahman' 'SA Yadav' 'AB Dinda' 'CH Morris' 'CR Brathwaite'\n 'MP Stoinis' 'A Zampa' 'BCJ Cutting' 'KL Rahul' 'SW Billings' 'JJ Roy'\n 'B Stanlake' 'J Archer' 'AS Rajpoot' 'TG Southee' 'AS Yadav'\n 'M Ur Rahman' 'Ishan Kishan' 'Kuldeep Yadav' 'S Gopal' 'L Ngidi' 'P Shaw'\n 'J Bairstow' 'S Curran' 'A Joseph' 'K Rabada' 'H Gurney' 'DL Chahar'\n 'Imran Tahir' 'K Paul' 'K Ahmed' 'S Gill' 'S Hetmyer']\n['Rajiv Gandhi International Stadium, Uppal'\n 'Maharashtra Cricket Association Stadium'\n 'Saurashtra Cricket Association Stadium' 'Holkar Cricket Stadium'\n 'M Chinnaswamy Stadium' 'Wankhede Stadium' 'Eden Gardens'\n 'Feroz Shah Kotla' 'Punjab Cricket Association IS Bindra Stadium, Mohali'\n 'Green Park' 'Punjab Cricket Association Stadium, Mohali'\n 'Sawai Mansingh Stadium' 'MA Chidambaram Stadium, Chepauk'\n 'Dr DY Patil Sports Academy' 'Newlands' \"St George's Park\" 'Kingsmead'\n 'SuperSport Park' 'Buffalo Park' 'New Wanderers Stadium'\n 'De Beers Diamond Oval' 'OUTsurance Oval' 'Brabourne Stadium'\n 'Sardar Patel Stadium, Motera' 'Barabati Stadium'\n 'Vidarbha Cricket Association Stadium, Jamtha'\n 'Himachal Pradesh Cricket Association Stadium' 'Nehru Stadium'\n 'Dr. Y.S. Rajasekhara Reddy ACA-VDCA Cricket Stadium'\n 'Subrata Roy Sahara Stadium'\n 'Shaheed Veer Narayan Singh International Stadium'\n 'JSCA International Stadium Complex' 'Sheikh Zayed Stadium'\n 'Sharjah Cricket Stadium' 'Dubai International Cricket Stadium'\n 'M. A. Chidambaram Stadium' 'Feroz Shah Kotla Ground'\n 'M. Chinnaswamy Stadium' 'Rajiv Gandhi Intl. Cricket Stadium'\n 'IS Bindra Stadium' 'ACA-VDCA Stadium']\n['AY Dandekar' 'A Nand Kishore' 'Nitin Menon' 'AK Chaudhary' nan\n 'A Deshmukh' 'KN Ananthapadmanabhan' 'YC Barde' 'S Ravi' 'CB Gaffaney'\n 'M Erasmus' 'NJ Llong' 'CK Nandan' 'Asad Rauf' 'MR Benson' 'Aleem Dar'\n 'SJ Davis' 'BF Bowden' 'IL Howell' 'DJ Harper' 'RE Koertzen'\n 'BR Doctrove' 'AV Jayaprakash' 'BG Jerling' 'HDPK Dharmasena' 'S Asnani'\n 'GAV Baxter' 'SS Hazare' 'K Hariharan' 'SL Shastri' 'SK Tarapore'\n 'SJA Taufel' 'S Das' 'AM Saheba' 'PR Reiffel' 'JD Cloete' 'VA Kulkarni'\n 'BNJ Oxenford' 'C Shamshuddin' 'RK Illingworth' 'RM Deshpande'\n 'K Srinath' 'SD Fry' 'PG Pathak' 'K Bharatan' 'Chris Gaffaney'\n 'Rod Tucker' 'Nigel Llong' 'Anil Chaudhary' 'K Ananthapadmanabhan'\n 'O Nandan' 'A Nanda Kishore' 'Vineet Kulkarni' 'Bruce Oxenford'\n 'Marais Erasmus' 'Kumar Dharmasena' 'Anil Dandekar' 'Yeshwant Barde'\n 'Ian Gould' 'Ulhas Gandhe' 'Nanda Kishore' 'Sundaram Ravi']\n['NJ Llong' 'S Ravi' 'CK Nandan' 'C Shamshuddin' nan 'AK Chaudhary'\n 'Nitin Menon' 'A Deshmukh' 'VK Sharma' 'M Erasmus' 'CB Gaffaney'\n 'A Nand Kishore' 'RE Koertzen' 'SL Shastri' 'GA Pratapkumar' 'DJ Harper'\n 'K Hariharan' 'RB Tiffin' 'AM Saheba' 'MR Benson' 'IL Howell'\n 'AV Jayaprakash' 'I Shivram' 'BR Doctrove' 'BG Jerling' 'SJ Davis'\n 'SD Ranade' 'SJA Taufel' 'TH Wijewardene' 'SK Tarapore' 'HDPK Dharmasena'\n 'SS Hazare' 'PR Reiffel' 'AL Hill' 'RJ Tucker' 'VA Kulkarni' 'JD Cloete'\n 'BNJ Oxenford' 'S Asnani' 'S Das' 'K Srinath' 'Subroto Das'\n 'RK Illingworth' 'PG Pathak' 'K Srinivasan' 'SD Fry' 'A Nanda Kishore'\n 'K Ananthapadmanabhan' 'A.D Deshmukh' 'Vineet Kulkarni' 'Chris Gaffaney'\n 'Rod Tucker' 'Nigel Llong' 'Anil Chaudhary' 'O Nandan'\n 'Virender Kumar Sharma' 'Yeshwant Barde' 'Anil Dandekar'\n 'Kumar Dharmasena' 'KN Anantapadmanabhan' 'Ulhas Gandhe' 'Nanda Kishore'\n 'Bruce Oxenford' 'Nand Kishore' 'KN Ananthapadmanabhan' 'Ian Gould']\n[nan 'Anil Chaudhary' 'Nitin Menon' 'S Ravi' 'O Nandan' 'A Nanda Kishore'\n 'Vineet Kulkarni' 'C Shamshuddin' 'Rod Tucker' 'Chris Gaffaney'\n 'A.D Deshmukh' 'Nigel Llong' 'K Ananthapadmanabhan' 'Anil Dandekar'\n 'Virender Kumar Sharma' 'Yeshwant Barde' 'Bruce Oxenford'\n 'Marais Erasmus' 'Kumar Dharmasena' 'KN Anantapadmanabhan' 'Ulhas Gandhe'\n 'Nanda Kishore' 'Ian Gould' 'Sundaram Ravi' 'KN Ananthapadmanabhan'\n 'Chettithody Shamshuddin']\n" ] ], [ [ "### Finding out Null values in Each Columns", "_____no_output_____" ] ], [ [ "df_matches.isnull().sum()", "_____no_output_____" ] ], [ [ "### Dropping of Columns having significant number of Null values", "_____no_output_____" ] ], [ [ "df_matches1 =df_matches.drop(columns=['umpire3'], axis =1)", "_____no_output_____" ] ], [ [ "### Verification of Dropped Column", "_____no_output_____" ] ], [ [ "df_matches\n", "_____no_output_____" ], [ "df_matches.isnull().sum()", "_____no_output_____" ], [ "df_matches.fillna(0,inplace=True)", "_____no_output_____" ], [ "df_matches", "_____no_output_____" ], [ "df_matches.isnull().sum()", "_____no_output_____" ], [ "# We have successfully replace the Null values with 'Zeros'", "_____no_output_____" ], [ "df_deliveries.dtypes", "_____no_output_____" ], [ "df_deliveries.shape", "_____no_output_____" ], [ "df_deliveries.dtypes", "_____no_output_____" ], [ "df_deliveries.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 179078 entries, 0 to 179077\nData columns (total 21 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 match_id 179078 non-null int64 \n 1 inning 179078 non-null int64 \n 2 batting_team 179078 non-null object\n 3 bowling_team 179078 non-null object\n 4 over 179078 non-null int64 \n 5 ball 179078 non-null int64 \n 6 batsman 179078 non-null object\n 7 non_striker 179078 non-null object\n 8 bowler 179078 non-null object\n 9 is_super_over 179078 non-null int64 \n 10 wide_runs 179078 non-null int64 \n 11 bye_runs 179078 non-null int64 \n 12 legbye_runs 179078 non-null int64 \n 13 noball_runs 179078 non-null int64 \n 14 penalty_runs 179078 non-null int64 \n 15 batsman_runs 179078 non-null int64 \n 16 extra_runs 179078 non-null int64 \n 17 total_runs 179078 non-null int64 \n 18 player_dismissed 8834 non-null object\n 19 dismissal_kind 8834 non-null object\n 20 fielder 6448 non-null object\ndtypes: int64(13), object(8)\nmemory usage: 28.7+ MB\n" ], [ "df_deliveries.describe()", "_____no_output_____" ], [ "df_deliveries.columns", "_____no_output_____" ] ], [ [ "### Counting the Null Values in the data set", "_____no_output_____" ] ], [ [ "df_deliveries.isnull().sum()", "_____no_output_____" ] ], [ [ "### Total number of null values in the dataset", "_____no_output_____" ] ], [ [ "df_deliveries.isnull().sum().sum()", "_____no_output_____" ] ], [ [ "### Step - 4 Analysing the data", "_____no_output_____" ], [ "### Which Team had won by maximum runs?", "_____no_output_____" ] ], [ [ "df_matches.iloc[df_matches['win_by_runs'].idxmax()]", "_____no_output_____" ] ], [ [ "### Which Team had won by maximum wicket?", "_____no_output_____" ] ], [ [ "df_matches.iloc[df_matches['win_by_wickets'].idxmax()]", "_____no_output_____" ] ], [ [ "### Which Team had won by minimum Margin?", "_____no_output_____" ] ], [ [ "df_matches.iloc[df_matches[df_matches['win_by_runs'].ge(1)].win_by_runs.idxmin()]", "_____no_output_____" ] ], [ [ "### Which Team had won by Minimum Wickets?", "_____no_output_____" ] ], [ [ "df_matches.iloc[df_matches[df_matches['win_by_wickets'].ge(1)].win_by_wickets.idxmin()]", "_____no_output_____" ], [ "len(df_matches['season'].unique())", "_____no_output_____" ], [ "df_deliveries.fillna(0,inplace=True)", "_____no_output_____" ], [ "df_deliveries", "_____no_output_____" ], [ "df_deliveries.isnull().sum()", "_____no_output_____" ] ], [ [ "### The team with most number of Wins per season", "_____no_output_____" ] ], [ [ "teams_per_season =df_matches.groupby('season')['winner'].value_counts()", "_____no_output_____" ], [ "teams_per_season", "_____no_output_____" ], [ "\"\"\"\nfor i, w in wins_per_season.iteritmes():\n print(i, w)\nfor items in win_per_season.iteritems():\n print(items)\n\"\"\"\nyear = 2008\nwin_per_season_df_matches=pd.DataFrame(columns=['year', 'team', 'wins'])\nfor items in teams_per_season.iteritems():\n if items[0][0]==year:\n print(items)\n win_series =pd.DataFrame({\n 'year': [items[0][0]],\n 'team':[items[0][1]],\n 'wins':[items[1]]\n })\n win_per_season_df_matches = win_per_season_df_matches.append(win_series)\n year +=1\n \n \n", "((2008, 'RR'), 13)\n((2009, 'DD'), 10)\n((2010, 'MI'), 11)\n((2011, 'CSK'), 11)\n((2012, 'KKR'), 12)\n((2013, 'MI'), 13)\n((2014, 'KXIP'), 12)\n((2015, 'CSK'), 10)\n((2016, 'SRH'), 11)\n((2017, 'MI'), 12)\n((2018, 'CSK'), 11)\n((2019, 'MI'), 11)\n" ], [ "win_per_season_df_matches", "_____no_output_____" ] ], [ [ "### Step- 5 DATA Visualising", "_____no_output_____" ] ], [ [ "venue_ser=df_matches['venue'].value_counts()", "_____no_output_____" ], [ "venue_df_matches =pd.DataFrame(columns=['venue', 'matches'])\nfor items in venue_ser.iteritems():\n temp_df_matches =pd.DataFrame({\n 'venue':[items[0]],\n 'matches':[items[1]]\n })\n \n venue_df_matches = venue_df_matches.append(temp_df_matches,ignore_index=True)", "_____no_output_____" ] ], [ [ "### Ipl Venues", "_____no_output_____" ], [ "plt.title('Ipl Venues')\nsns.barplot(x='matches', y='venue', data =venue_df_matches);", "_____no_output_____" ], [ "### Number of Matches played and venue", "_____no_output_____" ] ], [ [ "venue_df_matches", "_____no_output_____" ] ], [ [ "### The most Successful IPL team", "_____no_output_____" ] ], [ [ "team_wins_ser= df_matches['winner'].value_counts()\nteam_wins_df_matches=pd.DataFrame(columns=['team', 'wins'])\nfor items in team_wins_ser.iteritems():\n temp_df1 =pd.DataFrame({\n 'team':[items[0]],\n 'wins':[items[1]]\n })\n team_wins_df_matches= team_wins_df_matches.append(temp_df1,ignore_index=True)", "_____no_output_____" ] ], [ [ "### Finding the most successful Ipl team\n", "_____no_output_____" ] ], [ [ "team_wins_df_matches", "_____no_output_____" ] ], [ [ "### IPL Victories by team", "_____no_output_____" ] ], [ [ "plt.title('Total victories of IPL Teams')\nsns.barplot(x='wins', y='team', data =team_wins_df_matches, palette ='ocean_r');", "_____no_output_____" ] ], [ [ "\n### Most valuable players", "_____no_output_____" ] ], [ [ "mpv_ser=df_matches['player_of_match'].value_counts()\n\nmvp_10_df_matches=pd.DataFrame(columns=['player','wins'])\ncount = 0\nfor items in mvp_ser.iteritems():\n if count>9:\n break\n else:\n temp_df2=pd.DataFrame({\n 'player':[items[0]],\n 'wins':[items[1]]\n })\n mvp_10_df_matches =mvp_10_df_matches.append(temp_df2,ignore_index=True)\n count += 1\n \n \n ", "_____no_output_____" ] ], [ [ "### Top 10 Most valuable players", "_____no_output_____" ] ], [ [ "mvp_10_df_matches", "_____no_output_____" ], [ "plt.title(\"Top IPL Player\")\nsns.barplot(x='wins', y='player', data =mvp_10_df_matches, palette ='cool')", "_____no_output_____" ] ], [ [ "### Team that won the most number of toss", "_____no_output_____" ] ], [ [ "toss_ser =df_matches['toss_winner'].value_counts()\ntoss_df_matches=pd.DataFrame(columns=['team','wins'])\n\nfor items in toss_ser.iteritems():\n temp_df3=pd.DataFrame({\n 'team':[items[0]],\n 'wins':[items[1]]\n })\n toss_df_matches = toss_df_matches.append(temp_df3,ignore_index=True)", "_____no_output_____" ] ], [ [ "### Count of Number of toss wins and teams", "_____no_output_____" ] ], [ [ "toss_df_matches", "_____no_output_____" ] ], [ [ "### Teams which has won More number of Toss", "_____no_output_____" ] ], [ [ "plt.title('Which team won more number of Toss')\nsns.barplot(x='wins', y='team', data=toss_df_matches, palette='Dark2')", "_____no_output_____" ] ], [ [ "### Observations\n", "_____no_output_____" ] ], [ [ "# Mumbai Indians has won the most toss(till 2019) in ipl history.\n", "_____no_output_____" ] ], [ [ "### Numbebr of Matches won by team", "_____no_output_____" ] ], [ [ "plt.figure(figsize = (18,10))\nsns.countplot(x='winner',data=df_matches, palette='cool')\nplt.title(\"Numbers of matches won by team \",fontsize=20)\nplt.xticks(rotation=50)\nplt.xlabel(\"Teams\",fontsize=15)\nplt.ylabel(\"No of wins\",fontsize=15)\nplt.show()", "_____no_output_____" ], [ "df_matches.result.value_counts()", "_____no_output_____" ], [ "plt.subplots(figsize=(10,6))\nsns.countplot(x='season', hue='toss_decision', data=df_matches)\nplt.show()", "_____no_output_____" ] ], [ [ "### Maximum Toss Winner", "_____no_output_____" ] ], [ [ "plt.subplots(figsize=(10,8))\nax=df_matches['toss_winner'].value_counts().plot.bar(width=0.9,color=sns.color_palette('RdYlGn', 20))\nfor p in ax.patches:\n ax.annotate(format(p.get_height()),(p.get_x()+0.15, p.get_height()+1))\nplt.show() \n \n \n \n ", "_____no_output_____" ] ], [ [ "### Matches played across each seasons", "_____no_output_____" ] ], [ [ "plt.subplots(figsize=(10,8))\nsns.countplot(x='season', data=df_matches,palette=sns.color_palette('winter'))\nplt.show()", "_____no_output_____" ] ], [ [ "### Top 10 Batsman from the dataset", "_____no_output_____" ] ], [ [ "plt.subplots(figsize=(10,6))\nmax_runs=df_deliveries.groupby(['batsman'])['batsman_runs'].sum()\nax=max_runs.sort_values(ascending=False)[:10].plot.bar(width=0.8,color=sns.color_palette('winter_r',20))\nfor p in ax.patches:\n ax.annotate(format(p.get_height()),(p.get_x()+0.1, p.get_height()+50),fontsize=15)\nplt.show()", "_____no_output_____" ] ], [ [ "### Number of matches won by Toss winning side", "_____no_output_____" ] ], [ [ "plt.figure(figsize = (18,10))\nsns.countplot('season',hue='toss_winner',data=df_matches,palette='hsv')\nplt.title(\"Numbers of matches won by batting and bowling first \",fontsize=20)\nplt.xlabel(\"season\",fontsize=15)\nplt.ylabel(\"Count\",fontsize=15)\nplt.show()", "_____no_output_____" ], [ "df_matches", "_____no_output_____" ], [ "# we will print winner season wise\nfinal_matches=df_matches.drop_duplicates(subset=['season'], keep='last')\n\nfinal_matches[['season','winner']].reset_index(drop=True).sort_values('season')", "_____no_output_____" ], [ "# we will print number of season won by teams\nfinal_matches[\"winner\"].value_counts()", "_____no_output_____" ], [ "# we will print toss winner, toss decision, winner in final matches.\nfinal_matches[['toss_winner','toss_decision','winner']].reset_index(drop=True)", "_____no_output_____" ], [ "# we will print man of the match\nfinal_matches[['winner','player_of_match']].reset_index(drop=True)", "_____no_output_____" ], [ "# we will print numbers of fours hit by team\nseason_data=df_matches[['id','season','winner']]\ncomplete_data=df_deliveries.merge(season_data,how='inner',left_on='match_id',right_on='id')\nfour_data=complete_data[complete_data['batsman_runs']==4]\nfour_data.groupby('batting_team')['batsman_runs'].agg([('runs by fours','sum'),('fours','count')])", "_____no_output_____" ], [ "Toss=final_matches.toss_decision.value_counts()\nlabels=np.array(Toss.index)\nsizes = Toss.values\ncolors = ['#FFBF00', '#FA8072']\nplt.figure(figsize = (10,8))\nplt.pie(sizes, labels=labels, colors=colors,\n autopct='%1.1f%%', shadow=True,startangle=90)\nplt.title('Toss Result', fontsize=20)\nplt.axis('equal')\nplt.show()", "_____no_output_____" ], [ "# we will plot graph on four hit by players\nbatsman_four=four_data.groupby('batsman')['batsman_runs'].agg([('four','count')]).reset_index().sort_values('four',ascending=0)\nax=batsman_four.iloc[:10,:].plot('batsman','four',kind='bar',color='black')\nplt.title(\"Numbers of fours hit by playes \",fontsize=20)\nplt.xticks(rotation=50)\nplt.xlabel(\"Player name\",fontsize=15)\nplt.ylabel(\"No of fours\",fontsize=15)\nplt.show()", "_____no_output_____" ], [ "# we will plot graph on no of four hit in each season\nax=four_data.groupby('season')['batsman_runs'].agg([('four','count')]).reset_index().plot('season','four',kind='bar',color = 'red')\nplt.title(\"Numbers of fours hit in each season \",fontsize=20)\nplt.xticks(rotation=50)\nplt.xlabel(\"season\",fontsize=15)\nplt.ylabel(\"No of fours\",fontsize=15)\nplt.show()", "_____no_output_____" ], [ "\n# we will print no of sixes hit by team\nsix_data=complete_data[complete_data['batsman_runs']==6]\nsix_data.groupby('batting_team')['batsman_runs'].agg([('runs by six','sum'),('sixes','count')])", "_____no_output_____" ], [ "# we will plot graph of six hit by players\nbatsman_six=six_data.groupby('batsman')['batsman_runs'].agg([('six','count')]).reset_index().sort_values('six',ascending=0)\nax=batsman_six.iloc[:10,:].plot('batsman','six',kind='bar',color='green')\nplt.title(\"Numbers of six hit by playes \",fontsize=20)\nplt.xticks(rotation=50)\nplt.xlabel(\"Player name\",fontsize=15)\nplt.ylabel(\"No of six\",fontsize=15)\nplt.show()", "_____no_output_____" ], [ "# we will plot graph on no of six hit in each season\nax=six_data.groupby('season')['batsman_runs'].agg([('six','count')]).reset_index().plot('season','six',kind='bar',color = 'blue')\nplt.title(\"Numbers of fours hit in each season \",fontsize=20)\nplt.xticks(rotation=50)\nplt.xlabel(\"season\",fontsize=15)\nplt.ylabel(\"No of fours\",fontsize=15)\nplt.show()", "_____no_output_____" ], [ "# we will print no of matches played by batsman\nNo_Matches_player= df_deliveries[[\"match_id\",\"player_dismissed\"]]\nNo_Matches_player =No_Matches_player .groupby(\"player_dismissed\")[\"match_id\"].count().reset_index().sort_values(by=\"match_id\",ascending=False).reset_index(drop=True)\nNo_Matches_player.columns=[\"batsman\",\"No_of Matches\"]\nNo_Matches_player .head(10)", "_____no_output_____" ], [ "# Dismissals in IPL\nplt.figure(figsize=(18,10))\nax=sns.countplot(df_deliveries.dismissal_kind)\nplt.title(\"Dismissals in IPL\",fontsize=20)\nplt.xlabel(\"Dismissals kind\",fontsize=15)\nplt.ylabel(\"count\",fontsize=15)\nplt.xticks(rotation=50)\nplt.show()", "_____no_output_____" ], [ "wicket_data=df_deliveries.dropna(subset=['dismissal_kind'])\nwicket_data=wicket_data[~wicket_data['dismissal_kind'].isin(['run out','retired hurt','obstructing the field'])]", "_____no_output_____" ], [ "# we will print ipl most wicket taking bowlers\nwicket_data.groupby('bowler')['dismissal_kind'].agg(['count']).reset_index().sort_values('count',ascending=False).reset_index(drop=True).iloc[:10,:]", "_____no_output_____" ] ], [ [ "### Conclusion :", "_____no_output_____" ], [ "The highest number of match played in IPL season was 2013,2014,2015.\n\nThe highest number of match won by Mumbai Indians i.e 4 match out of 12 matches.\n\nTeams which Bowl first has higher chances of winning then the team which bat first.\n\nAfter winning toss more teams decide to do fielding first.\n\nIn finals teams which decide to do fielding first win the matches more then the team which bat first.\n\nIn finals most teams after winning toss decide to do fielding first.\n\nTop player of match winning are CH gayle, AB de villers.\n\nIt is interesting that out of 12 IPL finals,9 times the team that won the toss was also the winner of IPL.\n\nThe highest number of four hit by player is Shikar Dhawan.\n\nThe highest number of six hit by player is CH gayle.\n\nTop leading run scorer in IPL are Virat kholi, SK Raina, RG Sharma.\n\nDismissals in IPL was most by Catch out.\n\nThe IPL most wicket taken blower is Harbajan Singh.\n\nThe highest number of matches played by player name are SK Raina, RG Sharma.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
cbde0e5b29e9175db86f5d74def6bf47af5effff
4,045
ipynb
Jupyter Notebook
00-Python Object and Data Structure Basics/01-VariableAssigments.ipynb
dglynn/python-bootcamp-udemy
649b73eefa1bedcbd40b387076bfe5fc6e15cb27
[ "MIT" ]
null
null
null
00-Python Object and Data Structure Basics/01-VariableAssigments.ipynb
dglynn/python-bootcamp-udemy
649b73eefa1bedcbd40b387076bfe5fc6e15cb27
[ "MIT" ]
null
null
null
00-Python Object and Data Structure Basics/01-VariableAssigments.ipynb
dglynn/python-bootcamp-udemy
649b73eefa1bedcbd40b387076bfe5fc6e15cb27
[ "MIT" ]
null
null
null
16.924686
102
0.454141
[ [ [ "# Variables\na = 5", "_____no_output_____" ], [ "a", "_____no_output_____" ], [ "# Reassign the variable\na = 10", "_____no_output_____" ], [ "a", "_____no_output_____" ], [ "# Add vars to gether\na + a", "_____no_output_____" ], [ "# Add add to itself, in a cell environement its keep adding to irlcef when run over and over\n# in .py it runs only once as its one line\na = a + a", "_____no_output_____" ], [ "# It keeps doubling all the time\na", "_____no_output_____" ], [ "# Inbuilt python function\n# Init signature: type(self, /, *args, **kwargs)\n# Docstring: \n# type(object_or_name, bases, dict)\n# type(object) -> the object's type\n# type(name, bases, dict) -> a new type\n# Type: type\ntype(a)", "_____no_output_____" ], [ "# resassign as float\na = 30.1", "_____no_output_____" ], [ "type(a)", "_____no_output_____" ], [ "# Speacial built in keywaord, you cant assign these as vars\n# int = 4", "_____no_output_____" ], [ "my_income = 100\n\ntax_rate = 0.1\n\nmy_taxes = my_income * tax_rate", "_____no_output_____" ], [ "my_taxes", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbde2cf7fda2d82705a352b1be05fa1c5373981e
143,035
ipynb
Jupyter Notebook
random_signals/independent.ipynb
davidjustin1974/digital-signal-processing-lecture
3959b6c929828b0e2b5ae440523d9adc43ea928c
[ "MIT" ]
2
2018-12-29T19:13:49.000Z
2020-05-25T09:53:21.000Z
random_signals/independent.ipynb
davidjustin1974/digital-signal-processing-lecture
3959b6c929828b0e2b5ae440523d9adc43ea928c
[ "MIT" ]
null
null
null
random_signals/independent.ipynb
davidjustin1974/digital-signal-processing-lecture
3959b6c929828b0e2b5ae440523d9adc43ea928c
[ "MIT" ]
3
2020-10-17T07:48:22.000Z
2022-03-17T06:28:58.000Z
394.035813
39,200
0.927277
[ [ [ "# Random Signals\n\n*This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [[email protected]](mailto:[email protected]).*", "_____no_output_____" ], [ "## Independent Processes\n\nThe independence of random signals is a desired property in many applications of statistical signal processing, as well as uncorrelatedness and orthogonality. The concept of independence is introduced in the following together with a discussion of the links to uncorrelatedness and orthogonality.", "_____no_output_____" ], [ "### Definition\n\nTwo stochastic events are said to be [independent](https://en.wikipedia.org/wiki/Independence_(probability_theory%29) if the probability of occurrence of one event is not affected by the occurrence of the other event. Or more specifically, if their joint probability equals the product of their individual probabilities. In terms of the bivariate probability density function (PDF) of two continuous-amplitude real-valued random processes $x[k]$ and $y[k]$ this reads\n\n\\begin{equation}\np_{xy}(\\theta_x, \\theta_y, k_x, k_y) = p_x(\\theta_x, k_x) \\cdot p_y(\\theta_y, k_y)\n\\end{equation}\n\nwhere $p_x(\\theta_x, k_x)$ and $p_y(\\theta_y, k_y)$ denote the univariate ([marginal](https://en.wikipedia.org/wiki/Marginal_distribution)) PDFs of the random processes for the time-instances $k_x$ and $k_y$, respectively. The bivariate PDF of two independent random processes is given by the multiplication of their univariate PDFs. It follows that the [second-order ensemble average](ensemble_averages.ipynb#Second-Order-Ensemble-Averages) for a linear mapping is given as\n\n\\begin{equation}\nE\\{ x[k_x] \\cdot y[k_y] \\} = E\\{ x[k_x] \\} \\cdot E\\{ y[k_y] \\}\n\\end{equation}\n\nThe linear second-order ensemble average of two independent random signals is equal to the multiplication of their linear first-order ensemble averages. For jointly wide-sense stationary (WSS) processes, the bivariate PDF does only depend on the difference $\\kappa = k_x - k_y$ of the time instants. Hence, two jointly WSS random signals are independent if \n\n\\begin{equation}\n\\begin{split}\np_{xy}(\\theta_x, \\theta_y, \\kappa) &= p_x(\\theta_x, k_x) \\cdot p_y(\\theta_y, k_x - \\kappa) \\\\\n&= p_x(\\theta_x) \\cdot p_y(\\theta_y, \\kappa)\n\\end{split}\n\\end{equation}\n\nAbove bivariate PDF is rewritten using the definition of [conditional probabilities](https://en.wikipedia.org/wiki/Conditional_probability) in order to specialize the definition of independence to one WSS random signal $x[k]$ \n\n\\begin{equation}\np_{xy}(\\theta_x, \\theta_y, \\kappa) = p_{y|x}(\\theta_x, \\theta_y, \\kappa) \\cdot p_x(\\theta_x)\n\\end{equation}\n\nwhere $p_{y|x}(\\theta_x, \\theta_y, \\kappa)$ denotes the conditional probability that $y[k - \\kappa]$ takes the amplitude value $\\theta_y$ under the condition that $x[k]$ takes the amplitude value $\\theta_x$. Under the assumption that $y[k-\\kappa] = x[k-\\kappa]$ and substituting $\\theta_x$ and $\\theta_y$ by $\\theta_1$ and $\\theta_2$, independence for one random signal is defined as\n\n\\begin{equation}\np_{xx}(\\theta_1, \\theta_2, \\kappa) = \n\\begin{cases}\np_x(\\theta_1) \\cdot \\delta(\\theta_2 - \\theta_1) & \\text{for } \\kappa = 0 \\\\\np_x(\\theta_1) \\cdot p_x(\\theta_2, \\kappa) & \\text{for } \\kappa \\neq 0\n\\end{cases}\n\\end{equation}\n\nsince the conditional probability $p_{x[k]|x[k-\\kappa]}(\\theta_1, \\theta_2, \\kappa) = \\delta(\\theta_2 - \\theta_1)$ for $\\kappa = 0$ since this represents a sure event. The bivariate PDF of an independent random signal is equal to the product of the univariate PDFs of the signal and the time-shifted signal for $\\kappa \\neq 0$. A random signal for which this condition does not hold shows statistical dependencies between samples. These dependencies can be exploited for instance for coding or prediction.", "_____no_output_____" ], [ "#### Example - Comparison of bivariate PDF and product of marginal PDFs\n\nThe following example estimates the bivariate PDF $p_{xx}(\\theta_1, \\theta_2, \\kappa)$ of a WSS random signal $x[k]$ by computing its two-dimensional histogram. The univariate PDFs $p_x(\\theta_1)$ and $p_x(\\theta_2, \\kappa)$ are additionally estimated. Both the estimated bivariate PDF and the product of the two univariate PDFs $p_x(\\theta_1) \\cdot p_x(\\theta_2, \\kappa)$ are plotted for different $\\kappa$.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nN = 10000000 # number of random samles\nM = 50 # number of bins for bivariate/marginal histograms\n\n\ndef compute_plot_histograms(kappa):\n # shift signal\n x2 = np.concatenate((x1[kappa:], np.zeros(kappa)))\n\n # compute bivariate and marginal histograms\n pdf_xx, x1edges, x2edges = np.histogram2d(x1, x2, bins=(M,M), range=((-1.5, 1.5),(-1.5, 1.5)), normed=True)\n pdf_x1, _ = np.histogram(x1, bins=M, range=(-1.5, 1.5), density=True)\n pdf_x2, _ = np.histogram(x2, bins=M, range=(-1.5, 1.5), density=True)\n\n # plot results\n fig = plt.figure(figsize=(10, 10))\n \n plt.subplot(121, aspect='equal')\n plt.pcolormesh(x1edges, x2edges, pdf_xx)\n plt.xlabel(r'$\\theta_1$')\n plt.ylabel(r'$\\theta_2$')\n plt.title(r'Bivariate PDF $p_{{xy}}(\\theta_1, \\theta_2, \\kappa)$')\n plt.colorbar(fraction=0.046)\n\n plt.subplot(122, aspect='equal')\n plt.pcolormesh(x1edges, x2edges, np.outer(pdf_x1, pdf_x2))\n plt.xlabel(r'$\\theta_1$')\n plt.ylabel(r'$\\theta_2$')\n plt.title(r'Product of PDFs $p_x(\\theta_1) \\cdot p_x(\\theta_2, \\kappa)$')\n plt.colorbar(fraction=0.046)\n \n fig.suptitle('Shift $\\kappa =$ {:<2.0f}'.format(kappa), y=0.72)\n fig.tight_layout()\n\n\n# generate signal\nx = np.random.normal(size=N)\nx1 = np.convolve(x, [1, .5, .3, .7, .3], mode='same')\n\n# compute and plot the PDFs for various shifts\ncompute_plot_histograms(0)\ncompute_plot_histograms(2)\ncompute_plot_histograms(20)", "_____no_output_____" ] ], [ [ "**Exercise**\n\n* With the given results, how can you evaluate the independence of the random signal?\n* Can the random signal assumed to be independent?\n\nSolution: According to the definition of independence, the bivariate PDF and the product of the univariate PDFs has to be equal for $\\kappa \\neq 0$. This is obviously not the case for $\\kappa=2$. Hence, the random signal is not independent in a strict sense. However for $\\kappa=20$ the condition for independence is sufficiently fulfilled, considering the statistical uncertainty due to a finite number of samples. ", "_____no_output_____" ], [ "### Independence versus Uncorrelatedness \n\nTwo continuous-amplitude real-valued jointly WSS random processes $x[k]$ and $y[k]$ are termed as [uncorrelated](correlation_functions.ipynb#Properties) if their cross-correlation function (CCF) is equal to the product of their linear means, $\\varphi_{xy}[\\kappa] = \\mu_x \\cdot \\mu_y$. If two random signals are independent then they are also uncorrelated. This can be proven by introducing above findings for the linear second-order ensemble average of independent random signals into the definition of the CCF\n\n\\begin{equation}\n\\varphi_{xy}[\\kappa] = E \\{ x[k] \\cdot y[k - \\kappa] \\} = E \\{ x[k] \\} \\cdot E \\{ y[k - \\kappa] \\} = \\mu_x \\cdot \\mu_y\n\\end{equation}\n\nwhere the last equality is a consequence of the assumed wide-sense stationarity. The reverse, that two uncorrelated signals are also independent does not hold in general from this result.\n\nThe auto-correlation function (ACF) of an [uncorrelated signal](correlation_functions.ipynb#Properties) is given as $\\varphi_{xx}[\\kappa] = \\mu_x^2 + \\sigma_x^2 \\cdot \\delta[\\kappa]$. Introducing the definition of independence into the definition of the ACF yields\n\n\\begin{equation}\n\\begin{split}\n\\varphi_{xx}[\\kappa] &= E \\{ x[k] \\cdot x[k - \\kappa] \\} \\\\\n&= \n\\begin{cases}\nE \\{ x^2[k] \\} & \\text{for } \\kappa = 0 \\\\\nE \\{ x[k] \\} \\cdot E \\{ x[k - \\kappa] \\} & \\text{for } \\kappa \\neq 0\n\\end{cases} \\\\\n&= \n\\begin{cases}\n\\mu_x^2 + \\sigma_x^2 & \\text{for } \\kappa = 0 \\\\\n\\mu_x^2 & \\text{for } \\kappa \\neq 0\n\\end{cases} \\\\\n&= \\mu_x^2 + \\sigma_x^2 \\delta[\\kappa]\n\\end{split}\n\\end{equation}\n\nwhere the result for $\\kappa = 0$ follows from the bivariate PDF $p_{xx}(\\theta_1, \\theta_2, \\kappa)$ of an independent signal, as derived above. It can be concluded from this result that an independent random signal is also uncorrelated. The reverse, that an uncorrelated signal is independent does not hold in general.", "_____no_output_____" ], [ "### Independence versus Orthogonality\n\nIn geometry, two vectors are said to be [orthogonal](https://en.wikipedia.org/wiki/Orthogonality) if their dot product equals zero. This definition is frequently applied to finite-length random signals by interpreting them as vectors. The relation between independence, correlatedness and orthogonality is derived in the following.\n\nLet's assume two continuous-amplitude real-valued jointly wide-sense ergodic random signals $x_N[k]$ and $y_M[k]$ with finite lengths $N$ and $M$, respectively. The CCF $\\varphi_{xy}[\\kappa]$ between both can be reformulated as follows\n\n\\begin{equation}\n\\begin{split}\n\\varphi_{xy}[\\kappa] &= \\frac{1}{N} \\sum_{k=0}^{N-1} x_N[k] \\cdot y_M[k-\\kappa] \\\\\n&= \\frac{1}{N} < \\mathbf{x}_N, \\mathbf{y}_M[\\kappa] > \n\\end{split}\n\\end{equation}\n\nwhere $<\\cdot, \\cdot>$ denotes the [dot product](https://en.wikipedia.org/wiki/Dot_product). The $(N+2M-2) \\times 1$ vector $\\mathbf{x}_N$ is defined as \n\n$$\\mathbf{x}_N = \\left[ \\mathbf{0}^T_{(M-1) \\times 1}, x[0], x[1], \\dots, x[N-1], \\mathbf{0}^T_{(M-1) \\times 1} \\right]^T$$\n\nwhere $\\mathbf{0}_{(M-1) \\times 1}$ denotes the zero vector of length $M-1$. The $(N+2M-2) \\times 1$ vector $\\mathbf{y}_M[\\kappa]$ is defined as \n\n$$\\mathbf{y}_M = \\left[ \\mathbf{0}^T_{\\kappa \\times 1}, y[0], y[1], \\dots, y[M-1], \\mathbf{0}^T_{(N+M-2-\\kappa) \\times 1} \\right]^T$$\n\nIt follows from above definition of orthogonality that two finite-length random signals are orthogonal if their CCF is zero. This implies that at least one of the two signals has to be mean free. It can be concluded further that two independent random signals are also orthogonal and uncorrelated if at least one of them is mean free. The reverse, that orthogonal signals are independent, does not hold in general.\n\nThe concept of orthogonality can also be extended to one random signal by setting $\\mathbf{y}_M[\\kappa] = \\mathbf{x}_N[\\kappa]$. Since a random signal cannot be orthogonal to itself for $\\kappa = 0$, the definition of orthogonality has to be extended for this case. According to the ACF of a mean-free uncorrelated random signal $x[k]$, self-orthogonality may be defined as\n\n\\begin{equation}\n\\frac{1}{N} < \\mathbf{x}_N, \\mathbf{x}_N[\\kappa] > =\n\\begin{cases}\n\\sigma_x^2 & \\text{for } \\kappa = 0 \\\\\n0 & \\text{for } \\kappa \\neq 0\n\\end{cases}\n\\end{equation}\n\nAn independent random signal is also orthogonal if it is zero-mean. The reverse, that an orthogonal signal is independent does not hold in general.", "_____no_output_____" ], [ "#### Example - Computation of cross-correlation by dot product\n\nThis example illustrates the computation of the CCF by the dot product. First, a function is defined which computes the CCF by means of the dot product", "_____no_output_____" ] ], [ [ "def ccf_by_dotprod(x, y):\n N = len(x)\n M = len(y)\n xN = np.concatenate((np.zeros(M-1), x, np.zeros(M-1)))\n yM = np.concatenate((y, np.zeros(N+M-2)))\n \n return np.fromiter([np.dot(xN, np.roll(yM, kappa)) for kappa in range(N+M-1)], float)", "_____no_output_____" ] ], [ [ "Now the CCF is computed using different methods: computation by the dot product and by the built-in correlation function. The CCF is plotted for the computation by the dot product, as well as the difference (magnitude) between both methods. The resulting difference is in the typical expected range due to numerical inaccuracies.", "_____no_output_____" ] ], [ [ "N = 32 # length of signals\n\n# generate signals\nnp.random.seed(1)\nx = np.random.normal(size=N)\ny = np.convolve(x, [1, .5, .3, .7, .3], mode='same')\n\n# compute CCF\nccf1 = 1/N * np.correlate(x, y, mode='full')\nccf2 = 1/N * ccf_by_dotprod(x, y)\nkappa = np.arange(-N+1, N)\n\n# plot results\nplt.figure(figsize=(10, 4))\n\nplt.subplot(121)\nplt.stem(kappa, ccf1)\nplt.xlabel('$\\kappa$')\nplt.ylabel(r'$\\varphi_{xy}[\\kappa]$')\nplt.title('CCF by dot product')\nplt.grid()\n\nplt.subplot(122)\nplt.stem(kappa, np.abs(ccf1-ccf2))\nplt.xlabel('$\\kappa$')\nplt.title('Difference (magnitude)')\nplt.tight_layout()", "_____no_output_____" ] ], [ [ "**Copyright**\n\nThis notebook is provided as [Open Educational Resource](https://en.wikipedia.org/wiki/Open_educational_resources). Feel free to use the notebook for your own purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT). Please attribute the work as follows: *Sascha Spors, Digital Signal Processing - Lecture notes featuring computational examples, 2016-2018*.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbde44032894bf5bed2e2f58d6f9887a9c0dc97c
3,038
ipynb
Jupyter Notebook
examples/01-filter/extract-cells-inside-surface.ipynb
pyvista/pyvista-examples
60dda52b4c8069c15d73768d04bee3f84d2f803f
[ "MIT" ]
4
2019-05-13T06:42:18.000Z
2020-12-18T05:09:29.000Z
examples/01-filter/extract-cells-inside-surface.ipynb
pyvista/pyvista-examples
60dda52b4c8069c15d73768d04bee3f84d2f803f
[ "MIT" ]
1
2020-07-30T11:53:38.000Z
2020-07-30T11:55:44.000Z
examples/01-filter/extract-cells-inside-surface.ipynb
pyvista/pyvista-examples
60dda52b4c8069c15d73768d04bee3f84d2f803f
[ "MIT" ]
2
2020-07-26T14:09:58.000Z
2020-11-03T11:27:29.000Z
28.12963
479
0.520079
[ [ [ "%matplotlib inline\nfrom pyvista import set_plot_theme\nset_plot_theme('document')", "_____no_output_____" ] ], [ [ "Extract Cells Inside Surface\n============================\n\nExtract the cells in a mesh that exist inside or outside a closed\nsurface of another mesh\n", "_____no_output_____" ] ], [ [ "# sphinx_gallery_thumbnail_number = 2\nimport pyvista as pv\nfrom pyvista import examples\n\nmesh = examples.download_cow()\n\ncpos = [(13.0, 7.6, -13.85), (0.44, -0.4, -0.37), (-0.28, 0.9, 0.3)]\n\ndargs = dict(show_edges=True)\n# Rotate the mesh to have a second mesh\nrot = mesh.copy()\nrot.rotate_y(90)\n\np = pv.Plotter()\np.add_mesh(mesh, color=\"Crimson\", **dargs)\np.add_mesh(rot, color=\"mintcream\", opacity=0.35, **dargs)\np.camera_position = cpos\np.show()", "_____no_output_____" ] ], [ [ "Mark points inside with 1 and outside with a 0\n", "_____no_output_____" ] ], [ [ "select = mesh.select_enclosed_points(rot)\n\nselect", "_____no_output_____" ] ], [ [ "Extract two meshes, one completely inside and one completely outside the\nenclosing surface.\n", "_____no_output_____" ] ], [ [ "inside = select.threshold(0.5)\noutside = select.threshold(0.5, invert=True)", "_____no_output_____" ] ], [ [ "display the results\n", "_____no_output_____" ] ], [ [ "p = pv.Plotter()\np.add_mesh(outside, color=\"Crimson\", **dargs)\np.add_mesh(inside, color=\"green\", **dargs)\np.add_mesh(rot, color=\"mintcream\", opacity=0.35, **dargs)\n\np.camera_position = cpos\np.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbde44d578d876a283a1844116d5249e6308aa06
36,128
ipynb
Jupyter Notebook
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
joaopamaral/deep-learning-v2-pytorch
baf6d0adfd79fc6d7418de9c0f2a52c44b6e3cfc
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
joaopamaral/deep-learning-v2-pytorch
baf6d0adfd79fc6d7418de9c0f2a52c44b6e3cfc
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
joaopamaral/deep-learning-v2-pytorch
baf6d0adfd79fc6d7418de9c0f2a52c44b6e3cfc
[ "MIT" ]
null
null
null
45.964377
7,272
0.65816
[ [ [ "# Training Neural Networks\n\nThe network we built in the previous part isn't so smart, it doesn't know anything about our handwritten digits. Neural networks with non-linear activations work like universal function approximators. There is some function that maps your input to the output. For example, images of handwritten digits to class probabilities. The power of neural networks is that we can train them to approximate this function, and basically any function given enough data and compute time.\n\n<img src=\"assets/function_approx.png\" width=500px>\n\nAt first the network is naive, it doesn't know the function mapping the inputs to the outputs. We train the network by showing it examples of real data, then adjusting the network parameters such that it approximates this function.\n\nTo find these parameters, we need to know how poorly the network is predicting the real outputs. For this we calculate a **loss function** (also called the cost), a measure of our prediction error. For example, the mean squared loss is often used in regression and binary classification problems\n\n$$\n\\large \\ell = \\frac{1}{2n}\\sum_i^n{\\left(y_i - \\hat{y}_i\\right)^2}\n$$\n\nwhere $n$ is the number of training examples, $y_i$ are the true labels, and $\\hat{y}_i$ are the predicted labels.\n\nBy minimizing this loss with respect to the network parameters, we can find configurations where the loss is at a minimum and the network is able to predict the correct labels with high accuracy. We find this minimum using a process called **gradient descent**. The gradient is the slope of the loss function and points in the direction of fastest change. To get to the minimum in the least amount of time, we then want to follow the gradient (downwards). You can think of this like descending a mountain by following the steepest slope to the base.\n\n<img src='assets/gradient_descent.png' width=350px>", "_____no_output_____" ], [ "## Backpropagation\n\nFor single layer networks, gradient descent is straightforward to implement. However, it's more complicated for deeper, multilayer neural networks like the one we've built. Complicated enough that it took about 30 years before researchers figured out how to train multilayer networks.\n\nTraining multilayer networks is done through **backpropagation** which is really just an application of the chain rule from calculus. It's easiest to understand if we convert a two layer network into a graph representation.\n\n<img src='assets/backprop_diagram.png' width=550px>\n\nIn the forward pass through the network, our data and operations go from bottom to top here. We pass the input $x$ through a linear transformation $L_1$ with weights $W_1$ and biases $b_1$. The output then goes through the sigmoid operation $S$ and another linear transformation $L_2$. Finally we calculate the loss $\\ell$. We use the loss as a measure of how bad the network's predictions are. The goal then is to adjust the weights and biases to minimize the loss.\n\nTo train the weights with gradient descent, we propagate the gradient of the loss backwards through the network. Each operation has some gradient between the inputs and outputs. As we send the gradients backwards, we multiply the incoming gradient with the gradient for the operation. Mathematically, this is really just calculating the gradient of the loss with respect to the weights using the chain rule.\n\n$$\n\\large \\frac{\\partial \\ell}{\\partial W_1} = \\frac{\\partial L_1}{\\partial W_1} \\frac{\\partial S}{\\partial L_1} \\frac{\\partial L_2}{\\partial S} \\frac{\\partial \\ell}{\\partial L_2}\n$$\n\n**Note:** I'm glossing over a few details here that require some knowledge of vector calculus, but they aren't necessary to understand what's going on.\n\nWe update our weights using this gradient with some learning rate $\\alpha$. \n\n$$\n\\large W^\\prime_1 = W_1 - \\alpha \\frac{\\partial \\ell}{\\partial W_1}\n$$\n\nThe learning rate $\\alpha$ is set such that the weight update steps are small enough that the iterative method settles in a minimum.", "_____no_output_____" ], [ "## Losses in PyTorch\n\nLet's start by seeing how we calculate the loss with PyTorch. Through the `nn` module, PyTorch provides losses such as the cross-entropy loss (`nn.CrossEntropyLoss`). You'll usually see the loss assigned to `criterion`. As noted in the last part, with a classification problem such as MNIST, we're using the softmax function to predict class probabilities. With a softmax output, you want to use cross-entropy as the loss. To actually calculate the loss, you first define the criterion then pass in the output of your network and the correct labels.\n\nSomething really important to note here. Looking at [the documentation for `nn.CrossEntropyLoss`](https://pytorch.org/docs/stable/nn.html#torch.nn.CrossEntropyLoss),\n\n> This criterion combines `nn.LogSoftmax()` and `nn.NLLLoss()` in one single class.\n>\n> The input is expected to contain scores for each class.\n\nThis means we need to pass in the raw output of our network into the loss, not the output of the softmax function. This raw output is usually called the *logits* or *scores*. We use the logits because softmax gives you probabilities which will often be very close to zero or one but floating-point numbers can't accurately represent values near zero or one ([read more here](https://docs.python.org/3/tutorial/floatingpoint.html)). It's usually best to avoid doing calculations with probabilities, typically we use log-probabilities.", "_____no_output_____" ] ], [ [ "import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\n\n# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n# Download and load the training data\ntrainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)", "_____no_output_____" ], [ "# Build a feed-forward network\nmodel = nn.Sequential(nn.Linear(784, 128),\n nn.ReLU(),\n nn.Linear(128, 64),\n nn.ReLU(),\n nn.Linear(64, 10))\n\n# Define the loss\ncriterion = nn.CrossEntropyLoss()\n\n# Get our data\nimages, labels = next(iter(trainloader))\n# Flatten images\nimages = images.view(images.shape[0], -1)\n\n# Forward pass, get our logits\nlogits = model(images)\n# Calculate the loss with the logits and the labels\nloss = criterion(logits, labels)\n\nprint(loss)", "tensor(2.2984, grad_fn=<NllLossBackward>)\n" ] ], [ [ "In my experience it's more convenient to build the model with a log-softmax output using `nn.LogSoftmax` or `F.log_softmax` ([documentation](https://pytorch.org/docs/stable/nn.html#torch.nn.LogSoftmax)). Then you can get the actual probabilities by taking the exponential `torch.exp(output)`. With a log-softmax output, you want to use the negative log likelihood loss, `nn.NLLLoss` ([documentation](https://pytorch.org/docs/stable/nn.html#torch.nn.NLLLoss)).\n\n>**Exercise:** Build a model that returns the log-softmax as the output and calculate the loss using the negative log likelihood loss. Note that for `nn.LogSoftmax` and `F.log_softmax` you'll need to set the `dim` keyword argument appropriately. `dim=0` calculates softmax across the rows, so each column sums to 1, while `dim=1` calculates across the columns so each row sums to 1. Think about what you want the output to be and choose `dim` appropriately.", "_____no_output_____" ] ], [ [ "# TODO: Build a feed-forward network\nmodel = nn.Sequential(nn.Linear(784, 128),\n nn.ReLU(),\n nn.Linear(128, 64),\n nn.ReLU(),\n nn.Linear(64, 10),\n nn.LogSoftmax(dim=1))\n\n# TODO: Define the loss\ncriterion = nn.NLLLoss()\n\n### Run this to check your work\n# Get our data\nimages, labels = next(iter(trainloader))\n# Flatten images\nimages = images.view(images.shape[0], -1)\n\n# Forward pass, get our logits\nlogps = model(images)\n# Calculate the loss with the logits and the labels\nloss = criterion(logps, labels)\n\nprint(loss)", "tensor(2.2955, grad_fn=<NllLossBackward>)\n" ] ], [ [ "## Autograd\n\nNow that we know how to calculate a loss, how do we use it to perform backpropagation? Torch provides a module, `autograd`, for automatically calculating the gradients of tensors. We can use it to calculate the gradients of all our parameters with respect to the loss. Autograd works by keeping track of operations performed on tensors, then going backwards through those operations, calculating gradients along the way. To make sure PyTorch keeps track of operations on a tensor and calculates the gradients, you need to set `requires_grad = True` on a tensor. You can do this at creation with the `requires_grad` keyword, or at any time with `x.requires_grad_(True)`.\n\nYou can turn off gradients for a block of code with the `torch.no_grad()` content:\n```python\nx = torch.zeros(1, requires_grad=True)\n>>> with torch.no_grad():\n... y = x * 2\n>>> y.requires_grad\nFalse\n```\n\nAlso, you can turn on or off gradients altogether with `torch.set_grad_enabled(True|False)`.\n\nThe gradients are computed with respect to some variable `z` with `z.backward()`. This does a backward pass through the operations that created `z`.", "_____no_output_____" ] ], [ [ "x = torch.randn(2,2, requires_grad=True)\nprint(x)", "tensor([[-0.9168, 0.1082],\n [-0.9551, -1.3768]], requires_grad=True)\n" ], [ "y = x**2\nprint(y)", "tensor([[0.8405, 0.0117],\n [0.9121, 1.8956]], grad_fn=<PowBackward0>)\n" ] ], [ [ "Below we can see the operation that created `y`, a power operation `PowBackward0`.", "_____no_output_____" ] ], [ [ "## grad_fn shows the function that generated this variable\nprint(y.grad_fn)", "<PowBackward0 object at 0x0000024BB2419860>\n" ] ], [ [ "The autgrad module keeps track of these operations and knows how to calculate the gradient for each one. In this way, it's able to calculate the gradients for a chain of operations, with respect to any one tensor. Let's reduce the tensor `y` to a scalar value, the mean.", "_____no_output_____" ] ], [ [ "z = y.mean()\nprint(z)", "tensor(0.9150, grad_fn=<MeanBackward1>)\n" ] ], [ [ "You can check the gradients for `x` and `y` but they are empty currently.", "_____no_output_____" ] ], [ [ "print(x.grad)", "None\n" ] ], [ [ "To calculate the gradients, you need to run the `.backward` method on a Variable, `z` for example. This will calculate the gradient for `z` with respect to `x`\n\n$$\n\\frac{\\partial z}{\\partial x} = \\frac{\\partial}{\\partial x}\\left[\\frac{1}{n}\\sum_i^n x_i^2\\right] = \\frac{x}{2}\n$$", "_____no_output_____" ] ], [ [ "z.backward()\nprint(x.grad)\nprint(x/2)", "tensor([[-0.4584, 0.0541],\n [-0.4775, -0.6884]])\ntensor([[-0.4584, 0.0541],\n [-0.4775, -0.6884]], grad_fn=<DivBackward0>)\n" ] ], [ [ "These gradients calculations are particularly useful for neural networks. For training we need the gradients of the weights with respect to the cost. With PyTorch, we run data forward through the network to calculate the loss, then, go backwards to calculate the gradients with respect to the loss. Once we have the gradients we can make a gradient descent step. ", "_____no_output_____" ], [ "## Loss and Autograd together\n\nWhen we create a network with PyTorch, all of the parameters are initialized with `requires_grad = True`. This means that when we calculate the loss and call `loss.backward()`, the gradients for the parameters are calculated. These gradients are used to update the weights with gradient descent. Below you can see an example of calculating the gradients using a backwards pass.", "_____no_output_____" ] ], [ [ "# Build a feed-forward network\nmodel = nn.Sequential(nn.Linear(784, 128),\n nn.ReLU(),\n nn.Linear(128, 64),\n nn.ReLU(),\n nn.Linear(64, 10),\n nn.LogSoftmax(dim=1))\n\ncriterion = nn.NLLLoss()\nimages, labels = next(iter(trainloader))\nimages = images.view(images.shape[0], -1)\n\nlogps = model(images)\nloss = criterion(logps, labels)", "_____no_output_____" ], [ "print('Before backward pass: \\n', model[0].weight.grad)\n\nloss.backward()\n\nprint('After backward pass: \\n', model[0].weight.grad)", "Before backward pass: \n None\nAfter backward pass: \n tensor([[-1.8442e-03, -1.8442e-03, -1.8442e-03, ..., -1.8442e-03,\n -1.8442e-03, -1.8442e-03],\n [-2.7849e-04, -2.7849e-04, -2.7849e-04, ..., -2.7849e-04,\n -2.7849e-04, -2.7849e-04],\n [ 8.7307e-04, 8.7307e-04, 8.7307e-04, ..., 8.7307e-04,\n 8.7307e-04, 8.7307e-04],\n ...,\n [ 9.1007e-04, 9.1007e-04, 9.1007e-04, ..., 9.1007e-04,\n 9.1007e-04, 9.1007e-04],\n [ 3.3051e-04, 3.3051e-04, 3.3051e-04, ..., 3.3051e-04,\n 3.3051e-04, 3.3051e-04],\n [-6.3408e-05, -6.3408e-05, -6.3408e-05, ..., -6.3408e-05,\n -6.3408e-05, -6.3408e-05]])\n" ] ], [ [ "## Training the network!\n\nThere's one last piece we need to start training, an optimizer that we'll use to update the weights with the gradients. We get these from PyTorch's [`optim` package](https://pytorch.org/docs/stable/optim.html). For example we can use stochastic gradient descent with `optim.SGD`. You can see how to define an optimizer below.", "_____no_output_____" ] ], [ [ "from torch import optim\n\n# Optimizers require the parameters to optimize and a learning rate\noptimizer = optim.SGD(model.parameters(), lr=0.01)", "_____no_output_____" ] ], [ [ "Now we know how to use all the individual parts so it's time to see how they work together. Let's consider just one learning step before looping through all the data. The general process with PyTorch:\n\n* Make a forward pass through the network \n* Use the network output to calculate the loss\n* Perform a backward pass through the network with `loss.backward()` to calculate the gradients\n* Take a step with the optimizer to update the weights\n\nBelow I'll go through one training step and print out the weights and gradients so you can see how it changes. Note that I have a line of code `optimizer.zero_grad()`. When you do multiple backwards passes with the same parameters, the gradients are accumulated. This means that you need to zero the gradients on each training pass or you'll retain gradients from previous training batches.", "_____no_output_____" ] ], [ [ "print('Initial weights - ', model[0].weight)\n\nimages, labels = next(iter(trainloader))\nimages.resize_(64, 784)\n\n# Clear the gradients, do this because gradients are accumulated\noptimizer.zero_grad()\n\n# Forward pass, then backward pass, then update weights\noutput = model.forward(images)\nloss = criterion(output, labels)\nloss.backward()\nprint('Gradient -', model[0].weight.grad)", "Initial weights - Parameter containing:\ntensor([[-0.0128, -0.0233, -0.0240, ..., 0.0220, 0.0024, 0.0254],\n [ 0.0003, 0.0309, -0.0174, ..., -0.0009, -0.0109, -0.0041],\n [ 0.0283, 0.0222, 0.0207, ..., -0.0125, 0.0185, 0.0240],\n ...,\n [ 0.0120, 0.0169, -0.0304, ..., -0.0109, -0.0117, -0.0034],\n [ 0.0167, -0.0072, 0.0145, ..., -0.0061, 0.0261, 0.0296],\n [ 0.0157, 0.0200, 0.0220, ..., 0.0189, -0.0035, 0.0029]],\n requires_grad=True)\nGradient - tensor([[-0.0021, -0.0021, -0.0021, ..., -0.0021, -0.0021, -0.0021],\n [ 0.0026, 0.0026, 0.0026, ..., 0.0026, 0.0026, 0.0026],\n [-0.0019, -0.0019, -0.0019, ..., -0.0019, -0.0019, -0.0019],\n ...,\n [ 0.0005, 0.0005, 0.0005, ..., 0.0005, 0.0005, 0.0005],\n [-0.0010, -0.0010, -0.0010, ..., -0.0010, -0.0010, -0.0010],\n [ 0.0003, 0.0003, 0.0003, ..., 0.0003, 0.0003, 0.0003]])\n" ], [ "# Take an update step and few the new weights \noptimizer.step()\nprint('Updated weights - ', model[0].weight)", "Updated weights - Parameter containing:\ntensor([[-0.0128, -0.0233, -0.0240, ..., 0.0220, 0.0024, 0.0254],\n [ 0.0003, 0.0309, -0.0174, ..., -0.0010, -0.0109, -0.0041],\n [ 0.0283, 0.0222, 0.0207, ..., -0.0125, 0.0185, 0.0240],\n ...,\n [ 0.0120, 0.0169, -0.0304, ..., -0.0109, -0.0117, -0.0034],\n [ 0.0167, -0.0072, 0.0146, ..., -0.0061, 0.0261, 0.0296],\n [ 0.0157, 0.0200, 0.0220, ..., 0.0188, -0.0035, 0.0029]],\n requires_grad=True)\n" ] ], [ [ "### Training for real\n\nNow we'll put this algorithm into a loop so we can go through all the images. Some nomenclature, one pass through the entire dataset is called an *epoch*. So here we're going to loop through `trainloader` to get our training batches. For each batch, we'll doing a training pass where we calculate the loss, do a backwards pass, and update the weights.\n\n>**Exercise:** Implement the training pass for our network. If you implemented it correctly, you should see the training loss drop with each epoch.", "_____no_output_____" ] ], [ [ "## Your solution here\n\nmodel = nn.Sequential(nn.Linear(784, 128),\n nn.ReLU(),\n nn.Linear(128, 64),\n nn.ReLU(),\n nn.Linear(64, 10),\n nn.LogSoftmax(dim=1))\n# model.cuda()\n\ncriterion = nn.NLLLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.003)\n\nepochs = 5\nfor e in range(epochs):\n running_loss = 0\n for images, labels in trainloader:\n # Flatten MNIST images into a 784 long vector\n images = images.view(images.shape[0], -1)\n# images, labels = images.cuda(), labels.cuda()\n \n # TODO: Training pass\n # Clear the gradients, do this because gradients are accumulated\n optimizer.zero_grad()\n \n # Forward pass, then backward pass, then update weights\n logps = model.forward(images)\n loss = criterion(logps, labels)\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n else:\n print(f\"Training loss: {running_loss/len(trainloader)}\")", "Training loss: 1.9250698829256396\nTraining loss: 0.8626406244568224\nTraining loss: 0.5396255757540528\nTraining loss: 0.4405489337088457\nTraining loss: 0.39467297337139085\n" ] ], [ [ "With the network trained, we can check out it's predictions.", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport helper\n\nimages, labels = next(iter(trainloader))\n\nimg = images[0].view(1, 784)\n# Turn off gradients to speed up this part\nwith torch.no_grad():\n logits = model.forward(img)\n\n# Output of the network are logits, need to take softmax for probabilities\nps = F.softmax(logits, dim=1)\nhelper.view_classify(img.view(1, 28, 28), ps)", "_____no_output_____" ] ], [ [ "Now our network is brilliant. It can accurately predict the digits in our images. Next up you'll write the code for training a neural network on a more complex dataset.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbde5a1f496de3b5a7b34228e009ec8e75740fe4
129,401
ipynb
Jupyter Notebook
project_files/Recommendations_with_IBM/Recommendations_with_IBM.ipynb
randomwalk10/DSND_Term2
a3fe74ae5d53f589764600ebe7ca1f54b6f9dd57
[ "MIT" ]
null
null
null
project_files/Recommendations_with_IBM/Recommendations_with_IBM.ipynb
randomwalk10/DSND_Term2
a3fe74ae5d53f589764600ebe7ca1f54b6f9dd57
[ "MIT" ]
null
null
null
project_files/Recommendations_with_IBM/Recommendations_with_IBM.ipynb
randomwalk10/DSND_Term2
a3fe74ae5d53f589764600ebe7ca1f54b6f9dd57
[ "MIT" ]
null
null
null
60.158531
20,388
0.700481
[ [ [ "# Recommendations with IBM\n\nIn this notebook, you will be putting your recommendation skills to use on real data from the IBM Watson Studio platform. \n\n\nYou may either submit your notebook through the workspace here, or you may work from your local machine and submit through the next page. Either way assure that your code passes the project [RUBRIC](https://review.udacity.com/#!/rubrics/2322/view). **Please save regularly.**\n\nBy following the table of contents, you will build out a number of different methods for making recommendations that can be used for different situations. \n\n\n## Table of Contents\n\nI. [Exploratory Data Analysis](#Exploratory-Data-Analysis)<br>\nII. [Rank Based Recommendations](#Rank)<br>\nIII. [User-User Based Collaborative Filtering](#User-User)<br>\nIV. [Content Based Recommendations (EXTRA - NOT REQUIRED)](#Content-Recs)<br>\nV. [Matrix Factorization](#Matrix-Fact)<br>\nVI. [Extras & Concluding](#conclusions)\n\nAt the end of the notebook, you will find directions for how to submit your work. Let's get started by importing the necessary libraries and reading in the data.", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport project_tests as t\nimport pickle\n\n%matplotlib inline\n\ndf = pd.read_csv('data/user-item-interactions.csv')\ndf_content = pd.read_csv('data/articles_community.csv')\ndel df['Unnamed: 0']\ndel df_content['Unnamed: 0']\n\n# Show df to get an idea of the data\ndf.head()", "/home/randomwalk10/anaconda3/envs/aind/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n return f(*args, **kwds)\n" ], [ "# Show df_content to get an idea of the data\ndf_content.head()", "_____no_output_____" ] ], [ [ "### <a class=\"anchor\" id=\"Exploratory-Data-Analysis\">Part I : Exploratory Data Analysis</a>\n\nUse the dictionary and cells below to provide some insight into the descriptive statistics of the data.\n\n`1.` What is the distribution of how many articles a user interacts with in the dataset? Provide a visual and descriptive statistics to assist with giving a look at the number of times each user interacts with an article. ", "_____no_output_____" ] ], [ [ "df.groupby('email')['article_id'].count().values", "_____no_output_____" ], [ "interaction_per_user = df.groupby('email')['article_id'].count().values\n\ncounts, bins, _ = plt.hist(df.article_id.value_counts().values, 50, cumulative=False)\n\nplt.xlabel('number of interactions per user')\nplt.ylabel('counts')\nplt.title('counts vs interactions per user')\nplt.grid(True)\n\nplt.show()", "_____no_output_____" ], [ "# max number of user-article interactions by any user\nprint(\"The maximum number of user-article interactions by any user is [%d]\" % interaction_per_user.max())", "The maximum number of user-article interactions by any user is [364]\n" ], [ "# median value of the array of interaction_per_user\nprint(\"50 percents of individuals interact with [%d] number of articles or fewer\" % np.median(interaction_per_user))", "50 percents of individuals interact with [3] number of articles or fewer\n" ], [ "# Fill in the median and maximum number of user_article interactios below\n\nmedian_val = 3 # 50% of individuals interact with ____ number of articles or fewer.\nmax_views_by_user = 364 # The maximum number of user-article interactions by any 1 user is ______.", "_____no_output_____" ] ], [ [ "`2.` Explore and remove duplicate articles from the **df_content** dataframe. ", "_____no_output_____" ] ], [ [ "# Find and explore duplicate articles\nprint(\"duplicate articles:\")\ndf_content[df_content.duplicated(\"article_id\", keep=\"first\")]", "duplicate articles:\n" ], [ "# Remove any rows that have the same article_id - only keep the first\nold_num_rows = df_content.shape[0]\ndf_content.drop_duplicates(\"article_id\", inplace=True)\nprint(\"%d rows are dropped in df_content.\" % (old_num_rows - df_content.shape[0]))", "5 rows are dropped in df_content.\n" ] ], [ [ "`3.` Use the cells below to find:\n\n**a.** The number of unique articles that have an interaction with a user. \n**b.** The number of unique articles in the dataset (whether they have any interactions or not).<br>\n**c.** The number of unique users in the dataset. (excluding null values) <br>\n**d.** The number of user-article interactions in the dataset.", "_____no_output_____" ] ], [ [ "print(\"The number of unique articles that have an interaction with a user:\",\n np.sum(df.groupby(\"article_id\")['email'].count()>=1))", "The number of unique articles that have an interaction with a user: 714\n" ], [ "print(\"The number of unique articles in the dataset:\", df_content.article_id.nunique())", "The number of unique articles in the dataset: 1051\n" ], [ "print(\"The number of unique users in the dataset:\", df.email.nunique())", "The number of unique users in the dataset: 5148\n" ], [ "print(\"The number of user-article interactions in the dataset:\", df.shape[0])", "The number of user-article interactions in the dataset: 45993\n" ], [ "unique_articles = 714 # The number of unique articles that have at least one interaction\ntotal_articles = 1051 # The number of unique articles on the IBM platform\nunique_users = 5148 # The number of unique users\nuser_article_interactions = 45993 # The number of user-article interactions", "_____no_output_____" ] ], [ [ "`4.` Use the cells below to find the most viewed **article_id**, as well as how often it was viewed. After talking to the company leaders, the `email_mapper` function was deemed a reasonable way to map users to ids. There were a small number of null values, and it was found that all of these null values likely belonged to a single user (which is how they are stored using the function below).", "_____no_output_____" ] ], [ [ "print(\"The most viewed article in the dataset as a string with one value following the decimal:\",\n df.groupby(\"article_id\")[\"email\"].count().idxmax())", "The most viewed article in the dataset as a string with one value following the decimal: 1429.0\n" ], [ "print(\"The most viewed article in the dataset was viewed how many times:\",\n df.groupby(\"article_id\")[\"email\"].count().max())", "The most viewed article in the dataset was viewed how many times: 937\n" ], [ "most_viewed_article_id = \"1429.0\" # The most viewed article in the dataset as a string with one value following the decimal \nmax_views = 937 # The most viewed article in the dataset was viewed how many times?", "_____no_output_____" ], [ "## No need to change the code here - this will be helpful for later parts of the notebook\n# Run this cell to map the user email to a user_id column and remove the email column\n\ndef email_mapper():\n coded_dict = dict()\n cter = 1\n email_encoded = []\n \n for val in df['email']:\n if val not in coded_dict:\n coded_dict[val] = cter\n cter+=1\n \n email_encoded.append(coded_dict[val])\n return email_encoded\n\nemail_encoded = email_mapper()\ndel df['email']\ndf['user_id'] = email_encoded\n\n# show header\ndf.head()", "_____no_output_____" ], [ "## If you stored all your results in the variable names above, \n## you shouldn't need to change anything in this cell\n\nsol_1_dict = {\n '`50% of individuals have _____ or fewer interactions.`': median_val,\n '`The total number of user-article interactions in the dataset is ______.`': user_article_interactions,\n '`The maximum number of user-article interactions by any 1 user is ______.`': max_views_by_user,\n '`The most viewed article in the dataset was viewed _____ times.`': max_views,\n '`The article_id of the most viewed article is ______.`': most_viewed_article_id,\n '`The number of unique articles that have at least 1 rating ______.`': unique_articles,\n '`The number of unique users in the dataset is ______`': unique_users,\n '`The number of unique articles on the IBM platform`': total_articles\n}\n\n# Test your dictionary against the solution\nt.sol_1_test(sol_1_dict)", "It looks like you have everything right here! Nice job!\n" ] ], [ [ "### <a class=\"anchor\" id=\"Rank\">Part II: Rank-Based Recommendations</a>\n\nUnlike in the earlier lessons, we don't actually have ratings for whether a user liked an article or not. We only know that a user has interacted with an article. In these cases, the popularity of an article can really only be based on how often an article was interacted with.\n\n`1.` Fill in the function below to return the **n** top articles ordered with most interactions as the top. Test your function using the tests below.", "_____no_output_____" ] ], [ [ "def get_top_articles(n, df=df):\n '''\n INPUT:\n n - (int) the number of top articles to return\n df - (pandas dataframe) df as defined at the top of the notebook \n \n OUTPUT:\n top_articles - (list) A list of the top 'n' article titles \n \n '''\n # Your code here\n top_idx = get_top_article_ids(n, df=df)\n top_articles = [df[df.article_id==float(x)][\"title\"].values[0] for x in top_idx]\n return top_articles # Return the top article titles from df (not df_content)\n\ndef get_top_article_ids(n, df=df):\n '''\n INPUT:\n n - (int) the number of top articles to return\n df - (pandas dataframe) df as defined at the top of the notebook \n \n OUTPUT:\n top_articles - (list) A list of the top 'n' article titles \n \n '''\n # Your code here\n top_articles = list(df.article_id.value_counts().index[:n])\n top_articles = [str(x) for x in top_articles]\n return top_articles # Return the top article ids", "_____no_output_____" ], [ "print(get_top_articles(10))\nprint(get_top_article_ids(10))", "['use deep learning for image classification', 'insights from new york car accident reports', 'visualize car data with brunel', 'use xgboost, scikit-learn & ibm watson machine learning apis', 'predicting churn with the spss random tree algorithm', 'healthcare python streaming application demo', 'finding optimal locations of new store using decision optimization', 'apache spark lab, part 1: basic concepts', 'analyze energy consumption in buildings', 'gosales transactions for logistic regression model']\n['1429.0', '1330.0', '1431.0', '1427.0', '1364.0', '1314.0', '1293.0', '1170.0', '1162.0', '1304.0']\n" ], [ "# Test your function by returning the top 5, 10, and 20 articles\ntop_5 = get_top_articles(5)\ntop_10 = get_top_articles(10)\ntop_20 = get_top_articles(20)\n\n# Test each of your three lists from above\nt.sol_2_test(get_top_articles)", "Your top_5 looks like the solution list! Nice job.\nYour top_10 looks like the solution list! Nice job.\nYour top_20 looks like the solution list! Nice job.\n" ] ], [ [ "### <a class=\"anchor\" id=\"User-User\">Part III: User-User Based Collaborative Filtering</a>\n\n\n`1.` Use the function below to reformat the **df** dataframe to be shaped with users as the rows and articles as the columns. \n\n* Each **user** should only appear in each **row** once.\n\n\n* Each **article** should only show up in one **column**. \n\n\n* **If a user has interacted with an article, then place a 1 where the user-row meets for that article-column**. It does not matter how many times a user has interacted with the article, all entries where a user has interacted with an article should be a 1. \n\n\n* **If a user has not interacted with an item, then place a zero where the user-row meets for that article-column**. \n\nUse the tests to make sure the basic structure of your matrix matches what is expected by the solution.", "_____no_output_____" ] ], [ [ "# create the user-article matrix with 1's and 0's\n\ndef create_user_item_matrix(df):\n '''\n INPUT:\n df - pandas dataframe with article_id, title, user_id columns\n \n OUTPUT:\n user_item - user item matrix \n \n Description:\n Return a matrix with user ids as rows and article ids on the columns with 1 values where a user interacted with \n an article and a 0 otherwise\n '''\n # Fill in the function here\n user_item = df.groupby([\"user_id\", \"article_id\"])[\"title\"].max().unstack().apply(\n lambda row: [1 if x else 0 for x in row], axis=1)\n return user_item # return the user_item matrix \n\nuser_item = create_user_item_matrix(df)", "_____no_output_____" ], [ "## Tests: You should just need to run this cell. Don't change the code.\nassert user_item.shape[0] == 5149, \"Oops! The number of users in the user-article matrix doesn't look right.\"\nassert user_item.shape[1] == 714, \"Oops! The number of articles in the user-article matrix doesn't look right.\"\nassert user_item.sum(axis=1)[1] == 36, \"Oops! The number of articles seen by user 1 doesn't look right.\"\nprint(\"You have passed our quick tests! Please proceed!\")", "You have passed our quick tests! Please proceed!\n" ] ], [ [ "`2.` Complete the function below which should take a user_id and provide an ordered list of the most similar users to that user (from most similar to least similar). The returned result should not contain the provided user_id, as we know that each user is similar to him/herself. Because the results for each user here are binary, it (perhaps) makes sense to compute similarity as the dot product of two users. \n\nUse the tests to test your function.", "_____no_output_____" ] ], [ [ "def find_similar_users(user_id, user_item=user_item):\n '''\n INPUT:\n user_id - (int) a user_id\n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n OUTPUT:\n similar_users - (list) an ordered list where the closest users (largest dot product users)\n are listed first\n \n Description:\n Computes the similarity of every pair of users based on the dot product\n Returns an ordered\n \n '''\n # compute similarity of each user to the provided user\n similarity_array = user_item.dot(user_item.loc[user_id]).values\n # sort by similarity\n sorted_idx = np.argsort(similarity_array)[::-1]\n # create list of just the ids\n most_similar_users = user_item.index[sorted_idx]\n # remove the own user's id\n most_similar_users = list(np.setdiff1d(most_similar_users, user_id))\n return most_similar_users # return a list of the users in order from most to least similar\n ", "_____no_output_____" ], [ "# Do a spot check of your function\nprint(\"The 10 most similar users to user 1 are: {}\".format(find_similar_users(1)[:10]))\nprint(\"The 5 most similar users to user 3933 are: {}\".format(find_similar_users(3933)[:5]))\nprint(\"The 3 most similar users to user 46 are: {}\".format(find_similar_users(46)[:3]))", "The 10 most similar users to user 1 are: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\nThe 5 most similar users to user 3933 are: [1, 2, 3, 4, 5]\nThe 3 most similar users to user 46 are: [1, 2, 3]\n" ] ], [ [ "`3.` Now that you have a function that provides the most similar users to each user, you will want to use these users to find articles you can recommend. Complete the functions below to return the articles you would recommend to each user. ", "_____no_output_____" ] ], [ [ "def get_article_names(article_ids, df=df):\n '''\n INPUT:\n article_ids - (list) a list of article ids\n df - (pandas dataframe) df as defined at the top of the notebook\n \n OUTPUT:\n article_names - (list) a list of article names associated with the list of article ids \n (this is identified by the title column)\n '''\n # Your code here\n article_names = [df[df.article_id==float(x)][\"title\"].values[0] for x in article_ids]\n return article_names # Return the article names associated with list of article ids\n\n\ndef get_user_articles(user_id, user_item=user_item):\n '''\n INPUT:\n user_id - (int) a user id\n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n OUTPUT:\n article_ids - (list) a list of the article ids seen by the user\n article_names - (list) a list of article names associated with the list of article ids \n (this is identified by the doc_full_name column in df_content)\n \n Description:\n Provides a list of the article_ids and article titles that have been seen by a user\n '''\n # Your code here\n user_data = user_item.loc[user_id]\n article_ids = user_data[user_data>0].index.tolist()\n article_names = get_article_names(article_ids)\n article_ids = [str(x) for x in article_ids]\n return article_ids, article_names # return the ids and names\n\n\ndef user_user_recs(user_id, m=10):\n '''\n INPUT:\n user_id - (int) a user id\n m - (int) the number of recommendations you want for the user\n \n OUTPUT:\n recs - (list) a list of recommendations for the user\n \n Description:\n Loops through the users based on closeness to the input user_id\n For each user - finds articles the user hasn't seen before and provides them as recs\n Does this until m recommendations are found\n \n Notes:\n Users who are the same closeness are chosen arbitrarily as the 'next' user\n \n For the user where the number of recommended articles starts below m \n and ends exceeding m, the last items are chosen arbitrarily\n \n '''\n # get a list of similar users\n similar_users = find_similar_users(user_id, user_item=user_item)\n # add recommended articles iteratively\n recs = np.array([])\n for similar_user in similar_users:\n # concatenate articles not seen before\n row_data = user_item.loc[similar_user]\n interacted_articles = np.array(row_data[row_data>0].index)\n interacted_articles = np.setdiff1d(interacted_articles, recs)\n recs = np.concatenate([recs, interacted_articles])\n if len(recs) >= m:\n break\n recs = list(recs[:m])\n return recs # return your recommendations for this user_id ", "_____no_output_____" ], [ "# Check Results\nget_article_names(user_user_recs(1, 10)) # Return 10 recommendations for user 1", "_____no_output_____" ], [ "# Test your functions here - No need to change this code - just run this cell\nassert set(get_article_names(['1024.0', '1176.0', '1305.0', '1314.0', '1422.0', '1427.0'])) == set(['using deep learning to reconstruct high-resolution audio', 'build a python app on the streaming analytics service', 'gosales transactions for naive bayes model', 'healthcare python streaming application demo', 'use r dataframes & ibm watson natural language understanding', 'use xgboost, scikit-learn & ibm watson machine learning apis']), \"Oops! Your the get_article_names function doesn't work quite how we expect.\"\nassert set(get_article_names(['1320.0', '232.0', '844.0'])) == set(['housing (2015): united states demographic measures','self-service data preparation with ibm data refinery','use the cloudant-spark connector in python notebook']), \"Oops! Your the get_article_names function doesn't work quite how we expect.\"\nassert set(get_user_articles(20)[0]) == set(['1320.0', '232.0', '844.0'])\nassert set(get_user_articles(20)[1]) == set(['housing (2015): united states demographic measures', 'self-service data preparation with ibm data refinery','use the cloudant-spark connector in python notebook'])\nassert set(get_user_articles(2)[0]) == set(['1024.0', '1176.0', '1305.0', '1314.0', '1422.0', '1427.0'])\nassert set(get_user_articles(2)[1]) == set(['using deep learning to reconstruct high-resolution audio', 'build a python app on the streaming analytics service', 'gosales transactions for naive bayes model', 'healthcare python streaming application demo', 'use r dataframes & ibm watson natural language understanding', 'use xgboost, scikit-learn & ibm watson machine learning apis'])\nprint(\"If this is all you see, you passed all of our tests! Nice job!\")", "If this is all you see, you passed all of our tests! Nice job!\n" ] ], [ [ "`4.` Now we are going to improve the consistency of the **user_user_recs** function from above. \n\n* Instead of arbitrarily choosing when we obtain users who are all the same closeness to a given user - choose the users that have the most total article interactions before choosing those with fewer article interactions.\n\n\n* Instead of arbitrarily choosing articles from the user where the number of recommended articles starts below m and ends exceeding m, choose articles with the articles with the most total interactions before choosing those with fewer total interactions. This ranking should be what would be obtained from the **top_articles** function you wrote earlier.", "_____no_output_____" ] ], [ [ "def get_top_sorted_users(user_id, df=df, user_item=user_item):\n '''\n INPUT:\n user_id - (int)\n df - (pandas dataframe) df as defined at the top of the notebook \n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n \n OUTPUT:\n neighbors_df - (pandas dataframe) a dataframe with:\n neighbor_id - is a neighbor user_id\n similarity - measure of the similarity of each user to the provided user_id\n num_interactions - the number of articles viewed by the user - if a u\n \n Other Details - sort the neighbors_df by the similarity and then by number of interactions where \n highest of each is higher in the dataframe\n \n '''\n # create data frame\n neighbors_df = pd.DataFrame({\"similarity\": user_item.dot(user_item.loc[user_id]),\n \"num_interactions\": user_item.apply(lambda x: sum(x), axis=1)},\n index=user_item.index)\n # drop row at user_id\n neighbors_df = neighbors_df.drop(user_id)\n \n # sort by \"similarity\" and then num_interactions\n neighbors_df = neighbors_df.sort_values([\"similarity\", \"num_interactions\"], ascending=False)\n \n return neighbors_df # Return the dataframe specified in the doc_string\n\n\ndef user_user_recs_part2(user_id, m=10):\n '''\n INPUT:\n user_id - (int) a user id\n m - (int) the number of recommendations you want for the user\n \n OUTPUT:\n recs - (list) a list of recommendations for the user by article id\n rec_names - (list) a list of recommendations for the user by article title\n \n Description:\n Loops through the users based on closeness to the input user_id\n For each user - finds articles the user hasn't seen before and provides them as recs\n Does this until m recommendations are found\n \n Notes:\n * Choose the users that have the most total article interactions \n before choosing those with fewer article interactions.\n\n * Choose articles with the articles with the most total interactions \n before choosing those with fewer total interactions. \n \n '''\n # get neighbors that is sorted\n neighbors_df = get_top_sorted_users(user_id, df=df, user_item=user_item)\n \n # get ranked user ids\n similar_users = neighbors_df.index.tolist()\n \n # get ranked article ids\n recs = np.array([])\n for similar_user in similar_users:\n # obtain articles not seen before\n row_data = user_item.loc[similar_user]\n interacted_articles = np.array(row_data[row_data>0].index)\n interacted_articles = np.setdiff1d(interacted_articles, recs)\n # sort interacted_articles based on the number of interactions\n if len(interacted_articles)>0:\n interacted_articles = np.array(df[df.article_id.isin(\n list(interacted_articles))][\"article_id\"].value_counts().index)\n # concatenate to recs\n recs = np.concatenate([recs, interacted_articles])\n if len(recs) >= m:\n break\n recs = list(recs[:m])\n \n # get article names\n rec_names = get_article_names(recs, df=df)\n\n return recs, rec_names", "_____no_output_____" ], [ "# Quick spot check - don't change this code - just use it to test your functions\nrec_ids, rec_names = user_user_recs_part2(20, 10)\nprint(\"The top 10 recommendations for user 20 are the following article ids:\")\nprint(rec_ids)\nprint()\nprint(\"The top 10 recommendations for user 20 are the following article names:\")\nprint(rec_names)", "The top 10 recommendations for user 20 are the following article ids:\n[1429.0, 1330.0, 1314.0, 1293.0, 1162.0, 1271.0, 43.0, 1351.0, 1368.0, 1305.0]\n\nThe top 10 recommendations for user 20 are the following article names:\n['use deep learning for image classification', 'insights from new york car accident reports', 'healthcare python streaming application demo', 'finding optimal locations of new store using decision optimization', 'analyze energy consumption in buildings', 'customer demographics and sales', 'deep learning with tensorflow course by big data university', 'model bike sharing data with spss', 'putting a human face on machine learning', 'gosales transactions for naive bayes model']\n" ] ], [ [ "`5.` Use your functions from above to correctly fill in the solutions to the dictionary below. Then test your dictionary against the solution. Provide the code you need to answer each following the comments below.", "_____no_output_____" ] ], [ [ "### Tests with a dictionary of results\n\nuser1_most_sim = get_top_sorted_users(1).index.tolist()[0] # Find the user that is most similar to user 1 \nuser131_10th_sim = get_top_sorted_users(131).index.tolist()[10] # Find the 10th most similar user to user 131", "_____no_output_____" ], [ "## Dictionary Test Here\nsol_5_dict = {\n 'The user that is most similar to user 1.': user1_most_sim, \n 'The user that is the 10th most similar to user 131': user131_10th_sim,\n}\n\nt.sol_5_test(sol_5_dict)", "This all looks good! Nice job!\n" ] ], [ [ "`6.` If we were given a new user, which of the above functions would you be able to use to make recommendations? Explain. Can you think of a better way we might make recommendations? Use the cell below to explain a better method for new users.", "_____no_output_____" ], [ "**Provide your response here.**\n\nget_top_articles(). Since it is a new user with no interaction in any article, it is not possible to make recommendation with collaborative method. What we have in hand is the number of interactions with all users for each article, we could make recommendation of articles with most universal interactions. This method does not provide personalized recommendatin as we don't have any information on the new user.\n\nIf there is a better way for new user, I would like to make knowledge-based recommendation using prior knowledge about this new user, e.g., article preference, so that we could select the prefered articles accordingly. In this way, we might make better recommendations than the purely ranked ones.", "_____no_output_____" ], [ "`7.` Using your existing functions, provide the top 10 recommended articles you would provide for the a new user below. You can test your function against our thoughts to make sure we are all on the same page with how we might make a recommendation.", "_____no_output_____" ] ], [ [ "new_user = '0.0'\n\n# What would your recommendations be for this new user '0.0'? As a new user, they have no observed articles.\n# Provide a list of the top 10 article ids you would give to \nnew_user_recs = get_top_article_ids(10) # Your recommendations here\n\n", "_____no_output_____" ], [ "assert set(new_user_recs) == set(['1314.0','1429.0','1293.0','1427.0','1162.0','1364.0','1304.0','1170.0','1431.0','1330.0']), \"Oops! It makes sense that in this case we would want to recommend the most popular articles, because we don't know anything about these users.\"\n\nprint(\"That's right! Nice job!\")", "That's right! Nice job!\n" ] ], [ [ "### <a class=\"anchor\" id=\"Content-Recs\">Part IV: Content Based Recommendations (EXTRA - NOT REQUIRED)</a>\n\nAnother method we might use to make recommendations is to perform a ranking of the highest ranked articles associated with some term. You might consider content to be the **doc_body**, **doc_description**, or **doc_full_name**. There isn't one way to create a content based recommendation, especially considering that each of these columns hold content related information. \n\n`1.` Use the function body below to create a content based recommender. Since there isn't one right answer for this recommendation tactic, no test functions are provided. Feel free to change the function inputs if you decide you want to try a method that requires more input values. The input values are currently set with one idea in mind that you may use to make content based recommendations. One additional idea is that you might want to choose the most popular recommendations that meet your 'content criteria', but again, there is a lot of flexibility in how you might make these recommendations.\n\n### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills.", "_____no_output_____" ] ], [ [ "def make_content_recs():\n '''\n INPUT:\n \n OUTPUT:\n \n '''", "_____no_output_____" ] ], [ [ "`2.` Now that you have put together your content-based recommendation system, use the cell below to write a summary explaining how your content based recommender works. Do you see any possible improvements that could be made to your function? Is there anything novel about your content based recommender?\n\n### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills.", "_____no_output_____" ], [ "**Write an explanation of your content based recommendation system here.**", "_____no_output_____" ], [ "`3.` Use your content-recommendation system to make recommendations for the below scenarios based on the comments. Again no tests are provided here, because there isn't one right answer that could be used to find these content based recommendations.\n\n### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills.", "_____no_output_____" ] ], [ [ "# make recommendations for a brand new user\n\n\n# make a recommendations for a user who only has interacted with article id '1427.0'\n\n", "_____no_output_____" ] ], [ [ "### <a class=\"anchor\" id=\"Matrix-Fact\">Part V: Matrix Factorization</a>\n\nIn this part of the notebook, you will build use matrix factorization to make article recommendations to the users on the IBM Watson Studio platform.\n\n`1.` You should have already created a **user_item** matrix above in **question 1** of **Part III** above. This first question here will just require that you run the cells to get things set up for the rest of **Part V** of the notebook. ", "_____no_output_____" ] ], [ [ "# Load the matrix here\nuser_item_matrix = pd.read_pickle('user_item_matrix.p')", "_____no_output_____" ], [ "# quick look at the matrix\nuser_item_matrix.head()", "_____no_output_____" ] ], [ [ "`2.` In this situation, you can use Singular Value Decomposition from [numpy](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.svd.html) on the user-item matrix. Use the cell to perform SVD, and explain why this is different than in the lesson.", "_____no_output_____" ] ], [ [ "# Perform SVD on the User-Item Matrix Here\n\nu, s, vt = np.linalg.svd(user_item_matrix) # use the built in to get the three matrices", "_____no_output_____" ] ], [ [ "**Provide your response here.**\n\nThere is no missing value in user_item_matrix, which is why this time we get no error in implementing SVD function from numpy.", "_____no_output_____" ], [ "`3.` Now for the tricky part, how do we choose the number of latent features to use? Running the below cell, you can see that as the number of latent features increases, we obtain a lower error rate on making predictions for the 1 and 0 values in the user-item matrix. Run the cell below to get an idea of how the accuracy improves as we increase the number of latent features.", "_____no_output_____" ] ], [ [ "num_latent_feats = np.arange(10,700+10,20)\nsum_errs = []\n\nfor k in num_latent_feats:\n # restructure with k latent features\n s_new, u_new, vt_new = np.diag(s[:k]), u[:, :k], vt[:k, :]\n \n # take dot product\n user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new))\n \n # compute error for each prediction to actual value\n diffs = np.subtract(user_item_matrix, user_item_est)\n \n # total errors and keep track of them\n err = np.sum(np.sum(np.abs(diffs)))\n sum_errs.append(err)\n \n \nplt.plot(num_latent_feats, 1 - np.array(sum_errs)/df.shape[0]);\nplt.xlabel('Number of Latent Features');\nplt.ylabel('Accuracy');\nplt.title('Accuracy vs. Number of Latent Features');", "_____no_output_____" ] ], [ [ "`4.` From the above, we can't really be sure how many features to use, because simply having a better way to predict the 1's and 0's of the matrix doesn't exactly give us an indication of if we are able to make good recommendations. Instead, we might split our dataset into a training and test set of data, as shown in the cell below. \n\nUse the code from question 3 to understand the impact on accuracy of the training and test sets of data with different numbers of latent features. Using the split below: \n\n* How many users can we make predictions for in the test set? \n* How many users are we not able to make predictions for because of the cold start problem?\n* How many articles can we make predictions for in the test set? \n* How many articles are we not able to make predictions for because of the cold start problem?", "_____no_output_____" ] ], [ [ "df_train = df.head(40000)\ndf_test = df.tail(5993)\n\ndef create_test_and_train_user_item(df_train, df_test):\n '''\n INPUT:\n df_train - training dataframe\n df_test - test dataframe\n \n OUTPUT:\n user_item_train - a user-item matrix of the training dataframe \n (unique users for each row and unique articles for each column)\n user_item_test - a user-item matrix of the testing dataframe \n (unique users for each row and unique articles for each column)\n test_idx - all of the test user ids\n test_arts - all of the test article ids\n \n '''\n # user_item_train\n user_item_train = create_user_item_matrix(df_train)\n # user_item_test\n user_item_test = create_user_item_matrix(df_test)\n # test_idx\n test_idx = np.array(user_item_test.index)\n # test_arts\n test_arts = np.array(user_item_test.columns.tolist())\n \n return user_item_train, user_item_test, test_idx, test_arts\n\nuser_item_train, user_item_test, test_idx, test_arts = create_test_and_train_user_item(df_train, df_test)", "_____no_output_____" ], [ "print(\"How many users can we make predictions for in the test set?\",\n len(np.intersect1d(user_item_train.index, test_idx, assume_unique=True)))", "How many users can we make predictions for in the test set? 20\n" ], [ "print('How many users in the test set are we not able to make predictions for because of the cold start problem?',\n len(test_idx) - 20)", "How many users in the test set are we not able to make predictions for because of the cold start problem? 662\n" ], [ "print('How many articles can we make predictions for in the test set?',\n len(np.intersect1d(user_item_train.columns, test_arts, assume_unique=True)))", "How many articles can we make predictions for in the test set? 574\n" ], [ "print('How many articles in the test set are we not able to make predictions for because of the cold start problem?',\n len(test_arts)-574)", "How many articles in the test set are we not able to make predictions for because of the cold start problem? 0\n" ], [ "# Replace the values in the dictionary below\na = 662 \nb = 574 \nc = 20 \nd = 0 \n\n\nsol_4_dict = {\n 'How many users can we make predictions for in the test set?': c, # letter here, \n 'How many users in the test set are we not able to make predictions for because of the cold start problem?': a, # letter here, \n 'How many articles can we make predictions for in the test set?': b, # letter here,\n 'How many articles in the test set are we not able to make predictions for because of the cold start problem?': d # letter here\n}\n\nt.sol_4_test(sol_4_dict)", "Awesome job! That's right! All of the test movies are in the training data, but there are only 20 test users that were also in the training set. All of the other users that are in the test set we have no data on. Therefore, we cannot make predictions for these users using SVD.\n" ] ], [ [ "`5.` Now use the **user_item_train** dataset from above to find U, S, and V transpose using SVD. Then find the subset of rows in the **user_item_test** dataset that you can predict using this matrix decomposition with different numbers of latent features to see how many features makes sense to keep based on the accuracy on the test data. This will require combining what was done in questions `2` - `4`.\n\nUse the cells below to explore how well SVD works towards making predictions for recommendations on the test data. ", "_____no_output_____" ] ], [ [ "# fit SVD on the user_item_train matrix\nu_train, s_train, vt_train = np.linalg.svd(user_item_train) # fit svd similar to above then use the cells below", "_____no_output_____" ], [ "# Use these cells to see how well you can use the training \n# decomposition to predict on test data\n\n# selected user_item_test\ntest_idx_selected = np.intersect1d(test_idx, user_item_train.index)\nuser_item_test_selected = user_item_test.loc[test_idx_selected]\n\n# selected u_train\nrow_idx_selected = user_item_train.index.isin(test_idx)\nu_train_selected = u_train[row_idx_selected, :]\n\n# selected vt_train\ncol_idx_selected = user_item_train.columns.isin(test_arts)\nvt_train_selected = vt_train[:, col_idx_selected] ", "_____no_output_____" ], [ "num_latent_feats = np.arange(10, len(test_arts), 10)\nsum_errs = []\n\nfor k in num_latent_feats:\n # restructure with k latent features\n s_new, u_new, vt_new = np.diag(s_train[:k]), u_train_selected[:, :k], vt_train_selected[:k, :]\n \n # take dot product\n user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new))\n \n # compute error for each prediction to actual value\n diffs = np.subtract(user_item_test_selected, user_item_est)\n \n # total errors and keep track of them\n err = np.sum(np.sum(np.abs(diffs)))\n sum_errs.append(err)\n \n \nplt.plot(num_latent_feats, 1 - np.array(sum_errs)/(user_item_test_selected.shape[0]*\n user_item_test_selected.shape[1]));\nplt.xlabel('Number of Latent Features');\nplt.ylabel('Accuracy');\nplt.title('Accuracy vs. Number of Latent Features on Test Data');\nplt.grid(True)\nplt.show()", "_____no_output_____" ], [ "print(\"sparsity ratio:\",\n user_item_test_selected.sum().sum() / (user_item_test_selected.shape[0] * user_item_test_selected.shape[1]))", "sparsity ratio: 0.018989547038327528\n" ] ], [ [ "`6.` Use the cell below to comment on the results you found in the previous question. Given the circumstances of your results, discuss what you might do to determine if the recommendations you make with any of the above recommendation systems are an improvement to how users currently find articles? ", "_____no_output_____" ], [ "**Your response here.**\n\nAs we could see in the above plot, the accuracy looks ok(>0.964) on test data but keeps declining as we increase the number of latent features. It is likely that as only 20 users are tested on the test data and user_item_test_selected has a very high sparsity ratio, more latent features are implemented more far away the prediction on test data is from the ground truth.\n\nDue to limited size of test data, we might consider test our new recommendation system online with real user data. For example, we could run an A/B test to observe if the new recommender system performs better than the existing one by comparing the results, over a period of time, between the experiment group and the control group.", "_____no_output_____" ], [ "<a id='conclusions'></a>\n### Extras\nUsing your workbook, you could now save your recommendations for each user, develop a class to make new predictions and update your results, and make a flask app to deploy your results. These tasks are beyond what is required for this project. However, from what you learned in the lessons, you certainly capable of taking these tasks on to improve upon your work here!\n\n\n## Conclusion\n\n> Congratulations! You have reached the end of the Recommendations with IBM project! \n\n> **Tip**: Once you are satisfied with your work here, check over your report to make sure that it is satisfies all the areas of the [rubric](https://review.udacity.com/#!/rubrics/2322/view). You should also probably remove all of the \"Tips\" like this one so that the presentation is as polished as possible.\n\n\n## Directions to Submit\n\n> Before you submit your project, you need to create a .html or .pdf version of this notebook in the workspace here. To do that, run the code cell below. If it worked correctly, you should get a return code of 0, and you should see the generated .html file in the workspace directory (click on the orange Jupyter icon in the upper left).\n\n> Alternatively, you can download this report as .html via the **File** > **Download as** submenu, and then manually upload it into the workspace directory by clicking on the orange Jupyter icon in the upper left, then using the Upload button.\n\n> Once you've done this, you can submit your project by clicking on the \"Submit Project\" button in the lower right here. This will create and submit a zip file with this .ipynb doc and the .html or .pdf version you created. Congratulations! ", "_____no_output_____" ] ], [ [ "from subprocess import call\ncall(['python', '-m', 'nbconvert', 'Recommendations_with_IBM.ipynb'])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ] ]
cbde5fe7285a2ae89e50696d5f0a251ac145a354
259,222
ipynb
Jupyter Notebook
lab_notebooks/NYT-Magazine Classifier V1.ipynb
Atomahawk/print-journalism-topic-models
f9b6c57de38f9300eaae4bab4f53ef868e34c3eb
[ "MIT" ]
4
2018-02-20T21:15:38.000Z
2020-04-17T17:42:11.000Z
lab_notebooks/NYT-Magazine Classifier V1.ipynb
Atomahawk/print-journalism-topic-models
f9b6c57de38f9300eaae4bab4f53ef868e34c3eb
[ "MIT" ]
null
null
null
lab_notebooks/NYT-Magazine Classifier V1.ipynb
Atomahawk/print-journalism-topic-models
f9b6c57de38f9300eaae4bab4f53ef868e34c3eb
[ "MIT" ]
null
null
null
53.032324
1,634
0.486247
[ [ [ "# Model Development V1\n- This is really more like scratchwork\n- Divide this into multiple notebooks for easier reading\n\n**Reference**\n- http://zacstewart.com/2014/08/05/pipelines-of-featureunions-of-pipelines.html", "_____no_output_____" ] ], [ [ "import json\nimport pickle\nfrom pymongo import MongoClient\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n%matplotlib inline\n\nimport nltk\nimport os\nfrom nltk.corpus import stopwords\nfrom sklearn.utils.extmath import randomized_svd\n\n# gensim\nfrom gensim import corpora, models, similarities, matutils\n# sklearn\nfrom sklearn import datasets\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.cluster import KMeans\nfrom sklearn.neighbors import KNeighborsClassifier\nimport sklearn.metrics.pairwise as smp\n\n\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)", "_____no_output_____" ] ], [ [ "# NYT Corpus", "_____no_output_____" ], [ "## Read data in\n- pickle from mongod output on amazon ec2 instance\n\nscp -i ~/.ssh/aws_andrew [email protected]:/home/andrew/Notebooks/initial-model-df.pkl ~/ds/metis/challenges/", "_____no_output_____" ] ], [ [ "with open('initial-model-df.pkl', 'rb') as nyt_data:\n df = pickle.load(nyt_data)", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "df.head(30)", "_____no_output_____" ], [ "df1 = df.dropna()", "_____no_output_____" ] ], [ [ "## LSI Preprocessing", "_____no_output_____" ] ], [ [ "# docs = data['lead_paragraph'][0:100]\ndocs = df1['lead_paragraph']", "_____no_output_____" ], [ "docs.shape", "_____no_output_____" ], [ "for doc in docs:\n doc = doc.decode(\"utf8\")", "_____no_output_____" ], [ "# create a list of stopwords\nstopwords_set = frozenset(stopwords.words('english'))\n\n# Update iterator to remove stopwords\nclass SentencesIterator(object):\n # giving 'stop' a list of stopwords would exclude them\n def __init__(self, dirname, stop=None):\n self.dirname = dirname\n \n def __iter__(self):\n # os.listdr is ALSO a generator\n for fname in os.listdir(self.dirname):\n for line in open(os.path.join(self.dirname, fname),encoding=\"latin-1\"):\n # at each step, gensim needs a list of words\n line = line.lower().split()\n if stop:\n outline = [] \n for word in line:\n if word not in stopwords_set:\n outline.append(word)\n yield outline\n else:\n yield line", "_____no_output_____" ], [ "docs1 = docs.dropna()", "_____no_output_____" ], [ "for doc in docs1:\n doc = SentencesIterator(doc.decode(\"utf8\"))", "_____no_output_____" ], [ "docs = pd.Series.tolist(docs1)", "_____no_output_____" ], [ "tfidf = TfidfVectorizer(stop_words=\"english\", \n token_pattern=\"\\\\b[a-zA-Z][a-zA-Z]+\\\\b\", \n min_df=10)\n\ntfidf_vecs = tfidf.fit_transform(docs)", "_____no_output_____" ], [ "tfidf_vecs.shape\n\n# it's too big to see in a dataframe:\n# pd.DataFrame(tfidf_vecs.todense(), \n# columns=tfidf.get_feature_names()\n# ).head(30)", "_____no_output_____" ] ], [ [ "## BASELINE: Multinomial Naive Bayes Classification\n- language is fundamentally different\n- captures word choice", "_____no_output_____" ] ], [ [ "pd.DataFrame(tfidf_vecs.todense(), \n columns=tfidf.get_feature_names()\n ).head()", "_____no_output_____" ], [ "df1.shape, tfidf_vecs.shape", "_____no_output_____" ], [ "# Train/Test split\nX_train, X_test, y_train, y_test = train_test_split(tfidf_vecs, df1['source'], test_size=0.33)\n\n# Train \nnb = MultinomialNB()\nnb.fit(X_train, y_train)\n\n# Test \nnb.score(X_test, y_test)", "_____no_output_____" ] ], [ [ "# LSI Begin\n**Essentially, this has been my workflow so far:**\n1. TFIDF in sklearn --> output a sparse corpus matrix DTM\n2. LSI (SVD) in gensim --> output a 300 dim matrix TDM\n - Analyze topic vectors\n3. Viewed LSI[tfidf]", "_____no_output_____" ] ], [ [ "# terms by docs instead of docs by terms\ntfidf_corpus = matutils.Sparse2Corpus(tfidf_vecs.transpose())\n\n# Row indices\nid2word = dict((v, k) for k, v in tfidf.vocabulary_.items())\n\n# This is a hack for Python 3!\nid2word = corpora.Dictionary.from_corpus(tfidf_corpus, \n id2word=id2word)", "2017-06-02 06:53:08,735 : INFO : adding document #0 to Dictionary(0 unique tokens: [])\n2017-06-02 06:53:09,009 : INFO : adding document #10000 to Dictionary(0 unique tokens: [])\n2017-06-02 06:53:09,250 : INFO : adding document #20000 to Dictionary(0 unique tokens: [])\n2017-06-02 06:53:09,472 : INFO : adding document #30000 to Dictionary(0 unique tokens: [])\n2017-06-02 06:53:09,754 : INFO : adding document #40000 to Dictionary(0 unique tokens: [])\n2017-06-02 06:53:09,940 : INFO : adding document #50000 to Dictionary(0 unique tokens: [])\n2017-06-02 06:53:10,197 : INFO : adding document #60000 to Dictionary(0 unique tokens: [])\n2017-06-02 06:53:10,354 : INFO : built Dictionary(11552 unique tokens: ['week', 'year', 'begin', 'traders', 'following']...) from 65730 documents (total 241491 corpus positions)\n" ], [ "# Build an LSI space from the input TFIDF matrix, mapping of row id to word, and num_topics\n# num_topics is the number of dimensions (k) to reduce to after the SVD\n\n# Analagous to \"fit\" in sklearn, it primes an LSI space trained to 300-500 dimensions\nlsi = models.LsiModel(tfidf_corpus, id2word=id2word, num_topics=300)", "2017-06-01 17:57:40,661 : INFO : using serial LSI version on this node\n2017-06-01 17:57:40,663 : INFO : updating model with new documents\n2017-06-01 17:57:40,897 : INFO : preparing a new chunk of documents\n2017-06-01 17:57:41,118 : INFO : using 100 extra samples and 2 power iterations\n2017-06-01 17:57:41,119 : INFO : 1st phase: constructing (10982, 400) action matrix\n2017-06-01 17:57:41,789 : INFO : orthonormalizing (10982, 400) action matrix\n2017-06-01 17:57:44,333 : INFO : 2nd phase: running dense svd on (400, 20000) matrix\n2017-06-01 17:57:45,361 : INFO : computing the final decomposition\n2017-06-01 17:57:45,362 : INFO : keeping 300 factors (discarding 13.515% of energy spectrum)\n2017-06-01 17:57:45,466 : INFO : processed documents up to #20000\n2017-06-01 17:57:45,473 : INFO : topic #0(13.238): 0.275*\"said\" + 0.251*\"company\" + 0.216*\"percent\" + 0.189*\"billion\" + 0.181*\"year\" + 0.175*\"new\" + 0.142*\"million\" + 0.120*\"quarter\" + 0.111*\"president\" + 0.109*\"business\"\n2017-06-01 17:57:45,475 : INFO : topic #1(8.899): -0.344*\"percent\" + 0.264*\"president\" + 0.237*\"obama\" + -0.234*\"quarter\" + -0.204*\"billion\" + 0.190*\"new\" + -0.165*\"company\" + -0.163*\"profit\" + 0.155*\"state\" + -0.150*\"fourth\"\n2017-06-01 17:57:45,477 : INFO : topic #2(7.691): -0.363*\"company\" + 0.333*\"percent\" + -0.275*\"chief\" + -0.270*\"executive\" + 0.257*\"obama\" + 0.239*\"president\" + -0.130*\"new\" + 0.122*\"quarter\" + -0.119*\"business\" + 0.117*\"state\"\n2017-06-01 17:57:45,478 : INFO : topic #3(7.264): 0.322*\"company\" + 0.258*\"president\" + 0.247*\"obama\" + -0.227*\"new\" + 0.208*\"billion\" + 0.194*\"chief\" + 0.191*\"executive\" + 0.183*\"said\" + -0.133*\"economy\" + -0.133*\"states\"\n2017-06-01 17:57:45,480 : INFO : topic #4(6.658): -0.609*\"new\" + -0.209*\"york\" + 0.208*\"united\" + 0.204*\"states\" + 0.152*\"chief\" + 0.146*\"jobs\" + 0.143*\"executive\" + 0.141*\"bank\" + -0.136*\"million\" + 0.136*\"said\"\n2017-06-01 17:57:45,668 : INFO : preparing a new chunk of documents\n2017-06-01 17:57:45,827 : INFO : using 100 extra samples and 2 power iterations\n2017-06-01 17:57:45,828 : INFO : 1st phase: constructing (10982, 400) action matrix\n2017-06-01 17:57:46,331 : INFO : orthonormalizing (10982, 400) action matrix\n2017-06-01 17:57:47,996 : INFO : 2nd phase: running dense svd on (400, 20000) matrix\n2017-06-01 17:57:49,379 : INFO : computing the final decomposition\n2017-06-01 17:57:49,380 : INFO : keeping 300 factors (discarding 13.344% of energy spectrum)\n2017-06-01 17:57:49,479 : INFO : merging projections: (10982, 300) + (10982, 300)\n2017-06-01 17:57:49,886 : INFO : keeping 300 factors (discarding 13.015% of energy spectrum)\n2017-06-01 17:57:50,026 : INFO : processed documents up to #40000\n2017-06-01 17:57:50,027 : INFO : topic #0(17.491): 0.238*\"said\" + 0.194*\"new\" + 0.189*\"president\" + 0.183*\"percent\" + 0.167*\"year\" + 0.157*\"company\" + 0.146*\"obama\" + 0.135*\"billion\" + 0.112*\"federal\" + 0.108*\"states\"\n2017-06-01 17:57:50,029 : INFO : topic #1(12.237): 0.405*\"president\" + 0.375*\"obama\" + -0.326*\"percent\" + -0.167*\"company\" + -0.150*\"year\" + -0.148*\"quarter\" + -0.143*\"billion\" + 0.135*\"house\" + 0.134*\"republican\" + -0.118*\"said\"\n2017-06-01 17:57:50,031 : INFO : topic #2(10.268): -0.419*\"percent\" + -0.336*\"president\" + 0.336*\"new\" + -0.336*\"obama\" + -0.152*\"quarter\" + -0.133*\"year\" + -0.115*\"billion\" + 0.113*\"people\" + 0.110*\"states\" + -0.105*\"rose\"\n2017-06-01 17:57:50,033 : INFO : topic #3(9.531): -0.421*\"states\" + -0.381*\"united\" + 0.369*\"company\" + 0.193*\"chief\" + 0.185*\"executive\" + 0.182*\"said\" + 0.161*\"billion\" + -0.158*\"economy\" + -0.142*\"economic\" + 0.132*\"mr\"\n2017-06-01 17:57:50,035 : INFO : topic #4(9.224): 0.515*\"new\" + -0.324*\"states\" + -0.318*\"united\" + 0.265*\"percent\" + -0.239*\"said\" + -0.237*\"company\" + 0.149*\"york\" + -0.137*\"billion\" + -0.132*\"chief\" + -0.131*\"executive\"\n2017-06-01 17:57:50,219 : INFO : preparing a new chunk of documents\n2017-06-01 17:57:50,372 : INFO : using 100 extra samples and 2 power iterations\n2017-06-01 17:57:50,373 : INFO : 1st phase: constructing (10982, 400) action matrix\n2017-06-01 17:57:50,870 : INFO : orthonormalizing (10982, 400) action matrix\n2017-06-01 17:57:52,520 : INFO : 2nd phase: running dense svd on (400, 18727) matrix\n2017-06-01 17:57:53,861 : INFO : computing the final decomposition\n2017-06-01 17:57:53,862 : INFO : keeping 300 factors (discarding 13.109% of energy spectrum)\n2017-06-01 17:57:53,963 : INFO : merging projections: (10982, 300) + (10982, 300)\n2017-06-01 17:57:54,373 : INFO : keeping 300 factors (discarding 9.038% of energy spectrum)\n2017-06-01 17:57:54,510 : INFO : processed documents up to #58727\n2017-06-01 17:57:54,511 : INFO : topic #0(21.168): 0.235*\"president\" + 0.222*\"said\" + 0.193*\"new\" + 0.193*\"obama\" + 0.157*\"year\" + 0.150*\"percent\" + 0.137*\"health\" + 0.124*\"company\" + 0.123*\"federal\" + 0.114*\"billion\"\n2017-06-01 17:57:54,513 : INFO : topic #1(15.148): 0.409*\"president\" + 0.400*\"obama\" + -0.287*\"percent\" + 0.175*\"health\" + -0.167*\"year\" + -0.162*\"company\" + -0.144*\"said\" + -0.138*\"billion\" + 0.136*\"care\" + 0.135*\"house\"\n2017-06-01 17:57:54,515 : INFO : topic #2(12.468): 0.409*\"health\" + -0.364*\"president\" + -0.357*\"obama\" + 0.289*\"care\" + -0.267*\"percent\" + 0.243*\"new\" + 0.122*\"insurance\" + 0.118*\"law\" + -0.111*\"quarter\" + -0.107*\"year\"\n2017-06-01 17:57:54,517 : INFO : topic #3(12.151): -0.563*\"health\" + -0.388*\"care\" + -0.286*\"percent\" + 0.213*\"new\" + -0.134*\"insurance\" + 0.121*\"states\" + -0.121*\"obama\" + -0.118*\"quarter\" + 0.114*\"united\" + 0.096*\"republican\"\n2017-06-01 17:57:54,518 : INFO : topic #4(11.290): -0.423*\"states\" + -0.372*\"united\" + 0.251*\"new\" + 0.224*\"company\" + -0.177*\"federal\" + -0.157*\"bank\" + -0.152*\"economic\" + 0.148*\"house\" + 0.136*\"said\" + -0.133*\"economy\"\n" ], [ "# Retrieve vectors for the original tfidf corpus in the LSI space (\"transform\" in sklearn)\nlsi_corpus = lsi[tfidf_corpus] # pass using square brackets\n# what are the values given by lsi? (topic distributions)\n\n# ALSO, IT IS LAZY! IT WON'T ACTUALLY DO THE TRANSFORMING COMPUTATION UNTIL ITS CALLED. IT STORES THE INSTRUCTIONS\n\n# Dump the resulting document vectors into a list so we can take a look\ndoc_vecs = [doc for doc in lsi_corpus]\ndoc_vecs[0] #print the first document vector for all the words", "_____no_output_____" ] ], [ [ "## Doc-Term Cosine Similarity using LSI Corpus\n- cosine similarity of [docs to terms](http://localhost:8888/notebooks/ds/metis/classnotes/5.24.17%20Vector%20Space%20Models%2C%20NMF%2C%20W2V.ipynb#Toy-Example:-Conceptual-Similarity-Between-Arbitrary-Text-Blobs)", "_____no_output_____" ] ], [ [ "# Convert the gensim-style corpus vecs to a numpy array for sklearn manipulations\nnyt_lsi = matutils.corpus2dense(lsi_corpus, num_terms=300).transpose()", "_____no_output_____" ], [ "nyt_lsi.shape", "_____no_output_____" ], [ "lsi.show_topic(0)", "_____no_output_____" ], [ "# Create an index transformer that calculates similarity based on our space\nindex = similarities.MatrixSimilarity(lsi_corpus, num_features=len(id2word))", "2017-06-01 17:58:20,168 : INFO : creating matrix with 58727 documents and 10982 features\n" ], [ "# all docs by 300 topic vectors (word vectors)\npd.DataFrame(nyt_lsi).head()\n\n# need to transform by cosine similarity\n# look up if I need to change into an LDA corpus", "_____no_output_____" ], [ "# take the mean of every word vector! (averaged across all document vectors)\ndf.mean()", "_____no_output_____" ], [ "# describes word usage ('meaning') across the body of documents in the nyt corpus\n# answers the question: what 'topics' has the nyt been talking about the most over 2005-2015?\ndf.mean().sort_values()", "_____no_output_____" ] ], [ [ "# Sorted doc-doc cosine similarity!", "_____no_output_____" ] ], [ [ "# Create an index transformer that calculates similarity based on our space\nindex = similarities.MatrixSimilarity(doc_vecs, num_features=len(id2word))", "_____no_output_____" ], [ "# Return the sorted list of cosine similarities to the first document\nsims = sorted(enumerate(index[doc_vecs[0]]), key=lambda item: -item[1])\nsims\n\n# Document 1491 is very similar (.66) to document 0", "_____no_output_____" ], [ "# Let's take a look at how we did by analyzing syntax\nfor sim_doc_id, sim_score in enumerate(sims[0:30]): \n print(\"DocumentID: {}, Similarity Score: {} \".format(sim_score[0], sim_score[1]))\n print(\"Headline: \" + str(df1.iloc[sim_doc_id].headline.decode('utf-8')))\n print(\"Lead Paragraph: \" + str(df1.iloc[sim_doc_id].lead_paragraph.decode('utf-8')))\n print(\"Publish Date: \" + str(df1.iloc[sim_doc_id].date))\n print('\\n')", "_____no_output_____" ] ], [ [ "## Pass into KMeans Clustering", "_____no_output_____" ] ], [ [ "# Convert the gensim-style corpus vecs to a numpy array for sklearn manipulations (back to docs to terms matrix)\nnyt_lsi = matutils.corpus2dense(lsi_corpus, num_terms=300).transpose()\nnyt_lsi.shape", "_____no_output_____" ], [ "# Create KMeans. \nkmeans = KMeans(n_clusters=3)\n\n# Cluster\nnyt_lsi_clusters = kmeans.fit_predict(nyt_lsi)", "_____no_output_____" ], [ "# Take a look. It likely didn't do cosine distances.\nprint(nyt_lsi_clusters[0:50])\nprint(\"Lead Paragraph: \\n\" + str(df1.iloc[0:5].lead_paragraph))", "[0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 2 0 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 0 1 1]\nLead Paragraph: \n0 b\"THE first week of the year may begin with tr...\n1 b'I ALWAYS wanted to be a journalist and cover...\n2 b\"The Original Gourmet Brunch, a restaurant on...\n3 b\"Not too long ago it snowed in New York City....\n4 b'IMAGINE loving a hotel room so much that you...\nName: lead_paragraph, dtype: object\n" ] ], [ [ "## LSA Begin", "_____no_output_____" ] ], [ [ "lda = models.LdaModel(corpus=tfidf_corpus, num_topics=20, id2word=id2word, passes=3)\n\nlda.print_topics()", "2017-06-02 06:53:20,196 : INFO : using symmetric alpha at 0.05\n2017-06-02 06:53:20,198 : INFO : using symmetric eta at 8.65650969529e-05\n2017-06-02 06:53:20,202 : INFO : using serial LDA version on this node\n2017-06-02 06:53:21,447 : INFO : running online LDA training, 20 topics, 3 passes over the supplied corpus of 65730 documents, updating model once every 2000 documents, evaluating perplexity every 20000 documents, iterating 50x with a convergence threshold of 0.001000\n2017-06-02 06:53:21,466 : INFO : PROGRESS: pass 0, at document #2000/65730\n2017-06-02 06:53:22,792 : INFO : merging changes from 2000 documents into a model of 65730 documents\n2017-06-02 06:53:22,889 : INFO : topic #2 (0.050): 0.005*\"new\" + 0.003*\"said\" + 0.003*\"billion\" + 0.003*\"commercials\" + 0.003*\"year\" + 0.003*\"play\" + 0.003*\"insurance\" + 0.003*\"years\" + 0.003*\"time\" + 0.002*\"come\"\n2017-06-02 06:53:22,890 : INFO : topic #4 (0.050): 0.005*\"new\" + 0.004*\"said\" + 0.004*\"senator\" + 0.003*\"mr\" + 0.003*\"group\" + 0.003*\"chief\" + 0.003*\"billion\" + 0.002*\"company\" + 0.002*\"market\" + 0.002*\"run\"\n2017-06-02 06:53:22,892 : INFO : topic #9 (0.050): 0.005*\"said\" + 0.004*\"mr\" + 0.004*\"business\" + 0.003*\"new\" + 0.003*\"companies\" + 0.003*\"bush\" + 0.003*\"year\" + 0.003*\"company\" + 0.003*\"executive\" + 0.003*\"senator\"\n2017-06-02 06:53:22,894 : INFO : topic #14 (0.050): 0.004*\"mr\" + 0.004*\"said\" + 0.004*\"run\" + 0.004*\"company\" + 0.004*\"new\" + 0.003*\"video\" + 0.003*\"like\" + 0.003*\"week\" + 0.003*\"agency\" + 0.002*\"enron\"\n2017-06-02 06:53:22,896 : INFO : topic #18 (0.050): 0.004*\"said\" + 0.004*\"bush\" + 0.003*\"company\" + 0.003*\"million\" + 0.003*\"new\" + 0.003*\"business\" + 0.003*\"year\" + 0.003*\"world\" + 0.003*\"billion\" + 0.003*\"president\"\n2017-06-02 06:53:22,899 : INFO : topic diff=17.223306, rho=1.000000\n2017-06-02 06:53:22,925 : INFO : PROGRESS: pass 0, at document #4000/65730\n2017-06-02 06:53:24,280 : INFO : merging changes from 2000 documents into a model of 65730 documents\n2017-06-02 06:53:24,482 : INFO : topic #17 (0.050): 0.005*\"run\" + 0.005*\"general\" + 0.004*\"said\" + 0.004*\"chief\" + 0.004*\"new\" + 0.003*\"governor\" + 0.003*\"executive\" + 0.003*\"goldman\" + 0.003*\"company\" + 0.003*\"year\"\n2017-06-02 06:53:24,484 : INFO : topic #12 (0.050): 0.005*\"search\" + 0.004*\"million\" + 0.004*\"state\" + 0.004*\"media\" + 0.004*\"new\" + 0.004*\"china\" + 0.004*\"sell\" + 0.004*\"run\" + 0.003*\"struggled\" + 0.003*\"american\"\n2017-06-02 06:53:24,487 : INFO : topic #5 (0.050): 0.012*\"obama\" + 0.007*\"barack\" + 0.007*\"hillary\" + 0.006*\"clinton\" + 0.006*\"rodham\" + 0.006*\"new\" + 0.005*\"primary\" + 0.005*\"mobile\" + 0.004*\"senator\" + 0.004*\"run\"\n2017-06-02 06:53:24,489 : INFO : topic #10 (0.050): 0.007*\"scheme\" + 0.006*\"answering\" + 0.006*\"editor\" + 0.005*\"federal\" + 0.004*\"new\" + 0.004*\"general\" + 0.004*\"john\" + 0.004*\"questions\" + 0.004*\"bank\" + 0.004*\"feb\"\n2017-06-02 06:53:24,491 : INFO : topic #4 (0.050): 0.010*\"obama\" + 0.006*\"new\" + 0.005*\"greece\" + 0.005*\"provided\" + 0.004*\"barack\" + 0.004*\"primary\" + 0.004*\"senator\" + 0.004*\"transcript\" + 0.003*\"supporters\" + 0.003*\"following\"\n2017-06-02 06:53:24,494 : INFO : topic diff=0.737651, rho=0.707107\n2017-06-02 06:53:24,510 : INFO : PROGRESS: pass 0, at document #6000/65730\n2017-06-02 06:53:25,938 : INFO : merging changes from 2000 documents into a model of 65730 documents\n2017-06-02 06:53:26,089 : INFO : topic #0 (0.050): 0.006*\"said\" + 0.005*\"republican\" + 0.005*\"richard\" + 0.004*\"counts\" + 0.004*\"daley\" + 0.004*\"mayor\" + 0.004*\"state\" + 0.004*\"run\" + 0.004*\"creditors\" + 0.004*\"conspiracy\"\n2017-06-02 06:53:26,090 : INFO : topic #17 (0.050): 0.006*\"goldman\" + 0.005*\"chief\" + 0.005*\"said\" + 0.004*\"shooting\" + 0.004*\"general\" + 0.004*\"monday\" + 0.004*\"applications\" + 0.004*\"executive\" + 0.004*\"sachs\" + 0.004*\"hired\"\n2017-06-02 06:53:26,092 : INFO : topic #5 (0.050): 0.009*\"clinton\" + 0.009*\"obama\" + 0.008*\"hillary\" + 0.007*\"rodham\" + 0.005*\"accounts\" + 0.005*\"candidates\" + 0.005*\"run\" + 0.004*\"presidential\" + 0.004*\"new\" + 0.004*\"challenged\"\n2017-06-02 06:53:26,094 : INFO : topic #14 (0.050): 0.004*\"contest\" + 0.004*\"original\" + 0.004*\"veterans\" + 0.004*\"mr\" + 0.004*\"ballot\" + 0.003*\"readers\" + 0.003*\"like\" + 0.003*\"new\" + 0.003*\"tenure\" + 0.003*\"republican\"\n2017-06-02 06:53:26,096 : INFO : topic #19 (0.050): 0.006*\"ipad\" + 0.004*\"sports\" + 0.004*\"perry\" + 0.004*\"rick\" + 0.004*\"new\" + 0.003*\"huckabee\" + 0.003*\"elect\" + 0.003*\"won\" + 0.003*\"governments\" + 0.003*\"run\"\n2017-06-02 06:53:26,099 : INFO : topic diff=0.565785, rho=0.577350\n2017-06-02 06:53:26,114 : INFO : PROGRESS: pass 0, at document #8000/65730\n2017-06-02 06:53:27,328 : INFO : merging changes from 2000 documents into a model of 65730 documents\n2017-06-02 06:53:27,461 : INFO : topic #10 (0.050): 0.011*\"unemployment\" + 0.007*\"answering\" + 0.006*\"bank\" + 0.005*\"editor\" + 0.005*\"questions\" + 0.005*\"loan\" + 0.005*\"unemployed\" + 0.005*\"weak\" + 0.005*\"federal\" + 0.005*\"said\"\n2017-06-02 06:53:27,462 : INFO : topic #18 (0.050): 0.005*\"updated\" + 0.005*\"billion\" + 0.005*\"said\" + 0.004*\"company\" + 0.004*\"new\" + 0.004*\"transition\" + 0.004*\"loss\" + 0.004*\"cnbc\" + 0.004*\"improve\" + 0.004*\"fought\"\n2017-06-02 06:53:27,464 : INFO : topic #9 (0.050): 0.017*\"downturn\" + 0.010*\"jobs\" + 0.006*\"mortgage\" + 0.006*\"eliminate\" + 0.006*\"payments\" + 0.006*\"obama\" + 0.005*\"economy\" + 0.005*\"factories\" + 0.005*\"president\" + 0.005*\"emanuel\"\n2017-06-02 06:53:27,466 : INFO : topic #16 (0.050): 0.008*\"prepared\" + 0.008*\"slowdown\" + 0.008*\"answered\" + 0.007*\"questions\" + 0.006*\"save\" + 0.005*\"readers\" + 0.005*\"president\" + 0.004*\"struggles\" + 0.004*\"economic\" + 0.004*\"recession\"\n2017-06-02 06:53:27,468 : INFO : topic #2 (0.050): 0.010*\"recovery\" + 0.008*\"economic\" + 0.006*\"survey\" + 0.005*\"super\" + 0.005*\"new\" + 0.005*\"losing\" + 0.005*\"economy\" + 0.005*\"falling\" + 0.005*\"billion\" + 0.004*\"boeing\"\n2017-06-02 06:53:27,470 : INFO : topic diff=0.373545, rho=0.500000\n2017-06-02 06:53:27,484 : INFO : PROGRESS: pass 0, at document #10000/65730\n2017-06-02 06:53:28,676 : INFO : merging changes from 2000 documents into a model of 65730 documents\n2017-06-02 06:53:28,799 : INFO : topic #13 (0.050): 0.008*\"cuts\" + 0.005*\"new\" + 0.004*\"jobs\" + 0.004*\"company\" + 0.004*\"teachers\" + 0.004*\"companies\" + 0.004*\"spending\" + 0.004*\"tax\" + 0.004*\"job\" + 0.004*\"subsidies\"\n2017-06-02 06:53:28,800 : INFO : topic #18 (0.050): 0.011*\"updated\" + 0.005*\"company\" + 0.005*\"obama\" + 0.004*\"improve\" + 0.004*\"cnbc\" + 0.004*\"said\" + 0.004*\"billion\" + 0.004*\"new\" + 0.004*\"session\" + 0.004*\"president\"\n2017-06-02 06:53:28,802 : INFO : topic #10 (0.050): 0.020*\"unemployment\" + 0.007*\"labor\" + 0.006*\"federal\" + 0.006*\"rate\" + 0.006*\"bank\" + 0.006*\"apple\" + 0.005*\"unemployed\" + 0.005*\"reserve\" + 0.005*\"weak\" + 0.005*\"said\"\n2017-06-02 06:53:28,803 : INFO : topic #15 (0.050): 0.007*\"carolina\" + 0.005*\"south\" + 0.005*\"obama\" + 0.005*\"transcript\" + 0.005*\"president\" + 0.005*\"construction\" + 0.005*\"service\" + 0.005*\"following\" + 0.005*\"labor\" + 0.004*\"democratic\"\n2017-06-02 06:53:28,805 : INFO : topic #1 (0.050): 0.008*\"health\" + 0.007*\"crisis\" + 0.007*\"obama\" + 0.007*\"valley\" + 0.005*\"package\" + 0.005*\"silicon\" + 0.005*\"news\" + 0.005*\"web\" + 0.005*\"administration\" + 0.004*\"president\"\n2017-06-02 06:53:28,807 : INFO : topic diff=0.378810, rho=0.447214\n2017-06-02 06:53:29,370 : INFO : PROGRESS: pass 0, at document #12000/65730\n2017-06-02 06:53:30,974 : INFO : merging changes from 2000 documents into a model of 65730 documents\n2017-06-02 06:53:31,090 : INFO : topic #7 (0.050): 0.007*\"jobs\" + 0.006*\"said\" + 0.005*\"cuts\" + 0.005*\"invest\" + 0.004*\"slow\" + 0.004*\"publishing\" + 0.004*\"los\" + 0.004*\"company\" + 0.004*\"partly\" + 0.004*\"urban\"\n2017-06-02 06:53:31,091 : INFO : topic #17 (0.050): 0.006*\"applications\" + 0.006*\"chief\" + 0.006*\"executive\" + 0.005*\"said\" + 0.005*\"jobs\" + 0.004*\"politicians\" + 0.004*\"euro\" + 0.004*\"stopped\" + 0.004*\"bankers\" + 0.004*\"june\"\n2017-06-02 06:53:31,093 : INFO : topic #11 (0.050): 0.005*\"adjusted\" + 0.004*\"combat\" + 0.003*\"walker\" + 0.003*\"improving\" + 0.003*\"education\" + 0.003*\"favor\" + 0.003*\"creative\" + 0.003*\"aid\" + 0.003*\"states\" + 0.003*\"posts\"\n2017-06-02 06:53:31,095 : INFO : topic #13 (0.050): 0.005*\"cuts\" + 0.005*\"new\" + 0.005*\"company\" + 0.004*\"prime\" + 0.004*\"city\" + 0.004*\"companies\" + 0.004*\"jobs\" + 0.004*\"spending\" + 0.004*\"business\" + 0.003*\"layoffs\"\n" ], [ "lda_corpus = lda[tfidf_corpus]", "_____no_output_____" ], [ "nyt_lda = matutils.corpus2dense(lda_corpus, num_terms=20).transpose()\ndf3 = pd.DataFrame(nyt_lda)", "_____no_output_____" ], [ "df3.mean().sort_values(ascending=False).head(10)", "_____no_output_____" ] ], [ [ "## Logistic Regression / Random Forest\n- <s>Tried KNN Classifier </s> Destroyed me\n- probabilistic classification on a spectrum from nyt to natl enq", "_____no_output_____" ] ], [ [ "from sklearn.neighbors import KNeighborsClassifier\nimport sklearn.metrics.pairwise as smp", "_____no_output_____" ], [ "# Train/Test\nX_train, X_test, y_train, y_test = train_test_split(nyt_lsi, df1['source'], \n test_size=0.33)", "_____no_output_____" ], [ "# X_train = X_train.reshape(1,-1)\n# X_test = X_test.reshape(1,-1)\n\ny_train = np.reshape(y_train.values, (-1,1))\ny_test = np.reshape(y_test.values, (-1,1))", "_____no_output_____" ], [ "X_train.shape, X_test.shape", "_____no_output_____" ], [ "y_train.shape, y_test.shape", "_____no_output_____" ], [ "# WARNING: This ruined me\n# Need pairwise Cosine for KNN\n\n# Fit KNN classifier to training set with cosine distance. One of the best algorithms for clustering documents\n# knn = KNeighborsClassifier(n_neighbors=3, metric=smp.cosine_distances)\n# knn.fit(X_train, y_train)\n# knn.score(X_test, y_test)", "_____no_output_____" ] ], [ [ "# PHASE 2: pull in natl enq data\n- mix in labels, source labels\n- pull labels (source category in nyt)\n\n- Review Nlp notes\n - Feature trans & Pipelines\n- Gensim doc2vec", "_____no_output_____" ] ], [ [ "with open('mag-model-df.pkl', 'rb') as mag_data:\n df1 = pickle.load(mag_data)", "_____no_output_____" ], [ "df1.head()", "_____no_output_____" ], [ "df1.dropna(axis=0, how='all')", "_____no_output_____" ], [ "df1.shape", "_____no_output_____" ], [ "docs2 = df1['lead_paragraph']", "_____no_output_____" ], [ "docs2 = docs2.dropna()", "_____no_output_____" ], [ "for doc in docs2:\n doc = SentencesIterator(doc)", "_____no_output_____" ], [ "docs = pd.Series.tolist(docs2)", "_____no_output_____" ], [ "tfidf = TfidfVectorizer(stop_words=\"english\", \n token_pattern=\"\\\\b[a-zA-Z][a-zA-Z]+\\\\b\", \n min_df=10)\n\ntfidf_vecs = tfidf.fit_transform(docs)", "_____no_output_____" ], [ "tfidf_vecs.shape", "_____no_output_____" ] ], [ [ "## BASELINE: Multinomial Naive Bayes", "_____no_output_____" ] ], [ [ "pd.DataFrame(tfidf_vecs.todense(), \n columns=tfidf.get_feature_names()\n ).head()", "_____no_output_____" ], [ "# Train/Test split\nX_train, X_test, y_train, y_test = train_test_split(tfidf_vecs, df1['source'], test_size=0.33)\n\n# Train \nnb = MultinomialNB()\nnb.fit(X_train, y_train)\n\n# Test \nnb.score(X_test, y_test)", "_____no_output_____" ] ], [ [ "## LSA Begin 2", "_____no_output_____" ] ], [ [ "# terms by docs instead of docs by terms\ntfidf_corpus = matutils.Sparse2Corpus(tfidf_vecs.transpose())\n\n# Row indices\nid2word = dict((v, k) for k, v in tfidf.vocabulary_.items())\n\n# This is a hack for Python 3!\nid2word = corpora.Dictionary.from_corpus(tfidf_corpus, \n id2word=id2word)", "2017-06-02 07:08:48,190 : INFO : adding document #0 to Dictionary(0 unique tokens: [])\n2017-06-02 07:08:48,467 : INFO : built Dictionary(4404 unique tokens: ['run', 'baby', 'like', 'scene', 'disney']...) from 1461 documents (total 10956 corpus positions)\n" ], [ "lda = models.LdaModel(corpus=tfidf_corpus, num_topics=20, id2word=id2word, passes=3)\n\nlda.print_topics()", "2017-06-02 07:08:51,580 : INFO : using symmetric alpha at 0.05\n2017-06-02 07:08:51,582 : INFO : using symmetric eta at 0.000227066303361\n2017-06-02 07:08:51,585 : INFO : using serial LDA version on this node\n2017-06-02 07:08:52,088 : INFO : running online LDA training, 20 topics, 3 passes over the supplied corpus of 1461 documents, updating model once every 1461 documents, evaluating perplexity every 1461 documents, iterating 50x with a convergence threshold of 0.001000\n2017-06-02 07:08:52,089 : WARNING : too few updates, training might not converge; consider increasing the number of passes or iterations to improve accuracy\n2017-06-02 07:09:01,771 : INFO : -22.825 per-word bound, 7432456.2 perplexity estimate based on a held-out corpus of 1461 documents with 10956 words\n2017-06-02 07:09:01,773 : INFO : PROGRESS: pass 0, at document #1461/1461\n2017-06-02 07:09:04,148 : INFO : topic #7 (0.050): 0.009*\"trump\" + 0.004*\"president\" + 0.003*\"paris\" + 0.003*\"climate\" + 0.003*\"people\" + 0.003*\"donald\" + 0.003*\"said\" + 0.003*\"new\" + 0.002*\"agreement\" + 0.002*\"cancer\"\n2017-06-02 07:09:04,149 : INFO : topic #17 (0.050): 0.006*\"trump\" + 0.003*\"springer\" + 0.002*\"video\" + 0.002*\"climate\" + 0.002*\"jerry\" + 0.002*\"president\" + 0.002*\"people\" + 0.002*\"paris\" + 0.002*\"heat\" + 0.002*\"twitter\"\n2017-06-02 07:09:04,151 : INFO : topic #13 (0.050): 0.008*\"trump\" + 0.003*\"president\" + 0.003*\"said\" + 0.003*\"news\" + 0.003*\"information\" + 0.002*\"video\" + 0.002*\"people\" + 0.002*\"great\" + 0.002*\"right\" + 0.002*\"donald\"\n2017-06-02 07:09:04,153 : INFO : topic #14 (0.050): 0.006*\"trump\" + 0.003*\"people\" + 0.003*\"india\" + 0.002*\"news\" + 0.002*\"illness\" + 0.002*\"modi\" + 0.002*\"destroy\" + 0.002*\"like\" + 0.002*\"said\" + 0.002*\"man\"\n2017-06-02 07:09:04,155 : INFO : topic #4 (0.050): 0.005*\"like\" + 0.005*\"trump\" + 0.005*\"facebook\" + 0.003*\"video\" + 0.003*\"thanks\" + 0.002*\"hillary\" + 0.002*\"said\" + 0.002*\"president\" + 0.002*\"old\" + 0.002*\"low\"\n2017-06-02 07:09:04,157 : INFO : topic diff=9.135340, rho=1.000000\n2017-06-02 07:09:14,525 : INFO : -13.491 per-word bound, 11515.7 perplexity estimate based on a held-out corpus of 1461 documents with 10956 words\n2017-06-02 07:09:14,526 : INFO : PROGRESS: pass 1, at document #1461/1461\n2017-06-02 07:09:16,900 : INFO : topic #15 (0.050): 0.004*\"sure\" + 0.003*\"like\" + 0.003*\"trump\" + 0.003*\"life\" + 0.003*\"street\" + 0.003*\"delivered\" + 0.003*\"feed\" + 0.003*\"heat\" + 0.003*\"cooper\" + 0.003*\"reading\"\n2017-06-02 07:09:16,902 : INFO : topic #7 (0.050): 0.011*\"trump\" + 0.005*\"paris\" + 0.005*\"president\" + 0.005*\"climate\" + 0.004*\"agreement\" + 0.004*\"june\" + 0.004*\"musk\" + 0.003*\"change\" + 0.003*\"donald\" + 0.003*\"said\"\n2017-06-02 07:09:16,903 : INFO : topic #16 (0.050): 0.006*\"trump\" + 0.004*\"missile\" + 0.003*\"new\" + 0.003*\"illness\" + 0.003*\"president\" + 0.003*\"mental\" + 0.003*\"video\" + 0.002*\"news\" + 0.002*\"said\" + 0.002*\"world\"\n2017-06-02 07:09:16,906 : INFO : topic #9 (0.050): 0.005*\"custody\" + 0.004*\"arrested\" + 0.004*\"surprise\" + 0.004*\"definitely\" + 0.004*\"trump\" + 0.003*\"team\" + 0.003*\"ice\" + 0.003*\"read\" + 0.003*\"like\" + 0.003*\"said\"\n2017-06-02 07:09:16,908 : INFO : topic #18 (0.050): 0.006*\"trump\" + 0.004*\"modi\" + 0.004*\"climate\" + 0.003*\"peterson\" + 0.003*\"like\" + 0.003*\"picture\" + 0.003*\"know\" + 0.003*\"agreement\" + 0.003*\"significant\" + 0.003*\"paris\"\n2017-06-02 07:09:16,910 : INFO : topic diff=1.572960, rho=0.577350\n2017-06-02 07:09:29,404 : INFO : -12.483 per-word bound, 5724.2 perplexity estimate based on a held-out corpus of 1461 documents with 10956 words\n2017-06-02 07:09:29,406 : INFO : PROGRESS: pass 2, at document #1461/1461\n2017-06-02 07:09:30,721 : INFO : topic #1 (0.050): 0.015*\"cookies\" + 0.014*\"agreeing\" + 0.013*\"privacy\" + 0.011*\"experience\" + 0.011*\"policy\" + 0.010*\"liberty\" + 0.010*\"using\" + 0.010*\"writers\" + 0.010*\"possible\" + 0.009*\"best\"\n2017-06-02 07:09:30,723 : INFO : topic #12 (0.050): 0.004*\"moon\" + 0.004*\"trump\" + 0.004*\"center\" + 0.004*\"people\" + 0.003*\"movies\" + 0.003*\"exxon\" + 0.003*\"couple\" + 0.003*\"lady\" + 0.003*\"power\" + 0.003*\"like\"\n2017-06-02 07:09:30,725 : INFO : topic #10 (0.050): 0.011*\"trump\" + 0.009*\"ignoramuses\" + 0.009*\"reactions\" + 0.008*\"harshest\" + 0.008*\"swift\" + 0.008*\"reaction\" + 0.008*\"harsh\" + 0.008*\"weather\" + 0.008*\"disaster\" + 0.007*\"paris\"\n2017-06-02 07:09:30,726 : INFO : topic #6 (0.050): 0.021*\"advance\" + 0.021*\"donate\" + 0.020*\"click\" + 0.019*\"helps\" + 0.019*\"fund\" + 0.018*\"site\" + 0.016*\"bit\" + 0.016*\"information\" + 0.015*\"free\" + 0.015*\"little\"\n2017-06-02 07:09:30,728 : INFO : topic #3 (0.050): 0.004*\"video\" + 0.003*\"trump\" + 0.003*\"opposing\" + 0.003*\"negative\" + 0.003*\"behaviors\" + 0.002*\"topics\" + 0.002*\"radio\" + 0.002*\"social\" + 0.002*\"emotions\" + 0.002*\"time\"\n2017-06-02 07:09:30,730 : INFO : topic diff=1.323812, rho=0.500000\n2017-06-02 07:09:30,746 : INFO : topic #0 (0.050): 0.009*\"location\" + 0.008*\"trump\" + 0.006*\"transgender\" + 0.006*\"tweet\" + 0.004*\"switch\" + 0.004*\"people\" + 0.003*\"twitter\" + 0.003*\"good\" + 0.003*\"add\" + 0.003*\"button\"\n2017-06-02 07:09:30,747 : INFO : topic #1 (0.050): 0.015*\"cookies\" + 0.014*\"agreeing\" + 0.013*\"privacy\" + 0.011*\"experience\" + 0.011*\"policy\" + 0.010*\"liberty\" + 0.010*\"using\" + 0.010*\"writers\" + 0.010*\"possible\" + 0.009*\"best\"\n2017-06-02 07:09:30,749 : INFO : topic #2 (0.050): 0.012*\"heat\" + 0.012*\"feed\" + 0.012*\"delivered\" + 0.011*\"reading\" + 0.011*\"street\" + 0.010*\"latest\" + 0.010*\"thanks\" + 0.009*\"like\" + 0.008*\"trump\" + 0.006*\"video\"\n2017-06-02 07:09:30,750 : INFO : topic #3 (0.050): 0.004*\"video\" + 0.003*\"trump\" + 0.003*\"opposing\" + 0.003*\"negative\" + 0.003*\"behaviors\" + 0.002*\"topics\" + 0.002*\"radio\" + 0.002*\"social\" + 0.002*\"emotions\" + 0.002*\"time\"\n2017-06-02 07:09:30,752 : INFO : topic #4 (0.050): 0.012*\"facebook\" + 0.010*\"like\" + 0.004*\"low\" + 0.004*\"police\" + 0.003*\"ring\" + 0.003*\"wikileaks\" + 0.003*\"driving\" + 0.003*\"old\" + 0.003*\"music\" + 0.003*\"expose\"\n2017-06-02 07:09:30,753 : INFO : topic #5 (0.050): 0.013*\"trump\" + 0.005*\"president\" + 0.003*\"reading\" + 0.003*\"did\" + 0.003*\"feed\" + 0.003*\"heat\" + 0.003*\"delivered\" + 0.003*\"spicer\" + 0.003*\"twitter\" + 0.003*\"street\"\n2017-06-02 07:09:30,755 : INFO : topic #6 (0.050): 0.021*\"advance\" + 0.021*\"donate\" + 0.020*\"click\" + 0.019*\"helps\" + 0.019*\"fund\" + 0.018*\"site\" + 0.016*\"bit\" + 0.016*\"information\" + 0.015*\"free\" + 0.015*\"little\"\n2017-06-02 07:09:30,757 : INFO : topic #7 (0.050): 0.012*\"trump\" + 0.008*\"paris\" + 0.007*\"agreement\" + 0.007*\"climate\" + 0.006*\"june\" + 0.005*\"president\" + 0.005*\"change\" + 0.005*\"musk\" + 0.004*\"decision\" + 0.003*\"united\"\n2017-06-02 07:09:30,759 : INFO : topic #8 (0.050): 0.006*\"tribe\" + 0.005*\"modi\" + 0.005*\"native\" + 0.005*\"pm\" + 0.005*\"shocking\" + 0.004*\"china\" + 0.004*\"amazing\" + 0.004*\"fall\" + 0.003*\"government\" + 0.003*\"demands\"\n2017-06-02 07:09:30,760 : INFO : topic #9 (0.050): 0.006*\"custody\" + 0.005*\"arrested\" + 0.005*\"surprise\" + 0.005*\"definitely\" + 0.004*\"ice\" + 0.004*\"team\" + 0.004*\"read\" + 0.003*\"orders\" + 0.003*\"taken\" + 0.003*\"said\"\n2017-06-02 07:09:30,762 : INFO : topic #10 (0.050): 0.011*\"trump\" + 0.009*\"ignoramuses\" + 0.009*\"reactions\" + 0.008*\"harshest\" + 0.008*\"swift\" + 0.008*\"reaction\" + 0.008*\"harsh\" + 0.008*\"weather\" + 0.008*\"disaster\" + 0.007*\"paris\"\n2017-06-02 07:09:30,764 : INFO : topic #11 (0.050): 0.010*\"trump\" + 0.005*\"woman\" + 0.004*\"video\" + 0.004*\"donald\" + 0.004*\"clinton\" + 0.003*\"long\" + 0.003*\"voters\" + 0.003*\"water\" + 0.003*\"people\" + 0.003*\"women\"\n2017-06-02 07:09:30,765 : INFO : topic #12 (0.050): 0.004*\"moon\" + 0.004*\"trump\" + 0.004*\"center\" + 0.004*\"people\" + 0.003*\"movies\" + 0.003*\"exxon\" + 0.003*\"couple\" + 0.003*\"lady\" + 0.003*\"power\" + 0.003*\"like\"\n2017-06-02 07:09:30,767 : INFO : topic #13 (0.050): 0.010*\"trump\" + 0.004*\"obama\" + 0.003*\"video\" + 0.003*\"russia\" + 0.003*\"president\" + 0.003*\"right\" + 0.003*\"donald\" + 0.003*\"great\" + 0.003*\"news\" + 0.003*\"law\"\n2017-06-02 07:09:30,768 : INFO : topic #14 (0.050): 0.009*\"india\" + 0.005*\"narendra\" + 0.005*\"modi\" + 0.004*\"ancient\" + 0.004*\"taking\" + 0.004*\"universities\" + 0.004*\"wars\" + 0.003*\"star\" + 0.003*\"message\" + 0.003*\"germany\"\n2017-06-02 07:09:30,769 : INFO : topic #15 (0.050): 0.004*\"sure\" + 0.004*\"life\" + 0.003*\"cooper\" + 0.003*\"subpoenas\" + 0.003*\"nunes\" + 0.003*\"anderson\" + 0.003*\"argue\" + 0.003*\"fans\" + 0.003*\"challenges\" + 0.003*\"investigation\"\n" ], [ "lda_corpus = lda[tfidf_corpus]", "_____no_output_____" ], [ "nyt_lda = matutils.corpus2dense(lda_corpus, num_terms=20).transpose()\ndf3 = pd.DataFrame(nyt_lda)", "_____no_output_____" ], [ "df3.mean().sort_values(ascending=False).head(10)", "_____no_output_____" ] ], [ [ "# Future Work =====================================", "_____no_output_____" ], [ "# Troubleshoot doc2vec\n- look into the output of this", "_____no_output_____" ] ], [ [ "from gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom pprint import pprint\nimport multiprocessing", "_____no_output_____" ], [ "# Create doc2Vec model\nd2v = doc2vec.Doc2Vec(tfidf_corpus,min_count=3,workers=5)", "2017-06-01 04:28:57,205 : INFO : collecting all words and their counts\n" ] ], [ [ "# PHASE 3: Visualize clusters\n- [NLP visualization PyLDAvis](https://github.com/bmabey/pyLDAvis)\n- [Bokeh](http://bokeh.pydata.org/en/latest/)\n- [Bqplot](https://github.com/bloomberg/bqplot)\n- I'd rather not d3...", "_____no_output_____" ] ], [ [ "with open('nyt-model-df.pkl', 'rb') as nyt_data:\n df = pickle.load(nyt_data)", "_____no_output_____" ], [ "with open('mag-model-df.pkl', 'rb') as mag_data:\n df1 = pickle.load(mag_data)", "_____no_output_____" ], [ "# select the relevant columns in our ratings dataset\nnyt_df = df[['lead_paragraph', 'source']]\nmag_df = df1[['lead_paragraph', 'source']]", "_____no_output_____" ], [ "# For the word cloud: https://www.jasondavies.com/wordcloud/\nnyt_df['lead_paragraph'].to_csv(path='nyt-text.csv', index=False)", "_____no_output_____" ], [ "# For the word cloud: https://www.jasondavies.com/wordcloud/\nmag_df['lead_paragraph'].to_csv(path='mag-text.csv', index=False)", "_____no_output_____" ], [ "!ls", "2013_movies.csv challenge_set_5_andrew-RESUBMIT.ipynb\r\n5.15.17 Sort, Search, Merge.ipynb challenge_set_6_andrew-RESUBMIT.ipynb\r\nChallenge_7+8_o.ipynb challenge_set_7_andrew.ipynb\r\nNLP-model-development.ipynb challenge_set_8_andrew.ipynb\r\nNYT-Magazine Classifier.ipynb challenge_set_X_TEMPLATE.ipynb\r\n\u001b[1m\u001b[36mProj_Benson\u001b[m\u001b[m haberman.csv\r\n\u001b[1m\u001b[36mProj_Luther\u001b[m\u001b[m house-votes-84.csv\r\nSet7_Class_Models.pkl initial-model-df.pkl\r\nSet7_House_Data.pkl mag-model-df.pkl\r\n_challenge_7.ipynb mag.csv\r\nchallenge_set_15_andrew.ipynb nyt-model-df.pkl\r\nchallenge_set_1_andrew.ipynb nyt-text.csv\r\nchallenge_set_1_andrew_pandas.ipynb \u001b[1m\u001b[36mtom_andrew\u001b[m\u001b[m\r\nchallenge_set_3_andrew-Copy1.ipynb\r\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
cbde66974751121428f812ee88c4ed305a9e3abd
489,297
ipynb
Jupyter Notebook
Models/Object_detection_Faster_RCNN.ipynb
alifiaharmd/Malaria-Detection
846b2d50d483b27e32c07f742277227d50d97500
[ "Unlicense" ]
null
null
null
Models/Object_detection_Faster_RCNN.ipynb
alifiaharmd/Malaria-Detection
846b2d50d483b27e32c07f742277227d50d97500
[ "Unlicense" ]
null
null
null
Models/Object_detection_Faster_RCNN.ipynb
alifiaharmd/Malaria-Detection
846b2d50d483b27e32c07f742277227d50d97500
[ "Unlicense" ]
null
null
null
489,297
489,297
0.803955
[ [ [ "\"\"\"The file needed to run this notebook can be accessed from the following folder using a UTS email account:\nhttps://drive.google.com/drive/folders/1y6e1Z2SbLDKkmvK3-tyQ6INO5rrzT3jp\n\"\"\"", "_____no_output_____" ] ], [ [ "##Task-1: Installation of Google Object Detection API and required packages\n\n\n", "_____no_output_____" ], [ "### Step 1: Import packages\n\n\n\n\n", "_____no_output_____" ] ], [ [ "#Mount the drive\nfrom google.colab import drive\ndrive.mount('/content/drive')", "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" ], [ "%tensorflow_version 1.x \n!pip install numpy==1.17.4", "TensorFlow 1.x selected.\nCollecting numpy==1.17.4\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/d2/ab/43e678759326f728de861edbef34b8e2ad1b1490505f20e0d1f0716c3bf4/numpy-1.17.4-cp36-cp36m-manylinux1_x86_64.whl (20.0MB)\n\u001b[K |████████████████████████████████| 20.0MB 33.5MB/s \n\u001b[31mERROR: tensorflow 1.15.2 has requirement gast==0.2.2, but you'll have gast 0.3.3 which is incompatible.\u001b[0m\n\u001b[31mERROR: datascience 0.10.6 has requirement folium==0.2.1, but you'll have folium 0.8.3 which is incompatible.\u001b[0m\n\u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n\u001b[?25hInstalling collected packages: numpy\n Found existing installation: numpy 1.18.5\n Uninstalling numpy-1.18.5:\n Successfully uninstalled numpy-1.18.5\nSuccessfully installed numpy-1.17.4\n" ], [ "import os\nimport re\nimport tensorflow as tf", "_____no_output_____" ], [ "print(tf.__version__)", "1.15.2\n" ], [ "pip install --upgrade tf_slim", "Collecting tf_slim\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n\u001b[K |████████████████████████████████| 358kB 2.8MB/s \n\u001b[?25hRequirement already satisfied, skipping upgrade: absl-py>=0.2.2 in /usr/local/lib/python3.6/dist-packages (from tf_slim) (0.9.0)\nRequirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from absl-py>=0.2.2->tf_slim) (1.12.0)\nInstalling collected packages: tf-slim\nSuccessfully installed tf-slim-1.1.0\n" ] ], [ [ "### Step 2: Initial Configuration to Select SSD model config file and selection of other hyperparameters", "_____no_output_____" ] ], [ [ "# If you forked the repository, you can replace the link.\nrepo_url = 'https://github.com/Tony607/object_detection_demo'\n\n# Number of training steps.\nnum_steps = 10000 # 200000\n\n# Number of evaluation steps.\nnum_eval_steps = 50\n\nMODELS_CONFIG = {\n 'ssd_mobilenet_v2': {\n 'model_name': 'ssd_mobilenet_v2_coco_2018_03_29',\n 'pipeline_file': 'ssd_mobilenet_v2_coco.config',\n 'batch_size': 12\n },\n 'faster_rcnn_inception_v2': {\n 'model_name': 'faster_rcnn_inception_v2_coco_2018_01_28',\n 'pipeline_file': 'faster_rcnn_inception_v2_pets.config',\n 'batch_size': 12\n },\n 'facessd_mobilenet_v2_quantized_open_image_v4': {\n 'model_name': 'facessd_mobilenet_v2_quantized_320x320_open_image_v4',\n 'pipeline_file': 'facessd_mobilenet_v2_quantized_320x320_open_image_v4.config',\n 'batch_size': 32\n }\n}\n\n# Pick the model you want to use\n\nselected_model = 'faster_rcnn_inception_v2'\n\n# Name of the object detection model to use.\nMODEL = MODELS_CONFIG[selected_model]['model_name']\n\n# Name of the pipline file in tensorflow object detection API.\npipeline_file = MODELS_CONFIG[selected_model]['pipeline_file']\n\n# Training batch size fits in Colabe's Tesla K80 GPU memory for selected model.\nbatch_size = MODELS_CONFIG[selected_model]['batch_size']", "_____no_output_____" ], [ "%cd /content\n\nrepo_dir_path = os.path.abspath(os.path.join('.', os.path.basename(repo_url)))\n\n!git clone {repo_url}\n%cd {repo_dir_path}\n!git pull", "/content\nCloning into 'object_detection_demo'...\nremote: Enumerating objects: 124, done.\u001b[K\nremote: Total 124 (delta 0), reused 0 (delta 0), pack-reused 124\u001b[K\nReceiving objects: 100% (124/124), 11.16 MiB | 6.28 MiB/s, done.\nResolving deltas: 100% (45/45), done.\n/content/object_detection_demo\nAlready up to date.\n" ] ], [ [ "### Step 3: Download Google Object Detection API and other dependencies", "_____no_output_____" ] ], [ [ "%cd /content\n!git clone --quiet https://github.com/tensorflow/models.git\n\n!apt-get install -qq protobuf-compiler python-pil python-lxml python-tk\n\n!pip install -q Cython contextlib2 pillow lxml matplotlib\n\n!pip install -q pycocotools\n\n%cd /content/models/research\n!protoc object_detection/protos/*.proto --python_out=.\n\nimport os\nos.environ['PYTHONPATH'] += ':/content/models/research/:/content/models/research/slim/'\n\n!python object_detection/builders/model_builder_test.py", "/content\nSelecting previously unselected package python-bs4.\n(Reading database ... 144328 files and directories currently installed.)\nPreparing to unpack .../0-python-bs4_4.6.0-1_all.deb ...\nUnpacking python-bs4 (4.6.0-1) ...\nSelecting previously unselected package python-pkg-resources.\nPreparing to unpack .../1-python-pkg-resources_39.0.1-2_all.deb ...\nUnpacking python-pkg-resources (39.0.1-2) ...\nSelecting previously unselected package python-chardet.\nPreparing to unpack .../2-python-chardet_3.0.4-1_all.deb ...\nUnpacking python-chardet (3.0.4-1) ...\nSelecting previously unselected package python-six.\nPreparing to unpack .../3-python-six_1.11.0-2_all.deb ...\nUnpacking python-six (1.11.0-2) ...\nSelecting previously unselected package python-webencodings.\nPreparing to unpack .../4-python-webencodings_0.5-2_all.deb ...\nUnpacking python-webencodings (0.5-2) ...\nSelecting previously unselected package python-html5lib.\nPreparing to unpack .../5-python-html5lib_0.999999999-1_all.deb ...\nUnpacking python-html5lib (0.999999999-1) ...\nSelecting previously unselected package python-lxml:amd64.\nPreparing to unpack .../6-python-lxml_4.2.1-1ubuntu0.1_amd64.deb ...\nUnpacking python-lxml:amd64 (4.2.1-1ubuntu0.1) ...\nSelecting previously unselected package python-olefile.\nPreparing to unpack .../7-python-olefile_0.45.1-1_all.deb ...\nUnpacking python-olefile (0.45.1-1) ...\nSelecting previously unselected package python-pil:amd64.\nPreparing to unpack .../8-python-pil_5.1.0-1ubuntu0.2_amd64.deb ...\nUnpacking python-pil:amd64 (5.1.0-1ubuntu0.2) ...\nSetting up python-pkg-resources (39.0.1-2) ...\nSetting up python-six (1.11.0-2) ...\nSetting up python-bs4 (4.6.0-1) ...\nSetting up python-lxml:amd64 (4.2.1-1ubuntu0.1) ...\nSetting up python-olefile (0.45.1-1) ...\nSetting up python-pil:amd64 (5.1.0-1ubuntu0.2) ...\nSetting up python-webencodings (0.5-2) ...\nSetting up python-chardet (3.0.4-1) ...\nSetting up python-html5lib (0.999999999-1) ...\nProcessing triggers for man-db (2.8.3-2ubuntu0.1) ...\n/content/models/research\nobject_detection/protos/input_reader.proto: warning: Import object_detection/protos/image_resizer.proto but not used.\n" ] ], [ [ "", "_____no_output_____" ], [ "##Task-2: Conversion of XML annotations and images into tfrecords for training and testing datasets", "_____no_output_____" ], [ "### Step 4: Prepare `tfrecord` files\n\nUse the following scripts to generate the `tfrecord` files.\n```bash\n# Convert train folder annotation xml files to a single csv file,\n# generate the `label_map.pbtxt` file to `data/` directory as well.\npython xml_to_csv.py -i data/images/train -o data/annotations/train_labels.csv -l data/annotations\n\n# Convert test folder annotation xml files to a single csv.\npython xml_to_csv.py -i data/images/test -o data/annotations/test_labels.csv\n\n# Generate `train.record`\npython generate_tfrecord.py --csv_input=data/annotations/train_labels.csv --output_path=data/annotations/train.record --img_path=data/images/train --label_map data/annotations/label_map.pbtxt\n\n# Generate `test.record`\npython generate_tfrecord.py --csv_input=data/annotations/test_labels.csv --output_path=data/annotations/test.record --img_path=data/images/test --label_map data/annotations/label_map.pbtxt\n```", "_____no_output_____" ] ], [ [ "import zipfile\n#Extract the zip file \nlocal_zip = '/content/drive/My Drive/Assignment 3/resized-20200512T050739Z-001.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/content/object_detection_demo/data/images/train')\nzip_ref.close()\n", "_____no_output_____" ], [ "import zipfile\n#Extract the zip file \nlocal_zip = '/content/drive/My Drive/Assignment 3/resized-20200512T050739Z-001.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/content/object_detection_demo/data/images/test')\nzip_ref.close()", "_____no_output_____" ], [ "#create the annotation directory\n%cd /content/object_detection_demo/data\nannotation_dir = 'annotations/'\nos.makedirs(annotation_dir, exist_ok=True)\n", "/content/object_detection_demo/data\n" ], [ "\"\"\"Need to manually upload the label_pbtxt file and the train_labels.csv and test_labels.csv\ninto the annotation folder using the link here\nhttps://drive.google.com/drive/folders/1NqKz2tC8I5eL5Qo4YzZiEph8W-dtI44d\n\"\"\"", "_____no_output_____" ], [ "%cd {repo_dir_path}\n# Generate `train.record`\n#Only need to change the path for csv input\n!python generate_tfrecord.py --csv_input=/content/object_detection_demo/data/annotations/train_labels.csv --output_path=/content/object_detection_demo/data/annotations/train.record --img_path=/content/object_detection_demo/data/images/train/resized --label_map /content/object_detection_demo/data/annotations/label_map.pbtxt", "/content/object_detection_demo\nWARNING:tensorflow:From generate_tfrecord.py:134: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n\nWARNING:tensorflow:From generate_tfrecord.py:107: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.\n\nW0617 08:50:25.861793 140277859268480 module_wrapper.py:139] From generate_tfrecord.py:107: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.\n\nWARNING:tensorflow:From generate_tfrecord.py:53: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nW0617 08:50:27.694240 140277859268480 module_wrapper.py:139] From generate_tfrecord.py:53: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nSuccessfully created the TFRecords: /content/object_detection_demo/data/annotations/train.record\n" ], [ "# Generate `test.record`\n#Only need to change the path for csv input\n!python generate_tfrecord.py --csv_input=data/annotations/test_labels.csv --output_path=data/annotations/test.record --img_path=/content/object_detection_demo/data/images/test/resized --label_map data/annotations/label_map.pbtxt", "WARNING:tensorflow:From generate_tfrecord.py:134: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n\nWARNING:tensorflow:From generate_tfrecord.py:107: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.\n\nW0617 08:40:17.209351 139957186725760 module_wrapper.py:139] From generate_tfrecord.py:107: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.\n\nWARNING:tensorflow:From generate_tfrecord.py:53: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nW0617 08:40:18.559039 139957186725760 module_wrapper.py:139] From generate_tfrecord.py:53: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nSuccessfully created the TFRecords: /content/object_detection_demo/data/annotations/test.record\n" ], [ "test_record_fname = '/content/object_detection_demo/data/annotations/test.record'\ntrain_record_fname = '/content/object_detection_demo/data/annotations/train.record'\nlabel_map_pbtxt_fname = '/content/object_detection_demo/data/annotations/label_map.pbtxt'", "_____no_output_____" ] ], [ [ "### Step 5. Download the base model for transfer learning", "_____no_output_____" ] ], [ [ "%cd /content/models/research\n\nimport os\nimport shutil\nimport glob\nimport urllib.request\nimport tarfile\nMODEL_FILE = MODEL + '.tar.gz'\nDOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\nDEST_DIR = '/content/models/research/pretrained_model'\n\nif not (os.path.exists(MODEL_FILE)):\n urllib.request.urlretrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)\n\ntar = tarfile.open(MODEL_FILE)\ntar.extractall()\ntar.close()\n\nos.remove(MODEL_FILE)\nif (os.path.exists(DEST_DIR)):\n shutil.rmtree(DEST_DIR)\nos.rename(MODEL, DEST_DIR)", "/content/models/research\n" ], [ "!echo {DEST_DIR}\n!ls -alh {DEST_DIR}", "/content/models/research/pretrained_model\ntotal 111M\ndrwxr-xr-x 3 345018 5000 4.0K Feb 1 2018 .\ndrwxr-xr-x 63 root root 4.0K Jun 17 08:50 ..\n-rw-r--r-- 1 345018 5000 77 Feb 1 2018 checkpoint\n-rw-r--r-- 1 345018 5000 55M Feb 1 2018 frozen_inference_graph.pb\n-rw-r--r-- 1 345018 5000 51M Feb 1 2018 model.ckpt.data-00000-of-00001\n-rw-r--r-- 1 345018 5000 16K Feb 1 2018 model.ckpt.index\n-rw-r--r-- 1 345018 5000 5.5M Feb 1 2018 model.ckpt.meta\n-rw-r--r-- 1 345018 5000 3.2K Feb 1 2018 pipeline.config\ndrwxr-xr-x 3 345018 5000 4.0K Feb 1 2018 saved_model\n" ], [ "fine_tune_checkpoint = os.path.join(DEST_DIR, \"model.ckpt\")\nfine_tune_checkpoint", "_____no_output_____" ] ], [ [ "##Task-3: Training: Transfer learning from already trained models\n\n", "_____no_output_____" ], [ "###Step 6: configuring a training pipeline", "_____no_output_____" ] ], [ [ "import os\npipeline_fname = os.path.join('/content/models/research/object_detection/samples/configs/', pipeline_file)\n\nassert os.path.isfile(pipeline_fname), '`{}` not exist'.format(pipeline_fname)", "_____no_output_____" ], [ "def get_num_classes(pbtxt_fname):\n from object_detection.utils import label_map_util\n label_map = label_map_util.load_labelmap(pbtxt_fname)\n categories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=90, use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n return len(category_index.keys())", "_____no_output_____" ], [ "num_classes = get_num_classes(label_map_pbtxt_fname)\nwith open(pipeline_fname) as f:\n s = f.read()\nwith open(pipeline_fname, 'w') as f:\n \n # fine_tune_checkpoint\n s = re.sub('fine_tune_checkpoint: \".*?\"',\n 'fine_tune_checkpoint: \"{}\"'.format(fine_tune_checkpoint), s)\n \n # tfrecord files train and test.\n s = re.sub(\n '(input_path: \".*?)(train.record)(.*?\")', 'input_path: \"{}\"'.format(train_record_fname), s)\n s = re.sub(\n '(input_path: \".*?)(val.record)(.*?\")', 'input_path: \"{}\"'.format(test_record_fname), s)\n\n # label_map_path\n s = re.sub(\n 'label_map_path: \".*?\"', 'label_map_path: \"{}\"'.format(label_map_pbtxt_fname), s)\n\n # Set training batch_size.\n s = re.sub('batch_size: [0-9]+',\n 'batch_size: {}'.format(batch_size), s)\n\n # Set training steps, num_steps\n s = re.sub('num_steps: [0-9]+',\n 'num_steps: {}'.format(num_steps), s)\n \n # Set number of classes num_classes.\n s = re.sub('num_classes: [0-9]+',\n 'num_classes: {}'.format(num_classes), s)\n \n #set image resizer\n \"\"\"s = re.sub('initial_learning_rate: [-+]?[0-9]*\\.?[0-9]+',\n 'initial_learning_rate: {}'.format(initial_learning_rate), s)\"\"\"\n\n \n f.write(s)", "_____no_output_____" ], [ "!cat {pipeline_fname}", "# Faster R-CNN with Inception v2, configured for Oxford-IIIT Pets Dataset.\n# Users should configure the fine_tune_checkpoint field in the train config as\n# well as the label_map_path and input_path fields in the train_input_reader and\n# eval_input_reader. Search for \"PATH_TO_BE_CONFIGURED\" to find the fields that\n# should be configured.\n\nmodel {\n faster_rcnn {\n num_classes: 1\n image_resizer {\n keep_aspect_ratio_resizer {\n min_dimension: 600\n max_dimension: 1024\n }\n }\n feature_extractor {\n type: 'faster_rcnn_inception_v2'\n first_stage_features_stride: 16\n }\n first_stage_anchor_generator {\n grid_anchor_generator {\n scales: [0.25, 0.5, 1.0, 2.0]\n aspect_ratios: [0.5, 1.0, 2.0]\n height_stride: 16\n width_stride: 16\n }\n }\n first_stage_box_predictor_conv_hyperparams {\n op: CONV\n regularizer {\n l2_regularizer {\n weight: 0.0\n }\n }\n initializer {\n truncated_normal_initializer {\n stddev: 0.01\n }\n }\n }\n first_stage_nms_score_threshold: 0.0\n first_stage_nms_iou_threshold: 0.7\n first_stage_max_proposals: 300\n first_stage_localization_loss_weight: 2.0\n first_stage_objectness_loss_weight: 1.0\n initial_crop_size: 14\n maxpool_kernel_size: 2\n maxpool_stride: 2\n second_stage_box_predictor {\n mask_rcnn_box_predictor {\n use_dropout: false\n dropout_keep_probability: 1.0\n fc_hyperparams {\n op: FC\n regularizer {\n l2_regularizer {\n weight: 0.0\n }\n }\n initializer {\n variance_scaling_initializer {\n factor: 1.0\n uniform: true\n mode: FAN_AVG\n }\n }\n }\n }\n }\n second_stage_post_processing {\n batch_non_max_suppression {\n score_threshold: 0.0\n iou_threshold: 0.6\n max_detections_per_class: 100\n max_total_detections: 300\n }\n score_converter: SOFTMAX\n }\n second_stage_localization_loss_weight: 2.0\n second_stage_classification_loss_weight: 1.0\n }\n}\n\ntrain_config: {\n batch_size: 12\n optimizer {\n momentum_optimizer: {\n learning_rate: {\n manual_step_learning_rate {\n initial_learning_rate: 0.0002\n schedule {\n step: 900000\n learning_rate: .00002\n }\n schedule {\n step: 1200000\n learning_rate: .000002\n }\n }\n }\n momentum_optimizer_value: 0.9\n }\n use_moving_average: false\n }\n gradient_clipping_by_norm: 10.0\n fine_tune_checkpoint: \"/content/models/research/pretrained_model/model.ckpt\"\n from_detection_checkpoint: true\n load_all_detection_checkpoint_vars: true\n # Note: The below line limits the training process to 200K steps, which we\n # empirically found to be sufficient enough to train the pets dataset. This\n # effectively bypasses the learning rate schedule (the learning rate will\n # never decay). Remove the below line to train indefinitely.\n num_steps: 10000\n data_augmentation_options {\n random_horizontal_flip {\n }\n }\n}\n\n\ntrain_input_reader: {\n tf_record_input_reader {\n input_path: \"/content/object_detection_demo/data/annotations/train.record\"\n }\n label_map_path: \"/content/object_detection_demo/data/annotations/label_map.pbtxt\"\n}\n\neval_config: {\n metrics_set: \"coco_detection_metrics\"\n num_examples: 1101\n}\n\neval_input_reader: {\n tf_record_input_reader {\n input_path: \"/content/object_detection_demo/data/annotations/test.record\"\n }\n label_map_path: \"/content/object_detection_demo/data/annotations/label_map.pbtxt\"\n shuffle: false\n num_readers: 1\n}\n" ], [ "model_dir = 'training/'\n# Optionally remove content in output model directory to fresh start.\n!rm -rf {model_dir}\nos.makedirs(model_dir, exist_ok=True)", "_____no_output_____" ] ], [ [ "### Step 7. Install Tensorboard to visualize the progress of training process", "_____no_output_____" ] ], [ [ "!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\n!unzip -o ngrok-stable-linux-amd64.zip", "--2020-06-17 08:51:40-- https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\nResolving bin.equinox.io (bin.equinox.io)... 52.86.203.217, 50.16.94.112, 54.208.57.0, ...\nConnecting to bin.equinox.io (bin.equinox.io)|52.86.203.217|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 13773305 (13M) [application/octet-stream]\nSaving to: ‘ngrok-stable-linux-amd64.zip’\n\nngrok-stable-linux- 100%[===================>] 13.13M 6.08MB/s in 2.2s \n\n2020-06-17 08:51:43 (6.08 MB/s) - ‘ngrok-stable-linux-amd64.zip’ saved [13773305/13773305]\n\nArchive: ngrok-stable-linux-amd64.zip\n inflating: ngrok \n" ], [ "LOG_DIR = model_dir\nget_ipython().system_raw(\n 'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'\n .format(LOG_DIR)\n)", "_____no_output_____" ], [ "get_ipython().system_raw('./ngrok http 6006 &')\n", "_____no_output_____" ] ], [ [ "### Step: 8 Get tensorboard link", "_____no_output_____" ] ], [ [ "! curl -s http://localhost:4040/api/tunnels | python3 -c \\\n \"import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])\"", "http://e5f1ada81844.ngrok.io\n" ] ], [ [ "### Step 9. Training the model", "_____no_output_____" ] ], [ [ "!python /content/models/research/object_detection/model_main.py \\\n --pipeline_config_path={pipeline_fname} \\\n --model_dir={model_dir} \\\n --alsologtostderr \\\n --num_train_steps={num_steps} \\\n --num_eval_steps={num_eval_steps}", "WARNING:tensorflow:Forced number of epochs for all eval validations to be 1.\nW0617 08:52:21.150880 139802647791488 model_lib.py:717] Forced number of epochs for all eval validations to be 1.\nINFO:tensorflow:Maybe overwriting train_steps: 10000\nI0617 08:52:21.151218 139802647791488 config_util.py:523] Maybe overwriting train_steps: 10000\nINFO:tensorflow:Maybe overwriting use_bfloat16: False\nI0617 08:52:21.151412 139802647791488 config_util.py:523] Maybe overwriting use_bfloat16: False\nINFO:tensorflow:Maybe overwriting sample_1_of_n_eval_examples: 1\nI0617 08:52:21.151632 139802647791488 config_util.py:523] Maybe overwriting sample_1_of_n_eval_examples: 1\nINFO:tensorflow:Maybe overwriting eval_num_epochs: 1\nI0617 08:52:21.151835 139802647791488 config_util.py:523] Maybe overwriting eval_num_epochs: 1\nINFO:tensorflow:Maybe overwriting load_pretrained: True\nI0617 08:52:21.152001 139802647791488 config_util.py:523] Maybe overwriting load_pretrained: True\nINFO:tensorflow:Ignoring config override key: load_pretrained\nI0617 08:52:21.152132 139802647791488 config_util.py:533] Ignoring config override key: load_pretrained\nWARNING:tensorflow:Expected number of evaluation epochs is 1, but instead encountered `eval_on_train_input_config.num_epochs` = 0. Overwriting `num_epochs` to 1.\nW0617 08:52:21.153077 139802647791488 model_lib.py:733] Expected number of evaluation epochs is 1, but instead encountered `eval_on_train_input_config.num_epochs` = 0. Overwriting `num_epochs` to 1.\nINFO:tensorflow:create_estimator_and_inputs: use_tpu False, export_to_tpu False\nI0617 08:52:21.153277 139802647791488 model_lib.py:768] create_estimator_and_inputs: use_tpu False, export_to_tpu False\nINFO:tensorflow:Using config: {'_model_dir': 'training/', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true\ngraph_options {\n rewrite_options {\n meta_optimizer_iterations: ONE\n }\n}\n, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f2608fe5c18>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}\nI0617 08:52:21.153795 139802647791488 estimator.py:212] Using config: {'_model_dir': 'training/', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true\ngraph_options {\n rewrite_options {\n meta_optimizer_iterations: ONE\n }\n}\n, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f2608fe5c18>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}\nWARNING:tensorflow:Estimator's model_fn (<function create_model_fn.<locals>.model_fn at 0x7f25eee5cc80>) includes params argument, but params are not passed to Estimator.\nW0617 08:52:21.154086 139802647791488 model_fn.py:630] Estimator's model_fn (<function create_model_fn.<locals>.model_fn at 0x7f25eee5cc80>) includes params argument, but params are not passed to Estimator.\nINFO:tensorflow:Not using Distribute Coordinator.\nI0617 08:52:21.154873 139802647791488 estimator_training.py:186] Not using Distribute Coordinator.\nINFO:tensorflow:Running training and evaluation locally (non-distributed).\nI0617 08:52:21.155112 139802647791488 training.py:612] Running training and evaluation locally (non-distributed).\nINFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600.\nI0617 08:52:21.155418 139802647791488 training.py:700] Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600.\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\nW0617 08:52:21.162232 139802647791488 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\nWARNING:tensorflow:num_readers has been reduced to 1 to match input file shards.\nW0617 08:52:21.217070 139802647791488 dataset_builder.py:83] num_readers has been reduced to 1 to match input file shards.\nWARNING:tensorflow:From /content/models/research/object_detection/builders/dataset_builder.py:100: parallel_interleave (from tensorflow.python.data.experimental.ops.interleave_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.Dataset.interleave(map_func, cycle_length, block_length, num_parallel_calls=tf.data.experimental.AUTOTUNE)` instead. If sloppy execution is desired, use `tf.data.Options.experimental_determinstic`.\nW0617 08:52:21.224488 139802647791488 deprecation.py:323] From /content/models/research/object_detection/builders/dataset_builder.py:100: parallel_interleave (from tensorflow.python.data.experimental.ops.interleave_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.Dataset.interleave(map_func, cycle_length, block_length, num_parallel_calls=tf.data.experimental.AUTOTUNE)` instead. If sloppy execution is desired, use `tf.data.Options.experimental_determinstic`.\nWARNING:tensorflow:From /content/models/research/object_detection/builders/dataset_builder.py:175: DatasetV1.map_with_legacy_function (from tensorflow.python.data.ops.dataset_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.Dataset.map()\nW0617 08:52:21.249082 139802647791488 deprecation.py:323] From /content/models/research/object_detection/builders/dataset_builder.py:175: DatasetV1.map_with_legacy_function (from tensorflow.python.data.ops.dataset_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.Dataset.map()\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25ee64c710>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 08:52:21.283932 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25ee64c710>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function train_input.<locals>.transform_and_pad_input_data_fn at 0x7f2613c0cbf8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 08:52:21.518044 139802647791488 ag_logging.py:146] Entity <function train_input.<locals>.transform_and_pad_input_data_fn at 0x7f2613c0cbf8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nWARNING:tensorflow:From /content/models/research/object_detection/inputs.py:79: sparse_to_dense (from tensorflow.python.ops.sparse_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nCreate a `tf.sparse.SparseTensor` and use `tf.sparse.to_dense` instead.\nW0617 08:52:21.525182 139802647791488 deprecation.py:323] From /content/models/research/object_detection/inputs.py:79: sparse_to_dense (from tensorflow.python.ops.sparse_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nCreate a `tf.sparse.SparseTensor` and use `tf.sparse.to_dense` instead.\nWARNING:tensorflow:From /content/models/research/object_detection/utils/ops.py:493: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.where in 2.0, which has the same broadcast rule as np.where\nW0617 08:52:21.534516 139802647791488 deprecation.py:323] From /content/models/research/object_detection/utils/ops.py:493: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.where in 2.0, which has the same broadcast rule as np.where\nWARNING:tensorflow:From /content/models/research/object_detection/inputs.py:260: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nW0617 08:52:21.693887 139802647791488 deprecation.py:323] From /content/models/research/object_detection/inputs.py:260: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nINFO:tensorflow:Calling model_fn.\nI0617 08:52:22.209970 139802647791488 estimator.py:1148] Calling model_fn.\nWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tf_slim/layers/layers.py:2802: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `layer.__call__` method instead.\nW0617 08:52:22.596474 139802647791488 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tf_slim/layers/layers.py:2802: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `layer.__call__` method instead.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 08:52:24.502778 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 08:52:24.522963 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 08:52:24.523390 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nWARNING:tensorflow:From /content/models/research/object_detection/utils/spatial_transform_ops.py:428: calling crop_and_resize_v1 (from tensorflow.python.ops.image_ops_impl) with box_ind is deprecated and will be removed in a future version.\nInstructions for updating:\nbox_ind is deprecated, use box_indices instead\nW0617 08:52:33.097250 139802647791488 deprecation.py:506] From /content/models/research/object_detection/utils/spatial_transform_ops.py:428: calling crop_and_resize_v1 (from tensorflow.python.ops.image_ops_impl) with box_ind is deprecated and will be removed in a future version.\nInstructions for updating:\nbox_ind is deprecated, use box_indices instead\nWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tf_slim/layers/layers.py:1666: flatten (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse keras.layers.flatten instead.\nW0617 08:52:33.779938 139802647791488 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tf_slim/layers/layers.py:1666: flatten (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse keras.layers.flatten instead.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 08:52:33.782926 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 08:52:33.803099 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nW0617 08:52:33.900285 139802647791488 variables_helper.py:153] Variable [SecondStageBoxPredictor/BoxEncodingPredictor/biases] is available in checkpoint, but has an incompatible shape with model variable. Checkpoint shape: [[360]], model variable shape: [[4]]. This variable will not be initialized from the checkpoint.\nW0617 08:52:33.900566 139802647791488 variables_helper.py:153] Variable [SecondStageBoxPredictor/BoxEncodingPredictor/weights] is available in checkpoint, but has an incompatible shape with model variable. Checkpoint shape: [[1024, 360]], model variable shape: [[1024, 4]]. This variable will not be initialized from the checkpoint.\nW0617 08:52:33.900743 139802647791488 variables_helper.py:153] Variable [SecondStageBoxPredictor/ClassPredictor/biases] is available in checkpoint, but has an incompatible shape with model variable. Checkpoint shape: [[91]], model variable shape: [[2]]. This variable will not be initialized from the checkpoint.\nW0617 08:52:33.900881 139802647791488 variables_helper.py:153] Variable [SecondStageBoxPredictor/ClassPredictor/weights] is available in checkpoint, but has an incompatible shape with model variable. Checkpoint shape: [[1024, 91]], model variable shape: [[1024, 2]]. This variable will not be initialized from the checkpoint.\nW0617 08:52:33.901760 139802647791488 variables_helper.py:156] Variable [global_step] is not available in checkpoint\nWARNING:tensorflow:From /content/models/research/object_detection/core/losses.py:347: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\n\nFuture major versions of TensorFlow will allow gradients to flow\ninto the labels input on backprop by default.\n\nSee `tf.nn.softmax_cross_entropy_with_logits_v2`.\n\nW0617 08:52:38.567042 139802647791488 deprecation.py:323] From /content/models/research/object_detection/core/losses.py:347: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\n\nFuture major versions of TensorFlow will allow gradients to flow\ninto the labels input on backprop by default.\n\nSee `tf.nn.softmax_cross_entropy_with_logits_v2`.\n\n/tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/indexed_slices.py:424: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.\n \"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"\n/tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/indexed_slices.py:424: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.\n \"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"\nINFO:tensorflow:Done calling model_fn.\nI0617 08:52:48.092770 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Create CheckpointSaverHook.\nI0617 08:52:48.094382 139802647791488 basic_session_run_hooks.py:541] Create CheckpointSaverHook.\nINFO:tensorflow:Graph was finalized.\nI0617 08:52:52.690185 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 08:52:52.695610: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2300000000 Hz\n2020-06-17 08:52:52.695926: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x1bb9d2c0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n2020-06-17 08:52:52.695962: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version\n2020-06-17 08:52:52.697945: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n2020-06-17 08:52:52.774677: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:52:52.777632: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x1bb9d100 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n2020-06-17 08:52:52.777665: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Tesla K80, Compute Capability 3.7\n2020-06-17 08:52:52.777969: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:52:52.778822: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 08:52:52.779261: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 08:52:52.781618: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 08:52:52.783728: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 08:52:52.784209: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 08:52:52.787619: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 08:52:52.789798: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 08:52:52.794342: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 08:52:52.794495: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:52:52.795288: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:52:52.796056: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 08:52:52.796125: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 08:52:52.797856: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 08:52:52.797889: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 08:52:52.797918: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 08:52:52.798113: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:52:52.798912: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:52:52.799633: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0.\n2020-06-17 08:52:52.799684: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Running local_init_op.\nI0617 08:52:56.794116 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 08:52:57.299461 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Saving checkpoints for 0 into training/model.ckpt.\nI0617 08:53:11.989169 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 0 into training/model.ckpt.\n2020-06-17 08:53:23.878871: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 08:53:25.358095: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\nINFO:tensorflow:loss = 1.3446282, step = 0\nI0617 08:53:39.558938 139802647791488 basic_session_run_hooks.py:262] loss = 1.3446282, step = 0\nINFO:tensorflow:global_step/sec: 0.510226\nI0617 08:56:55.549791 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.510226\nINFO:tensorflow:loss = 0.74235845, step = 100 (195.992 sec)\nI0617 08:56:55.551240 139802647791488 basic_session_run_hooks.py:260] loss = 0.74235845, step = 100 (195.992 sec)\nINFO:tensorflow:global_step/sec: 0.532761\nI0617 09:00:03.251033 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.532761\nINFO:tensorflow:loss = 0.5561745, step = 200 (187.701 sec)\nI0617 09:00:03.252495 139802647791488 basic_session_run_hooks.py:260] loss = 0.5561745, step = 200 (187.701 sec)\nINFO:tensorflow:global_step/sec: 0.533503\nI0617 09:03:10.691553 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.533503\nINFO:tensorflow:loss = 0.5961203, step = 300 (187.441 sec)\nI0617 09:03:10.693331 139802647791488 basic_session_run_hooks.py:260] loss = 0.5961203, step = 300 (187.441 sec)\nINFO:tensorflow:Saving checkpoints for 304 into training/model.ckpt.\nI0617 09:03:16.283773 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 304 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e029d518>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 09:03:18.685151 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e029d518>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e6194e18> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:03:19.163296 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e6194e18> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:03:19.891094 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:03:21.810374 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:03:21.828256 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:03:21.828679 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:03:23.115337 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:03:23.136284 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /content/models/research/object_detection/eval_util.py:830: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nW0617 09:03:24.319291 139802647791488 deprecation.py:323] From /content/models/research/object_detection/eval_util.py:830: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nWARNING:tensorflow:From /content/models/research/object_detection/utils/visualization_utils.py:618: py_func (from tensorflow.python.ops.script_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\ntf.py_func is deprecated in TF V2. Instead, there are two\n options available in V2.\n - tf.py_function takes a python function which manipulates tf eager\n tensors instead of numpy arrays. It's easy to convert a tf eager tensor to\n an ndarray (just call tensor.numpy()) but having access to eager tensors\n means `tf.py_function`s can use accelerators such as GPUs as well as\n being differentiable using a gradient tape.\n - tf.numpy_function maintains the semantics of the deprecated tf.py_func\n (it is not differentiable, and manipulates numpy arrays). It drops the\n stateful argument making all functions stateful.\n \nW0617 09:03:24.579822 139802647791488 deprecation.py:323] From /content/models/research/object_detection/utils/visualization_utils.py:618: py_func (from tensorflow.python.ops.script_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\ntf.py_func is deprecated in TF V2. Instead, there are two\n options available in V2.\n - tf.py_function takes a python function which manipulates tf eager\n tensors instead of numpy arrays. It's easy to convert a tf eager tensor to\n an ndarray (just call tensor.numpy()) but having access to eager tensors\n means `tf.py_function`s can use accelerators such as GPUs as well as\n being differentiable using a gradient tape.\n - tf.numpy_function maintains the semantics of the deprecated tf.py_func\n (it is not differentiable, and manipulates numpy arrays). It drops the\n stateful argument making all functions stateful.\n \nINFO:tensorflow:Done calling model_fn.\nI0617 09:03:25.319309 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:03:25Z\nI0617 09:03:25.342405 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T09:03:25Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:03:25.950376 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:03:25.951766: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:03:25.952158: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 09:03:25.952295: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:03:25.952343: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:03:25.952397: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:03:25.952443: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:03:25.952486: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:03:25.952531: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:03:25.952595: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:03:25.952746: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:03:25.953153: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:03:25.953472: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:03:25.953543: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:03:25.953596: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:03:25.953619: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:03:25.953778: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:03:25.954225: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:03:25.954531: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-304\nI0617 09:03:25.955710 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-304\nINFO:tensorflow:Running local_init_op.\nI0617 09:03:27.035672 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:03:27.185680 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 09:09:55.075882 139799335950080 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:09:55.085885 139799335950080 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 09:09:55.566352 139799335950080 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.23s).\nAccumulating evaluation results...\nDONE (t=2.89s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.301\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.650\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.221\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.322\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.189\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.003\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.249\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.439\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.468\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.482\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.378\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.513\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:10:21\nI0617 09:10:21.621694 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-09:10:21\nINFO:tensorflow:Saving dict for global step 304: DetectionBoxes_Precision/mAP = 0.30102244, DetectionBoxes_Precision/mAP (large) = 0.0028955534, DetectionBoxes_Precision/mAP (medium) = 0.18877691, DetectionBoxes_Precision/mAP (small) = 0.3215453, DetectionBoxes_Precision/[email protected] = 0.6500826, DetectionBoxes_Precision/[email protected] = 0.22105871, DetectionBoxes_Recall/AR@1 = 0.24879579, DetectionBoxes_Recall/AR@10 = 0.43897995, DetectionBoxes_Recall/AR@100 = 0.46834648, DetectionBoxes_Recall/AR@100 (large) = 0.5133333, DetectionBoxes_Recall/AR@100 (medium) = 0.3784522, DetectionBoxes_Recall/AR@100 (small) = 0.48205248, Loss/BoxClassifierLoss/classification_loss = 0.09752336, Loss/BoxClassifierLoss/localization_loss = 0.08336916, Loss/RPNLoss/localization_loss = 0.040898863, Loss/RPNLoss/objectness_loss = 0.08552844, Loss/total_loss = 0.30731982, global_step = 304, learning_rate = 0.0002, loss = 0.30731982\nI0617 09:10:21.622043 139802647791488 estimator.py:2049] Saving dict for global step 304: DetectionBoxes_Precision/mAP = 0.30102244, DetectionBoxes_Precision/mAP (large) = 0.0028955534, DetectionBoxes_Precision/mAP (medium) = 0.18877691, DetectionBoxes_Precision/mAP (small) = 0.3215453, DetectionBoxes_Precision/[email protected] = 0.6500826, DetectionBoxes_Precision/[email protected] = 0.22105871, DetectionBoxes_Recall/AR@1 = 0.24879579, DetectionBoxes_Recall/AR@10 = 0.43897995, DetectionBoxes_Recall/AR@100 = 0.46834648, DetectionBoxes_Recall/AR@100 (large) = 0.5133333, DetectionBoxes_Recall/AR@100 (medium) = 0.3784522, DetectionBoxes_Recall/AR@100 (small) = 0.48205248, Loss/BoxClassifierLoss/classification_loss = 0.09752336, Loss/BoxClassifierLoss/localization_loss = 0.08336916, Loss/RPNLoss/localization_loss = 0.040898863, Loss/RPNLoss/objectness_loss = 0.08552844, Loss/total_loss = 0.30731982, global_step = 304, learning_rate = 0.0002, loss = 0.30731982\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 304: training/model.ckpt-304\nI0617 09:10:22.837960 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 304: training/model.ckpt-304\nINFO:tensorflow:Saving checkpoints for 397 into training/model.ckpt.\nI0617 09:13:18.144727 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 397 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f256d6de4a8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 09:13:20.410936 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f256d6de4a8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25ea046400> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:13:20.642064 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25ea046400> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:13:21.316280 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:13:23.237620 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:13:23.256669 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:13:23.257187 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:13:24.551907 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:13:24.573545 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 09:13:26.768089 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:13:26Z\nI0617 09:13:26.789741 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T09:13:26Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:13:27.379868 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:13:27.380733: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:13:27.381211: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 09:13:27.381373: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:13:27.381435: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:13:27.381497: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:13:27.381556: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:13:27.381622: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:13:27.381677: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:13:27.381734: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:13:27.381910: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:13:27.382343: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:13:27.382654: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:13:27.382709: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:13:27.382738: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:13:27.382765: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:13:27.382924: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:13:27.383337: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:13:27.383680: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-397\nI0617 09:13:27.384910 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-397\nINFO:tensorflow:Running local_init_op.\nI0617 09:13:28.428139 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:13:28.579118 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 09:19:53.876752 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:19:53.884868 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.49s)\nI0617 09:19:54.376165 139799327557376 coco_tools.py:138] DONE (t=0.49s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.15s).\nAccumulating evaluation results...\nDONE (t=2.88s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.317\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.670\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.238\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.337\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.198\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.003\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.255\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.456\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.488\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.501\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.406\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.480\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:20:20\nI0617 09:20:20.320706 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-09:20:20\nINFO:tensorflow:Saving dict for global step 397: DetectionBoxes_Precision/mAP = 0.31654575, DetectionBoxes_Precision/mAP (large) = 0.002658377, DetectionBoxes_Precision/mAP (medium) = 0.19834335, DetectionBoxes_Precision/mAP (small) = 0.33739334, DetectionBoxes_Precision/[email protected] = 0.6695401, DetectionBoxes_Precision/[email protected] = 0.23836155, DetectionBoxes_Recall/AR@1 = 0.25472575, DetectionBoxes_Recall/AR@10 = 0.45622343, DetectionBoxes_Recall/AR@100 = 0.4884234, DetectionBoxes_Recall/AR@100 (large) = 0.48, DetectionBoxes_Recall/AR@100 (medium) = 0.4063733, DetectionBoxes_Recall/AR@100 (small) = 0.50105435, Loss/BoxClassifierLoss/classification_loss = 0.10596372, Loss/BoxClassifierLoss/localization_loss = 0.087367184, Loss/RPNLoss/localization_loss = 0.038753074, Loss/RPNLoss/objectness_loss = 0.084906965, Loss/total_loss = 0.31699136, global_step = 397, learning_rate = 0.0002, loss = 0.31699136\nI0617 09:20:20.321013 139802647791488 estimator.py:2049] Saving dict for global step 397: DetectionBoxes_Precision/mAP = 0.31654575, DetectionBoxes_Precision/mAP (large) = 0.002658377, DetectionBoxes_Precision/mAP (medium) = 0.19834335, DetectionBoxes_Precision/mAP (small) = 0.33739334, DetectionBoxes_Precision/[email protected] = 0.6695401, DetectionBoxes_Precision/[email protected] = 0.23836155, DetectionBoxes_Recall/AR@1 = 0.25472575, DetectionBoxes_Recall/AR@10 = 0.45622343, DetectionBoxes_Recall/AR@100 = 0.4884234, DetectionBoxes_Recall/AR@100 (large) = 0.48, DetectionBoxes_Recall/AR@100 (medium) = 0.4063733, DetectionBoxes_Recall/AR@100 (small) = 0.50105435, Loss/BoxClassifierLoss/classification_loss = 0.10596372, Loss/BoxClassifierLoss/localization_loss = 0.087367184, Loss/RPNLoss/localization_loss = 0.038753074, Loss/RPNLoss/objectness_loss = 0.084906965, Loss/total_loss = 0.31699136, global_step = 397, learning_rate = 0.0002, loss = 0.31699136\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 397: training/model.ckpt-397\nI0617 09:20:20.322307 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 397: training/model.ckpt-397\nINFO:tensorflow:global_step/sec: 0.0964088\nI0617 09:20:27.940744 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.0964088\nINFO:tensorflow:loss = 0.5228123, step = 400 (1037.249 sec)\nI0617 09:20:27.942262 139802647791488 basic_session_run_hooks.py:260] loss = 0.5228123, step = 400 (1037.249 sec)\nINFO:tensorflow:Saving checkpoints for 492 into training/model.ckpt.\nI0617 09:23:18.587970 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 492 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f256d794cc0>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 09:23:20.964770 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f256d794cc0>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256d462c80> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:23:21.195350 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256d462c80> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:23:22.224460 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:23:24.162819 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:23:24.179536 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:23:24.179966 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:23:25.460384 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:23:25.483160 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 09:23:27.607132 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:23:27Z\nI0617 09:23:27.629013 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T09:23:27Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:23:28.240840 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:23:28.241682: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:23:28.242094: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 09:23:28.242243: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:23:28.242319: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:23:28.242396: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:23:28.242463: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:23:28.242517: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:23:28.242611: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:23:28.242674: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:23:28.242830: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:23:28.243253: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:23:28.243538: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:23:28.243603: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:23:28.243630: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:23:28.243646: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:23:28.243833: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:23:28.244314: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:23:28.244713: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-492\nI0617 09:23:28.246314 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-492\nINFO:tensorflow:Running local_init_op.\nI0617 09:23:29.317684 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:23:29.463603 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 09:29:55.580435 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:29:55.589095 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.50s)\nI0617 09:29:56.085434 139799327557376 coco_tools.py:138] DONE (t=0.50s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.10s).\nAccumulating evaluation results...\nDONE (t=2.82s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.310\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.663\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.231\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.331\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.196\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.004\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.251\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.452\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.487\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.499\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.413\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.493\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:30:21\nI0617 09:30:21.867248 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-09:30:21\nINFO:tensorflow:Saving dict for global step 492: DetectionBoxes_Precision/mAP = 0.31028607, DetectionBoxes_Precision/mAP (large) = 0.0043341694, DetectionBoxes_Precision/mAP (medium) = 0.19571707, DetectionBoxes_Precision/mAP (small) = 0.3314546, DetectionBoxes_Precision/[email protected] = 0.662934, DetectionBoxes_Precision/[email protected] = 0.23120397, DetectionBoxes_Recall/AR@1 = 0.25090063, DetectionBoxes_Recall/AR@10 = 0.45231736, DetectionBoxes_Recall/AR@100 = 0.48708764, DetectionBoxes_Recall/AR@100 (large) = 0.49333334, DetectionBoxes_Recall/AR@100 (medium) = 0.41274658, DetectionBoxes_Recall/AR@100 (small) = 0.49850047, Loss/BoxClassifierLoss/classification_loss = 0.11129096, Loss/BoxClassifierLoss/localization_loss = 0.091888644, Loss/RPNLoss/localization_loss = 0.038377043, Loss/RPNLoss/objectness_loss = 0.081706315, Loss/total_loss = 0.32326302, global_step = 492, learning_rate = 0.0002, loss = 0.32326302\nI0617 09:30:21.867757 139802647791488 estimator.py:2049] Saving dict for global step 492: DetectionBoxes_Precision/mAP = 0.31028607, DetectionBoxes_Precision/mAP (large) = 0.0043341694, DetectionBoxes_Precision/mAP (medium) = 0.19571707, DetectionBoxes_Precision/mAP (small) = 0.3314546, DetectionBoxes_Precision/[email protected] = 0.662934, DetectionBoxes_Precision/[email protected] = 0.23120397, DetectionBoxes_Recall/AR@1 = 0.25090063, DetectionBoxes_Recall/AR@10 = 0.45231736, DetectionBoxes_Recall/AR@100 = 0.48708764, DetectionBoxes_Recall/AR@100 (large) = 0.49333334, DetectionBoxes_Recall/AR@100 (medium) = 0.41274658, DetectionBoxes_Recall/AR@100 (small) = 0.49850047, Loss/BoxClassifierLoss/classification_loss = 0.11129096, Loss/BoxClassifierLoss/localization_loss = 0.091888644, Loss/RPNLoss/localization_loss = 0.038377043, Loss/RPNLoss/objectness_loss = 0.081706315, Loss/total_loss = 0.32326302, global_step = 492, learning_rate = 0.0002, loss = 0.32326302\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 492: training/model.ckpt-492\nI0617 09:30:21.869137 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 492: training/model.ckpt-492\nINFO:tensorflow:global_step/sec: 0.163752\nI0617 09:30:38.620423 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163752\nINFO:tensorflow:loss = 0.43197256, step = 500 (610.680 sec)\nI0617 09:30:38.621876 139802647791488 basic_session_run_hooks.py:260] loss = 0.43197256, step = 500 (610.680 sec)\nINFO:tensorflow:Saving checkpoints for 587 into training/model.ckpt.\nI0617 09:33:19.412141 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 587 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e028da58>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 09:33:21.791113 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e028da58>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256d3eca60> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:33:22.011909 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256d3eca60> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:33:23.077821 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:33:25.037920 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:33:25.056176 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:33:25.056565 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:33:26.355836 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:33:26.376722 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 09:33:28.507978 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:33:28Z\nI0617 09:33:28.530186 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T09:33:28Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:33:29.137186 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:33:29.138069: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:33:29.138509: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 09:33:29.138656: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:33:29.138718: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:33:29.138768: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:33:29.138820: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:33:29.138860: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:33:29.138937: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:33:29.138986: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:33:29.139136: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:33:29.139603: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:33:29.139917: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:33:29.139995: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:33:29.140015: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:33:29.140054: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:33:29.140220: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:33:29.140773: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:33:29.141107: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-587\nI0617 09:33:29.142320 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-587\nINFO:tensorflow:Running local_init_op.\nI0617 09:33:30.246475 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:33:30.397874 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 09:39:58.273677 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:39:58.281780 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.49s)\nI0617 09:39:58.771351 139799327557376 coco_tools.py:138] DONE (t=0.49s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.73s).\nAccumulating evaluation results...\nDONE (t=2.85s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.322\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.677\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.253\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.342\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.208\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.005\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.258\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.465\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.498\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.508\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.436\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.467\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:40:24\nI0617 09:40:24.252780 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-09:40:24\nINFO:tensorflow:Saving dict for global step 587: DetectionBoxes_Precision/mAP = 0.3216573, DetectionBoxes_Precision/mAP (large) = 0.005455753, DetectionBoxes_Precision/mAP (medium) = 0.20822518, DetectionBoxes_Precision/mAP (small) = 0.34199223, DetectionBoxes_Precision/[email protected] = 0.67727506, DetectionBoxes_Precision/[email protected] = 0.25340477, DetectionBoxes_Recall/AR@1 = 0.25786278, DetectionBoxes_Recall/AR@10 = 0.46510828, DetectionBoxes_Recall/AR@100 = 0.49809754, DetectionBoxes_Recall/AR@100 (large) = 0.46666667, DetectionBoxes_Recall/AR@100 (medium) = 0.4356601, DetectionBoxes_Recall/AR@100 (small) = 0.50780225, Loss/BoxClassifierLoss/classification_loss = 0.11380663, Loss/BoxClassifierLoss/localization_loss = 0.092767306, Loss/RPNLoss/localization_loss = 0.037355013, Loss/RPNLoss/objectness_loss = 0.08002754, Loss/total_loss = 0.32395688, global_step = 587, learning_rate = 0.0002, loss = 0.32395688\nI0617 09:40:24.253174 139802647791488 estimator.py:2049] Saving dict for global step 587: DetectionBoxes_Precision/mAP = 0.3216573, DetectionBoxes_Precision/mAP (large) = 0.005455753, DetectionBoxes_Precision/mAP (medium) = 0.20822518, DetectionBoxes_Precision/mAP (small) = 0.34199223, DetectionBoxes_Precision/[email protected] = 0.67727506, DetectionBoxes_Precision/[email protected] = 0.25340477, DetectionBoxes_Recall/AR@1 = 0.25786278, DetectionBoxes_Recall/AR@10 = 0.46510828, DetectionBoxes_Recall/AR@100 = 0.49809754, DetectionBoxes_Recall/AR@100 (large) = 0.46666667, DetectionBoxes_Recall/AR@100 (medium) = 0.4356601, DetectionBoxes_Recall/AR@100 (small) = 0.50780225, Loss/BoxClassifierLoss/classification_loss = 0.11380663, Loss/BoxClassifierLoss/localization_loss = 0.092767306, Loss/RPNLoss/localization_loss = 0.037355013, Loss/RPNLoss/objectness_loss = 0.08002754, Loss/total_loss = 0.32395688, global_step = 587, learning_rate = 0.0002, loss = 0.32395688\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 587: training/model.ckpt-587\nI0617 09:40:24.254391 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 587: training/model.ckpt-587\nINFO:tensorflow:global_step/sec: 0.163402\nI0617 09:40:50.609552 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163402\nINFO:tensorflow:loss = 0.5513719, step = 600 (611.989 sec)\nI0617 09:40:50.611058 139802647791488 basic_session_run_hooks.py:260] loss = 0.5513719, step = 600 (611.989 sec)\nINFO:tensorflow:Saving checkpoints for 680 into training/model.ckpt.\nI0617 09:43:19.732001 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 680 into training/model.ckpt.\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/training/saver.py:963: remove_checkpoint (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse standard file APIs to delete files with this prefix.\nW0617 09:43:19.885838 139802647791488 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/training/saver.py:963: remove_checkpoint (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse standard file APIs to delete files with this prefix.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f256d6d2b00>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 09:43:22.173925 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f256d6d2b00>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348950> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:43:22.398154 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348950> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:43:23.162628 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:43:25.388596 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:43:25.405709 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:43:25.406070 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:43:26.696761 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:43:26.717764 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 09:43:28.889770 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:43:28Z\nI0617 09:43:28.910487 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T09:43:28Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:43:29.509376 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:43:29.510325: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:43:29.510753: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 09:43:29.510866: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:43:29.510927: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:43:29.510978: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:43:29.511032: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:43:29.511076: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:43:29.511119: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:43:29.511164: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:43:29.511327: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:43:29.511747: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:43:29.512040: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:43:29.512095: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:43:29.512117: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:43:29.512132: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:43:29.512294: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:43:29.512710: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:43:29.513035: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-680\nI0617 09:43:29.514486 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-680\nINFO:tensorflow:Running local_init_op.\nI0617 09:43:30.628054 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:43:30.776070 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 09:49:57.866572 139799335950080 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:49:57.876522 139799335950080 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 09:49:58.359786 139799335950080 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.73s).\nAccumulating evaluation results...\nDONE (t=2.85s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.313\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.671\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.237\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.334\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.204\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.005\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.252\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.459\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.495\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.504\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.436\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.493\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:50:23\nI0617 09:50:23.818917 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-09:50:23\nINFO:tensorflow:Saving dict for global step 680: DetectionBoxes_Precision/mAP = 0.31328058, DetectionBoxes_Precision/mAP (large) = 0.0049730497, DetectionBoxes_Precision/mAP (medium) = 0.20442589, DetectionBoxes_Precision/mAP (small) = 0.33366096, DetectionBoxes_Precision/[email protected] = 0.67076516, DetectionBoxes_Precision/[email protected] = 0.23672819, DetectionBoxes_Recall/AR@1 = 0.25233757, DetectionBoxes_Recall/AR@10 = 0.45931998, DetectionBoxes_Recall/AR@100 = 0.49530458, DetectionBoxes_Recall/AR@100 (large) = 0.49333334, DetectionBoxes_Recall/AR@100 (medium) = 0.4356601, DetectionBoxes_Recall/AR@100 (small) = 0.5044752, Loss/BoxClassifierLoss/classification_loss = 0.11971803, Loss/BoxClassifierLoss/localization_loss = 0.09785683, Loss/RPNLoss/localization_loss = 0.037010368, Loss/RPNLoss/objectness_loss = 0.07979442, Loss/total_loss = 0.33437935, global_step = 680, learning_rate = 0.0002, loss = 0.33437935\nI0617 09:50:23.819239 139802647791488 estimator.py:2049] Saving dict for global step 680: DetectionBoxes_Precision/mAP = 0.31328058, DetectionBoxes_Precision/mAP (large) = 0.0049730497, DetectionBoxes_Precision/mAP (medium) = 0.20442589, DetectionBoxes_Precision/mAP (small) = 0.33366096, DetectionBoxes_Precision/[email protected] = 0.67076516, DetectionBoxes_Precision/[email protected] = 0.23672819, DetectionBoxes_Recall/AR@1 = 0.25233757, DetectionBoxes_Recall/AR@10 = 0.45931998, DetectionBoxes_Recall/AR@100 = 0.49530458, DetectionBoxes_Recall/AR@100 (large) = 0.49333334, DetectionBoxes_Recall/AR@100 (medium) = 0.4356601, DetectionBoxes_Recall/AR@100 (small) = 0.5044752, Loss/BoxClassifierLoss/classification_loss = 0.11971803, Loss/BoxClassifierLoss/localization_loss = 0.09785683, Loss/RPNLoss/localization_loss = 0.037010368, Loss/RPNLoss/objectness_loss = 0.07979442, Loss/total_loss = 0.33437935, global_step = 680, learning_rate = 0.0002, loss = 0.33437935\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 680: training/model.ckpt-680\nI0617 09:50:23.820399 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 680: training/model.ckpt-680\nINFO:tensorflow:global_step/sec: 0.163242\nI0617 09:51:03.198357 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163242\nINFO:tensorflow:loss = 0.6384513, step = 700 (612.589 sec)\nI0617 09:51:03.199834 139802647791488 basic_session_run_hooks.py:260] loss = 0.6384513, step = 700 (612.589 sec)\nINFO:tensorflow:Saving checkpoints for 774 into training/model.ckpt.\nI0617 09:53:21.133934 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 774 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2582431a90>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 09:53:23.603084 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2582431a90>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f258a87a510> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:53:23.843273 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f258a87a510> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:53:24.592526 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:53:26.442865 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:53:26.459075 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:53:26.459435 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:53:28.061152 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:53:28.084334 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 09:53:30.276308 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:53:30Z\nI0617 09:53:30.297646 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T09:53:30Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:53:30.906702 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:53:30.907492: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:53:30.907906: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 09:53:30.908000: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:53:30.908047: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:53:30.908109: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:53:30.908158: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:53:30.908202: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:53:30.908245: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:53:30.908288: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:53:30.908430: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:53:30.909041: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:53:30.909365: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:53:30.909420: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:53:30.909443: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:53:30.909459: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:53:30.909636: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:53:30.910016: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:53:30.910495: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-774\nI0617 09:53:30.911690 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-774\nINFO:tensorflow:Running local_init_op.\nI0617 09:53:31.984099 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:53:32.130879 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 09:59:57.993338 139799335950080 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:59:58.005127 139799335950080 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.49s)\nI0617 09:59:58.499085 139799335950080 coco_tools.py:138] DONE (t=0.49s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.51s).\nAccumulating evaluation results...\nDONE (t=2.85s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.323\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.683\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.245\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.342\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.222\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.006\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.259\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.470\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.507\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.514\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.461\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.513\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:00:23\nI0617 10:00:23.704938 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-10:00:23\nINFO:tensorflow:Saving dict for global step 774: DetectionBoxes_Precision/mAP = 0.3227786, DetectionBoxes_Precision/mAP (large) = 0.005871538, DetectionBoxes_Precision/mAP (medium) = 0.22151007, DetectionBoxes_Precision/mAP (small) = 0.3419864, DetectionBoxes_Precision/[email protected] = 0.68298274, DetectionBoxes_Precision/[email protected] = 0.2446977, DetectionBoxes_Recall/AR@1 = 0.25915807, DetectionBoxes_Recall/AR@10 = 0.46952033, DetectionBoxes_Recall/AR@100 = 0.50678, DetectionBoxes_Recall/AR@100 (large) = 0.5133333, DetectionBoxes_Recall/AR@100 (medium) = 0.46069804, DetectionBoxes_Recall/AR@100 (small) = 0.51384723, Loss/BoxClassifierLoss/classification_loss = 0.12124108, Loss/BoxClassifierLoss/localization_loss = 0.09775733, Loss/RPNLoss/localization_loss = 0.03678816, Loss/RPNLoss/objectness_loss = 0.07607423, Loss/total_loss = 0.3318606, global_step = 774, learning_rate = 0.0002, loss = 0.3318606\nI0617 10:00:23.705271 139802647791488 estimator.py:2049] Saving dict for global step 774: DetectionBoxes_Precision/mAP = 0.3227786, DetectionBoxes_Precision/mAP (large) = 0.005871538, DetectionBoxes_Precision/mAP (medium) = 0.22151007, DetectionBoxes_Precision/mAP (small) = 0.3419864, DetectionBoxes_Precision/[email protected] = 0.68298274, DetectionBoxes_Precision/[email protected] = 0.2446977, DetectionBoxes_Recall/AR@1 = 0.25915807, DetectionBoxes_Recall/AR@10 = 0.46952033, DetectionBoxes_Recall/AR@100 = 0.50678, DetectionBoxes_Recall/AR@100 (large) = 0.5133333, DetectionBoxes_Recall/AR@100 (medium) = 0.46069804, DetectionBoxes_Recall/AR@100 (small) = 0.51384723, Loss/BoxClassifierLoss/classification_loss = 0.12124108, Loss/BoxClassifierLoss/localization_loss = 0.09775733, Loss/RPNLoss/localization_loss = 0.03678816, Loss/RPNLoss/objectness_loss = 0.07607423, Loss/total_loss = 0.3318606, global_step = 774, learning_rate = 0.0002, loss = 0.3318606\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 774: training/model.ckpt-774\nI0617 10:00:23.706647 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 774: training/model.ckpt-774\nINFO:tensorflow:global_step/sec: 0.163729\nI0617 10:01:13.964701 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163729\nINFO:tensorflow:loss = 0.51952976, step = 800 (610.766 sec)\nI0617 10:01:13.966169 139802647791488 basic_session_run_hooks.py:260] loss = 0.51952976, step = 800 (610.766 sec)\nINFO:tensorflow:Saving checkpoints for 869 into training/model.ckpt.\nI0617 10:03:21.413390 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 869 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2585c18780>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 10:03:23.790722 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2585c18780>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e0085488> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:03:24.006200 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e0085488> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:03:24.688405 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:03:26.558005 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:03:26.576160 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:03:26.576552 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:03:27.922190 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:03:27.943778 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:03:30.123743 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:03:30Z\nI0617 10:03:30.144896 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T10:03:30Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:03:30.739018 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:03:30.739885: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:03:30.740254: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 10:03:30.740364: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:03:30.740411: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:03:30.740458: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:03:30.740506: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:03:30.740548: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:03:30.740611: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:03:30.740654: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:03:30.740796: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:03:30.741193: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:03:30.741474: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:03:30.741526: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:03:30.741548: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:03:30.741562: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:03:30.741725: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:03:30.742099: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:03:30.742387: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-869\nI0617 10:03:30.743566 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-869\nINFO:tensorflow:Running local_init_op.\nI0617 10:03:31.818225 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:03:31.956973 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 10:09:58.067379 139799335950080 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:09:58.075883 139799335950080 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 10:09:58.551983 139799335950080 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.98s).\nAccumulating evaluation results...\nDONE (t=2.87s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.321\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.675\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.254\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.341\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.216\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.006\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.258\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.469\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.508\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.514\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.467\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.507\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:10:24\nI0617 10:10:24.312726 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-10:10:24\nINFO:tensorflow:Saving dict for global step 869: DetectionBoxes_Precision/mAP = 0.32119274, DetectionBoxes_Precision/mAP (large) = 0.00567189, DetectionBoxes_Precision/mAP (medium) = 0.21638714, DetectionBoxes_Precision/mAP (small) = 0.34094587, DetectionBoxes_Precision/[email protected] = 0.67546767, DetectionBoxes_Precision/[email protected] = 0.2537081, DetectionBoxes_Recall/AR@1 = 0.25753897, DetectionBoxes_Recall/AR@10 = 0.4685084, DetectionBoxes_Recall/AR@100 = 0.50763005, DetectionBoxes_Recall/AR@100 (large) = 0.50666666, DetectionBoxes_Recall/AR@100 (medium) = 0.4673748, DetectionBoxes_Recall/AR@100 (small) = 0.5138238, Loss/BoxClassifierLoss/classification_loss = 0.12643787, Loss/BoxClassifierLoss/localization_loss = 0.09976964, Loss/RPNLoss/localization_loss = 0.036813866, Loss/RPNLoss/objectness_loss = 0.07451692, Loss/total_loss = 0.33753818, global_step = 869, learning_rate = 0.0002, loss = 0.33753818\nI0617 10:10:24.313090 139802647791488 estimator.py:2049] Saving dict for global step 869: DetectionBoxes_Precision/mAP = 0.32119274, DetectionBoxes_Precision/mAP (large) = 0.00567189, DetectionBoxes_Precision/mAP (medium) = 0.21638714, DetectionBoxes_Precision/mAP (small) = 0.34094587, DetectionBoxes_Precision/[email protected] = 0.67546767, DetectionBoxes_Precision/[email protected] = 0.2537081, DetectionBoxes_Recall/AR@1 = 0.25753897, DetectionBoxes_Recall/AR@10 = 0.4685084, DetectionBoxes_Recall/AR@100 = 0.50763005, DetectionBoxes_Recall/AR@100 (large) = 0.50666666, DetectionBoxes_Recall/AR@100 (medium) = 0.4673748, DetectionBoxes_Recall/AR@100 (small) = 0.5138238, Loss/BoxClassifierLoss/classification_loss = 0.12643787, Loss/BoxClassifierLoss/localization_loss = 0.09976964, Loss/RPNLoss/localization_loss = 0.036813866, Loss/RPNLoss/objectness_loss = 0.07451692, Loss/total_loss = 0.33753818, global_step = 869, learning_rate = 0.0002, loss = 0.33753818\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 869: training/model.ckpt-869\nI0617 10:10:24.314385 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 869: training/model.ckpt-869\nINFO:tensorflow:global_step/sec: 0.163673\nI0617 10:11:24.938791 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163673\nINFO:tensorflow:loss = 0.605257, step = 900 (610.974 sec)\nI0617 10:11:24.940254 139802647791488 basic_session_run_hooks.py:260] loss = 0.605257, step = 900 (610.974 sec)\nINFO:tensorflow:Saving checkpoints for 963 into training/model.ckpt.\nI0617 10:13:21.774383 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 963 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f257b097160>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 10:13:24.227612 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f257b097160>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256d7d1ae8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:13:24.457230 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256d7d1ae8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:13:25.135904 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:13:27.043474 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:13:27.060173 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:13:27.060652 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:13:28.345263 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:13:28.366737 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:13:30.514560 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:13:30Z\nI0617 10:13:30.535616 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T10:13:30Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:13:31.129958 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:13:31.130797: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:13:31.131198: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 10:13:31.131293: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:13:31.131348: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:13:31.131395: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:13:31.131445: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:13:31.131487: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:13:31.131528: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:13:31.131570: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:13:31.131731: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:13:31.132143: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:13:31.132521: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:13:31.132588: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:13:31.132610: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:13:31.132625: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:13:31.132780: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:13:31.133237: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:13:31.133551: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-963\nI0617 10:13:31.134826 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-963\nINFO:tensorflow:Running local_init_op.\nI0617 10:13:32.204608 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:13:32.359159 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 10:19:58.753206 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:19:58.761821 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 10:19:59.242709 139799327557376 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.23s).\nAccumulating evaluation results...\nDONE (t=2.90s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.316\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.670\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.237\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.336\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.208\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.005\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.253\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.466\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.504\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.511\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.458\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.500\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:20:25\nI0617 10:20:25.250772 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-10:20:25\nINFO:tensorflow:Saving dict for global step 963: DetectionBoxes_Precision/mAP = 0.31550056, DetectionBoxes_Precision/mAP (large) = 0.005450045, DetectionBoxes_Precision/mAP (medium) = 0.20829868, DetectionBoxes_Precision/mAP (small) = 0.3359797, DetectionBoxes_Precision/[email protected] = 0.6702008, DetectionBoxes_Precision/[email protected] = 0.23679096, DetectionBoxes_Recall/AR@1 = 0.25332928, DetectionBoxes_Recall/AR@10 = 0.4660595, DetectionBoxes_Recall/AR@100 = 0.50378466, DetectionBoxes_Recall/AR@100 (large) = 0.5, DetectionBoxes_Recall/AR@100 (medium) = 0.45842186, DetectionBoxes_Recall/AR@100 (small) = 0.5107779, Loss/BoxClassifierLoss/classification_loss = 0.11668084, Loss/BoxClassifierLoss/localization_loss = 0.101718634, Loss/RPNLoss/localization_loss = 0.03671709, Loss/RPNLoss/objectness_loss = 0.075118385, Loss/total_loss = 0.33023494, global_step = 963, learning_rate = 0.0002, loss = 0.33023494\nI0617 10:20:25.251122 139802647791488 estimator.py:2049] Saving dict for global step 963: DetectionBoxes_Precision/mAP = 0.31550056, DetectionBoxes_Precision/mAP (large) = 0.005450045, DetectionBoxes_Precision/mAP (medium) = 0.20829868, DetectionBoxes_Precision/mAP (small) = 0.3359797, DetectionBoxes_Precision/[email protected] = 0.6702008, DetectionBoxes_Precision/[email protected] = 0.23679096, DetectionBoxes_Recall/AR@1 = 0.25332928, DetectionBoxes_Recall/AR@10 = 0.4660595, DetectionBoxes_Recall/AR@100 = 0.50378466, DetectionBoxes_Recall/AR@100 (large) = 0.5, DetectionBoxes_Recall/AR@100 (medium) = 0.45842186, DetectionBoxes_Recall/AR@100 (small) = 0.5107779, Loss/BoxClassifierLoss/classification_loss = 0.11668084, Loss/BoxClassifierLoss/localization_loss = 0.101718634, Loss/RPNLoss/localization_loss = 0.03671709, Loss/RPNLoss/objectness_loss = 0.075118385, Loss/total_loss = 0.33023494, global_step = 963, learning_rate = 0.0002, loss = 0.33023494\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 963: training/model.ckpt-963\nI0617 10:20:25.252166 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 963: training/model.ckpt-963\nINFO:tensorflow:global_step/sec: 0.163637\nI0617 10:21:36.046636 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163637\nINFO:tensorflow:loss = 0.6556028, step = 1000 (611.108 sec)\nI0617 10:21:36.048070 139802647791488 basic_session_run_hooks.py:260] loss = 0.6556028, step = 1000 (611.108 sec)\nINFO:tensorflow:Saving checkpoints for 1058 into training/model.ckpt.\nI0617 10:23:23.400055 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1058 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2588a802e8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 10:23:25.841529 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2588a802e8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2588acb510> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:23:26.071191 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2588acb510> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:23:27.112606 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:23:29.060023 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:23:29.078756 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:23:29.079192 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:23:30.345223 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:23:30.366508 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:23:32.566471 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:23:32Z\nI0617 10:23:32.587623 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T10:23:32Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:23:33.172688 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:23:33.173537: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:23:33.173915: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 10:23:33.174031: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:23:33.174079: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:23:33.174144: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:23:33.174185: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:23:33.174227: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:23:33.174272: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:23:33.174318: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:23:33.174495: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:23:33.174956: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:23:33.175266: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:23:33.175322: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:23:33.175343: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:23:33.175358: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:23:33.175514: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:23:33.175916: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:23:33.176270: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1058\nI0617 10:23:33.177652 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1058\nINFO:tensorflow:Running local_init_op.\nI0617 10:23:34.289046 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:23:34.450568 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 10:30:01.776358 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:30:01.796285 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.46s)\nI0617 10:30:02.259448 139799327557376 coco_tools.py:138] DONE (t=0.46s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.05s).\nAccumulating evaluation results...\nDONE (t=2.91s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.319\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.677\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.244\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.340\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.213\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.009\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.254\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.468\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.509\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.516\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.460\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.500\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:30:28\nI0617 10:30:28.069728 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-10:30:28\nINFO:tensorflow:Saving dict for global step 1058: DetectionBoxes_Precision/mAP = 0.31909412, DetectionBoxes_Precision/mAP (large) = 0.009121176, DetectionBoxes_Precision/mAP (medium) = 0.21321878, DetectionBoxes_Precision/mAP (small) = 0.34019524, DetectionBoxes_Precision/[email protected] = 0.6766073, DetectionBoxes_Precision/[email protected] = 0.24373096, DetectionBoxes_Recall/AR@1 = 0.2541186, DetectionBoxes_Recall/AR@10 = 0.467881, DetectionBoxes_Recall/AR@100 = 0.50864196, DetectionBoxes_Recall/AR@100 (large) = 0.5, DetectionBoxes_Recall/AR@100 (medium) = 0.46009105, DetectionBoxes_Recall/AR@100 (small) = 0.5161434, Loss/BoxClassifierLoss/classification_loss = 0.1300322, Loss/BoxClassifierLoss/localization_loss = 0.10332142, Loss/RPNLoss/localization_loss = 0.036500596, Loss/RPNLoss/objectness_loss = 0.07351136, Loss/total_loss = 0.3433657, global_step = 1058, learning_rate = 0.0002, loss = 0.3433657\nI0617 10:30:28.070079 139802647791488 estimator.py:2049] Saving dict for global step 1058: DetectionBoxes_Precision/mAP = 0.31909412, DetectionBoxes_Precision/mAP (large) = 0.009121176, DetectionBoxes_Precision/mAP (medium) = 0.21321878, DetectionBoxes_Precision/mAP (small) = 0.34019524, DetectionBoxes_Precision/[email protected] = 0.6766073, DetectionBoxes_Precision/[email protected] = 0.24373096, DetectionBoxes_Recall/AR@1 = 0.2541186, DetectionBoxes_Recall/AR@10 = 0.467881, DetectionBoxes_Recall/AR@100 = 0.50864196, DetectionBoxes_Recall/AR@100 (large) = 0.5, DetectionBoxes_Recall/AR@100 (medium) = 0.46009105, DetectionBoxes_Recall/AR@100 (small) = 0.5161434, Loss/BoxClassifierLoss/classification_loss = 0.1300322, Loss/BoxClassifierLoss/localization_loss = 0.10332142, Loss/RPNLoss/localization_loss = 0.036500596, Loss/RPNLoss/objectness_loss = 0.07351136, Loss/total_loss = 0.3433657, global_step = 1058, learning_rate = 0.0002, loss = 0.3433657\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1058: training/model.ckpt-1058\nI0617 10:30:28.071364 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1058: training/model.ckpt-1058\nINFO:tensorflow:global_step/sec: 0.163363\nI0617 10:31:48.180052 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163363\nINFO:tensorflow:loss = 0.53314406, step = 1100 (612.133 sec)\nI0617 10:31:48.181440 139802647791488 basic_session_run_hooks.py:260] loss = 0.53314406, step = 1100 (612.133 sec)\nINFO:tensorflow:Saving checkpoints for 1152 into training/model.ckpt.\nI0617 10:33:24.509836 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1152 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e02aa048>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 10:33:26.948322 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e02aa048>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348d90> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:33:27.172644 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348d90> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:33:28.205767 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:33:30.176141 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:33:30.194098 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:33:30.194556 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:33:31.522054 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:33:31.542139 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:33:33.723077 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:33:33Z\nI0617 10:33:33.743967 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T10:33:33Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:33:34.344648 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:33:34.345484: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:33:34.345948: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 10:33:34.346047: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:33:34.346102: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:33:34.346181: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:33:34.346234: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:33:34.346279: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:33:34.346322: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:33:34.346381: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:33:34.346519: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:33:34.346930: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:33:34.347237: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:33:34.347291: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:33:34.347314: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:33:34.347332: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:33:34.347493: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:33:34.347964: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:33:34.348360: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1152\nI0617 10:33:34.349535 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1152\nINFO:tensorflow:Running local_init_op.\nI0617 10:33:35.420451 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:33:35.572655 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 10:40:00.878658 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:40:00.888298 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.47s)\nI0617 10:40:01.354110 139799327557376 coco_tools.py:138] DONE (t=0.47s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.14s).\nAccumulating evaluation results...\nDONE (t=2.95s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.334\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.695\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.264\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.353\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.231\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.008\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.265\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.481\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.520\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.525\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.488\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.487\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:40:27\nI0617 10:40:27.308949 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-10:40:27\nINFO:tensorflow:Saving dict for global step 1152: DetectionBoxes_Precision/mAP = 0.33436817, DetectionBoxes_Precision/mAP (large) = 0.007504563, DetectionBoxes_Precision/mAP (medium) = 0.23078635, DetectionBoxes_Precision/mAP (small) = 0.35336673, DetectionBoxes_Precision/[email protected] = 0.69455814, DetectionBoxes_Precision/[email protected] = 0.26429784, DetectionBoxes_Recall/AR@1 = 0.2652297, DetectionBoxes_Recall/AR@10 = 0.48146126, DetectionBoxes_Recall/AR@100 = 0.51969236, DetectionBoxes_Recall/AR@100 (large) = 0.48666668, DetectionBoxes_Recall/AR@100 (medium) = 0.48786038, DetectionBoxes_Recall/AR@100 (small) = 0.5246954, Loss/BoxClassifierLoss/classification_loss = 0.12105487, Loss/BoxClassifierLoss/localization_loss = 0.09975987, Loss/RPNLoss/localization_loss = 0.036040884, Loss/RPNLoss/objectness_loss = 0.07321267, Loss/total_loss = 0.33006826, global_step = 1152, learning_rate = 0.0002, loss = 0.33006826\nI0617 10:40:27.309278 139802647791488 estimator.py:2049] Saving dict for global step 1152: DetectionBoxes_Precision/mAP = 0.33436817, DetectionBoxes_Precision/mAP (large) = 0.007504563, DetectionBoxes_Precision/mAP (medium) = 0.23078635, DetectionBoxes_Precision/mAP (small) = 0.35336673, DetectionBoxes_Precision/[email protected] = 0.69455814, DetectionBoxes_Precision/[email protected] = 0.26429784, DetectionBoxes_Recall/AR@1 = 0.2652297, DetectionBoxes_Recall/AR@10 = 0.48146126, DetectionBoxes_Recall/AR@100 = 0.51969236, DetectionBoxes_Recall/AR@100 (large) = 0.48666668, DetectionBoxes_Recall/AR@100 (medium) = 0.48786038, DetectionBoxes_Recall/AR@100 (small) = 0.5246954, Loss/BoxClassifierLoss/classification_loss = 0.12105487, Loss/BoxClassifierLoss/localization_loss = 0.09975987, Loss/RPNLoss/localization_loss = 0.036040884, Loss/RPNLoss/objectness_loss = 0.07321267, Loss/total_loss = 0.33006826, global_step = 1152, learning_rate = 0.0002, loss = 0.33006826\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1152: training/model.ckpt-1152\nI0617 10:40:27.310510 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1152: training/model.ckpt-1152\nINFO:tensorflow:global_step/sec: 0.16367\nI0617 10:41:59.167104 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.16367\nINFO:tensorflow:loss = 0.6338854, step = 1200 (610.987 sec)\nI0617 10:41:59.168398 139802647791488 basic_session_run_hooks.py:260] loss = 0.6338854, step = 1200 (610.987 sec)\nINFO:tensorflow:Saving checkpoints for 1247 into training/model.ckpt.\nI0617 10:43:24.662836 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1247 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25ee586390>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 10:43:27.070459 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25ee586390>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348400> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:43:27.297823 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348400> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:43:28.041752 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:43:30.347378 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:43:30.366352 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:43:30.366872 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:43:31.703043 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:43:31.730445 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:43:33.867759 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:43:33Z\nI0617 10:43:33.890909 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T10:43:33Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:43:34.537636 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:43:34.538569: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:43:34.539070: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 10:43:34.539192: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:43:34.539253: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:43:34.539321: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:43:34.539381: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:43:34.539432: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:43:34.539489: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:43:34.539545: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:43:34.539742: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:43:34.540178: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:43:34.540504: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:43:34.540563: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:43:34.540607: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:43:34.540630: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:43:34.540829: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:43:34.541312: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:43:34.541679: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1247\nI0617 10:43:34.543137 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1247\nINFO:tensorflow:Running local_init_op.\nI0617 10:43:35.624864 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:43:35.780272 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 10:50:01.726865 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:50:01.737593 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 10:50:02.220151 139799327557376 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.78s).\nAccumulating evaluation results...\nDONE (t=2.83s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.323\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.679\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.257\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.343\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.223\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.011\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.259\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.473\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.511\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.517\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.472\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.560\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:50:27\nI0617 10:50:27.688014 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-10:50:27\nINFO:tensorflow:Saving dict for global step 1247: DetectionBoxes_Precision/mAP = 0.32334355, DetectionBoxes_Precision/mAP (large) = 0.011302313, DetectionBoxes_Precision/mAP (medium) = 0.22251032, DetectionBoxes_Precision/mAP (small) = 0.34312773, DetectionBoxes_Precision/[email protected] = 0.6785598, DetectionBoxes_Precision/[email protected] = 0.25694403, DetectionBoxes_Recall/AR@1 = 0.25885448, DetectionBoxes_Recall/AR@10 = 0.4730419, DetectionBoxes_Recall/AR@100 = 0.51074684, DetectionBoxes_Recall/AR@100 (large) = 0.56, DetectionBoxes_Recall/AR@100 (medium) = 0.4717754, DetectionBoxes_Recall/AR@100 (small) = 0.51658857, Loss/BoxClassifierLoss/classification_loss = 0.13070855, Loss/BoxClassifierLoss/localization_loss = 0.10277465, Loss/RPNLoss/localization_loss = 0.036123764, Loss/RPNLoss/objectness_loss = 0.07319018, Loss/total_loss = 0.3427973, global_step = 1247, learning_rate = 0.0002, loss = 0.3427973\nI0617 10:50:27.688360 139802647791488 estimator.py:2049] Saving dict for global step 1247: DetectionBoxes_Precision/mAP = 0.32334355, DetectionBoxes_Precision/mAP (large) = 0.011302313, DetectionBoxes_Precision/mAP (medium) = 0.22251032, DetectionBoxes_Precision/mAP (small) = 0.34312773, DetectionBoxes_Precision/[email protected] = 0.6785598, DetectionBoxes_Precision/[email protected] = 0.25694403, DetectionBoxes_Recall/AR@1 = 0.25885448, DetectionBoxes_Recall/AR@10 = 0.4730419, DetectionBoxes_Recall/AR@100 = 0.51074684, DetectionBoxes_Recall/AR@100 (large) = 0.56, DetectionBoxes_Recall/AR@100 (medium) = 0.4717754, DetectionBoxes_Recall/AR@100 (small) = 0.51658857, Loss/BoxClassifierLoss/classification_loss = 0.13070855, Loss/BoxClassifierLoss/localization_loss = 0.10277465, Loss/RPNLoss/localization_loss = 0.036123764, Loss/RPNLoss/objectness_loss = 0.07319018, Loss/total_loss = 0.3427973, global_step = 1247, learning_rate = 0.0002, loss = 0.3427973\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1247: training/model.ckpt-1247\nI0617 10:50:27.689565 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1247: training/model.ckpt-1247\nINFO:tensorflow:global_step/sec: 0.163635\nI0617 10:52:10.284658 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163635\nINFO:tensorflow:loss = 0.49522212, step = 1300 (611.118 sec)\nI0617 10:52:10.285912 139802647791488 basic_session_run_hooks.py:260] loss = 0.49522212, step = 1300 (611.118 sec)\nINFO:tensorflow:Saving checkpoints for 1341 into training/model.ckpt.\nI0617 10:53:25.855052 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1341 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2588a62240>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 10:53:28.265204 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2588a62240>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2562bf5378> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:53:28.501914 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2562bf5378> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:53:29.191868 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:53:31.137695 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:53:31.155519 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:53:31.155899 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:53:32.788174 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:53:32.808132 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:53:34.879244 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:53:34Z\nI0617 10:53:34.900312 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T10:53:34Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:53:35.499802 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:53:35.500595: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:53:35.500999: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 10:53:35.501103: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:53:35.501171: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:53:35.501225: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:53:35.501278: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:53:35.501324: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:53:35.501371: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:53:35.501425: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:53:35.501596: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:53:35.501992: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:53:35.502292: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:53:35.502344: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:53:35.502366: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:53:35.502382: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:53:35.502547: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:53:35.502993: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:53:35.503293: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1341\nI0617 10:53:35.504518 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1341\nINFO:tensorflow:Running local_init_op.\nI0617 10:53:36.668182 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:53:36.822046 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 11:00:02.221396 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:00:02.229446 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.46s)\nI0617 11:00:02.689752 139799327557376 coco_tools.py:138] DONE (t=0.46s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.81s).\nAccumulating evaluation results...\nDONE (t=2.86s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.310\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.666\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.232\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.331\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.212\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.009\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.251\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.463\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.507\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.513\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.468\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.567\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:00:28\nI0617 11:00:28.209038 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-11:00:28\nINFO:tensorflow:Saving dict for global step 1341: DetectionBoxes_Precision/mAP = 0.31007373, DetectionBoxes_Precision/mAP (large) = 0.009439064, DetectionBoxes_Precision/mAP (medium) = 0.21204315, DetectionBoxes_Precision/mAP (small) = 0.3306571, DetectionBoxes_Precision/[email protected] = 0.6659675, DetectionBoxes_Precision/[email protected] = 0.23215717, DetectionBoxes_Recall/AR@1 = 0.25134587, DetectionBoxes_Recall/AR@10 = 0.46312487, DetectionBoxes_Recall/AR@100 = 0.50712407, DetectionBoxes_Recall/AR@100 (large) = 0.56666666, DetectionBoxes_Recall/AR@100 (medium) = 0.46843702, DetectionBoxes_Recall/AR@100 (small) = 0.5128866, Loss/BoxClassifierLoss/classification_loss = 0.1304511, Loss/BoxClassifierLoss/localization_loss = 0.10643686, Loss/RPNLoss/localization_loss = 0.03633958, Loss/RPNLoss/objectness_loss = 0.073248915, Loss/total_loss = 0.34647638, global_step = 1341, learning_rate = 0.0002, loss = 0.34647638\nI0617 11:00:28.209381 139802647791488 estimator.py:2049] Saving dict for global step 1341: DetectionBoxes_Precision/mAP = 0.31007373, DetectionBoxes_Precision/mAP (large) = 0.009439064, DetectionBoxes_Precision/mAP (medium) = 0.21204315, DetectionBoxes_Precision/mAP (small) = 0.3306571, DetectionBoxes_Precision/[email protected] = 0.6659675, DetectionBoxes_Precision/[email protected] = 0.23215717, DetectionBoxes_Recall/AR@1 = 0.25134587, DetectionBoxes_Recall/AR@10 = 0.46312487, DetectionBoxes_Recall/AR@100 = 0.50712407, DetectionBoxes_Recall/AR@100 (large) = 0.56666666, DetectionBoxes_Recall/AR@100 (medium) = 0.46843702, DetectionBoxes_Recall/AR@100 (small) = 0.5128866, Loss/BoxClassifierLoss/classification_loss = 0.1304511, Loss/BoxClassifierLoss/localization_loss = 0.10643686, Loss/RPNLoss/localization_loss = 0.03633958, Loss/RPNLoss/objectness_loss = 0.073248915, Loss/total_loss = 0.34647638, global_step = 1341, learning_rate = 0.0002, loss = 0.34647638\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1341: training/model.ckpt-1341\nI0617 11:00:28.210435 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1341: training/model.ckpt-1341\nINFO:tensorflow:global_step/sec: 0.16371\nI0617 11:02:21.120748 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.16371\nINFO:tensorflow:loss = 0.3713319, step = 1400 (610.836 sec)\nI0617 11:02:21.122160 139802647791488 basic_session_run_hooks.py:260] loss = 0.3713319, step = 1400 (610.836 sec)\nINFO:tensorflow:Saving checkpoints for 1436 into training/model.ckpt.\nI0617 11:03:26.976682 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1436 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f257a514400>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 11:03:29.377398 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f257a514400>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256dce5158> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:03:29.604662 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256dce5158> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:03:30.312442 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:03:32.245480 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:03:32.263611 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:03:32.264085 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:03:33.573124 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:03:33.593666 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:03:35.642174 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:03:35Z\nI0617 11:03:35.663186 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T11:03:35Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:03:36.243114 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:03:36.244035: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:03:36.244395: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 11:03:36.244501: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:03:36.244545: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:03:36.244616: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:03:36.244669: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:03:36.244727: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:03:36.244772: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:03:36.244832: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:03:36.245057: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:03:36.245542: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:03:36.245960: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:03:36.246011: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:03:36.246033: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:03:36.246047: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:03:36.246256: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:03:36.246679: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:03:36.247041: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1436\nI0617 11:03:36.248242 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1436\nINFO:tensorflow:Running local_init_op.\nI0617 11:03:37.287271 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:03:37.437439 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 11:10:05.061337 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:10:05.071551 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.46s)\nI0617 11:10:05.528001 139799327557376 coco_tools.py:138] DONE (t=0.46s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.70s).\nAccumulating evaluation results...\nDONE (t=2.84s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.336\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.694\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.263\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.354\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.234\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.008\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.267\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.483\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.520\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.524\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.497\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.547\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:10:30\nI0617 11:10:30.936739 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-11:10:30\nINFO:tensorflow:Saving dict for global step 1436: DetectionBoxes_Precision/mAP = 0.33598092, DetectionBoxes_Precision/mAP (large) = 0.007911225, DetectionBoxes_Precision/mAP (medium) = 0.23391153, DetectionBoxes_Precision/mAP (small) = 0.35420635, DetectionBoxes_Precision/[email protected] = 0.6936579, DetectionBoxes_Precision/[email protected] = 0.2632859, DetectionBoxes_Recall/AR@1 = 0.2667274, DetectionBoxes_Recall/AR@10 = 0.48269582, DetectionBoxes_Recall/AR@100 = 0.5203805, DetectionBoxes_Recall/AR@100 (large) = 0.5466667, DetectionBoxes_Recall/AR@100 (medium) = 0.49711683, DetectionBoxes_Recall/AR@100 (small) = 0.52385193, Loss/BoxClassifierLoss/classification_loss = 0.1339599, Loss/BoxClassifierLoss/localization_loss = 0.10113817, Loss/RPNLoss/localization_loss = 0.03571015, Loss/RPNLoss/objectness_loss = 0.071933195, Loss/total_loss = 0.3427412, global_step = 1436, learning_rate = 0.0002, loss = 0.3427412\nI0617 11:10:30.937128 139802647791488 estimator.py:2049] Saving dict for global step 1436: DetectionBoxes_Precision/mAP = 0.33598092, DetectionBoxes_Precision/mAP (large) = 0.007911225, DetectionBoxes_Precision/mAP (medium) = 0.23391153, DetectionBoxes_Precision/mAP (small) = 0.35420635, DetectionBoxes_Precision/[email protected] = 0.6936579, DetectionBoxes_Precision/[email protected] = 0.2632859, DetectionBoxes_Recall/AR@1 = 0.2667274, DetectionBoxes_Recall/AR@10 = 0.48269582, DetectionBoxes_Recall/AR@100 = 0.5203805, DetectionBoxes_Recall/AR@100 (large) = 0.5466667, DetectionBoxes_Recall/AR@100 (medium) = 0.49711683, DetectionBoxes_Recall/AR@100 (small) = 0.52385193, Loss/BoxClassifierLoss/classification_loss = 0.1339599, Loss/BoxClassifierLoss/localization_loss = 0.10113817, Loss/RPNLoss/localization_loss = 0.03571015, Loss/RPNLoss/objectness_loss = 0.071933195, Loss/total_loss = 0.3427412, global_step = 1436, learning_rate = 0.0002, loss = 0.3427412\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1436: training/model.ckpt-1436\nI0617 11:10:30.938359 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1436: training/model.ckpt-1436\nINFO:tensorflow:global_step/sec: 0.163282\nI0617 11:12:33.559173 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163282\nINFO:tensorflow:loss = 0.66106766, step = 1500 (612.438 sec)\nI0617 11:12:33.560411 139802647791488 basic_session_run_hooks.py:260] loss = 0.66106766, step = 1500 (612.438 sec)\nINFO:tensorflow:Saving checkpoints for 1530 into training/model.ckpt.\nI0617 11:13:27.538418 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1530 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25733142e8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 11:13:29.912697 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25733142e8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256e4f8510> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:13:30.139609 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256e4f8510> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:13:30.843523 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:13:32.808456 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:13:32.825814 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:13:32.826176 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:13:34.072734 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:13:34.092900 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:13:36.319700 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:13:36Z\nI0617 11:13:36.346672 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T11:13:36Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:13:36.932775 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:13:36.933590: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:13:36.933929: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 11:13:36.934028: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:13:36.934070: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:13:36.934129: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:13:36.934185: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:13:36.934224: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:13:36.934262: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:13:36.934300: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:13:36.934435: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:13:36.934850: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:13:36.935154: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:13:36.935204: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:13:36.935223: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:13:36.935237: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:13:36.935390: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:13:36.935776: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:13:36.936206: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1530\nI0617 11:13:36.937496 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1530\nINFO:tensorflow:Running local_init_op.\nI0617 11:13:37.998127 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:13:38.140842 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 11:20:03.330425 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:20:03.339948 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 11:20:03.820557 139799327557376 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.48s).\nAccumulating evaluation results...\nDONE (t=2.79s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.326\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.679\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.258\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.345\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.224\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.009\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.262\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.473\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.512\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.518\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.472\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.527\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:20:28\nI0617 11:20:28.949679 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-11:20:28\nINFO:tensorflow:Saving dict for global step 1530: DetectionBoxes_Precision/mAP = 0.32594216, DetectionBoxes_Precision/mAP (large) = 0.008652094, DetectionBoxes_Precision/mAP (medium) = 0.22448805, DetectionBoxes_Precision/mAP (small) = 0.3451636, DetectionBoxes_Precision/[email protected] = 0.679328, DetectionBoxes_Precision/[email protected] = 0.25757343, DetectionBoxes_Recall/AR@1 = 0.26197127, DetectionBoxes_Recall/AR@10 = 0.4731431, DetectionBoxes_Recall/AR@100 = 0.5120421, DetectionBoxes_Recall/AR@100 (large) = 0.52666664, DetectionBoxes_Recall/AR@100 (medium) = 0.4723824, DetectionBoxes_Recall/AR@100 (small) = 0.5180881, Loss/BoxClassifierLoss/classification_loss = 0.12331954, Loss/BoxClassifierLoss/localization_loss = 0.1013043, Loss/RPNLoss/localization_loss = 0.036484104, Loss/RPNLoss/objectness_loss = 0.07275483, Loss/total_loss = 0.33386263, global_step = 1530, learning_rate = 0.0002, loss = 0.33386263\nI0617 11:20:28.950029 139802647791488 estimator.py:2049] Saving dict for global step 1530: DetectionBoxes_Precision/mAP = 0.32594216, DetectionBoxes_Precision/mAP (large) = 0.008652094, DetectionBoxes_Precision/mAP (medium) = 0.22448805, DetectionBoxes_Precision/mAP (small) = 0.3451636, DetectionBoxes_Precision/[email protected] = 0.679328, DetectionBoxes_Precision/[email protected] = 0.25757343, DetectionBoxes_Recall/AR@1 = 0.26197127, DetectionBoxes_Recall/AR@10 = 0.4731431, DetectionBoxes_Recall/AR@100 = 0.5120421, DetectionBoxes_Recall/AR@100 (large) = 0.52666664, DetectionBoxes_Recall/AR@100 (medium) = 0.4723824, DetectionBoxes_Recall/AR@100 (small) = 0.5180881, Loss/BoxClassifierLoss/classification_loss = 0.12331954, Loss/BoxClassifierLoss/localization_loss = 0.1013043, Loss/RPNLoss/localization_loss = 0.036484104, Loss/RPNLoss/objectness_loss = 0.07275483, Loss/total_loss = 0.33386263, global_step = 1530, learning_rate = 0.0002, loss = 0.33386263\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1530: training/model.ckpt-1530\nI0617 11:20:28.951192 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1530: training/model.ckpt-1530\nINFO:tensorflow:global_step/sec: 0.1642\nI0617 11:22:42.570988 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.1642\nINFO:tensorflow:loss = 0.573259, step = 1600 (609.012 sec)\nI0617 11:22:42.572528 139802647791488 basic_session_run_hooks.py:260] loss = 0.573259, step = 1600 (609.012 sec)\nINFO:tensorflow:Saving checkpoints for 1626 into training/model.ckpt.\nI0617 11:23:29.043543 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1626 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e018aef0>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 11:23:31.477963 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e018aef0>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348c80> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:23:31.700461 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348c80> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:23:32.730109 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:23:34.617297 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:23:34.634447 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:23:34.634838 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:23:35.890237 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:23:35.912561 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:23:38.058312 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:23:38Z\nI0617 11:23:38.079915 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T11:23:38Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:23:38.706674 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:23:38.707443: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:23:38.707816: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 11:23:38.707915: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:23:38.707958: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:23:38.708001: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:23:38.708041: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:23:38.708079: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:23:38.708171: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:23:38.708226: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:23:38.708359: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:23:38.708853: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:23:38.709201: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:23:38.709303: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:23:38.709324: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:23:38.709337: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:23:38.709480: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:23:38.709861: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:23:38.710141: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1626\nI0617 11:23:38.711393 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1626\nINFO:tensorflow:Running local_init_op.\nI0617 11:23:39.765871 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:23:39.915355 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 11:30:04.641541 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:30:04.652727 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 11:30:05.128349 139799327557376 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.10s).\nAccumulating evaluation results...\nDONE (t=2.90s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.319\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.676\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.241\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.340\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.217\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.012\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.257\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.468\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.510\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.516\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.472\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.533\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:30:30\nI0617 11:30:30.971927 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-11:30:30\nINFO:tensorflow:Saving dict for global step 1626: DetectionBoxes_Precision/mAP = 0.31915236, DetectionBoxes_Precision/mAP (large) = 0.0115754185, DetectionBoxes_Precision/mAP (medium) = 0.21687205, DetectionBoxes_Precision/mAP (small) = 0.33972692, DetectionBoxes_Precision/[email protected] = 0.6764363, DetectionBoxes_Precision/[email protected] = 0.24076445, DetectionBoxes_Recall/AR@1 = 0.25662822, DetectionBoxes_Recall/AR@10 = 0.46802267, DetectionBoxes_Recall/AR@100 = 0.50989676, DetectionBoxes_Recall/AR@100 (large) = 0.53333336, DetectionBoxes_Recall/AR@100 (medium) = 0.47162366, DetectionBoxes_Recall/AR@100 (small) = 0.5157451, Loss/BoxClassifierLoss/classification_loss = 0.1259491, Loss/BoxClassifierLoss/localization_loss = 0.104594074, Loss/RPNLoss/localization_loss = 0.036639992, Loss/RPNLoss/objectness_loss = 0.07141476, Loss/total_loss = 0.33859846, global_step = 1626, learning_rate = 0.0002, loss = 0.33859846\nI0617 11:30:30.972256 139802647791488 estimator.py:2049] Saving dict for global step 1626: DetectionBoxes_Precision/mAP = 0.31915236, DetectionBoxes_Precision/mAP (large) = 0.0115754185, DetectionBoxes_Precision/mAP (medium) = 0.21687205, DetectionBoxes_Precision/mAP (small) = 0.33972692, DetectionBoxes_Precision/[email protected] = 0.6764363, DetectionBoxes_Precision/[email protected] = 0.24076445, DetectionBoxes_Recall/AR@1 = 0.25662822, DetectionBoxes_Recall/AR@10 = 0.46802267, DetectionBoxes_Recall/AR@100 = 0.50989676, DetectionBoxes_Recall/AR@100 (large) = 0.53333336, DetectionBoxes_Recall/AR@100 (medium) = 0.47162366, DetectionBoxes_Recall/AR@100 (small) = 0.5157451, Loss/BoxClassifierLoss/classification_loss = 0.1259491, Loss/BoxClassifierLoss/localization_loss = 0.104594074, Loss/RPNLoss/localization_loss = 0.036639992, Loss/RPNLoss/objectness_loss = 0.07141476, Loss/total_loss = 0.33859846, global_step = 1626, learning_rate = 0.0002, loss = 0.33859846\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1626: training/model.ckpt-1626\nI0617 11:30:30.973409 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1626: training/model.ckpt-1626\nINFO:tensorflow:global_step/sec: 0.164143\nI0617 11:32:51.794468 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.164143\nINFO:tensorflow:loss = 0.6064381, step = 1700 (609.223 sec)\nI0617 11:32:51.795871 139802647791488 basic_session_run_hooks.py:260] loss = 0.6064381, step = 1700 (609.223 sec)\nINFO:tensorflow:Saving checkpoints for 1721 into training/model.ckpt.\nI0617 11:33:29.208868 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1721 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e028d940>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 11:33:31.745477 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e028d940>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2588bd0048> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:33:31.979923 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2588bd0048> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:33:33.031380 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:33:34.901983 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:33:34.919707 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:33:34.920094 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:33:36.192367 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:33:36.212752 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:33:38.362025 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:33:38Z\nI0617 11:33:38.383534 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T11:33:38Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:33:38.968037 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:33:38.968766: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:33:38.969116: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 11:33:38.969207: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:33:38.969258: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:33:38.969303: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:33:38.969351: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:33:38.969393: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:33:38.969432: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:33:38.969473: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:33:38.969638: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:33:38.970068: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:33:38.970362: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:33:38.970412: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:33:38.970447: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:33:38.970462: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:33:38.970635: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:33:38.971007: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:33:38.971303: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1721\nI0617 11:33:38.972838 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1721\nINFO:tensorflow:Running local_init_op.\nI0617 11:33:40.123536 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:33:40.293151 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 11:40:06.305908 139799335950080 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:40:06.315646 139799335950080 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 11:40:06.791612 139799335950080 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.51s).\nAccumulating evaluation results...\nDONE (t=2.95s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.329\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.684\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.263\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.349\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.232\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.013\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.262\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.477\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.518\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.523\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.489\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.567\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:40:33\nI0617 11:40:33.126482 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-11:40:33\nINFO:tensorflow:Saving dict for global step 1721: DetectionBoxes_Precision/mAP = 0.32893255, DetectionBoxes_Precision/mAP (large) = 0.012792524, DetectionBoxes_Precision/mAP (medium) = 0.23169906, DetectionBoxes_Precision/mAP (small) = 0.34901085, DetectionBoxes_Precision/[email protected] = 0.6839061, DetectionBoxes_Precision/[email protected] = 0.26312852, DetectionBoxes_Recall/AR@1 = 0.2622546, DetectionBoxes_Recall/AR@10 = 0.47682655, DetectionBoxes_Recall/AR@100 = 0.51823515, DetectionBoxes_Recall/AR@100 (large) = 0.56666666, DetectionBoxes_Recall/AR@100 (medium) = 0.4892261, DetectionBoxes_Recall/AR@100 (small) = 0.52253985, Loss/BoxClassifierLoss/classification_loss = 0.12826909, Loss/BoxClassifierLoss/localization_loss = 0.10322927, Loss/RPNLoss/localization_loss = 0.036389824, Loss/RPNLoss/objectness_loss = 0.070885636, Loss/total_loss = 0.33877423, global_step = 1721, learning_rate = 0.0002, loss = 0.33877423\nI0617 11:40:33.126910 139802647791488 estimator.py:2049] Saving dict for global step 1721: DetectionBoxes_Precision/mAP = 0.32893255, DetectionBoxes_Precision/mAP (large) = 0.012792524, DetectionBoxes_Precision/mAP (medium) = 0.23169906, DetectionBoxes_Precision/mAP (small) = 0.34901085, DetectionBoxes_Precision/[email protected] = 0.6839061, DetectionBoxes_Precision/[email protected] = 0.26312852, DetectionBoxes_Recall/AR@1 = 0.2622546, DetectionBoxes_Recall/AR@10 = 0.47682655, DetectionBoxes_Recall/AR@100 = 0.51823515, DetectionBoxes_Recall/AR@100 (large) = 0.56666666, DetectionBoxes_Recall/AR@100 (medium) = 0.4892261, DetectionBoxes_Recall/AR@100 (small) = 0.52253985, Loss/BoxClassifierLoss/classification_loss = 0.12826909, Loss/BoxClassifierLoss/localization_loss = 0.10322927, Loss/RPNLoss/localization_loss = 0.036389824, Loss/RPNLoss/objectness_loss = 0.070885636, Loss/total_loss = 0.33877423, global_step = 1721, learning_rate = 0.0002, loss = 0.33877423\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1721: training/model.ckpt-1721\nI0617 11:40:33.128043 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1721: training/model.ckpt-1721\nINFO:tensorflow:global_step/sec: 0.163447\nI0617 11:43:03.613782 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163447\nINFO:tensorflow:loss = 0.5612267, step = 1800 (611.820 sec)\nI0617 11:43:03.616018 139802647791488 basic_session_run_hooks.py:260] loss = 0.5612267, step = 1800 (611.820 sec)\nINFO:tensorflow:Saving checkpoints for 1815 into training/model.ckpt.\nI0617 11:43:29.523809 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1815 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f258a5bb9e8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 11:43:31.882415 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f258a5bb9e8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25840aa950> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:43:32.118296 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25840aa950> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:43:32.848012 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:43:35.120463 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:43:35.138540 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:43:35.139060 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:43:36.434070 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:43:36.455765 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:43:38.568095 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:43:38Z\nI0617 11:43:38.589097 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T11:43:38Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:43:39.192921 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:43:39.193815: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:43:39.194209: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 11:43:39.194328: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:43:39.194374: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:43:39.194419: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:43:39.194462: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:43:39.194514: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:43:39.194558: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:43:39.194618: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:43:39.194763: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:43:39.195150: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:43:39.195490: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:43:39.195560: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:43:39.195598: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:43:39.195620: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:43:39.195784: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:43:39.196164: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:43:39.196487: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1815\nI0617 11:43:39.197803 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1815\nINFO:tensorflow:Running local_init_op.\nI0617 11:43:40.310671 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:43:40.485549 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 11:50:06.884081 139799335950080 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:50:06.891904 139799335950080 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 11:50:07.371784 139799335950080 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.49s).\nAccumulating evaluation results...\nDONE (t=2.95s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.326\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.680\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.261\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.345\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.231\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.009\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.262\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.475\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.518\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.523\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.482\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.547\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:50:33\nI0617 11:50:33.695068 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-11:50:33\nINFO:tensorflow:Saving dict for global step 1815: DetectionBoxes_Precision/mAP = 0.32560992, DetectionBoxes_Precision/mAP (large) = 0.008914655, DetectionBoxes_Precision/mAP (medium) = 0.23107545, DetectionBoxes_Precision/mAP (small) = 0.34543017, DetectionBoxes_Precision/[email protected] = 0.6798527, DetectionBoxes_Precision/[email protected] = 0.2608959, DetectionBoxes_Recall/AR@1 = 0.26176888, DetectionBoxes_Recall/AR@10 = 0.47549078, DetectionBoxes_Recall/AR@100 = 0.5179923, DetectionBoxes_Recall/AR@100 (large) = 0.5466667, DetectionBoxes_Recall/AR@100 (medium) = 0.48163885, DetectionBoxes_Recall/AR@100 (small) = 0.523477, Loss/BoxClassifierLoss/classification_loss = 0.13313939, Loss/BoxClassifierLoss/localization_loss = 0.10318348, Loss/RPNLoss/localization_loss = 0.03655962, Loss/RPNLoss/objectness_loss = 0.07134176, Loss/total_loss = 0.34422433, global_step = 1815, learning_rate = 0.0002, loss = 0.34422433\nI0617 11:50:33.695514 139802647791488 estimator.py:2049] Saving dict for global step 1815: DetectionBoxes_Precision/mAP = 0.32560992, DetectionBoxes_Precision/mAP (large) = 0.008914655, DetectionBoxes_Precision/mAP (medium) = 0.23107545, DetectionBoxes_Precision/mAP (small) = 0.34543017, DetectionBoxes_Precision/[email protected] = 0.6798527, DetectionBoxes_Precision/[email protected] = 0.2608959, DetectionBoxes_Recall/AR@1 = 0.26176888, DetectionBoxes_Recall/AR@10 = 0.47549078, DetectionBoxes_Recall/AR@100 = 0.5179923, DetectionBoxes_Recall/AR@100 (large) = 0.5466667, DetectionBoxes_Recall/AR@100 (medium) = 0.48163885, DetectionBoxes_Recall/AR@100 (small) = 0.523477, Loss/BoxClassifierLoss/classification_loss = 0.13313939, Loss/BoxClassifierLoss/localization_loss = 0.10318348, Loss/RPNLoss/localization_loss = 0.03655962, Loss/RPNLoss/objectness_loss = 0.07134176, Loss/total_loss = 0.34422433, global_step = 1815, learning_rate = 0.0002, loss = 0.34422433\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1815: training/model.ckpt-1815\nI0617 11:50:33.697352 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1815: training/model.ckpt-1815\nINFO:tensorflow:global_step/sec: 0.162755\nI0617 11:53:18.035232 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.162755\nINFO:tensorflow:loss = 0.46053752, step = 1900 (614.421 sec)\nI0617 11:53:18.036714 139802647791488 basic_session_run_hooks.py:260] loss = 0.46053752, step = 1900 (614.421 sec)\nINFO:tensorflow:Saving checkpoints for 1908 into training/model.ckpt.\nI0617 11:53:31.356000 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1908 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25770d06d8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 11:53:33.768193 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25770d06d8>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256d97b510> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:53:34.009176 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f256d97b510> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:53:34.717794 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:53:36.690812 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:53:36.722340 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:53:36.722964 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:53:38.081032 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:53:38.104014 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:53:40.597276 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:53:40Z\nI0617 11:53:40.618346 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T11:53:40Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:53:41.216692 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:53:41.217688: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:53:41.218065: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 11:53:41.218158: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:53:41.218206: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:53:41.218252: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:53:41.218309: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:53:41.218351: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:53:41.218394: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:53:41.218436: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:53:41.218571: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:53:41.219026: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:53:41.219327: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:53:41.219379: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:53:41.219399: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:53:41.219416: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:53:41.219622: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:53:41.220031: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:53:41.220337: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1908\nI0617 11:53:41.221776 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1908\nINFO:tensorflow:Running local_init_op.\nI0617 11:53:42.457285 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:53:42.630955 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 12:00:12.627047 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 12:00:12.635830 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.49s)\nI0617 12:00:13.123806 139799327557376 coco_tools.py:138] DONE (t=0.49s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.42s).\nAccumulating evaluation results...\nDONE (t=2.97s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.328\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.679\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.264\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.348\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.229\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.006\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.262\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.476\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.520\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.525\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.482\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.560\nINFO:tensorflow:Finished evaluation at 2020-06-17-12:00:39\nI0617 12:00:39.357226 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-12:00:39\nINFO:tensorflow:Saving dict for global step 1908: DetectionBoxes_Precision/mAP = 0.32772863, DetectionBoxes_Precision/mAP (large) = 0.0063580032, DetectionBoxes_Precision/mAP (medium) = 0.22921737, DetectionBoxes_Precision/mAP (small) = 0.34828082, DetectionBoxes_Precision/[email protected] = 0.67906135, DetectionBoxes_Precision/[email protected] = 0.26403633, DetectionBoxes_Recall/AR@1 = 0.26180935, DetectionBoxes_Recall/AR@10 = 0.4759563, DetectionBoxes_Recall/AR@100 = 0.5197733, DetectionBoxes_Recall/AR@100 (large) = 0.56, DetectionBoxes_Recall/AR@100 (medium) = 0.48209408, DetectionBoxes_Recall/AR@100 (small) = 0.52542174, Loss/BoxClassifierLoss/classification_loss = 0.13032408, Loss/BoxClassifierLoss/localization_loss = 0.10284437, Loss/RPNLoss/localization_loss = 0.036467995, Loss/RPNLoss/objectness_loss = 0.070652865, Loss/total_loss = 0.3402895, global_step = 1908, learning_rate = 0.0002, loss = 0.3402895\nI0617 12:00:39.357555 139802647791488 estimator.py:2049] Saving dict for global step 1908: DetectionBoxes_Precision/mAP = 0.32772863, DetectionBoxes_Precision/mAP (large) = 0.0063580032, DetectionBoxes_Precision/mAP (medium) = 0.22921737, DetectionBoxes_Precision/mAP (small) = 0.34828082, DetectionBoxes_Precision/[email protected] = 0.67906135, DetectionBoxes_Precision/[email protected] = 0.26403633, DetectionBoxes_Recall/AR@1 = 0.26180935, DetectionBoxes_Recall/AR@10 = 0.4759563, DetectionBoxes_Recall/AR@100 = 0.5197733, DetectionBoxes_Recall/AR@100 (large) = 0.56, DetectionBoxes_Recall/AR@100 (medium) = 0.48209408, DetectionBoxes_Recall/AR@100 (small) = 0.52542174, Loss/BoxClassifierLoss/classification_loss = 0.13032408, Loss/BoxClassifierLoss/localization_loss = 0.10284437, Loss/RPNLoss/localization_loss = 0.036467995, Loss/RPNLoss/objectness_loss = 0.070652865, Loss/total_loss = 0.3402895, global_step = 1908, learning_rate = 0.0002, loss = 0.3402895\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1908: training/model.ckpt-1908\nI0617 12:00:39.358718 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1908: training/model.ckpt-1908\nINFO:tensorflow:Saving checkpoints for 1998 into training/model.ckpt.\nI0617 12:03:31.361756 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 1998 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25841af668>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 12:03:33.808801 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25841af668>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2588a64488> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 12:03:34.061697 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2588a64488> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 12:03:34.802305 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:03:36.725186 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:03:36.743419 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 12:03:36.743834 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:03:38.037283 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:03:38.059015 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 12:03:40.212065 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T12:03:40Z\nI0617 12:03:40.233618 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T12:03:40Z\nINFO:tensorflow:Graph was finalized.\nI0617 12:03:40.852136 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 12:03:40.853112: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:03:40.853531: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 12:03:40.853678: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 12:03:40.853727: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 12:03:40.853775: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 12:03:40.853839: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 12:03:40.853883: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 12:03:40.853921: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 12:03:40.853964: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 12:03:40.854102: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:03:40.854515: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:03:40.854845: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 12:03:40.854898: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 12:03:40.854921: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 12:03:40.854937: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 12:03:40.855091: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:03:40.855494: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:03:40.855831: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1998\nI0617 12:03:40.857125 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-1998\nINFO:tensorflow:Running local_init_op.\nI0617 12:03:41.980895 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 12:03:42.148290 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 12:10:11.755403 139799335950080 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 12:10:11.766660 139799335950080 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.47s)\nI0617 12:10:12.239591 139799335950080 coco_tools.py:138] DONE (t=0.47s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.34s).\nAccumulating evaluation results...\nDONE (t=2.93s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.326\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.680\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.255\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.346\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.224\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.010\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.261\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.473\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.517\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.523\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.479\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.560\nINFO:tensorflow:Finished evaluation at 2020-06-17-12:10:38\nI0617 12:10:38.436757 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-12:10:38\nINFO:tensorflow:Saving dict for global step 1998: DetectionBoxes_Precision/mAP = 0.32623446, DetectionBoxes_Precision/mAP (large) = 0.010327048, DetectionBoxes_Precision/mAP (medium) = 0.22393951, DetectionBoxes_Precision/mAP (small) = 0.3464543, DetectionBoxes_Precision/[email protected] = 0.67961353, DetectionBoxes_Precision/[email protected] = 0.2552359, DetectionBoxes_Recall/AR@1 = 0.26075694, DetectionBoxes_Recall/AR@10 = 0.47300142, DetectionBoxes_Recall/AR@100 = 0.5174256, DetectionBoxes_Recall/AR@100 (large) = 0.56, DetectionBoxes_Recall/AR@100 (medium) = 0.4792109, DetectionBoxes_Recall/AR@100 (small) = 0.52317244, Loss/BoxClassifierLoss/classification_loss = 0.12645853, Loss/BoxClassifierLoss/localization_loss = 0.105661936, Loss/RPNLoss/localization_loss = 0.03641581, Loss/RPNLoss/objectness_loss = 0.070797294, Loss/total_loss = 0.339334, global_step = 1998, learning_rate = 0.0002, loss = 0.339334\nI0617 12:10:38.437137 139802647791488 estimator.py:2049] Saving dict for global step 1998: DetectionBoxes_Precision/mAP = 0.32623446, DetectionBoxes_Precision/mAP (large) = 0.010327048, DetectionBoxes_Precision/mAP (medium) = 0.22393951, DetectionBoxes_Precision/mAP (small) = 0.3464543, DetectionBoxes_Precision/[email protected] = 0.67961353, DetectionBoxes_Precision/[email protected] = 0.2552359, DetectionBoxes_Recall/AR@1 = 0.26075694, DetectionBoxes_Recall/AR@10 = 0.47300142, DetectionBoxes_Recall/AR@100 = 0.5174256, DetectionBoxes_Recall/AR@100 (large) = 0.56, DetectionBoxes_Recall/AR@100 (medium) = 0.4792109, DetectionBoxes_Recall/AR@100 (small) = 0.52317244, Loss/BoxClassifierLoss/classification_loss = 0.12645853, Loss/BoxClassifierLoss/localization_loss = 0.105661936, Loss/RPNLoss/localization_loss = 0.03641581, Loss/RPNLoss/objectness_loss = 0.070797294, Loss/total_loss = 0.339334, global_step = 1998, learning_rate = 0.0002, loss = 0.339334\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1998: training/model.ckpt-1998\nI0617 12:10:38.438446 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1998: training/model.ckpt-1998\nINFO:tensorflow:global_step/sec: 0.0955844\nI0617 12:10:44.231301 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.0955844\nINFO:tensorflow:loss = 0.51109624, step = 2000 (1046.196 sec)\nI0617 12:10:44.232784 139802647791488 basic_session_run_hooks.py:260] loss = 0.51109624, step = 2000 (1046.196 sec)\nINFO:tensorflow:Saving checkpoints for 2090 into training/model.ckpt.\nI0617 12:13:32.967097 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 2090 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f258a5b24e0>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 12:13:35.448065 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f258a5b24e0>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f258ace7950> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 12:13:35.695603 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f258ace7950> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 12:13:36.388079 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:13:38.317874 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:13:38.334917 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 12:13:38.335299 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:13:39.635941 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:13:39.662235 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 12:13:41.835321 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T12:13:41Z\nI0617 12:13:41.857403 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T12:13:41Z\nINFO:tensorflow:Graph was finalized.\nI0617 12:13:42.466319 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 12:13:42.467208: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:13:42.467624: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 12:13:42.467743: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 12:13:42.467793: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 12:13:42.467853: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 12:13:42.467911: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 12:13:42.467955: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 12:13:42.467997: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 12:13:42.468057: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 12:13:42.468202: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:13:42.468620: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:13:42.468924: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 12:13:42.468980: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 12:13:42.469004: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 12:13:42.469019: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 12:13:42.469190: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:13:42.469606: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:13:42.469913: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-2090\nI0617 12:13:42.471122 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-2090\nINFO:tensorflow:Running local_init_op.\nI0617 12:13:43.629013 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 12:13:43.788613 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 12:20:15.063311 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 12:20:15.071277 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.49s)\nI0617 12:20:15.556897 139799327557376 coco_tools.py:138] DONE (t=0.49s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.43s).\nAccumulating evaluation results...\nDONE (t=3.62s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.332\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.687\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.266\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.353\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.226\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.008\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.265\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.479\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.521\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.527\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.481\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.540\nINFO:tensorflow:Finished evaluation at 2020-06-17-12:20:42\nI0617 12:20:42.483023 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-12:20:42\nINFO:tensorflow:Saving dict for global step 2090: DetectionBoxes_Precision/mAP = 0.33222565, DetectionBoxes_Precision/mAP (large) = 0.008122945, DetectionBoxes_Precision/mAP (medium) = 0.22649626, DetectionBoxes_Precision/mAP (small) = 0.35296994, DetectionBoxes_Precision/[email protected] = 0.6866763, DetectionBoxes_Precision/[email protected] = 0.2663323, DetectionBoxes_Recall/AR@1 = 0.2650678, DetectionBoxes_Recall/AR@10 = 0.4794576, DetectionBoxes_Recall/AR@100 = 0.52108884, DetectionBoxes_Recall/AR@100 (large) = 0.54, DetectionBoxes_Recall/AR@100 (medium) = 0.4807284, DetectionBoxes_Recall/AR@100 (small) = 0.5272493, Loss/BoxClassifierLoss/classification_loss = 0.12831649, Loss/BoxClassifierLoss/localization_loss = 0.10418997, Loss/RPNLoss/localization_loss = 0.03621192, Loss/RPNLoss/objectness_loss = 0.070403166, Loss/total_loss = 0.3391217, global_step = 2090, learning_rate = 0.0002, loss = 0.3391217\nI0617 12:20:42.483410 139802647791488 estimator.py:2049] Saving dict for global step 2090: DetectionBoxes_Precision/mAP = 0.33222565, DetectionBoxes_Precision/mAP (large) = 0.008122945, DetectionBoxes_Precision/mAP (medium) = 0.22649626, DetectionBoxes_Precision/mAP (small) = 0.35296994, DetectionBoxes_Precision/[email protected] = 0.6866763, DetectionBoxes_Precision/[email protected] = 0.2663323, DetectionBoxes_Recall/AR@1 = 0.2650678, DetectionBoxes_Recall/AR@10 = 0.4794576, DetectionBoxes_Recall/AR@100 = 0.52108884, DetectionBoxes_Recall/AR@100 (large) = 0.54, DetectionBoxes_Recall/AR@100 (medium) = 0.4807284, DetectionBoxes_Recall/AR@100 (small) = 0.5272493, Loss/BoxClassifierLoss/classification_loss = 0.12831649, Loss/BoxClassifierLoss/localization_loss = 0.10418997, Loss/RPNLoss/localization_loss = 0.03621192, Loss/RPNLoss/objectness_loss = 0.070403166, Loss/total_loss = 0.3391217, global_step = 2090, learning_rate = 0.0002, loss = 0.3391217\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 2090: training/model.ckpt-2090\nI0617 12:20:42.484653 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 2090: training/model.ckpt-2090\nINFO:tensorflow:global_step/sec: 0.161506\nI0617 12:21:03.402760 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.161506\nINFO:tensorflow:loss = 0.51855975, step = 2100 (619.171 sec)\nI0617 12:21:03.404134 139802647791488 basic_session_run_hooks.py:260] loss = 0.51855975, step = 2100 (619.171 sec)\nINFO:tensorflow:Saving checkpoints for 2181 into training/model.ckpt.\nI0617 12:23:34.769557 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 2181 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e02aab38>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 12:23:37.204606 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25e02aab38>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e6194d08> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 12:23:37.438462 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e6194d08> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 12:23:38.195138 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:23:40.149394 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:23:40.167077 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 12:23:40.167452 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:23:41.444274 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:23:41.466727 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 12:23:43.595812 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T12:23:43Z\nI0617 12:23:43.616697 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T12:23:43Z\nINFO:tensorflow:Graph was finalized.\nI0617 12:23:44.223181 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 12:23:44.224225: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:23:44.224653: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 12:23:44.224782: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 12:23:44.224841: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 12:23:44.224893: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 12:23:44.224943: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 12:23:44.224997: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 12:23:44.225045: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 12:23:44.225096: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 12:23:44.225251: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:23:44.225708: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:23:44.226030: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 12:23:44.226101: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 12:23:44.226131: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 12:23:44.226154: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 12:23:44.226329: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:23:44.226776: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:23:44.227117: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-2181\nI0617 12:23:44.228382 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-2181\nINFO:tensorflow:Running local_init_op.\nI0617 12:23:45.352960 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 12:23:45.511244 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 12:30:14.720657 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 12:30:14.729533 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.47s)\nI0617 12:30:15.204269 139799327557376 coco_tools.py:138] DONE (t=0.47s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.58s).\nAccumulating evaluation results...\nDONE (t=3.04s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.331\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.689\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.262\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.351\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.231\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.012\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.264\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.481\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.523\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.528\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.495\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.553\nINFO:tensorflow:Finished evaluation at 2020-06-17-12:30:41\nI0617 12:30:41.721312 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-12:30:41\nINFO:tensorflow:Saving dict for global step 2181: DetectionBoxes_Precision/mAP = 0.33111954, DetectionBoxes_Precision/mAP (large) = 0.012235991, DetectionBoxes_Precision/mAP (medium) = 0.23089333, DetectionBoxes_Precision/mAP (small) = 0.35097843, DetectionBoxes_Precision/[email protected] = 0.6894082, DetectionBoxes_Precision/[email protected] = 0.262043, DetectionBoxes_Recall/AR@1 = 0.26435944, DetectionBoxes_Recall/AR@10 = 0.48105645, DetectionBoxes_Recall/AR@100 = 0.52343655, DetectionBoxes_Recall/AR@100 (large) = 0.55333334, DetectionBoxes_Recall/AR@100 (medium) = 0.49453717, DetectionBoxes_Recall/AR@100 (small) = 0.52778816, Loss/BoxClassifierLoss/classification_loss = 0.14096211, Loss/BoxClassifierLoss/localization_loss = 0.105743356, Loss/RPNLoss/localization_loss = 0.036049135, Loss/RPNLoss/objectness_loss = 0.06868647, Loss/total_loss = 0.3514414, global_step = 2181, learning_rate = 0.0002, loss = 0.3514414\nI0617 12:30:41.721715 139802647791488 estimator.py:2049] Saving dict for global step 2181: DetectionBoxes_Precision/mAP = 0.33111954, DetectionBoxes_Precision/mAP (large) = 0.012235991, DetectionBoxes_Precision/mAP (medium) = 0.23089333, DetectionBoxes_Precision/mAP (small) = 0.35097843, DetectionBoxes_Precision/[email protected] = 0.6894082, DetectionBoxes_Precision/[email protected] = 0.262043, DetectionBoxes_Recall/AR@1 = 0.26435944, DetectionBoxes_Recall/AR@10 = 0.48105645, DetectionBoxes_Recall/AR@100 = 0.52343655, DetectionBoxes_Recall/AR@100 (large) = 0.55333334, DetectionBoxes_Recall/AR@100 (medium) = 0.49453717, DetectionBoxes_Recall/AR@100 (small) = 0.52778816, Loss/BoxClassifierLoss/classification_loss = 0.14096211, Loss/BoxClassifierLoss/localization_loss = 0.105743356, Loss/RPNLoss/localization_loss = 0.036049135, Loss/RPNLoss/objectness_loss = 0.06868647, Loss/total_loss = 0.3514414, global_step = 2181, learning_rate = 0.0002, loss = 0.3514414\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 2181: training/model.ckpt-2181\nI0617 12:30:41.722930 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 2181: training/model.ckpt-2181\nINFO:tensorflow:global_step/sec: 0.162392\nI0617 12:31:19.195303 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.162392\nINFO:tensorflow:loss = 0.48422962, step = 2200 (615.793 sec)\nI0617 12:31:19.196845 139802647791488 basic_session_run_hooks.py:260] loss = 0.48422962, step = 2200 (615.793 sec)\nINFO:tensorflow:Saving checkpoints for 2274 into training/model.ckpt.\nI0617 12:33:35.939026 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 2274 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25745eec18>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 12:33:38.521519 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f25745eec18>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f258a6eb0d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 12:33:38.750788 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f258a6eb0d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 12:33:39.460825 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:33:41.454279 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:33:41.472536 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 12:33:41.472967 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:33:42.746846 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:33:42.769212 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 12:33:44.945682 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T12:33:44Z\nI0617 12:33:44.967491 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T12:33:44Z\nINFO:tensorflow:Graph was finalized.\nI0617 12:33:45.587052 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 12:33:45.588031: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:33:45.588484: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 12:33:45.588603: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 12:33:45.588656: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 12:33:45.588707: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 12:33:45.588753: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 12:33:45.588801: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 12:33:45.588841: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 12:33:45.588890: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 12:33:45.589041: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:33:45.589445: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:33:45.589831: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 12:33:45.589903: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 12:33:45.589942: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 12:33:45.589958: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 12:33:45.590121: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:33:45.590513: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:33:45.590845: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-2274\nI0617 12:33:45.592252 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-2274\nINFO:tensorflow:Running local_init_op.\nI0617 12:33:46.722850 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 12:33:46.881603 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 12:40:15.692725 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 12:40:15.706644 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.47s)\nI0617 12:40:16.174664 139799327557376 coco_tools.py:138] DONE (t=0.47s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=22.23s).\nAccumulating evaluation results...\nDONE (t=2.97s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.330\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.682\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.268\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.350\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.224\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.007\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.264\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.479\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.524\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.530\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.484\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.560\nINFO:tensorflow:Finished evaluation at 2020-06-17-12:40:42\nI0617 12:40:42.258328 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-12:40:42\nINFO:tensorflow:Saving dict for global step 2274: DetectionBoxes_Precision/mAP = 0.32960534, DetectionBoxes_Precision/mAP (large) = 0.0071100583, DetectionBoxes_Precision/mAP (medium) = 0.22406957, DetectionBoxes_Precision/mAP (small) = 0.3504384, DetectionBoxes_Precision/[email protected] = 0.6816099, DetectionBoxes_Precision/[email protected] = 0.26760113, DetectionBoxes_Recall/AR@1 = 0.26442015, DetectionBoxes_Recall/AR@10 = 0.4792552, DetectionBoxes_Recall/AR@100 = 0.52426636, DetectionBoxes_Recall/AR@100 (large) = 0.56, DetectionBoxes_Recall/AR@100 (medium) = 0.48376328, DetectionBoxes_Recall/AR@100 (small) = 0.5303421, Loss/BoxClassifierLoss/classification_loss = 0.13229713, Loss/BoxClassifierLoss/localization_loss = 0.10554022, Loss/RPNLoss/localization_loss = 0.036124945, Loss/RPNLoss/objectness_loss = 0.069881834, Loss/total_loss = 0.34384367, global_step = 2274, learning_rate = 0.0002, loss = 0.34384367\nI0617 12:40:42.258841 139802647791488 estimator.py:2049] Saving dict for global step 2274: DetectionBoxes_Precision/mAP = 0.32960534, DetectionBoxes_Precision/mAP (large) = 0.0071100583, DetectionBoxes_Precision/mAP (medium) = 0.22406957, DetectionBoxes_Precision/mAP (small) = 0.3504384, DetectionBoxes_Precision/[email protected] = 0.6816099, DetectionBoxes_Precision/[email protected] = 0.26760113, DetectionBoxes_Recall/AR@1 = 0.26442015, DetectionBoxes_Recall/AR@10 = 0.4792552, DetectionBoxes_Recall/AR@100 = 0.52426636, DetectionBoxes_Recall/AR@100 (large) = 0.56, DetectionBoxes_Recall/AR@100 (medium) = 0.48376328, DetectionBoxes_Recall/AR@100 (small) = 0.5303421, Loss/BoxClassifierLoss/classification_loss = 0.13229713, Loss/BoxClassifierLoss/localization_loss = 0.10554022, Loss/RPNLoss/localization_loss = 0.036124945, Loss/RPNLoss/objectness_loss = 0.069881834, Loss/total_loss = 0.34384367, global_step = 2274, learning_rate = 0.0002, loss = 0.34384367\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 2274: training/model.ckpt-2274\nI0617 12:40:42.259904 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 2274: training/model.ckpt-2274\nINFO:tensorflow:global_step/sec: 0.162899\nI0617 12:41:33.072008 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.162899\nINFO:tensorflow:loss = 0.6364177, step = 2300 (613.877 sec)\nI0617 12:41:33.073675 139802647791488 basic_session_run_hooks.py:260] loss = 0.6364177, step = 2300 (613.877 sec)\nINFO:tensorflow:Saving checkpoints for 2367 into training/model.ckpt.\nI0617 12:43:37.749652 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 2367 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2587b52748>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 12:43:40.114447 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2587b52748>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348bf8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 12:43:40.341064 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f25e7348bf8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 12:43:41.062187 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:43:43.035840 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:43:43.054135 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 12:43:43.054666 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:43:44.376071 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:43:44.397092 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 12:43:46.489278 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T12:43:46Z\nI0617 12:43:46.510764 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T12:43:46Z\nINFO:tensorflow:Graph was finalized.\nI0617 12:43:47.097676 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 12:43:47.098503: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:43:47.098915: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 12:43:47.099023: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 12:43:47.099069: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 12:43:47.099115: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 12:43:47.099156: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 12:43:47.099205: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 12:43:47.099245: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 12:43:47.099285: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 12:43:47.099415: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:43:47.100859: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:43:47.101183: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 12:43:47.101235: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 12:43:47.101256: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 12:43:47.101271: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 12:43:47.101424: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:43:47.101863: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:43:47.102163: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-2367\nI0617 12:43:47.103524 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-2367\nINFO:tensorflow:Running local_init_op.\nI0617 12:43:48.224051 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 12:43:48.392888 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 12:50:14.430521 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 12:50:14.440838 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.44s)\nI0617 12:50:14.885509 139799327557376 coco_tools.py:138] DONE (t=0.44s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.72s).\nAccumulating evaluation results...\nDONE (t=2.81s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.335\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.689\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.273\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.355\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.235\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.007\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.266\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.482\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.528\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.532\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.499\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.567\nINFO:tensorflow:Finished evaluation at 2020-06-17-12:50:40\nI0617 12:50:40.261375 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-12:50:40\nINFO:tensorflow:Saving dict for global step 2367: DetectionBoxes_Precision/mAP = 0.33500353, DetectionBoxes_Precision/mAP (large) = 0.006779188, DetectionBoxes_Precision/mAP (medium) = 0.23548616, DetectionBoxes_Precision/mAP (small) = 0.35500464, DetectionBoxes_Precision/[email protected] = 0.68911326, DetectionBoxes_Precision/[email protected] = 0.27320376, DetectionBoxes_Recall/AR@1 = 0.26648453, DetectionBoxes_Recall/AR@10 = 0.4824327, DetectionBoxes_Recall/AR@100 = 0.52756524, DetectionBoxes_Recall/AR@100 (large) = 0.56666666, DetectionBoxes_Recall/AR@100 (medium) = 0.4986343, DetectionBoxes_Recall/AR@100 (small) = 0.53184164, Loss/BoxClassifierLoss/classification_loss = 0.13569054, Loss/BoxClassifierLoss/localization_loss = 0.10461085, Loss/RPNLoss/localization_loss = 0.03611979, Loss/RPNLoss/objectness_loss = 0.06907656, Loss/total_loss = 0.34549797, global_step = 2367, learning_rate = 0.0002, loss = 0.34549797\nI0617 12:50:40.261749 139802647791488 estimator.py:2049] Saving dict for global step 2367: DetectionBoxes_Precision/mAP = 0.33500353, DetectionBoxes_Precision/mAP (large) = 0.006779188, DetectionBoxes_Precision/mAP (medium) = 0.23548616, DetectionBoxes_Precision/mAP (small) = 0.35500464, DetectionBoxes_Precision/[email protected] = 0.68911326, DetectionBoxes_Precision/[email protected] = 0.27320376, DetectionBoxes_Recall/AR@1 = 0.26648453, DetectionBoxes_Recall/AR@10 = 0.4824327, DetectionBoxes_Recall/AR@100 = 0.52756524, DetectionBoxes_Recall/AR@100 (large) = 0.56666666, DetectionBoxes_Recall/AR@100 (medium) = 0.4986343, DetectionBoxes_Recall/AR@100 (small) = 0.53184164, Loss/BoxClassifierLoss/classification_loss = 0.13569054, Loss/BoxClassifierLoss/localization_loss = 0.10461085, Loss/RPNLoss/localization_loss = 0.03611979, Loss/RPNLoss/objectness_loss = 0.06907656, Loss/total_loss = 0.34549797, global_step = 2367, learning_rate = 0.0002, loss = 0.34549797\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 2367: training/model.ckpt-2367\nI0617 12:50:40.262822 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 2367: training/model.ckpt-2367\nINFO:tensorflow:global_step/sec: 0.163392\nI0617 12:51:45.097746 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.163392\nINFO:tensorflow:loss = 0.65673417, step = 2400 (612.025 sec)\nI0617 12:51:45.099101 139802647791488 basic_session_run_hooks.py:260] loss = 0.65673417, step = 2400 (612.025 sec)\nINFO:tensorflow:Saving checkpoints for 2461 into training/model.ckpt.\nI0617 12:53:39.142415 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 2461 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2563be9b38>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 12:53:41.538780 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f2563be9b38>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f258a6eb840> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 12:53:41.752483 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f258a6eb840> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 12:53:42.414479 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:53:44.268326 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:53:44.286333 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 12:53:44.286789 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:53:45.481396 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 12:53:45.500910 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 12:53:47.548420 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T12:53:47Z\nI0617 12:53:47.569504 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T12:53:47Z\nINFO:tensorflow:Graph was finalized.\nI0617 12:53:48.118988 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 12:53:48.119884: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:53:48.120236: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 12:53:48.120365: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 12:53:48.120408: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 12:53:48.120457: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 12:53:48.120500: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 12:53:48.120538: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 12:53:48.120616: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 12:53:48.120661: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 12:53:48.120797: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:53:48.121261: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:53:48.121543: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 12:53:48.121614: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 12:53:48.121634: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 12:53:48.121648: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 12:53:48.121794: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:53:48.122181: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 12:53:48.122515: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-2461\nI0617 12:53:48.123817 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-2461\nINFO:tensorflow:Running local_init_op.\nI0617 12:53:49.167438 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 12:53:49.316193 139802647791488 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Performing evaluation on 2768 images.\nI0617 13:00:17.855750 139799327557376 coco_evaluation.py:237] Performing evaluation on 2768 images.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 13:00:17.863650 139799327557376 coco_tools.py:116] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.48s)\nI0617 13:00:18.345427 139799327557376 coco_tools.py:138] DONE (t=0.48s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=21.74s).\nAccumulating evaluation results...\nDONE (t=2.92s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.322\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.676\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.251\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.342\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.225\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.010\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.260\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.471\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.517\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.521\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.486\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.607\nINFO:tensorflow:Finished evaluation at 2020-06-17-13:00:43\nI0617 13:00:43.889070 139802647791488 evaluation.py:275] Finished evaluation at 2020-06-17-13:00:43\nINFO:tensorflow:Saving dict for global step 2461: DetectionBoxes_Precision/mAP = 0.3224893, DetectionBoxes_Precision/mAP (large) = 0.0101903, DetectionBoxes_Precision/mAP (medium) = 0.2246002, DetectionBoxes_Precision/mAP (small) = 0.34192362, DetectionBoxes_Precision/[email protected] = 0.67600334, DetectionBoxes_Precision/[email protected] = 0.2508166, DetectionBoxes_Recall/AR@1 = 0.25966403, DetectionBoxes_Recall/AR@10 = 0.47081563, DetectionBoxes_Recall/AR@100 = 0.5166565, DetectionBoxes_Recall/AR@100 (large) = 0.6066667, DetectionBoxes_Recall/AR@100 (medium) = 0.4864947, DetectionBoxes_Recall/AR@100 (small) = 0.52097, Loss/BoxClassifierLoss/classification_loss = 0.13005792, Loss/BoxClassifierLoss/localization_loss = 0.10705918, Loss/RPNLoss/localization_loss = 0.03635343, Loss/RPNLoss/objectness_loss = 0.07035515, Loss/total_loss = 0.3438254, global_step = 2461, learning_rate = 0.0002, loss = 0.3438254\nI0617 13:00:43.889385 139802647791488 estimator.py:2049] Saving dict for global step 2461: DetectionBoxes_Precision/mAP = 0.3224893, DetectionBoxes_Precision/mAP (large) = 0.0101903, DetectionBoxes_Precision/mAP (medium) = 0.2246002, DetectionBoxes_Precision/mAP (small) = 0.34192362, DetectionBoxes_Precision/[email protected] = 0.67600334, DetectionBoxes_Precision/[email protected] = 0.2508166, DetectionBoxes_Recall/AR@1 = 0.25966403, DetectionBoxes_Recall/AR@10 = 0.47081563, DetectionBoxes_Recall/AR@100 = 0.5166565, DetectionBoxes_Recall/AR@100 (large) = 0.6066667, DetectionBoxes_Recall/AR@100 (medium) = 0.4864947, DetectionBoxes_Recall/AR@100 (small) = 0.52097, Loss/BoxClassifierLoss/classification_loss = 0.13005792, Loss/BoxClassifierLoss/localization_loss = 0.10705918, Loss/RPNLoss/localization_loss = 0.03635343, Loss/RPNLoss/objectness_loss = 0.07035515, Loss/total_loss = 0.3438254, global_step = 2461, learning_rate = 0.0002, loss = 0.3438254\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 2461: training/model.ckpt-2461\nI0617 13:00:43.890416 139802647791488 estimator.py:2109] Saving 'checkpoint_path' summary for global step 2461: training/model.ckpt-2461\nINFO:tensorflow:global_step/sec: 0.162448\nI0617 13:02:00.680937 139802647791488 basic_session_run_hooks.py:692] global_step/sec: 0.162448\nINFO:tensorflow:loss = 0.44722554, step = 2500 (615.583 sec)\nI0617 13:02:00.682462 139802647791488 basic_session_run_hooks.py:260] loss = 0.44722554, step = 2500 (615.583 sec)\nINFO:tensorflow:Saving checkpoints for 2553 into training/model.ckpt.\nI0617 13:03:39.778919 139802647791488 basic_session_run_hooks.py:606] Saving checkpoints for 2553 into training/model.ckpt.\nWARNING:tensorflow:Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f256e742080>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nW0617 13:03:42.210686 139802647791488 ag_logging.py:146] Entity <bound method TfExampleDecoder.decode of <object_detection.data_decoders.tf_example_decoder.TfExampleDecoder object at 0x7f256e742080>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING:tensorflow:Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2588acb598> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 13:03:42.447380 139802647791488 ag_logging.py:146] Entity <function eval_input.<locals>.transform_and_pad_input_data_fn at 0x7f2588acb598> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 13:03:43.215162 139802647791488 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 13:03:45.132844 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 13:03:45.149499 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 13:03:45.150006 139802647791488 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 13:03:46.448384 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 13:03:46.471515 139802647791488 regularizers.py:99] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 13:03:48.620736 139802647791488 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T13:03:48Z\nI0617 13:03:48.641299 139802647791488 evaluation.py:255] Starting evaluation at 2020-06-17T13:03:48Z\nINFO:tensorflow:Graph was finalized.\nI0617 13:03:49.245546 139802647791488 monitored_session.py:240] Graph was finalized.\n2020-06-17 13:03:49.246449: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 13:03:49.246900: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-17 13:03:49.247073: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 13:03:49.247142: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 13:03:49.247186: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 13:03:49.247227: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 13:03:49.247267: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 13:03:49.247322: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 13:03:49.247392: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 13:03:49.247589: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 13:03:49.248063: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 13:03:49.248352: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 13:03:49.248402: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 13:03:49.248421: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 13:03:49.248435: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 13:03:49.248590: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 13:03:49.248997: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 13:03:49.249293: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-2553\nI0617 13:03:49.250655 139802647791488 saver.py:1284] Restoring parameters from training/model.ckpt-2553\nINFO:tensorflow:Running local_init_op.\nI0617 13:03:50.425700 139802647791488 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 13:03:50.597386 139802647791488 session_manager.py:502] Done running local_init_op.\n" ], [ "!ls {model_dir}", "checkpoint\neval_0\nevents.out.tfevents.1592284871.2e559208a432\nexport\ngraph.pbtxt\nmodel.ckpt-10000.data-00000-of-00001\nmodel.ckpt-10000.index\nmodel.ckpt-10000.meta\nmodel.ckpt-5510.data-00000-of-00001\nmodel.ckpt-5510.index\nmodel.ckpt-5510.meta\nmodel.ckpt-6633.data-00000-of-00001\nmodel.ckpt-6633.index\nmodel.ckpt-6633.meta\nmodel.ckpt-7759.data-00000-of-00001\nmodel.ckpt-7759.index\nmodel.ckpt-7759.meta\nmodel.ckpt-8880.data-00000-of-00001\nmodel.ckpt-8880.index\nmodel.ckpt-8880.meta\n" ] ], [ [ "##Task-4: Freezing a trained model and export it for inference\n", "_____no_output_____" ], [ "### Step: 10 Exporting a Trained Inference Graph", "_____no_output_____" ] ], [ [ "import re\nimport numpy as np\n\noutput_directory = './fine_tuned_model'\n\nlst = os.listdir(model_dir)\nlst = [l for l in lst if 'model.ckpt-' in l and '.meta' in l]\nsteps=np.array([int(re.findall('\\d+', l)[0]) for l in lst])\nlast_model = lst[steps.argmax()].replace('.meta', '')\n\nlast_model_path = os.path.join(model_dir, last_model)\nprint(last_model_path)\n!python /content/models/research/object_detection/export_inference_graph.py \\\n --input_type=image_tensor \\\n --pipeline_config_path={pipeline_fname} \\\n --output_directory={output_directory} \\\n --trained_checkpoint_prefix={last_model_path}", "training/model.ckpt-10000\nWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tf_slim/layers/layers.py:1089: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `layer.__call__` method instead.\nW0616 06:46:28.778084 140645638100864 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tf_slim/layers/layers.py:1089: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `layer.__call__` method instead.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0616 06:46:31.542984 140645638100864 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0616 06:46:31.590529 140645638100864 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0616 06:46:31.740777 140645638100864 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0616 06:46:31.787602 140645638100864 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0616 06:46:31.834694 140645638100864 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0616 06:46:31.893069 140645638100864 convolutional_box_predictor.py:156] depth of additional conv before box predictor: 0\nWARNING:tensorflow:From /content/models/research/object_detection/core/post_processing.py:583: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.where in 2.0, which has the same broadcast rule as np.where\nW0616 06:46:32.218458 140645638100864 deprecation.py:323] From /content/models/research/object_detection/core/post_processing.py:583: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.where in 2.0, which has the same broadcast rule as np.where\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:400: get_or_create_global_step (from tf_slim.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease switch to tf.train.get_or_create_global_step\nW0616 06:46:32.625969 140645638100864 deprecation.py:323] From /content/models/research/object_detection/exporter.py:400: get_or_create_global_step (from tf_slim.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease switch to tf.train.get_or_create_global_step\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:555: print_model_analysis (from tensorflow.contrib.tfprof.model_analyzer) is deprecated and will be removed after 2018-01-01.\nInstructions for updating:\nUse `tf.profiler.profile(graph, run_meta, op_log, cmd, options)`. Build `options` with `tf.profiler.ProfileOptionBuilder`. See README.md for details\nW0616 06:46:32.630128 140645638100864 deprecation.py:323] From /content/models/research/object_detection/exporter.py:555: print_model_analysis (from tensorflow.contrib.tfprof.model_analyzer) is deprecated and will be removed after 2018-01-01.\nInstructions for updating:\nUse `tf.profiler.profile(graph, run_meta, op_log, cmd, options)`. Build `options` with `tf.profiler.ProfileOptionBuilder`. See README.md for details\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/profiler/internal/flops_registry.py:142: tensor_shape_from_node_def_name (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.tensor_shape_from_node_def_name`\nW0616 06:46:32.631534 140645638100864 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/profiler/internal/flops_registry.py:142: tensor_shape_from_node_def_name (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.tensor_shape_from_node_def_name`\n133 ops no flops stats due to incomplete shapes.\nParsing Inputs...\nIncomplete shape.\n\n=========================Options=============================\n-max_depth 10000\n-min_bytes 0\n-min_peak_bytes 0\n-min_residual_bytes 0\n-min_output_bytes 0\n-min_micros 0\n-min_accelerator_micros 0\n-min_cpu_micros 0\n-min_params 0\n-min_float_ops 0\n-min_occurrence 0\n-step -1\n-order_by name\n-account_type_regexes _trainable_variables\n-start_name_regexes .*\n-trim_name_regexes .*BatchNorm.*\n-show_name_regexes .*\n-hide_name_regexes \n-account_displayed_op_only true\n-select params\n-output stdout:\n\n==================Model Analysis Report======================\nIncomplete shape.\n\nDoc:\nscope: The nodes in the model graph are organized by their names, which is hierarchical like filesystem.\nparam: Number of parameters (in the Variable).\n\nProfile:\nnode name | # parameters\n_TFProfRoot (--/4.57m params)\n BoxPredictor_0 (--/10.39k params)\n BoxPredictor_0/BoxEncodingPredictor (--/6.92k params)\n BoxPredictor_0/BoxEncodingPredictor/biases (12, 12/12 params)\n BoxPredictor_0/BoxEncodingPredictor/weights (1x1x576x12, 6.91k/6.91k params)\n BoxPredictor_0/ClassPredictor (--/3.46k params)\n BoxPredictor_0/ClassPredictor/biases (6, 6/6 params)\n BoxPredictor_0/ClassPredictor/weights (1x1x576x6, 3.46k/3.46k params)\n BoxPredictor_1 (--/46.12k params)\n BoxPredictor_1/BoxEncodingPredictor (--/30.74k params)\n BoxPredictor_1/BoxEncodingPredictor/biases (24, 24/24 params)\n BoxPredictor_1/BoxEncodingPredictor/weights (1x1x1280x24, 30.72k/30.72k params)\n BoxPredictor_1/ClassPredictor (--/15.37k params)\n BoxPredictor_1/ClassPredictor/biases (12, 12/12 params)\n BoxPredictor_1/ClassPredictor/weights (1x1x1280x12, 15.36k/15.36k params)\n BoxPredictor_2 (--/18.47k params)\n BoxPredictor_2/BoxEncodingPredictor (--/12.31k params)\n BoxPredictor_2/BoxEncodingPredictor/biases (24, 24/24 params)\n BoxPredictor_2/BoxEncodingPredictor/weights (1x1x512x24, 12.29k/12.29k params)\n BoxPredictor_2/ClassPredictor (--/6.16k params)\n BoxPredictor_2/ClassPredictor/biases (12, 12/12 params)\n BoxPredictor_2/ClassPredictor/weights (1x1x512x12, 6.14k/6.14k params)\n BoxPredictor_3 (--/9.25k params)\n BoxPredictor_3/BoxEncodingPredictor (--/6.17k params)\n BoxPredictor_3/BoxEncodingPredictor/biases (24, 24/24 params)\n BoxPredictor_3/BoxEncodingPredictor/weights (1x1x256x24, 6.14k/6.14k params)\n BoxPredictor_3/ClassPredictor (--/3.08k params)\n BoxPredictor_3/ClassPredictor/biases (12, 12/12 params)\n BoxPredictor_3/ClassPredictor/weights (1x1x256x12, 3.07k/3.07k params)\n BoxPredictor_4 (--/9.25k params)\n BoxPredictor_4/BoxEncodingPredictor (--/6.17k params)\n BoxPredictor_4/BoxEncodingPredictor/biases (24, 24/24 params)\n BoxPredictor_4/BoxEncodingPredictor/weights (1x1x256x24, 6.14k/6.14k params)\n BoxPredictor_4/ClassPredictor (--/3.08k params)\n BoxPredictor_4/ClassPredictor/biases (12, 12/12 params)\n BoxPredictor_4/ClassPredictor/weights (1x1x256x12, 3.07k/3.07k params)\n BoxPredictor_5 (--/4.64k params)\n BoxPredictor_5/BoxEncodingPredictor (--/3.10k params)\n BoxPredictor_5/BoxEncodingPredictor/biases (24, 24/24 params)\n BoxPredictor_5/BoxEncodingPredictor/weights (1x1x128x24, 3.07k/3.07k params)\n BoxPredictor_5/ClassPredictor (--/1.55k params)\n BoxPredictor_5/ClassPredictor/biases (12, 12/12 params)\n BoxPredictor_5/ClassPredictor/weights (1x1x128x12, 1.54k/1.54k params)\n FeatureExtractor (--/4.48m params)\n FeatureExtractor/MobilenetV2 (--/4.48m params)\n FeatureExtractor/MobilenetV2/Conv (--/864 params)\n FeatureExtractor/MobilenetV2/Conv/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/Conv/weights (3x3x3x32, 864/864 params)\n FeatureExtractor/MobilenetV2/Conv_1 (--/409.60k params)\n FeatureExtractor/MobilenetV2/Conv_1/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/Conv_1/weights (1x1x320x1280, 409.60k/409.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv (--/800 params)\n FeatureExtractor/MobilenetV2/expanded_conv/depthwise (--/288 params)\n FeatureExtractor/MobilenetV2/expanded_conv/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv/depthwise/depthwise_weights (3x3x32x1, 288/288 params)\n FeatureExtractor/MobilenetV2/expanded_conv/project (--/512 params)\n FeatureExtractor/MobilenetV2/expanded_conv/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv/project/weights (1x1x32x16, 512/512 params)\n FeatureExtractor/MobilenetV2/expanded_conv_1 (--/4.70k params)\n FeatureExtractor/MobilenetV2/expanded_conv_1/depthwise (--/864 params)\n FeatureExtractor/MobilenetV2/expanded_conv_1/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_1/depthwise/depthwise_weights (3x3x96x1, 864/864 params)\n FeatureExtractor/MobilenetV2/expanded_conv_1/expand (--/1.54k params)\n FeatureExtractor/MobilenetV2/expanded_conv_1/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_1/expand/weights (1x1x16x96, 1.54k/1.54k params)\n FeatureExtractor/MobilenetV2/expanded_conv_1/project (--/2.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_1/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_1/project/weights (1x1x96x24, 2.30k/2.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_10 (--/64.90k params)\n FeatureExtractor/MobilenetV2/expanded_conv_10/depthwise (--/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_10/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_10/depthwise/depthwise_weights (3x3x384x1, 3.46k/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_10/expand (--/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_10/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_10/expand/weights (1x1x64x384, 24.58k/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_10/project (--/36.86k params)\n FeatureExtractor/MobilenetV2/expanded_conv_10/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_10/project/weights (1x1x384x96, 36.86k/36.86k params)\n FeatureExtractor/MobilenetV2/expanded_conv_11 (--/115.78k params)\n FeatureExtractor/MobilenetV2/expanded_conv_11/depthwise (--/5.18k params)\n FeatureExtractor/MobilenetV2/expanded_conv_11/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_11/depthwise/depthwise_weights (3x3x576x1, 5.18k/5.18k params)\n FeatureExtractor/MobilenetV2/expanded_conv_11/expand (--/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_11/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_11/expand/weights (1x1x96x576, 55.30k/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_11/project (--/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_11/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_11/project/weights (1x1x576x96, 55.30k/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_12 (--/115.78k params)\n FeatureExtractor/MobilenetV2/expanded_conv_12/depthwise (--/5.18k params)\n FeatureExtractor/MobilenetV2/expanded_conv_12/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_12/depthwise/depthwise_weights (3x3x576x1, 5.18k/5.18k params)\n FeatureExtractor/MobilenetV2/expanded_conv_12/expand (--/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_12/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_12/expand/weights (1x1x96x576, 55.30k/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_12/project (--/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_12/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_12/project/weights (1x1x576x96, 55.30k/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_13 (--/152.64k params)\n FeatureExtractor/MobilenetV2/expanded_conv_13/depthwise (--/5.18k params)\n FeatureExtractor/MobilenetV2/expanded_conv_13/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_13/depthwise/depthwise_weights (3x3x576x1, 5.18k/5.18k params)\n FeatureExtractor/MobilenetV2/expanded_conv_13/expand (--/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_13/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_13/expand/weights (1x1x96x576, 55.30k/55.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_13/project (--/92.16k params)\n FeatureExtractor/MobilenetV2/expanded_conv_13/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_13/project/weights (1x1x576x160, 92.16k/92.16k params)\n FeatureExtractor/MobilenetV2/expanded_conv_14 (--/315.84k params)\n FeatureExtractor/MobilenetV2/expanded_conv_14/depthwise (--/8.64k params)\n FeatureExtractor/MobilenetV2/expanded_conv_14/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_14/depthwise/depthwise_weights (3x3x960x1, 8.64k/8.64k params)\n FeatureExtractor/MobilenetV2/expanded_conv_14/expand (--/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_14/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_14/expand/weights (1x1x160x960, 153.60k/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_14/project (--/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_14/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_14/project/weights (1x1x960x160, 153.60k/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_15 (--/315.84k params)\n FeatureExtractor/MobilenetV2/expanded_conv_15/depthwise (--/8.64k params)\n FeatureExtractor/MobilenetV2/expanded_conv_15/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_15/depthwise/depthwise_weights (3x3x960x1, 8.64k/8.64k params)\n FeatureExtractor/MobilenetV2/expanded_conv_15/expand (--/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_15/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_15/expand/weights (1x1x160x960, 153.60k/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_15/project (--/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_15/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_15/project/weights (1x1x960x160, 153.60k/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_16 (--/469.44k params)\n FeatureExtractor/MobilenetV2/expanded_conv_16/depthwise (--/8.64k params)\n FeatureExtractor/MobilenetV2/expanded_conv_16/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_16/depthwise/depthwise_weights (3x3x960x1, 8.64k/8.64k params)\n FeatureExtractor/MobilenetV2/expanded_conv_16/expand (--/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_16/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_16/expand/weights (1x1x160x960, 153.60k/153.60k params)\n FeatureExtractor/MobilenetV2/expanded_conv_16/project (--/307.20k params)\n FeatureExtractor/MobilenetV2/expanded_conv_16/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_16/project/weights (1x1x960x320, 307.20k/307.20k params)\n FeatureExtractor/MobilenetV2/expanded_conv_2 (--/8.21k params)\n FeatureExtractor/MobilenetV2/expanded_conv_2/depthwise (--/1.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_2/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_2/depthwise/depthwise_weights (3x3x144x1, 1.30k/1.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_2/expand (--/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_2/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_2/expand/weights (1x1x24x144, 3.46k/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_2/project (--/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_2/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_2/project/weights (1x1x144x24, 3.46k/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_3 (--/9.36k params)\n FeatureExtractor/MobilenetV2/expanded_conv_3/depthwise (--/1.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_3/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_3/depthwise/depthwise_weights (3x3x144x1, 1.30k/1.30k params)\n FeatureExtractor/MobilenetV2/expanded_conv_3/expand (--/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_3/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_3/expand/weights (1x1x24x144, 3.46k/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_3/project (--/4.61k params)\n FeatureExtractor/MobilenetV2/expanded_conv_3/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_3/project/weights (1x1x144x32, 4.61k/4.61k params)\n FeatureExtractor/MobilenetV2/expanded_conv_4 (--/14.02k params)\n FeatureExtractor/MobilenetV2/expanded_conv_4/depthwise (--/1.73k params)\n FeatureExtractor/MobilenetV2/expanded_conv_4/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_4/depthwise/depthwise_weights (3x3x192x1, 1.73k/1.73k params)\n FeatureExtractor/MobilenetV2/expanded_conv_4/expand (--/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_4/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_4/expand/weights (1x1x32x192, 6.14k/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_4/project (--/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_4/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_4/project/weights (1x1x192x32, 6.14k/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_5 (--/14.02k params)\n FeatureExtractor/MobilenetV2/expanded_conv_5/depthwise (--/1.73k params)\n FeatureExtractor/MobilenetV2/expanded_conv_5/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_5/depthwise/depthwise_weights (3x3x192x1, 1.73k/1.73k params)\n FeatureExtractor/MobilenetV2/expanded_conv_5/expand (--/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_5/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_5/expand/weights (1x1x32x192, 6.14k/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_5/project (--/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_5/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_5/project/weights (1x1x192x32, 6.14k/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_6 (--/20.16k params)\n FeatureExtractor/MobilenetV2/expanded_conv_6/depthwise (--/1.73k params)\n FeatureExtractor/MobilenetV2/expanded_conv_6/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_6/depthwise/depthwise_weights (3x3x192x1, 1.73k/1.73k params)\n FeatureExtractor/MobilenetV2/expanded_conv_6/expand (--/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_6/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_6/expand/weights (1x1x32x192, 6.14k/6.14k params)\n FeatureExtractor/MobilenetV2/expanded_conv_6/project (--/12.29k params)\n FeatureExtractor/MobilenetV2/expanded_conv_6/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_6/project/weights (1x1x192x64, 12.29k/12.29k params)\n FeatureExtractor/MobilenetV2/expanded_conv_7 (--/52.61k params)\n FeatureExtractor/MobilenetV2/expanded_conv_7/depthwise (--/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_7/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_7/depthwise/depthwise_weights (3x3x384x1, 3.46k/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_7/expand (--/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_7/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_7/expand/weights (1x1x64x384, 24.58k/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_7/project (--/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_7/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_7/project/weights (1x1x384x64, 24.58k/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_8 (--/52.61k params)\n FeatureExtractor/MobilenetV2/expanded_conv_8/depthwise (--/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_8/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_8/depthwise/depthwise_weights (3x3x384x1, 3.46k/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_8/expand (--/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_8/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_8/expand/weights (1x1x64x384, 24.58k/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_8/project (--/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_8/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_8/project/weights (1x1x384x64, 24.58k/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_9 (--/52.61k params)\n FeatureExtractor/MobilenetV2/expanded_conv_9/depthwise (--/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_9/depthwise/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_9/depthwise/depthwise_weights (3x3x384x1, 3.46k/3.46k params)\n FeatureExtractor/MobilenetV2/expanded_conv_9/expand (--/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_9/expand/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_9/expand/weights (1x1x64x384, 24.58k/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_9/project (--/24.58k params)\n FeatureExtractor/MobilenetV2/expanded_conv_9/project/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/expanded_conv_9/project/weights (1x1x384x64, 24.58k/24.58k params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_2_1x1_256 (--/327.68k params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_2_1x1_256/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_2_1x1_256/weights (1x1x1280x256, 327.68k/327.68k params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_3_1x1_128 (--/65.54k params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_3_1x1_128/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_3_1x1_128/weights (1x1x512x128, 65.54k/65.54k params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_4_1x1_128 (--/32.77k params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_4_1x1_128/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_4_1x1_128/weights (1x1x256x128, 32.77k/32.77k params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_5_1x1_64 (--/16.38k params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_5_1x1_64/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/layer_19_1_Conv2d_5_1x1_64/weights (1x1x256x64, 16.38k/16.38k params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_2_3x3_s2_512 (--/1.18m params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_2_3x3_s2_512/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_2_3x3_s2_512/weights (3x3x256x512, 1.18m/1.18m params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_3_3x3_s2_256 (--/294.91k params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_3_3x3_s2_256/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_3_3x3_s2_256/weights (3x3x128x256, 294.91k/294.91k params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_4_3x3_s2_256 (--/294.91k params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_4_3x3_s2_256/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_4_3x3_s2_256/weights (3x3x128x256, 294.91k/294.91k params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_5_3x3_s2_128 (--/73.73k params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_5_3x3_s2_128/BatchNorm (--/0 params)\n FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_5_3x3_s2_128/weights (3x3x64x128, 73.73k/73.73k params)\n\n======================End of Report==========================\n133 ops no flops stats due to incomplete shapes.\nParsing Inputs...\nIncomplete shape.\n\n=========================Options=============================\n-max_depth 10000\n-min_bytes 0\n-min_peak_bytes 0\n-min_residual_bytes 0\n-min_output_bytes 0\n-min_micros 0\n-min_accelerator_micros 0\n-min_cpu_micros 0\n-min_params 0\n-min_float_ops 1\n-min_occurrence 0\n-step -1\n-order_by float_ops\n-account_type_regexes .*\n-start_name_regexes .*\n-trim_name_regexes .*BatchNorm.*,.*Initializer.*,.*Regularizer.*,.*BiasAdd.*\n-show_name_regexes .*\n-hide_name_regexes \n-account_displayed_op_only true\n-select float_ops\n-output stdout:\n\n==================Model Analysis Report======================\nIncomplete shape.\n\nDoc:\nscope: The nodes in the model graph are organized by their names, which is hierarchical like filesystem.\nflops: Number of float operations. Note: Please read the implementation for the math behind it.\n\nProfile:\nnode name | # float_ops\n_TFProfRoot (--/13.71k flops)\n MultipleGridAnchorGenerator/sub (2.17k/2.17k flops)\n MultipleGridAnchorGenerator/mul_20 (2.17k/2.17k flops)\n MultipleGridAnchorGenerator/mul_19 (2.17k/2.17k flops)\n MultipleGridAnchorGenerator/mul_27 (1.20k/1.20k flops)\n MultipleGridAnchorGenerator/mul_28 (1.20k/1.20k flops)\n MultipleGridAnchorGenerator/sub_1 (1.20k/1.20k flops)\n MultipleGridAnchorGenerator/mul_21 (1.08k/1.08k flops)\n MultipleGridAnchorGenerator/mul_29 (600/600 flops)\n MultipleGridAnchorGenerator/mul_36 (300/300 flops)\n MultipleGridAnchorGenerator/mul_35 (300/300 flops)\n MultipleGridAnchorGenerator/sub_2 (300/300 flops)\n MultipleGridAnchorGenerator/mul_37 (150/150 flops)\n MultipleGridAnchorGenerator/mul_43 (108/108 flops)\n MultipleGridAnchorGenerator/mul_44 (108/108 flops)\n MultipleGridAnchorGenerator/sub_3 (108/108 flops)\n MultipleGridAnchorGenerator/mul_45 (54/54 flops)\n MultipleGridAnchorGenerator/mul_52 (48/48 flops)\n MultipleGridAnchorGenerator/mul_51 (48/48 flops)\n MultipleGridAnchorGenerator/sub_4 (48/48 flops)\n MultipleGridAnchorGenerator/mul_53 (24/24 flops)\n MultipleGridAnchorGenerator/mul_18 (19/19 flops)\n MultipleGridAnchorGenerator/mul_17 (19/19 flops)\n MultipleGridAnchorGenerator/sub_5 (12/12 flops)\n MultipleGridAnchorGenerator/mul_60 (12/12 flops)\n MultipleGridAnchorGenerator/mul_59 (12/12 flops)\n MultipleGridAnchorGenerator/mul_25 (10/10 flops)\n MultipleGridAnchorGenerator/mul_26 (10/10 flops)\n MultipleGridAnchorGenerator/mul_46 (6/6 flops)\n MultipleGridAnchorGenerator/mul_40 (6/6 flops)\n MultipleGridAnchorGenerator/mul_54 (6/6 flops)\n MultipleGridAnchorGenerator/truediv_17 (6/6 flops)\n MultipleGridAnchorGenerator/truediv_16 (6/6 flops)\n MultipleGridAnchorGenerator/truediv_15 (6/6 flops)\n MultipleGridAnchorGenerator/mul_24 (6/6 flops)\n MultipleGridAnchorGenerator/mul_47 (6/6 flops)\n MultipleGridAnchorGenerator/mul_48 (6/6 flops)\n MultipleGridAnchorGenerator/mul_61 (6/6 flops)\n MultipleGridAnchorGenerator/mul_39 (6/6 flops)\n MultipleGridAnchorGenerator/mul_38 (6/6 flops)\n MultipleGridAnchorGenerator/truediv_19 (6/6 flops)\n MultipleGridAnchorGenerator/mul_55 (6/6 flops)\n MultipleGridAnchorGenerator/mul_56 (6/6 flops)\n MultipleGridAnchorGenerator/mul_32 (6/6 flops)\n MultipleGridAnchorGenerator/mul_31 (6/6 flops)\n MultipleGridAnchorGenerator/mul_30 (6/6 flops)\n MultipleGridAnchorGenerator/truediv_18 (6/6 flops)\n MultipleGridAnchorGenerator/mul_22 (6/6 flops)\n MultipleGridAnchorGenerator/mul_23 (6/6 flops)\n MultipleGridAnchorGenerator/mul_34 (5/5 flops)\n MultipleGridAnchorGenerator/mul_33 (5/5 flops)\n MultipleGridAnchorGenerator/mul_42 (3/3 flops)\n MultipleGridAnchorGenerator/mul_41 (3/3 flops)\n MultipleGridAnchorGenerator/mul_16 (3/3 flops)\n MultipleGridAnchorGenerator/mul_15 (3/3 flops)\n MultipleGridAnchorGenerator/mul_14 (3/3 flops)\n MultipleGridAnchorGenerator/truediv_14 (3/3 flops)\n MultipleGridAnchorGenerator/mul_50 (2/2 flops)\n MultipleGridAnchorGenerator/mul_49 (2/2 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_9 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/Minimum_1 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_8 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_7 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_6 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_5 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_4 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_3 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_2 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_1 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/sub_1 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/sub (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/SortByField_1/Equal (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/SortByField/Equal (1/1 flops)\n Preprocessor/map/while/Less_1 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_2 (1/1 flops)\n MultipleGridAnchorGenerator/Minimum (1/1 flops)\n Preprocessor/map/while/Less (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/ones/Less (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_9 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_8 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_7 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_6 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_5 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_4 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_3 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_1 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_19 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_18 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_17 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_16 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_15 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_14 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_13 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_12 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_11 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_10 (1/1 flops)\n MultipleGridAnchorGenerator/mul_4 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_1 (1/1 flops)\n MultipleGridAnchorGenerator/truediv (1/1 flops)\n MultipleGridAnchorGenerator/mul_9 (1/1 flops)\n MultipleGridAnchorGenerator/mul_8 (1/1 flops)\n MultipleGridAnchorGenerator/mul_7 (1/1 flops)\n MultipleGridAnchorGenerator/mul_6 (1/1 flops)\n MultipleGridAnchorGenerator/mul_58 (1/1 flops)\n MultipleGridAnchorGenerator/mul_57 (1/1 flops)\n MultipleGridAnchorGenerator/mul_5 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_10 (1/1 flops)\n MultipleGridAnchorGenerator/mul_3 (1/1 flops)\n MultipleGridAnchorGenerator/mul_2 (1/1 flops)\n MultipleGridAnchorGenerator/mul_13 (1/1 flops)\n MultipleGridAnchorGenerator/mul_12 (1/1 flops)\n MultipleGridAnchorGenerator/mul_11 (1/1 flops)\n MultipleGridAnchorGenerator/mul_10 (1/1 flops)\n MultipleGridAnchorGenerator/mul_1 (1/1 flops)\n MultipleGridAnchorGenerator/mul (1/1 flops)\n MultipleGridAnchorGenerator/assert_equal_1/Equal (1/1 flops)\n MultipleGridAnchorGenerator/truediv_7 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/Greater (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/ChangeCoordinateFrame/truediv_1 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/ChangeCoordinateFrame/truediv (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/ChangeCoordinateFrame/sub_1 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/ChangeCoordinateFrame/sub (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/Less_1 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/Less (1/1 flops)\n MultipleGridAnchorGenerator/truediv_9 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_8 (1/1 flops)\n Postprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/Minimum (1/1 flops)\n MultipleGridAnchorGenerator/truediv_6 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_5 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_4 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_3 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_2 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_13 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_12 (1/1 flops)\n MultipleGridAnchorGenerator/truediv_11 (1/1 flops)\n\n======================End of Report==========================\n2020-06-16 06:46:35.028420: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n2020-06-16 06:46:35.047173: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:35.047954: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-16 06:46:35.048327: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-16 06:46:35.049954: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-16 06:46:35.051561: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-16 06:46:35.051926: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-16 06:46:35.053970: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-16 06:46:35.064178: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-16 06:46:35.072365: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-16 06:46:35.072560: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:35.073397: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:35.074097: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-16 06:46:35.079605: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2300000000 Hz\n2020-06-16 06:46:35.079832: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x2490bc0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n2020-06-16 06:46:35.079868: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version\n2020-06-16 06:46:35.133530: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:35.134464: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x2490d80 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n2020-06-16 06:46:35.134498: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Tesla K80, Compute Capability 3.7\n2020-06-16 06:46:35.134724: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:35.135439: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-16 06:46:35.135572: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-16 06:46:35.135618: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-16 06:46:35.135684: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-16 06:46:35.135726: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-16 06:46:35.135777: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-16 06:46:35.135823: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-16 06:46:35.135872: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-16 06:46:35.136023: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:35.136820: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:35.137520: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-16 06:46:35.137589: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-16 06:46:35.139152: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-16 06:46:35.139212: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-16 06:46:35.139235: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-16 06:46:35.139428: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:35.140225: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:35.140906: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0.\n2020-06-16 06:46:35.140967: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-10000\nI0616 06:46:35.143435 140645638100864 saver.py:1284] Restoring parameters from training/model.ckpt-10000\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/tools/freeze_graph.py:127: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse standard file APIs to check for files with this prefix.\nW0616 06:46:36.854488 140645638100864 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/tools/freeze_graph.py:127: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse standard file APIs to check for files with this prefix.\n2020-06-16 06:46:37.591266: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:37.592021: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-16 06:46:37.592110: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-16 06:46:37.592155: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-16 06:46:37.592226: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-16 06:46:37.592317: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-16 06:46:37.592389: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-16 06:46:37.592428: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-16 06:46:37.592467: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-16 06:46:37.592613: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:37.593488: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:37.594142: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-16 06:46:37.594216: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-16 06:46:37.594241: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-16 06:46:37.594257: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-16 06:46:37.594409: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:37.595176: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:37.595884: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-10000\nI0616 06:46:37.597453 140645638100864 saver.py:1284] Restoring parameters from training/model.ckpt-10000\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/tools/freeze_graph.py:233: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.convert_variables_to_constants`\nW0616 06:46:38.229506 140645638100864 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/tools/freeze_graph.py:233: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.convert_variables_to_constants`\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/graph_util_impl.py:277: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.extract_sub_graph`\nW0616 06:46:38.229824 140645638100864 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/graph_util_impl.py:277: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.extract_sub_graph`\nINFO:tensorflow:Froze 324 variables.\nI0616 06:46:38.676989 140645638100864 graph_util_impl.py:334] Froze 324 variables.\nINFO:tensorflow:Converted 324 variables to const ops.\nI0616 06:46:38.771919 140645638100864 graph_util_impl.py:394] Converted 324 variables to const ops.\n2020-06-16 06:46:38.910982: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:38.911884: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235\npciBusID: 0000:00:04.0\n2020-06-16 06:46:38.912016: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-16 06:46:38.912072: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-16 06:46:38.912128: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-16 06:46:38.912175: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-16 06:46:38.912247: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-16 06:46:38.912305: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-16 06:46:38.912362: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-16 06:46:38.912557: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:38.913525: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:38.914332: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-16 06:46:38.914397: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-16 06:46:38.914427: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-16 06:46:38.914452: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-16 06:46:38.914679: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:38.915634: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-16 06:46:38.916476: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:326: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.\nW0616 06:46:39.671801 140645638100864 deprecation.py:323] From /content/models/research/object_detection/exporter.py:326: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.\nINFO:tensorflow:No assets to save.\nI0616 06:46:39.672760 140645638100864 builder_impl.py:640] No assets to save.\nINFO:tensorflow:No assets to write.\nI0616 06:46:39.672923 140645638100864 builder_impl.py:460] No assets to write.\nINFO:tensorflow:SavedModel written to: ./fine_tuned_model/saved_model/saved_model.pb\nI0616 06:46:39.979663 140645638100864 builder_impl.py:425] SavedModel written to: ./fine_tuned_model/saved_model/saved_model.pb\nINFO:tensorflow:Writing pipeline config file to ./fine_tuned_model/pipeline.config\nI0616 06:46:40.007677 140645638100864 config_util.py:225] Writing pipeline config file to ./fine_tuned_model/pipeline.config\n" ], [ "!ls {output_directory}", "checkpoint\t\t\tmodel.ckpt.index saved_model\nfrozen_inference_graph.pb\tmodel.ckpt.meta\nmodel.ckpt.data-00000-of-00001\tpipeline.config\n" ] ], [ [ "### Step 11: Use frozen model for inference.", "_____no_output_____" ] ], [ [ "import os\n\npb_fname = os.path.join(os.path.abspath(output_directory), \"frozen_inference_graph.pb\")\nassert os.path.isfile(pb_fname), '`{}` not exist'.format(pb_fname)", "_____no_output_____" ], [ "!ls -alh {pb_fname}", "-rw-r--r-- 1 root root 19M Jun 15 21:52 /content/models/research/fine_tuned_model/frozen_inference_graph.pb\n" ], [ "import os\nimport glob\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = pb_fname\n\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = label_map_pbtxt_fname\n\n# If you want to test the code with your images, just add images files to the PATH_TO_TEST_IMAGES_DIR.\nPATH_TO_TEST_IMAGES_DIR = os.path.join(repo_dir_path, \"test\")\n\nassert os.path.isfile(pb_fname)\nassert os.path.isfile(PATH_TO_LABELS)\nTEST_IMAGE_PATHS = glob.glob(os.path.join(PATH_TO_TEST_IMAGES_DIR, \"*.*\"))\nassert len(TEST_IMAGE_PATHS) > 0, 'No image found in `{}`.'.format(PATH_TO_TEST_IMAGES_DIR)\nprint(TEST_IMAGE_PATHS)", "['/content/object_detection_demo/test/resized_C99P60ThinF_IMG_20150918_141857_cell_26.png', '/content/object_detection_demo/test/resized_C133P94ThinF_IMG_20151004_155144_cell_119.png']\n" ], [ "%cd /content/models/research/object_detection\n\nimport numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\n\n# This is needed since the notebook is stored in the object_detection folder.\nsys.path.append(\"..\")\nfrom object_detection.utils import ops as utils_ops\n\n\n# This is needed to display the images.\n%matplotlib inline\n\n\nfrom object_detection.utils import label_map_util\n\nfrom object_detection.utils import visualization_utils as vis_util\n\n\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=num_classes, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n# Size, in inches, of the output images.\nIMAGE_SIZE = (4, 4)\n\n\ndef run_inference_for_single_image(image, graph):\n with graph.as_default():\n with tf.Session() as sess:\n # Get handles to input and output tensors\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {\n output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in [\n 'num_detections', 'detection_boxes', 'detection_scores',\n 'detection_classes', 'detection_masks'\n ]:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(\n tensor_name)\n if 'detection_masks' in tensor_dict:\n # The following processing is only for single image\n detection_boxes = tf.squeeze(\n tensor_dict['detection_boxes'], [0])\n detection_masks = tf.squeeze(\n tensor_dict['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(\n tensor_dict['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [\n real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [\n real_num_detection, -1, -1])\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n detection_masks, detection_boxes, image.shape[0], image.shape[1])\n detection_masks_reframed = tf.cast(\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict['detection_masks'] = tf.expand_dims(\n detection_masks_reframed, 0)\n image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n # Run inference\n output_dict = sess.run(tensor_dict,\n feed_dict={image_tensor: np.expand_dims(image, 0)})\n\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(\n output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict[\n 'detection_classes'][0].astype(np.uint8)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n if 'detection_masks' in output_dict:\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\n return output_dict\n\n\nfor image_path in TEST_IMAGE_PATHS:\n image = Image.open(image_path)\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n image_np = load_image_into_numpy_array(image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n output_dict = run_inference_for_single_image(image_np, detection_graph)\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=8)\n plt.figure(figsize=IMAGE_SIZE)\n plt.imshow(image_np)", "/content/models/research/object_detection\n" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cbde6c57e4b805ea6f0ad1bb89a78ced69e9e13f
23,661
ipynb
Jupyter Notebook
transfer-learning/Transfer_Learning.ipynb
mgfrantz/deep-learning
dabd919be2440c60aea1d352f36a2cbaf7ce30de
[ "MIT" ]
null
null
null
transfer-learning/Transfer_Learning.ipynb
mgfrantz/deep-learning
dabd919be2440c60aea1d352f36a2cbaf7ce30de
[ "MIT" ]
null
null
null
transfer-learning/Transfer_Learning.ipynb
mgfrantz/deep-learning
dabd919be2440c60aea1d352f36a2cbaf7ce30de
[ "MIT" ]
null
null
null
33
665
0.576856
[ [ [ "# Transfer Learning\n\nMost of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this notebook, you'll be using [VGGNet](https://arxiv.org/pdf/1409.1556.pdf) trained on the [ImageNet dataset](http://www.image-net.org/) as a feature extractor. Below is a diagram of the VGGNet architecture.\n\n<img src=\"assets/cnnarchitecture.jpg\" width=700px>\n\nVGGNet is great because it's simple and has great performance, coming in second in the ImageNet competition. The idea here is that we keep all the convolutional layers, but replace the final fully connected layers with our own classifier. This way we can use VGGNet as a feature extractor for our images then easily train a simple classifier on top of that. What we'll do is take the first fully connected layer with 4096 units, including thresholding with ReLUs. We can use those values as a code for each image, then build a classifier on top of those codes.\n\nYou can read more about transfer learning from [the CS231n course notes](http://cs231n.github.io/transfer-learning/#tf).\n\n## Pretrained VGGNet\n\nWe'll be using a pretrained network from https://github.com/machrisaa/tensorflow-vgg. This code is already included in 'tensorflow_vgg' directory, sdo you don't have to clone it.\n\nThis is a really nice implementation of VGGNet, quite easy to work with. The network has already been trained and the parameters are available from this link. **You'll need to clone the repo into the folder containing this notebook.** Then download the parameter file using the next cell.", "_____no_output_____" ] ], [ [ "from urllib import urlretrieve\nfrom os.path import isfile, isdir\nfrom tqdm import tqdm\n\nvgg_dir = 'tensorflow_vgg/'\n# Make sure vgg exists\nif not isdir(vgg_dir):\n raise Exception(\"VGG directory doesn't exist!\")\n\nclass DLProgress(tqdm):\n last_block = 0\n\n def hook(self, block_num=1, block_size=1, total_size=None):\n self.total = total_size\n self.update((block_num - self.last_block) * block_size)\n self.last_block = block_num\n\nif not isfile(vgg_dir + \"vgg16.npy\"):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='VGG16 Parameters') as pbar:\n urlretrieve(\n 'https://s3.amazonaws.com/content.udacity-data.com/nd101/vgg16.npy',\n vgg_dir + 'vgg16.npy',\n pbar.hook)\nelse:\n print(\"Parameter file already exists!\")", "VGG16 Parameters: 553MB [00:30, 18.3MB/s] \n" ] ], [ [ "## Flower power\n\nHere we'll be using VGGNet to classify images of flowers. To get the flower dataset, run the cell below. This dataset comes from the [TensorFlow inception tutorial](https://www.tensorflow.org/tutorials/image_retraining).", "_____no_output_____" ] ], [ [ "import tarfile\n\ndataset_folder_path = 'flower_photos'\n\nclass DLProgress(tqdm):\n last_block = 0\n\n def hook(self, block_num=1, block_size=1, total_size=None):\n self.total = total_size\n self.update((block_num - self.last_block) * block_size)\n self.last_block = block_num\n\nif not isfile('flower_photos.tar.gz'):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='Flowers Dataset') as pbar:\n urlretrieve(\n 'http://download.tensorflow.org/example_images/flower_photos.tgz',\n 'flower_photos.tar.gz',\n pbar.hook)\n\nif not isdir(dataset_folder_path):\n with tarfile.open('flower_photos.tar.gz') as tar:\n tar.extractall()\n tar.close()", "Flowers Dataset: 229MB [00:02, 92.2MB/s] \n" ] ], [ [ "## ConvNet Codes\n\nBelow, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.\n\nHere we're using the `vgg16` module from `tensorflow_vgg`. The network takes images of size $224 \\times 224 \\times 3$ as input. Then it has 5 sets of convolutional layers. The network implemented here has this structure (copied from [the source code](https://github.com/machrisaa/tensorflow-vgg/blob/master/vgg16.py)):\n\n```\nself.conv1_1 = self.conv_layer(bgr, \"conv1_1\")\nself.conv1_2 = self.conv_layer(self.conv1_1, \"conv1_2\")\nself.pool1 = self.max_pool(self.conv1_2, 'pool1')\n\nself.conv2_1 = self.conv_layer(self.pool1, \"conv2_1\")\nself.conv2_2 = self.conv_layer(self.conv2_1, \"conv2_2\")\nself.pool2 = self.max_pool(self.conv2_2, 'pool2')\n\nself.conv3_1 = self.conv_layer(self.pool2, \"conv3_1\")\nself.conv3_2 = self.conv_layer(self.conv3_1, \"conv3_2\")\nself.conv3_3 = self.conv_layer(self.conv3_2, \"conv3_3\")\nself.pool3 = self.max_pool(self.conv3_3, 'pool3')\n\nself.conv4_1 = self.conv_layer(self.pool3, \"conv4_1\")\nself.conv4_2 = self.conv_layer(self.conv4_1, \"conv4_2\")\nself.conv4_3 = self.conv_layer(self.conv4_2, \"conv4_3\")\nself.pool4 = self.max_pool(self.conv4_3, 'pool4')\n\nself.conv5_1 = self.conv_layer(self.pool4, \"conv5_1\")\nself.conv5_2 = self.conv_layer(self.conv5_1, \"conv5_2\")\nself.conv5_3 = self.conv_layer(self.conv5_2, \"conv5_3\")\nself.pool5 = self.max_pool(self.conv5_3, 'pool5')\n\nself.fc6 = self.fc_layer(self.pool5, \"fc6\")\nself.relu6 = tf.nn.relu(self.fc6)\n```\n\nSo what we want are the values of the first fully connected layer, after being ReLUd (`self.relu6`). To build the network, we use\n\n```\nwith tf.Session() as sess:\n vgg = vgg16.Vgg16()\n input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])\n with tf.name_scope(\"content_vgg\"):\n vgg.build(input_)\n```\n\nThis creates the `vgg` object, then builds the graph with `vgg.build(input_)`. Then to get the values from the layer,\n\n```\nfeed_dict = {input_: images}\ncodes = sess.run(vgg.relu6, feed_dict=feed_dict)\n```", "_____no_output_____" ] ], [ [ "import os\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_vgg import vgg16\nfrom tensorflow_vgg import utils", "_____no_output_____" ], [ "data_dir = 'flower_photos/'\ncontents = os.listdir(data_dir)\nclasses = [each for each in contents if os.path.isdir(data_dir + each)]", "_____no_output_____" ] ], [ [ "Below I'm running images through the VGG network in batches.\n\n> **Exercise:** Below, build the VGG network. Also get the codes from the first fully connected layer (make sure you get the ReLUd values).", "_____no_output_____" ] ], [ [ "# Set the batch size higher if you can fit in in your GPU memory\nbatch_size = 10\ncodes_list = []\nlabels = []\nbatch = []\n\ncodes = None\n\nwith tf.Session() as sess:\n \n vgg = vgg16.Vgg16('./tensorflow_vgg/vgg16.npy')\n \n for each in classes:\n print(\"Starting {} images\".format(each))\n class_path = data_dir + each\n files = os.listdir(class_path)\n for ii, file in enumerate(files, 1):\n # Add images to the current batch\n # utils.load_image crops the input images for us, from the center\n img = utils.load_image(os.path.join(class_path, file))\n batch.append(img.reshape((1, 224, 224, 3)))\n labels.append(each)\n \n # Running the batch through the network to get the codes\n if ii % batch_size == 0 or ii == len(files):\n \n # Image batch to pass to VGG network\n images = np.concatenate(batch)\n \n # TODO: Get the values from the relu6 layer of the VGG network\n codes_batch = \n \n # Here I'm building an array of the codes\n if codes is None:\n codes = codes_batch\n else:\n codes = np.concatenate((codes, codes_batch))\n \n # Reset to start building the next batch\n batch = []\n print('{} images processed'.format(ii))", "_____no_output_____" ], [ "# write codes to file\nwith open('codes', 'w') as f:\n codes.tofile(f)\n \n# write labels to file\nimport csv\nwith open('labels', 'w') as f:\n writer = csv.writer(f, delimiter='\\n')\n writer.writerow(labels)", "_____no_output_____" ] ], [ [ "## Building the Classifier\n\nNow that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.", "_____no_output_____" ] ], [ [ "# read codes and labels from file\nimport csv\n\nwith open('labels') as f:\n reader = csv.reader(f, delimiter='\\n')\n labels = np.array([each for each in reader if len(each) > 0]).squeeze()\nwith open('codes') as f:\n codes = np.fromfile(f, dtype=np.float32)\n codes = codes.reshape((len(labels), -1))", "_____no_output_____" ] ], [ [ "### Data prep\n\nAs usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!\n\n> **Exercise:** From scikit-learn, use [LabelBinarizer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html) to create one-hot encoded vectors from the labels. ", "_____no_output_____" ] ], [ [ "labels_vecs = # Your one-hot encoded labels array here", "_____no_output_____" ] ], [ [ "Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typically, you'll also want to make sure that each smaller set has the same the distribution of classes as it is for the whole data set. The easiest way to accomplish both these goals is to use [`StratifiedShuffleSplit`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html) from scikit-learn.\n\nYou can create the splitter like so:\n```\nss = StratifiedShuffleSplit(n_splits=1, test_size=0.2)\n```\nThen split the data with \n```\nsplitter = ss.split(x, y)\n```\n\n`ss.split` returns a generator of indices. You can pass the indices into the arrays to get the split sets. The fact that it's a generator means you either need to iterate over it, or use `next(splitter)` to get the indices. Be sure to read the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html) and the [user guide](http://scikit-learn.org/stable/modules/cross_validation.html#random-permutations-cross-validation-a-k-a-shuffle-split).\n\n> **Exercise:** Use StratifiedShuffleSplit to split the codes and labels into training, validation, and test sets.", "_____no_output_____" ] ], [ [ "train_x, train_y = \nval_x, val_y = \ntest_x, test_y = ", "_____no_output_____" ], [ "print(\"Train shapes (x, y):\", train_x.shape, train_y.shape)\nprint(\"Validation shapes (x, y):\", val_x.shape, val_y.shape)\nprint(\"Test shapes (x, y):\", test_x.shape, test_y.shape)", "_____no_output_____" ] ], [ [ "If you did it right, you should see these sizes for the training sets:\n\n```\nTrain shapes (x, y): (2936, 4096) (2936, 5)\nValidation shapes (x, y): (367, 4096) (367, 5)\nTest shapes (x, y): (367, 4096) (367, 5)\n```", "_____no_output_____" ], [ "### Classifier layers\n\nOnce you have the convolutional codes, you just need to build a classfier from some fully connected layers. You use the codes as the inputs and the image labels as targets. Otherwise the classifier is a typical neural network.\n\n> **Exercise:** With the codes and labels loaded, build the classifier. Consider the codes as your inputs, each of them are 4096D vectors. You'll want to use a hidden layer and an output layer as your classifier. Remember that the output layer needs to have one unit for each class and a softmax activation function. Use the cross entropy to calculate the cost.", "_____no_output_____" ] ], [ [ "inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]])\nlabels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]])\n\n# TODO: Classifier layers and operations\n\nlogits = # output layer logits\ncost = # cross entropy loss\n\noptimizer = # training optimizer\n\n# Operations for validation/test accuracy\npredicted = tf.nn.softmax(logits)\ncorrect_pred = tf.equal(tf.argmax(predicted, 1), tf.argmax(labels_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))", "_____no_output_____" ] ], [ [ "### Batches!\n\nHere is just a simple way to do batches. I've written it so that it includes all the data. Sometimes you'll throw out some data at the end to make sure you have full batches. Here I just extend the last batch to include the remaining data.", "_____no_output_____" ] ], [ [ "def get_batches(x, y, n_batches=10):\n \"\"\" Return a generator that yields batches from arrays x and y. \"\"\"\n batch_size = len(x)//n_batches\n \n for ii in range(0, n_batches*batch_size, batch_size):\n # If we're not on the last batch, grab data with size batch_size\n if ii != (n_batches-1)*batch_size:\n X, Y = x[ii: ii+batch_size], y[ii: ii+batch_size] \n # On the last batch, grab the rest of the data\n else:\n X, Y = x[ii:], y[ii:]\n # I love generators\n yield X, Y", "_____no_output_____" ] ], [ [ "### Training\n\nHere, we'll train the network.\n\n> **Exercise:** So far we've been providing the training code for you. Here, I'm going to give you a bit more of a challenge and have you write the code to train the network. Of course, you'll be able to see my solution if you need help. Use the `get_batches` function I wrote before to get your batches like `for x, y in get_batches(train_x, train_y)`. Or write your own!", "_____no_output_____" ] ], [ [ "saver = tf.train.Saver()\nwith tf.Session() as sess:\n \n # TODO: Your training code here\n saver.save(sess, \"checkpoints/flowers.ckpt\")", "_____no_output_____" ] ], [ [ "### Testing\n\nBelow you see the test accuracy. You can also see the predictions returned for images.", "_____no_output_____" ] ], [ [ "with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n \n feed = {inputs_: test_x,\n labels_: test_y}\n test_acc = sess.run(accuracy, feed_dict=feed)\n print(\"Test accuracy: {:.4f}\".format(test_acc))", "_____no_output_____" ], [ "%matplotlib inline\n\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage import imread", "_____no_output_____" ] ], [ [ "Below, feel free to choose images and see how the trained classifier predicts the flowers in them.", "_____no_output_____" ] ], [ [ "test_img_path = 'flower_photos/roses/10894627425_ec76bbc757_n.jpg'\ntest_img = imread(test_img_path)\nplt.imshow(test_img)", "_____no_output_____" ], [ "# Run this cell if you don't have a vgg graph built\nif 'vgg' in globals():\n print('\"vgg\" object already exists. Will not create again.')\nelse:\n #create vgg\n with tf.Session() as sess:\n input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])\n vgg = vgg16.Vgg16()\n vgg.build(input_)", "_____no_output_____" ], [ "with tf.Session() as sess:\n img = utils.load_image(test_img_path)\n img = img.reshape((1, 224, 224, 3))\n\n feed_dict = {input_: img}\n code = sess.run(vgg.relu6, feed_dict=feed_dict)\n \nsaver = tf.train.Saver()\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n \n feed = {inputs_: code}\n prediction = sess.run(predicted, feed_dict=feed).squeeze()", "_____no_output_____" ], [ "plt.imshow(test_img)", "_____no_output_____" ], [ "plt.barh(np.arange(5), prediction)\n_ = plt.yticks(np.arange(5), lb.classes_)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cbde6c695dbedf8f50e479f7b8ccd084e8abd587
4,125
ipynb
Jupyter Notebook
chapter5/program5-1.ipynb
robonoriaki/Python_firststep
f99df8384907815bae06d51c310110b353e7fb6c
[ "MIT" ]
null
null
null
chapter5/program5-1.ipynb
robonoriaki/Python_firststep
f99df8384907815bae06d51c310110b353e7fb6c
[ "MIT" ]
null
null
null
chapter5/program5-1.ipynb
robonoriaki/Python_firststep
f99df8384907815bae06d51c310110b353e7fb6c
[ "MIT" ]
null
null
null
18.333333
77
0.426182
[ [ [ "#Chapter5-1\n\nfor i in range(5):\n print('Hello World! round {}'.format(i))", "Hello World! round 0\nHello World! round 1\nHello World! round 2\nHello World! round 3\nHello World! round 4\n" ], [ "for i in range(1,6):\n print('round {}'.format(i))", "round 1\nround 2\nround 3\nround 4\nround 5\n" ], [ "for i in range(1,6,2):\n print('round {}'.format(i))", "round 1\nround 3\nround 5\n" ], [ "for i in ['a','b','c']:\n print('character -> {}'.format(i))", "character -> a\ncharacter -> b\ncharacter -> c\n" ], [ "for i in ('e','f','g'):\n print('character -> {}'.format(i))", "character -> e\ncharacter -> f\ncharacter -> g\n" ], [ "for i in {'x','y','z'}:\n print('character -> {}'.format(i))", "character -> y\ncharacter -> x\ncharacter -> z\n" ], [ "for i in 'hello':\n print(i)", "h\ne\nl\nl\no\n" ], [ "for i, value in enumerate(['a','b','c','d']):\n print('index {0}, value -> {1}'.format(i,value))", "index 0, value -> a\nindex 1, value -> b\nindex 2, value -> c\nindex 3, value -> d\n" ], [ "dic = {'a':123,'b':234,'c':345,'d':456}\n\nfor i, key in enumerate(dic):\n print('index {0}, kye -> {1}, value -> {2}'.format(i,key,dic[key]))", "index 0, kye -> a, value -> 123\nindex 1, kye -> b, value -> 234\nindex 2, kye -> c, value -> 345\nindex 3, kye -> d, value -> 456\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbde8676479cbb6d503ef3f2b96d89d3c6153946
36,492
ipynb
Jupyter Notebook
RoadSegmentor.ipynb
Geoyi/neural-road-inspector
514ef94be6d6f54f0d9ff4ab3c19e6733f4d2ba1
[ "MIT" ]
41
2017-12-15T18:17:02.000Z
2021-11-15T13:53:08.000Z
RoadSegmentor.ipynb
marybarnes37/neural-road-inspector
514ef94be6d6f54f0d9ff4ab3c19e6733f4d2ba1
[ "MIT" ]
2
2017-12-27T18:53:40.000Z
2018-10-04T17:33:43.000Z
RoadSegmentor.ipynb
marybarnes37/neural-road-inspector
514ef94be6d6f54f0d9ff4ab3c19e6733f4d2ba1
[ "MIT" ]
13
2017-12-18T05:08:18.000Z
2022-03-07T01:43:54.000Z
77.642553
1,334
0.636633
[ [ [ "import numpy as np\nimport pandas as pd\nfrom keras.models import *\nfrom keras.layers import Input, merge, Conv2D, MaxPooling2D, UpSampling2D, Dropout, Cropping2D\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, EarlyStopping, ReduceLROnPlateau\n\nfrom datetime import datetime\nimport time\nimport sys\nimport configparser\nimport json\nimport pickle\n\nimport matplotlib.pyplot as plt\n#%matplotlib inline\n\nfrom unet.generator import *\nfrom unet.loss import *\nfrom unet.maskprocessor import *\nfrom unet.visualization import *\nfrom unet.modelfactory import *", "Using TensorFlow backend.\n//anaconda/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.\n warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')\n" ] ], [ [ "This notebook trains the Road Segmentation model. The exported .py script takes in the config filename via a command line parameter. To run this notebook directly in jupyter notebook, please manually set config_file to point to a configuration file (e.g. cfg/default.cfg).", "_____no_output_____" ] ], [ [ "# command line args processing \"python RoadSegmentor.py cfg/your_config.cfg\"\nif len(sys.argv) > 1 and '.cfg' in sys.argv[1]:\n config_file = sys.argv[1]\nelse:\n config_file = 'cfg/default.cfg'\n #print('missing argument. please provide config file as argument. syntax: python RoadSegmentor.py <config_file>')\n #exit(0)\n\nprint('reading configurations from config file: {}'.format(config_file))\n\nsettings = configparser.ConfigParser()\nsettings.read(config_file)\n\nx_data_dir = settings.get('data', 'train_x_dir')\ny_data_dir = settings.get('data', 'train_y_dir')\nprint('x_data_dir: {}'.format(x_data_dir))\nprint('y_data_dir: {}'.format(y_data_dir))\n\ndata_csv_path = settings.get('data', 'train_list_csv')\n\nprint('model configuration options:', settings.options(\"model\"))\n\nmodel_dir = settings.get('model', 'model_dir')\nprint('model_dir: {}'.format(model_dir))\n\ntimestr = time.strftime(\"%Y%m%d-%H%M%S\")\n\nmodel_id = settings.get('model', 'id')\nprint('model: {}'.format(model_id))\n\noptimizer_label = 'Adam' # default\n\nif settings.has_option('model', 'optimizer'):\n optimizer_label = settings.get('model', 'optimizer')\n \nif settings.has_option('model', 'source'):\n model_file = settings.get('model', 'source')\n print('model_file: {}'.format(model_file))\nelse:\n model_file = None\n\nlearning_rate = settings.getfloat('model', 'learning_rate')\nmax_number_epoch = settings.getint('model', 'max_epoch')\nprint('learning rate: {}'.format(learning_rate))\nprint('max epoch: {}'.format(max_number_epoch))\n\nmin_learning_rate = 0.000001\nif settings.has_option('model', 'min_learning_rate'):\n min_learning_rate = settings.getfloat('model', 'min_learning_rate')\nprint('minimum learning rate: {}'.format(min_learning_rate))\n\nlr_reduction_factor = 0.1\nif settings.has_option('model', 'lr_reduction_factor'):\n lr_reduction_factor = settings.getfloat('model', 'lr_reduction_factor')\nprint('lr_reduction_factor: {}'.format(lr_reduction_factor))\n\nbatch_size = settings.getint('model', 'batch_size') \nprint('batch size: {}'.format(batch_size))\n\ninput_width = settings.getint('model', 'input_width')\ninput_height = settings.getint('model', 'input_height')", "reading configurations from config file: cfg/default.cfg\nx_data_dir: /Users/jkwok/Documents/Insight/tools/jTileDownloader 2/mapbox-sat@2x/\ny_data_dir: /Users/jkwok/Documents/Insight/tools/jTileDownloader 2/mapbox-st@2x/\n('model configuration options:', [u'id', u'optimizer', u'learning_rate', u'min_learning_rate', u'lr_reduction_factor', u'max_epoch', u'batch_size', u'model_dir'])\nmodel_dir: /Users/jkwok/Documents/Insights/models/\nmodel: Dilated_Unet\nlearning rate: 0.0001\nmax epoch: 32\nminimum learning rate: 1e-07\nlr_reduction_factor: 0.2\nbatch size: 16\n" ], [ "img_gen = CustomImgGenerator(x_data_dir, y_data_dir, data_csv_path)\n\ntrain_gen = img_gen.trainGen(batch_size=batch_size, is_Validation=False)\n\nvalidation_gen = img_gen.trainGen(batch_size=batch_size, is_Validation=True)", "_____no_output_____" ], [ "timestr = time.strftime(\"%Y%m%d-%H%M%S\")\nmodel_filename = model_dir + '{}-{}.hdf5'.format(model_id, timestr)\nprint('model checkpoint file path: {}'.format(model_filename))\n\n# Early stopping prevents overfitting on training data\n# Make sure the patience value for EarlyStopping > patience value for ReduceLROnPlateau. \n# Otherwise ReduceLROnPlateau will never be called.\nearly_stop = EarlyStopping(monitor='val_loss',\n patience=3,\n min_delta=0, \n verbose=1,\n mode='auto')\n\nmodel_checkpoint = ModelCheckpoint(model_filename,\n monitor='val_loss',\n verbose=1,\n save_best_only=True)\n\nreduceLR = ReduceLROnPlateau(monitor='val_loss',\n factor=lr_reduction_factor,\n patience=2,\n verbose=1,\n min_lr=min_learning_rate,\n epsilon=1e-4)", "model checkpoint file path: /Users/jkwok/Documents/Insights/models/Dilated_Unet-20170924-204045.hdf5\n" ], [ "training_start_time = datetime.now()\n\nnumber_validations = img_gen.validation_samples_count()\n\nsamples_per_epoch = img_gen.training_samples_count()\n\nmodelFactory = ModelFactory(num_channels = 3, \n img_rows = input_height,\n img_cols = input_width)\n\nif model_file is not None:\n model = load_model(model_dir + model_file,\n custom_objects={'dice_coef_loss': dice_coef_loss, \n 'dice_coef': dice_coef, \n 'binary_crossentropy_dice_loss': binary_crossentropy_dice_loss})\nelse:\n model = modelFactory.get_model(model_id)\n\nprint(model.summary())\n\nif optimizer_label == 'Adam':\n optimizer = Adam(lr = learning_rate)\nelif optimizer_label == 'RMSprop':\n optimizer = RMSprop(lr = learning_rate)\nelse:\n raise ValueError('unsupported optimizer: {}'.format(optimizer_label))\n\nmodel.compile(optimizer = optimizer,\n loss = dice_coef_loss,\n metrics = ['accuracy', dice_coef])", "____________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n====================================================================================================\ninput_1 (InputLayer) (None, 512, 512, 3) 0 \n____________________________________________________________________________________________________\nconv2d_1 (Conv2D) (None, 512, 512, 32) 896 input_1[0][0] \n____________________________________________________________________________________________________\nactivation_1 (Activation) (None, 512, 512, 32) 0 conv2d_1[0][0] \n____________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 512, 512, 32) 9248 activation_1[0][0] \n____________________________________________________________________________________________________\nactivation_2 (Activation) (None, 512, 512, 32) 0 conv2d_2[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 256, 256, 32) 0 activation_2[0][0] \n____________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 256, 256, 64) 18496 max_pooling2d_1[0][0] \n____________________________________________________________________________________________________\nactivation_3 (Activation) (None, 256, 256, 64) 0 conv2d_3[0][0] \n____________________________________________________________________________________________________\nconv2d_4 (Conv2D) (None, 256, 256, 64) 36928 activation_3[0][0] \n____________________________________________________________________________________________________\nactivation_4 (Activation) (None, 256, 256, 64) 0 conv2d_4[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_2 (MaxPooling2D) (None, 128, 128, 64) 0 activation_4[0][0] \n____________________________________________________________________________________________________\nconv2d_5 (Conv2D) (None, 128, 128, 128) 73856 max_pooling2d_2[0][0] \n____________________________________________________________________________________________________\nactivation_5 (Activation) (None, 128, 128, 128) 0 conv2d_5[0][0] \n____________________________________________________________________________________________________\nconv2d_6 (Conv2D) (None, 128, 128, 128) 147584 activation_5[0][0] \n____________________________________________________________________________________________________\nactivation_6 (Activation) (None, 128, 128, 128) 0 conv2d_6[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_3 (MaxPooling2D) (None, 64, 64, 128) 0 activation_6[0][0] \n____________________________________________________________________________________________________\nconv2d_7 (Conv2D) (None, 64, 64, 256) 295168 max_pooling2d_3[0][0] \n____________________________________________________________________________________________________\nactivation_7 (Activation) (None, 64, 64, 256) 0 conv2d_7[0][0] \n____________________________________________________________________________________________________\nconv2d_8 (Conv2D) (None, 64, 64, 256) 590080 activation_7[0][0] \n____________________________________________________________________________________________________\nactivation_8 (Activation) (None, 64, 64, 256) 0 conv2d_8[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_4 (MaxPooling2D) (None, 32, 32, 256) 0 activation_8[0][0] \n____________________________________________________________________________________________________\nconv2d_9 (Conv2D) (None, 32, 32, 512) 1180160 max_pooling2d_4[0][0] \n____________________________________________________________________________________________________\nactivation_9 (Activation) (None, 32, 32, 512) 0 conv2d_9[0][0] \n____________________________________________________________________________________________________\nconv2d_10 (Conv2D) (None, 32, 32, 512) 2359808 activation_9[0][0] \n____________________________________________________________________________________________________\nactivation_10 (Activation) (None, 32, 32, 512) 0 conv2d_10[0][0] \n____________________________________________________________________________________________________\nconv2d_11 (Conv2D) (None, 32, 32, 512) 2359808 activation_10[0][0] \n____________________________________________________________________________________________________\nactivation_11 (Activation) (None, 32, 32, 512) 0 conv2d_11[0][0] \n____________________________________________________________________________________________________\nconv2d_12 (Conv2D) (None, 32, 32, 512) 2359808 activation_11[0][0] \n____________________________________________________________________________________________________\nactivation_12 (Activation) (None, 32, 32, 512) 0 conv2d_12[0][0] \n____________________________________________________________________________________________________\nconv2d_13 (Conv2D) (None, 32, 32, 512) 2359808 activation_12[0][0] \n____________________________________________________________________________________________________\nactivation_13 (Activation) (None, 32, 32, 512) 0 conv2d_13[0][0] \n____________________________________________________________________________________________________\nconv2d_transpose_1 (Conv2DTransp (None, 64, 64, 256) 524544 activation_13[0][0] \n____________________________________________________________________________________________________\nconcatenate_1 (Concatenate) (None, 64, 64, 512) 0 conv2d_transpose_1[0][0] \n activation_8[0][0] \n____________________________________________________________________________________________________\nconv2d_14 (Conv2D) (None, 64, 64, 256) 1179904 concatenate_1[0][0] \n____________________________________________________________________________________________________\nactivation_14 (Activation) (None, 64, 64, 256) 0 conv2d_14[0][0] \n____________________________________________________________________________________________________\nconv2d_15 (Conv2D) (None, 64, 64, 256) 590080 activation_14[0][0] \n____________________________________________________________________________________________________\nactivation_15 (Activation) (None, 64, 64, 256) 0 conv2d_15[0][0] \n____________________________________________________________________________________________________\nconv2d_transpose_2 (Conv2DTransp (None, 128, 128, 128) 131200 activation_15[0][0] \n____________________________________________________________________________________________________\nconcatenate_2 (Concatenate) (None, 128, 128, 256) 0 conv2d_transpose_2[0][0] \n activation_6[0][0] \n____________________________________________________________________________________________________\nconv2d_16 (Conv2D) (None, 128, 128, 128) 295040 concatenate_2[0][0] \n____________________________________________________________________________________________________\nactivation_16 (Activation) (None, 128, 128, 128) 0 conv2d_16[0][0] \n____________________________________________________________________________________________________\nconv2d_17 (Conv2D) (None, 128, 128, 128) 147584 activation_16[0][0] \n____________________________________________________________________________________________________\nactivation_17 (Activation) (None, 128, 128, 128) 0 conv2d_17[0][0] \n____________________________________________________________________________________________________\nconv2d_transpose_3 (Conv2DTransp (None, 256, 256, 64) 32832 activation_17[0][0] \n____________________________________________________________________________________________________\nconcatenate_3 (Concatenate) (None, 256, 256, 128) 0 conv2d_transpose_3[0][0] \n activation_4[0][0] \n____________________________________________________________________________________________________\nconv2d_18 (Conv2D) (None, 256, 256, 64) 73792 concatenate_3[0][0] \n____________________________________________________________________________________________________\nactivation_18 (Activation) (None, 256, 256, 64) 0 conv2d_18[0][0] \n____________________________________________________________________________________________________\nconv2d_19 (Conv2D) (None, 256, 256, 64) 36928 activation_18[0][0] \n____________________________________________________________________________________________________\nactivation_19 (Activation) (None, 256, 256, 64) 0 conv2d_19[0][0] \n____________________________________________________________________________________________________\nconv2d_transpose_4 (Conv2DTransp (None, 512, 512, 32) 8224 activation_19[0][0] \n____________________________________________________________________________________________________\nconcatenate_4 (Concatenate) (None, 512, 512, 64) 0 conv2d_transpose_4[0][0] \n activation_2[0][0] \n____________________________________________________________________________________________________\nconv2d_20 (Conv2D) (None, 512, 512, 32) 18464 concatenate_4[0][0] \n____________________________________________________________________________________________________\nactivation_20 (Activation) (None, 512, 512, 32) 0 conv2d_20[0][0] \n____________________________________________________________________________________________________\nconv2d_21 (Conv2D) (None, 512, 512, 32) 9248 activation_20[0][0] \n____________________________________________________________________________________________________\nactivation_21 (Activation) (None, 512, 512, 32) 0 conv2d_21[0][0] \n____________________________________________________________________________________________________\nconv2d_22 (Conv2D) (None, 512, 512, 2) 66 activation_21[0][0] \n____________________________________________________________________________________________________\nlambda_1 (Lambda) (None, 512, 512, 2) 0 conv2d_22[0][0] \n____________________________________________________________________________________________________\nactivation_22 (Activation) (None, 512, 512, 2) 0 lambda_1[0][0] \n====================================================================================================\nTotal params: 14,839,554\nTrainable params: 14,839,554\nNon-trainable params: 0\n____________________________________________________________________________________________________\nNone\n" ], [ "history = model.fit_generator(generator=train_gen,\n steps_per_epoch=np.ceil(float(samples_per_epoch) / float(batch_size)),\n validation_data=validation_gen,\n validation_steps=np.ceil(float(number_validations) / float(batch_size)),\n epochs=max_number_epoch,\n verbose=1,\n callbacks=[model_checkpoint, early_stop, reduceLR])\n\ntime_spent_trianing = datetime.now() - training_start_time\nprint('model training complete. time spent: {}'.format(time_spent_trianing))", "Epoch 1/32\n" ], [ "print(history.history)\n\nhistoryFilePath = model_dir + '{}-{}-train-history.png'.format(model_id, timestr)\ntrainingHistoryPlot(model_id + timestr, historyFilePath, history.history)\n\npickleFilePath = model_dir + '{}-{}-history-dict.pickle'.format(model_id, timestr)\nwith open(pickleFilePath, 'wb') as handle:\n pickle.dump(history.history, handle, protocol=pickle.HIGHEST_PROTOCOL)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
cbdea0e9948992f2f972971c9b6f4d788dd32646
13,057
ipynb
Jupyter Notebook
Graph_Database/purchase_anomaly/purchase anomaly.ipynb
hanhanwu/Hanhan_Data_Science_Practice
ac48401121062d03f9983f6a8c7f7adb0ab9b616
[ "MIT" ]
24
2016-05-20T00:50:57.000Z
2020-10-01T15:42:16.000Z
Graph_Database/purchase_anomaly/purchase anomaly.ipynb
hanhanwu/Hanhan_Data_Science_Practice
ac48401121062d03f9983f6a8c7f7adb0ab9b616
[ "MIT" ]
null
null
null
Graph_Database/purchase_anomaly/purchase anomaly.ipynb
hanhanwu/Hanhan_Data_Science_Practice
ac48401121062d03f9983f6a8c7f7adb0ab9b616
[ "MIT" ]
14
2018-01-29T06:08:59.000Z
2020-10-03T08:08:31.000Z
48.359259
410
0.564525
[ [ [ "from neo4j import GraphDatabase\nimport json", "_____no_output_____" ], [ "with open('credentials.json') as json_file:\n credentials = json.load(json_file)\n\nusername = credentials['username']\npwd = credentials['password']", "_____no_output_____" ] ], [ [ "### NOTE ❣️\n\n* BEFORE running this, still need to run `bin\\neo4j console` to enable bolt on 127.0.0.1:7687\n* When the queryyou wrote is wrong, the error will show connection or credential has problem, you don't really need to restart the server, after the query has been corrected, everything will be running fine.\n\n#### Userful Links\n* Results can be outputed: https://neo4j.com/docs/api/python-driver/current/results.html", "_____no_output_____" ] ], [ [ "driver = GraphDatabase.driver(\"bolt://localhost:7687\", auth=(username, pwd))", "_____no_output_____" ], [ "def delete_all(tx):\n result = tx.run(\"\"\"match (n) detach delete n\"\"\").single()\n if result is None:\n print('Removed All!')\n\ndef create_entity(tx, entity_id, entity_name, entity_properties):\n query = \"\"\"CREATE (\"\"\"+entity_id+\"\"\": \"\"\"+entity_name+entity_properties+\"\"\")\"\"\"\n result = tx.run(query)\n \ndef display_all(tx, query):\n results = tx.run(query)\n for record in results:\n print(record)\n return results.graph()", "_____no_output_____" ], [ "with driver.session() as session:\n session.write_transaction(delete_all)\n session.write_transaction(create_entity, entity_id='Alice', entity_name='Client',\n entity_properties = \"{name:'Alice', ip: '1.1.1.1', shipping_address: 'a place', billing_address: 'a place'}\")\n \n graph = session.read_transaction(display_all, query=\"MATCH (c:Client) RETURN c\")", "Removed All!\n<Record c=<Node id=18 labels={'Client'} properties={'name': 'Alice', 'billing_address': 'a place', 'shipping_address': 'a place', 'ip': '1.1.1.1'}>>\n" ], [ "def create_all(tx, query):\n result = tx.run(query)\n \n query = \"\"\"\n // Clients\n CREATE (Alice:Client {name:'Alice', ip: '1.1.1.1', shipping_address: 'a place', billing_address: 'a place'})\n CREATE (Bob:Client {name:'Bob', ip: '1.1.1.2', shipping_address: 'b place', billing_address: 'b place'})\n CREATE (Cindy:Client {name:'Cindy', ip: '1.1.1.3', shipping_address: 'c place', billing_address: 'c place'})\n CREATE (Diana:Client {name:'Diana', ip: '1.1.1.4', shipping_address: 'd place', billing_address: 'd place'})\n CREATE (Emily:Client {name:'Emily', ip: '1.1.1.5', shipping_address: 'e place', billing_address: 'e place'})\n CREATE (Fiona:Client {name:'Fiona', ip: '1.1.1.6', shipping_address: 'f place', billing_address: 'f place'})\n\n // Products\n CREATE (prod1:Product {name: 'strawberry ice-cream', category: 'ice-cream', price: 6.9, unit: 'box'})\n CREATE (prod2:Product {name: 'mint ice-cream', category: 'ice-cream', price: 6.9, unit: 'box'})\n CREATE (prod3:Product {name: 'mango ice-cream', category: 'ice-cream', price: 6.9, unit: 'box'})\n CREATE (prod4:Product {name: 'cheesecake ice-cream', category: 'ice-cream', price: 7.9, unit: 'box'})\n CREATE (prod5:Product {name: 'orange', category: 'furit', unit: 'lb', price: 2.6, unit: 'box'})\n CREATE (prod6:Product {name: 'dragon fruit', category: 'furit', unit: 'lb', price: 4.8, unit: 'box'})\n CREATE (prod7:Product {name: 'kiwi', category: 'furit', unit: 'lb', price: 5.3, unit: 'box'})\n CREATE (prod8:Product {name: 'cherry', category: 'furit', unit: 'lb', price: 4.8, unit: 'box'})\n CREATE (prod9:Product {name: 'strawberry', category: 'furit', unit: 'lb', price: 3.9, unit: 'box'})\n\n // Orders\n CREATE (d1:Order {id:'d1', name:'d1', deliverdate:'20190410', status:'delivered'})\n CREATE (d2:Order {id:'d2', name:'d2', deliverdate:'20130708', status:'delivered'})\n CREATE (d3:Order {id:'d3', name:'d3', deliverdate:'20021201', status:'delivered'})\n CREATE (d4:Order {id:'d4', name:'d4', deliverdate:'20040612', status:'delivered'})\n CREATE (d5:Order {id:'d5', name:'d5', deliverdate:'20110801', status:'delivered'})\n CREATE (d6:Order {id:'d6', name:'d6',deliverdate:'20171212', status:'delivered'})\n\n // Link Clients, Orders and ProductsCREATE\n CREATE\n (Alice)-[:PLACED]->(d1)-[:CONTAINS {quantity:1}]->(prod1),\n (d1)-[:CONTAINS {quantity:2}]->(prod2),\n (Bob)-[:PLACED]->(d2)-[:CONTAINS {quantity:2}]->(prod1),\n (d2)-[:CONTAINS {quantity:6}]->(prod7),\n (Cindy)-[:PLACED]->(d3)-[:CONTAINS {quantity:1}]->(prod9),\n (Alice)-[:PLACED]->(d4)-[:CONTAINS {quantity:100}]->(prod4),\n (Alice)-[:PLACED]->(d5)-[:CONTAINS {quantity:10}]->(prod8),\n (Alice)-[:PLACED]->(d6)-[:CONTAINS {quantity:1}]->(prod7);\n \"\"\"", "_____no_output_____" ], [ "with driver.session() as session:\n session.write_transaction(delete_all)\n session.write_transaction(create_all, query)\n \n graph = session.read_transaction(display_all, query=\"\"\"MATCH (c:Client)-[:PLACED]-(o)-[:CONTAINS]->(p)\n return c, o, p;\"\"\")", "Removed All!\n<Record c=<Node id=22 labels={'Client'} properties={'name': 'Alice', 'billing_address': 'a place', 'shipping_address': 'a place', 'ip': '1.1.1.1'}> o=<Node id=17 labels={'Order'} properties={'name': 'd6', 'id': 'd6', 'deliverdate': '20171212', 'status': 'delivered'}> p=<Node id=12 labels={'Product'} properties={'name': 'kiwi', 'unit': 'box', 'category': 'furit', 'price': 5.3}>>\n<Record c=<Node id=22 labels={'Client'} properties={'name': 'Alice', 'billing_address': 'a place', 'shipping_address': 'a place', 'ip': '1.1.1.1'}> o=<Node id=16 labels={'Order'} properties={'name': 'd5', 'id': 'd5', 'deliverdate': '20110801', 'status': 'delivered'}> p=<Node id=13 labels={'Product'} properties={'name': 'cherry', 'unit': 'box', 'category': 'furit', 'price': 4.8}>>\n<Record c=<Node id=22 labels={'Client'} properties={'name': 'Alice', 'billing_address': 'a place', 'shipping_address': 'a place', 'ip': '1.1.1.1'}> o=<Node id=15 labels={'Order'} properties={'name': 'd4', 'id': 'd4', 'deliverdate': '20040612', 'status': 'delivered'}> p=<Node id=9 labels={'Product'} properties={'name': 'cheesecake ice-cream', 'unit': 'box', 'category': 'ice-cream', 'price': 7.9}>>\n<Record c=<Node id=22 labels={'Client'} properties={'name': 'Alice', 'billing_address': 'a place', 'shipping_address': 'a place', 'ip': '1.1.1.1'}> o=<Node id=0 labels={'Order'} properties={'name': 'd1', 'id': 'd1', 'deliverdate': '20190410', 'status': 'delivered'}> p=<Node id=7 labels={'Product'} properties={'name': 'mint ice-cream', 'unit': 'box', 'category': 'ice-cream', 'price': 6.9}>>\n<Record c=<Node id=22 labels={'Client'} properties={'name': 'Alice', 'billing_address': 'a place', 'shipping_address': 'a place', 'ip': '1.1.1.1'}> o=<Node id=0 labels={'Order'} properties={'name': 'd1', 'id': 'd1', 'deliverdate': '20190410', 'status': 'delivered'}> p=<Node id=6 labels={'Product'} properties={'name': 'strawberry ice-cream', 'unit': 'box', 'category': 'ice-cream', 'price': 6.9}>>\n<Record c=<Node id=23 labels={'Client'} properties={'name': 'Bob', 'billing_address': 'b place', 'shipping_address': 'b place', 'ip': '1.1.1.2'}> o=<Node id=1 labels={'Order'} properties={'name': 'd2', 'id': 'd2', 'deliverdate': '20130708', 'status': 'delivered'}> p=<Node id=12 labels={'Product'} properties={'name': 'kiwi', 'unit': 'box', 'category': 'furit', 'price': 5.3}>>\n<Record c=<Node id=23 labels={'Client'} properties={'name': 'Bob', 'billing_address': 'b place', 'shipping_address': 'b place', 'ip': '1.1.1.2'}> o=<Node id=1 labels={'Order'} properties={'name': 'd2', 'id': 'd2', 'deliverdate': '20130708', 'status': 'delivered'}> p=<Node id=6 labels={'Product'} properties={'name': 'strawberry ice-cream', 'unit': 'box', 'category': 'ice-cream', 'price': 6.9}>>\n<Record c=<Node id=24 labels={'Client'} properties={'name': 'Cindy', 'billing_address': 'c place', 'shipping_address': 'c place', 'ip': '1.1.1.3'}> o=<Node id=2 labels={'Order'} properties={'name': 'd3', 'id': 'd3', 'deliverdate': '20021201', 'status': 'delivered'}> p=<Node id=14 labels={'Product'} properties={'name': 'strawberry', 'unit': 'box', 'category': 'furit', 'price': 3.9}>>\n" ], [ "graph", "_____no_output_____" ], [ "with driver.session() as session:\n graph = session.read_transaction(display_all, query=\"\"\"MATCH (c:Client {name:'Alice'})-[:PLACED]->(o)-[cts:CONTAINS]->(p)\nWITH c, o, SUM(cts.quantity * p.price) as order_price\n ORDER BY o.deliverdate\nWITH c.name AS name, COLLECT(o) AS os, COLLECT(order_price) as ops\nUNWIND [i IN RANGE(0, SIZE(os)-1) |\n {name: name, id: os[i].id, current_order_cost: round(ops[i]),\n other_orders: [x IN os[0..i] + os[i+1..SIZE(os)] | x.id],\n other_orders_costs: [x IN ops[0..i] + ops[i+1..SIZE(os)] | round(x)]\n }] AS result\nWITH result.name as name, result.id as order_id, result.current_order_cost as current_order_cost,\nresult.other_orders as other_orders, result.other_orders_costs as other_orders_costs\nUNWIND(other_orders_costs) as unwind_other_orders_costs\nreturn name, order_id, current_order_cost, other_orders, other_orders_costs,\nround(stDev(unwind_other_orders_costs)) as other_costs_std;\"\"\")", "<Record name='Alice' order_id='d4' current_order_cost=790.0 other_orders=['d5', 'd6', 'd1'] other_orders_costs=[48.0, 5.0, 21.0] other_costs_std=22.0>\n<Record name='Alice' order_id='d5' current_order_cost=48.0 other_orders=['d4', 'd6', 'd1'] other_orders_costs=[790.0, 5.0, 21.0] other_costs_std=449.0>\n<Record name='Alice' order_id='d6' current_order_cost=5.0 other_orders=['d4', 'd5', 'd1'] other_orders_costs=[790.0, 48.0, 21.0] other_costs_std=436.0>\n<Record name='Alice' order_id='d1' current_order_cost=21.0 other_orders=['d4', 'd5', 'd6'] other_orders_costs=[790.0, 48.0, 5.0] other_costs_std=441.0>\n" ], [ "graph", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdeb0e02ddd7117285af0cad942a6bef86ce93f
54,919
ipynb
Jupyter Notebook
CNN/VGGNET16.ipynb
KarinkiManikanta/Deep-Learning
05231af420f86f59a7635873bf9d1d602f414e77
[ "MIT" ]
null
null
null
CNN/VGGNET16.ipynb
KarinkiManikanta/Deep-Learning
05231af420f86f59a7635873bf9d1d602f414e77
[ "MIT" ]
null
null
null
CNN/VGGNET16.ipynb
KarinkiManikanta/Deep-Learning
05231af420f86f59a7635873bf9d1d602f414e77
[ "MIT" ]
null
null
null
59.62975
13,736
0.686229
[ [ [ "import matplotlib.pyplot as plt\nfrom tensorflow.keras.layers import Input,Conv2D\nfrom tensorflow.keras.layers import MaxPool2D,Flatten,Dense\nfrom tensorflow.keras import Model", "_____no_output_____" ] ], [ [ "![](https://lh3.googleusercontent.com/-WuPVxynI_ss/X_6DG-R179I/AAAAAAAAsSc/S0rVDJtOW_Q7bbPdOC2xnvRn3DpRbbe6wCK8BGAsYHg/s0/2021-01-12.png)", "_____no_output_____" ] ], [ [ "input=Input(shape=(224,224,3)) ## Input is a RGB image so 3 channel", "_____no_output_____" ] ], [ [ "## Conv Block-1", "_____no_output_____" ] ], [ [ "x=Conv2D(filters=128,kernel_size=3,padding='same',activation='relu')(input)\nx=Conv2D(filters=128,kernel_size=3,padding='same',activation='relu')(x)\nx=MaxPool2D(pool_size=2,strides=2,padding='same')(x)\n", "_____no_output_____" ] ], [ [ "## Conv Block-2", "_____no_output_____" ] ], [ [ "x=Conv2D(filters=128,kernel_size=3,padding='same',activation='relu')(x)\nx=Conv2D(filters=128,kernel_size=3,padding='same',activation='relu')(x)\nx=MaxPool2D(pool_size=2,strides=2,padding='same')(x)", "_____no_output_____" ] ], [ [ "### Conv Block-3", "_____no_output_____" ] ], [ [ "x=Conv2D(filters=256,kernel_size=3,padding='same',activation='relu')(x)\nx=Conv2D(filters=256,kernel_size=3,padding='same',activation='relu')(x)\nx=Conv2D(filters=256,kernel_size=3,padding='same',activation='relu')(x)\nx=MaxPool2D(pool_size=2,strides=2,padding='same')(x)", "_____no_output_____" ] ], [ [ "## Conv Block-4", "_____no_output_____" ] ], [ [ "x=Conv2D(filters=512,kernel_size=3,padding='same',activation='relu')(x)\nx=Conv2D(filters=512,kernel_size=3,padding='same',activation='relu')(x)\nx=Conv2D(filters=512,kernel_size=3,padding='same',activation='relu')(x)\nx=MaxPool2D(pool_size=2,strides=2,padding='same')(x)", "_____no_output_____" ] ], [ [ "## Conv Block-5", "_____no_output_____" ] ], [ [ "x=Conv2D(filters=512,kernel_size=3,padding='same',activation='relu')(x)\nx=Conv2D(filters=512,kernel_size=3,padding='same',activation='relu')(x)\nx=Conv2D(filters=512,kernel_size=3,padding='same',activation='relu')(x)\nx=MaxPool2D(pool_size=2,strides=2,padding='same')(x)", "_____no_output_____" ], [ "x=Flatten()(x)\nx=Dense(units=4096,activation='relu')(x)\nx=Dense(units=4096,activation='relu')(x)\noutput=Dense(units=1000,activation='softmax')(x)", "_____no_output_____" ], [ "model=Model(inputs=input,outputs=output)\nmodel.summary()", "Model: \"model_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 224, 224, 3)] 0 \n_________________________________________________________________\nconv2d_3 (Conv2D) (None, 224, 224, 128) 3584 \n_________________________________________________________________\nconv2d_4 (Conv2D) (None, 224, 224, 128) 147584 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 112, 112, 128) 0 \n_________________________________________________________________\nconv2d_5 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nconv2d_6 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 56, 56, 128) 0 \n_________________________________________________________________\nconv2d_7 (Conv2D) (None, 56, 56, 512) 590336 \n_________________________________________________________________\nconv2d_8 (Conv2D) (None, 56, 56, 512) 2359808 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 28, 28, 512) 0 \n_________________________________________________________________\nconv2d_9 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nconv2d_10 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nmax_pooling2d_3 (MaxPooling2 (None, 14, 14, 512) 0 \n_________________________________________________________________\nconv2d_11 (Conv2D) (None, 14, 14, 256) 1179904 \n_________________________________________________________________\nconv2d_12 (Conv2D) (None, 14, 14, 256) 590080 \n_________________________________________________________________\nmax_pooling2d_4 (MaxPooling2 (None, 7, 7, 256) 0 \n_________________________________________________________________\nconv2d_13 (Conv2D) (None, 7, 7, 512) 1180160 \n_________________________________________________________________\nconv2d_14 (Conv2D) (None, 7, 7, 512) 2359808 \n_________________________________________________________________\nmax_pooling2d_5 (MaxPooling2 (None, 4, 4, 512) 0 \n_________________________________________________________________\nconv2d_15 (Conv2D) (None, 4, 4, 128) 589952 \n_________________________________________________________________\nconv2d_16 (Conv2D) (None, 4, 4, 128) 147584 \n_________________________________________________________________\nmax_pooling2d_6 (MaxPooling2 (None, 2, 2, 128) 0 \n_________________________________________________________________\nconv2d_17 (Conv2D) (None, 2, 2, 256) 295168 \n_________________________________________________________________\nconv2d_18 (Conv2D) (None, 2, 2, 256) 590080 \n_________________________________________________________________\nconv2d_19 (Conv2D) (None, 2, 2, 256) 590080 \n_________________________________________________________________\nmax_pooling2d_7 (MaxPooling2 (None, 1, 1, 256) 0 \n_________________________________________________________________\nconv2d_20 (Conv2D) (None, 1, 1, 512) 1180160 \n_________________________________________________________________\nconv2d_21 (Conv2D) (None, 1, 1, 512) 2359808 \n_________________________________________________________________\nconv2d_22 (Conv2D) (None, 1, 1, 512) 2359808 \n_________________________________________________________________\nmax_pooling2d_8 (MaxPooling2 (None, 1, 1, 512) 0 \n_________________________________________________________________\nconv2d_23 (Conv2D) (None, 1, 1, 512) 2359808 \n_________________________________________________________________\nconv2d_24 (Conv2D) (None, 1, 1, 512) 2359808 \n_________________________________________________________________\nconv2d_25 (Conv2D) (None, 1, 1, 512) 2359808 \n_________________________________________________________________\nmax_pooling2d_9 (MaxPooling2 (None, 1, 1, 512) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 512) 0 \n_________________________________________________________________\ndense (Dense) (None, 4096) 2101248 \n_________________________________________________________________\ndense_1 (Dense) (None, 4096) 16781312 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 4096) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 4096) 16781312 \n_________________________________________________________________\ndense_4 (Dense) (None, 4096) 16781312 \n_________________________________________________________________\ndense_5 (Dense) (None, 1000) 4097000 \n=================================================================\nTotal params: 85,160,296\nTrainable params: 85,160,296\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### Keras pretrined weights", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nfrom tensorflow.keras.applications.vgg16 import VGG16\nimport numpy as np\nimport cv2", "_____no_output_____" ], [ "model=VGG16(weights='imagenet',include_top=True)\nmodel.compile(optimizer='sgd',loss='categorical_crossentropy')", "Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels.h5\n553467904/553467096 [==============================] - 69s 0us/step\n" ], [ "im= cv2.resize( cv2.imread('/home/hemanth/Documents/DeepLearning/CNN/2021-01-12.jpeg'),(224,224))\nim=np.expand_dims(im,axis=0)\nim.astype(np.float32)", "_____no_output_____" ], [ "out=model.predict(im)\nindex=np.argmax(out)\nprint(index)", "820\n" ], [ "plt.plot(out)\nplt.show()", "_____no_output_____" ] ], [ [ "## feature Extraction in VGG16", "_____no_output_____" ] ], [ [ "from tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.vgg16 import preprocess_input\nfrom tensorflow.keras import models\nbase_model=VGG16(weights='imagenet',include_top=True)\nprint(base_model)\nfor i, layer in enumerate(base_model.layers):\n print(i,layer.name,layer.output_shape)", "<tensorflow.python.keras.engine.functional.Functional object at 0x7efe9cc8bd60>\n0 input_3 [(None, 224, 224, 3)]\n1 block1_conv1 (None, 224, 224, 64)\n2 block1_conv2 (None, 224, 224, 64)\n3 block1_pool (None, 112, 112, 64)\n4 block2_conv1 (None, 112, 112, 128)\n5 block2_conv2 (None, 112, 112, 128)\n6 block2_pool (None, 56, 56, 128)\n7 block3_conv1 (None, 56, 56, 256)\n8 block3_conv2 (None, 56, 56, 256)\n9 block3_conv3 (None, 56, 56, 256)\n10 block3_pool (None, 28, 28, 256)\n11 block4_conv1 (None, 28, 28, 512)\n12 block4_conv2 (None, 28, 28, 512)\n13 block4_conv3 (None, 28, 28, 512)\n14 block4_pool (None, 14, 14, 512)\n15 block5_conv1 (None, 14, 14, 512)\n16 block5_conv2 (None, 14, 14, 512)\n17 block5_conv3 (None, 14, 14, 512)\n18 block5_pool (None, 7, 7, 512)\n19 flatten (None, 25088)\n20 fc1 (None, 4096)\n21 fc2 (None, 4096)\n22 predictions (None, 1000)\n" ], [ "model=models.Model(inputs=base_model.input,\n outputs=base_model.get_layer('block1_pool').output)\n", "_____no_output_____" ], [ "imge_path='/home/hemanth/Documents/DeepLearning/CNN/cats_and_dogs_filtered/train/cats/cat.0.jpg'\nimg=image.load_img(imge_path,target_size=(224,224))\nx=image.img_to_array(img)\nx=np.expand_dims(x,axis=0)\nx=preprocess_input(x)", "_____no_output_____" ], [ "x", "_____no_output_____" ], [ "features=model.predict(x)\nprint(features)", "[[[[3.11129517e+02 4.79596062e+01 0.00000000e+00 ... 3.11482269e+02\n 2.00290955e+02 4.42955437e+01]\n [1.25340279e+02 5.14630089e+01 0.00000000e+00 ... 3.10924042e+02\n 1.37026245e+02 0.00000000e+00]\n [1.47215195e+02 5.68571663e+01 0.00000000e+00 ... 3.17700806e+02\n 1.37320801e+02 0.00000000e+00]\n ...\n [1.81297394e+02 7.70597839e+01 0.00000000e+00 ... 3.48985260e+02\n 2.36017059e+02 0.00000000e+00]\n [1.69442383e+02 7.26701584e+01 0.00000000e+00 ... 3.53717377e+02\n 2.18394928e+02 0.00000000e+00]\n [3.64689751e+01 0.00000000e+00 0.00000000e+00 ... 2.93437164e+02\n 4.67910339e+02 0.00000000e+00]]\n\n [[1.44133530e+02 7.37263489e+01 0.00000000e+00 ... 3.05310760e+02\n 9.46780777e+01 0.00000000e+00]\n [5.03478737e+01 4.57347107e+01 0.00000000e+00 ... 2.85215240e+02\n 1.41354723e+01 0.00000000e+00]\n [6.88971558e+01 4.96073036e+01 0.00000000e+00 ... 2.85181641e+02\n 0.00000000e+00 0.00000000e+00]\n ...\n [8.93914948e+01 5.06453781e+01 0.00000000e+00 ... 2.70332031e+02\n 1.28124247e+01 0.00000000e+00]\n [9.26538391e+01 5.31709557e+01 0.00000000e+00 ... 2.81921234e+02\n 0.00000000e+00 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 2.42748917e+02\n 2.63648499e+02 1.28303314e+02]]\n\n [[1.44133530e+02 7.37263489e+01 0.00000000e+00 ... 3.05310760e+02\n 9.46780777e+01 0.00000000e+00]\n [5.03478737e+01 4.57347107e+01 0.00000000e+00 ... 2.85215240e+02\n 1.41354723e+01 0.00000000e+00]\n [6.62951126e+01 4.86287498e+01 0.00000000e+00 ... 2.84876160e+02\n 0.00000000e+00 0.00000000e+00]\n ...\n [8.92307663e+01 4.65176048e+01 0.00000000e+00 ... 2.59554230e+02\n 1.69193573e+01 0.00000000e+00]\n [9.89337540e+01 5.60880737e+01 0.00000000e+00 ... 2.74577576e+02\n 0.00000000e+00 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 2.38854599e+02\n 2.72144653e+02 1.30796982e+02]]\n\n ...\n\n [[8.83513927e+00 2.91909161e+01 0.00000000e+00 ... 2.29880997e+02\n 6.57050753e+00 0.00000000e+00]\n [1.49421406e+01 3.71585960e+01 0.00000000e+00 ... 2.53973999e+02\n 1.87157798e+00 0.00000000e+00]\n [1.26421947e+01 3.70958099e+01 0.00000000e+00 ... 2.53300308e+02\n 6.40645266e+00 0.00000000e+00]\n ...\n [0.00000000e+00 2.66415833e+02 6.37576447e+01 ... 1.75577354e+01\n 3.48958254e+00 0.00000000e+00]\n [0.00000000e+00 2.64270569e+02 6.79010086e+01 ... 1.84656429e+01\n 1.15926485e+01 0.00000000e+00]\n [3.90131622e+02 4.14468658e+02 1.03482521e+02 ... 1.09585510e+02\n 4.27146187e+01 2.30493271e+02]]\n\n [[5.59370518e+00 2.95157928e+01 0.00000000e+00 ... 2.17997498e+02\n 4.52603865e+00 1.29722905e+00]\n [2.05820484e+01 3.78326759e+01 0.00000000e+00 ... 2.43044266e+02\n 1.30281725e+01 3.81371319e-01]\n [1.41411705e+01 3.80636330e+01 0.00000000e+00 ... 2.44881882e+02\n 2.37266006e+01 0.00000000e+00]\n ...\n [0.00000000e+00 2.65236328e+02 7.53794403e+01 ... 2.07916508e+01\n 8.84041309e+00 0.00000000e+00]\n [0.00000000e+00 2.64393402e+02 7.61051788e+01 ... 2.10842762e+01\n 1.48279648e+01 0.00000000e+00]\n [3.78785675e+02 4.09048462e+02 1.07675491e+02 ... 1.10812508e+02\n 5.62991066e+01 2.29640060e+02]]\n\n [[1.20673275e+01 3.53393593e+01 0.00000000e+00 ... 1.91170151e+02\n 0.00000000e+00 2.99661517e+00]\n [1.16464252e+01 3.63901329e+01 0.00000000e+00 ... 2.13286331e+02\n 2.80235386e+00 0.00000000e+00]\n [0.00000000e+00 2.77253666e+01 0.00000000e+00 ... 2.14530258e+02\n 2.54195614e+01 7.53865063e-01]\n ...\n [2.88724060e+02 3.48310791e+02 9.76093750e+01 ... 1.42734573e+02\n 2.43721333e+01 8.53497803e+02]\n [2.88724060e+02 3.48310791e+02 9.76093750e+01 ... 1.42734573e+02\n 2.43721333e+01 8.53497803e+02]\n [6.13538635e+02 5.21453491e+02 1.18484428e+02 ... 2.19471283e+02\n 0.00000000e+00 8.56193420e+02]]]]\n" ], [ "plt.plot(features.ravel())", "_____no_output_____" ] ], [ [ "## Without weight vgg16 model with zero padding", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nfrom tensorflow.keras import layers,models\nimport cv2,numpy as np\nimport os", "_____no_output_____" ], [ "def VGG_16(weights_path=None):\n model = models.Sequential()\n model.add(layers.ZeroPadding2D((1,1),input_shape=(224,224, 3)))\n model.add(layers.Convolution2D(64, (3, 3), activation='relu'))\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(64, (3, 3), activation='relu'))\n model.add(layers.MaxPooling2D((2,2), strides=(2,2)))\n\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(128, (3, 3), activation='relu'))\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(128, (3, 3), activation='relu'))\n model.add(layers.MaxPooling2D((2,2), strides=(2,2)))\n\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(256, (3, 3), activation='relu'))\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(256, (3, 3), activation='relu'))\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(256, (3, 3), activation='relu'))\n model.add(layers.MaxPooling2D((2,2), strides=(2,2)))\n\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(512, (3, 3), activation='relu'))\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(512, (3, 3), activation='relu'))\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(512, (3, 3), activation='relu'))\n model.add(layers.MaxPooling2D((2,2), strides=(2,2)))\n\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(512, (3, 3), activation='relu'))\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(512, (3, 3), activation='relu'))\n model.add(layers.ZeroPadding2D((1,1)))\n model.add(layers.Convolution2D(512, (3, 3), activation='relu'))\n model.add(layers.MaxPooling2D((2,2), strides=(2,2)))\n\n model.add(layers.Flatten())\n\n #top layer of the VGG net\n model.add(layers.Dense(4096, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(4096, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(1000, activation='softmax'))\n\n if weights_path:\n model.load_weights(weights_path)\n\n return model\n \n ", "_____no_output_____" ], [ "\nim = cv2.resize(cv2.imread('2021-01-12.jpeg'), (224, 224)).astype(np.float32)\n#im = im.transpose((2,0,1))\nim = np.expand_dims(im, axis=0)\n\n\n", "_____no_output_____" ], [ "# Test pretrained model\npath_file = os.path.join(os.path.expanduser(\"~\"), '.keras/models/vgg16_weights_tf_dim_ordering_tf_kernels.h5')\nmodel = VGG_16(path_file)\nmodel.summary()\n", "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nzero_padding2d_10 (ZeroPaddi (None, 226, 226, 3) 0 \n_________________________________________________________________\nconv2d_10 (Conv2D) (None, 224, 224, 64) 1792 \n_________________________________________________________________\nzero_padding2d_11 (ZeroPaddi (None, 226, 226, 64) 0 \n_________________________________________________________________\nconv2d_11 (Conv2D) (None, 224, 224, 64) 36928 \n_________________________________________________________________\nmax_pooling2d_4 (MaxPooling2 (None, 112, 112, 64) 0 \n_________________________________________________________________\nzero_padding2d_12 (ZeroPaddi (None, 114, 114, 64) 0 \n_________________________________________________________________\nconv2d_12 (Conv2D) (None, 112, 112, 128) 73856 \n_________________________________________________________________\nzero_padding2d_13 (ZeroPaddi (None, 114, 114, 128) 0 \n_________________________________________________________________\nconv2d_13 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nmax_pooling2d_5 (MaxPooling2 (None, 56, 56, 128) 0 \n_________________________________________________________________\nzero_padding2d_14 (ZeroPaddi (None, 58, 58, 128) 0 \n_________________________________________________________________\nconv2d_14 (Conv2D) (None, 56, 56, 256) 295168 \n_________________________________________________________________\nzero_padding2d_15 (ZeroPaddi (None, 58, 58, 256) 0 \n_________________________________________________________________\nconv2d_15 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nzero_padding2d_16 (ZeroPaddi (None, 58, 58, 256) 0 \n_________________________________________________________________\nconv2d_16 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nmax_pooling2d_6 (MaxPooling2 (None, 28, 28, 256) 0 \n_________________________________________________________________\nzero_padding2d_17 (ZeroPaddi (None, 30, 30, 256) 0 \n_________________________________________________________________\nconv2d_17 (Conv2D) (None, 28, 28, 512) 1180160 \n_________________________________________________________________\nzero_padding2d_18 (ZeroPaddi (None, 30, 30, 512) 0 \n_________________________________________________________________\nconv2d_18 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nzero_padding2d_19 (ZeroPaddi (None, 30, 30, 512) 0 \n_________________________________________________________________\nconv2d_19 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nmax_pooling2d_7 (MaxPooling2 (None, 14, 14, 512) 0 \n_________________________________________________________________\nzero_padding2d_20 (ZeroPaddi (None, 16, 16, 512) 0 \n_________________________________________________________________\nconv2d_20 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nzero_padding2d_21 (ZeroPaddi (None, 16, 16, 512) 0 \n_________________________________________________________________\nconv2d_21 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nzero_padding2d_22 (ZeroPaddi (None, 16, 16, 512) 0 \n_________________________________________________________________\nconv2d_22 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nmax_pooling2d_8 (MaxPooling2 (None, 7, 7, 512) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 25088) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 4096) 102764544 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 4096) 0 \n_________________________________________________________________\ndense_4 (Dense) (None, 4096) 16781312 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 4096) 0 \n_________________________________________________________________\ndense_5 (Dense) (None, 1000) 4097000 \n=================================================================\nTotal params: 138,357,544\nTrainable params: 138,357,544\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(optimizer='sgd', loss='categorical_crossentropy')\nout = model.predict(im)\nprint(np.argmax(out))\n ", "820\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cbdebe5f16f54e79a298705dc2810864440db7c2
10,716
ipynb
Jupyter Notebook
datasets/probav/QuickstartExample.ipynb
VITObelgium/notebook-samples
6e175817d3682bdd89351b1077522a4cc072f7d1
[ "Apache-2.0" ]
3
2020-05-15T12:28:48.000Z
2021-08-19T15:35:24.000Z
datasets/probav/QuickstartExample.ipynb
VITObelgium/notebook-samples
6e175817d3682bdd89351b1077522a4cc072f7d1
[ "Apache-2.0" ]
null
null
null
datasets/probav/QuickstartExample.ipynb
VITObelgium/notebook-samples
6e175817d3682bdd89351b1077522a4cc072f7d1
[ "Apache-2.0" ]
3
2020-06-13T21:29:39.000Z
2021-11-22T21:21:03.000Z
32.670732
404
0.565043
[ [ [ "This notebook shows the MEP quickstart sample, which also exists as a non-notebook version at:\nhttps://bitbucket.org/vitotap/python-spark-quickstart\n\nIt shows how to use Spark (http://spark.apache.org/) for distributed processing on the PROBA-V Mission Exploitation Platform. (https://proba-v-mep.esa.int/) The sample intentionally implements a very simple computation: for each PROBA-V tile in a given bounding box and time range, a histogram is computed. The results are then summed and printed. Computation of the histograms runs in parallel.\n## First step: get file paths\nA catalog API is available to easily retrieve paths to PROBA-V files:\nhttps://readthedocs.org/projects/mep-catalogclient/", "_____no_output_____" ] ], [ [ "from catalogclient import catalog\ncat=catalog.Catalog()\ncat.get_producttypes()", "_____no_output_____" ], [ "date = \"2016-01-01\"\nproducts = cat.get_products('PROBAV_L3_S1_TOC_333M', \n fileformat='GEOTIFF', \n startdate=date, \n enddate=date, \n min_lon=0, max_lon=10, min_lat=36, max_lat=53)\n#extract NDVI geotiff files from product metadata\nfiles = [p.file('NDVI')[5:] for p in products]\nprint('Found '+str(len(files)) + ' files.')\nprint(files[0])\n#check if file exists\n!file {files[0]}", "Found 2 files.\n/data/MTDA/TIFFDERIVED/PROBAV_L3_S1_TOC_333M/2016/20160101/PROBAV_S1_TOC_20160101_333M_V101/PROBAV_S1_TOC_X18Y02_20160101_333M_V101_NDVI.tif\n/data/MTDA/TIFFDERIVED/PROBAV_L3_S1_TOC_333M/2016/20160101/PROBAV_S1_TOC_20160101_333M_V101/PROBAV_S1_TOC_X18Y02_20160101_333M_V101_NDVI.tif: TIFF image data, little-endian\n" ] ], [ [ "## Second step: define function to apply\nDefine the histogram function, this can also be done inline, which allows for a faster feedback loop when writing the code, but here we want to clearly separate the processing 'algorithm' from the parallelization code.", "_____no_output_____" ] ], [ [ "# Calculates the histogram for a given (single band) image file.\ndef histogram(image_file):\n \n import numpy as np\n import gdal\n \n \n # Open image file\n img = gdal.Open(image_file)\n \n if img is None:\n print( '-ERROR- Unable to open image file \"%s\"' % image_file )\n \n # Open raster band (first band)\n raster = img.GetRasterBand(1) \n xSize = img.RasterXSize\n ySize = img.RasterYSize\n \n # Read raster data\n data = raster.ReadAsArray(0, 0, xSize, ySize)\n \n # Calculate histogram\n hist, _ = np.histogram(data, bins=256)\n return hist\n", "_____no_output_____" ] ], [ [ "## Third step: setup Spark\nTo work on the processing cluster, we need to specify the resources we want:\n\n* spark.executor.cores: Number of cores per executor. Usually our tasks are single threaded, so 1 is a good default.\n* spark.executor.memory: memory to assign per executor. For the Java/Spark processing, not the Python part.\n* spark.yarn.executor.memoryOverhead: memory available for Python in each executor.\n\nWe set up the SparkConf with these parameters, and create a SparkContext sc, which will be our access point to the cluster.", "_____no_output_____" ] ], [ [ "%%time\n# ================================================================\n# === Calculate the histogram for a given number of files. The ===\n# === processing is performed by spreading them over a cluster ===\n# === of Spark nodes. ===\n# ================================================================\n\nfrom datetime import datetime\nfrom operator import add\nimport pyspark\nimport os\n# Setup the Spark cluster\nconf = pyspark.SparkConf()\nconf.set('spark.yarn.executor.memoryOverhead', 512)\nconf.set('spark.executor.memory', '512m')\n\nsc = pyspark.SparkContext(conf=conf)", "CPU times: user 225 ms, sys: 15.4 ms, total: 240 ms\nWall time: 15.4 s\n" ] ], [ [ "## Fourth step: compute histograms\nWe use a couple of Spark functions to run our job on the cluster. Comments are provided in the code.", "_____no_output_____" ] ], [ [ "%%time\n# Distribute the local file list over the cluster.\nfilesRDD = sc.parallelize(files,len(files))\n\n# Apply the 'histogram' function to each filename using 'map', keep the result in memory using 'cache'.\nhists = filesRDD.map(histogram).cache()\n\ncount = hists.count()\n\n# Combine distributed histograms into a single result\ntotal = list(hists.reduce(lambda h, i: map(add, h, i)))\nhists.unpersist()\n\nprint( \"Sum of %i histograms: %s\" % (count, total))", "_____no_output_____" ], [ "#stop spark session if we no longer need it\nsc.stop()", "_____no_output_____" ] ], [ [ "## Fifth step: plot our result\nPlot the array of values as a simple line chart using matplotlib. This is the most basic Python library. More advanced options such as bokeh, mpld3 and seaborn are also available.", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.plot(total)\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cbdee1459b300ed64b6c5f32c2aec171c316c6ff
780,334
ipynb
Jupyter Notebook
notebooks/2. Data Understanding.ipynb
kaivlya1993/data_science_covid-19
602b9c1b1e62d8320528a437fa0bacbd198d750f
[ "FTL" ]
null
null
null
notebooks/2. Data Understanding.ipynb
kaivlya1993/data_science_covid-19
602b9c1b1e62d8320528a437fa0bacbd198d750f
[ "FTL" ]
null
null
null
notebooks/2. Data Understanding.ipynb
kaivlya1993/data_science_covid-19
602b9c1b1e62d8320528a437fa0bacbd198d750f
[ "FTL" ]
null
null
null
279.089413
623,504
0.821005
[ [ [ "CRISP_DM = \"C:/Users/kaivl/data_science_covid-19/CRISP_DM.png\"\nfrom PIL import Image\nimport glob\nImage.open(CRISP_DM)", "_____no_output_____" ], [ "import pandas as pd\nimport subprocess\nimport os\nimport ntpath\n\npd.set_option('display.max_rows', 500)", "_____no_output_____" ] ], [ [ "### Data Understanding", "_____no_output_____" ], [ "* RKI, webscrape (webscraping) https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Fallzahlen.html\n* John Hopkins (GITHUB) https://github.com/CSSEGISandData/COVID-19.git\n* Rest API services to retreive data https://npgeo-corona-npgeo-de.hub.arcgis.com/", "_____no_output_____" ], [ "### GITHUB csv data", "_____no_output_____" ] ], [ [ "git_pull = subprocess.Popen( \"git pull\", \n cwd = os.path.dirname('C:\\\\Users\\\\kaivl\\\\data_science_covid-19\\\\data\\\\raw\\\\COVID-19'), \n shell = True, \n stdout = subprocess.PIPE, \n stderr = subprocess.PIPE )\n(out, error) = git_pull.communicate()\n\n\nprint(\"Error : \" + str(error)) \nprint(\"out : \" + str(out))", "Error : b'fatal: not a git repository (or any of the parent directories): .git\\n'\nout : b''\n" ], [ "data_path='../data/raw/COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'\npd_raw=pd.read_csv(data_path)", "_____no_output_____" ], [ "pd_raw.head()", "_____no_output_____" ] ], [ [ "## Webscrapping", "_____no_output_____" ] ], [ [ "import requests\nfrom bs4 import BeautifulSoup", "_____no_output_____" ], [ "page = requests.get(\"https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Fallzahlen.html\")", "_____no_output_____" ], [ "soup = BeautifulSoup(page.content, 'html.parser')", "_____no_output_____" ], [ "html_table=soup.find('table')", "_____no_output_____" ], [ "all_rows=html_table.find_all('tr')", "_____no_output_____" ], [ "final_data_list=[]", "_____no_output_____" ], [ "for pos,rows in enumerate(all_rows):\n col_list=[each_col.get_text(strip=True) for each_col in rows.find_all('td')] #tag td for each data element in raw\n final_data_list.append(col_list)", "_____no_output_____" ], [ "pd_daily_status=pd.DataFrame(final_data_list).dropna().rename(columns={0:'state',\n 1:'cases',\n 2:'changes',\n 3:'cases in the past 7 days',\n 4:'7-day incidence',\n 5:'deaths'})\n# Note: All the data is in german standard (decimals: ',' and tousands: '.')", "_____no_output_____" ], [ "pd_daily_status.head()", "_____no_output_____" ], [ "pd_daily_status.to_csv('../data/raw/RKI/RKI_data.csv',sep=';', index = False) \n# Data will be prepared in notebook 'data_preparation'", "_____no_output_____" ] ], [ [ "## REST API calls\n", "_____no_output_____" ] ], [ [ "data=requests.get('https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/Coronaf%C3%A4lle_in_den_Bundesl%C3%A4ndern/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json')", "_____no_output_____" ], [ "import json", "_____no_output_____" ], [ "json_object=json.loads(data.content)", "_____no_output_____" ], [ "type(json_object)", "_____no_output_____" ], [ "json_object.keys()", "_____no_output_____" ], [ "# Extract the data from the dict.\n\nfull_list=[]\nfor pos,each_dict in enumerate (json_object['features'][:]):\n full_list.append(each_dict['attributes'])", "_____no_output_____" ], [ "pd.DataFrame(full_list)", "_____no_output_____" ], [ "pd_full_list=pd.DataFrame(full_list)\npd_full_list.head()", "_____no_output_____" ], [ "pd_full_list.to_csv('../data/raw/NPGEO/GER_state_data.csv',sep=';')", "_____no_output_____" ] ], [ [ "## API access via REST service, e.g. USA data\n\nexample of a REST confirm interface (attention registration mandatory)\n\nwww.smartable.ai", "_____no_output_____" ] ], [ [ "import requests", "_____no_output_____" ], [ "url_endpoint='https://api.smartable.ai/coronavirus/stats/US'\n\nheaders = {\n 'Cache-Control': 'no-cache',\n 'Subscription-Key': '28ee4219700f48718be78b057beb7eb4',\n}\n\nresponse = requests.get('https://api.smartable.ai/coronavirus/stats/US', headers=headers)\nprint(response)", "<Response [200]>\n" ], [ "response.content", "_____no_output_____" ], [ "US_dict=json.loads(response.content)\nwith open('../data/raw/SMARTABLE/US_data.json', 'w') as outfile:\n json.dump(US_dict, outfile,indent=2)", "_____no_output_____" ], [ "US_dict['stats']['breakdowns'][0]", "_____no_output_____" ], [ "# Extract data of interest from dict.\n\nfull_list_US_country=[]\nfor pos, each_dict in enumerate(US_dict['stats']['breakdowns'][:]):\n flatten_dict = each_dict['location']\n flatten_dict.update(dict(list(US_dict['stats']['breakdowns'][pos].items())[1:7]))\n full_list_US_country.append(flatten_dict)", "_____no_output_____" ], [ "pd.DataFrame(full_list_US_country).to_csv('../data/raw/SMARTABLE/full_list_US_country.csv',sep=';',index=False)", "_____no_output_____" ], [ "url_endpoint='https://api.smartable.ai/coronavirus/stats/IN'\n\nheaders={\n 'Cache-Control': 'no-cache',\n 'Subscription-Key': '79fead24cb57472d820cb56d1b451d7c',\n}\nresponse=requests.get(url_endpoint,headers=headers)", "_____no_output_____" ], [ "IN_dict = json.loads(response.content) # importing strings for India dataset and dump into JSON file with .txt format\nwith open ('../data/raw/IN_data.txt','w') as outfile:\n json.dump(IN_dict, outfile,indent=2)", "_____no_output_____" ], [ "print(json.dumps(IN_dict, indent = 2)) #string dump", "{\n \"location\": {\n \"long\": 78.0,\n \"countryOrRegion\": \"India\",\n \"provinceOrState\": null,\n \"county\": null,\n \"isoCode\": \"IN\",\n \"lat\": 21.0\n },\n \"updatedDateTime\": \"2020-08-16T06:00:54.3144001Z\",\n \"stats\": {\n \"totalConfirmedCases\": 2590501,\n \"newlyConfirmedCases\": 63193,\n \"totalDeaths\": 50099,\n \"newDeaths\": 951,\n \"totalRecoveredCases\": 1862665,\n \"newlyRecoveredCases\": 53123,\n \"history\": [\n {\n \"date\": \"2020-01-22T00:00:00\",\n \"confirmed\": 0,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-01-23T00:00:00\",\n \"confirmed\": 0,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-01-24T00:00:00\",\n \"confirmed\": 0,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-01-25T00:00:00\",\n \"confirmed\": 0,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-01-26T00:00:00\",\n \"confirmed\": 0,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-01-27T00:00:00\",\n \"confirmed\": 0,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-01-28T00:00:00\",\n \"confirmed\": 0,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-01-29T00:00:00\",\n \"confirmed\": 0,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-01-30T00:00:00\",\n \"confirmed\": 1,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-01-31T00:00:00\",\n \"confirmed\": 1,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-01T00:00:00\",\n \"confirmed\": 1,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-02T00:00:00\",\n \"confirmed\": 2,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-03T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-04T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-05T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-06T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-07T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-08T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-09T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-10T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-11T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-12T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-13T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-14T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-15T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 0\n },\n {\n \"date\": \"2020-02-16T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-17T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-18T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-19T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-20T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-21T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-22T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-23T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-24T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-25T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-26T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-27T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-28T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-02-29T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-01T00:00:00\",\n \"confirmed\": 3,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-02T00:00:00\",\n \"confirmed\": 5,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-03T00:00:00\",\n \"confirmed\": 5,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-04T00:00:00\",\n \"confirmed\": 28,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-05T00:00:00\",\n \"confirmed\": 30,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-06T00:00:00\",\n \"confirmed\": 31,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-07T00:00:00\",\n \"confirmed\": 34,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-08T00:00:00\",\n \"confirmed\": 39,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-09T00:00:00\",\n \"confirmed\": 43,\n \"deaths\": 0,\n \"recovered\": 3\n },\n {\n \"date\": \"2020-03-10T00:00:00\",\n \"confirmed\": 56,\n \"deaths\": 0,\n \"recovered\": 4\n },\n {\n \"date\": \"2020-03-11T00:00:00\",\n \"confirmed\": 62,\n \"deaths\": 1,\n \"recovered\": 4\n },\n {\n \"date\": \"2020-03-12T00:00:00\",\n \"confirmed\": 75,\n \"deaths\": 1,\n \"recovered\": 4\n },\n {\n \"date\": \"2020-03-13T00:00:00\",\n \"confirmed\": 83,\n \"deaths\": 2,\n \"recovered\": 10\n },\n {\n \"date\": \"2020-03-14T00:00:00\",\n \"confirmed\": 105,\n \"deaths\": 2,\n \"recovered\": 10\n },\n {\n \"date\": \"2020-03-15T00:00:00\",\n \"confirmed\": 114,\n \"deaths\": 2,\n \"recovered\": 13\n },\n {\n \"date\": \"2020-03-16T00:00:00\",\n \"confirmed\": 129,\n \"deaths\": 3,\n \"recovered\": 13\n },\n {\n \"date\": \"2020-03-17T00:00:00\",\n \"confirmed\": 148,\n \"deaths\": 3,\n \"recovered\": 14\n },\n {\n \"date\": \"2020-03-18T00:00:00\",\n \"confirmed\": 171,\n \"deaths\": 3,\n \"recovered\": 15\n },\n {\n \"date\": \"2020-03-19T00:00:00\",\n \"confirmed\": 201,\n \"deaths\": 5,\n \"recovered\": 20\n },\n {\n \"date\": \"2020-03-20T00:00:00\",\n \"confirmed\": 275,\n \"deaths\": 5,\n \"recovered\": 23\n },\n {\n \"date\": \"2020-03-21T00:00:00\",\n \"confirmed\": 332,\n \"deaths\": 5,\n \"recovered\": 27\n },\n {\n \"date\": \"2020-03-22T00:00:00\",\n \"confirmed\": 425,\n \"deaths\": 8,\n \"recovered\": 27\n },\n {\n \"date\": \"2020-03-23T00:00:00\",\n \"confirmed\": 499,\n \"deaths\": 10,\n \"recovered\": 37\n },\n {\n \"date\": \"2020-03-24T00:00:00\",\n \"confirmed\": 562,\n \"deaths\": 11,\n \"recovered\": 40\n },\n {\n \"date\": \"2020-03-25T00:00:00\",\n \"confirmed\": 673,\n \"deaths\": 13,\n \"recovered\": 43\n },\n {\n \"date\": \"2020-03-26T00:00:00\",\n \"confirmed\": 747,\n \"deaths\": 20,\n \"recovered\": 66\n },\n {\n \"date\": \"2020-03-27T00:00:00\",\n \"confirmed\": 902,\n \"deaths\": 20,\n \"recovered\": 83\n },\n {\n \"date\": \"2020-03-28T00:00:00\",\n \"confirmed\": 987,\n \"deaths\": 25,\n \"recovered\": 87\n },\n {\n \"date\": \"2020-03-29T00:00:00\",\n \"confirmed\": 1024,\n \"deaths\": 27,\n \"recovered\": 95\n },\n {\n \"date\": \"2020-03-30T00:00:00\",\n \"confirmed\": 1251,\n \"deaths\": 32,\n \"recovered\": 102\n },\n {\n \"date\": \"2020-03-31T00:00:00\",\n \"confirmed\": 1590,\n \"deaths\": 45,\n \"recovered\": 148\n },\n {\n \"date\": \"2020-04-01T00:00:00\",\n \"confirmed\": 2032,\n \"deaths\": 58,\n \"recovered\": 148\n },\n {\n \"date\": \"2020-04-02T00:00:00\",\n \"confirmed\": 2567,\n \"deaths\": 72,\n \"recovered\": 192\n },\n {\n \"date\": \"2020-04-03T00:00:00\",\n \"confirmed\": 2567,\n \"deaths\": 72,\n \"recovered\": 192\n },\n {\n \"date\": \"2020-04-04T00:00:00\",\n \"confirmed\": 3588,\n \"deaths\": 99,\n \"recovered\": 229\n },\n {\n \"date\": \"2020-04-05T00:00:00\",\n \"confirmed\": 4314,\n \"deaths\": 118,\n \"recovered\": 328\n },\n {\n \"date\": \"2020-04-06T00:00:00\",\n \"confirmed\": 4778,\n \"deaths\": 136,\n \"recovered\": 382\n },\n {\n \"date\": \"2020-04-07T00:00:00\",\n \"confirmed\": 5356,\n \"deaths\": 160,\n \"recovered\": 468\n },\n {\n \"date\": \"2020-04-08T00:00:00\",\n \"confirmed\": 5916,\n \"deaths\": 178,\n \"recovered\": 506\n },\n {\n \"date\": \"2020-04-09T00:00:00\",\n \"confirmed\": 6771,\n \"deaths\": 228,\n \"recovered\": 635\n },\n {\n \"date\": \"2020-04-10T00:00:00\",\n \"confirmed\": 7600,\n \"deaths\": 249,\n \"recovered\": 774\n },\n {\n \"date\": \"2020-04-11T00:00:00\",\n \"confirmed\": 8446,\n \"deaths\": 288,\n \"recovered\": 969\n },\n {\n \"date\": \"2020-04-12T00:00:00\",\n \"confirmed\": 9240,\n \"deaths\": 331,\n \"recovered\": 1096\n },\n {\n \"date\": \"2020-04-13T00:00:00\",\n \"confirmed\": 10541,\n \"deaths\": 358,\n \"recovered\": 1205\n },\n {\n \"date\": \"2020-04-14T00:00:00\",\n \"confirmed\": 11555,\n \"deaths\": 396,\n \"recovered\": 1362\n },\n {\n \"date\": \"2020-04-15T00:00:00\",\n \"confirmed\": 12370,\n \"deaths\": 422,\n \"recovered\": 1508\n },\n {\n \"date\": \"2020-04-16T00:00:00\",\n \"confirmed\": 13495,\n \"deaths\": 448,\n \"recovered\": 1777\n },\n {\n \"date\": \"2020-04-17T00:00:00\",\n \"confirmed\": 14425,\n \"deaths\": 488,\n \"recovered\": 2045\n },\n {\n \"date\": \"2020-04-18T00:00:00\",\n \"confirmed\": 16365,\n \"deaths\": 521,\n \"recovered\": 2466\n },\n {\n \"date\": \"2020-04-19T00:00:00\",\n \"confirmed\": 17615,\n \"deaths\": 559,\n \"recovered\": 2854\n },\n {\n \"date\": \"2020-04-20T00:00:00\",\n \"confirmed\": 18658,\n \"deaths\": 592,\n \"recovered\": 3273\n },\n {\n \"date\": \"2020-04-21T00:00:00\",\n \"confirmed\": 20178,\n \"deaths\": 645,\n \"recovered\": 3976\n },\n {\n \"date\": \"2020-04-22T00:00:00\",\n \"confirmed\": 21797,\n \"deaths\": 681,\n \"recovered\": 4376\n },\n {\n \"date\": \"2020-04-23T00:00:00\",\n \"confirmed\": 23502,\n \"deaths\": 722,\n \"recovered\": 5012\n },\n {\n \"date\": \"2020-04-24T00:00:00\",\n \"confirmed\": 24530,\n \"deaths\": 780,\n \"recovered\": 5498\n },\n {\n \"date\": \"2020-04-25T00:00:00\",\n \"confirmed\": 26496,\n \"deaths\": 825,\n \"recovered\": 5939\n },\n {\n \"date\": \"2020-04-26T00:00:00\",\n \"confirmed\": 27977,\n \"deaths\": 884,\n \"recovered\": 6523\n },\n {\n \"date\": \"2020-04-27T00:00:00\",\n \"confirmed\": 29451,\n \"deaths\": 939,\n \"recovered\": 7137\n },\n {\n \"date\": \"2020-04-28T00:00:00\",\n \"confirmed\": 31360,\n \"deaths\": 1008,\n \"recovered\": 7747\n },\n {\n \"date\": \"2020-04-29T00:00:00\",\n \"confirmed\": 33062,\n \"deaths\": 1079,\n \"recovered\": 8437\n },\n {\n \"date\": \"2020-04-30T00:00:00\",\n \"confirmed\": 35043,\n \"deaths\": 1154,\n \"recovered\": 9068\n },\n {\n \"date\": \"2020-05-01T00:00:00\",\n \"confirmed\": 37371,\n \"deaths\": 1238,\n \"recovered\": 9943\n },\n {\n \"date\": \"2020-05-02T00:00:00\",\n \"confirmed\": 39980,\n \"deaths\": 1323,\n \"recovered\": 10819\n },\n {\n \"date\": \"2020-05-03T00:00:00\",\n \"confirmed\": 42670,\n \"deaths\": 1395,\n \"recovered\": 11782\n },\n {\n \"date\": \"2020-05-04T00:00:00\",\n \"confirmed\": 46476,\n \"deaths\": 1571,\n \"recovered\": 12849\n },\n {\n \"date\": \"2020-05-05T00:00:00\",\n \"confirmed\": 49436,\n \"deaths\": 1695,\n \"recovered\": 14183\n },\n {\n \"date\": \"2020-05-06T00:00:00\",\n \"confirmed\": 53045,\n \"deaths\": 1787,\n \"recovered\": 15331\n },\n {\n \"date\": \"2020-05-07T00:00:00\",\n \"confirmed\": 56409,\n \"deaths\": 1890,\n \"recovered\": 16790\n },\n {\n \"date\": \"2020-05-08T00:00:00\",\n \"confirmed\": 59765,\n \"deaths\": 1986,\n \"recovered\": 17897\n },\n {\n \"date\": \"2020-05-09T00:00:00\",\n \"confirmed\": 62939,\n \"deaths\": 2109,\n \"recovered\": 19358\n },\n {\n \"date\": \"2020-05-10T00:00:00\",\n \"confirmed\": 67259,\n \"deaths\": 2212,\n \"recovered\": 20969\n },\n {\n \"date\": \"2020-05-11T00:00:00\",\n \"confirmed\": 70827,\n \"deaths\": 2294,\n \"recovered\": 22549\n },\n {\n \"date\": \"2020-05-12T00:00:00\",\n \"confirmed\": 74480,\n \"deaths\": 2415,\n \"recovered\": 24453\n },\n {\n \"date\": \"2020-05-13T00:00:00\",\n \"confirmed\": 78194,\n \"deaths\": 2551,\n \"recovered\": 26400\n },\n {\n \"date\": \"2020-05-14T00:00:00\",\n \"confirmed\": 81997,\n \"deaths\": 2649,\n \"recovered\": 27969\n },\n {\n \"date\": \"2020-05-15T00:00:00\",\n \"confirmed\": 85940,\n \"deaths\": 2753,\n \"recovered\": 30258\n },\n {\n \"date\": \"2020-05-16T00:00:00\",\n \"confirmed\": 90927,\n \"deaths\": 2872,\n \"recovered\": 34224\n },\n {\n \"date\": \"2020-05-17T00:00:00\",\n \"confirmed\": 96169,\n \"deaths\": 3029,\n \"recovered\": 36824\n },\n {\n \"date\": \"2020-05-18T00:00:00\",\n \"confirmed\": 101261,\n \"deaths\": 3164,\n \"recovered\": 39233\n },\n {\n \"date\": \"2020-05-19T00:00:00\",\n \"confirmed\": 106886,\n \"deaths\": 3303,\n \"recovered\": 42309\n },\n {\n \"date\": \"2020-05-20T00:00:00\",\n \"confirmed\": 112442,\n \"deaths\": 3438,\n \"recovered\": 45422\n },\n {\n \"date\": \"2020-05-21T00:00:00\",\n \"confirmed\": 118501,\n \"deaths\": 3585,\n \"recovered\": 48553\n },\n {\n \"date\": \"2020-05-22T00:00:00\",\n \"confirmed\": 125149,\n \"deaths\": 3728,\n \"recovered\": 51824\n },\n {\n \"date\": \"2020-05-23T00:00:00\",\n \"confirmed\": 131920,\n \"deaths\": 3869,\n \"recovered\": 54441\n },\n {\n \"date\": \"2020-05-24T00:00:00\",\n \"confirmed\": 139049,\n \"deaths\": 4024,\n \"recovered\": 57721\n },\n {\n \"date\": \"2020-05-25T00:00:00\",\n \"confirmed\": 145456,\n \"deaths\": 4172,\n \"recovered\": 60706\n },\n {\n \"date\": \"2020-05-26T00:00:00\",\n \"confirmed\": 151876,\n \"deaths\": 4349,\n \"recovered\": 64426\n },\n {\n \"date\": \"2020-05-27T00:00:00\",\n \"confirmed\": 158415,\n \"deaths\": 4534,\n \"recovered\": 67749\n },\n {\n \"date\": \"2020-05-28T00:00:00\",\n \"confirmed\": 165829,\n \"deaths\": 4713,\n \"recovered\": 71106\n },\n {\n \"date\": \"2020-05-29T00:00:00\",\n \"confirmed\": 173763,\n \"deaths\": 4980,\n \"recovered\": 82627\n },\n {\n \"date\": \"2020-05-30T00:00:00\",\n \"confirmed\": 182490,\n \"deaths\": 5186,\n \"recovered\": 86984\n },\n {\n \"date\": \"2020-05-31T00:00:00\",\n \"confirmed\": 190791,\n \"deaths\": 5408,\n \"recovered\": 91855\n },\n {\n \"date\": \"2020-06-01T00:00:00\",\n \"confirmed\": 198706,\n \"deaths\": 5608,\n \"recovered\": 95754\n },\n {\n \"date\": \"2020-06-02T00:00:00\",\n \"confirmed\": 207615,\n \"deaths\": 5829,\n \"recovered\": 100303\n },\n {\n \"date\": \"2020-06-03T00:00:00\",\n \"confirmed\": 216824,\n \"deaths\": 6088,\n \"recovered\": 104071\n },\n {\n \"date\": \"2020-06-04T00:00:00\",\n \"confirmed\": 227029,\n \"deaths\": 6363,\n \"recovered\": 109462\n },\n {\n \"date\": \"2020-06-05T00:00:00\",\n \"confirmed\": 236954,\n \"deaths\": 6649,\n \"recovered\": 114073\n },\n {\n \"date\": \"2020-06-06T00:00:00\",\n \"confirmed\": 247040,\n \"deaths\": 6946,\n \"recovered\": 119293\n },\n {\n \"date\": \"2020-06-07T00:00:00\",\n \"confirmed\": 258090,\n \"deaths\": 7207,\n \"recovered\": 124095\n },\n {\n \"date\": \"2020-06-08T00:00:00\",\n \"confirmed\": 267046,\n \"deaths\": 7473,\n \"recovered\": 129215\n },\n {\n \"date\": \"2020-06-09T00:00:00\",\n \"confirmed\": 276146,\n \"deaths\": 7750,\n \"recovered\": 134670\n },\n {\n \"date\": \"2020-06-10T00:00:00\",\n \"confirmed\": 287155,\n \"deaths\": 8107,\n \"recovered\": 140979\n },\n {\n \"date\": \"2020-06-11T00:00:00\",\n \"confirmed\": 298283,\n \"deaths\": 8501,\n \"recovered\": 147195\n },\n {\n \"date\": \"2020-06-12T00:00:00\",\n \"confirmed\": 309603,\n \"deaths\": 8890,\n \"recovered\": 154330\n },\n {\n \"date\": \"2020-06-13T00:00:00\",\n \"confirmed\": 321626,\n \"deaths\": 9205,\n \"recovered\": 162379\n },\n {\n \"date\": \"2020-06-14T00:00:00\",\n \"confirmed\": 333008,\n \"deaths\": 9523,\n \"recovered\": 169748\n },\n {\n \"date\": \"2020-06-15T00:00:00\",\n \"confirmed\": 343091,\n \"deaths\": 9915,\n \"recovered\": 180320\n },\n {\n \"date\": \"2020-06-16T00:00:00\",\n \"confirmed\": 354161,\n \"deaths\": 11921,\n \"recovered\": 187552\n },\n {\n \"date\": \"2020-06-17T00:00:00\",\n \"confirmed\": 367963,\n \"deaths\": 12272,\n \"recovered\": 194553\n },\n {\n \"date\": \"2020-06-18T00:00:00\",\n \"confirmed\": 381485,\n \"deaths\": 12605,\n \"recovered\": 205183\n },\n {\n \"date\": \"2020-06-19T00:00:00\",\n \"confirmed\": 396182,\n \"deaths\": 12970,\n \"recovered\": 214209\n },\n {\n \"date\": \"2020-06-20T00:00:00\",\n \"confirmed\": 411773,\n \"deaths\": 13346,\n \"recovered\": 228307\n },\n {\n \"date\": \"2020-06-21T00:00:00\",\n \"confirmed\": 426910,\n \"deaths\": 13703,\n \"recovered\": 237252\n },\n {\n \"date\": \"2020-06-22T00:00:00\",\n \"confirmed\": 440685,\n \"deaths\": 14015,\n \"recovered\": 248190\n },\n {\n \"date\": \"2020-06-23T00:00:00\",\n \"confirmed\": 456552,\n \"deaths\": 14483,\n \"recovered\": 258685\n },\n {\n \"date\": \"2020-06-24T00:00:00\",\n \"confirmed\": 473719,\n \"deaths\": 14907,\n \"recovered\": 271723\n },\n {\n \"date\": \"2020-06-25T00:00:00\",\n \"confirmed\": 491170,\n \"deaths\": 15308,\n \"recovered\": 285671\n },\n {\n \"date\": \"2020-06-26T00:00:00\",\n \"confirmed\": 509446,\n \"deaths\": 15689,\n \"recovered\": 295917\n },\n {\n \"date\": \"2020-06-27T00:00:00\",\n \"confirmed\": 529577,\n \"deaths\": 16103,\n \"recovered\": 310146\n },\n {\n \"date\": \"2020-06-28T00:00:00\",\n \"confirmed\": 549197,\n \"deaths\": 16487,\n \"recovered\": 321774\n },\n {\n \"date\": \"2020-06-29T00:00:00\",\n \"confirmed\": 567536,\n \"deaths\": 16904,\n \"recovered\": 335272\n },\n {\n \"date\": \"2020-06-30T00:00:00\",\n \"confirmed\": 585792,\n \"deaths\": 17410,\n \"recovered\": 347979\n },\n {\n \"date\": \"2020-07-01T00:00:00\",\n \"confirmed\": 605220,\n \"deaths\": 17848,\n \"recovered\": 359896\n },\n {\n \"date\": \"2020-07-02T00:00:00\",\n \"confirmed\": 627168,\n \"deaths\": 18225,\n \"recovered\": 379902\n },\n {\n \"date\": \"2020-07-03T00:00:00\",\n \"confirmed\": 649889,\n \"deaths\": 18669,\n \"recovered\": 394319\n },\n {\n \"date\": \"2020-07-04T00:00:00\",\n \"confirmed\": 673904,\n \"deaths\": 19279,\n \"recovered\": 409083\n },\n {\n \"date\": \"2020-07-05T00:00:00\",\n \"confirmed\": 698233,\n \"deaths\": 19703,\n \"recovered\": 424928\n },\n {\n \"date\": \"2020-07-06T00:00:00\",\n \"confirmed\": 720707,\n \"deaths\": 20178,\n \"recovered\": 440192\n },\n {\n \"date\": \"2020-07-07T00:00:00\",\n \"confirmed\": 744879,\n \"deaths\": 20661,\n \"recovered\": 458373\n },\n {\n \"date\": \"2020-07-08T00:00:00\",\n \"confirmed\": 769150,\n \"deaths\": 21151,\n \"recovered\": 476565\n },\n {\n \"date\": \"2020-07-09T00:00:00\",\n \"confirmed\": 795605,\n \"deaths\": 21632,\n \"recovered\": 496048\n },\n {\n \"date\": \"2020-07-10T00:00:00\",\n \"confirmed\": 822603,\n \"deaths\": 22144,\n \"recovered\": 516206\n },\n {\n \"date\": \"2020-07-11T00:00:00\",\n \"confirmed\": 850827,\n \"deaths\": 22696,\n \"recovered\": 536314\n },\n {\n \"date\": \"2020-07-12T00:00:00\",\n \"confirmed\": 879487,\n \"deaths\": 23194,\n \"recovered\": 554429\n },\n {\n \"date\": \"2020-07-13T00:00:00\",\n \"confirmed\": 907645,\n \"deaths\": 23727,\n \"recovered\": 572112\n },\n {\n \"date\": \"2020-07-14T00:00:00\",\n \"confirmed\": 937487,\n \"deaths\": 24315,\n \"recovered\": 593080\n },\n {\n \"date\": \"2020-07-15T00:00:00\",\n \"confirmed\": 970596,\n \"deaths\": 24935,\n \"recovered\": 613820\n },\n {\n \"date\": \"2020-07-16T00:00:00\",\n \"confirmed\": 1005760,\n \"deaths\": 25619,\n \"recovered\": 636660\n },\n {\n \"date\": \"2020-07-17T00:00:00\",\n \"confirmed\": 1040746,\n \"deaths\": 26291,\n \"recovered\": 654130\n },\n {\n \"date\": \"2020-07-18T00:00:00\",\n \"confirmed\": 1077864,\n \"deaths\": 26828,\n \"recovered\": 677630\n },\n {\n \"date\": \"2020-07-19T00:00:00\",\n \"confirmed\": 1118780,\n \"deaths\": 27503,\n \"recovered\": 700399\n },\n {\n \"date\": \"2020-07-20T00:00:00\",\n \"confirmed\": 1156189,\n \"deaths\": 28099,\n \"recovered\": 724702\n },\n {\n \"date\": \"2020-07-21T00:00:00\",\n \"confirmed\": 1194888,\n \"deaths\": 28771,\n \"recovered\": 753050\n },\n {\n \"date\": \"2020-07-22T00:00:00\",\n \"confirmed\": 1241509,\n \"deaths\": 29708,\n \"recovered\": 785321\n },\n {\n \"date\": \"2020-07-23T00:00:00\",\n \"confirmed\": 1288130,\n \"deaths\": 30645,\n \"recovered\": 817593\n },\n {\n \"date\": \"2020-07-24T00:00:00\",\n \"confirmed\": 1339067,\n \"deaths\": 31425,\n \"recovered\": 850295\n },\n {\n \"date\": \"2020-07-25T00:00:00\",\n \"confirmed\": 1387481,\n \"deaths\": 32119,\n \"recovered\": 886282\n },\n {\n \"date\": \"2020-07-26T00:00:00\",\n \"confirmed\": 1437976,\n \"deaths\": 32826,\n \"recovered\": 918906\n },\n {\n \"date\": \"2020-07-27T00:00:00\",\n \"confirmed\": 1484136,\n \"deaths\": 33461,\n \"recovered\": 954004\n },\n {\n \"date\": \"2020-07-28T00:00:00\",\n \"confirmed\": 1533936,\n \"deaths\": 34240,\n \"recovered\": 989624\n },\n {\n \"date\": \"2020-07-29T00:00:00\",\n \"confirmed\": 1587982,\n \"deaths\": 35035,\n \"recovered\": 1022565\n },\n {\n \"date\": \"2020-07-30T00:00:00\",\n \"confirmed\": 1643416,\n \"deaths\": 35807,\n \"recovered\": 1059983\n },\n {\n \"date\": \"2020-07-31T00:00:00\",\n \"confirmed\": 1700744,\n \"deaths\": 36562,\n \"recovered\": 1096761\n },\n {\n \"date\": \"2020-08-01T00:00:00\",\n \"confirmed\": 1754117,\n \"deaths\": 37415,\n \"recovered\": 1148103\n },\n {\n \"date\": \"2020-08-02T00:00:00\",\n \"confirmed\": 1805838,\n \"deaths\": 38176,\n \"recovered\": 1188389\n },\n {\n \"date\": \"2020-08-03T00:00:00\",\n \"confirmed\": 1856754,\n \"deaths\": 38993,\n \"recovered\": 1231576\n },\n {\n \"date\": \"2020-08-04T00:00:00\",\n \"confirmed\": 1910681,\n \"deaths\": 39856,\n \"recovered\": 1282917\n },\n {\n \"date\": \"2020-08-05T00:00:00\",\n \"confirmed\": 1964536,\n \"deaths\": 40739,\n \"recovered\": 1328336\n },\n {\n \"date\": \"2020-08-06T00:00:00\",\n \"confirmed\": 2027074,\n \"deaths\": 41638,\n \"recovered\": 1378105\n },\n {\n \"date\": \"2020-08-07T00:00:00\",\n \"confirmed\": 2089773,\n \"deaths\": 42602,\n \"recovered\": 1429100\n },\n {\n \"date\": \"2020-08-08T00:00:00\",\n \"confirmed\": 2156169,\n \"deaths\": 43484,\n \"recovered\": 1481627\n },\n {\n \"date\": \"2020-08-09T00:00:00\",\n \"confirmed\": 2215074,\n \"deaths\": 44466,\n \"recovered\": 1535743\n },\n {\n \"date\": \"2020-08-10T00:00:00\",\n \"confirmed\": 2269052,\n \"deaths\": 45361,\n \"recovered\": 1583489\n },\n {\n \"date\": \"2020-08-11T00:00:00\",\n \"confirmed\": 2332908,\n \"deaths\": 46216,\n \"recovered\": 1640362\n },\n {\n \"date\": \"2020-08-12T00:00:00\",\n \"confirmed\": 2397225,\n \"deaths\": 47184,\n \"recovered\": 1696104\n },\n {\n \"date\": \"2020-08-13T00:00:00\",\n \"confirmed\": 2461542,\n \"deaths\": 48153,\n \"recovered\": 1751846\n },\n {\n \"date\": \"2020-08-14T00:00:00\",\n \"confirmed\": 2527308,\n \"deaths\": 49148,\n \"recovered\": 1809542\n },\n {\n \"date\": \"2020-08-15T00:00:00\",\n \"confirmed\": 2590501,\n \"deaths\": 50099,\n \"recovered\": 1862665\n }\n ],\n \"breakdowns\": [\n {\n \"location\": {\n \"long\": 78.0,\n \"countryOrRegion\": \"India\",\n \"provinceOrState\": null,\n \"county\": null,\n \"isoCode\": \"IN\",\n \"lat\": 21.0\n },\n \"totalConfirmedCases\": 2590501,\n \"newlyConfirmedCases\": 63193,\n \"totalDeaths\": 50099,\n \"newDeaths\": 951,\n \"totalRecoveredCases\": 1862665,\n \"newlyRecoveredCases\": 53123\n }\n ]\n }\n}\n" ], [ "# put all dictionary type data for INDIA into dataframe\ndf_4 = pd.DataFrame(IN_dict)\ndf_4.head()", "_____no_output_____" ] ], [ [ "## Individual states in India", "_____no_output_____" ] ], [ [ "full_list_IN_country=[]\nfor pos,each_dict in enumerate (IN_dict['stats']['breakdowns'][:]):\n flatten_dict=each_dict['location']\n flatten_dict.update(dict(list(IN_dict['stats']['breakdowns'][pos].items())[1: 7]) \n )\n full_list_IN_country.append(flatten_dict)", "_____no_output_____" ], [ "df_india = pd.DataFrame(full_list_IN_country)", "_____no_output_____" ], [ "pd.DataFrame(full_list_IN_country).to_csv('../data/raw/SMARTABLE/full_list_IN_country.csv',sep=';',index=False)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cbdee49d9e1f0ac4d969a454bae8d07aab1d3f15
948,974
ipynb
Jupyter Notebook
Chapter3_MCMC/IntroMCMC.ipynb
brianzhang01/Bayesian-Methods-for-Hackers
f0ce2a6d35ac5a839c89b306ab5bda603e2f31bd
[ "MIT" ]
2
2018-02-28T06:01:33.000Z
2019-03-04T02:32:34.000Z
Chapter3_MCMC/IntroMCMC.ipynb
brianzhang01/Bayesian-Methods-for-Hackers
f0ce2a6d35ac5a839c89b306ab5bda603e2f31bd
[ "MIT" ]
null
null
null
Chapter3_MCMC/IntroMCMC.ipynb
brianzhang01/Bayesian-Methods-for-Hackers
f0ce2a6d35ac5a839c89b306ab5bda603e2f31bd
[ "MIT" ]
1
2018-06-04T21:46:21.000Z
2018-06-04T21:46:21.000Z
636.041555
119,391
0.927593
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cbdeea34bc911e227a3c443ffb63eb2ae22e56b6
9,960
ipynb
Jupyter Notebook
23/Day 23 - Amphipod.ipynb
GreyGooClub/Advent2021-DTC
a5d80e4b20d8619fdc437b3d7624cf3651a01e1f
[ "MIT" ]
null
null
null
23/Day 23 - Amphipod.ipynb
GreyGooClub/Advent2021-DTC
a5d80e4b20d8619fdc437b3d7624cf3651a01e1f
[ "MIT" ]
null
null
null
23/Day 23 - Amphipod.ipynb
GreyGooClub/Advent2021-DTC
a5d80e4b20d8619fdc437b3d7624cf3651a01e1f
[ "MIT" ]
null
null
null
32.129032
115
0.435141
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cbdef4d01a73fdad9d87254b87ccd123c2a4ed58
28,893
ipynb
Jupyter Notebook
notebooks/embeddings_insights.ipynb
megaelius/EPAA
38900be53d6544becf8c51ed1de0501fd639b9c8
[ "FTL" ]
null
null
null
notebooks/embeddings_insights.ipynb
megaelius/EPAA
38900be53d6544becf8c51ed1de0501fd639b9c8
[ "FTL" ]
null
null
null
notebooks/embeddings_insights.ipynb
megaelius/EPAA
38900be53d6544becf8c51ed1de0501fd639b9c8
[ "FTL" ]
null
null
null
37.867628
1,536
0.565154
[ [ [ "import torch\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport random\n%matplotlib inline", "_____no_output_____" ], [ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nimport glob\nimport os.path\nfrom tqdm import tqdm", "_____no_output_____" ], [ "predictionDB = pd.read_csv(\"../data/processed/predictionDB.csv\",lineterminator='\\n')\n\nembeddings = [None]*len(predictionDB)\ni=0\nk=0\n#for np_name in glob.glob('./../data/processed/embeddings/*.np[yz]'):\n# embeddings[i] = np.load(np_name)\n# i = i + 1\n\nfor x in predictionDB[\"COMMIT_HASH\"]:\n embeddings[i] = np.load(\"./../data/processed/embeddings2/\"+x+\".npy\")\n i = i + 1\n\nembeddings\nprint(len(predictionDB),i)", "62917 62917\n" ], [ "'''\nclean = ''\nfor i,s in enumerate(predictionDB[\"COMMIT_MESSAGE\"][3].split()[:-3]):\n if i!=0:\n clean+= ' '\n clean+=s\nprint(clean)\n'''", "_____no_output_____" ], [ "'''\nclean_column = [None]*len(predictionDB[\"COMMIT_MESSAGE\"])\nfor i in range(len(predictionDB[\"COMMIT_MESSAGE\"])):\n clean = ''\n for j,s in enumerate(predictionDB[\"COMMIT_MESSAGE\"][i].split()[:-3]):\n if j!=0:\n clean+= ' '\n clean+=s\n clean_column[i] = clean\n if not len(clean):\n clean_column[i] = predictionDB[\"COMMIT_MESSAGE\"]\npredictionDB[\"CLEAN_CMS\"] = clean_column\n'''", "_____no_output_____" ], [ "# predictionDB.to_csv(\"../data/processed/predictionDB2.csv\", index='False') #export!", "_____no_output_____" ], [ "#a = predictionDB[\"CLEAN_CMS\"].to_frame()\n#np.where(a.applymap(lambda x: x == ''))", "_____no_output_____" ], [ "predictionDB[\"CLEAN_CMS\"][4355]", "_____no_output_____" ], [ "from scipy import spatial", "_____no_output_____" ], [ "a = predictionDB[\"CLEAN_CMS\"][2]\nb = predictionDB[\"CLEAN_CMS\"][3]\nc = predictionDB[\"CLEAN_CMS\"][62912]\nemb_a = embeddings[2]\nemb_b = embeddings[3]\nemb_c = embeddings[62912]\nprint(\"a =\",a)\nprint(\"b =\",b)\nprint(\"c =\",c[:73])\nprint(\"\")\nprint(\"Similarity {emb(a),emb(b)} = %.2f\" % (1-spatial.distance.cosine(emb_a, emb_b)))\nprint(\"Similarity {emb(a),emb(c)} = %.2f\" % (1-spatial.distance.cosine(emb_a, emb_c)))\nprint(\"Similarity {emb(b),emb(c)} = %.2f\" % (1-spatial.distance.cosine(emb_b, emb_c)))\n\nprint(\"_______________________________________________________________________________________\")\nprint(\"\")\n\na = predictionDB[\"CLEAN_CMS\"][6788]\nb = predictionDB[\"CLEAN_CMS\"][6787]\nc = predictionDB[\"CLEAN_CMS\"][4444]\nemb_a = embeddings[6788]\nemb_b = embeddings[6787]\nemb_c = embeddings[4444]\n\nprint(\"a =\",a)\nprint(\"b =\",b)\nprint(\"c =\",c)\nprint(\"\")\nprint(\"Similarity {emb(a),emb(b)} = %.2f\" % (1-spatial.distance.cosine(emb_a, emb_b)))\nprint(\"Similarity {emb(a),emb(c)} = %.2f\" % (1-spatial.distance.cosine(emb_a, emb_c)))\nprint(\"Similarity {emb(b),emb(c)} = %.2f\" % (1-spatial.distance.cosine(emb_b, emb_c)))", "a = add test PR: MRM-9\nb = add some more tests PR: MRM-9\nc = ZOOKEEPER-2172: Cluster crashes when reconfig a new node as a participant\n\nSimilarity {emb(a),emb(b)} = 0.95\nSimilarity {emb(a),emb(c)} = 0.09\nSimilarity {emb(b),emb(c)} = 0.14\n_______________________________________________________________________________________\n\na = http://issues.apache.org/bugzilla/show_bug.cgi?id=40577\nb = http://issues.apache.org/bugzilla/show_bug.cgi?id=39695\nc = [MRM-1578] add layout\n\nSimilarity {emb(a),emb(b)} = 1.00\nSimilarity {emb(a),emb(c)} = 0.13\nSimilarity {emb(b),emb(c)} = 0.13\n" ], [ "a = predictionDB[\"CLEAN_CMS\"][6788]\nb = predictionDB[\"CLEAN_CMS\"][6787]\nc = predictionDB[\"CLEAN_CMS\"][4444]\nemb_a = embeddings[6788]\nemb_b = embeddings[6787]\nemb_c = embeddings[4444]\nprint(\"Commit msg a =\",a)\nprint(\"Commit msg b =\",b)\nprint(\"Commit msg c =\",c)\nprint(\"\")\nprint(\"Cosine similarity (a,b) = \",1-spatial.distance.cosine(emb_a, emb_b))\nprint(\"Cosine similarity (a,c) = \",1-spatial.distance.cosine(emb_a, emb_c))\nprint(\"Cosine similarity (b,c) = \",1-spatial.distance.cosine(emb_b, emb_c))", "Commit msg a = http://issues.apache.org/bugzilla/show_bug.cgi?id=40577\nCommit msg b = http://issues.apache.org/bugzilla/show_bug.cgi?id=39695\nCommit msg c = [MRM-1578] add layout\n\nCosine similarity (a,b) = 0.9983712434768677\nCosine similarity (a,c) = 0.13024194538593292\nCosine similarity (b,c) = 0.13068857789039612\n" ], [ "print(spatial.distance.cosine(emb_a, emb_c))", "0.5867696702480316\n" ], [ "embeddings2 = pd.Series( (v for v in embeddings) )\nembeddings2", "_____no_output_____" ], [ "#data = embeddings\nlabels = predictionDB[\"inc_complexity\"]\n\nfor i in range(len(labels)):\n if labels[i]<=0:\n labels[i]=0\n else:\n labels[i]=1\n\nlabels", "/usr/local/lib/python3.7/site-packages/ipykernel_launcher.py:6: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n/usr/local/lib/python3.7/site-packages/ipykernel_launcher.py:8: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n" ], [ "from sklearn.model_selection import train_test_split\n\n\ndata_train, data_test, labels_train, labels_test = train_test_split(embeddings2, labels, test_size=0.20, random_state=42)\n", "_____no_output_____" ], [ "labels_train.shape", "_____no_output_____" ], [ "type(embeddings2)", "_____no_output_____" ], [ "class commits_dataset(Dataset):\n def __init__(self, X, y):\n self.X = X\n self.y = y\n\n def __len__(self):\n return len(self.X.index)\n \n def __getitem__(self, index):\n return torch.Tensor(self.X.iloc[index]),torch.as_tensor(self.y.iloc[index]).float()", "_____no_output_____" ], [ "commits_dataset_train = commits_dataset(X=data_train,y=labels_train)\ncommits_dataset_test = commits_dataset(X=data_test,y=labels_test)\n# print(commits_dataset_train[0])", "_____no_output_____" ], [ "train_loader = DataLoader(dataset=commits_dataset_train, batch_size=32, shuffle=True)\nvalid_loader = DataLoader(dataset=commits_dataset_test, batch_size=32, shuffle=False)\n#dls = DataLoaders(train_loader,valid_loader)\n", "_____no_output_____" ], [ "#predictionDB[\"is_valid\"] = np.zeros(len(predictionDB))\n#for i in range(len(predictionDB[\"is_valid\"])):\n# predictionDB[\"is_valid\"][i] = 1 if random.random()<0.2 else 0 ", "_____no_output_____" ], [ "#from fastai.text.all import *\n#dls = TextDataLoaders.from_df(predictionDB, text_col='COMMIT_MESSAGE', label_col='inc_complexity', valid_col='is_valid')\n#dls.show_batch(max_n=3)", "_____no_output_____" ], [ "# Multilayer perceptron\nclass MultilayerPerceptron(nn.Module):\n def __init__(self):\n super().__init__()\n self.lin1 = nn.Linear(384, 512, bias=True) \n self.lin2 = nn.Linear(512, 256, bias=True)\n self.lin3 = nn.Linear(256, 1, bias=True)\n\n def forward(self, xb):\n x = xb.float()\n #x = xb.view(250, -1)\n x = F.relu(self.lin1(x))\n x = F.relu(self.lin2(x))\n return self.lin3(x)", "_____no_output_____" ], [ "#mlp_learner = Learner(data=data, model=MultilayerPerceptron(), loss_func=nn.CrossEntropyLoss(),metrics=accuracy)\n#mlp_learner.fine_tune(20)", "_____no_output_____" ], [ "model = MultilayerPerceptron()\nprint(model)", "MultilayerPerceptron(\n (lin1): Linear(in_features=384, out_features=512, bias=True)\n (lin2): Linear(in_features=512, out_features=256, bias=True)\n (lin3): Linear(in_features=256, out_features=1, bias=True)\n)\n" ], [ "optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)\nloss_fn = nn.BCELoss()", "_____no_output_____" ], [ "mean_train_losses = []\nmean_valid_losses = []\nvalid_acc_list = []\nepochs = 100\n\nfor epoch in range(epochs):\n model.train()\n \n train_losses = []\n valid_losses = []\n for i, (embeddings, labels) in tqdm(enumerate(train_loader)):\n \n optimizer.zero_grad()\n \n outputs = model(embeddings)\n loss = loss_fn(outputs.squeeze(0),labels)\n loss.backward()\n optimizer.step()\n \n train_losses.append(loss.item())\n \n \n model.eval()\n correct = 0\n total = 0\n with torch.no_grad():\n for i, (embeddings, labels) in enumerate(valid_loader):\n outputs = model(embeddings)\n loss = loss_fn(outputs.squeeze(0), labels)\n \n valid_losses.append(loss.item())\n \n _, predicted = torch.max(outputs.data, 1)\n \n total += labels.size(0)\n \n mean_train_losses.append(np.mean(train_losses))\n mean_valid_losses.append(np.mean(valid_losses))\n print('epoch : {}, train loss : {:.4f}, valid loss : {:.4f}'\\\n .format(epoch+1, mean_train_losses[-1], mean_valid_losses[-1]))", "0it [00:00, ?it/s]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdef52de17de6b3b834b8251182ff02caf2e86d
582,120
ipynb
Jupyter Notebook
intro-to-pytorch/Part 7 - Loading Image Data (Exercises).ipynb
faber6911/deep-learning-v2-pytorch
d11ddf5c73d0f59e7c2ba6fb2265d575b160cd71
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 7 - Loading Image Data (Exercises).ipynb
faber6911/deep-learning-v2-pytorch
d11ddf5c73d0f59e7c2ba6fb2265d575b160cd71
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 7 - Loading Image Data (Exercises).ipynb
faber6911/deep-learning-v2-pytorch
d11ddf5c73d0f59e7c2ba6fb2265d575b160cd71
[ "MIT" ]
null
null
null
582,120
582,120
0.940243
[ [ [ "from google.colab import drive\n\nROOT = \"/content/drive\"\n\ndrive.mount(ROOT)", "Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n\nEnter your authorization code:\n··········\nMounted at /content/drive\n" ], [ "%cd \"/content/drive/My Drive/Learning/deep-learning-v2-pytorch/intro-to-pytorch\"", "/content/drive/My Drive/Learning/deep-learning-v2-pytorch/intro-to-pytorch\n" ] ], [ [ "# Loading Image Data\n\nSo far we've been working with fairly artificial datasets that you wouldn't typically be using in real projects. Instead, you'll likely be dealing with full-sized images like you'd get from smart phone cameras. In this notebook, we'll look at how to load images and use them to train neural networks.\n\nWe'll be using a [dataset of cat and dog photos](https://www.kaggle.com/c/dogs-vs-cats) available from Kaggle. Here are a couple example images:\n\n<img src='assets/dog_cat.png'>\n\nWe'll use this dataset to train a neural network that can differentiate between cats and dogs. These days it doesn't seem like a big accomplishment, but five years ago it was a serious challenge for computer vision systems.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torchvision import datasets, transforms\n\nimport helper", "_____no_output_____" ] ], [ [ "The easiest way to load image data is with `datasets.ImageFolder` from `torchvision` ([documentation](http://pytorch.org/docs/master/torchvision/datasets.html#imagefolder)). In general you'll use `ImageFolder` like so:\n\n```python\ndataset = datasets.ImageFolder('path/to/data', transform=transform)\n```\n\nwhere `'path/to/data'` is the file path to the data directory and `transform` is a list of processing steps built with the [`transforms`](http://pytorch.org/docs/master/torchvision/transforms.html) module from `torchvision`. ImageFolder expects the files and directories to be constructed like so:\n```\nroot/dog/xxx.png\nroot/dog/xxy.png\nroot/dog/xxz.png\n\nroot/cat/123.png\nroot/cat/nsdf3.png\nroot/cat/asd932_.png\n```\n\nwhere each class has it's own directory (`cat` and `dog`) for the images. The images are then labeled with the class taken from the directory name. So here, the image `123.png` would be loaded with the class label `cat`. You can download the dataset already structured like this [from here](https://s3.amazonaws.com/content.udacity-data.com/nd089/Cat_Dog_data.zip). I've also split it into a training set and test set.\n\n### Transforms\n\nWhen you load in the data with `ImageFolder`, you'll need to define some transforms. For example, the images are different sizes but we'll need them to all be the same size for training. You can either resize them with `transforms.Resize()` or crop with `transforms.CenterCrop()`, `transforms.RandomResizedCrop()`, etc. We'll also need to convert the images to PyTorch tensors with `transforms.ToTensor()`. Typically you'll combine these transforms into a pipeline with `transforms.Compose()`, which accepts a list of transforms and runs them in sequence. It looks something like this to scale, then crop, then convert to a tensor:\n\n```python\ntransform = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor()])\n\n```\n\nThere are plenty of transforms available, I'll cover more in a bit and you can read through the [documentation](http://pytorch.org/docs/master/torchvision/transforms.html). \n\n### Data Loaders\n\nWith the `ImageFolder` loaded, you have to pass it to a [`DataLoader`](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader). The `DataLoader` takes a dataset (such as you would get from `ImageFolder`) and returns batches of images and the corresponding labels. You can set various parameters like the batch size and if the data is shuffled after each epoch.\n\n```python\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)\n```\n\nHere `dataloader` is a [generator](https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/). To get data out of it, you need to loop through it or convert it to an iterator and call `next()`.\n\n```python\n# Looping through it, get a batch on each loop \nfor images, labels in dataloader:\n pass\n\n# Get one batch\nimages, labels = next(iter(dataloader))\n```\n \n>**Exercise:** Load images from the `Cat_Dog_data/train` folder, define a few transforms, then build the dataloader.", "_____no_output_____" ] ], [ [ "data_dir = 'Cat_Dog_data/train'\n\ntransform = transforms.Compose([transforms.Resize(225),\n transforms.CenterCrop(224),\n transforms.ToTensor()]) # TODO: compose transforms here\n\ndataset = datasets.ImageFolder(data_dir, transform = transform)\n# TODO: create the ImageFolder\ndataloader = torch.utils.data.DataLoader(dataset, batch_size = 63, shuffle = True)\n# TODO: use the ImageFolder dataset to create the DataLoader", "_____no_output_____" ], [ "# Run this to test your data loader\nimages, labels = next(iter(dataloader))\nhelper.imshow(images[0], normalize=False)", "_____no_output_____" ] ], [ [ "If you loaded the data correctly, you should see something like this (your image will be different):\n\n<img src='assets/cat_cropped.png' width=244>", "_____no_output_____" ], [ "## Data Augmentation\n\nA common strategy for training neural networks is to introduce randomness in the input data itself. For example, you can randomly rotate, mirror, scale, and/or crop your images during training. This will help your network generalize as it's seeing the same images but in different locations, with different sizes, in different orientations, etc.\n\nTo randomly rotate, scale and crop, then flip your images you would define your transforms like this:\n\n```python\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], \n [0.5, 0.5, 0.5])])\n```\n\nYou'll also typically want to normalize images with `transforms.Normalize`. You pass in a list of means and list of standard deviations, then the color channels are normalized like so\n\n```input[channel] = (input[channel] - mean[channel]) / std[channel]```\n\nSubtracting `mean` centers the data around zero and dividing by `std` squishes the values to be between -1 and 1. Normalizing helps keep the network work weights near zero which in turn makes backpropagation more stable. Without normalization, networks will tend to fail to learn.\n\nYou can find a list of all [the available transforms here](http://pytorch.org/docs/0.3.0/torchvision/transforms.html). When you're testing however, you'll want to use images that aren't altered (except you'll need to normalize the same way). So, for validation/test images, you'll typically just resize and crop.\n\n>**Exercise:** Define transforms for training data and testing data below. Leave off normalization for now.", "_____no_output_____" ] ], [ [ "data_dir = 'Cat_Dog_data'\n\n# TODO: Define transforms for the training data and testing data\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([.5, .5, .5],\n [.5, .5, .5])])\n\ntest_transforms = transforms.Compose([transforms.Resize(225),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([.5, .5, .5],\n [.5, .5, .5])])\n\n\n# Pass transforms in here, then run the next cell to see how the transforms look\ntrain_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)\ntest_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)\n\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=32)\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=32)", "_____no_output_____" ], [ "# change this to the trainloader or testloader \ndata_iter = iter(testloader)\n\nimages, labels = next(data_iter)\nfig, axes = plt.subplots(figsize=(10,4), ncols=4)\nfor ii in range(4):\n ax = axes[ii]\n helper.imshow(images[ii], ax=ax, normalize=False)", "Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\nClipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\nClipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\nClipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\n" ] ], [ [ "Your transformed images should look something like this.\n\n<center>Training examples:</center>\n<img src='assets/train_examples.png' width=500px>\n\n<center>Testing examples:</center>\n<img src='assets/test_examples.png' width=500px>", "_____no_output_____" ], [ "At this point you should be able to load data for training and testing. Now, you should try building a network that can classify cats vs dogs. This is quite a bit more complicated than before with the MNIST and Fashion-MNIST datasets. To be honest, you probably won't get it to work with a fully-connected network, no matter how deep. These images have three color channels and at a higher resolution (so far you've seen 28x28 images which are tiny).\n\nIn the next part, I'll show you how to use a pre-trained network to build a model that can actually solve this problem.", "_____no_output_____" ] ], [ [ "from torch import nn\nimport torch.nn.functional as F\nfrom torch import optim", "_____no_output_____" ], [ "fake_list = [100, 200, 300, 500]", "_____no_output_____" ], [ "# Optional TODO: Attempt to build a network to classify cats vs dogs from this dataset\n\nclass MyNet(nn.Module):\n def __init__(self, input_size, fc1, fc2, fc3, classes):\n super().__init__()\n self.fc1 = nn.Linear(input_size, fc1)\n self.fc2 = nn.Linear(fc1, fc2)\n self.fc3 = nn.Linear(fc2, fc3)\n self.output = nn.Linear(fc3, classes)\n self.dropout = nn.Dropout(p = .2)\n\n def forward(self, x):\n x = x.view(x.shape[0], -1)\n x = self.dropout(F.relu(self.fc1(x)))\n x = self.dropout(F.relu(self.fc2(x)))\n x = self.dropout(F.relu(self.fc3(x)))\n x = F.log_softmax(self.output(x), dim = 1)\n\n return x", "_____no_output_____" ], [ "classes = len(trainloader.dataset.classes)\ninput_size = 224*224*3\nfc1 = 512\nfc2 = 256\nfc3 = 128", "_____no_output_____" ], [ "model = MyNet(input_size, fc1, fc2, fc3, classes)\ncriterion = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters())\n\n\nepochs = 10\n\nacc_history, val_acc_history, train_losses, test_losses = [], [], [], []\n\nfor e in range(epochs):\n acc = 0\n running_loss = 0\n for images, labels in trainloader:\n optimizer.zero_grad()\n\n log_ps = model(images)\n ps = torch.exp(log_ps)\n loss = criterion(log_ps, labels)\n _, top_class = ps.topk(1, dim = 1)\n equals = top_class == labels.view(*top_class.shape)\n acc = torch.mean(equals.type(torch.FloatTensor))\n\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n else:\n val_acc = 0\n val_loss = 0\n with torch.no_grad():\n model.eval()\n for images, labels in testloader:\n log_ps = model(images)\n ps = torch.exp(log_ps)\n loss = criterion(log_ps, labels)\n _, top_class = ps.topk(1, dim = 1)\n equals = top_class == labels.view(*top_class.shape)\n val_acc = torch.mean(equals.type(torch.FloatTensor))\n val_loss += loss.item()\n\n model.train()\n acc_history.append(acc.item())\n val_acc_history.append(val_acc.item())\n train_losses.append(running_loss/len(trainloader))\n test_losses.append(val_loss/len(testloader))\n\n print(\"Epoch: {}/{}\".format(e+1, epochs))\n print(\"loss: {}, val_loss: {}, acc: {}, val_acc: {}\".format(running_loss/len(trainloader), val_loss/len(testloader), acc.item(), val_acc.item()))\n\n\n ", "_____no_output_____" ] ], [ [ "images are too big using fc layers", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cbdefe80a277d70289eacffd5ab845f435ca86d4
5,341
ipynb
Jupyter Notebook
src/dataset_maker/Clastering.ipynb
Dmitriy1594/TelegramParser
163c5d26798b302bf37754f95e2d6623f23a13a8
[ "MIT" ]
1
2021-07-14T19:56:50.000Z
2021-07-14T19:56:50.000Z
src/dataset_maker/Clastering.ipynb
dromakin/TelegramParser
163c5d26798b302bf37754f95e2d6623f23a13a8
[ "MIT" ]
null
null
null
src/dataset_maker/Clastering.ipynb
dromakin/TelegramParser
163c5d26798b302bf37754f95e2d6623f23a13a8
[ "MIT" ]
null
null
null
28.259259
1,462
0.558884
[ [ [ "https://scikit-learn.org/stable/modules/clustering.html", "_____no_output_____" ] ], [ [ "document = [\"This is the most beautiful place in the world.\", \"This man has more skills to show in cricket than any other game.\", \"Hi there! how was your ladakh trip last month?\", \"There was a player who had scored 200+ runs in single cricket innings in his career.\", \"I have got the opportunity to travel to Paris next year for my internship.\", \"May be he is better than you in batting but you are much better than him in bowling.\", \"That was really a great day for me when I was there at Lavasa for the whole night.\", \"That’s exactly I wanted to become, a highest ratting batsmen ever with top scores.\", \"Does it really matter wether you go to Thailand or Goa, its just you have spend your holidays.\", \"Why don’t you go to Switzerland next year for your 25th Wedding anniversary?\", \"Travel is fatal to prejudice, bigotry, and narrow mindedness., and many of our people need it sorely on these accounts.\", \"Stop worrying about the potholes in the road and enjoy the journey.\", \"No cricket team in the world depends on one or two players. The team always plays to win.\", \"Cricket is a team game. If you want fame for yourself, go play an individual game.\", \"Because in the end, you won’t remember the time you spent working in the office or mowing your lawn. Climb that goddamn mountain.\", \"Isn’t cricket supposed to be a team sport? I feel people should decide first whether cricket is a team game or an individual sport.\"]", "_____no_output_____" ], [ "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans\nimport numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "vectorizer = TfidfVectorizer(stop_words='english')\nX = vectorizer.fit_transform(document)", "_____no_output_____" ], [ "true_k = 4\nmodel = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1)\nmodel.fit(X)", "_____no_output_____" ], [ "order_centroids = model.cluster_centers_.argsort()[:, ::-1]\nterms = vectorizer.get_feature_names()", "_____no_output_____" ], [ "for i in range(true_k):\n print(\"Cluster %d:\" % i),\n for ind in order_centroids[i, :10]:\n print(' %s' % terms[ind])", "Cluster 0:\n better\n really\n hi\n ladakh\n month\n trip\n lavasa\n day\n great\n night\nCluster 1:\n cricket\n team\n game\n world\n beautiful\n place\n man\n skills\n individual\n sport\nCluster 2:\n year\n travel\n got\n paris\n opportunity\n internship\n don\n switzerland\n anniversary\n wedding\nCluster 3:\n mountain\n time\n mowing\n office\n goddamn\n remember\n end\n spent\n climb\n lawn\n" ], [ "print(\"Prediction\")\nX = vectorizer.transform([\"Nothing is easy in cricket. Maybe when you watch it on TV, it looks easy. But it is not. You have to use your brain and time the ball.\"])\npredicted = model.predict(X)\nprint(predicted)", "Prediction\n[1]\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
cbdf0b5b9220837890b155ce566d8289e122fc6b
34,044
ipynb
Jupyter Notebook
DataScience_Project1_Predict_products_sales_in_Walmart/station_4.ipynb
jaykim-asset/datascience_review
c55782f5d4226e179088346da399e299433c6ca6
[ "MIT" ]
4
2018-05-30T10:39:47.000Z
2018-11-10T15:39:53.000Z
DataScience_Project1_Predict_products_sales_in_Walmart/station_4.ipynb
jaykim-asset/datascience_review
c55782f5d4226e179088346da399e299433c6ca6
[ "MIT" ]
null
null
null
DataScience_Project1_Predict_products_sales_in_Walmart/station_4.ipynb
jaykim-asset/datascience_review
c55782f5d4226e179088346da399e299433c6ca6
[ "MIT" ]
null
null
null
39.402778
193
0.375925
[ [ [ "from statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom sklearn.model_selection import KFold\nfrom sklearn.datasets import make_regression\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import cross_val_score\n\n\n%matplotlib inline\n%config InlineBackend.figure_formats = {'png', 'retina'}\npd.options.mode.chained_assignment = None # default='warn'?\n\n# data_key DataFrame\ndata_key = pd.read_csv('key.csv')\n\n# data_train DataFrame\ndata_train = pd.read_csv('train.csv')\n\n# data_weather DataFrame\ndata_weather = pd.read_csv('weather.csv')\n\nrain_text = ['FC', 'TS', 'GR', 'RA', 'DZ', 'SN', 'SG', 'GS', 'PL', 'IC', 'FG', 'BR', 'UP', 'FG+']\nother_text = ['HZ', 'FU', 'VA', 'DU', 'DS', 'PO', 'SA', 'SS', 'PY', 'SQ', 'DR', 'SH', 'FZ', 'MI', 'PR', 'BC', 'BL', 'VC' ]\n\ndata_weather['codesum'].replace(\"+\", \"\")\na = []\nfor i in range(len(data_weather['codesum'])):\n a.append(data_weather['codesum'].values[i].split(\" \"))\n for i_text in a[i]:\n if len(i_text) == 4:\n a[i].append(i_text[:2])\n a[i].append(i_text[2:])\n \ndata_weather[\"nothing\"] = 1\ndata_weather[\"rain\"] = 0\ndata_weather[\"other\"] = 0\nb = -1\nfor ls in a:\n b += 1\n for text in ls:\n if text in rain_text:\n data_weather.loc[b, 'rain'] = 1\n data_weather.loc[b, 'nothing'] = 0\n elif text in other_text:\n data_weather.loc[b,'other'] = 1\n data_weather.loc[b, 'nothing'] = 0 \n# 모든 데이터 Merge\ndf = pd.merge(data_weather, data_key)\n\nstation_nbr = df['station_nbr']\ndf.drop('station_nbr', axis=1, inplace=True)\ndf['station_nbr'] = station_nbr\n\ndf = pd.merge(df, data_train)\n\n# T 값 처리 하기. Remained Subject = > 'M' and '-'\ndf['snowfall'][df['snowfall'] == ' T'] = 0.05\ndf['preciptotal'][df['preciptotal'] == ' T'] = 0.005\n\n# 주말과 주중 구분 작업 하기\ndf['date'] = pd.to_datetime(df['date'])\ndf['week7'] = df['date'].dt.dayofweek\ndf['weekend'] = 0\ndf.loc[df['week7'] == 5, 'weekend'] = 1\ndf.loc[df['week7'] == 6, 'weekend'] = 1\n\ndf1 = df[df['station_nbr'] == 1]; df11 = df[df['station_nbr'] == 11]\ndf2 = df[df['station_nbr'] == 2]; df12 = df[df['station_nbr'] == 12]\ndf3 = df[df['station_nbr'] == 3]; df13 = df[df['station_nbr'] == 13]\ndf4 = df[df['station_nbr'] == 4]; df14 = df[df['station_nbr'] == 14]\ndf5 = df[df['station_nbr'] == 5]; df15 = df[df['station_nbr'] == 15]\ndf6 = df[df['station_nbr'] == 6]; df16 = df[df['station_nbr'] == 16]\ndf7 = df[df['station_nbr'] == 7]; df17 = df[df['station_nbr'] == 17]\ndf8 = df[df['station_nbr'] == 8]; df18 = df[df['station_nbr'] == 18]\ndf9 = df[df['station_nbr'] == 9]; df19 = df[df['station_nbr'] == 19]\ndf10 = df[df['station_nbr'] == 10]; df20 = df[df['station_nbr'] == 20]", "_____no_output_____" ], [ "df4 = df4.apply(pd.to_numeric, errors = 'coerce')\ndf4.describe().iloc[:, 14:]\n# 없는 Column = codesum, station_nbr, date, store_nbr", "_____no_output_____" ], [ "df4_drop_columns = ['date', 'station_nbr', 'codesum', 'store_nbr']\ndf4 = df4.drop(columns = df4_drop_columns)", "_____no_output_____" ], [ "df4['store_nbr'].unique()", "_____no_output_____" ], [ "# np.nan를 포함하고 있는 변수(column)를 찾아서, 그 변수에 mean 값 대입해서 Frame의 모든 Value가 fill 되게 하기.\ndf4_columns = df4.columns\n\n# Cateogry 값을 포함하는 변수는 np.nan에 mode값으로 대체하고, 나머지 실수 값을 포함한 변수는 np.nan에 mean값으로 대체\nfor i in df4_columns:\n if (i == 'resultdir'):\n df4[i].fillna(df4[i].mode()[0], inplace=True)\n print(df4[i].mode()[0])\n else:\n df4[i].fillna(df4[i].mean(), inplace=True)\n\n# 이제 모든 변수가 숫자로 표기 되었기 때문에, 가능 함. \n# 상대 습도 추가 #\ndf4['relative_humility'] = 100*(np.exp((17.625*((df4['dewpoint']-32)/1.8))/(243.04+((df4['dewpoint']-32)/1.8)))/np.exp((17.625*((df4['tavg']-32)/1.8))/(243.04+((df4['tavg']-32)/1.8))))\n\n# 체감온도 계산\ndf4[\"windchill\"] = 35.74 + 0.6215*df4[\"tavg\"] - 35.75*(df4[\"avgspeed\"]**0.16) + 0.4275*df4[\"tavg\"]*(df4[\"avgspeed\"]**0.16)\n\ndf4 = df4[df4['units'] != 0]", "17.0\n" ], [ "model_df4 = sm.OLS.from_formula('np.log1p(units) ~ tmax + tmin + tavg + dewpoint + wetbulb + heat + cool + preciptotal + stnpressure + \\\nsealevel + resultspeed + resultdir + avgspeed + C(nothing) + C(rain) + C(other) + C(item_nbr) + C(week7) + \\\nC(weekend) + relative_humility + windchill + 0', data = df4)\nresult_df4 = model_df4.fit()\n\nprint(result_df4.summary())", " OLS Regression Results \n==============================================================================\nDep. Variable: np.log1p(units) R-squared: 0.781\nModel: OLS Adj. R-squared: 0.779\nMethod: Least Squares F-statistic: 364.1\nDate: Wed, 04 Jul 2018 Prob (F-statistic): 0.00\nTime: 13:34:09 Log-Likelihood: -2196.0\nNo. Observations: 2890 AIC: 4450.\nDf Residuals: 2861 BIC: 4623.\nDf Model: 28 \nCovariance Type: nonrobust \n======================================================================================\n coef std err t P>|t| [0.025 0.975]\n--------------------------------------------------------------------------------------\nC(nothing)[0] -0.0654 0.045 -1.439 0.150 -0.155 0.024\nC(nothing)[1] 0.0639 0.045 1.408 0.159 -0.025 0.153\nC(rain)[T.1] 0.1099 0.089 1.241 0.215 -0.064 0.284\nC(other)[T.1] -0.0342 0.042 -0.812 0.417 -0.117 0.048\nC(item_nbr)[T.23] -0.9198 0.024 -37.880 0.000 -0.967 -0.872\nC(item_nbr)[T.59] -2.4648 0.029 -86.342 0.000 -2.521 -2.409\nC(item_nbr)[T.84] -2.4024 0.066 -36.380 0.000 -2.532 -2.273\nC(item_nbr)[T.93] -1.7960 0.041 -44.089 0.000 -1.876 -1.716\nC(item_nbr)[T.100] -2.2950 0.036 -63.143 0.000 -2.366 -2.224\nC(week7)[T.1] -0.0908 0.036 -2.494 0.013 -0.162 -0.019\nC(week7)[T.2] -0.1369 0.037 -3.724 0.000 -0.209 -0.065\nC(week7)[T.3] -0.1795 0.036 -4.932 0.000 -0.251 -0.108\nC(week7)[T.4] -0.0827 0.036 -2.284 0.022 -0.154 -0.012\nC(week7)[T.5] -0.0316 0.021 -1.504 0.133 -0.073 0.010\nC(week7)[T.6] 0.1021 0.021 4.849 0.000 0.061 0.143\nC(weekend)[T.1] 0.0705 0.021 3.347 0.001 0.029 0.112\ntmax -0.0016 0.005 -0.328 0.743 -0.011 0.008\ntmin -0.0039 0.005 -0.800 0.424 -0.013 0.006\ntavg -0.0082 0.047 -0.173 0.862 -0.100 0.084\ndewpoint -0.0091 0.009 -0.956 0.339 -0.028 0.010\nwetbulb 0.0107 0.006 1.760 0.079 -0.001 0.023\nheat -0.0404 0.045 -0.900 0.368 -0.128 0.048\ncool 0.0502 0.044 1.138 0.255 -0.036 0.137\npreciptotal 0.0859 0.041 2.109 0.035 0.006 0.166\nstnpressure -0.1125 0.361 -0.311 0.756 -0.821 0.596\nsealevel 0.2941 0.365 0.805 0.421 -0.422 1.010\nresultspeed -0.0083 0.011 -0.789 0.430 -0.029 0.012\nresultdir 0.0010 0.001 0.869 0.385 -0.001 0.003\navgspeed -0.0108 0.012 -0.873 0.383 -0.035 0.013\nrelative_humility 0.0030 0.005 0.635 0.525 -0.006 0.012\nwindchill -0.0255 0.016 -1.590 0.112 -0.057 0.006\n==============================================================================\nOmnibus: 133.981 Durbin-Watson: 2.040\nProb(Omnibus): 0.000 Jarque-Bera (JB): 412.628\nSkew: -0.146 Prob(JB): 2.51e-90\nKurtosis: 4.828 Cond. No. 2.77e+16\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The smallest eigenvalue is 1.27e-25. This might indicate that there are\nstrong multicollinearity problems or that the design matrix is singular.\n" ], [ "anova_result_df4 = sm.stats.anova_lm(result_df4, typ=2).sort_values(by=['PR(>F)'], ascending = False)\nanova_result_df4[anova_result_df4['PR(>F)'] <= 0.05]", "_____no_output_____" ], [ "vif = pd.DataFrame()\nvif[\"VIF Factor\"] = [variance_inflation_factor(df4.values, i) for i in range(df4.shape[1])]\nvif[\"features\"] = df4.columns\nvif = vif.sort_values(\"VIF Factor\").reset_index(drop=True)\nvif\n# 10순위까지 겹치는것만 쓴다\n# item_nbr, weekend, week7, preciptotal ", "_____no_output_____" ], [ "# item_nbr, weekend, week7, preciptotal \nmodel_df4 = sm.OLS.from_formula('np.log1p(units) ~ C(item_nbr) + C(week7) + C(weekend) + scale(preciptotal) + 0', data = df4)\nresult_df4 = model_df4.fit()\n\nprint(result_df4.summary())", " OLS Regression Results \n==============================================================================\nDep. Variable: np.log1p(units) R-squared: 0.777\nModel: OLS Adj. R-squared: 0.776\nMethod: Least Squares F-statistic: 835.3\nDate: Wed, 04 Jul 2018 Prob (F-statistic): 0.00\nTime: 13:35:31 Log-Likelihood: -2221.3\nNo. Observations: 2890 AIC: 4469.\nDf Residuals: 2877 BIC: 4546.\nDf Model: 12 \nCovariance Type: nonrobust \n======================================================================================\n coef std err t P>|t| [0.025 0.975]\n--------------------------------------------------------------------------------------\nC(item_nbr)[5] 3.3852 0.029 115.155 0.000 3.328 3.443\nC(item_nbr)[23] 2.4651 0.029 83.881 0.000 2.408 2.523\nC(item_nbr)[59] 0.9177 0.033 27.915 0.000 0.853 0.982\nC(item_nbr)[84] 0.9859 0.068 14.434 0.000 0.852 1.120\nC(item_nbr)[93] 1.5884 0.044 35.837 0.000 1.501 1.675\nC(item_nbr)[100] 1.0773 0.040 27.200 0.000 1.000 1.155\nC(week7)[T.1] -0.0886 0.036 -2.444 0.015 -0.160 -0.018\nC(week7)[T.2] -0.1386 0.037 -3.763 0.000 -0.211 -0.066\nC(week7)[T.3] -0.1749 0.036 -4.828 0.000 -0.246 -0.104\nC(week7)[T.4] -0.0855 0.036 -2.359 0.018 -0.157 -0.014\nC(week7)[T.5] -0.0296 0.021 -1.410 0.159 -0.071 0.012\nC(week7)[T.6] 0.0980 0.021 4.663 0.000 0.057 0.139\nC(weekend)[T.1] 0.0684 0.021 3.262 0.001 0.027 0.110\nscale(preciptotal) 0.0214 0.010 2.192 0.028 0.002 0.041\n==============================================================================\nOmnibus: 133.979 Durbin-Watson: 2.003\nProb(Omnibus): 0.000 Jarque-Bera (JB): 430.627\nSkew: -0.116 Prob(JB): 3.09e-94\nKurtosis: 4.877 Cond. No. 9.97e+15\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The smallest eigenvalue is 2.91e-29. This might indicate that there are\nstrong multicollinearity problems or that the design matrix is singular.\n" ], [ "X4 = df4[['week7', 'weekend', 'item_nbr', 'preciptotal']]\ny4 = df4['units']\nmodel4 = LinearRegression()\n\ncv4 = KFold(n_splits=10, shuffle=True, random_state=0)\n\ncross_val_score(model4, X4, y4, scoring=\"r2\", cv=cv4)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdf0ea6e3c6c71d887623cf7087df93f4bac8d5
14,748
ipynb
Jupyter Notebook
docs/lectures/lecture28/notebook/s7-exb1-challenge.ipynb
r34g4n/2020-CS109A
665100fec24309edb818a51bc8c29db2912d370f
[ "MIT" ]
81
2020-08-17T10:18:50.000Z
2022-03-14T00:10:17.000Z
docs/lectures/lecture28/notebook/s7-exb1-challenge.ipynb
SBalas/2020-CS109A
3eb01ac57adbef09c7dbb10eda7408dd4545b3f7
[ "MIT" ]
1
2022-02-09T06:15:51.000Z
2022-02-09T12:42:44.000Z
docs/lectures/lecture28/notebook/s7-exb1-challenge.ipynb
SBalas/2020-CS109A
3eb01ac57adbef09c7dbb10eda7408dd4545b3f7
[ "MIT" ]
95
2020-08-29T22:49:34.000Z
2022-03-25T18:36:13.000Z
31.716129
439
0.535801
[ [ [ "# Title\n\n**Exercise: B.1 - MLP by Hand**\n\n# Description\n\nIn this exercise, we will **construct a neural network** to classify 3 species of iris. The classification is based on 4 measurement predictor variables: sepal length & width, and petal length & width in the given dataset.", "_____no_output_____" ], [ "<img src=\"../img/image5.jpeg\" style=\"width: 500px;\">", "_____no_output_____" ], [ "# Instructions:\nThe Neural Network will be built from scratch using pre-trained weights and biases. Hence, we will only be doing the forward (i.e., prediction) pass. \n\n- Load the iris dataset from sklearn standard datasets.\n- Assign the predictor and response variables appropriately.\n- One hot encode the categorical labels of the predictor variable.\n- Load and inspect the pre-trained weights and biases.\n- Construct the MLP:\n - Augment X with a column of ones to create the augmented design matrix X \n - Create the first layer weight matrix by vertically stacking the bias vector on top of the weight vector\n - Perform the affine transformation \n - Activate the output of the affine transformation using ReLU \n - Repeat the first 3 steps for the hidden layer (augment, vertical stack, affine)\n - Use softmax on the final layer\n - Finally, predict y \n \n# Hints:\nThis will further develop our intuition for the architecture of a deep neural network. This diagram shows the structure of our network. You may find it useful to refer to it during the exercise.", "_____no_output_____" ], [ "<img src=\"../img/image6.png\" style=\"width: 500px;\">", "_____no_output_____" ], [ "This is our first encounter with a multi-class classification problem and also the softmax activation on the output layer. Note: $f_1()$ above is the ReLU activation and $f_2()$ is the softmax.\n\n<a href=\"https://www.tensorflow.org/api_docs/python/tf/keras/utils/to_categorical\" target=\"_blank\">to_categorical(y, num_classes=None, dtype='float32')</a> : Converts a class vector (integers) to the binary class matrix.\n\n<a href=\"https://numpy.org/doc/stable/reference/generated/numpy.vstack.html\" target=\"_blank\">np.vstack(tup)</a> : Stack arrays in sequence vertically (row-wise).\n\n<a href=\"https://numpy.org/doc/stable/reference/generated/numpy.dot.html\" target=\"_blank\">numpy.dot(a, b, out=None)</a> : Returns the dot product of two arrays.\n\n<a href=\"https://numpy.org/doc/stable/reference/generated/numpy.argmax.html\" target=\"_blank\">numpy.argmax(a, axis=None, out=None)</a> : Returns the indices of the maximum values along an axis.\n\nNote: This exercise is **auto-graded and you can try multiple attempts.**", "_____no_output_____" ] ], [ [ "#Import library\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom sklearn.datasets import load_iris\nfrom tensorflow.keras.utils import to_categorical\n%matplotlib inline", "_____no_output_____" ], [ "#Load the iris data\niris_data = load_iris()\n\n#Get the predictor and reponse variables\nX = iris_data.data\ny = iris_data.target\n\n#See the shape of the data\nprint(f'X shape: {X.shape}')\nprint(f'y shape: {y.shape}')", "X shape: (150, 4)\ny shape: (150,)\n" ], [ "#One-hot encode target labels\nY = to_categorical(y)\nprint(f'Y shape: {Y.shape}')", "Y shape: (150, 3)\n" ] ], [ [ "Load and inspect the pre-trained weights and biases. Compare their shapes to the NN diagram.", "_____no_output_____" ] ], [ [ "#Load and inspect the pre-trained weights and biases\nweights = np.load('data/weights.npy', allow_pickle=True)\n\n# weights for hidden (1st) layer\nw1 = weights[0] \n\n# biases for hidden (1st) layer\nb1 = weights[1]\n\n# weights for output (2nd) layer\nw2 = weights[2]\n\n#biases for output (2nd) layer\nb2 = weights[3] ", "_____no_output_____" ], [ "#Compare their shapes to that in the NN diagram.\nfor arr, name in zip([w1,b1,w2,b2], ['w1','b1','w2','b2']):\n print(f'{name} - shape: {arr.shape}')\n print(arr)\n print()", "w1 - shape: (4, 3)\n[[-0.42714605 -0.72814226 0.37730372]\n [ 0.39002347 -0.73936987 0.7850246 ]\n [ 0.12336338 -0.7267647 -0.48210236]\n [ 0.20957732 -0.7505736 -1.3789996 ]]\n\nb1 - shape: (3,)\n[0. 0. 0.31270522]\n\nw2 - shape: (3, 3)\n[[ 0.7043929 0.13273811 -0.845736 ]\n [-0.8318007 -0.6977086 0.75894 ]\n [ 1.1978723 0.14868832 -0.473792 ]]\n\nb2 - shape: (3,)\n[-1.2774311 0.45491916 0.73040146]\n\n" ] ], [ [ "For the first affine transformation we need to multiple the augmented input by the first weight matrix (i.e., layer).\n\n$$\n\\begin{bmatrix}\n1 & X_{11} & X_{12} & X_{13} & X_{14}\\\\\n1 & X_{21} & X_{22} & X_{23} & X_{24}\\\\\n\\vdots & \\vdots & \\vdots & \\vdots & \\vdots \\\\\n1 & X_{n1} & X_{n2} & X_{n3} & X_{n4}\\\\\n\\end{bmatrix} \\begin{bmatrix}\nb_{1}^1 & b_{2}^1 & b_{3}^1\\\\\nW_{11}^1 & W_{12}^1 & W_{13}^1\\\\\nW_{21}^1 & W_{22}^1 & W_{23}^1\\\\\nW_{31}^1 & W_{32}^1 & W_{33}^1\\\\\nW_{41}^1 & W_{42}^1 & W_{43}^1\\\\\n\\end{bmatrix} =\n\\begin{bmatrix}\nz_{11}^1 & z_{12}^1 & z_{13}^1\\\\\nz_{21}^1 & z_{22}^1 & z_{23}^1\\\\\n\\vdots & \\vdots & \\vdots \\\\\nz_{n1}^1 & z_{n2}^1 & z_{n3}^1\\\\\n\\end{bmatrix}\n= \\textbf{Z}^{(1)}\n$$ \n<span style='color:gray'>About the notation: superscript refers to the layer and subscript refers to the index in the particular matrix. So $W_{23}^1$ is the weight in the 1st layer connecting the 2nd input to 3rd hidden node. Compare this matrix representation to the slide image. Also note the bias terms and ones that have been added to 'augment' certain matrices. You could consider $b_1^1$ to be $W_{01}^1$.</span><div></div>\n<span style='color:blue'>1. Augment X with a column of ones to create `X_aug`</span><div></div><span style='color:blue'>2. Create the first layer weight matrix `W1` by vertically stacking the bias vector `b1`on top of `w1` (consult `add_ones_col` for ideas. Don't forget your `Tab` and `Shift+Tab` tricks!)</span><div></div><span style='color:blue'>3. Do the matrix multiplication to find `Z1`</span>\n\n", "_____no_output_____" ] ], [ [ "def add_ones_col(X):\n '''Augment matrix with a column of ones'''\n X_aug = np.hstack((np.ones((X.shape[0],1)), X))\n return X_aug", "_____no_output_____" ], [ "#Use add_ones_col()\nX_aug = add_ones_col(___)\n\n#Use np.vstack to add biases to weight matrix\nW1 = np.vstack((___,___))\n\n#Use np.dot() to multiple X_aug and W1\nZ1 = np.dot(___,___) ", "_____no_output_____" ] ], [ [ "Next, we use our non-linearity\n$$\n\\textit{a}_{\\text{relu}}(\\textbf{Z}^{(1)})=\n\\begin{bmatrix}\nh_{11} & h_{12} & h_{13}\\\\\nh_{21} & h_{22} & h_{23}\\\\\n\\vdots & \\vdots & \\vdots \\\\\nh_{n1} & h_{n2} & h_{n3}\\\\\n\\end{bmatrix}= \\textbf{H}\n$$\n\n\n\n<span style='color:blue'>1. Define the ReLU activation</span><div></div>\n<span style='color:blue'>2. use `plot_activation_func` to confirm implementation</span><div></div>\n<span style='color:blue'>3. Use relu on `Z1` to create `H`</span>", "_____no_output_____" ] ], [ [ "def relu(z: np.array) -> np.array:\n # hint: \n # relu(z) = 0 when z < 0\n # otherwise relu(z) = z\n # your code here\n h = np.maximum(___,___) # np.maximum() will help\n return h", "_____no_output_____" ], [ "#Helper code to plot the activation function\ndef plot_activation_func(f, name):\n lin_x = np.linspace(-10,10,200)\n h = f(lin_x)\n plt.plot(lin_x, h)\n plt.xlabel('x')\n plt.ylabel('y')\n plt.title(f'{name} Activation Function')\n\nplot_activation_func(relu, name='RELU')", "_____no_output_____" ], [ "# use your relu activation function on Z1\nH = relu(___) ", "_____no_output_____" ] ], [ [ "The next step is very similar to the first and so we've filled it in for you.\n\n$$\n\\begin{bmatrix}\n1 & h_{11} & h_{12} & h_{13}\\\\\n1 & h_{21} & h_{22} & h_{23}\\\\\n\\vdots & \\vdots & \\vdots & \\vdots \\\\\n1 & h_{n1} & h_{n2} & h_{n3}\\\\\n\\end{bmatrix}\n\\begin{bmatrix}\nb_{1}^{(2)} & b_{2}^2 & b_{3}^2\\\\\nW_{11}^2 & W_{12}^2 & W_{13}^2\\\\\nW_{21}^2 & W_{22}^2 & W_{23}^2\\\\\nW_{31}^2 & W_{32}^2 & W_{33}^2\\\\\n\\end{bmatrix}=\n\\begin{bmatrix}\nz_{11}^2 & z_{12}^2 & z_{13}^2\\\\\nz_{21}^2 & z_{22}^2 & z_{23}^2\\\\\n\\vdots & \\vdots & \\vdots \\\\\nz_{n1}^2 & z_{n2}^2 & z_{n3}^2\\\\\n\\end{bmatrix} = \\textbf{Z}^{(2)}\n$$\n\n\n<span style='color:blue'>1. Augment `H` with ones to create `H_aug`</span><div></div>\n<span style='color:blue'>2. Combine `w2` and `b2` to create the output weight matric `W2`</span><div></div>\n<span style='color:blue'>3. Perform the matrix multiplication to produce `Z2`</span><div></div>", "_____no_output_____" ] ], [ [ "#Use add_ones_col()\nH_aug = ___\n\n#Use np.vstack to add biases to weight matrix\nW2 = ___\n\n#Use np.dot()\nZ2 = np.dot(H_aug,W2)", "_____no_output_____" ] ], [ [ "Finally we use the softmax activation on `Z2`. Now for each observation we have an output vector of length 3 which can be interpreted as a probability (they sum to 1).\n$$\n\\textit{a}_{\\text{softmax}}(\\textbf{Z}^2)=\n\\begin{bmatrix}\n\\hat{y}_{11} & \\hat{y}_{12} & \\hat{y}_{13}\\\\\n\\hat{y}_{21} & \\hat{y}_{22} & \\hat{y}_{23}\\\\\n\\vdots & \\vdots & \\vdots \\\\\n\\hat{y}_{n1} & \\hat{y}_{n2} & \\hat{y}_{n3}\\\\\n\\end{bmatrix}\n= \\hat{\\textbf{Y}}\n$$\n\n<span style='color:blue'>1. Define softmax</span><div></div>\n<span style='color:blue'>2. Use `softmax` on `Z2` to create `Y_hat`</span><div></div>", "_____no_output_____" ] ], [ [ "def softmax(z: np.array) -> np.array:\n '''\n Input: z - 2D numpy array of logits \n rows are observations, classes are columns \n Returns: y_hat - 2D numpy array of probabilities\n rows are observations, classes are columns \n '''\n # hint: we are summing across the columns\n\n y_hat = np.exp(___)/np.sum(np.exp(___), axis=___, keepdims=True)\n return y_hat", "_____no_output_____" ], [ "#Calling the softmax function\nY_hat = softmax(___)", "_____no_output_____" ] ], [ [ "<span style='color:blue'>Now let's see how accuract the model's predictions are! Use `np.argmax` to collapse the columns of `Y_hat` to create `y_hat`, a vector of class labels like the original `y` before one-hot encoding.</span><div></div>", "_____no_output_____" ] ], [ [ "### edTest(test_acc) ###\n\n# Compute the accuracy\ny_hat = np.argmax(___, axis=___)\nacc = sum(y == y_hat)/len(y)\nprint(f'accuracy: {acc:.2%}')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cbdf17a0a71aa746b31b18244c478d6ed8151d55
1,492
ipynb
Jupyter Notebook
Other Notebooks/time module.ipynb
ArianNadjim/Tripods
f3c973251870e2e64af798f802798704d2f0249e
[ "MIT" ]
3
2020-08-10T02:19:44.000Z
2020-08-13T23:33:38.000Z
Other Notebooks/time module.ipynb
ArianNadjim/Tripods
f3c973251870e2e64af798f802798704d2f0249e
[ "MIT" ]
null
null
null
Other Notebooks/time module.ipynb
ArianNadjim/Tripods
f3c973251870e2e64af798f802798704d2f0249e
[ "MIT" ]
3
2020-08-10T17:38:32.000Z
2020-08-12T15:29:08.000Z
19.376623
74
0.509383
[ [ [ "import time \n\n# The number of seconds since the beginning of time\n\ntime.time()\n\n# Time and date right now \n\ntime.ctime(1594131442.187444)\n\n# Time and date right now in a different format\n\ntime.localtime()\n\n# Still returns the number of second since the beginning of time \n\na=time.localtime()\nb=time.mktime(a)\nprint(b)\n\n# Uses a to return local time in a reasonable format\n\nc=time.asctime(a)\nprint(c)\n\n", "1594131957.0\nTue Jul 7 10:25:57 2020\n" ] ], [ [ "Copyright (c) 2020 TRIPODS/GradStemForAll 2020 Team", "_____no_output_____" ] ] ]
[ "code", "markdown" ]
[ [ "code" ], [ "markdown" ] ]
cbdf1bae0ab87222007cc1cf972e51bc0f08ac56
160,436
ipynb
Jupyter Notebook
Data analysis.ipynb
mrdbarros/gquest_nbdev
20152de5e98fa4853800ac1110aace174d8dc6cf
[ "Apache-2.0" ]
null
null
null
Data analysis.ipynb
mrdbarros/gquest_nbdev
20152de5e98fa4853800ac1110aace174d8dc6cf
[ "Apache-2.0" ]
1
2022-02-26T06:15:29.000Z
2022-02-26T06:15:29.000Z
Data analysis.ipynb
mrdbarros/gquest_nbdev
20152de5e98fa4853800ac1110aace174d8dc6cf
[ "Apache-2.0" ]
null
null
null
52.636483
20,552
0.547608
[ [ [ "import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom pathlib import Path \n\nimport os\n\n\nimport random \n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# classification metric\nfrom scipy.stats import spearmanr\n", "_____no_output_____" ], [ "model_type = 'roberta'\npretrained_model_name = 'roberta-base' # 'roberta-base-openai-detector'\nDATA_ROOT = Path(\"../input/google-quest-challenge/\")\nMODEL_ROOT = Path(\"../input/\"+pretrained_model_name)\ntrain = pd.read_csv(DATA_ROOT / 'train.csv')\ntest = pd.read_csv(DATA_ROOT / 'test.csv')\nsample_sub = pd.read_csv(DATA_ROOT / 'sample_submission.csv')\nreal_sub = pd.read_csv(Path(\"~/Downloads/submission.csv\"))\nprint(train.shape,test.shape)\ndownload_model=False", "(6079, 41) (476, 11)\n" ], [ "train.head()", "_____no_output_____" ], [ "# matplotlib histogram\nplt.hist(train['question_well_written'], color = 'blue', edgecolor = 'black',\n bins = int(180/20))", "_____no_output_____" ], [ "# Density Plot and Histogram of all arrival delays\nsns.distplot(train['question_well_written'], hist=True, kde=True, \n bins=int(180/20), color = 'darkblue', \n hist_kws={'edgecolor':'black'},\n kde_kws={'linewidth': 4})", "_____no_output_____" ], [ "# Density Plot and Histogram of all arrival delays\nsns.distplot(real_sub['question_well_written'], hist=True, kde=True, \n bins=int(180/20), color = 'darkblue', \n hist_kws={'edgecolor':'black'},\n kde_kws={'linewidth': 4})", "_____no_output_____" ], [ "train['question_well_written'].unique()", "_____no_output_____" ], [ "labels = list(sample_sub.columns[1:].values)", "_____no_output_____" ], [ "for label in labels:\n print(train[label].value_counts(normalize=True))\n print()", "1.000000 0.466031\n0.888889 0.259747\n0.777778 0.145254\n0.666667 0.082744\n0.833333 0.017766\n0.333333 0.011186\n0.555556 0.009870\n0.500000 0.005429\n0.444444 0.001974\nName: question_asker_intent_understanding, dtype: float64\n\n0.333333 0.247738\n0.555556 0.153315\n0.444444 0.146899\n0.666667 0.139003\n0.777778 0.115315\n1.000000 0.095904\n0.888889 0.077315\n0.500000 0.015463\n0.833333 0.009048\nName: question_body_critical, dtype: float64\n\n0.000000 0.889785\n0.333333 0.063168\n0.666667 0.025004\n1.000000 0.017108\n0.500000 0.004935\nName: question_conversational, dtype: float64\n\n1.000000 0.482974\n0.666667 0.225860\n0.000000 0.132588\n0.333333 0.085869\n0.500000 0.072709\nName: question_expect_short_answer, dtype: float64\n\n1.000000 0.572463\n0.666667 0.218128\n0.333333 0.144267\n0.000000 0.051818\n0.500000 0.013325\nName: question_fact_seeking, dtype: float64\n\n1.000000 0.669683\n0.666667 0.130614\n0.000000 0.108077\n0.333333 0.053298\n0.500000 0.038329\nName: question_has_commonly_accepted_answer, dtype: float64\n\n0.666667 0.301201\n0.555556 0.279487\n0.444444 0.206942\n0.777778 0.077480\n0.333333 0.053298\n0.500000 0.032242\n0.888889 0.025498\n1.000000 0.016450\n0.833333 0.007403\nName: question_interestingness_others, dtype: float64\n\n0.333333 0.349400\n0.444444 0.234414\n0.555556 0.136042\n0.666667 0.105774\n0.777778 0.064155\n1.000000 0.039809\n0.888889 0.034381\n0.500000 0.029281\n0.833333 0.006745\nName: question_interestingness_self, dtype: float64\n\n0.000000 0.594999\n0.333333 0.179964\n0.666667 0.114657\n1.000000 0.094259\n0.500000 0.016121\nName: question_multi_intent, dtype: float64\n\n0.000000 0.989143\n0.333333 0.007896\n0.500000 0.001810\n0.666667 0.000658\n1.000000 0.000494\nName: question_not_really_a_question, dtype: float64\n\n0.000000 0.323079\n0.666667 0.239349\n0.333333 0.230137\n1.000000 0.179964\n0.500000 0.027472\nName: question_opinion_seeking, dtype: float64\n\n0.000000 0.553216\n0.333333 0.175029\n1.000000 0.143938\n0.666667 0.112354\n0.500000 0.015463\nName: question_type_choice, dtype: float64\n\n0.000000 0.929758\n0.333333 0.036519\n0.666667 0.019576\n1.000000 0.011680\n0.500000 0.002468\nName: question_type_compare, dtype: float64\n\n0.000000 0.978450\n0.333333 0.014147\n0.666667 0.004277\n1.000000 0.001810\n0.500000 0.001316\nName: question_type_consequence, dtype: float64\n\n0.000000 0.943412\n0.333333 0.028459\n0.666667 0.018095\n1.000000 0.008390\n0.500000 0.001645\nName: question_type_definition, dtype: float64\n\n0.000000 0.879750\n0.333333 0.064320\n0.666667 0.028294\n1.000000 0.022208\n0.500000 0.005429\nName: question_type_entity, dtype: float64\n\n0.000000 0.357131\n1.000000 0.326534\n0.666667 0.184570\n0.333333 0.107254\n0.500000 0.024511\nName: question_type_instructions, dtype: float64\n\n0.000000 0.651094\n0.333333 0.215989\n0.666667 0.087679\n1.000000 0.025991\n0.500000 0.019247\nName: question_type_procedure, dtype: float64\n\n0.000000 0.404014\n0.333333 0.216483\n1.000000 0.192630\n0.666667 0.168942\n0.500000 0.017931\nName: question_type_reason_explanation, dtype: float64\n\n0.000000 0.998190\n0.333333 0.001152\n0.666667 0.000658\nName: question_type_spelling, dtype: float64\n\n1.000000 0.266327\n0.888889 0.219937\n0.777778 0.182760\n0.666667 0.138016\n0.555556 0.088666\n0.444444 0.050502\n0.833333 0.026814\n0.333333 0.021550\n0.500000 0.005429\nName: question_well_written, dtype: float64\n\n1.000000 0.608817\n0.888889 0.201184\n0.666667 0.070900\n0.777778 0.070242\n0.833333 0.036026\n0.555556 0.004277\n0.333333 0.004113\n0.444444 0.002303\n0.500000 0.002139\nName: answer_helpful, dtype: float64\n\n0.666667 0.676756\n0.555556 0.093107\n0.777778 0.079289\n0.444444 0.034545\n0.333333 0.034216\n0.500000 0.026485\n0.888889 0.023688\n0.833333 0.016286\n1.000000 0.015628\nName: answer_level_of_information, dtype: float64\n\n1.000000 0.774798\n0.888889 0.121731\n0.666667 0.035368\n0.833333 0.032736\n0.777778 0.031420\n0.333333 0.001645\n0.555556 0.001316\n0.500000 0.000658\n0.444444 0.000329\nName: answer_plausible, dtype: float64\n\n1.000000 0.808192\n0.888889 0.117289\n0.777778 0.030268\n0.833333 0.022701\n0.666667 0.018260\n0.555556 0.001152\n0.333333 0.000823\n0.500000 0.000823\n0.444444 0.000494\nName: answer_relevance, dtype: float64\n\n1.000000 0.207600\n0.800000 0.198223\n0.933333 0.194604\n0.866667 0.152163\n0.900000 0.067610\n0.733333 0.052640\n0.600000 0.043757\n0.666667 0.031584\n0.700000 0.019411\n0.533333 0.011515\n0.400000 0.006745\n0.500000 0.004935\n0.466667 0.004771\n0.200000 0.002139\n0.300000 0.000823\n0.266667 0.000823\n0.333333 0.000658\nName: answer_satisfaction, dtype: float64\n\n0.000000 0.369140\n1.000000 0.315348\n0.666667 0.165652\n0.333333 0.126995\n0.500000 0.022866\nName: answer_type_instructions, dtype: float64\n\n0.000000 0.704228\n0.333333 0.205955\n0.666667 0.053134\n0.500000 0.020234\n1.000000 0.016450\nName: answer_type_procedure, dtype: float64\n\n1.000000 0.312387\n0.000000 0.311235\n0.666667 0.182102\n0.333333 0.170752\n0.500000 0.023524\nName: answer_type_reason_explanation, dtype: float64\n\n1.000000 0.433295\n0.888889 0.357789\n0.777778 0.119592\n0.666667 0.045073\n0.833333 0.034710\n0.555556 0.006251\n0.444444 0.001316\n0.500000 0.001316\n0.333333 0.000658\nName: answer_well_written, dtype: float64\n\n" ], [ "for label in labels:\n print(real_sub[label].value_counts(normalize=True))\n print()", "0.886719 0.014706\n0.916016 0.010504\n0.930176 0.010504\n0.873535 0.010504\n0.876465 0.010504\n ... \n0.901855 0.002101\n0.817871 0.002101\n0.885254 0.002101\n1.006836 0.002101\n1.000977 0.002101\nName: question_asker_intent_understanding, Length: 274, dtype: float64\n\n0.505371 0.008403\n0.501465 0.008403\n0.689941 0.006303\n0.725586 0.006303\n0.744629 0.006303\n ... \n0.809570 0.002101\n0.499023 0.002101\n0.399414 0.002101\n0.442871 0.002101\n0.637207 0.002101\nName: question_body_critical, Length: 394, dtype: float64\n\n0.012550 0.004202\n0.023849 0.004202\n0.164917 0.004202\n0.139526 0.004202\n0.225586 0.004202\n ... \n0.001127 0.002101\n0.277832 0.002101\n0.055634 0.002101\n0.201904 0.002101\n0.022583 0.002101\nName: question_conversational, Length: 462, dtype: float64\n\n0.755859 0.008403\n0.717285 0.008403\n0.754395 0.008403\n0.791016 0.008403\n0.566895 0.006303\n ... \n0.619141 0.002101\n0.715820 0.002101\n0.822266 0.002101\n0.825195 0.002101\n0.572754 0.002101\nName: question_expect_short_answer, Length: 354, dtype: float64\n\n0.856445 0.008403\n0.791016 0.008403\n0.820312 0.008403\n0.777832 0.008403\n0.788574 0.006303\n ... \n0.857422 0.002101\n0.525879 0.002101\n0.658203 0.002101\n0.975586 0.002101\n0.588867 0.002101\nName: question_fact_seeking, Length: 353, dtype: float64\n\n0.941895 0.008403\n0.940430 0.008403\n0.923340 0.008403\n0.901367 0.008403\n0.904297 0.008403\n ... \n1.019531 0.002101\n0.893555 0.002101\n0.790527 0.002101\n0.956055 0.002101\n0.546387 0.002101\nName: question_has_commonly_accepted_answer, Length: 333, dtype: float64\n\n0.523438 0.010504\n0.639160 0.010504\n0.625488 0.010504\n0.569336 0.010504\n0.580566 0.010504\n ... \n0.555664 0.002101\n0.594238 0.002101\n0.654297 0.002101\n0.658203 0.002101\n0.712891 0.002101\nName: question_interestingness_others, Length: 268, dtype: float64\n\n0.546387 0.008403\n0.472656 0.008403\n0.444092 0.008403\n0.477539 0.006303\n0.545898 0.006303\n ... \n0.393555 0.002101\n0.391602 0.002101\n0.451660 0.002101\n0.567871 0.002101\n0.396240 0.002101\nName: question_interestingness_self, Length: 365, dtype: float64\n\n0.559082 0.006303\n0.262451 0.004202\n0.632812 0.004202\n0.257812 0.004202\n0.718750 0.004202\n ... \n0.112854 0.002101\n0.185303 0.002101\n0.457520 0.002101\n0.483154 0.002101\n0.392578 0.002101\nName: question_multi_intent, Length: 454, dtype: float64\n\n 0.006969 0.006303\n 0.009171 0.006303\n 0.009224 0.004202\n 0.016083 0.004202\n 0.014023 0.004202\n ... \n-0.001245 0.002101\n 0.007084 0.002101\n 0.007195 0.002101\n 0.008316 0.002101\n 0.000240 0.002101\nName: question_not_really_a_question, Length: 459, dtype: float64\n\n0.409180 0.006303\n0.558105 0.006303\n0.451660 0.006303\n0.491699 0.006303\n0.486328 0.006303\n ... \n0.971191 0.002101\n0.561523 0.002101\n0.586914 0.002101\n0.080505 0.002101\n0.443359 0.002101\nName: question_opinion_seeking, Length: 422, dtype: float64\n\n0.131348 0.004202\n0.119690 0.004202\n0.094116 0.004202\n0.316162 0.004202\n0.042542 0.004202\n ... \n0.361816 0.002101\n0.081604 0.002101\n0.098755 0.002101\n0.389404 0.002101\n0.628906 0.002101\nName: question_type_choice, Length: 461, dtype: float64\n\n 0.018799 0.004202\n 0.039337 0.004202\n-0.009720 0.004202\n-0.009125 0.004202\n 0.032410 0.004202\n ... \n 0.071960 0.002101\n 0.043152 0.002101\n-0.045715 0.002101\n 0.018997 0.002101\n 0.045410 0.002101\nName: question_type_compare, Length: 465, dtype: float64\n\n-0.009987 0.004202\n 0.004524 0.004202\n 0.010628 0.004202\n 0.022064 0.004202\n 0.006973 0.004202\n ... \n 0.013588 0.002101\n 0.002987 0.002101\n 0.009048 0.002101\n-0.004391 0.002101\n-0.024170 0.002101\nName: question_type_consequence, Length: 469, dtype: float64\n\n 0.039246 0.006303\n 0.081421 0.004202\n-0.007473 0.004202\n 0.016098 0.004202\n 0.009460 0.004202\n ... \n 0.012039 0.002101\n-0.026566 0.002101\n-0.013779 0.002101\n 0.022980 0.002101\n 0.250000 0.002101\nName: question_type_definition, Length: 463, dtype: float64\n\n 0.031174 0.004202\n 0.019287 0.004202\n 0.021057 0.004202\n-0.011414 0.004202\n 0.048767 0.004202\n ... \n-0.044250 0.002101\n 0.053986 0.002101\n 0.014633 0.002101\n-0.040588 0.002101\n-0.021729 0.002101\nName: question_type_entity, Length: 465, dtype: float64\n\n0.979980 0.006303\n0.842773 0.006303\n0.802734 0.006303\n0.640137 0.006303\n0.940430 0.006303\n ... \n0.121948 0.002101\n0.144775 0.002101\n0.499756 0.002101\n0.512695 0.002101\n0.178589 0.002101\nName: question_type_instructions, Length: 427, dtype: float64\n\n 0.236938 0.006303\n 0.242065 0.006303\n 0.214233 0.006303\n 0.163452 0.006303\n 0.170410 0.004202\n ... \n-0.065063 0.002101\n 0.108948 0.002101\n 0.183350 0.002101\n 0.174072 0.002101\n 0.129395 0.002101\nName: question_type_procedure, Length: 430, dtype: float64\n\n0.793457 0.006303\n0.126831 0.004202\n0.602051 0.004202\n0.579102 0.004202\n0.288574 0.004202\n ... \n0.111938 0.002101\n0.071838 0.002101\n0.049744 0.002101\n0.645996 0.002101\n0.638672 0.002101\nName: question_type_reason_explanation, Length: 452, dtype: float64\n\n-0.008629 0.004202\n 0.004585 0.004202\n 0.005035 0.004202\n 0.002432 0.004202\n-0.006134 0.004202\n ... \n-0.001860 0.002101\n-0.012833 0.002101\n 0.008995 0.002101\n 0.006187 0.002101\n-0.013412 0.002101\nName: question_type_spelling, Length: 471, dtype: float64\n\n0.792969 0.008403\n0.867676 0.008403\n0.805664 0.008403\n0.835449 0.006303\n0.863770 0.006303\n ... \n0.730957 0.002101\n0.740234 0.002101\n0.846680 0.002101\n0.935547 0.002101\n0.662598 0.002101\nName: question_well_written, Length: 365, dtype: float64\n\n0.937012 0.016807\n0.972168 0.014706\n0.934082 0.014706\n0.942383 0.012605\n0.940430 0.012605\n ... \n0.849609 0.002101\n0.974609 0.002101\n0.919922 0.002101\n0.989258 0.002101\n0.970215 0.002101\nName: answer_helpful, Length: 207, dtype: float64\n\n0.657227 0.016807\n0.674316 0.012605\n0.657715 0.012605\n0.635254 0.012605\n0.633789 0.012605\n ... \n0.653809 0.002101\n0.689453 0.002101\n0.716797 0.002101\n0.602539 0.002101\n0.615723 0.002101\nName: answer_level_of_information, Length: 218, dtype: float64\n\n0.979004 0.023109\n0.970703 0.018908\n0.982910 0.016807\n1.006836 0.016807\n0.966797 0.016807\n ... \n1.023438 0.002101\n0.953125 0.002101\n1.031250 0.002101\n1.007812 0.002101\n1.055664 0.002101\nName: answer_plausible, Length: 160, dtype: float64\n\n1.001953 0.021008\n1.008789 0.021008\n1.000977 0.018908\n0.984375 0.016807\n0.992188 0.016807\n ... \n0.956543 0.002101\n0.962891 0.002101\n0.957031 0.002101\n0.994141 0.002101\n0.997559 0.002101\nName: answer_relevance, Length: 161, dtype: float64\n\n0.882324 0.014706\n0.887207 0.014706\n0.839844 0.012605\n0.888184 0.012605\n0.860840 0.012605\n ... \n0.771484 0.002101\n0.846680 0.002101\n0.726074 0.002101\n0.870117 0.002101\n0.883301 0.002101\nName: answer_satisfaction, Length: 236, dtype: float64\n\n0.854492 0.010504\n0.778809 0.008403\n0.825195 0.006303\n0.404541 0.006303\n0.870605 0.006303\n ... \n0.476074 0.002101\n0.563477 0.002101\n0.728027 0.002101\n0.497559 0.002101\n0.878906 0.002101\nName: answer_type_instructions, Length: 438, dtype: float64\n\n0.130981 0.008403\n0.152222 0.006303\n0.114868 0.006303\n0.145630 0.006303\n0.147583 0.006303\n ... \n0.183838 0.002101\n0.116394 0.002101\n0.153076 0.002101\n0.008987 0.002101\n0.050903 0.002101\nName: answer_type_procedure, Length: 422, dtype: float64\n\n0.615723 0.008403\n0.669434 0.006303\n0.858887 0.004202\n0.240845 0.004202\n0.222656 0.004202\n ... \n0.236084 0.002101\n0.297363 0.002101\n0.999512 0.002101\n0.384277 0.002101\n0.746094 0.002101\nName: answer_type_reason_explanation, Length: 447, dtype: float64\n\n0.914551 0.016807\n0.916992 0.016807\n0.913574 0.016807\n0.920410 0.014706\n0.902832 0.012605\n ... \n0.969238 0.002101\n0.893066 0.002101\n0.958984 0.002101\n0.884766 0.002101\n0.925293 0.002101\nName: answer_well_written, Length: 183, dtype: float64\n\n" ], [ "import pdb\nfrom bisect import bisect", "_____no_output_____" ], [ "def make_intervals(train_df,labels):\n boundaries ={}\n unique_values={}\n for label in labels:\n unique_values[label] =np.sort( train_df[label].unique())\n boundaries[label] = [(unique_values[label][i+1]+unique_values[label][i])/2 for i in range(len(unique_values[label])-1)]\n return unique_values,boundaries\n ", "_____no_output_____" ], [ "unique_values,boundaries=make_intervals(train,labels)", "_____no_output_____" ], [ "train[\"question_asker_intent_understanding\"][2],boundaries[\"question_asker_intent_understanding\"]", "_____no_output_____" ], [ "real_sub[\"question_asker_intent_understanding\"][2]", "_____no_output_____" ], [ "def return_categorical_value(df_column,col_unique_values,col_boundaries):\n #pdb.set_trace()\n return df_column.apply(lambda row: col_unique_values[bisect(col_boundaries,df_column[1])])\n", "_____no_output_____" ], [ "real_sub2=real_sub.copy()\nreal_sub2.head()", "_____no_output_____" ], [ "for label in labels:\n real_sub2[label]=return_categorical_value(real_sub[label],unique_values[label],boundaries[label])", "_____no_output_____" ], [ "real_sub.head(20)", "_____no_output_____" ], [ "real_sub2", "_____no_output_____" ], [ "for label in labels:\n print(train[label].value_counts(normalize=True))\n print()", "1.000000 0.466031\n0.888889 0.259747\n0.777778 0.145254\n0.666667 0.082744\n0.833333 0.017766\n0.333333 0.011186\n0.555556 0.009870\n0.500000 0.005429\n0.444444 0.001974\nName: question_asker_intent_understanding, dtype: float64\n\n0.333333 0.247738\n0.555556 0.153315\n0.444444 0.146899\n0.666667 0.139003\n0.777778 0.115315\n1.000000 0.095904\n0.888889 0.077315\n0.500000 0.015463\n0.833333 0.009048\nName: question_body_critical, dtype: float64\n\n0.000000 0.889785\n0.333333 0.063168\n0.666667 0.025004\n1.000000 0.017108\n0.500000 0.004935\nName: question_conversational, dtype: float64\n\n1.000000 0.482974\n0.666667 0.225860\n0.000000 0.132588\n0.333333 0.085869\n0.500000 0.072709\nName: question_expect_short_answer, dtype: float64\n\n1.000000 0.572463\n0.666667 0.218128\n0.333333 0.144267\n0.000000 0.051818\n0.500000 0.013325\nName: question_fact_seeking, dtype: float64\n\n1.000000 0.669683\n0.666667 0.130614\n0.000000 0.108077\n0.333333 0.053298\n0.500000 0.038329\nName: question_has_commonly_accepted_answer, dtype: float64\n\n0.666667 0.301201\n0.555556 0.279487\n0.444444 0.206942\n0.777778 0.077480\n0.333333 0.053298\n0.500000 0.032242\n0.888889 0.025498\n1.000000 0.016450\n0.833333 0.007403\nName: question_interestingness_others, dtype: float64\n\n0.333333 0.349400\n0.444444 0.234414\n0.555556 0.136042\n0.666667 0.105774\n0.777778 0.064155\n1.000000 0.039809\n0.888889 0.034381\n0.500000 0.029281\n0.833333 0.006745\nName: question_interestingness_self, dtype: float64\n\n0.000000 0.594999\n0.333333 0.179964\n0.666667 0.114657\n1.000000 0.094259\n0.500000 0.016121\nName: question_multi_intent, dtype: float64\n\n0.000000 0.989143\n0.333333 0.007896\n0.500000 0.001810\n0.666667 0.000658\n1.000000 0.000494\nName: question_not_really_a_question, dtype: float64\n\n0.000000 0.323079\n0.666667 0.239349\n0.333333 0.230137\n1.000000 0.179964\n0.500000 0.027472\nName: question_opinion_seeking, dtype: float64\n\n0.000000 0.553216\n0.333333 0.175029\n1.000000 0.143938\n0.666667 0.112354\n0.500000 0.015463\nName: question_type_choice, dtype: float64\n\n0.000000 0.929758\n0.333333 0.036519\n0.666667 0.019576\n1.000000 0.011680\n0.500000 0.002468\nName: question_type_compare, dtype: float64\n\n0.000000 0.978450\n0.333333 0.014147\n0.666667 0.004277\n1.000000 0.001810\n0.500000 0.001316\nName: question_type_consequence, dtype: float64\n\n0.000000 0.943412\n0.333333 0.028459\n0.666667 0.018095\n1.000000 0.008390\n0.500000 0.001645\nName: question_type_definition, dtype: float64\n\n0.000000 0.879750\n0.333333 0.064320\n0.666667 0.028294\n1.000000 0.022208\n0.500000 0.005429\nName: question_type_entity, dtype: float64\n\n0.000000 0.357131\n1.000000 0.326534\n0.666667 0.184570\n0.333333 0.107254\n0.500000 0.024511\nName: question_type_instructions, dtype: float64\n\n0.000000 0.651094\n0.333333 0.215989\n0.666667 0.087679\n1.000000 0.025991\n0.500000 0.019247\nName: question_type_procedure, dtype: float64\n\n0.000000 0.404014\n0.333333 0.216483\n1.000000 0.192630\n0.666667 0.168942\n0.500000 0.017931\nName: question_type_reason_explanation, dtype: float64\n\n0.000000 0.998190\n0.333333 0.001152\n0.666667 0.000658\nName: question_type_spelling, dtype: float64\n\n1.000000 0.266327\n0.888889 0.219937\n0.777778 0.182760\n0.666667 0.138016\n0.555556 0.088666\n0.444444 0.050502\n0.833333 0.026814\n0.333333 0.021550\n0.500000 0.005429\nName: question_well_written, dtype: float64\n\n1.000000 0.608817\n0.888889 0.201184\n0.666667 0.070900\n0.777778 0.070242\n0.833333 0.036026\n0.555556 0.004277\n0.333333 0.004113\n0.444444 0.002303\n0.500000 0.002139\nName: answer_helpful, dtype: float64\n\n0.666667 0.676756\n0.555556 0.093107\n0.777778 0.079289\n0.444444 0.034545\n0.333333 0.034216\n0.500000 0.026485\n0.888889 0.023688\n0.833333 0.016286\n1.000000 0.015628\nName: answer_level_of_information, dtype: float64\n\n1.000000 0.774798\n0.888889 0.121731\n0.666667 0.035368\n0.833333 0.032736\n0.777778 0.031420\n0.333333 0.001645\n0.555556 0.001316\n0.500000 0.000658\n0.444444 0.000329\nName: answer_plausible, dtype: float64\n\n1.000000 0.808192\n0.888889 0.117289\n0.777778 0.030268\n0.833333 0.022701\n0.666667 0.018260\n0.555556 0.001152\n0.333333 0.000823\n0.500000 0.000823\n0.444444 0.000494\nName: answer_relevance, dtype: float64\n\n1.000000 0.207600\n0.800000 0.198223\n0.933333 0.194604\n0.866667 0.152163\n0.900000 0.067610\n0.733333 0.052640\n0.600000 0.043757\n0.666667 0.031584\n0.700000 0.019411\n0.533333 0.011515\n0.400000 0.006745\n0.500000 0.004935\n0.466667 0.004771\n0.200000 0.002139\n0.300000 0.000823\n0.266667 0.000823\n0.333333 0.000658\nName: answer_satisfaction, dtype: float64\n\n0.000000 0.369140\n1.000000 0.315348\n0.666667 0.165652\n0.333333 0.126995\n0.500000 0.022866\nName: answer_type_instructions, dtype: float64\n\n0.000000 0.704228\n0.333333 0.205955\n0.666667 0.053134\n0.500000 0.020234\n1.000000 0.016450\nName: answer_type_procedure, dtype: float64\n\n1.000000 0.312387\n0.000000 0.311235\n0.666667 0.182102\n0.333333 0.170752\n0.500000 0.023524\nName: answer_type_reason_explanation, dtype: float64\n\n1.000000 0.433295\n0.888889 0.357789\n0.777778 0.119592\n0.666667 0.045073\n0.833333 0.034710\n0.555556 0.006251\n0.444444 0.001316\n0.500000 0.001316\n0.333333 0.000658\nName: answer_well_written, dtype: float64\n\n" ], [ "for label in labels:\n print(real_sub2[label].value_counts(normalize=True))", "0.888889 1.0\nName: question_asker_intent_understanding, dtype: float64\n0.5 1.0\nName: question_body_critical, dtype: float64\n0.0 1.0\nName: question_conversational, dtype: float64\n0.666667 1.0\nName: question_expect_short_answer, dtype: float64\n0.666667 1.0\nName: question_fact_seeking, dtype: float64\n1.0 1.0\nName: question_has_commonly_accepted_answer, dtype: float64\n0.555556 1.0\nName: question_interestingness_others, dtype: float64\n0.444444 1.0\nName: question_interestingness_self, dtype: float64\n0.333333 1.0\nName: question_multi_intent, dtype: float64\n0.0 1.0\nName: question_not_really_a_question, dtype: float64\n0.5 1.0\nName: question_opinion_seeking, dtype: float64\n0.5 1.0\nName: question_type_choice, dtype: float64\n0.0 1.0\nName: question_type_compare, dtype: float64\n0.0 1.0\nName: question_type_consequence, dtype: float64\n0.0 1.0\nName: question_type_definition, dtype: float64\n0.0 1.0\nName: question_type_entity, dtype: float64\n1.0 1.0\nName: question_type_instructions, dtype: float64\n0.333333 1.0\nName: question_type_procedure, dtype: float64\n0.0 1.0\nName: question_type_reason_explanation, dtype: float64\n0.0 1.0\nName: question_type_spelling, dtype: float64\n0.666667 1.0\nName: question_well_written, dtype: float64\n0.888889 1.0\nName: answer_helpful, dtype: float64\n0.666667 1.0\nName: answer_level_of_information, dtype: float64\n1.0 1.0\nName: answer_plausible, dtype: float64\n1.0 1.0\nName: answer_relevance, dtype: float64\n0.866667 1.0\nName: answer_satisfaction, dtype: float64\n1.0 1.0\nName: answer_type_instructions, dtype: float64\n0.0 1.0\nName: answer_type_procedure, dtype: float64\n0.0 1.0\nName: answer_type_reason_explanation, dtype: float64\n0.888889 1.0\nName: answer_well_written, dtype: float64\n" ], [ "def categorical_adjust(df_column):\n for in labels", "_____no_output_____" ], [ "train[[labels]]\nreal_sub[label].apply()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdf1d1781f0914def189e0454416822d97813ff
142,936
ipynb
Jupyter Notebook
01-Introduction/chapter01.ipynb
dariuszzbyrad/ML_for_Hackers
31aca9e7044b07e4f1cb976605af0c3a07f062dc
[ "BSD-2-Clause" ]
1
2021-03-13T07:22:05.000Z
2021-03-13T07:22:05.000Z
01-Introduction/chapter01.ipynb
dariuszzbyrad/ML_for_Hackers
31aca9e7044b07e4f1cb976605af0c3a07f062dc
[ "BSD-2-Clause" ]
null
null
null
01-Introduction/chapter01.ipynb
dariuszzbyrad/ML_for_Hackers
31aca9e7044b07e4f1cb976605af0c3a07f062dc
[ "BSD-2-Clause" ]
4
2019-07-19T04:38:13.000Z
2021-03-13T07:22:13.000Z
209.27672
75,432
0.871341
[ [ [ "# Code for Chapter 1. \n\nIn this case we will review some of the basic R functions and coding paradigms we will use throughout this book. This includes loading, viewing, and cleaning raw data; as well as some basic visualization. This specific case we will use data from reported UFO sightings to investigate what, if any, seasonal trends exists in the data.", "_____no_output_____" ], [ "## Load data", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ndf = pd.read_csv('data/ufo/ufo_awesome.tsv', sep='\\t', error_bad_lines=False, header=None)\ndf.shape\n\n#error_bad_lines=False - for some lines the last column which contains a description, contains also invalid character \\t, which is separator for us. We ignore it.", "b'Skipping line 755: expected 6 fields, saw 7\\nSkipping line 1167: expected 6 fields, saw 7\\nSkipping line 1569: expected 6 fields, saw 13\\nSkipping line 1571: expected 6 fields, saw 7\\nSkipping line 1659: expected 6 fields, saw 10\\nSkipping line 1951: expected 6 fields, saw 7\\nSkipping line 2077: expected 6 fields, saw 12\\nSkipping line 2382: expected 6 fields, saw 11\\nSkipping line 2753: expected 6 fields, saw 8\\nSkipping line 3076: expected 6 fields, saw 13\\nSkipping line 3218: expected 6 fields, saw 8\\nSkipping line 3238: expected 6 fields, saw 7\\nSkipping line 3346: expected 6 fields, saw 7\\nSkipping line 3453: expected 6 fields, saw 8\\nSkipping line 3513: expected 6 fields, saw 7\\nSkipping line 3571: expected 6 fields, saw 7\\nSkipping line 3632: expected 6 fields, saw 8\\nSkipping line 3718: expected 6 fields, saw 7\\nSkipping line 3814: expected 6 fields, saw 9\\nSkipping line 4607: expected 6 fields, saw 10\\nSkipping line 4627: expected 6 fields, saw 9\\nSkipping line 4666: expected 6 fields, saw 8\\nSkipping line 4996: expected 6 fields, saw 7\\nSkipping line 5357: expected 6 fields, saw 7\\nSkipping line 5371: expected 6 fields, saw 8\\nSkipping line 5531: expected 6 fields, saw 7\\nSkipping line 5686: expected 6 fields, saw 8\\nSkipping line 5919: expected 6 fields, saw 8\\nSkipping line 5927: expected 6 fields, saw 8\\nSkipping line 5988: expected 6 fields, saw 8\\nSkipping line 6043: expected 6 fields, saw 7\\nSkipping line 6337: expected 6 fields, saw 7\\nSkipping line 6403: expected 6 fields, saw 7\\nSkipping line 6646: expected 6 fields, saw 7\\nSkipping line 6803: expected 6 fields, saw 7\\nSkipping line 6924: expected 6 fields, saw 7\\nSkipping line 7341: expected 6 fields, saw 7\\nSkipping line 7736: expected 6 fields, saw 7\\nSkipping line 7737: expected 6 fields, saw 7\\nSkipping line 7834: expected 6 fields, saw 7\\nSkipping line 8177: expected 6 fields, saw 9\\nSkipping line 8470: expected 6 fields, saw 7\\nSkipping line 8539: expected 6 fields, saw 7\\nSkipping line 8546: expected 6 fields, saw 10\\nSkipping line 8815: expected 6 fields, saw 8\\nSkipping line 9014: expected 6 fields, saw 9\\nSkipping line 9043: expected 6 fields, saw 7\\nSkipping line 9155: expected 6 fields, saw 7\\nSkipping line 9350: expected 6 fields, saw 11\\nSkipping line 9400: expected 6 fields, saw 16\\nSkipping line 9533: expected 6 fields, saw 14\\nSkipping line 10060: expected 6 fields, saw 9\\nSkipping line 10219: expected 6 fields, saw 7\\nSkipping line 10820: expected 6 fields, saw 26\\nSkipping line 10953: expected 6 fields, saw 7\\nSkipping line 11035: expected 6 fields, saw 8\\nSkipping line 11671: expected 6 fields, saw 7\\nSkipping line 12155: expected 6 fields, saw 7\\nSkipping line 12324: expected 6 fields, saw 7\\nSkipping line 12464: expected 6 fields, saw 10\\nSkipping line 13600: expected 6 fields, saw 8\\nSkipping line 14799: expected 6 fields, saw 7\\nSkipping line 14923: expected 6 fields, saw 11\\nSkipping line 15026: expected 6 fields, saw 7\\nSkipping line 16147: expected 6 fields, saw 8\\nSkipping line 16865: expected 6 fields, saw 10\\nSkipping line 17307: expected 6 fields, saw 28\\nSkipping line 17619: expected 6 fields, saw 28\\nSkipping line 17644: expected 6 fields, saw 7\\nSkipping line 19515: expected 6 fields, saw 7\\nSkipping line 22182: expected 6 fields, saw 10\\nSkipping line 22600: expected 6 fields, saw 13\\nSkipping line 25163: expected 6 fields, saw 7\\nSkipping line 26619: expected 6 fields, saw 14\\nSkipping line 27120: expected 6 fields, saw 7\\nSkipping line 27230: expected 6 fields, saw 7\\nSkipping line 27394: expected 6 fields, saw 34\\nSkipping line 30609: expected 6 fields, saw 118\\nSkipping line 31120: expected 6 fields, saw 7\\nSkipping line 32439: expected 6 fields, saw 33\\nSkipping line 33087: expected 6 fields, saw 9\\nSkipping line 34733: expected 6 fields, saw 13\\nSkipping line 35622: expected 6 fields, saw 9\\nSkipping line 35943: expected 6 fields, saw 14\\nSkipping line 35993: expected 6 fields, saw 7\\nSkipping line 36007: expected 6 fields, saw 7\\nSkipping line 36111: expected 6 fields, saw 7\\nSkipping line 37201: expected 6 fields, saw 7\\nSkipping line 37330: expected 6 fields, saw 7\\nSkipping line 37657: expected 6 fields, saw 7\\nSkipping line 38386: expected 6 fields, saw 12\\nSkipping line 38636: expected 6 fields, saw 8\\nSkipping line 39533: expected 6 fields, saw 7\\nSkipping line 39639: expected 6 fields, saw 29\\nSkipping line 39910: expected 6 fields, saw 15\\nSkipping line 40214: expected 6 fields, saw 12\\nSkipping line 40446: expected 6 fields, saw 7\\nSkipping line 40540: expected 6 fields, saw 7\\nSkipping line 40547: expected 6 fields, saw 11\\nSkipping line 40677: expected 6 fields, saw 11\\nSkipping line 40899: expected 6 fields, saw 7\\nSkipping line 40960: expected 6 fields, saw 36\\nSkipping line 41034: expected 6 fields, saw 8\\nSkipping line 41185: expected 6 fields, saw 7\\nSkipping line 41461: expected 6 fields, saw 10\\nSkipping line 41486: expected 6 fields, saw 8\\nSkipping line 41497: expected 6 fields, saw 12\\nSkipping line 41509: expected 6 fields, saw 7\\nSkipping line 41542: expected 6 fields, saw 10\\nSkipping line 41549: expected 6 fields, saw 8\\nSkipping line 41625: expected 6 fields, saw 8\\nSkipping line 41739: expected 6 fields, saw 10\\nSkipping line 41812: expected 6 fields, saw 13\\nSkipping line 41860: expected 6 fields, saw 8\\nSkipping line 41903: expected 6 fields, saw 7\\nSkipping line 41930: expected 6 fields, saw 13\\nSkipping line 42058: expected 6 fields, saw 7\\nSkipping line 42072: expected 6 fields, saw 23\\nSkipping line 42105: expected 6 fields, saw 8\\nSkipping line 42133: expected 6 fields, saw 7\\nSkipping line 42165: expected 6 fields, saw 10\\nSkipping line 42293: expected 6 fields, saw 13\\nSkipping line 42344: expected 6 fields, saw 9\\nSkipping line 42361: expected 6 fields, saw 15\\nSkipping line 42370: expected 6 fields, saw 8\\nSkipping line 42379: expected 6 fields, saw 9\\nSkipping line 42496: expected 6 fields, saw 7\\nSkipping line 42523: expected 6 fields, saw 10\\nSkipping line 42546: expected 6 fields, saw 10\\nSkipping line 42547: expected 6 fields, saw 10\\nSkipping line 42565: expected 6 fields, saw 8\\nSkipping line 42570: expected 6 fields, saw 15\\nSkipping line 42587: expected 6 fields, saw 9\\nSkipping line 42608: expected 6 fields, saw 13\\nSkipping line 42655: expected 6 fields, saw 10\\nSkipping line 42679: expected 6 fields, saw 11\\nSkipping line 42694: expected 6 fields, saw 10\\nSkipping line 42771: expected 6 fields, saw 8\\nSkipping line 42784: expected 6 fields, saw 9\\nSkipping line 42827: expected 6 fields, saw 15\\nSkipping line 42841: expected 6 fields, saw 7\\nSkipping line 42853: expected 6 fields, saw 10\\nSkipping line 42872: expected 6 fields, saw 7\\nSkipping line 42888: expected 6 fields, saw 8\\nSkipping line 42902: expected 6 fields, saw 58\\nSkipping line 42915: expected 6 fields, saw 10\\nSkipping line 43007: expected 6 fields, saw 19\\nSkipping line 43046: expected 6 fields, saw 7\\nSkipping line 43091: expected 6 fields, saw 9\\nSkipping line 43155: expected 6 fields, saw 8\\nSkipping line 43176: expected 6 fields, saw 9\\nSkipping line 43232: expected 6 fields, saw 10\\nSkipping line 43240: expected 6 fields, saw 13\\nSkipping line 43249: expected 6 fields, saw 8\\nSkipping line 43298: expected 6 fields, saw 7\\nSkipping line 43332: expected 6 fields, saw 11\\nSkipping line 43367: expected 6 fields, saw 10\\nSkipping line 43369: expected 6 fields, saw 8\\nSkipping line 43418: expected 6 fields, saw 10\\nSkipping line 43461: expected 6 fields, saw 13\\nSkipping line 43560: expected 6 fields, saw 8\\nSkipping line 43612: expected 6 fields, saw 8\\nSkipping line 43622: expected 6 fields, saw 7\\nSkipping line 43625: expected 6 fields, saw 7\\nSkipping line 43644: expected 6 fields, saw 7\\nSkipping line 43645: expected 6 fields, saw 9\\nSkipping line 43648: expected 6 fields, saw 7\\nSkipping line 43761: expected 6 fields, saw 10\\nSkipping line 43772: expected 6 fields, saw 8\\nSkipping line 43792: expected 6 fields, saw 7\\nSkipping line 43796: expected 6 fields, saw 9\\nSkipping line 43824: expected 6 fields, saw 8\\nSkipping line 43891: expected 6 fields, saw 8\\nSkipping line 43985: expected 6 fields, saw 8\\nSkipping line 43994: expected 6 fields, saw 10\\nSkipping line 44000: expected 6 fields, saw 9\\nSkipping line 44030: expected 6 fields, saw 7\\nSkipping line 44032: expected 6 fields, saw 8\\nSkipping line 44088: expected 6 fields, saw 12\\nSkipping line 44131: expected 6 fields, saw 10\\nSkipping line 44178: expected 6 fields, saw 8\\nSkipping line 44220: expected 6 fields, saw 7\\nSkipping line 44269: expected 6 fields, saw 13\\nSkipping line 44403: expected 6 fields, saw 9\\nSkipping line 44497: expected 6 fields, saw 10\\nSkipping line 44530: expected 6 fields, saw 7\\nSkipping line 44579: expected 6 fields, saw 18\\nSkipping line 44582: expected 6 fields, saw 8\\nSkipping line 44587: expected 6 fields, saw 9\\nSkipping line 44651: expected 6 fields, saw 10\\nSkipping line 44652: expected 6 fields, saw 7\\nSkipping line 44706: expected 6 fields, saw 14\\nSkipping line 44794: expected 6 fields, saw 9\\nSkipping line 44803: expected 6 fields, saw 10\\nSkipping line 44824: expected 6 fields, saw 8\\nSkipping line 44970: expected 6 fields, saw 10\\nSkipping line 45115: expected 6 fields, saw 9\\nSkipping line 45184: expected 6 fields, saw 9\\nSkipping line 45198: expected 6 fields, saw 7\\nSkipping line 45232: expected 6 fields, saw 7\\nSkipping line 45398: expected 6 fields, saw 10\\nSkipping line 45422: expected 6 fields, saw 7\\nSkipping line 45565: expected 6 fields, saw 7\\nSkipping line 45570: expected 6 fields, saw 7\\nSkipping line 45593: expected 6 fields, saw 7\\nSkipping line 45645: expected 6 fields, saw 17\\nSkipping line 45698: expected 6 fields, saw 10\\nSkipping line 45774: expected 6 fields, saw 11\\nSkipping line 45845: expected 6 fields, saw 21\\nSkipping line 46138: expected 6 fields, saw 9\\nSkipping line 46238: expected 6 fields, saw 7\\nSkipping line 46251: expected 6 fields, saw 9\\nSkipping line 46254: expected 6 fields, saw 10\\nSkipping line 46271: expected 6 fields, saw 11\\nSkipping line 46292: expected 6 fields, saw 7\\nSkipping line 46297: expected 6 fields, saw 18\\nSkipping line 46389: expected 6 fields, saw 8\\nSkipping line 46402: expected 6 fields, saw 8\\nSkipping line 46469: expected 6 fields, saw 10\\nSkipping line 46551: expected 6 fields, saw 10\\nSkipping line 46594: expected 6 fields, saw 7\\nSkipping line 46634: expected 6 fields, saw 7\\nSkipping line 46717: expected 6 fields, saw 10\\nSkipping line 46882: expected 6 fields, saw 10\\nSkipping line 46957: expected 6 fields, saw 9\\nSkipping line 47033: expected 6 fields, saw 7\\nSkipping line 47102: expected 6 fields, saw 7\\nSkipping line 47123: expected 6 fields, saw 7\\nSkipping line 47200: expected 6 fields, saw 8\\nSkipping line 47206: expected 6 fields, saw 9\\nSkipping line 47230: expected 6 fields, saw 123\\nSkipping line 47285: expected 6 fields, saw 9\\nSkipping line 47371: expected 6 fields, saw 7\\nSkipping line 47381: expected 6 fields, saw 7\\nSkipping line 47654: expected 6 fields, saw 7\\nSkipping line 47768: expected 6 fields, saw 8\\nSkipping line 47813: expected 6 fields, saw 8\\nSkipping line 48057: expected 6 fields, saw 12\\nSkipping line 48071: expected 6 fields, saw 7\\nSkipping line 48087: expected 6 fields, saw 38\\nSkipping line 48090: expected 6 fields, saw 11\\nSkipping line 48130: expected 6 fields, saw 8\\nSkipping line 48365: expected 6 fields, saw 7\\nSkipping line 48670: expected 6 fields, saw 7\\nSkipping line 48745: expected 6 fields, saw 8\\nSkipping line 48866: expected 6 fields, saw 12\\nSkipping line 49022: expected 6 fields, saw 7\\nSkipping line 49079: expected 6 fields, saw 7\\nSkipping line 49092: expected 6 fields, saw 9\\nSkipping line 49133: expected 6 fields, saw 7\\nSkipping line 49417: expected 6 fields, saw 7\\nSkipping line 49563: expected 6 fields, saw 7\\nSkipping line 49746: expected 6 fields, saw 7\\nSkipping line 49800: expected 6 fields, saw 7\\nSkipping line 49836: expected 6 fields, saw 7\\nSkipping line 49922: expected 6 fields, saw 7\\nSkipping line 50005: expected 6 fields, saw 13\\nSkipping line 50094: expected 6 fields, saw 14\\nSkipping line 50102: expected 6 fields, saw 11\\nSkipping line 50257: expected 6 fields, saw 8\\nSkipping line 50485: expected 6 fields, saw 21\\nSkipping line 50600: expected 6 fields, saw 7\\nSkipping line 50609: expected 6 fields, saw 8\\nSkipping line 50704: expected 6 fields, saw 7\\nSkipping line 50830: expected 6 fields, saw 7\\nSkipping line 51076: expected 6 fields, saw 7\\nSkipping line 51238: expected 6 fields, saw 7\\nSkipping line 51749: expected 6 fields, saw 8\\nSkipping line 52276: expected 6 fields, saw 7\\nSkipping line 52475: expected 6 fields, saw 7\\nSkipping line 52705: expected 6 fields, saw 7\\nSkipping line 53011: expected 6 fields, saw 7\\nSkipping line 53058: expected 6 fields, saw 7\\nSkipping line 53086: expected 6 fields, saw 7\\nSkipping line 53181: expected 6 fields, saw 7\\nSkipping line 53232: expected 6 fields, saw 8\\nSkipping line 53325: expected 6 fields, saw 7\\nSkipping line 53398: expected 6 fields, saw 7\\nSkipping line 53517: expected 6 fields, saw 14\\nSkipping line 53583: expected 6 fields, saw 7\\nSkipping line 53997: expected 6 fields, saw 12\\nSkipping line 54005: expected 6 fields, saw 7\\nSkipping line 54182: expected 6 fields, saw 10\\nSkipping line 54237: expected 6 fields, saw 8\\nSkipping line 54367: expected 6 fields, saw 56\\nSkipping line 54544: expected 6 fields, saw 7\\nSkipping line 54582: expected 6 fields, saw 7\\nSkipping line 55194: expected 6 fields, saw 10\\nSkipping line 55218: expected 6 fields, saw 12\\nSkipping line 55290: expected 6 fields, saw 76\\nSkipping line 55381: expected 6 fields, saw 9\\nSkipping line 55493: expected 6 fields, saw 7\\nSkipping line 55810: expected 6 fields, saw 7\\nSkipping line 55853: expected 6 fields, saw 9\\nSkipping line 55897: expected 6 fields, saw 21\\nSkipping line 56001: expected 6 fields, saw 7\\nSkipping line 56082: expected 6 fields, saw 56\\nSkipping line 56114: expected 6 fields, saw 7\\nSkipping line 56128: expected 6 fields, saw 7\\nSkipping line 56199: expected 6 fields, saw 8\\nSkipping line 56487: expected 6 fields, saw 8\\nSkipping line 56550: expected 6 fields, saw 9\\nSkipping line 56610: expected 6 fields, saw 7\\nSkipping line 56733: expected 6 fields, saw 46\\nSkipping line 56735: expected 6 fields, saw 7\\nSkipping line 56993: expected 6 fields, saw 7\\nSkipping line 57060: expected 6 fields, saw 7\\nSkipping line 57087: expected 6 fields, saw 7\\nSkipping line 57426: expected 6 fields, saw 7\\nSkipping line 57527: expected 6 fields, saw 7\\nSkipping line 57828: expected 6 fields, saw 7\\nSkipping line 58144: expected 6 fields, saw 10\\nSkipping line 58191: expected 6 fields, saw 16\\nSkipping line 58404: expected 6 fields, saw 13\\nSkipping line 58654: expected 6 fields, saw 7\\nSkipping line 58662: expected 6 fields, saw 7\\nSkipping line 58804: expected 6 fields, saw 56\\nSkipping line 59066: expected 6 fields, saw 7\\nSkipping line 59119: expected 6 fields, saw 7\\nSkipping line 59461: expected 6 fields, saw 9\\nSkipping line 60196: expected 6 fields, saw 7\\nSkipping line 60754: expected 6 fields, saw 7\\nSkipping line 60972: expected 6 fields, saw 11\\nSkipping line 61138: expected 6 fields, saw 7\\n'\n" ], [ "df.head()", "_____no_output_____" ] ], [ [ "## Set columns names", "_____no_output_____" ] ], [ [ "df.columns = [\"DateOccurred\",\"DateReported\",\"Location\",\"ShortDescription\",\n\"Duration\",\"LongDescription\"]", "_____no_output_____" ] ], [ [ "## Check data size for the DateOccurred and DateReported columns", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n%matplotlib inline\ndf['DateOccurred'].astype(str).str.len().plot(kind='hist')\ndf['DateReported'].astype(str).str.len().plot(kind='hist')", "_____no_output_____" ] ], [ [ "## Remove rows with incorrect dates (length not eqauls 8)", "_____no_output_____" ] ], [ [ "mask = (df['DateReported'].astype('str').str.len() == 8) & (df['DateOccurred'].astype('str').str.len() == 8)\n \ndf = df.loc[mask]\n\ndf.shape", "_____no_output_____" ] ], [ [ "## Convert the DateReported and DateOccurred columns to Date type", "_____no_output_____" ] ], [ [ "df['DateReported'] = pd.to_datetime(df['DateReported'], format='%Y%m%d', errors='coerce')\ndf['DateOccurred'] = pd.to_datetime(df['DateOccurred'], format='%Y%m%d', errors='coerce')", "_____no_output_____" ] ], [ [ "## Split the 'Locaton' column to two new columns: 'City' and 'State'", "_____no_output_____" ] ], [ [ "df_location = df['Location'].str.partition(', ')[[0, 2]]\ndf_location.columns = ['USCity', 'USState']\ndf['USCity'] = df_location['USCity']\ndf['USState'] = df_location['USState']\n\ndf.head()", "_____no_output_____" ] ], [ [ "## Keep rows only with correct US states", "_____no_output_____" ] ], [ [ "USStates = [\"AK\",\"AL\",\"AR\",\"AZ\",\"CA\",\"CO\",\"CT\",\"DE\",\"FL\",\"GA\",\"HI\",\"IA\",\"ID\",\"IL\",\n\"IN\",\"KS\",\"KY\",\"LA\",\"MA\",\"MD\",\"ME\",\"MI\",\"MN\",\"MO\",\"MS\",\"MT\",\"NC\",\"ND\",\"NE\",\"NH\",\n\"NJ\",\"NM\",\"NV\",\"NY\",\"OH\",\"OK\",\"OR\",\"PA\",\"RI\",\"SC\",\"SD\",\"TN\",\"TX\",\"UT\",\"VA\",\"VT\",\n\"WA\",\"WI\",\"WV\",\"WY\"]\n\ndf = df[df['USState'].isin(USStates)]\n\ndf.head()", "_____no_output_____" ] ], [ [ "## Creating a histogram of frequencies for UFO sightings over time", "_____no_output_____" ] ], [ [ "df['DateOccurred'].dt.year.plot(kind='hist', bins=15, title='Exploratory histogram of UFO data over time')", "_____no_output_____" ] ], [ [ "## We will only look at incidents that occurred from 1990 to the most recent", "_____no_output_____" ] ], [ [ "df = df[(df['DateOccurred'] >= '1990-01-01')]", "_____no_output_____" ], [ "df['DateOccurred'].dt.year.plot(kind='hist', bins=15, title='Histogram of subset UFO data over time (1900 - 2010)')", "_____no_output_____" ] ], [ [ "## Create finally histogram of subset UFO data over time (1900 - 2010) by US state", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\nplt.style.use('ggplot')\n\n# set up figure & axes\nfig, axes = plt.subplots(nrows=10, ncols=5, sharex=True, sharey=True, figsize=(18, 12), dpi= 80)\n\n# drop sharex, sharey, layout & add ax=axes\ndf['YearOccurred'] = df['DateOccurred'].dt.year\ndf.hist(column='YearOccurred',by='USState', ax=axes)\n\n# set title and axis labels\nplt.suptitle('Number of UFO sightings by Month-Year and U.S. State (1990-2010)', x=0.5, y=1, ha='center', fontsize='xx-large')\nfig.text(0.5, 0.06, 'Times', ha='center', fontsize='x-large')\nfig.text(0.05, 0.5, 'Number of Sightings', va='center', rotation='vertical', fontsize='x-large')\nplt.savefig('images/ufo_sightings.pdf', format='pdf')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cbdf222ffefc3277a498a989a0b1a8090fc7585a
1,414
ipynb
Jupyter Notebook
examples/gallery/demos/matplotlib/boxplot_chart.ipynb
jsignell/holoviews
4f9fd27367f23c3d067d176f638ec82e4b9ec8f0
[ "BSD-3-Clause" ]
1
2019-01-02T20:20:09.000Z
2019-01-02T20:20:09.000Z
examples/gallery/demos/matplotlib/boxplot_chart.ipynb
jsignell/holoviews
4f9fd27367f23c3d067d176f638ec82e4b9ec8f0
[ "BSD-3-Clause" ]
null
null
null
examples/gallery/demos/matplotlib/boxplot_chart.ipynb
jsignell/holoviews
4f9fd27367f23c3d067d176f638ec82e4b9ec8f0
[ "BSD-3-Clause" ]
1
2021-10-31T05:26:08.000Z
2021-10-31T05:26:08.000Z
20.2
98
0.545262
[ [ [ "URL: http://bokeh.pydata.org/en/latest/docs/gallery/boxplot_chart.html\n\nMost examples work across multiple plotting backends, this example is also available for:\n\n* [Bokeh - boxplot_chart](../bokeh/boxplot_chart.ipynb)", "_____no_output_____" ] ], [ [ "import holoviews as hv\nhv.extension('matplotlib')\n%output fig='svg'", "_____no_output_____" ] ], [ [ "## Declaring data", "_____no_output_____" ] ], [ [ "from bokeh.sampledata.autompg import autompg as df\n\ntitle = \"MPG by Cylinders and Data Source, Colored by Cylinders\"\nboxwhisker = hv.BoxWhisker(df, ['cyl', 'origin'], 'mpg', label=title)", "_____no_output_____" ] ], [ [ "## Plot", "_____no_output_____" ] ], [ [ "boxwhisker.options(bgcolor='white', aspect=2, fig_size=200)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbdf29a6b705944e7d045e557d18e7ade25cfead
514,084
ipynb
Jupyter Notebook
ASPECT_quadHex.ipynb
chrishavlin/unstructured_vtu
b2b2babee2537cf0b633b2f95167f5ae8e78c4ea
[ "BSD-3-Clause" ]
1
2020-08-05T19:37:01.000Z
2020-08-05T19:37:01.000Z
ASPECT_quadHex.ipynb
chrishavlin/unstructured_vtu
b2b2babee2537cf0b633b2f95167f5ae8e78c4ea
[ "BSD-3-Clause" ]
1
2020-08-15T15:37:59.000Z
2020-08-15T15:37:59.000Z
ASPECT_quadHex.ipynb
chrishavlin/unstructured_vtu
b2b2babee2537cf0b633b2f95167f5ae8e78c4ea
[ "BSD-3-Clause" ]
1
2020-06-23T14:35:12.000Z
2020-06-23T14:35:12.000Z
1,321.552699
460,349
0.978941
[ [ [ "# Attempting to load higher order ASPECT elements\n\nAn initial attempt at loading higher order element output from ASPECT. \n\nThe VTU files have elements with a VTU type of `VTK_LAGRANGE_HEXAHEDRON` (VTK ID number 72, https://vtk.org/doc/nightly/html/classvtkLagrangeHexahedron.html#details), corresponding to 2nd order (quadratic) hexahedron, resulting in 27 nodes. \n\nSome useful links about this type of FEM output:\n* https://blog.kitware.com/modeling-arbitrary-order-lagrange-finite-elements-in-the-visualization-toolkit/\n* https://github.com/Kitware/VTK/blob/0ce0d74e67927fd964a27c045d68e2f32b5f65f7/Common/DataModel/vtkCellType.h#L112\n* https://github.com/ju-kreber/paraview-scripts\n* https://doi.org/10.1016/B978-1-85617-633-0.00006-X\n* https://discourse.paraview.org/t/about-high-order-non-traditional-lagrange-finite-element/1577/4\n* https://gitlab.kitware.com/vtk/vtk/-/blob/7a0b92864c96680b1f42ee84920df556fc6ebaa3/Common/DataModel/vtkHigherOrderInterpolation.cxx \n\nAt present, tis notebook requires the `vtu72` branch on the `meshio` fork at https://github.com/chrishavlin/meshio/pull/new/vtu72 to attempt to load the `VTK_LAGRANGE_HEXAHEDRON` output. \n\nAs seen below, the data can be loaded with the general `unstructured_mesh_loader` but `yt` can not presently handle higher order output. \n", "_____no_output_____" ] ], [ [ "import os, yt, numpy as np\nimport xmltodict, meshio ", "_____no_output_____" ], [ "DataDir=os.path.join(os.environ.get('ASPECTdatadir','../'),'litho_defo_sample','data')", "_____no_output_____" ], [ "pFile=os.path.join(DataDir,'solution-00002.pvtu')\nif os.path.isfile(pFile) is False:\n print(\"data file not found\")", "_____no_output_____" ], [ "class pvuFile(object):\n def __init__(self,file,**kwargs):\n self.file=file \n self.dataDir=kwargs.get('dataDir',os.path.split(file)[0])\n with open(file) as data:\n self.pXML = xmltodict.parse(data.read())\n \n # store fields for convenience \n self.fields=self.pXML['VTKFile']['PUnstructuredGrid']['PPointData']['PDataArray'] \n \n def load(self): \n \n conlist=[] # list of 2D connectivity arrays \n coordlist=[] # global, concatenated coordinate array \n nodeDictList=[] # list of node_data dicts, same length as conlist \n\n con_offset=-1\n for mesh_id,src in enumerate(self.pXML['VTKFile']['PUnstructuredGrid']['Piece']): \n mesh_name=\"connect{meshnum}\".format(meshnum=mesh_id+1) # connect1, connect2, etc. \n srcFi=os.path.join(self.dataDir,src['@Source']) # full path to .vtu file \n \n [con,coord,node_d]=self.loadPiece(srcFi,mesh_name,con_offset+1) \n con_offset=con.max() \n \n conlist.append(con.astype(\"i8\"))\n coordlist.extend(coord.astype(\"f8\"))\n nodeDictList.append(node_d)\n \n self.connectivity=conlist\n self.coordinates=np.array(coordlist)\n self.node_data=nodeDictList\n \n def loadPiece(self,srcFi,mesh_name,connectivity_offset=0): \n# print(srcFi)\n meshPiece=meshio.read(srcFi) # read it in with meshio \n coords=meshPiece.points # coords and node_data are already global\n connectivity=meshPiece.cells_dict['lagrange_hexahedron'] # 2D connectivity array \n\n # parse node data \n node_data=self.parseNodeData(meshPiece.point_data,connectivity,mesh_name)\n\n # offset the connectivity matrix to global value \n connectivity=np.array(connectivity)+connectivity_offset\n\n return [connectivity,coords,node_data]\n \n def parseNodeData(self,point_data,connectivity,mesh_name):\n \n # for each field, evaluate field data by index, reshape to match connectivity \n con1d=connectivity.ravel() \n conn_shp=connectivity.shape \n \n comp_hash={0:'cx',1:'cy',2:'cz'}\n def rshpData(data1d):\n return np.reshape(data1d[con1d],conn_shp)\n \n node_data={} \n for fld in self.fields: \n nm=fld['@Name']\n if nm in point_data.keys():\n if '@NumberOfComponents' in fld.keys() and int(fld['@NumberOfComponents'])>1:\n # we have a vector, deal with components\n for component in range(int(fld['@NumberOfComponents'])): \n comp_name=nm+'_'+comp_hash[component] # e.g., velocity_cx \n m_F=(mesh_name,comp_name) # e.g., ('connect1','velocity_cx')\n node_data[m_F]=rshpData(point_data[nm][:,component])\n else:\n # just a scalar! \n m_F=(mesh_name,nm) # e.g., ('connect1','T')\n node_data[m_F]=rshpData(point_data[nm])\n \n return node_data \n", "_____no_output_____" ], [ "pvuData=pvuFile(pFile)\npvuData.load()", "_____no_output_____" ] ], [ [ "So it loads... `meshio`'s treatment of high order elements is not complicated: it assumes the same number of nodes per elements and just reshapes the 1d connectivity array appropriately. In this case, a single element has 27 nodes:", "_____no_output_____" ] ], [ [ "pvuData.connectivity[0].shape", "_____no_output_____" ] ], [ [ "And yes, it can load:", "_____no_output_____" ] ], [ [ "ds4 = yt.load_unstructured_mesh(\n pvuData.connectivity,\n pvuData.coordinates,\n node_data = pvuData.node_data\n) ", "yt : [INFO ] 2020-08-07 11:08:49,548 Parameters: current_time = 0.0\nyt : [INFO ] 2020-08-07 11:08:49,549 Parameters: domain_dimensions = [2 2 2]\nyt : [INFO ] 2020-08-07 11:08:49,549 Parameters: domain_left_edge = [0. 0. 0.]\nyt : [INFO ] 2020-08-07 11:08:49,550 Parameters: domain_right_edge = [88000. 550. 33000.]\nyt : [INFO ] 2020-08-07 11:08:49,550 Parameters: cosmological_simulation = 0.0\n" ] ], [ [ "but the plots are don't actually take advantage of all the data, noted by the warning when slicing: \"High order elements not yet supported, dropping to 1st order.\"", "_____no_output_____" ] ], [ [ "p=yt.SlicePlot(ds4, \"x\", (\"all\", \"T\"))\np.set_log(\"T\",False)\np.show()", "yt : [INFO ] 2020-08-07 11:08:50,026 xlim = 0.000000 550.000000\nyt : [INFO ] 2020-08-07 11:08:50,027 ylim = 0.000000 33000.000000\nyt : [INFO ] 2020-08-07 11:08:50,027 xlim = 0.000000 550.000000\nyt : [INFO ] 2020-08-07 11:08:50,028 ylim = 0.000000 33000.000000\nyt : [INFO ] 2020-08-07 11:08:50,032 Making a fixed resolution buffer of (('all', 'T')) 800 by 800\nyt : [WARNING ] 2020-08-07 11:08:50,039 High order elements not yet supported, dropping to 1st order.\n" ] ], [ [ "This run is a very high aspect ratio cartesian simulation so let's rescale the coords first and then reload (**TO DO** look up how to do this with *yt* after loading the data...)", "_____no_output_____" ] ], [ [ "def minmax(x):\n return [x.min(),x.max()]\n\nfor idim in range(0,3):\n print([idim,minmax(pvuData.coordinates[:,idim])])", "[0, [0.0, 80000.0]]\n[1, [0.0, 500.0]]\n[2, [0.0, 30000.0]]\n" ], [ "# some artificial rescaling \nfor idim in range(0,3):\n pvuData.coordinates[:,idim]=pvuData.coordinates[:,idim] / pvuData.coordinates[:,idim].max()\n", "_____no_output_____" ], [ "ds4 = yt.load_unstructured_mesh(\n pvuData.connectivity,\n pvuData.coordinates,\n node_data = pvuData.node_data\n) ", "yt : [INFO ] 2020-08-07 11:08:53,803 Parameters: current_time = 0.0\nyt : [INFO ] 2020-08-07 11:08:53,803 Parameters: domain_dimensions = [2 2 2]\nyt : [INFO ] 2020-08-07 11:08:53,804 Parameters: domain_left_edge = [0. 0. 0.]\nyt : [INFO ] 2020-08-07 11:08:53,804 Parameters: domain_right_edge = [1.1 1.1 1.1]\nyt : [INFO ] 2020-08-07 11:08:53,805 Parameters: cosmological_simulation = 0.0\n" ], [ "p=yt.SlicePlot(ds4, \"x\", (\"all\", \"T\"))\np.set_log(\"T\",False)\np.show()", "yt : [INFO ] 2020-08-07 11:08:54,279 xlim = 0.000000 1.100000\nyt : [INFO ] 2020-08-07 11:08:54,279 ylim = 0.000000 1.100000\nyt : [INFO ] 2020-08-07 11:08:54,279 xlim = 0.000000 1.100000\nyt : [INFO ] 2020-08-07 11:08:54,280 ylim = 0.000000 1.100000\nyt : [INFO ] 2020-08-07 11:08:54,280 Making a fixed resolution buffer of (('all', 'T')) 800 by 800\nyt : [WARNING ] 2020-08-07 11:08:54,288 High order elements not yet supported, dropping to 1st order.\n" ] ], [ [ "To use all the data, we need to add a new element mapping for sampling these elements (see `yt/utilities/lib/element_mappings.pyx`). These element mappings can be automatically generated using a symbolic math library, e.g., `sympy`. See `ASPECT_VTK_quad_hex_mapping.ipynb`", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
cbdf542afe37469cd763f45431a8d49b71745244
69,917
ipynb
Jupyter Notebook
titanic_shipwreck.ipynb
sushiPlague/titanic-shipwreck-prediction-model
eb97f344b8eaf46b57c1aed68e8de865c5783f08
[ "MIT" ]
null
null
null
titanic_shipwreck.ipynb
sushiPlague/titanic-shipwreck-prediction-model
eb97f344b8eaf46b57c1aed68e8de865c5783f08
[ "MIT" ]
null
null
null
titanic_shipwreck.ipynb
sushiPlague/titanic-shipwreck-prediction-model
eb97f344b8eaf46b57c1aed68e8de865c5783f08
[ "MIT" ]
null
null
null
103.888559
16,032
0.809803
[ [ [ "<img src=\"resources/titanic_sinking.gif\" alt=\"Titanic sinking gif\" style=\"margin: 10px auto 20px; border-radius: 15px;\" width=\"100%\"/>", "_____no_output_____" ], [ "<a id=\"project-overview\"></a>\n_**Potonuće Titanika** jedno je od najozloglašenijih brodoloma u istoriji._\n\n_15. aprila 1912. godine, tokom njegovog prvog putovanja, široko smatrani „nepotopivi“ RMS Titanic potonuo je nakon sudara sa santom leda u severnom Atlantskom okeanu. Nažalost, nije bilo dovoljno čamaca za spasavanje za sve na brodu, što je rezultovalo smrću 1502 od 2224 putnika i posade._\n\n_Iako je u preživljavanju učestvovao neki element sreće, čini se da su neke grupe ljudi imale veću verovatnoću preživljavanja u odnosu na druge._\n\nCilj projekta predstavlja prediktivni model koji odgovara na pitanje: _„za koje vrste ljudi je veća verovatnoća da će preživeti?“_ korišćenjem dostupnih podataka o putnicima (tj. ime, starost, pol, socijalno-ekonomska klasa, itd.).\n\n<hr>\n\n<a id=\"table-of-contents\"></a>\n### Pregled sadržaja:\n* [Pregled projekta](#project-overview)\n* [Učitavanje i opis skupa podataka](#loading-datasets)\n* [Provera relevantnosti kolona za model](#column-relevance)\n* [Kreiranje trening i test skupova podataka](#train-test-split)\n* [Evaluacija/bodovanje klasifikacionih algoritama](#model-scoring)\n* [Model i predikcija](#model-prediction)\n\n<hr>", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import normalize, scale\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression, Perceptron\nfrom sklearn.svm import SVC\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "### Učitavanje i opis skupa podataka <a id=\"loading-datasets\"></a>\n\n<a href=\"#table-of-contents\"> Povratak na pregled sadržaja </a>\n\n", "_____no_output_____" ], [ "<div style=\"display: inline-block;\">\n\n \n| Variable | Definition | Key |\n|----------|------------------------------------------|------------------------------------------------|\n| Survived | Yes or No | 1 = Survived, 0 = Died |\n| Pclass | A proxy of socio-economic status (SES) | 1 = Upper, 2 = Middle, 3 = Lower |\n| Name | Passenger name | e.g. Allen, Mr. William Henry |\n| Sex | Passenger sex | male or female |\n| Age | Passenger age | integer |\n| SibSp | # of siblings/spouses aboard the Titanic | integer |\n| Parch | # of parents/children aboard the Titanic | integer |\n| Ticket | Ticket number | e.g. A/5 21171 |\n| Fare | Passenger fare | float |\n| Cabin | Cabin number (str) | e.g. B42 |\n| Embarked | Port of Embarkation | C = Cherbourg, Q = Queenstown, S = Southampton |\n \n \n</div>\n\n- **train.csv** sadrži detalje o podskupu putnika na brodu (tačnije 891 putnik - gde svaki putnik predstavlja zaseban red u tabeli).\n- **test.csv** sadrži detalje o podskupu putnika na brodu (tačnije 418 putnika - gde svaki putnik predstavlja zaseban red u tabeli) ** **bez 'Survived' kolone**.", "_____no_output_____" ] ], [ [ "# ucitavanje skupova podataka\ntrain_df = pd.read_csv(\"datasets/train.csv\").dropna(subset=[\"Age\"])\ntest_df = pd.read_csv(\"datasets/test.csv\")\n\ntrain_df.describe()", "_____no_output_____" ] ], [ [ "### Provera relevantnosti kolona za model<a id=\"column-relevance\"></a>\n\nPotrebno je proveriti koje od kolona uticu na rezultat prezivljavanja odredjenog putnika.\n\n- Sex - Izracunavanjem srednje vrednosti smo ustanovili da je **pol** putnika igrao bitnu ulogu u prezivljavanju. (veci deo prezivelih je bio zenskog pola)\n- Pclass - Izracunavanjem srednje vrednosti smo ustanovili da je **socijalno-ekonomska klasa** putnika igrala bitnu ulogu u prezivljavanju\n- SibSp - Iz histograma mozemo zakljuciti da je vecina prezivelih imala manje od dvoje brace/sestara ili partnera na Titaniku, tako da je **broj brace/sestara/partnera** igrao bitnu ulogu u prezivljavanju.\n- Age - Iz histograma mozemo zakljuciti da je vecina prezivelih bila starosti od 20-40 godina.\n- Parch - Iz histograma mozemo zakljuciti da je vecina prezivelih imala manje od dva deteta ili roditelja na Titaniku, tako daje **broj dece/roditelja** igrao bitnu ulogu u prezivljavanju. \n- U 'Cabin' koloni postoje duplikati, verovatno zato sto su odredjeni putnici delili kabinu, takodje ima dosta nepotpunih podataka.\n- Vecina putnika se ukrcala u Southampton-u.\n- Ime putnika kao i identifikacioni broj putnika nemaju nikakav uticaj na prezivljavanje.\n\n<a href=\"#table-of-contents\"> Povratak na pregled sadržaja </a>", "_____no_output_____" ] ], [ [ "# Sex\nsns.catplot(x=\"Sex\", y =\"Survived\", data=train_df, kind=\"bar\", height=4)\nplt.show()\n\nmen = np.mean(train_df.loc[train_df.Sex == 'male'][\"Survived\"])\nwomen = np.mean(train_df.loc[train_df.Sex == 'female'][\"Survived\"])\n\nprint(f'Procenat muskaraca koji su preziveli iznosi {men * 100:.2f}%, a procenat zena {women * 100:.2f}%.\\n')\n\n# Pclass\nsns.catplot(x=\"Pclass\", y =\"Survived\", data=train_df, kind=\"bar\", height=4)\nplt.show()\n\nupper = np.mean(train_df.loc[train_df.Pclass == 1][\"Survived\"])\nmiddle = np.mean(train_df.loc[train_df.Pclass == 2][\"Survived\"])\nlower = np.mean(train_df.loc[train_df.Pclass == 3][\"Survived\"])\n\nprint(f'Procenat prezivelih vise socijalno-ekonomske klase iznosi {upper * 100:.2f}%,',\n f'srednje {middle * 100:.2f}%,',\n f'i nize klase {lower * 100:.2f}%.\\n')\n\n# SibSp\ng = sns.FacetGrid(train_df, col='Survived')\ng.map(plt.hist, 'SibSp', bins=20)\nplt.show()\n\n# Age\ng = sns.FacetGrid(train_df, col='Survived')\ng.map(plt.hist, 'Age', bins=20)\nplt.show()\n\n# Parch\ng = sns.FacetGrid(train_df, col='Survived')\ng.map(plt.hist, 'Parch', bins=20)\nplt.show()", "_____no_output_____" ] ], [ [ "### Kreiranje trening i test skupova podataka <a id=\"train-test-split\"></a>\n\n<a href=\"#table-of-contents\"> Povratak na pregled sadržaja </a>", "_____no_output_____" ] ], [ [ "features = [\"Pclass\", \"Sex\", \"SibSp\", \"Parch\"]\n\ntrain_x = pd.get_dummies(train_df[features])\ntrain_y = train_df.Survived.to_numpy()\n\ntest_x = pd.get_dummies(test_df[features])", "_____no_output_____" ] ], [ [ "### Evaluacija/bodovanje klasifikacionih algoritama <a id=\"model-scoring\"></a>\n\n<a href=\"#table-of-contents\"> Povratak na pregled sadržaja </a>", "_____no_output_____" ], [ "Bodovanjem 5 klasifikacionih algoritama cemo odrediti koji nam najvise odgovara za kreiranje prediktivnog modela.\n\nAlgoritmi koji su bodovani/evaluirani:\n- Random Forest ❌\n- K Nearest Neighbor (KNN) ❌\n- Support Vector Machine (SVM) ✔️\n- Logistic Regression ❌\n- Perceptron ❌\n\nEvaluaciju smo vrsili sa '**cross_val_score**' metodom koja predstavlja nacin da iskoristimo trening podatke da bismo dobili dobre procene kako ce se model izvrsavati sa test podacima.", "_____no_output_____" ] ], [ [ "\"\"\"\nRandom Forest\n\"\"\"\nrandom_forest = RandomForestClassifier(n_estimators=200, max_depth=5, random_state=1)\nscore = cross_val_score(random_forest, train_x, train_y, scoring='accuracy', cv=10).mean()\nprint(f'Random Forest Score: {score * 100:.2f}%')\n\n\n\"\"\"\nKNN\n\"\"\"\nknn = KNeighborsClassifier(n_neighbors=25)\nscore = cross_val_score(knn, train_x, train_y, scoring='accuracy', cv=10).mean()\nprint(f'KNN Score: {score * 100:.2f}%')\n\n\n\"\"\"\nSVM\n\"\"\"\nsvm = SVC(kernel=\"rbf\")\nscore = cross_val_score(svm, train_x, train_y, scoring='accuracy', cv=10).mean()\nprint(f'SVM Score: {score * 100:.2f}%')\n\n\n\"\"\"\nLogistic Regression\n\"\"\"\nlog_reg = LogisticRegression(max_iter=2000)\nscore = cross_val_score(log_reg, train_x, train_y, scoring='accuracy', cv=10).mean()\nprint(f'Logistic Regression Score: {score * 100:.2f}%')\n\n\n\"\"\"\nPerceptron\n\"\"\"\nperceptron = Perceptron(random_state=1)\nscore = cross_val_score(perceptron, train_x, train_y, scoring='accuracy', cv=10).mean()\nprint(f'Perceptron Score: {score * 100:.2f}%')", "Random Forest Score: 78.58%\nKNN Score: 77.86%\nSVM Score: 79.27%\nLogistic Regression Score: 78.28%\nPerceptron Score: 67.95%\n" ] ], [ [ "### Model i predikcija <a id=\"model-prediction\"></a>\n\n<a href=\"#table-of-contents\"> Povratak na pregled sadržaja </a>", "_____no_output_____" ], [ "S obzirom da smo pri evaluaciji 5 klasifikacionih algoritama videli da **Support Vector Machine** (_SVM_) klasifikator daje najbolje rezultate, njega cemo odabrati za kreiranje prediktivnog modela.", "_____no_output_____" ] ], [ [ "svm.fit(train_x, train_y)\npredictions = svm.predict(test_x)\n\noutput = pd.DataFrame({'PassengerId': test_df.PassengerId, 'Survived': predictions})\noutput.to_csv('survival_prediction.csv', index=False)\n\noutput", "_____no_output_____" ] ], [ [ "### Score\n\n![Kaggle Score](attachment:4fb97ef8-ca3c-489f-9744-758ab04bef43.png)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
cbdf5671c6e209b12fae73bc2caba11bcc8d6aaa
27,687
ipynb
Jupyter Notebook
US_Transporter_eval.ipynb
tripathiarpan20/US-Transporter-eval
5620bb9f3c4eca16b0550cc05a9c17f2278e41d9
[ "MIT" ]
null
null
null
US_Transporter_eval.ipynb
tripathiarpan20/US-Transporter-eval
5620bb9f3c4eca16b0550cc05a9c17f2278e41d9
[ "MIT" ]
null
null
null
US_Transporter_eval.ipynb
tripathiarpan20/US-Transporter-eval
5620bb9f3c4eca16b0550cc05a9c17f2278e41d9
[ "MIT" ]
null
null
null
53.142035
360
0.555784
[ [ [ "<a href=\"https://colab.research.google.com/github/tripathiarpan20/US-Transporter-eval/blob/main/US_Transporter_eval.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "%cd /content/\n!git clone --recursive https://github.com/tripathiarpan20/US-Transporter-eval.git\n%cd US-Transporter-eval\n!pip install -r requirements.txt\n!mv phasepack/phasepack/* phasepack/", "/content\nCloning into 'US-Transporter-eval'...\nremote: Enumerating objects: 46, done.\u001b[K\nremote: Counting objects: 100% (46/46), done.\u001b[K\nremote: Compressing objects: 100% (33/33), done.\u001b[K\nremote: Total 46 (delta 17), reused 27 (delta 9), pack-reused 0\u001b[K\nUnpacking objects: 100% (46/46), done.\nSubmodule 'phasepack' (https://github.com/alimuldal/phasepack.git) registered for path 'phasepack'\nSubmodule 'pyssim' (https://github.com/jterrace/pyssim.git) registered for path 'pyssim'\nCloning into '/content/US-Transporter-eval/phasepack'...\nremote: Enumerating objects: 74, done. \nremote: Total 74 (delta 0), reused 0 (delta 0), pack-reused 74 \nCloning into '/content/US-Transporter-eval/pyssim'...\nremote: Enumerating objects: 238, done. \nremote: Total 238 (delta 0), reused 0 (delta 0), pack-reused 238 \nReceiving objects: 100% (238/238), 2.57 MiB | 20.75 MiB/s, done.\nResolving deltas: 100% (119/119), done.\nSubmodule path 'phasepack': checked out 'a7eaf26f4bd91b6cb7e3ac6cb93e9fd1c645e8de'\nSubmodule path 'pyssim': checked out 'ff9bd90c3eb7525013ad46babf66b7cc78391e89'\n/content/US-Transporter-eval\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 1)) (1.1.5)\nRequirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 2)) (1.9.0+cu102)\nRequirement already satisfied: torchtext in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 3)) (0.10.0)\nRequirement already satisfied: torchvision in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 4)) (0.10.0+cu102)\nCollecting pytorch_lightning\n Downloading pytorch_lightning-1.4.2-py3-none-any.whl (916 kB)\n\u001b[K |████████████████████████████████| 916 kB 5.6 MB/s \n\u001b[?25hCollecting pyfftw\n Downloading pyFFTW-0.12.0-cp37-cp37m-manylinux1_x86_64.whl (2.6 MB)\n\u001b[K |████████████████████████████████| 2.6 MB 37.5 MB/s \n\u001b[?25hCollecting av\n Downloading av-8.0.3-cp37-cp37m-manylinux2010_x86_64.whl (37.2 MB)\n\u001b[K |████████████████████████████████| 37.2 MB 30 kB/s \n\u001b[?25hRequirement already satisfied: scikit-image in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 8)) (0.16.2)\nRequirement already satisfied: numpy>=1.15.4 in /usr/local/lib/python3.7/dist-packages (from pandas->-r requirements.txt (line 1)) (1.19.5)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->-r requirements.txt (line 1)) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->-r requirements.txt (line 1)) (2.8.2)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->-r requirements.txt (line 1)) (1.15.0)\nRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch->-r requirements.txt (line 2)) (3.7.4.3)\nRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from torchtext->-r requirements.txt (line 3)) (4.62.0)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from torchtext->-r requirements.txt (line 3)) (2.23.0)\nRequirement already satisfied: pillow>=5.3.0 in /usr/local/lib/python3.7/dist-packages (from torchvision->-r requirements.txt (line 4)) (7.1.2)\nCollecting pyDeprecate==0.3.1\n Downloading pyDeprecate-0.3.1-py3-none-any.whl (10 kB)\nRequirement already satisfied: tensorboard>=2.2.0 in /usr/local/lib/python3.7/dist-packages (from pytorch_lightning->-r requirements.txt (line 5)) (2.6.0)\nCollecting future>=0.17.1\n Downloading future-0.18.2.tar.gz (829 kB)\n\u001b[K |████████████████████████████████| 829 kB 36.2 MB/s \n\u001b[?25hCollecting PyYAML>=5.1\n Downloading PyYAML-5.4.1-cp37-cp37m-manylinux1_x86_64.whl (636 kB)\n\u001b[K |████████████████████████████████| 636 kB 29.8 MB/s \n\u001b[?25hCollecting torchmetrics>=0.4.0\n Downloading torchmetrics-0.5.0-py3-none-any.whl (272 kB)\n\u001b[K |████████████████████████████████| 272 kB 42.1 MB/s \n\u001b[?25hRequirement already satisfied: packaging>=17.0 in /usr/local/lib/python3.7/dist-packages (from pytorch_lightning->-r requirements.txt (line 5)) (21.0)\nCollecting fsspec[http]!=2021.06.0,>=2021.05.0\n Downloading fsspec-2021.7.0-py3-none-any.whl (118 kB)\n\u001b[K |████████████████████████████████| 118 kB 54.9 MB/s \n\u001b[?25hCollecting aiohttp\n Downloading aiohttp-3.7.4.post0-cp37-cp37m-manylinux2014_x86_64.whl (1.3 MB)\n\u001b[K |████████████████████████████████| 1.3 MB 41.9 MB/s \n\u001b[?25hRequirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging>=17.0->pytorch_lightning->-r requirements.txt (line 5)) (2.4.7)\nRequirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (0.6.1)\nRequirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (1.34.0)\nRequirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (1.0.1)\nRequirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (0.12.0)\nRequirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (1.8.0)\nRequirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (1.39.0)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (3.3.4)\nRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (0.37.0)\nRequirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (57.4.0)\nRequirement already satisfied: protobuf>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (3.17.3)\nRequirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (0.4.5)\nRequirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (4.2.2)\nRequirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (0.2.8)\nRequirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (4.7.2)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (1.3.0)\nRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (4.6.4)\nRequirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (0.4.8)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->torchtext->-r requirements.txt (line 3)) (1.24.3)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->torchtext->-r requirements.txt (line 3)) (2.10)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->torchtext->-r requirements.txt (line 3)) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->torchtext->-r requirements.txt (line 3)) (2021.5.30)\nRequirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (3.1.1)\nRequirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image->-r requirements.txt (line 8)) (2.6.2)\nRequirement already satisfied: matplotlib!=3.0.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image->-r requirements.txt (line 8)) (3.2.2)\nRequirement already satisfied: scipy>=0.19.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image->-r requirements.txt (line 8)) (1.4.1)\nRequirement already satisfied: imageio>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image->-r requirements.txt (line 8)) (2.4.1)\nRequirement already satisfied: PyWavelets>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image->-r requirements.txt (line 8)) (1.1.1)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image->-r requirements.txt (line 8)) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image->-r requirements.txt (line 8)) (1.3.1)\nCollecting async-timeout<4.0,>=3.0\n Downloading async_timeout-3.0.1-py3-none-any.whl (8.2 kB)\nRequirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch_lightning->-r requirements.txt (line 5)) (21.2.0)\nCollecting multidict<7.0,>=4.5\n Downloading multidict-5.1.0-cp37-cp37m-manylinux2014_x86_64.whl (142 kB)\n\u001b[K |████████████████████████████████| 142 kB 72.6 MB/s \n\u001b[?25hCollecting yarl<2.0,>=1.0\n Downloading yarl-1.6.3-cp37-cp37m-manylinux2014_x86_64.whl (294 kB)\n\u001b[K |████████████████████████████████| 294 kB 55.5 MB/s \n\u001b[?25hRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard>=2.2.0->pytorch_lightning->-r requirements.txt (line 5)) (3.5.0)\nBuilding wheels for collected packages: future\n Building wheel for future (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for future: filename=future-0.18.2-py3-none-any.whl size=491070 sha256=fc43f45612bad39e7a8bd508a4aa065ce961b898062c6338f4824ddd323ae7a1\n Stored in directory: /root/.cache/pip/wheels/56/b0/fe/4410d17b32f1f0c3cf54cdfb2bc04d7b4b8f4ae377e2229ba0\nSuccessfully built future\nInstalling collected packages: multidict, yarl, async-timeout, fsspec, aiohttp, torchmetrics, PyYAML, pyDeprecate, future, pytorch-lightning, pyfftw, av\n Attempting uninstall: PyYAML\n Found existing installation: PyYAML 3.13\n Uninstalling PyYAML-3.13:\n Successfully uninstalled PyYAML-3.13\n Attempting uninstall: future\n Found existing installation: future 0.16.0\n Uninstalling future-0.16.0:\n Successfully uninstalled future-0.16.0\nSuccessfully installed PyYAML-5.4.1 aiohttp-3.7.4.post0 async-timeout-3.0.1 av-8.0.3 fsspec-2021.7.0 future-0.18.2 multidict-5.1.0 pyDeprecate-0.3.1 pyfftw-0.12.0 pytorch-lightning-1.4.2 torchmetrics-0.5.0 yarl-1.6.3\n" ], [ "#LUS weighted \n!gdown --id 1HBuTOm_5-p7VrpYWYYPoJp2epQvbyPl9\n\n#WUS weighted\n!gdown --id 1TMMNh6Vp07ejBDInsar5wXhljs9q7T57", "Downloading...\nFrom: https://drive.google.com/uc?id=1HBuTOm_5-p7VrpYWYYPoJp2epQvbyPl9\nTo: /content/US-Transporter-eval/ckpt_TPRv1_LUS_radonbpm_lr0.0001_LUS_nossim_dptdecay_samrate10_VER_HORIZ_weightedHlam_radonbpm_-epoch=59-val_loss=0.00012.ckpt\n11.0MB [00:00, 67.4MB/s]\nDownloading...\nFrom: https://drive.google.com/uc?id=1TMMNh6Vp07ejBDInsar5wXhljs9q7T57\nTo: /content/US-Transporter-eval/wrist_ckpt_TPRv1_lr0.0001_idxcsv_dptdecay_samrate=10_weightedHlam_15+3j_radon&bpm_-epoch=59-val_loss=0.00017.ckpt\n11.0MB [00:00, 66.9MB/s]\n" ], [ "#LUS sample data\n!gdown --id 11ZRVaMatUbYDI7IhK-Boq1yVWcKQHm8b\n\n#WUS sample data\n!gdown --id 1XTrF7wW8wxWLkNT6ZC9xHeh6uQl2rQTa\n", "Downloading...\nFrom: https://drive.google.com/uc?id=11ZRVaMatUbYDI7IhK-Boq1yVWcKQHm8b\nTo: /content/US-Transporter-eval/LUS.zip\n4.83MB [00:00, 15.4MB/s]\nDownloading...\nFrom: https://drive.google.com/uc?id=1XTrF7wW8wxWLkNT6ZC9xHeh6uQl2rQTa\nTo: /content/US-Transporter-eval/WUS.zip\n100% 705k/705k [00:00<00:00, 45.5MB/s]\n" ], [ "!unzip LUS.zip -d LUS/", "Archive: LUS.zip\n inflating: LUS/13089_2020_185_Fig3_HTML.jpg \n inflating: LUS/B-lines-and-lung-rockets-Typical-multiple-B-lines-This-figure-shows-the-7-features-of_Q640.jpg \n inflating: LUS/Vid18.mp4 \n" ], [ "!unzip WUS.zip -d WUS/", "Archive: WUS.zip\n inflating: WUS/011-wristDorSag-31L-5.mp4 \n" ], [ "!python eval_LUS.py --vid '/content/US-Transporter-eval/LUS/Vid18.mp4' --frame_no 50 --device 'cpu' --ckpt '/content/US-Transporter-eval/ckpt_TPRv1_LUS_radonbpm_lr0.0001_LUS_nossim_dptdecay_samrate10_VER_HORIZ_weightedHlam_radonbpm_-epoch=59-val_loss=0.00012.ckpt'", "importing ssim\nimported ssim\nimporting torchradon\nimported torchradon\nCheck 1\nNamespace(ckpt='/content/US-Transporter-eval/ckpt_TPRv1_LUS_radonbpm_lr0.0001_LUS_nossim_dptdecay_samrate10_VER_HORIZ_weightedHlam_radonbpm_-epoch=59-val_loss=0.00012.ckpt', device='cpu', frame_no=50, img='', vid='/content/US-Transporter-eval/LUS/Vid18.mp4')\nInitial Hlam weights are: Parameter containing:\ntensor([[[[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]]]], requires_grad=True)\ntorch.Size([3, 256, 256])\ntorch.Size([3, 256, 256])\ntorch.Size([3, 256, 256])\nreturned\nrecieved_vid_frame\noutput/frame50Vid18.jpg\n" ], [ "!python eval_LUS.py --img '/content/US-Transporter-eval/LUS/B-lines-and-lung-rockets-Typical-multiple-B-lines-This-figure-shows-the-7-features-of_Q640.jpg' --device 'cpu' --ckpt '/content/US-Transporter-eval/ckpt_TPRv1_LUS_radonbpm_lr0.0001_LUS_nossim_dptdecay_samrate10_VER_HORIZ_weightedHlam_radonbpm_-epoch=59-val_loss=0.00012.ckpt'", "importing ssim\nimported ssim\nimporting torchradon\nimported torchradon\nCheck 1\nNamespace(ckpt='/content/US-Transporter-eval/ckpt_TPRv1_LUS_radonbpm_lr0.0001_LUS_nossim_dptdecay_samrate10_VER_HORIZ_weightedHlam_radonbpm_-epoch=59-val_loss=0.00012.ckpt', device='cpu', frame_no=-1, img='/content/US-Transporter-eval/LUS/B-lines-and-lung-rockets-Typical-multiple-B-lines-This-figure-shows-the-7-features-of_Q640.jpg', vid='')\nInitial Hlam weights are: Parameter containing:\ntensor([[[[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]]]], requires_grad=True)\n(515, 515)\ntorch.Size([1, 256, 256])\ntorch.Size([3, 256, 256])\ntorch.Size([3, 256, 256])\nreturned\nrecieved_img\noutput/B-lines-and-lung-rockets-Typical-multiple-B-lines-This-figure-shows-the-7-features-of_Q640.jpg\n" ], [ "!python eval_LUS.py --img '/content/US-Transporter-eval/LUS/13089_2020_185_Fig3_HTML.jpg' --device 'cpu' --ckpt '/content/US-Transporter-eval/ckpt_TPRv1_LUS_radonbpm_lr0.0001_LUS_nossim_dptdecay_samrate10_VER_HORIZ_weightedHlam_radonbpm_-epoch=59-val_loss=0.00012.ckpt'", "importing ssim\nimported ssim\nimporting torchradon\nimported torchradon\nCheck 1\nNamespace(ckpt='/content/US-Transporter-eval/ckpt_TPRv1_LUS_radonbpm_lr0.0001_LUS_nossim_dptdecay_samrate10_VER_HORIZ_weightedHlam_radonbpm_-epoch=59-val_loss=0.00012.ckpt', device='cpu', frame_no=-1, img='/content/US-Transporter-eval/LUS/13089_2020_185_Fig3_HTML.jpg', vid='')\nInitial Hlam weights are: Parameter containing:\ntensor([[[[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]]]], requires_grad=True)\n(604, 685, 3)\ntorch.Size([1, 256, 256])\ntorch.Size([3, 256, 256])\ntorch.Size([3, 256, 256])\nreturned\nrecieved_img\noutput/13089_2020_185_Fig3_HTML.jpg\n" ], [ "!python eval_WUS.py --vid '/content/US-Transporter-eval/WUS/011-wristDorSag-31L-5.mp4' --frame_no 60 --device 'cpu' --ckpt '/content/US-Transporter-eval/ckpt_TPRv1_LUS_radonbpm_lr0.0001_LUS_nossim_dptdecay_samrate10_VER_HORIZ_weightedHlam_radonbpm_-epoch=59-val_loss=0.00012.ckpt'", "importing ssim\nimported ssim\nimporting torchradon\nimported torchradon\nCheck 1\nNamespace(ckpt='/content/US-Transporter-eval/ckpt_TPRv1_LUS_radonbpm_lr0.0001_LUS_nossim_dptdecay_samrate10_VER_HORIZ_weightedHlam_radonbpm_-epoch=59-val_loss=0.00012.ckpt', device='cpu', frame_no=60, img='', vid='/content/US-Transporter-eval/WUS/011-wristDorSag-31L-5.mp4')\nInitial Hlam weights are: Parameter containing:\ntensor([[[[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]],\n\n [[0.1000]]]], requires_grad=True)\ntorch.Size([3, 256, 256])\ntorch.Size([3, 256, 256])\ntorch.Size([3, 256, 256])\nreturned\nrecieved_vid_frame\noutput/frame60011-wristDorSag-31L-5.jpg\n" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdf5b99a2c0546f8ec6d45bcba2a08efa42524d
218,101
ipynb
Jupyter Notebook
simple_indexes/04_indexes/2.make_search_index.ipynb
B-tum/uncertainty_index
6ff21b31fa2bd74c5fcebee69b814884f2f23372
[ "MIT" ]
1
2021-01-12T14:24:26.000Z
2021-01-12T14:24:26.000Z
simple_indexes/04_indexes/2.make_search_index.ipynb
B-tum/uncertainty_index
6ff21b31fa2bd74c5fcebee69b814884f2f23372
[ "MIT" ]
null
null
null
simple_indexes/04_indexes/2.make_search_index.ipynb
B-tum/uncertainty_index
6ff21b31fa2bd74c5fcebee69b814884f2f23372
[ "MIT" ]
1
2021-01-21T11:36:15.000Z
2021-01-21T11:36:15.000Z
473.104121
99,284
0.929922
[ [ [ "# Индекс поиска", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport datetime\n\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport matplotlib.patches as mpatches\nmatplotlib.style.use('ggplot')\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "### Описание:\n\nИндекс строится на основе кризисных дескрипторов, взятых из [статьи Столбова.](https://yadi.sk/i/T24TXCw2Jzy8oQ) Автор посмотрел, что активнее всего гуглилось по категории \"Финансы и страхование\" в пик кризиса 2008 года. Он отобрал эти дескрипторы и разбавил их ещё несколькими терминами. \n\n### Технические особенности: \n\nСкачиваем поисковые запросы по всем дескрипторам Столбова. Можно и руками, но для больших объёмов поисковой скачки, есть [рекурсивный парсер.](https://nbviewer.jupyter.org/github/FUlyankin/Parsers/blob/master/Parsers%20/google_trends_selenium_parser.ipynb) Индекс будем строить двумя способами:\n\n- взвесив все слова с коэффицентами \n\n$$\nw_i = \\frac{\\sum_{j} r_{ij}}{\\sum_{i,j} r_{ij}}\n$$\n\n- взяв одну из компонент PCA-разложения. Брать будем не первую компоненту, а ту компоненту, которая улавливает в себе \"пики\". В нашем случае это вторая компонента.", "_____no_output_____" ] ], [ [ "!ls ../01_Google_trends_parser", "\u001b[1m\u001b[32mchromedriver\u001b[m\u001b[m krizis_poisk_month.tsv\r\ngoogle_selenium_parser.ipynb krizis_poisk_odinar_month.tsv\r\n" ], [ "path = '../01_Google_trends_parser/krizis_poisk_odinar_month.tsv'\n\ndf_poisk = pd.read_csv(path, sep='\\t')\ndf_poisk.set_index('Месяц', inplace=True)\nprint(df_poisk.shape)\ndf_poisk.head()", "(197, 15)\n" ], [ "def index_make(df_term):\n corr_matrix = df_term.corr()\n w = np.array(corr_matrix.sum()/corr_matrix.sum().sum())\n print(w)\n index = (np.array(df_term).T*w.reshape(len(w),1)).sum(axis = 0)\n mx = index.max()\n mn = index.min()\n return 100*(index - mn)/(mx - mn)\n\ndef min_max_scaler(df, col):\n mx = df[col].max()\n mn = df[col].min()\n df[col] = 100*(df[col] - mn)/(mx - mn)\n pass\n\nindex_poisk = index_make(df_poisk)", "[0.11159857 0.09763166 0.09528628 0.08221439 0.09049123 0.11958343\n 0.06802833 0.06472116 0.03397004 0.0450251 0.00104759 0.00602192\n 0.03392008 0.03049101 0.11996919]\n" ], [ "df_pi = pd.DataFrame() \ndf_pi['fielddate'] = df_poisk.index", "_____no_output_____" ], [ "df_pi['poiskInd_ind_corr'] = index_poisk\ndf_pi.set_index('fielddate').plot(legend=True, figsize=(12,6));", "_____no_output_____" ], [ "from sklearn.decomposition import PCA\nmodel_pca = PCA(n_components= 15)\nmodel_pca.fit(df_poisk)\ndf_pi_pca = model_pca.transform(df_poisk)\n\nplt.plot(model_pca.explained_variance_, label='Component variances')\nplt.xlabel('n components')\nplt.ylabel('variance')\nplt.legend(loc='upper right');", "_____no_output_____" ], [ "df_pi['poiskInd_ind_pca'] = list(df_pi_pca[:,1])\nmin_max_scaler(df_pi, 'poiskInd_ind_pca')\n\ndf_pi.plot(legend=True, figsize=(12,6));", "_____no_output_____" ] ], [ [ "--------", "_____no_output_____" ] ], [ [ "df_pi.to_csv('../Индексы/data_simple_index_v2/poisk_krizis_index_month.tsv', sep=\"\\t\", index=None)", "_____no_output_____" ] ], [ [ "-------------", "_____no_output_____" ], [ " ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cbdf68d83e9b067941bdff19cc3f9fbd14d1e75d
14,137
ipynb
Jupyter Notebook
model_notebooks/VSV/model.ipynb
indralab/adeft_indra
6f039b58b6dea5eefa529cf15afaffff2d485513
[ "BSD-2-Clause" ]
null
null
null
model_notebooks/VSV/model.ipynb
indralab/adeft_indra
6f039b58b6dea5eefa529cf15afaffff2d485513
[ "BSD-2-Clause" ]
null
null
null
model_notebooks/VSV/model.ipynb
indralab/adeft_indra
6f039b58b6dea5eefa529cf15afaffff2d485513
[ "BSD-2-Clause" ]
null
null
null
26.927619
156
0.539223
[ [ [ "import os\nimport json\nimport pickle\nimport random\nfrom collections import defaultdict, Counter\n\nfrom indra.literature.adeft_tools import universal_extract_text\nfrom indra.databases.hgnc_client import get_hgnc_name, get_hgnc_id\n\nfrom adeft.discover import AdeftMiner\nfrom adeft.gui import ground_with_gui\nfrom adeft.modeling.label import AdeftLabeler\nfrom adeft.modeling.classify import AdeftClassifier\nfrom adeft.disambiguate import AdeftDisambiguator\n\n\nfrom adeft_indra.ground.ground import AdeftGrounder\nfrom adeft_indra.model_building.s3 import model_to_s3\nfrom adeft_indra.model_building.escape import escape_filename\nfrom adeft_indra.db.content import get_pmids_for_agent_text, get_pmids_for_entity, \\\n get_plaintexts_for_pmids", "_____no_output_____" ], [ "adeft_grounder = AdeftGrounder()", "_____no_output_____" ], [ "shortforms = ['VSV']\nmodel_name = ':'.join(sorted(escape_filename(shortform) for shortform in shortforms))\nresults_path = os.path.abspath(os.path.join('../..', 'results', model_name))", "_____no_output_____" ], [ "miners = dict()\nall_texts = {}\nfor shortform in shortforms:\n pmids = get_pmids_for_agent_text(shortform)\n if len(pmids) > 10000:\n pmids = random.choices(pmids, k=10000)\n text_dict = get_plaintexts_for_pmids(pmids, contains=shortforms)\n text_dict = {pmid: text for pmid, text in text_dict.items() if len(text) > 5}\n miners[shortform] = AdeftMiner(shortform)\n miners[shortform].process_texts(text_dict.values())\n all_texts.update(text_dict)\n\nlongform_dict = {}\nfor shortform in shortforms:\n longforms = miners[shortform].get_longforms()\n longforms = [(longform, count, score) for longform, count, score in longforms\n if count*score > 2]\n longform_dict[shortform] = longforms\n \ncombined_longforms = Counter()\nfor longform_rows in longform_dict.values():\n combined_longforms.update({longform: count for longform, count, score\n in longform_rows})\ngrounding_map = {}\nnames = {}\nfor longform in combined_longforms:\n groundings = adeft_grounder.ground(longform)\n if groundings:\n grounding = groundings[0]['grounding']\n grounding_map[longform] = grounding\n names[grounding] = groundings[0]['name']\nlongforms, counts = zip(*combined_longforms.most_common())\npos_labels = []", "_____no_output_____" ], [ "list(zip(longforms, counts))", "_____no_output_____" ], [ "grounding_map, names, pos_labels = ground_with_gui(longforms, counts, \n grounding_map=grounding_map,\n names=names, pos_labels=pos_labels, no_browser=True, port=8890)", "_____no_output_____" ], [ "result = [grounding_map, names, pos_labels]", "_____no_output_____" ], [ "result", "_____no_output_____" ], [ "grounding_map, names, pos_labels = [{'vesicular stomatis virus': 'Taxonomy:11276',\n 'vesicular stomatitis virus': 'Taxonomy:11276'},\n {'Taxonomy:11276': 'Vesicular stomatitis virus'},\n ['Taxonomy:11276']]", "_____no_output_____" ], [ "excluded_longforms = []", "_____no_output_____" ], [ "grounding_dict = {shortform: {longform: grounding_map[longform] \n for longform, _, _ in longforms if longform in grounding_map\n and longform not in excluded_longforms}\n for shortform, longforms in longform_dict.items()}\nresult = [grounding_dict, names, pos_labels]\n\nif not os.path.exists(results_path):\n os.mkdir(results_path)\nwith open(os.path.join(results_path, f'{model_name}_preliminary_grounding_info.json'), 'w') as f:\n json.dump(result, f)", "_____no_output_____" ], [ "additional_entities = {'HGNC:5413': 'IFITM2'}", "_____no_output_____" ], [ "unambiguous_agent_texts = {}", "_____no_output_____" ], [ "labeler = AdeftLabeler(grounding_dict)\ncorpus = labeler.build_from_texts((text, pmid) for pmid, text in all_texts.items())\nagent_text_pmid_map = defaultdict(list)\nfor text, label, id_ in corpus:\n agent_text_pmid_map[label].append(id_)\n\nentity_pmid_map = {entity: set(get_pmids_for_entity(*entity.split(':', maxsplit=1),\n major_topic=True))for entity in additional_entities}", "_____no_output_____" ], [ "intersection1 = []\nfor entity1, pmids1 in entity_pmid_map.items():\n for entity2, pmids2 in entity_pmid_map.items():\n intersection1.append((entity1, entity2, len(pmids1 & pmids2)))", "_____no_output_____" ], [ "intersection2 = []\nfor entity1, pmids1 in agent_text_pmid_map.items():\n for entity2, pmids2 in entity_pmid_map.items():\n intersection2.append((entity1, entity2, len(set(pmids1) & pmids2)))", "_____no_output_____" ], [ "intersection1", "_____no_output_____" ], [ "intersection2", "_____no_output_____" ], [ "all_used_pmids = set()\nfor entity, agent_texts in unambiguous_agent_texts.items():\n used_pmids = set()\n for agent_text in agent_texts:\n pmids = set(get_pmids_for_agent_text(agent_text))\n new_pmids = list(pmids - all_texts.keys() - used_pmids)\n text_dict = get_plaintexts_for_pmids(new_pmids, contains=agent_texts)\n corpus.extend([(text, entity, pmid) for pmid, text in text_dict.items()])\n used_pmids.update(new_pmids)\n all_used_pmids.update(used_pmids)\n \nfor entity, pmids in entity_pmid_map.items():\n new_pmids = list(set(pmids) - all_texts.keys() - all_used_pmids)\n if len(new_pmids) > 10000:\n new_pmids = random.choices(new_pmids, k=10000)\n text_dict = get_plaintexts_for_pmids(new_pmids)\n corpus.extend([(text, entity, pmid) for pmid, text in text_dict.items()])", "_____no_output_____" ], [ "names.update(additional_entities)\npos_labels.extend(additional_entities.keys())", "_____no_output_____" ], [ "%%capture\n\nclassifier = AdeftClassifier(shortforms, pos_labels=pos_labels, random_state=1729)\nparam_grid = {'C': [100.0], 'max_features': [10000]}\ntexts, labels, pmids = zip(*corpus)\nclassifier.cv(texts, labels, param_grid, cv=5, n_jobs=5)", "INFO: [2020-10-02 02:06:22] /adeft/PythonRepos/adeft/adeft/modeling/classify.py - Beginning grid search in parameter space:\n{'C': [100.0], 'max_features': [10000]}\nINFO: [2020-10-02 02:06:32] /adeft/PythonRepos/adeft/adeft/modeling/classify.py - Best f1 score of 0.9448310828844158 found for parameter values:\n{'logit__C': 100.0, 'tfidf__max_features': 10000}\n" ], [ "classifier.stats", "_____no_output_____" ], [ "disamb = AdeftDisambiguator(classifier, grounding_dict, names)", "_____no_output_____" ], [ "disamb.dump(model_name, results_path)", "_____no_output_____" ], [ "print(disamb.info())", "Disambiguation model for VSV\n\nProduces the disambiguations:\n\tIFITM2*\tHGNC:5413\n\tVesicular stomatitis virus*\tTaxonomy:11276\n\nClass level metrics:\n--------------------\nGrounding \tCount\tF1 \nVesicular stomatitis virus*\t322\t0.97272\n IFITM2*\t 41\t0.72315\n\nWeighted Metrics:\n-----------------\n\tF1 score:\t0.94483\n\tPrecision:\t0.94646\n\tRecall:\t\t0.95046\n\n* Positive labels\nSee Docstring for explanation\n\n" ], [ "preds = disamb.disambiguate(all_texts.values())", "_____no_output_____" ], [ "a = [text for text, pred in zip(all_texts.values(), preds) if pred[0].startswith('HGNC')]", "_____no_output_____" ], [ "a", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdf73ac0ec1143dbdf421c93b3adb90dafaa505
5,876
ipynb
Jupyter Notebook
course_lessons/session1_introduction.ipynb
leodias-datascience/course-keras_tensorflow_python
ec96b30ed23b19bf01504832db4fd72eabf7489a
[ "MIT" ]
null
null
null
course_lessons/session1_introduction.ipynb
leodias-datascience/course-keras_tensorflow_python
ec96b30ed23b19bf01504832db4fd72eabf7489a
[ "MIT" ]
1
2021-11-03T22:27:29.000Z
2021-11-03T22:27:29.000Z
course_lessons/session1_introduction.ipynb
leodias-datascience/course-keras_tensorflow_python
ec96b30ed23b19bf01504832db4fd72eabf7489a
[ "MIT" ]
null
null
null
36.271605
441
0.633594
[ [ [ "# 1. Deep learning: Pre-requisites\n\n#### Understanding gradient descent, autodiff, and softmax\n", "_____no_output_____" ], [ "### Gradiant Descent\n\nOptimization technique for finding best parameters (Model parameters) for a giving problem - Cost function to reduce the error, for example, as the image. The neural network is trained with gradient descent to find the best solution. There are room for improvement, like applying \"momentum\" to the descent - as it descends, it gains speed and as it reaches a given value, it will reduce its speed so the minimum is reached faster.\n\nThere are the local minimum problems, but they have solutions. However, in practice, local minimum is not a problem since it rarely happens in real world problems.\n\n<img src=\"../course_imgs/gradientdescent.png\" alt=\"Gradient descent\" width=\"200\"/>", "_____no_output_____" ], [ "### Autodiff\n\nTo apply gradient descent, you need to know the gradient from the cost function - the slope of the curve. Gradient is obtained from partial derivatives and calculus are hard and inefficient for computers. \n\nSo **autodiff** is a technique to make things better. Specifically, **reverse-mode autodiff**. It still is a calculus trick (complicated but works) and <u>Tensorflow</u> uses it. Optimized for many inputs + few outputs, computing all partial derivatives by traversing your graph in the number of outputs that you have +1. This works well in neural networks because neurons usually have many inputs, but just one output.", "_____no_output_____" ], [ "### Softmax\n\nThe results of a NN are weights and they are converted into a probability by the NN. This probability represents the chance of each sample to belong to a class. The class with the closest probability is the answer. This could be represented like the implementation of a sigmoid function.\n\n![Sigmoid softmax](../course_imgs/sigmoid.png \"Sigmoid\")", "_____no_output_____" ], [ "# 2. Introducing Artificial Neural Networks", "_____no_output_____" ], [ "### Biological inspiration\n\nNeurons are connected to each other via axons. Neurons communicate with others they are connected to via electrical signals and determined inputs to each neuron will activate it. \n- It is simple in an individual level, but layers of billions of neurons connected to each others, with thousands of connections yields a mind. \n\n![neuron](../course_imgs/neuron.jpg \"Neuron\")", "_____no_output_____" ], [ "### Cortical columns\n\nNeurons seem to be arranged into stacks/columns that process information in parallel. \"Mini-columns\" of around 100 neurons are organized into larger \"hyper-columns\", and there are around 100 million mini-columns in our brain. This is similar to how a GPU works.\n\n![Cortical columns](../course_imgs/cortical.jpg \"Cortical columns\")", "_____no_output_____" ], [ "### First artificial neurons\n\nBack to 1943 - Logical expressions creation: AND, OR and NOT. Two inputs may define if the output is on or off!\n\n<img src=\"../course_imgs/artificialneuron.png\" alt=\"Artificial Neuron\" width=\"200\"/>", "_____no_output_____" ], [ "### Linear Threshold Unit (LTU)\n\nBack to 1957: Add weights into inputs and output is given by a step function.\n\n<img src=\"../course_imgs/ltu.png\" alt=\"LTU\" width=\"500\"/>", "_____no_output_____" ], [ "### The perceptron\n\nA layer of LTU. A perceptron can learn by reinforcing weights that lead to correct behavior during training. There is also de bias neuron to make things work.\n\n\n<img src=\"../course_imgs/perceptron.png\" alt=\"Perceptron\" width=\"200\"/>", "_____no_output_____" ], [ "### Multi-Layer perceptrons\n\nAddition of hidden layers. This is a Deep Neural Network, and training it is trickier. It began with a simple concept, and it all stacked...now we have a lot of neurons connected to each other and that is very complex...from a simple concept.\n\n<img src=\"../course_imgs/multilayerperceptrons.PNG\" alt=\"Multi-Layer Perceptron\" width=\"200\"/>", "_____no_output_____" ], [ "### A Modern Deep Neural Network\n\nReplace the step function with other type of function, apply softmax to the output, and train the network using gradient descent other method.\n<img src=\"../course_imgs/deepneuralnet.PNG \" alt=\"Modern Deep Neural Network\" width=\"200\"/>", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cbdf7cafc12420ca06e9796ea98b3d49eb3af508
250,536
ipynb
Jupyter Notebook
TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb
AndresHdzJmz/SPF-2021-I
2e2b25b0bfb9e3716ceea4253741a6c364f2a579
[ "MIT" ]
null
null
null
TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb
AndresHdzJmz/SPF-2021-I
2e2b25b0bfb9e3716ceea4253741a6c364f2a579
[ "MIT" ]
null
null
null
TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb
AndresHdzJmz/SPF-2021-I
2e2b25b0bfb9e3716ceea4253741a6c364f2a579
[ "MIT" ]
null
null
null
259.892116
28,136
0.919018
[ [ [ "# Generación de observaciones aleatorias a partir de una distribución de probabilidad", "_____no_output_____" ], [ "La primera etapa de la simulación es la **generación de números aleatorios**. Los números aleatorios sirven como el bloque de construcción de la simulación. La segunda etapa de la simulación es la **generación de variables aleatorias basadas en números aleatorios**. Esto incluye generar variables aleatorias <font color ='red'> discretas y continuas de distribuciones conocidas </font>. En esta clase, estudiaremos técnicas para generar variables aleatorias.\n\nIntentaremos dar respuesta a el siguiente interrogante:\n>Dada una secuencia de números aleatorios, ¿cómo se puede generar una secuencia de observaciones aleatorias a partir de una distribución de probabilidad dada? Varios enfoques diferentes están disponibles, dependiendo de la naturaleza de la distribución", "_____no_output_____" ], [ "Considerando la generación de números alestorios estudiados previamente, asumiremos que tenemos disponble una secuencia $U_1,U_2,\\cdots$ variables aleatorias independientes, para las cuales se satisface que:\n$$\nP(U_i\\leq u) = \\begin{cases}0,& u<0\\\\ u,&0\\leq u \\leq 1\\\\ 1,& u>1 \\end{cases}\n$$\nes decir, cada variable se distribuye uniformemente entre 0 y 1.\n\n**Recordar:** En clases pasadas, observamos como transformar un número p-seudoaletorio distribuido uniformemte entre 0 y 1, en una distribución normalmente distribuida con media $(\\mu,\\sigma^2)\\longrightarrow$ <font color='red'> [Médoto de Box Muller](http://www.lmpt.univ-tours.fr/~nicolis/Licence_NEW/08-09/boxmuller.pdf) </font> como un caso particular.\n\nEn esta sesión, se presentarán dos de los técnicas más ampliamente utilizados para generar variables aletorias, a partir de una distribución de probabilidad.", "_____no_output_____" ], [ "## 1. Método de la transformada inversa", "_____no_output_____" ], [ "Este método puede ser usado en ocasiones para generar una observación aleatoria. Tomando $X$ como la variable aletoria involucrada, denotaremos la función de distribución de probabilidad acumulada por\n$$F(x)=P(X\\leq x),\\quad \\forall x$$\n<font color ='blue'> Dibujar graficamente esta situación en el tablero</font>\n\nEl método de la transformada inversa establece\n$$X = F^{-1}(U),\\quad U \\sim \\text{Uniforme[0,1]}$$\ndonde $F^{-1}$ es la transformada inversa de $F$.\n\nRecordar que $F^{-1}$ está bien definida si $F$ es estrictamente creciente, de otro modo necesitamos una regla para solucionar los casos donde esta situación no se satisface. Por ejemplo, podríamos tomar\n$$F^{-1}(u)=\\inf\\{x:F(x)\\geq u\\}$$ \nSi hay muchos valores de $x$ para los cuales $F(x)=u$, esta regla escoje el valor mas pequeño. Observar esta situación en el siguiente ejemplo:\n\n![imagen.png](attachment:imagen.png)\nObserve que en el intervalo $(a,b]$ si $X$ tiene distribución $F$, entonces\n$$P(a<X\\leq b)=F(b)-F(a)=0\\longrightarrow \\text{secciones planas}$$\n\nPor lo tanto si $F$ tienen una densidad continua, entonces $F$ es estrictamente creciente y su inversa está bien definida. \n", "_____no_output_____" ], [ "Ahora observemos cuando se tienen las siguientes funciones:\n![imagen.png](attachment:imagen.png)\nObservemos que sucede en $x_0$\n$$\\lim_{x \\to x_0^-} F(x)\\equiv F(x^-)<F(x^+)\\equiv \\lim_{x\\to x_0^+}F(x)$$\nBajo esta distribución el resultado $x_0$ tiene probabilidad $F(x^+)-F(x^-)$. Por otro lado todos los valores de $u$ entre $[u_2,u_1]$ serán mapeados a $x_0$.\n\nLos siguientes ejemplos mostrarán una implementación directa de este método.", "_____no_output_____" ], [ "### Ejemplo 1: Distribución exponencial\nLa distribución exponencial con media $\\theta$ tiene distribución \n$$F(x)=1-e^{-x/\\theta}, \\quad x\\geq 0$$\n> Distrubución exponencial python: https://en.wikipedia.org/wiki/Exponential_distribution", "_____no_output_____" ], [ ">### <font color= blue> Mostrar en el tablero la demostración ", "_____no_output_____" ] ], [ [ "# Importamos las librerías principales\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd", "_____no_output_____" ], [ "# Creamos la función que crea muestras distribuidas exponencialmente\ndef D_exponential(theta,N):\n return -np.log(np.random.random(N))*theta", "_____no_output_____" ], [ "# Media\ntheta = 4 \n# Número de muestras\nN = 10**6 \n\n# creamos muestras exponenciales con la función que esta en numpy\nx = np.random.exponential(theta,N) \n\n# creamos muestras exponenciales con la función creada\nx2 = D_exponential(theta,N)\n\n# Graficamos el histograma para x\nplt.hist(x,100,density=True)\nplt.xlabel('valores aleatorios')\nplt.ylabel('probabilidad')\nplt.title('histograma función de numpy')\nprint(np.mean(x))\nplt.show()", "4.003122845438224\n" ], [ "plt.hist(x2,100,density=True)\nplt.xlabel('valores aleatorios')\nplt.ylabel('probabilidad')\nplt.title('histograma función creada')\nprint(np.mean(x2))\nplt.show()", "3.9980705773537206\n" ] ], [ [ "### Ejemplo 2\nSe sabe que la distribución Erlang resulta de la suma de $k$ variables distribuidas exponencialmente cada una con media $\\theta$, y por lo tanto esta variable resultante tiene distribución Erlang de tamaño $k$ y media $theta$.\n\n> Enlace distribución Erlang: https://en.wikipedia.org/wiki/Erlang_distribution", "_____no_output_____" ] ], [ [ "N = 10**4\n# Variables exponenciales\nx1 = np.random.exponential(4,N)\nx2 = np.random.exponential(4,N)\nx3 = np.random.exponential(4,N)\nx4 = np.random.exponential(4,N)\nx5 = np.random.exponential(4,N)\n\n# Variables erlang\ne0 = x1\ne1 = (x1+x2)\ne2 = (x3+x4+x5)\ne3 = (x1+x2+x3+x4)\ne4 = x1+x2+x3+x4+x5\nplt.hist(e0,100,density=True,label='1 exponencial')\nplt.hist(e1,100,density=True,label='suma de 2 exp')\nplt.hist(e2,100,density=True,label='suma de 3 exp')\nplt.hist(e3,100,density=True,label='suma de 4 exp')\nplt.hist(e4,100,density=True,label='suma de 5 exp')\nplt.legend()\n\nplt.show()", "_____no_output_____" ] ], [ [ ">### <font color= blue> Mostrar en el tablero la demostración ", "_____no_output_____" ] ], [ [ "N, k = 10, 2\ntheta = 4\nU = np.random.rand(N, k)\n-theta * np.log(np.product(U, axis=1))\n", "_____no_output_____" ], [ "# Función para crear variables aleatorias Erlang\ndef D_erlang(theta:'media distribución',k,N):\n # Matriz de variables aleatorias de dim N*k mejora la velocidad del algoritmo\n U = np.random.rand(N, k)\n y = -theta * np.log(np.product(U, axis=1))\n return y", "_____no_output_____" ], [ "# Prueba de la función creada\n# Cantidad de muestras\nN = 10**4\n# Parámetros de la distrubución erlang\nks = [1,2,3,4,5]\ntheta = 4\n\ny = [D_erlang(theta, ks[i], N) for i in range(len(ks))]\n\n[plt.hist(y[i], bins=50, density=True, label=f'suma de {ks[i]} exp') \n for i in range(len(ks))]\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "### Función de densidad variables Erlang\n\n$$p(x)=x^{k-1}\\frac{e^{-x/\\theta}}{\\theta^k\\Gamma(k)}\\equiv x^{k-1}\\frac{e^{-x/\\theta}}{\\theta^k(k-1)!}$$", "_____no_output_____" ] ], [ [ "#Librería que tiene la función gamma y factorial \n# Para mostrar la equivalencia entre el factorial y la función gamma\nimport scipy.special as sps \nfrom math import factorial as fac\nk = 4\ntheta = 4\n\nx = np.arange(0,60,0.01)\nplt.show() \n\n# Comparación de la función gamma y la función factorial \ny= x**(k-1)*(np.exp(-x/theta) /(sps.gamma(k)*theta**k))\ny2 = x**(k-1)*(np.exp(-x/theta) /(fac(k-1)*theta**k))\nplt.plot(x,y,'r')\nplt.plot(x,y2,'b--')\n# plt.show()\n\n# Creo variables aleatorias erlang y obtengo su histograma en la misma gráfica anterior\nN = 10**4\nr1 = D_erlang(theta,k,N)\nplt.hist(r1,bins=50,density=True)\nplt.show()", "_____no_output_____" ] ], [ [ "Para mejorar la eficiencia, creemos una función que grafique la misma gráfica anterior pero este caso que le podamos variar los parámetros `k` y $\\theta$ de la distribución", "_____no_output_____" ] ], [ [ "# Función que grafica subplots para cada señal de distribución Erlang\ndef histograma_erlang(signal:'señal que desea graficar',\n k:'Parámetro de la función Erlang'):\n\n plt.figure(figsize=(8,3))\n count, x, _ = plt.hist(signal,100,density=True,label='k=%d'%k)\n y = x**(k-1)*(np.exp(-x/theta) /(sps.gamma(k)*theta**k))\n plt.plot(x, y, linewidth=2,color='k')\n plt.ylabel('Probabilidad')\n plt.xlabel('Muestras')\n plt.legend()\n plt.show()", "_____no_output_____" ] ], [ [ "Con la función anterior, graficar la función de distribución de una Erlang con parámetros $\\theta = 4$ y `Ks = [1,8,3,6] `", "_____no_output_____" ] ], [ [ "theta = 4 # media \nN = 10**5 # Número de muestras\nKs = [1,8,3,6] # Diferentes valores de k para la distribución Erlang\n\n# Obtengo\na_erlang = list(map(lambda k: D_erlang(theta, k, N), Ks))\n[histograma_erlang(erlang_i, k) for erlang_i, k in zip(a_erlang, Ks)]", "_____no_output_____" ] ], [ [ "### Ejemplo 4\nDistribución de Rayleigh\n$$F(x)=1-e^{-2x(x-b)},\\quad x\\geq b $$", "_____no_output_____" ], [ "> Fuente: https://en.wikipedia.org/wiki/Rayleigh_distribution", "_____no_output_____" ] ], [ [ "# Función del ejemplo 4\ndef D_rayleigh(b,N):\n return (b/2)+np.sqrt(b**2-2*np.log(np.random.rand(N)))/2\n\nnp.random.rayleigh?\n\n# Función de Raylegh que contiene numpy\ndef D_rayleigh2(sigma,N):\n return np.sqrt(-2*sigma**2*np.log(np.random.rand(N)))", "Object `np.random.rayleigh` not found.\n" ], [ "b = 0.5; N =10**6;sigma = 2\nr = D_rayleigh(b,N) # Función del ejemplo \nr2 = np.random.rayleigh(sigma,N) # Función que contiene python\nr3 = D_rayleigh2(sigma,N) # Función creada de acuerdo a la función de python\n\nplt.figure(1,figsize=(10,8))\nplt.subplot(311)\nplt.hist(r3,100,density=True)\nplt.xlabel('valores aleatorios')\nplt.ylabel('probabilidad')\nplt.title('histograma función D_rayleigh2')\n\nplt.subplot(312)\nplt.hist(r2,100,density=True)\nplt.xlabel('valores aleatorios')\nplt.ylabel('probabilidad')\nplt.title('histograma función numpy')\n\nplt.subplot(313)\nplt.hist(r,100,density=True)\nplt.xlabel('valores aleatorios')\nplt.ylabel('probabilidad')\nplt.title('histograma función D_rayleigh')\nplt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95,\n hspace=.5,wspace=0)\nplt.show()", "_____no_output_____" ] ], [ [ "> ### <font color='red'> [Médoto de Box Muller](http://www.lmpt.univ-tours.fr/~nicolis/Licence_NEW/08-09/boxmuller.pdf) </font> $\\longrightarrow$ Aplicación del método de la transformada inversa", "_____no_output_____" ], [ "## Distribuciones discretas\n\nPara una variable dicreta, evaluar $F^{-1}$ se reduce a buscar en una tabla. Considere por ejemplo una variable aleatoria discreta, cuyos posibles valores son $c_1<c_2<\\cdots<c_n$. Tome $p_i$ la probabilidad alcanzada por $c_i$, $i=1,\\cdots,n$ y tome $q_0=0$, en donde $q_i$ representa las **probabilidades acumuladas asociadas con $c_i$** y está definido como:\n$$q_i=\\sum_{j=1}^{i}p_j,\\quad i=1,\\cdots,n \\longrightarrow q_i=F(c_i)$$\nEntonces, para tomar muestras de esta distribución se deben de realizar los siguientes pasos:\n 1. Generar un número uniforme $U$ entre (0,1).\n 2. Encontrar $k\\in\\{1,\\cdots,n\\}$ tal que $q_{k-1}<U\\leq q_k$\n 3. Tomar $X=c_k$.", "_____no_output_____" ], [ "### Ejemplo numérico", "_____no_output_____" ] ], [ [ "val = [1,2,3,4,5]\np_ocur = [.1,.2,.4,.2,.1]\np_acum = np.cumsum(p_ocur)\n\ndf = pd.DataFrame(index=val,columns=['Probabilidades','Probabilidad acumulada'], dtype='float')\ndf.index.name = \"Valores (índices)\"\ndf.loc[val,'Probabilidades'] = p_ocur\ndf.loc[val,'Probabilidad acumulada'] = p_acum\ndf", "_____no_output_____" ] ], [ [ "### Ilustración del método", "_____no_output_____" ] ], [ [ "u = .01\nsum([1 for p in p_acum if p < u])", "_____no_output_____" ], [ "indices = val\nN = 10\nU =np.random.rand(N)\n# Diccionario de valores aleatorios\nrand2reales = {i: idx for i, idx in enumerate(indices)}\n# Series de los valores aletorios generados\ny = pd.Series([sum([1 for p in p_acum if p < ui]) for ui in U]).map(rand2reales)\ny", "_____no_output_____" ], [ "def Gen_distr_discreta(p_acum: 'P.Acumulada de la distribución a generar',\n indices: 'valores reales a generar aleatoriamente',\n N: 'cantidad de números aleatorios a generar'):\n \n U =np.random.rand(N)\n # Diccionario de valores aleatorios\n rand2reales = {i: idx for i, idx in enumerate(indices)}\n\n # Series de los valores aletorios\n y = pd.Series([sum([1 for p in p_acum if p < ui]) for ui in U]).map(rand2reales)\n\n return y", "_____no_output_____" ] ], [ [ "# Lo que no se debe de hacer, cuando queremos graficar el histograma de una distribución discreta", "_____no_output_____" ] ], [ [ "N = 10**4\nu =np.random.rand(N)\nv = Gen_distr_discreta(p_acum, val, N)\nplt.hist(v,bins = len(set(val)))\nplt.show()", "_____no_output_____" ], [ "N = 10**4\nv = Gen_distr_discreta(p_acum, val, N)\n\n# Método 1 (Correcto)\ny, bins = np.histogram(v,bins=len(set(val)))\nplt.bar(val, y)\nplt.title('METODO CORRECTO')\nplt.xlabel('valores (índices)')\nplt.ylabel('frecuencias')\nplt.show()\n \n# Método 2 (incorrecto)\ny,x,_ = plt.hist(v,bins=len(val))\nplt.title('METODO INCORRECTO')\nplt.xlabel('valores (índices)')\nplt.ylabel('frecuencias')\nplt.legend(['incorrecto'])\nplt.show()\n", "_____no_output_____" ], [ "def plot_histogram_discrete(distribucion:'distribución a graficar histograma',\n label:'label del legend'):\n # len(set(distribucion)) cuenta la cantidad de elementos distintos de la variable 'distribucion'\n plt.figure(figsize=[8,4])\n y,x = np.histogram(distribucion,bins = len(set(distribucion))) \n plt.bar(list(set(distribucion)),y,label=label)\n plt.legend()\n plt.show()", "_____no_output_____" ] ], [ [ "># <font color ='red'> **Tarea 5** \n \n> Para las siguiente dos funciones, genere muestres aleatorias que distribuyan según la función dada usando el método de la transformada inversa y grafique el histograma de 1000 muestras generadas con el método de la transformada inversa y compárela con el función $f(x)$ **(recuerde que $f(x)$ es la distribución de probabilidad y $F(x)$ es la distribución de probabilidad acumulada)** [ver este enlace para más información](https://es.wikipedia.org/wiki/Funci%C3%B3n_de_distribuci%C3%B3n). Este procedimiento se realiza con el fín de validar que el procedimiento y los resultados son correctos.\n \n> 1. Generación variable aleatoria continua\n>El tiempo en el cual un movimiento browniano se mantiene sobre su punto máximo en el intervalo [0,1] tiene una distribución\n>$$F(x)=\\frac{2}{\\pi}\\sin^{-1}(\\sqrt x),\\quad 0\\leq x\\leq 1$$ </font>\n\n> 2. Generación variable aleatoria Discreta\n> La distribución binomial modela el número de éxitos de n ensayos independientes donde hay una probabilidad p de éxito en cada ensayo.\n> Generar una variable aletoria binomial con parámetros $n=10$ y $p=0.7$. Recordar que $$X\\sim binomial(n,p) \\longrightarrow p_i=P(X=i)=\\frac{n!}{i!(n-i)!}p^i(1-p)^{n-i},\\quad i=0,1,\\cdots,n$$\n> Por propiedades de la operación factorial la anterior $p_i$ se puede escribir como:\n> $$p_{i+1}=\\frac{n-i}{i+1}\\frac{p}{1-p} p_i $$\n\n> **Nota:** Por notación recuerde que para el caso continuo $f(x)$ es la distribución de probabilidad (PDF), mientras $F(x)$ corresponde a la distribución de probabilidad acumulada (CDF). Para el caso discreto, $P(X=i)$ corresponde a su distribución de probabilidad (PMF) y $ F_{X}(x)=\\operatorname {P} (X\\leq x)=\\sum _{x_{i}\\leq x}\\operatorname {P} (X=x_{i})=\\sum _{x_{i}\\leq x}p(x_{i})$, corresponde a su distribución de probabilidad acumulada (CDF).\n", "_____no_output_____" ], [ "<script>\n $(document).ready(function(){\n $('div.prompt').hide();\n $('div.back-to-top').hide();\n $('nav#menubar').hide();\n $('.breadcrumb').hide();\n $('.hidden-print').hide();\n });\n</script>\n\n<footer id=\"attribution\" style=\"float:right; color:#808080; background:#fff;\">\nCreated with Jupyter by Oscar David Jaramillo Z.\n</footer>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ] ]
cbdf7e4d523ebcacb01dca56cbec70a2cff8d6b3
85,031
ipynb
Jupyter Notebook
Python-notebooks/.ipynb_checkpoints/FirstJupyter-checkpoint.ipynb
Divyaraaga/w205-Fundamentals-Engineering
1f76a4bcdeb0a3cccaac4559e6e6e9a32d9beb81
[ "Apache-2.0" ]
1
2019-08-14T17:14:53.000Z
2019-08-14T17:14:53.000Z
Python-notebooks/.ipynb_checkpoints/FirstJupyter-checkpoint.ipynb
Divyaraaga/w205-Fundamentals-Engineering
1f76a4bcdeb0a3cccaac4559e6e6e9a32d9beb81
[ "Apache-2.0" ]
null
null
null
Python-notebooks/.ipynb_checkpoints/FirstJupyter-checkpoint.ipynb
Divyaraaga/w205-Fundamentals-Engineering
1f76a4bcdeb0a3cccaac4559e6e6e9a32d9beb81
[ "Apache-2.0" ]
null
null
null
55.503264
371
0.605732
[ [ [ "trips=pd.read_csv('trips.csv')\n", "_____no_output_____" ], [ "import redis\nimport pandas as pd", "_____no_output_____" ], [ "trips=pd.read_csv('trips.csv')\n\ndate_sorted_trips = trips.sort_values(by='end_date')\n\ndate_sorted_trips.head()", "_____no_output_____" ], [ "for trip in date_sorted_trips.itertuples():\n print(trip.end_date, '', trip.bike_number, '', trip.end_station_name)", "2013-08-29 22:18:00.000000 UTC 664 San Jose Diridon Caltrain Station\n2013-08-30 08:49:00.000000 UTC 675 San Pedro Square\n2013-08-30 18:00:00.000000 UTC 674 San Jose Civic Center\n2013-08-31 18:01:00.000000 UTC 661 Paseo de San Antonio\n2013-08-31 18:01:00.000000 UTC 664 Paseo de San Antonio\n2013-09-01 12:43:00.000000 UTC 245 San Pedro Square\n2013-09-01 13:25:00.000000 UTC 643 San Jose Civic Center\n2013-09-01 13:25:00.000000 UTC 37 San Jose Civic Center\n2013-09-01 15:59:00.000000 UTC 37 San Jose Diridon Caltrain Station\n2013-09-01 15:59:00.000000 UTC 680 San Jose Diridon Caltrain Station\n2013-09-02 16:21:00.000000 UTC 70 San Jose Diridon Caltrain Station\n2013-09-02 16:21:00.000000 UTC 37 San Jose Diridon Caltrain Station\n2013-09-02 19:48:00.000000 UTC 187 San Jose Civic Center\n2013-09-03 13:02:00.000000 UTC 654 San Jose Diridon Caltrain Station\n2013-09-05 18:50:00.000000 UTC 641 San Jose Diridon Caltrain Station\n2013-09-06 08:58:00.000000 UTC 641 San Pedro Square\n2013-09-06 08:58:00.000000 UTC 666 San Pedro Square\n2013-09-06 09:18:00.000000 UTC 246 Santa Clara at Almaden\n2013-09-06 15:51:00.000000 UTC 99 San Jose Civic Center\n2013-09-06 15:52:00.000000 UTC 109 San Jose Civic Center\n2013-09-06 15:52:00.000000 UTC 81 San Jose Civic Center\n2013-09-07 12:15:00.000000 UTC 88 Santa Clara at Almaden\n2013-09-08 17:20:00.000000 UTC 654 San Jose Civic Center\n2013-09-08 17:23:00.000000 UTC 658 San Jose Civic Center\n2013-09-10 08:22:00.000000 UTC 76 San Pedro Square\n2013-09-10 09:26:00.000000 UTC 44 San Pedro Square\n2013-09-10 13:25:00.000000 UTC 674 San Pedro Square\n2013-09-10 19:24:00.000000 UTC 645 San Jose Diridon Caltrain Station\n2013-09-10 19:26:00.000000 UTC 645 San Jose Diridon Caltrain Station\n2013-09-11 08:49:00.000000 UTC 30 San Pedro Square\n2013-09-11 18:20:00.000000 UTC 102 Japantown\n2013-09-12 08:24:00.000000 UTC 679 San Pedro Square\n2013-09-13 08:21:00.000000 UTC 641 San Pedro Square\n2013-09-13 13:25:00.000000 UTC 26 San Jose Civic Center\n2013-09-13 13:25:00.000000 UTC 30 San Jose Civic Center\n2013-09-14 07:23:00.000000 UTC 88 San Jose Diridon Caltrain Station\n2013-09-14 15:47:00.000000 UTC 88 San Jose Civic Center\n2013-09-15 20:10:00.000000 UTC 47 San Jose Civic Center\n2013-09-16 08:27:00.000000 UTC 31 San Pedro Square\n2013-09-17 08:26:00.000000 UTC 53 San Pedro Square\n2013-09-17 13:16:00.000000 UTC 198 Paseo de San Antonio\n2013-09-18 08:29:00.000000 UTC 78 San Pedro Square\n2013-09-19 09:19:00.000000 UTC 81 Paseo de San Antonio\n2013-09-19 19:04:00.000000 UTC 667 San Jose Diridon Caltrain Station\n2013-09-20 14:00:00.000000 UTC 23 San Jose Diridon Caltrain Station\n2013-09-20 18:14:00.000000 UTC 68 San Jose Civic Center\n2013-09-23 02:36:00.000000 UTC 26 Japantown\n2013-09-23 22:29:00.000000 UTC 303 Japantown\n2013-09-24 08:26:00.000000 UTC 55 San Pedro Square\n2013-09-25 08:46:00.000000 UTC 666 San Pedro Square\n2013-09-26 08:18:00.000000 UTC 664 Adobe on Almaden\n2013-09-26 09:14:00.000000 UTC 231 San Pedro Square\n2013-09-26 20:27:00.000000 UTC 703 San Salvador at 1st\n2013-09-27 16:06:00.000000 UTC 99 Japantown\n2013-09-30 01:48:00.000000 UTC 90 Japantown\n2013-09-30 21:18:00.000000 UTC 109 San Pedro Square\n2013-09-30 21:18:00.000000 UTC 42 San Pedro Square\n2013-10-04 19:08:00.000000 UTC 63 Paseo de San Antonio\n2013-10-05 11:38:00.000000 UTC 174 San Jose Diridon Caltrain Station\n2013-10-05 12:46:00.000000 UTC 664 San Jose Diridon Caltrain Station\n2013-10-05 12:46:00.000000 UTC 174 San Jose Diridon Caltrain Station\n2013-10-05 13:00:00.000000 UTC 174 San Jose Civic Center\n2013-10-06 08:12:00.000000 UTC 674 Santa Clara at Almaden\n2013-10-06 09:38:00.000000 UTC 656 San Jose Diridon Caltrain Station\n2013-10-06 09:38:00.000000 UTC 174 San Jose Diridon Caltrain Station\n2013-10-06 10:29:00.000000 UTC 656 Adobe on Almaden\n2013-10-06 10:29:00.000000 UTC 645 Adobe on Almaden\n2013-10-06 12:11:00.000000 UTC 706 San Jose Diridon Caltrain Station\n2013-10-06 16:18:00.000000 UTC 181 San Jose Civic Center\n2013-10-07 17:26:00.000000 UTC 28 San Jose Diridon Caltrain Station\n2013-10-08 12:38:00.000000 UTC 118 San Jose Civic Center\n2013-10-08 17:17:00.000000 UTC 200 San Jose Diridon Caltrain Station\n2013-10-10 23:31:00.000000 UTC 143 San Salvador at 1st\n2013-10-11 10:24:00.000000 UTC 77 Paseo de San Antonio\n2013-10-11 14:59:00.000000 UTC 183 San Jose Diridon Caltrain Station\n2013-10-12 14:54:00.000000 UTC 646 San Pedro Square\n2013-10-12 15:46:00.000000 UTC 52 San Jose Diridon Caltrain Station\n2013-10-12 15:46:00.000000 UTC 649 San Jose Diridon Caltrain Station\n2013-10-12 16:52:00.000000 UTC 666 San Jose Civic Center\n2013-10-12 16:52:00.000000 UTC 76 San Jose Civic Center\n2013-10-13 10:36:00.000000 UTC 293 San Jose Diridon Caltrain Station\n2013-10-13 10:36:00.000000 UTC 69 San Jose Diridon Caltrain Station\n2013-10-16 07:38:00.000000 UTC 45 Adobe on Almaden\n2013-10-16 07:48:00.000000 UTC 152 San Jose Civic Center\n2013-10-16 13:46:00.000000 UTC 175 San Jose Diridon Caltrain Station\n2013-10-16 16:08:00.000000 UTC 152 San Jose Diridon Caltrain Station\n2013-10-17 07:46:00.000000 UTC 40 San Jose Civic Center\n2013-10-17 16:05:00.000000 UTC 187 San Jose Diridon Caltrain Station\n2013-10-17 16:06:00.000000 UTC 650 San Jose Diridon Caltrain Station\n2013-10-17 16:35:00.000000 UTC 40 San Jose Civic Center\n2013-10-17 16:45:00.000000 UTC 674 San Jose Diridon Caltrain Station\n2013-10-17 17:45:00.000000 UTC 40 San Jose Diridon Caltrain Station\n2013-10-18 07:40:00.000000 UTC 40 San Jose Civic Center\n2013-10-18 12:58:00.000000 UTC 41 Adobe on Almaden\n2013-10-18 16:16:00.000000 UTC 709 San Jose Diridon Caltrain Station\n2013-10-20 13:06:00.000000 UTC 641 San Jose Diridon Caltrain Station\n2013-10-20 13:06:00.000000 UTC 45 San Jose Diridon Caltrain Station\n2013-10-20 13:06:00.000000 UTC 64 San Jose Diridon Caltrain Station\n2013-10-20 13:42:00.000000 UTC 646 San Jose Diridon Caltrain Station\n2013-10-20 16:37:00.000000 UTC 297 San Jose Civic Center\n2013-10-21 15:36:00.000000 UTC 646 San Salvador at 1st\n2013-10-21 18:48:00.000000 UTC 198 San Salvador at 1st\n2013-10-22 18:53:00.000000 UTC 56 San Salvador at 1st\n2013-10-23 18:52:00.000000 UTC 183 San Jose Civic Center\n2013-10-24 19:23:00.000000 UTC 126 San Salvador at 1st\n2013-10-25 16:48:00.000000 UTC 640 Santa Clara at Almaden\n2013-10-25 17:19:00.000000 UTC 237 Santa Clara at Almaden\n2013-10-26 14:39:00.000000 UTC 50 Japantown\n2013-10-28 13:49:00.000000 UTC 710 San Jose Diridon Caltrain Station\n2013-10-28 18:51:00.000000 UTC 231 San Salvador at 1st\n2013-10-28 23:22:00.000000 UTC 232 San Jose Civic Center\n2013-10-29 17:51:00.000000 UTC 86 San Salvador at 1st\n2013-10-30 18:23:00.000000 UTC 89 San Salvador at 1st\n2013-11-01 13:53:00.000000 UTC 59 Adobe on Almaden\n2013-11-03 12:31:00.000000 UTC 59 San Jose Civic Center\n2013-11-03 12:32:00.000000 UTC 700 San Jose Civic Center\n2013-11-03 17:29:00.000000 UTC 136 San Salvador at 1st\n2013-11-03 18:05:00.000000 UTC 45 San Jose Diridon Caltrain Station\n2013-11-05 08:20:00.000000 UTC 158 Adobe on Almaden\n2013-11-07 15:39:00.000000 UTC 59 San Jose Civic Center\n2013-11-07 17:40:00.000000 UTC 667 Japantown\n2013-11-08 13:12:00.000000 UTC 59 San Jose Civic Center\n2013-11-13 08:10:00.000000 UTC 691 Adobe on Almaden\n2013-11-13 17:06:00.000000 UTC 639 San Jose Civic Center\n2013-11-14 10:17:00.000000 UTC 149 Paseo de San Antonio\n2013-11-14 13:34:00.000000 UTC 293 San Jose Civic Center\n2013-11-14 16:07:00.000000 UTC 82 San Jose Diridon Caltrain Station\n2013-11-15 20:19:00.000000 UTC 69 San Jose Diridon Caltrain Station\n2013-11-15 20:19:00.000000 UTC 668 San Jose Diridon Caltrain Station\n2013-11-16 11:57:00.000000 UTC 180 San Jose Civic Center\n2013-11-16 14:46:00.000000 UTC 183 San Jose Diridon Caltrain Station\n2013-11-19 15:57:00.000000 UTC 140 San Jose Diridon Caltrain Station\n2013-11-20 10:17:00.000000 UTC 712 Paseo de San Antonio\n2013-11-24 02:32:00.000000 UTC 47 San Jose Civic Center\n2013-11-24 13:44:00.000000 UTC 640 San Jose Diridon Caltrain Station\n2013-11-25 19:14:00.000000 UTC 712 Adobe on Almaden\n2013-11-26 11:54:00.000000 UTC 38 Adobe on Almaden\n2013-11-26 11:54:00.000000 UTC 85 Adobe on Almaden\n2013-11-27 16:52:00.000000 UTC 143 San Jose Diridon Caltrain Station\n2013-11-30 00:09:00.000000 UTC 20 Japantown\n2013-11-30 17:22:00.000000 UTC 226 San Jose Civic Center\n2013-12-01 16:15:00.000000 UTC 130 San Pedro Square\n2013-12-01 16:15:00.000000 UTC 143 San Pedro Square\n2013-12-03 05:42:00.000000 UTC 183 San Jose Diridon Caltrain Station\n2013-12-06 15:10:00.000000 UTC 216 San Jose Diridon Caltrain Station\n2013-12-06 15:10:00.000000 UTC 152 San Jose Diridon Caltrain Station\n2013-12-06 19:31:00.000000 UTC 157 Adobe on Almaden\n2013-12-10 08:57:00.000000 UTC 708 San Jose Civic Center\n2013-12-11 08:03:00.000000 UTC 660 San Jose Civic Center\n2013-12-11 12:51:00.000000 UTC 660 San Jose Diridon Caltrain Station\n2013-12-13 01:50:00.000000 UTC 708 Japantown\n2013-12-13 05:35:00.000000 UTC 649 San Jose Diridon Caltrain Station\n2013-12-13 06:35:00.000000 UTC 297 San Jose Diridon Caltrain Station\n2013-12-15 13:23:00.000000 UTC 29 Adobe on Almaden\n2013-12-20 20:46:00.000000 UTC 696 San Jose Diridon Caltrain Station\n2013-12-20 22:27:00.000000 UTC 663 Adobe on Almaden\n2013-12-20 22:27:00.000000 UTC 688 Adobe on Almaden\n2013-12-20 22:27:00.000000 UTC 151 Adobe on Almaden\n2013-12-20 22:27:00.000000 UTC 168 Adobe on Almaden\n2013-12-20 22:27:00.000000 UTC 696 Adobe on Almaden\n2013-12-25 16:26:00.000000 UTC 262 Paseo de San Antonio\n2013-12-28 19:00:00.000000 UTC 200 San Jose Civic Center\n2013-12-29 17:16:00.000000 UTC 119 San Jose Civic Center\n2013-12-29 17:16:00.000000 UTC 648 San Jose Civic Center\n2013-12-29 17:16:00.000000 UTC 232 San Jose Civic Center\n2014-01-03 10:05:00.000000 UTC 11 Santa Clara at Almaden\n2014-01-03 16:14:00.000000 UTC 208 San Jose Diridon Caltrain Station\n2014-01-03 16:14:00.000000 UTC 663 San Jose Diridon Caltrain Station\n2014-01-03 18:53:00.000000 UTC 642 Paseo de San Antonio\n2014-01-05 15:12:00.000000 UTC 202 San Jose Diridon Caltrain Station\n2014-01-05 15:13:00.000000 UTC 60 San Jose Diridon Caltrain Station\n2014-01-05 15:13:00.000000 UTC 109 San Jose Diridon Caltrain Station\n2014-01-05 15:13:00.000000 UTC 145 San Jose Diridon Caltrain Station\n2014-01-05 15:13:00.000000 UTC 211 San Jose Diridon Caltrain Station\n2014-01-05 15:26:00.000000 UTC 60 San Jose Civic Center\n2014-01-05 15:26:00.000000 UTC 202 San Jose Civic Center\n2014-01-05 15:26:00.000000 UTC 142 San Jose Civic Center\n2014-01-05 15:26:00.000000 UTC 211 San Jose Civic Center\n2014-01-05 15:26:00.000000 UTC 109 San Jose Civic Center\n2014-01-06 12:23:00.000000 UTC 232 San Jose Civic Center\n2014-01-09 15:15:00.000000 UTC 52 San Jose Diridon Caltrain Station\n2014-01-09 15:36:00.000000 UTC 52 San Pedro Square\n2014-01-09 15:36:00.000000 UTC 657 San Pedro Square\n2014-01-09 19:04:00.000000 UTC 654 Paseo de San Antonio\n2014-01-10 22:26:00.000000 UTC 83 San Jose Diridon Caltrain Station\n2014-01-11 20:13:00.000000 UTC 83 San Jose Civic Center\n2014-01-12 13:16:00.000000 UTC 200 San Jose Diridon Caltrain Station\n2014-01-12 13:17:00.000000 UTC 117 San Jose Diridon Caltrain Station\n2014-01-12 13:48:00.000000 UTC 229 San Jose Civic Center\n2014-01-12 13:48:00.000000 UTC 42 San Jose Civic Center\n2014-01-12 13:48:00.000000 UTC 211 San Jose Civic Center\n2014-01-14 16:14:00.000000 UTC 108 San Jose Diridon Caltrain Station\n2014-01-14 23:18:00.000000 UTC 665 Adobe on Almaden\n2014-01-16 11:18:00.000000 UTC 487 San Jose Diridon Caltrain Station\n2014-01-16 11:18:00.000000 UTC 78 San Jose Diridon Caltrain Station\n2014-01-16 11:26:00.000000 UTC 175 San Jose Diridon Caltrain Station\n2014-01-17 16:25:00.000000 UTC 39 San Jose Civic Center\n2014-01-19 16:11:00.000000 UTC 643 San Jose Civic Center\n2014-01-19 17:08:00.000000 UTC 262 San Jose Civic Center\n2014-01-19 17:08:00.000000 UTC 92 San Jose Civic Center\n2014-01-19 17:08:00.000000 UTC 211 San Jose Civic Center\n2014-01-20 15:00:00.000000 UTC 209 San Salvador at 1st\n2014-01-21 18:22:00.000000 UTC 133 Santa Clara at Almaden\n2014-01-23 18:57:00.000000 UTC 200 San Jose Civic Center\n2014-01-23 18:58:00.000000 UTC 104 San Jose Civic Center\n2014-01-27 07:50:00.000000 UTC 202 San Jose Diridon Caltrain Station\n2014-01-27 07:50:00.000000 UTC 177 San Jose Diridon Caltrain Station\n2014-01-28 10:23:00.000000 UTC 49 San Jose Civic Center\n2014-01-29 18:14:00.000000 UTC 691 San Jose Civic Center\n2014-01-31 16:09:00.000000 UTC 50 Japantown\n2014-02-04 09:37:00.000000 UTC 129 San Jose Diridon Caltrain Station\n2014-02-04 12:59:00.000000 UTC 208 San Jose Diridon Caltrain Station\n2014-02-04 16:56:00.000000 UTC 205 San Jose Civic Center\n2014-02-05 00:19:00.000000 UTC 108 San Jose Civic Center\n2014-02-05 08:31:00.000000 UTC 135 San Jose Diridon Caltrain Station\n2014-02-05 11:07:00.000000 UTC 209 San Jose Diridon Caltrain Station\n2014-02-05 17:41:00.000000 UTC 710 San Jose Civic Center\n2014-02-08 15:28:00.000000 UTC 185 Japantown\n2014-02-09 09:35:00.000000 UTC 104 San Jose Diridon Caltrain Station\n2014-02-14 19:28:00.000000 UTC 685 San Jose Civic Center\n2014-02-15 10:39:00.000000 UTC 127 San Jose Diridon Caltrain Station\n2014-02-15 14:25:00.000000 UTC 127 San Jose Civic Center\n2014-02-17 01:07:00.000000 UTC 202 Paseo de San Antonio\n2014-02-18 00:04:00.000000 UTC 127 San Jose Civic Center\n2014-02-20 08:59:00.000000 UTC 107 San Jose Civic Center\n2014-02-23 12:37:00.000000 UTC 685 San Jose Civic Center\n2014-02-23 12:37:00.000000 UTC 196 San Jose Civic Center\n2014-02-23 21:54:00.000000 UTC 37 San Jose Diridon Caltrain Station\n2014-02-23 21:55:00.000000 UTC 193 San Jose Diridon Caltrain Station\n2014-02-28 13:34:00.000000 UTC 691 San Jose Diridon Caltrain Station\n2014-02-28 14:33:00.000000 UTC 647 Adobe on Almaden\n2014-03-05 17:31:00.000000 UTC 186 San Salvador at 1st\n2014-03-08 10:14:00.000000 UTC 647 San Pedro Square\n2014-03-11 00:24:00.000000 UTC 93 Paseo de San Antonio\n2014-03-12 20:27:00.000000 UTC 104 San Jose Diridon Caltrain Station\n2014-03-15 09:52:00.000000 UTC 680 San Jose Diridon Caltrain Station\n2014-03-15 09:52:00.000000 UTC 180 San Jose Diridon Caltrain Station\n2014-03-16 14:43:00.000000 UTC 59 San Jose Civic Center\n2014-03-16 14:43:00.000000 UTC 200 San Jose Civic Center\n2014-03-19 09:40:00.000000 UTC 145 San Jose Diridon Caltrain Station\n2014-03-22 14:46:00.000000 UTC 200 San Jose Civic Center\n2014-03-22 14:46:00.000000 UTC 182 San Jose Civic Center\n2014-03-22 16:16:00.000000 UTC 200 San Jose Diridon Caltrain Station\n2014-03-22 18:27:00.000000 UTC 638 San Jose Civic Center\n2014-03-22 18:28:00.000000 UTC 193 San Jose Civic Center\n2014-03-23 15:31:00.000000 UTC 57 San Jose Civic Center\n2014-03-23 17:18:00.000000 UTC 193 San Jose Civic Center\n2014-03-23 17:18:00.000000 UTC 182 San Jose Civic Center\n2014-03-24 18:56:00.000000 UTC 656 Japantown\n2014-03-25 19:31:00.000000 UTC 127 Japantown\n2014-03-26 19:18:00.000000 UTC 184 San Jose Diridon Caltrain Station\n2014-03-26 19:27:00.000000 UTC 127 San Jose Civic Center\n2014-03-27 09:55:00.000000 UTC 218 San Jose Diridon Caltrain Station\n2014-03-27 18:31:00.000000 UTC 688 Japantown\n2014-03-28 19:52:00.000000 UTC 158 Japantown\n2014-03-28 20:09:00.000000 UTC 701 San Jose Civic Center\n2014-03-28 20:09:00.000000 UTC 658 San Jose Civic Center\n2014-03-31 23:23:00.000000 UTC 665 Japantown\n2014-04-01 19:27:00.000000 UTC 45 Japantown\n2014-04-02 17:27:00.000000 UTC 67 Japantown\n2014-04-03 14:50:00.000000 UTC 683 San Jose Civic Center\n2014-04-03 17:55:00.000000 UTC 690 San Pedro Square\n2014-04-03 18:28:00.000000 UTC 146 Japantown\n2014-04-05 13:25:00.000000 UTC 302 San Jose Civic Center\n2014-04-06 16:19:00.000000 UTC 23 San Jose Diridon Caltrain Station\n2014-04-06 16:19:00.000000 UTC 168 San Jose Diridon Caltrain Station\n2014-04-06 16:19:00.000000 UTC 143 San Jose Diridon Caltrain Station\n2014-04-06 16:19:00.000000 UTC 70 San Jose Diridon Caltrain Station\n2014-04-08 19:26:00.000000 UTC 643 San Pedro Square\n2014-04-09 16:19:00.000000 UTC 31 San Jose Civic Center\n2014-04-09 16:34:00.000000 UTC 31 San Jose Diridon Caltrain Station\n2014-04-10 12:18:00.000000 UTC 710 San Pedro Square\n2014-04-11 07:57:00.000000 UTC 98 San Jose Civic Center\n2014-04-11 17:17:00.000000 UTC 668 San Jose Diridon Caltrain Station\n2014-04-12 14:24:00.000000 UTC 98 San Jose Diridon Caltrain Station\n2014-04-12 16:10:00.000000 UTC 112 San Jose Civic Center\n2014-04-13 13:24:00.000000 UTC 699 San Jose Civic Center\n2014-04-13 13:24:00.000000 UTC 669 San Jose Civic Center\n2014-04-13 13:24:00.000000 UTC 132 San Jose Civic Center\n2014-04-14 19:23:00.000000 UTC 303 San Jose Civic Center\n2014-04-17 17:53:00.000000 UTC 168 San Jose Civic Center\n2014-04-17 17:53:00.000000 UTC 41 San Jose Civic Center\n2014-04-17 17:53:00.000000 UTC 67 San Jose Civic Center\n2014-04-18 08:10:00.000000 UTC 671 San Jose Civic Center\n2014-04-19 16:38:00.000000 UTC 101 San Jose Diridon Caltrain Station\n2014-04-19 16:38:00.000000 UTC 185 San Jose Diridon Caltrain Station\n2014-04-19 16:57:00.000000 UTC 41 San Jose Civic Center\n2014-04-26 14:35:00.000000 UTC 41 San Jose Civic Center\n2014-04-26 14:35:00.000000 UTC 685 San Jose Civic Center\n2014-04-26 18:47:00.000000 UTC 67 San Jose Diridon Caltrain Station\n2014-04-26 18:47:00.000000 UTC 685 San Jose Diridon Caltrain Station\n2014-04-28 00:24:00.000000 UTC 131 San Jose Civic Center\n2014-04-28 00:25:00.000000 UTC 80 San Jose Civic Center\n2014-04-28 00:25:00.000000 UTC 164 San Jose Civic Center\n2014-04-28 17:32:00.000000 UTC 146 San Jose Civic Center\n2014-04-28 17:33:00.000000 UTC 80 San Jose Civic Center\n2014-05-08 09:52:00.000000 UTC 156 San Jose Diridon Caltrain Station\n2014-05-09 13:31:00.000000 UTC 665 San Jose Civic Center\n2014-05-09 20:23:00.000000 UTC 31 Paseo de San Antonio\n2014-05-10 12:32:00.000000 UTC 713 San Jose Diridon Caltrain Station\n2014-05-10 12:32:00.000000 UTC 693 San Jose Diridon Caltrain Station\n2014-05-11 19:16:00.000000 UTC 93 San Jose Civic Center\n2014-05-12 20:04:00.000000 UTC 127 Paseo de San Antonio\n2014-05-13 11:57:00.000000 UTC 711 San Jose Civic Center\n2014-05-13 18:20:00.000000 UTC 711 San Jose Diridon Caltrain Station\n2014-05-15 02:02:00.000000 UTC 299 San Jose Diridon Caltrain Station\n2014-05-16 14:53:00.000000 UTC 658 San Jose Civic Center\n2014-05-18 09:08:00.000000 UTC 129 San Jose Civic Center\n2014-05-18 10:51:00.000000 UTC 164 San Jose Diridon Caltrain Station\n2014-05-18 10:51:00.000000 UTC 15 San Jose Diridon Caltrain Station\n2014-05-18 10:52:00.000000 UTC 25 San Jose Diridon Caltrain Station\n2014-05-19 13:34:00.000000 UTC 15 San Pedro Square\n2014-05-20 10:31:00.000000 UTC 182 Santa Clara at Almaden\n2014-05-22 15:51:00.000000 UTC 93 San Jose Civic Center\n2014-05-24 12:46:00.000000 UTC 702 San Jose Diridon Caltrain Station\n2014-05-24 12:50:00.000000 UTC 199 San Jose Diridon Caltrain Station\n2014-05-24 16:53:00.000000 UTC 702 San Jose Diridon Caltrain Station\n2014-05-24 16:54:00.000000 UTC 299 San Jose Diridon Caltrain Station\n2014-05-24 16:54:00.000000 UTC 150 San Jose Diridon Caltrain Station\n2014-05-24 18:18:00.000000 UTC 149 San Jose Diridon Caltrain Station\n2014-05-24 18:18:00.000000 UTC 688 San Jose Diridon Caltrain Station\n2014-05-24 20:20:00.000000 UTC 149 San Jose Diridon Caltrain Station\n2014-05-24 20:21:00.000000 UTC 299 San Jose Diridon Caltrain Station\n2014-05-25 00:03:00.000000 UTC 32 San Jose Diridon Caltrain Station\n2014-05-29 11:21:00.000000 UTC 23 San Jose Civic Center\n2014-05-30 13:22:00.000000 UTC 688 San Jose Civic Center\n2014-05-31 13:18:00.000000 UTC 101 San Jose Civic Center\n2014-05-31 13:18:00.000000 UTC 711 San Jose Civic Center\n2014-05-31 13:19:00.000000 UTC 294 San Jose Civic Center\n2014-06-01 17:44:00.000000 UTC 644 San Jose Civic Center\n2014-06-01 17:44:00.000000 UTC 711 San Jose Civic Center\n2014-06-01 18:38:00.000000 UTC 711 San Jose Civic Center\n2014-06-01 19:00:00.000000 UTC 93 San Jose Diridon Caltrain Station\n2014-06-02 08:01:00.000000 UTC 107 San Jose Civic Center\n2014-06-02 08:02:00.000000 UTC 711 San Jose Civic Center\n2014-06-02 13:47:00.000000 UTC 107 San Jose Civic Center\n2014-06-06 08:40:00.000000 UTC 15 San Jose Civic Center\n2014-06-10 16:18:00.000000 UTC 190 San Jose Civic Center\n2014-06-11 18:16:00.000000 UTC 25 San Jose Civic Center\n2014-06-12 08:54:00.000000 UTC 185 San Jose Civic Center\n2014-06-12 12:48:00.000000 UTC 715 San Salvador at 1st\n2014-06-12 12:48:00.000000 UTC 65 San Salvador at 1st\n2014-06-12 17:41:00.000000 UTC 190 San Jose Diridon Caltrain Station\n2014-06-13 12:59:00.000000 UTC 151 San Jose Civic Center\n2014-06-14 17:38:00.000000 UTC 227 San Pedro Square\n2014-06-14 17:38:00.000000 UTC 710 San Pedro Square\n2014-06-15 01:55:00.000000 UTC 131 San Salvador at 1st\n2014-06-15 01:55:00.000000 UTC 164 San Salvador at 1st\n2014-06-16 21:36:00.000000 UTC 685 San Jose Diridon Caltrain Station\n2014-06-20 20:18:00.000000 UTC 65 Santa Clara at Almaden\n2014-06-21 00:14:00.000000 UTC 154 San Pedro Square\n2014-06-22 13:25:00.000000 UTC 150 San Jose Civic Center\n2014-06-22 19:21:00.000000 UTC 678 San Jose Civic Center\n2014-06-22 19:26:00.000000 UTC 664 San Jose Civic Center\n2014-06-22 19:26:00.000000 UTC 80 San Jose Civic Center\n2014-06-22 20:45:00.000000 UTC 669 San Jose Civic Center\n2014-06-23 09:18:00.000000 UTC 150 San Jose Civic Center\n2014-06-24 13:11:00.000000 UTC 53 San Jose Civic Center\n2014-06-26 10:00:00.000000 UTC 702 San Jose Civic Center\n2014-06-26 11:16:00.000000 UTC 702 San Jose Civic Center\n2014-06-27 08:22:00.000000 UTC 10 San Jose Civic Center\n2014-06-28 19:15:00.000000 UTC 10 San Jose Civic Center\n2014-06-29 11:48:00.000000 UTC 226 San Jose Civic Center\n2014-07-01 18:04:00.000000 UTC 226 San Jose Civic Center\n2014-07-03 13:25:00.000000 UTC 711 San Jose Civic Center\n2014-07-03 14:10:00.000000 UTC 209 San Jose Civic Center\n2014-07-04 15:09:00.000000 UTC 156 San Jose Civic Center\n2014-07-04 18:49:00.000000 UTC 21 San Jose Civic Center\n2014-07-04 18:50:00.000000 UTC 702 San Jose Civic Center\n2014-07-05 12:44:00.000000 UTC 703 San Jose Civic Center\n2014-07-05 12:44:00.000000 UTC 702 San Jose Civic Center\n2014-07-05 12:44:00.000000 UTC 156 San Jose Civic Center\n2014-07-09 16:00:00.000000 UTC 685 San Jose Civic Center\n2014-07-10 15:56:00.000000 UTC 162 San Jose Civic Center\n2014-07-10 15:57:00.000000 UTC 12 San Jose Civic Center\n2014-07-12 19:35:00.000000 UTC 175 San Jose Diridon Caltrain Station\n2014-07-14 18:03:00.000000 UTC 644 San Jose Civic Center\n2014-07-14 18:27:00.000000 UTC 644 San Jose Civic Center\n2014-07-16 14:33:00.000000 UTC 159 San Jose Civic Center\n2014-07-22 13:12:00.000000 UTC 297 San Jose Civic Center\n2014-07-26 09:48:00.000000 UTC 226 San Jose Diridon Caltrain Station\n2014-07-26 19:21:00.000000 UTC 108 San Jose Diridon Caltrain Station\n2014-07-28 17:39:00.000000 UTC 112 San Jose Diridon Caltrain Station\n2014-07-28 17:40:00.000000 UTC 164 San Jose Diridon Caltrain Station\n2014-08-09 10:16:00.000000 UTC 122 San Jose Civic Center\n2014-08-12 18:15:00.000000 UTC 144 San Jose Civic Center\n2014-08-13 08:17:00.000000 UTC 691 San Jose Civic Center\n2014-08-13 08:18:00.000000 UTC 150 San Jose Civic Center\n2014-08-17 09:15:00.000000 UTC 62 Santa Clara at Almaden\n2014-08-17 12:54:00.000000 UTC 84 Paseo de San Antonio\n2014-08-17 12:59:00.000000 UTC 710 Paseo de San Antonio\n2014-08-17 13:02:00.000000 UTC 294 Paseo de San Antonio\n2014-08-17 13:02:00.000000 UTC 127 Paseo de San Antonio\n2014-08-17 13:58:00.000000 UTC 227 San Jose Civic Center\n2014-08-17 14:00:00.000000 UTC 251 San Jose Civic Center\n2014-08-18 14:48:00.000000 UTC 150 San Jose Civic Center\n2014-08-20 16:16:00.000000 UTC 691 San Jose Civic Center\n2014-08-20 16:16:00.000000 UTC 28 San Jose Civic Center\n2014-08-20 16:17:00.000000 UTC 101 San Jose Civic Center\n2014-08-20 16:17:00.000000 UTC 124 San Jose Civic Center\n2014-08-22 15:07:00.000000 UTC 648 Japantown\n2014-08-27 17:02:00.000000 UTC 247 Adobe on Almaden\n2014-08-27 17:03:00.000000 UTC 702 Adobe on Almaden\n2014-08-28 20:39:00.000000 UTC 116 San Pedro Square\n2014-08-29 13:50:00.000000 UTC 715 San Jose Civic Center\n2014-08-29 16:17:00.000000 UTC 143 San Jose Civic Center\n2014-08-30 14:24:00.000000 UTC 143 San Jose Civic Center\n2014-08-31 05:28:00.000000 UTC 696 San Jose Diridon Caltrain Station\n2014-09-01 22:10:00.000000 UTC 696 San Jose Civic Center\n2014-09-01 22:10:00.000000 UTC 101 San Jose Civic Center\n2014-09-01 22:10:00.000000 UTC 256 San Jose Civic Center\n2014-09-01 22:11:00.000000 UTC 89 San Jose Civic Center\n2014-09-01 22:11:00.000000 UTC 150 San Jose Civic Center\n2014-09-02 14:56:00.000000 UTC 99 San Jose Civic Center\n2014-09-02 19:22:00.000000 UTC 713 Santa Clara at Almaden\n2014-09-03 00:54:00.000000 UTC 664 San Jose Civic Center\n2014-09-03 00:54:00.000000 UTC 143 San Jose Civic Center\n2014-09-04 12:33:00.000000 UTC 28 San Jose Diridon Caltrain Station\n2014-09-04 19:16:00.000000 UTC 150 San Pedro Square\n2014-09-06 18:12:00.000000 UTC 89 Paseo de San Antonio\n2014-09-11 16:50:00.000000 UTC 194 San Jose Civic Center\n2014-09-13 16:57:00.000000 UTC 101 San Jose Civic Center\n2014-09-13 17:06:00.000000 UTC 28 San Jose Civic Center\n2014-09-14 09:13:00.000000 UTC 42 San Jose Civic Center\n2014-09-14 09:13:00.000000 UTC 28 San Jose Civic Center\n2014-09-14 09:13:00.000000 UTC 645 San Jose Civic Center\n2014-09-14 16:08:00.000000 UTC 645 San Jose Civic Center\n2014-09-14 16:27:00.000000 UTC 23 San Jose Civic Center\n2014-09-15 11:15:00.000000 UTC 194 San Jose Diridon Caltrain Station\n2014-09-15 22:25:00.000000 UTC 39 Adobe on Almaden\n2014-09-16 07:55:00.000000 UTC 127 San Jose Diridon Caltrain Station\n2014-09-16 09:40:00.000000 UTC 645 San Jose Civic Center\n2014-09-18 08:31:00.000000 UTC 23 San Jose Civic Center\n2014-09-18 09:30:00.000000 UTC 31 San Jose Civic Center\n2014-09-18 17:00:00.000000 UTC 23 San Jose Diridon Caltrain Station\n2014-09-19 13:25:00.000000 UTC 194 San Jose Civic Center\n2014-09-19 18:29:00.000000 UTC 75 San Salvador at 1st\n2014-09-20 15:08:00.000000 UTC 258 San Pedro Square\n2014-09-20 20:27:00.000000 UTC 53 Japantown\n2014-09-20 20:27:00.000000 UTC 647 Japantown\n2014-09-21 14:56:00.000000 UTC 241 San Jose Diridon Caltrain Station\n2014-09-21 20:43:00.000000 UTC 658 San Jose Diridon Caltrain Station\n2014-09-21 20:43:00.000000 UTC 162 San Jose Diridon Caltrain Station\n2014-09-22 03:16:00.000000 UTC 116 San Jose Civic Center\n2014-09-22 03:17:00.000000 UTC 82 San Jose Civic Center\n2014-09-22 03:17:00.000000 UTC 148 San Jose Civic Center\n2014-09-26 12:04:00.000000 UTC 116 San Jose Civic Center\n2014-09-27 12:53:00.000000 UTC 148 San Jose Civic Center\n2014-09-27 12:53:00.000000 UTC 99 San Jose Civic Center\n2014-09-28 15:33:00.000000 UTC 99 San Jose Civic Center\n2014-10-01 07:44:00.000000 UTC 666 San Pedro Square\n2014-10-02 07:45:00.000000 UTC 135 San Pedro Square\n2014-10-04 19:27:00.000000 UTC 715 San Pedro Square\n2014-10-05 11:15:00.000000 UTC 186 San Jose Diridon Caltrain Station\n2014-10-05 13:46:00.000000 UTC 186 San Jose Diridon Caltrain Station\n2014-10-07 10:53:00.000000 UTC 221 San Jose Civic Center\n2014-10-07 10:53:00.000000 UTC 307 San Jose Civic Center\n2014-10-08 13:46:00.000000 UTC 161 Santa Clara at Almaden\n2014-10-09 21:26:00.000000 UTC 77 San Jose Civic Center\n2014-10-11 21:58:00.000000 UTC 39 San Jose Civic Center\n2014-10-11 21:58:00.000000 UTC 152 San Jose Civic Center\n2014-10-11 21:58:00.000000 UTC 257 San Jose Civic Center\n2014-10-11 22:05:00.000000 UTC 132 San Salvador at 1st\n2014-10-12 18:03:00.000000 UTC 60 Adobe on Almaden\n2014-10-12 19:32:00.000000 UTC 82 San Jose Civic Center\n2014-10-13 07:43:00.000000 UTC 159 San Pedro Square\n2014-10-13 09:07:00.000000 UTC 44 Adobe on Almaden\n2014-10-14 07:40:00.000000 UTC 702 San Pedro Square\n2014-10-15 07:38:00.000000 UTC 132 San Pedro Square\n2014-10-15 17:21:00.000000 UTC 656 San Jose Civic Center\n2014-10-16 07:40:00.000000 UTC 55 San Pedro Square\n2014-10-17 23:41:00.000000 UTC 710 San Jose Civic Center\n2014-10-17 23:41:00.000000 UTC 656 San Jose Civic Center\n2014-10-19 10:35:00.000000 UTC 656 San Jose Civic Center\n2014-10-21 07:43:00.000000 UTC 233 San Pedro Square\n2014-10-23 20:28:00.000000 UTC 75 San Jose Civic Center\n2014-10-23 20:28:00.000000 UTC 87 San Jose Civic Center\n2014-10-25 12:50:00.000000 UTC 17 San Jose Civic Center\n2014-10-25 12:50:00.000000 UTC 656 San Jose Civic Center\n2014-10-25 14:09:00.000000 UTC 127 San Jose Diridon Caltrain Station\n2014-10-25 14:09:00.000000 UTC 17 San Jose Diridon Caltrain Station\n2014-10-25 14:53:00.000000 UTC 656 San Jose Civic Center\n2014-10-25 17:04:00.000000 UTC 131 San Jose Diridon Caltrain Station\n2014-10-25 19:24:00.000000 UTC 87 San Jose Civic Center\n2014-10-25 19:24:00.000000 UTC 135 San Jose Civic Center\n2014-10-25 19:25:00.000000 UTC 11 San Jose Civic Center\n2014-10-26 13:31:00.000000 UTC 14 San Jose Civic Center\n2014-10-26 17:46:00.000000 UTC 14 San Jose Civic Center\n2014-11-01 13:59:00.000000 UTC 247 San Jose Civic Center\n2014-11-05 15:19:00.000000 UTC 105 San Jose Civic Center\n2014-11-05 19:17:00.000000 UTC 148 San Salvador at 1st\n2014-11-06 15:17:00.000000 UTC 258 San Jose Civic Center\n2014-11-08 14:15:00.000000 UTC 17 San Jose Civic Center\n2014-11-08 17:42:00.000000 UTC 308 San Salvador at 1st\n2014-11-09 09:39:00.000000 UTC 679 San Jose Civic Center\n2014-11-14 15:54:00.000000 UTC 65 San Jose Civic Center\n2014-11-15 20:08:00.000000 UTC 65 San Jose Civic Center\n2014-11-15 20:09:00.000000 UTC 161 San Jose Civic Center\n2014-11-16 09:45:00.000000 UTC 131 San Jose Civic Center\n2014-11-16 18:29:00.000000 UTC 65 San Jose Civic Center\n2014-11-16 18:29:00.000000 UTC 161 San Jose Civic Center\n2014-12-02 18:58:00.000000 UTC 644 San Jose Civic Center\n2014-12-07 13:15:00.000000 UTC 65 Adobe on Almaden\n2014-12-07 13:56:00.000000 UTC 691 San Jose Civic Center\n2014-12-09 14:48:00.000000 UTC 702 Adobe on Almaden\n2014-12-29 14:08:00.000000 UTC 142 San Jose Civic Center\n2014-12-31 13:08:00.000000 UTC 692 San Jose Civic Center\n2014-12-31 13:09:00.000000 UTC 682 San Jose Civic Center\n2014-12-31 15:15:00.000000 UTC 692 San Jose Diridon Caltrain Station\n2014-12-31 15:16:00.000000 UTC 682 San Jose Diridon Caltrain Station\n2015-01-01 20:26:00.000000 UTC 105 San Jose Civic Center\n2015-01-06 13:27:00.000000 UTC 710 San Jose Civic Center\n2015-01-06 13:29:00.000000 UTC 682 San Pedro Square\n2015-01-10 12:23:00.000000 UTC 257 San Jose Civic Center\n2015-01-10 20:43:00.000000 UTC 251 San Jose Diridon Caltrain Station\n2015-01-15 10:08:00.000000 UTC 36 San Jose Civic Center\n2015-01-15 10:08:00.000000 UTC 32 San Jose Civic Center\n2015-01-16 13:53:00.000000 UTC 32 San Jose Civic Center\n2015-01-16 17:10:00.000000 UTC 710 San Jose Civic Center\n2015-01-21 19:37:00.000000 UTC 110 Japantown\n2015-01-23 17:35:00.000000 UTC 228 Japantown\n2015-01-28 08:42:00.000000 UTC 256 San Pedro Square\n2015-02-05 23:01:00.000000 UTC 9 San Jose Civic Center\n2015-02-05 23:01:00.000000 UTC 132 San Jose Civic Center\n2015-02-05 23:02:00.000000 UTC 241 San Jose Civic Center\n2015-02-11 08:41:00.000000 UTC 87 San Pedro Square\n2015-02-11 10:32:00.000000 UTC 299 Santa Clara at Almaden\n2015-02-12 07:43:00.000000 UTC 682 San Pedro Square\n2015-02-13 07:39:00.000000 UTC 664 San Pedro Square\n2015-02-13 16:05:00.000000 UTC 680 San Jose Civic Center\n2015-02-14 14:19:00.000000 UTC 65 San Salvador at 1st\n2015-02-15 02:28:00.000000 UTC 9 San Jose Civic Center\n2015-02-16 17:15:00.000000 UTC 261 San Jose Civic Center\n2015-02-16 17:16:00.000000 UTC 230 San Jose Civic Center\n2015-02-17 07:48:00.000000 UTC 178 San Pedro Square\n2015-02-18 16:28:00.000000 UTC 37 San Salvador at 1st\n2015-02-19 14:34:00.000000 UTC 218 San Jose Civic Center\n2015-02-20 08:53:00.000000 UTC 159 San Pedro Square\n2015-02-20 17:54:00.000000 UTC 715 Paseo de San Antonio\n2015-02-20 18:32:00.000000 UTC 647 San Salvador at 1st\n2015-02-20 22:50:00.000000 UTC 710 San Jose Civic Center\n2015-02-20 22:50:00.000000 UTC 25 San Jose Civic Center\n2015-02-22 00:03:00.000000 UTC 105 San Jose Diridon Caltrain Station\n2015-02-22 00:03:00.000000 UTC 706 San Jose Diridon Caltrain Station\n2015-02-28 07:25:00.000000 UTC 295 San Jose Civic Center\n2015-02-28 11:53:00.000000 UTC 304 San Jose Civic Center\n2015-02-28 13:42:00.000000 UTC 297 San Pedro Square\n2015-03-01 13:53:00.000000 UTC 700 San Jose Civic Center\n2015-03-01 17:16:00.000000 UTC 64 San Pedro Square\n2015-03-03 07:49:00.000000 UTC 36 San Jose Civic Center\n2015-03-04 15:47:00.000000 UTC 36 San Jose Civic Center\n2015-03-04 15:47:00.000000 UTC 37 San Jose Civic Center\n2015-03-06 21:18:00.000000 UTC 153 San Jose Diridon Caltrain Station\n2015-03-08 17:27:00.000000 UTC 258 San Jose Civic Center\n2015-03-10 18:37:00.000000 UTC 654 San Jose Civic Center\n2015-03-12 21:25:00.000000 UTC 63 San Pedro Square\n2015-03-13 17:32:00.000000 UTC 669 San Jose Diridon Caltrain Station\n2015-03-18 16:27:00.000000 UTC 131 San Jose Civic Center\n2015-03-18 18:03:00.000000 UTC 131 San Jose Civic Center\n2015-03-19 17:16:00.000000 UTC 36 Paseo de San Antonio\n2015-03-19 19:08:00.000000 UTC 10 San Jose Diridon Caltrain Station\n2015-03-21 12:09:00.000000 UTC 131 San Jose Diridon Caltrain Station\n2015-03-21 12:40:00.000000 UTC 702 San Jose Civic Center\n2015-03-21 16:24:00.000000 UTC 232 San Jose Civic Center\n2015-03-22 15:09:00.000000 UTC 76 San Jose Civic Center\n2015-03-24 16:41:00.000000 UTC 253 San Pedro Square\n2015-03-28 08:52:00.000000 UTC 696 San Jose Civic Center\n2015-03-28 12:35:00.000000 UTC 40 San Jose Civic Center\n2015-04-01 10:34:00.000000 UTC 690 San Jose Diridon Caltrain Station\n2015-04-02 09:21:00.000000 UTC 643 San Jose Civic Center\n2015-04-02 14:47:00.000000 UTC 175 Adobe on Almaden\n2015-04-03 10:39:00.000000 UTC 690 Adobe on Almaden\n2015-04-04 07:23:00.000000 UTC 241 San Jose Diridon Caltrain Station\n2015-04-04 20:22:00.000000 UTC 241 San Jose Civic Center\n2015-04-04 21:59:00.000000 UTC 126 San Jose Diridon Caltrain Station\n2015-04-04 22:00:00.000000 UTC 31 San Jose Diridon Caltrain Station\n2015-04-05 20:15:00.000000 UTC 208 San Jose Civic Center\n2015-04-07 16:02:00.000000 UTC 715 San Jose Diridon Caltrain Station\n2015-04-07 16:02:00.000000 UTC 695 San Jose Diridon Caltrain Station\n2015-04-08 16:44:00.000000 UTC 218 San Jose Diridon Caltrain Station\n2015-04-08 16:44:00.000000 UTC 307 San Jose Diridon Caltrain Station\n2015-04-08 16:44:00.000000 UTC 126 San Jose Diridon Caltrain Station\n2015-04-09 08:22:00.000000 UTC 180 San Jose Diridon Caltrain Station\n2015-04-10 07:09:00.000000 UTC 120 San Jose Civic Center\n2015-04-10 07:09:00.000000 UTC 227 San Jose Civic Center\n2015-04-10 11:22:00.000000 UTC 64 San Jose Civic Center\n2015-04-10 12:36:00.000000 UTC 690 San Jose Diridon Caltrain Station\n2015-04-10 12:37:00.000000 UTC 81 San Jose Diridon Caltrain Station\n2015-04-10 18:52:00.000000 UTC 13 Paseo de San Antonio\n2015-04-15 13:02:00.000000 UTC 138 San Jose Civic Center\n2015-04-16 20:24:00.000000 UTC 178 Japantown\n2015-04-17 17:25:00.000000 UTC 117 Japantown\n2015-04-17 18:54:00.000000 UTC 692 San Salvador at 1st\n2015-04-18 17:06:00.000000 UTC 692 San Salvador at 1st\n2015-04-18 18:16:00.000000 UTC 138 San Jose Civic Center\n2015-04-20 16:58:00.000000 UTC 43 San Pedro Square\n2015-04-22 17:46:00.000000 UTC 83 San Pedro Square\n2015-04-23 19:36:00.000000 UTC 123 San Jose Diridon Caltrain Station\n2015-04-25 16:32:00.000000 UTC 253 San Jose Diridon Caltrain Station\n2015-04-25 16:32:00.000000 UTC 147 San Jose Diridon Caltrain Station\n2015-04-27 22:24:00.000000 UTC 72 Paseo de San Antonio\n2015-04-29 18:36:00.000000 UTC 227 San Jose Civic Center\n2015-04-29 18:37:00.000000 UTC 119 San Jose Civic Center\n2015-04-30 13:11:00.000000 UTC 208 San Jose Civic Center\n2015-04-30 13:11:00.000000 UTC 119 San Jose Civic Center\n2015-05-01 10:48:00.000000 UTC 17 Paseo de San Antonio\n2015-05-01 15:08:00.000000 UTC 120 San Jose Civic Center\n2015-05-01 18:28:00.000000 UTC 696 San Salvador at 1st\n2015-05-02 12:56:00.000000 UTC 242 San Pedro Square\n2015-05-03 14:03:00.000000 UTC 242 San Jose Diridon Caltrain Station\n2015-05-03 15:35:00.000000 UTC 39 San Jose Diridon Caltrain Station\n2015-05-06 12:35:00.000000 UTC 83 San Jose Civic Center\n2015-05-08 19:47:00.000000 UTC 674 San Salvador at 1st\n2015-05-09 20:59:00.000000 UTC 146 San Jose Civic Center\n2015-05-13 16:34:00.000000 UTC 159 San Jose Civic Center\n2015-05-13 16:34:00.000000 UTC 211 San Jose Civic Center\n2015-05-14 09:10:00.000000 UTC 213 San Jose Diridon Caltrain Station\n2015-05-16 08:45:00.000000 UTC 155 San Jose Civic Center\n2015-05-16 16:45:00.000000 UTC 192 San Jose Civic Center\n2015-05-17 13:52:00.000000 UTC 65 Paseo de San Antonio\n2015-05-17 16:26:00.000000 UTC 666 San Jose Civic Center\n2015-05-18 07:58:00.000000 UTC 698 San Pedro Square\n2015-05-19 12:34:00.000000 UTC 239 San Jose Civic Center\n2015-05-19 18:10:00.000000 UTC 144 San Jose Civic Center\n2015-05-20 07:03:00.000000 UTC 211 San Jose Civic Center\n2015-05-22 13:01:00.000000 UTC 242 San Jose Civic Center\n2015-05-22 17:03:00.000000 UTC 663 San Salvador at 1st\n2015-05-23 15:34:00.000000 UTC 143 San Jose Diridon Caltrain Station\n2015-05-23 17:28:00.000000 UTC 79 San Jose Civic Center\n2015-05-24 15:51:00.000000 UTC 93 San Jose Civic Center\n2015-05-24 15:51:00.000000 UTC 88 San Jose Civic Center\n2015-05-25 17:13:00.000000 UTC 123 Paseo de San Antonio\n2015-05-28 09:29:00.000000 UTC 136 Santa Clara at Almaden\n2015-05-29 09:12:00.000000 UTC 643 Santa Clara at Almaden\n2015-06-03 09:12:00.000000 UTC 638 Santa Clara at Almaden\n2015-06-03 14:35:00.000000 UTC 99 San Jose Diridon Caltrain Station\n2015-06-04 09:10:00.000000 UTC 83 Santa Clara at Almaden\n2015-06-05 17:28:00.000000 UTC 190 San Jose Diridon Caltrain Station\n2015-06-05 18:35:00.000000 UTC 245 San Jose Civic Center\n2015-06-06 15:41:00.000000 UTC 679 San Jose Civic Center\n2015-06-07 19:35:00.000000 UTC 163 San Jose Civic Center\n2015-06-10 09:39:00.000000 UTC 692 San Jose Civic Center\n2015-06-10 21:20:00.000000 UTC 93 San Jose Civic Center\n2015-06-10 21:20:00.000000 UTC 91 San Jose Civic Center\n2015-06-11 14:43:00.000000 UTC 679 San Jose Civic Center\n2015-06-12 08:42:00.000000 UTC 205 Adobe on Almaden\n2015-06-12 14:06:00.000000 UTC 227 San Salvador at 1st\n2015-06-12 17:05:00.000000 UTC 95 San Salvador at 1st\n2015-06-12 17:05:00.000000 UTC 245 San Salvador at 1st\n2015-06-14 14:57:00.000000 UTC 91 San Jose Civic Center\n2015-06-14 15:33:00.000000 UTC 174 San Jose Civic Center\n2015-06-14 18:41:00.000000 UTC 174 San Jose Diridon Caltrain Station\n2015-06-16 14:23:00.000000 UTC 90 San Jose Civic Center\n2015-06-18 10:25:00.000000 UTC 23 Santa Clara at Almaden\n2015-06-20 12:19:00.000000 UTC 32 San Jose Civic Center\n2015-06-20 12:34:00.000000 UTC 32 San Jose Diridon Caltrain Station\n2015-06-20 17:01:00.000000 UTC 138 San Jose Diridon Caltrain Station\n2015-06-25 12:42:00.000000 UTC 95 San Jose Diridon Caltrain Station\n2015-06-25 12:43:00.000000 UTC 117 San Jose Diridon Caltrain Station\n2015-06-27 12:17:00.000000 UTC 247 San Jose Civic Center\n2015-06-27 12:43:00.000000 UTC 55 San Jose Civic Center\n2015-06-27 17:43:00.000000 UTC 150 San Pedro Square\n2015-06-27 17:43:00.000000 UTC 264 San Pedro Square\n2015-06-29 11:49:00.000000 UTC 155 San Jose Civic Center\n2015-06-29 11:49:00.000000 UTC 174 San Jose Civic Center\n2015-06-29 14:00:00.000000 UTC 174 San Jose Diridon Caltrain Station\n2015-06-29 14:00:00.000000 UTC 47 San Jose Diridon Caltrain Station\n2015-06-30 13:28:00.000000 UTC 217 San Jose Civic Center\n2015-06-30 13:28:00.000000 UTC 155 San Jose Civic Center\n2015-06-30 21:06:00.000000 UTC 700 San Jose Diridon Caltrain Station\n2015-07-03 06:42:00.000000 UTC 30 San Jose Civic Center\n2015-07-05 19:39:00.000000 UTC 174 San Jose Diridon Caltrain Station\n2015-07-08 11:12:00.000000 UTC 247 San Jose Civic Center\n2015-07-11 12:23:00.000000 UTC 680 Japantown\n2015-07-11 16:09:00.000000 UTC 231 Paseo de San Antonio\n2015-07-12 13:50:00.000000 UTC 660 San Jose Civic Center\n2015-07-12 15:35:00.000000 UTC 660 San Jose Civic Center\n2015-07-12 15:45:00.000000 UTC 155 San Jose Civic Center\n2015-07-12 15:46:00.000000 UTC 178 San Jose Civic Center\n2015-07-13 00:55:00.000000 UTC 155 San Jose Civic Center\n2015-07-13 17:00:00.000000 UTC 99 San Jose Civic Center\n2015-07-15 12:41:00.000000 UTC 104 San Jose Civic Center\n2015-07-15 12:41:00.000000 UTC 157 San Jose Civic Center\n2015-07-16 17:34:00.000000 UTC 150 San Jose Civic Center\n2015-07-16 18:33:00.000000 UTC 667 San Jose Civic Center\n2015-07-18 13:00:00.000000 UTC 183 San Pedro Square\n2015-07-18 13:51:00.000000 UTC 213 San Pedro Square\n2015-07-18 13:51:00.000000 UTC 641 San Pedro Square\n2015-07-18 15:17:00.000000 UTC 150 San Jose Diridon Caltrain Station\n2015-07-19 19:09:00.000000 UTC 25 San Pedro Square\n2015-07-20 18:33:00.000000 UTC 712 San Jose Civic Center\n2015-07-21 07:51:00.000000 UTC 304 San Jose Diridon Caltrain Station\n2015-07-21 18:29:00.000000 UTC 54 San Jose Civic Center\n2015-07-23 07:54:00.000000 UTC 54 San Jose Diridon Caltrain Station\n2015-07-23 18:49:00.000000 UTC 54 San Jose Civic Center\n2015-07-23 20:25:00.000000 UTC 247 San Jose Diridon Caltrain Station\n2015-07-28 19:52:00.000000 UTC 47 San Jose Civic Center\n2015-07-29 16:22:00.000000 UTC 65 San Jose Civic Center\n2015-07-29 16:24:00.000000 UTC 65 San Jose Civic Center\n2015-07-29 21:43:00.000000 UTC 668 San Jose Diridon Caltrain Station\n2015-08-09 16:37:00.000000 UTC 176 San Jose Diridon Caltrain Station\n2015-08-15 11:02:00.000000 UTC 42 San Jose Civic Center\n2015-08-22 00:20:00.000000 UTC 38 San Jose Diridon Caltrain Station\n2015-08-23 14:19:00.000000 UTC 38 Japantown\n2015-08-25 18:47:00.000000 UTC 95 Santa Clara at Almaden\n2015-08-27 19:08:00.000000 UTC 95 Japantown\n2015-08-28 11:28:00.000000 UTC 18 San Jose Civic Center\n2015-08-30 17:14:00.000000 UTC 117 San Jose Diridon Caltrain Station\n2015-08-30 17:14:00.000000 UTC 213 San Jose Diridon Caltrain Station\n2015-09-03 08:04:00.000000 UTC 654 Adobe on Almaden\n2015-09-04 13:05:00.000000 UTC 304 San Jose Civic Center\n2015-09-04 13:06:00.000000 UTC 660 San Jose Civic Center\n2015-09-08 08:01:00.000000 UTC 71 Adobe on Almaden\n2015-09-10 13:38:00.000000 UTC 676 Santa Clara at Almaden\n2015-09-13 15:00:00.000000 UTC 701 San Salvador at 1st\n2015-09-13 19:23:00.000000 UTC 17 San Jose Civic Center\n2015-09-14 07:26:00.000000 UTC 17 San Jose Civic Center\n2015-09-16 10:25:00.000000 UTC 648 San Jose Diridon Caltrain Station\n2015-09-16 10:58:00.000000 UTC 667 San Jose Diridon Caltrain Station\n2015-09-16 13:51:00.000000 UTC 225 San Jose Diridon Caltrain Station\n2015-09-16 18:49:00.000000 UTC 78 San Jose Diridon Caltrain Station\n2015-09-17 09:33:00.000000 UTC 665 Santa Clara at Almaden\n2015-09-18 22:32:00.000000 UTC 667 Santa Clara at Almaden\n2015-09-19 12:45:00.000000 UTC 248 Adobe on Almaden\n2015-09-19 22:12:00.000000 UTC 225 Paseo de San Antonio\n2015-09-21 17:45:00.000000 UTC 299 Santa Clara at Almaden\n2015-09-23 00:17:00.000000 UTC 685 Santa Clara at Almaden\n2015-09-23 18:36:00.000000 UTC 22 Santa Clara at Almaden\n2015-09-25 08:49:00.000000 UTC 702 Paseo de San Antonio\n2015-09-26 12:59:00.000000 UTC 22 San Jose Civic Center\n2015-09-27 10:28:00.000000 UTC 42 Adobe on Almaden\n2015-10-01 14:18:00.000000 UTC 648 San Jose Civic Center\n2015-10-02 16:50:00.000000 UTC 304 Paseo de San Antonio\n2015-10-03 16:07:00.000000 UTC 150 San Jose Civic Center\n2015-10-03 17:01:00.000000 UTC 150 San Jose Diridon Caltrain Station\n2015-10-03 20:27:00.000000 UTC 297 San Jose Civic Center\n2015-10-03 20:27:00.000000 UTC 305 San Jose Civic Center\n2015-10-06 14:55:00.000000 UTC 305 San Jose Civic Center\n2015-10-06 15:16:00.000000 UTC 305 San Jose Civic Center\n2015-10-11 10:15:00.000000 UTC 696 San Jose Civic Center\n2015-10-11 12:33:00.000000 UTC 665 San Jose Civic Center\n2015-10-11 15:16:00.000000 UTC 144 San Jose Civic Center\n2015-10-16 23:28:00.000000 UTC 232 San Jose Civic Center\n2015-10-18 16:21:00.000000 UTC 162 Adobe on Almaden\n2015-10-19 19:41:00.000000 UTC 231 Japantown\n2015-10-21 12:11:00.000000 UTC 644 San Salvador at 1st\n2015-10-21 12:11:00.000000 UTC 150 San Salvador at 1st\n2015-10-23 19:41:00.000000 UTC 245 Japantown\n2015-10-27 19:36:00.000000 UTC 162 Japantown\n2015-10-29 10:58:00.000000 UTC 43 San Jose Civic Center\n2015-10-29 21:32:00.000000 UTC 132 San Jose Civic Center\n2015-10-29 21:32:00.000000 UTC 685 San Jose Civic Center\n2015-11-03 15:24:00.000000 UTC 130 San Jose Civic Center\n2015-11-03 18:08:00.000000 UTC 190 San Jose Diridon Caltrain Station\n2015-11-03 20:33:00.000000 UTC 190 Japantown\n2015-11-05 09:17:00.000000 UTC 231 Santa Clara at Almaden\n2015-11-08 14:58:00.000000 UTC 205 San Jose Civic Center\n2015-11-09 21:48:00.000000 UTC 174 San Jose Civic Center\n2015-11-09 21:48:00.000000 UTC 205 San Jose Civic Center\n2015-11-20 13:46:00.000000 UTC 54 San Jose Civic Center\n2015-11-21 00:04:00.000000 UTC 181 San Jose Civic Center\n2015-11-21 15:34:00.000000 UTC 295 San Jose Civic Center\n2015-11-22 09:48:00.000000 UTC 308 San Jose Civic Center\n2015-11-22 19:48:00.000000 UTC 667 Adobe on Almaden\n2015-11-22 19:48:00.000000 UTC 129 Adobe on Almaden\n2015-11-22 19:48:00.000000 UTC 143 Adobe on Almaden\n2015-11-24 18:19:00.000000 UTC 150 San Jose Civic Center\n2015-11-29 16:40:00.000000 UTC 701 San Salvador at 1st\n2015-11-29 18:33:00.000000 UTC 295 San Jose Diridon Caltrain Station\n2015-12-02 19:50:00.000000 UTC 130 San Jose Civic Center\n2015-12-18 15:53:00.000000 UTC 658 San Jose Civic Center\n2015-12-30 13:59:00.000000 UTC 57 San Pedro Square\n2016-01-02 12:14:00.000000 UTC 702 San Jose Civic Center\n2016-01-09 11:43:00.000000 UTC 150 San Jose Civic Center\n2016-01-09 11:43:00.000000 UTC 168 San Jose Civic Center\n2016-01-12 19:36:00.000000 UTC 156 San Jose Civic Center\n2016-01-13 09:06:00.000000 UTC 89 San Jose Diridon Caltrain Station\n2016-01-23 13:32:00.000000 UTC 297 San Jose Civic Center\n2016-01-24 14:49:00.000000 UTC 116 San Jose Diridon Caltrain Station\n2016-01-24 14:54:00.000000 UTC 712 San Jose Diridon Caltrain Station\n2016-01-24 15:53:00.000000 UTC 116 San Jose Diridon Caltrain Station\n2016-01-24 15:53:00.000000 UTC 712 San Jose Diridon Caltrain Station\n2016-01-24 15:54:00.000000 UTC 643 San Jose Diridon Caltrain Station\n2016-01-24 15:54:00.000000 UTC 692 San Jose Diridon Caltrain Station\n2016-01-24 15:54:00.000000 UTC 130 San Jose Diridon Caltrain Station\n2016-01-24 15:55:00.000000 UTC 99 San Jose Diridon Caltrain Station\n2016-01-25 15:04:00.000000 UTC 99 San Jose Diridon Caltrain Station\n2016-01-27 17:34:00.000000 UTC 125 San Jose Civic Center\n2016-02-07 12:57:00.000000 UTC 22 San Pedro Square\n2016-02-12 02:31:00.000000 UTC 11 San Jose Diridon Caltrain Station\n2016-02-14 11:27:00.000000 UTC 128 San Jose Civic Center\n2016-02-14 16:00:00.000000 UTC 248 San Jose Civic Center\n2016-02-14 17:15:00.000000 UTC 656 San Pedro Square\n2016-02-16 13:52:00.000000 UTC 661 Paseo de San Antonio\n2016-02-17 17:47:00.000000 UTC 124 Japantown\n2016-02-18 14:54:00.000000 UTC 660 Adobe on Almaden\n2016-02-20 15:30:00.000000 UTC 229 San Jose Civic Center\n2016-02-20 15:31:00.000000 UTC 99 San Jose Civic Center\n2016-02-20 15:31:00.000000 UTC 11 San Jose Civic Center\n2016-02-21 16:28:00.000000 UTC 60 San Jose Diridon Caltrain Station\n2016-02-21 16:28:00.000000 UTC 295 San Jose Diridon Caltrain Station\n2016-02-21 20:13:00.000000 UTC 88 San Jose Diridon Caltrain Station\n2016-02-23 11:50:00.000000 UTC 156 San Jose Civic Center\n2016-02-24 15:50:00.000000 UTC 655 San Jose Civic Center\n2016-02-25 16:58:00.000000 UTC 305 San Jose Civic Center\n2016-02-26 14:11:00.000000 UTC 229 San Jose Civic Center\n2016-02-27 10:23:00.000000 UTC 667 San Jose Civic Center\n" ], [ "current_bike_locations = redis.Redis(host='redis', port='6379')\ncurrent_bike_locations.keys()", "_____no_output_____" ], [ "for trip in date_sorted_trips.itertuples():\n current_bike_locations.set(trip.bike_number, trip.end_station_name)", "_____no_output_____" ], [ "current_bike_locations.keys()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
cbdf9cbc5fcec61fd94713ea577b334683f78ebf
1,840
ipynb
Jupyter Notebook
notebooks/Notebook_Template.ipynb
dopplerdaver/python-explorations
a3b0448348798cfe9d40903b18bfd1064973138e
[ "MIT" ]
1
2021-04-05T17:20:22.000Z
2021-04-05T17:20:22.000Z
notebooks/Notebook_Template.ipynb
dopplerdaver/python-explorations
a3b0448348798cfe9d40903b18bfd1064973138e
[ "MIT" ]
6
2021-11-05T18:29:26.000Z
2021-11-09T21:13:54.000Z
notebooks/Notebook_Template.ipynb
dopplerdaver/python-explorations
a3b0448348798cfe9d40903b18bfd1064973138e
[ "MIT" ]
2
2021-03-31T13:41:06.000Z
2021-08-09T16:02:56.000Z
17.692308
71
0.509783
[ [ [ "# Sample Notebook\n\nOnce you copy this repository, feel free to delete this notebook!", "_____no_output_____" ], [ "### Imports", "_____no_output_____" ] ], [ [ "#Import something here\nimport xarray as xr\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "### Data Ingest", "_____no_output_____" ] ], [ [ "# Read in the data using xarray or some other package\nds = xr.open_dataset('some_file.nc')", "_____no_output_____" ] ], [ [ "### Data Operation", "_____no_output_____" ] ], [ [ "# Do some sort of calculation on the data\nsome_calc = ds.temp * some_equation", "_____no_output_____" ] ], [ [ "### Data Visualization", "_____no_output_____" ] ], [ [ "# Plot the data\nplt.plot(x, y)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbdf9f931a9685d664f2ca778365bb54de4d5f0c
160,356
ipynb
Jupyter Notebook
E_commerce_website_expenditure.ipynb
bafnayash/E-commerce_website_expenditure
36357c9d6b22e67904a25655af6535525db0d7d1
[ "MIT" ]
null
null
null
E_commerce_website_expenditure.ipynb
bafnayash/E-commerce_website_expenditure
36357c9d6b22e67904a25655af6535525db0d7d1
[ "MIT" ]
null
null
null
E_commerce_website_expenditure.ipynb
bafnayash/E-commerce_website_expenditure
36357c9d6b22e67904a25655af6535525db0d7d1
[ "MIT" ]
null
null
null
152.574691
30,980
0.872216
[ [ [ "# Amount Spend by a User on an E-Commerce Website\nIn this machine learning project, I have collected the dataset from Kaggle (https://www.kaggle.com/iyadavvaibhav/ecommerce-customer-device-usage?select=Ecommerce+Customers) and I will be using Machine Learning to make predictions of amount spent by a user on E-commerce Website. Later, in order to apply the information gained in this study in real life, a GUI application was made using tkinter of python which takes in required parameters from the user and then displays the predcited amount spent by the user on E-commerce Website.", "_____no_output_____" ], [ "## Importing Libraries", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.compose import TransformedTargetRegressor\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import RandomForestRegressor", "_____no_output_____" ] ], [ [ "## Loading Dataset\nNow I will load the dataset which I have stored in the local directory with the name 'Ecommerce_customers'.", "_____no_output_____" ] ], [ [ "#Loading dataset\ndataset = pd.read_csv(\"Ecommerce_customers\")", "_____no_output_____" ] ], [ [ "## Data Exploration", "_____no_output_____" ] ], [ [ "print(f\"Dimensions of dataset: {dataset.shape}\")", "Dimensions of dataset: (500, 8)\n" ], [ "dataset.head()", "_____no_output_____" ], [ "dataset.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 500 entries, 0 to 499\nData columns (total 8 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Email 500 non-null object \n 1 Address 500 non-null object \n 2 Avatar 500 non-null object \n 3 Avg. Session Length 500 non-null float64\n 4 Time on App 500 non-null float64\n 5 Time on Website 500 non-null float64\n 6 Length of Membership 500 non-null float64\n 7 Yearly Amount Spent 500 non-null float64\ndtypes: float64(5), object(3)\nmemory usage: 31.4+ KB\n" ], [ "print(\"Statistics of dataset: \")\ndataset.describe()", "Statistics of dataset: \n" ] ], [ [ "## Data Visualization\nIn order to better understand the data, I will be using data visualization techniques like histogram and heatmaps.", "_____no_output_____" ] ], [ [ "#Histogram\nplt.figure(figsize = (20,20))\ndataset.hist()", "_____no_output_____" ], [ "#Heatmap\ncorrelation_matrix = dataset.corr().round(2)\nsns.heatmap(data = correlation_matrix, annot = True)", "_____no_output_____" ] ], [ [ "## Data Pre-Processing\nAs the columns of email, address and avatar do not affect the target variable, we do not include them in the list of independent variables. Here, we will split the dataset into independent and dependent variables and then split it into train and test data.", "_____no_output_____" ] ], [ [ "X = dataset.values[:,3:7]\nY = dataset.values[:, 7:]\nprint(f\"Shape of X: {X.shape}\")\nprint(f\"Shape of Y: {Y.shape}\")\n#Splitting the dataset into train and test data\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=0)", "Shape of X: (500, 4)\nShape of Y: (500, 1)\n" ] ], [ [ "## Machine Learning Models", "_____no_output_____" ], [ "#### Linear Regression Model", "_____no_output_____" ] ], [ [ "lrm = TransformedTargetRegressor(regressor = LinearRegression(), transformer = StandardScaler())\nlrm.fit(X_train, Y_train)\npredict = lrm.predict(X_test)\nlrm_score = mean_squared_error(Y_test, predict)\n#out = np.concatenate((Y_test, predict), axis=1)\n#print(out)", "_____no_output_____" ], [ "print(\"The mean square error for Linear Regression Model is %.2f.\" %(lrm_score.round(2)))", "The mean square error for Linear Regression Model is 92.89.\n" ] ], [ [ "#### Polynomial Regression Model", "_____no_output_____" ] ], [ [ "polynomial_scores = []\nfor i in range(2,6):\n polynomial = PolynomialFeatures(degree = i)\n X_poly_train = polynomial.fit_transform(X_train)\n X_poly_test = polynomial.fit_transform(X_test)\n prm = TransformedTargetRegressor(regressor = LinearRegression(), transformer = StandardScaler())\n prm.fit(X_poly_train, Y_train)\n predict = prm.predict(X_poly_test)\n polynomial_scores.append(mean_squared_error(Y_test, predict))\npmr_score = polynomial_scores[0]", "_____no_output_____" ], [ "#Plotting the graph between different degree of polynomial vs mean square error\nplt.figure(figsize = (10, 10))\nplt.plot([i for i in range(2,6)], polynomial_scores, color = 'red')\nfor i in range(2,6):\n plt.text(i, polynomial_scores[i-2], (i, polynomial_scores[i-2].round(2)))\nplt.xticks([i for i in range(1,6)])\nplt.xlabel(\"Degree of Polynomial\")\nplt.ylabel(\"Mean Square Error\")\nplt.title(\"Polynomial Regression Model Scores for different degree of polynomial\")\nplt.show()", "_____no_output_____" ], [ "print(\"The mean square error for Polynomial Regression Model is %.2f.\" %(polynomial_scores[0].round(2)))", "The mean square error for Polynomial Regression Model is 100.89.\n" ] ], [ [ "#### Support Vector Regression Model", "_____no_output_____" ] ], [ [ "svr_scores = []\nkernels = ['linear', 'poly', 'rbf', 'sigmoid']\nfor i in range(len(kernels)):\n svr = TransformedTargetRegressor(regressor = SVR(kernel = kernels[i]), transformer = StandardScaler())\n svr.fit(X_train, Y_train)\n predict = svr.predict(X_test)\n svr_scores.append(mean_squared_error(Y_test, predict))", "_____no_output_____" ], [ "#Plotting the bar grapgh for Support Vector Classifier for different kernels vs mean square error\nplt.figure(figsize=(10,10))\nplt.bar(kernels, svr_scores, color=['black', 'yellow', 'red', 'grey'])\nfor i in range(len(kernels)):\n plt.text(i, svr_scores[i], (svr_scores[i].round(2)))\nplt.title('Support Vector Regression Model scores for different Kernels')\nplt.xlabel('Kernels')\nplt.ylabel('Mean Square Error')\nsvr_score = svr_scores[0]", "_____no_output_____" ], [ "print(\"The mean square error for Support Vector Regression Model is {} with {} kernel.\".format(svr_scores[0].round(2), 'linear'))", "The mean square error for Support Vector Regression Model is 93.36 with linear kernel.\n" ] ], [ [ "#### Random Forest Regression Model", "_____no_output_____" ] ], [ [ "rf_scores = []\nestimators = [1, 10, 50 ,100, 500, 1000, 5000]\nfor i in range(len(estimators)):\n rf = TransformedTargetRegressor(regressor = RandomForestRegressor(n_estimators = estimators[i]), transformer = StandardScaler())\n rf.fit(X_train, Y_train)\n predict = rf.predict(X_test)\n rf_scores.append(mean_squared_error(Y_test, predict))", "_____no_output_____" ], [ "#Plotting the bar graph for Random Forest Regression Model scores for different kernels\nplt.figure(figsize=(10,10))\nplt.bar([i for i in range(len(estimators))], rf_scores, color=['grey', 'maroon', 'purple', 'red', 'yellow', 'blue', 'black'], width=0.8)\nfor i in range(len(estimators)):\n plt.text(i, rf_scores[i], (estimators[i], rf_scores[i].round(2)))\nplt.xticks([i for i in range(len(estimators))], labels=[str(estimators[i] for i in estimators)])\nplt.title('Random Forest Regression Model score for different number of estimators')\nplt.xlabel('Number of Estimators')\nplt.ylabel('Mean Square Error')\nrf_score = rf_scores[6]", "_____no_output_____" ], [ "print(\"The mean sqaure error for Random Forest Regression Model is {} with {} estimators.\".format(rf_scores[6].round(2), 5000))", "The mean sqaure error for Random Forest Regression Model is 575.07 with 5000 estimators.\n" ] ], [ [ "## Final Scores", "_____no_output_____" ] ], [ [ "print(\"The mean square error for Linear Regression Model is %.2f.\" %(lrm_score.round(2)))\nprint(\"The mean square error for Polynomial Regression Model is %.2f.\" %(polynomial_scores[0].round(2)))\nprint(\"The mean square error for Support Vector Regression Model is {} with {} kernel.\".format(svr_scores[0].round(2), 'linear'))\nprint(\"The mean sqaure error for Random Forest Regression Model is {} with {} estimators.\".format(rf_scores[6].round(2), 5000))", "The mean square error for Linear Regression Model is 92.89.\nThe mean square error for Polynomial Regression Model is 100.89.\nThe mean square error for Support Vector Regression Model is 93.36 with linear kernel.\nThe mean sqaure error for Random Forest Regression Model is 575.07 with 5000 estimators.\n" ] ], [ [ "## Conclusion\nIn this project, I applied machine learning models to predict the amount spent by a user on an E-Commerce Website. After importing the data, I used data visualization techniques for data exploration. Then, I applied 4 machine learning models namely Linear Regressor, Polynomial Regressor, Support Vector Regressor and Random Forest Regressor. I varied parameters in each model to achieve best scores. Finally, Linear Regression Model achieved the least mean square error of 92.89.", "_____no_output_____" ], [ "#### Final Model", "_____no_output_____" ] ], [ [ "final_model = TransformedTargetRegressor(regressor = LinearRegression(), transformer = StandardScaler())\nfinal_model.fit(X_train, Y_train)\npredict = final_model.predict(X_test)\nfinal_model_score = mean_squared_error(Y_test, predict)\nprint(f\"Model Mean Square Error: {final_model_score.round(2)}\")", "Model Mean Square Error: 92.89\n" ] ], [ [ "#### Predictor Function\nCreating a function that will later be used to predict the amount spent by a user on an E-Commerce Webiste using Linear Regression model.", "_____no_output_____" ] ], [ [ "def predict_now(lis):\n lis = pd.DataFrame(lis)\n return final_model.predict(lis).item()\n#lis = {'Avg. Session Length': [34.497268], 'Time on App': [12.655651], 'Time on Website': [39.577668], 'Length of Membership': [4.082621]}\n#predict_now(lis)", "_____no_output_____" ] ], [ [ "## Amount Spent on E-Commerce Website Predictor Application\nIn order to use the above created machine learning model to predict the amount spent by a user on an E-Commerce Webiste using Linear Regression model, we need to build a Graphical User Interface (GUI) wherein the user can enter the required data and get a prediction. I have done this using tkinter GUI of python.", "_____no_output_____" ], [ "#### Importing Libraries", "_____no_output_____" ] ], [ [ "import tkinter as tk\nfrom tkinter import ttk", "_____no_output_____" ] ], [ [ "#### Defining Required Functions", "_____no_output_____" ] ], [ [ "def submit(*args):\n try:\n final = {\n 'Avg. Session Length': [float(user4.get())], \n 'Time on App': [float(user5.get())], \n 'Time on Website': [float(user6.get())], \n 'Length of Membership': [float(user7.get())],\n }\n result = predict_now(final)\n this.set(f\"Predicted amount spent by the user on E-Commerce Website is {result}\")\n except ValueError:\n pass", "_____no_output_____" ] ], [ [ "#### Setting Up the Window", "_____no_output_____" ] ], [ [ "try: \n from ctypes import windll\n windll.shcore.SetProcessDPIAwareness(1)\nexcept:\n pass\n\nroot = tk.Tk()\nroot.title(\"Heart Disease Predictor\")\n\nuser1 = tk.StringVar()\nuser2 = tk.StringVar()\nuser3 = tk.StringVar()\nuser4 = tk.StringVar()\nuser5 = tk.StringVar()\nuser6 = tk.StringVar()\nuser7 = tk.StringVar()\nthis = tk.StringVar(value = \"Submit to get the result.\")\n\nmain = ttk.Frame(root, padding = (30, 10))\nmain.grid()", "_____no_output_____" ] ], [ [ "#### Declaring Widgets", "_____no_output_____" ] ], [ [ "label1 = ttk.Label(main, text = \"Enter the following details: \")\nlabel1.configure(font=(\"helvetica\", 15))\nlabel1.grid(row = 0, column = 0, sticky = \"w\")\n\nentry1 = ttk.Label(main, text = \"Email: \")\nuser_input1 = ttk.Entry(main, width = 20, textvariable = user1)\n\nentry2 = ttk.Label(main, text = \"Address: \")\nuser_input2 = ttk.Entry(main, width = 50, textvariable = user2)\n\nentry3 = ttk.Label(main, text = \"Avatar: \")\nuser_input3 = ttk.Entry(main, width = 20, textvariable = user3)\n\nentry4 = ttk.Label(main, text = \"Avg. Session Length: \")\nuser_input4 = ttk.Entry(main, width = 10, textvariable = user4)\n\nentry5 = ttk.Label(main, text = \"Time on App: \")\nuser_input5 = ttk.Entry(main, width = 10, textvariable = user5)\n\nentry6 = ttk.Label(main, text = \"Time on Website: \")\nuser_input6 = ttk.Entry(main, width = 10, textvariable = user6)\n\nentry7 = ttk.Label(main, text = \"Length of Membership: \")\nuser_input7 = ttk.Entry(main, width = 10, textvariable = user7)\n\nbutton = ttk.Button(main, text = \"Submit\", command = submit)\n\nout = ttk.Label(main, textvariable = this)", "_____no_output_____" ] ], [ [ "#### Displaying the Widgets", "_____no_output_____" ] ], [ [ "entry1.grid(row = 1, column = 0, sticky = \"w\", padx = 10, pady = 10)\nuser_input1.grid(row = 1, column = 1, sticky = \"ew\", padx = 10, pady = 10, columnspan = 4)\nuser_input1.focus()\n\nentry2.grid(row = 2, column = 0, sticky = \"w\", padx = 10, pady = 10)\nuser_input2.grid(row = 2, column = 1, sticky = \"ew\", padx = 10, pady = 10)\n\nentry3.grid(row = 3, column = 0, sticky = \"w\", padx = 10, pady = 10)\nuser_input3.grid(row = 3, column = 1, sticky = \"ew\", padx = 10, pady = 10)\n\nentry4.grid(row = 4, column = 0, sticky = \"w\", padx = 10, pady = 10)\nuser_input4.grid(row = 4, column = 1, sticky = \"ew\", padx = 10, pady = 10, columnspan = 4)\n\nentry5.grid(row = 5, column = 0, sticky = \"w\", padx = 10, pady = 10)\nuser_input5.grid(row = 5, column = 1, sticky = \"ew\", padx = 10, pady = 10, columnspan = 4)\n\nentry6.grid(row = 6, column = 0, sticky = \"w\", padx = 10, pady = 10)\nuser_input6.grid(row = 6, column = 1, sticky = \"ew\", padx = 10, pady = 10)\n\nentry7.grid(row = 7, column = 0, sticky = \"w\", padx = 10, pady = 10)\nuser_input7.grid(row = 7, column = 1, sticky = \"ew\", padx = 10, pady = 10)\n\nbutton.grid(row = 8, column = 0, columnspan = 2, sticky = \"ew\", padx = 10, pady = 10)\n\nout.grid(row = 9, column = 0, columnspan = 2)\n\nroot.mainloop()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbdfa2e8c7f20a846c60e42bbbc0567e6307e824
204,826
ipynb
Jupyter Notebook
examples/bcnllloss.ipynb
microsoft/BackwardCompatibilityML
5910e485453f07fd5c85114d15c423c5db521122
[ "MIT" ]
54
2020-09-11T18:36:59.000Z
2022-03-29T00:47:55.000Z
examples/bcnllloss.ipynb
microsoft/BackwardCompatibilityML
5910e485453f07fd5c85114d15c423c5db521122
[ "MIT" ]
115
2020-10-08T16:55:34.000Z
2022-03-12T00:50:21.000Z
examples/bcnllloss.ipynb
microsoft/BackwardCompatibilityML
5910e485453f07fd5c85114d15c423c5db521122
[ "MIT" ]
11
2020-10-04T09:40:11.000Z
2021-12-21T21:03:33.000Z
226.077263
30,532
0.896624
[ [ [ "import torch\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nimport random\n\nimport backwardcompatibilityml.loss as bcloss\nimport backwardcompatibilityml.scores as scores\n\n# Initialize random seed\nrandom.seed(123)\ntorch.manual_seed(456)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\n%matplotlib inline", "_____no_output_____" ], [ "n_epochs = 3\nbatch_size_train = 64\nbatch_size_test = 1000\nlearning_rate = 0.01\nmomentum = 0.5\nlog_interval = 10\n\ntorch.backends.cudnn.enabled = False", "_____no_output_____" ], [ "train_loader = list(torch.utils.data.DataLoader(\n torchvision.datasets.MNIST('datasets/', train=True, download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ])),\n batch_size=batch_size_train, shuffle=True))\n\ntest_loader = list(torch.utils.data.DataLoader(\n torchvision.datasets.MNIST('datasets/', train=False, download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ])),\n batch_size=batch_size_test, shuffle=True))", "_____no_output_____" ], [ "train_loader_a = train_loader[:int(len(train_loader)/2)]\ntrain_loader_b = train_loader[int(len(train_loader)/2):]", "_____no_output_____" ], [ "fig = plt.figure()\nfor i in range(6):\n plt.subplot(2,3,i+1)\n plt.tight_layout()\n plt.imshow(train_loader_a[0][0][i][0], cmap='gray', interpolation='none')\n plt.title(\"Ground Truth: {}\".format(train_loader_a[0][1][i]))\n plt.xticks([])\n plt.yticks([])\nfig", "_____no_output_____" ], [ "class Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(320, 50)\n self.fc2 = nn.Linear(50, 10)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, 320)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return x, F.softmax(x, dim=1), F.log_softmax(x, dim=1)", "_____no_output_____" ], [ "network = Net()\noptimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum)", "_____no_output_____" ], [ "train_losses = []\ntrain_counter = []\ntest_losses = []\ntest_counter = [i*len(train_loader_a)*batch_size_train for i in range(n_epochs + 1)]", "_____no_output_____" ], [ "def train(epoch):\n network.train()\n for batch_idx, (data, target) in enumerate(train_loader_a):\n optimizer.zero_grad()\n _, _, output = network(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader_a)*batch_size_train,\n 100. * batch_idx / len(train_loader_a), loss.item()))\n train_losses.append(loss.item())\n train_counter.append(\n (batch_idx*64) + ((epoch-1)*len(train_loader_a)*batch_size_train))", "_____no_output_____" ], [ "def test():\n network.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n _, _, output = network(data)\n test_loss += F.nll_loss(output, target, reduction=\"sum\").item()\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).sum()\n test_loss /= len(train_loader_a)*batch_size_train\n test_losses.append(test_loss)\n print('\\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(train_loader_a)*batch_size_train,\n 100. * correct / (len(train_loader_a)*batch_size_train)))", "_____no_output_____" ], [ "test()\nfor epoch in range(1, n_epochs + 1):\n train(epoch)\n test()", "\nTest set: Avg. loss: 0.7645, Accuracy: 1359/30016 (5%)\n\nTrain Epoch: 1 [0/30016 (0%)]\tLoss: 2.338004\nTrain Epoch: 1 [640/30016 (2%)]\tLoss: 2.281939\nTrain Epoch: 1 [1280/30016 (4%)]\tLoss: 2.274189\nTrain Epoch: 1 [1920/30016 (6%)]\tLoss: 2.249804\nTrain Epoch: 1 [2560/30016 (9%)]\tLoss: 2.218965\nTrain Epoch: 1 [3200/30016 (11%)]\tLoss: 2.199637\nTrain Epoch: 1 [3840/30016 (13%)]\tLoss: 2.167684\nTrain Epoch: 1 [4480/30016 (15%)]\tLoss: 2.119798\nTrain Epoch: 1 [5120/30016 (17%)]\tLoss: 2.025222\nTrain Epoch: 1 [5760/30016 (19%)]\tLoss: 1.932501\nTrain Epoch: 1 [6400/30016 (21%)]\tLoss: 1.671945\nTrain Epoch: 1 [7040/30016 (23%)]\tLoss: 1.561831\nTrain Epoch: 1 [7680/30016 (26%)]\tLoss: 1.626387\nTrain Epoch: 1 [8320/30016 (28%)]\tLoss: 1.685211\nTrain Epoch: 1 [8960/30016 (30%)]\tLoss: 1.400331\nTrain Epoch: 1 [9600/30016 (32%)]\tLoss: 1.427622\nTrain Epoch: 1 [10240/30016 (34%)]\tLoss: 0.989379\nTrain Epoch: 1 [10880/30016 (36%)]\tLoss: 1.192472\nTrain Epoch: 1 [11520/30016 (38%)]\tLoss: 1.240278\nTrain Epoch: 1 [12160/30016 (41%)]\tLoss: 1.094558\nTrain Epoch: 1 [12800/30016 (43%)]\tLoss: 1.126665\nTrain Epoch: 1 [13440/30016 (45%)]\tLoss: 0.786467\nTrain Epoch: 1 [14080/30016 (47%)]\tLoss: 0.961599\nTrain Epoch: 1 [14720/30016 (49%)]\tLoss: 0.717606\nTrain Epoch: 1 [15360/30016 (51%)]\tLoss: 0.923883\nTrain Epoch: 1 [16000/30016 (53%)]\tLoss: 0.835599\nTrain Epoch: 1 [16640/30016 (55%)]\tLoss: 0.820179\nTrain Epoch: 1 [17280/30016 (58%)]\tLoss: 1.214673\nTrain Epoch: 1 [17920/30016 (60%)]\tLoss: 0.545910\nTrain Epoch: 1 [18560/30016 (62%)]\tLoss: 0.864912\nTrain Epoch: 1 [19200/30016 (64%)]\tLoss: 1.045161\nTrain Epoch: 1 [19840/30016 (66%)]\tLoss: 0.737489\nTrain Epoch: 1 [20480/30016 (68%)]\tLoss: 0.576639\nTrain Epoch: 1 [21120/30016 (70%)]\tLoss: 0.706978\nTrain Epoch: 1 [21760/30016 (72%)]\tLoss: 0.708799\nTrain Epoch: 1 [22400/30016 (75%)]\tLoss: 0.598541\nTrain Epoch: 1 [23040/30016 (77%)]\tLoss: 0.870604\nTrain Epoch: 1 [23680/30016 (79%)]\tLoss: 0.716791\nTrain Epoch: 1 [24320/30016 (81%)]\tLoss: 0.696189\nTrain Epoch: 1 [24960/30016 (83%)]\tLoss: 0.651915\nTrain Epoch: 1 [25600/30016 (85%)]\tLoss: 0.746274\nTrain Epoch: 1 [26240/30016 (87%)]\tLoss: 0.463703\nTrain Epoch: 1 [26880/30016 (90%)]\tLoss: 0.636440\nTrain Epoch: 1 [27520/30016 (92%)]\tLoss: 0.778516\nTrain Epoch: 1 [28160/30016 (94%)]\tLoss: 0.637036\nTrain Epoch: 1 [28800/30016 (96%)]\tLoss: 0.829187\nTrain Epoch: 1 [29440/30016 (98%)]\tLoss: 0.561778\n\nTest set: Avg. loss: 0.0993, Accuracy: 9171/30016 (31%)\n\nTrain Epoch: 2 [0/30016 (0%)]\tLoss: 0.611573\nTrain Epoch: 2 [640/30016 (2%)]\tLoss: 0.685103\nTrain Epoch: 2 [1280/30016 (4%)]\tLoss: 0.856729\nTrain Epoch: 2 [1920/30016 (6%)]\tLoss: 0.519098\nTrain Epoch: 2 [2560/30016 (9%)]\tLoss: 0.601045\nTrain Epoch: 2 [3200/30016 (11%)]\tLoss: 0.542169\nTrain Epoch: 2 [3840/30016 (13%)]\tLoss: 0.590203\nTrain Epoch: 2 [4480/30016 (15%)]\tLoss: 0.535176\nTrain Epoch: 2 [5120/30016 (17%)]\tLoss: 0.604264\nTrain Epoch: 2 [5760/30016 (19%)]\tLoss: 0.699412\nTrain Epoch: 2 [6400/30016 (21%)]\tLoss: 0.469525\nTrain Epoch: 2 [7040/30016 (23%)]\tLoss: 0.458269\nTrain Epoch: 2 [7680/30016 (26%)]\tLoss: 0.676925\nTrain Epoch: 2 [8320/30016 (28%)]\tLoss: 0.671360\nTrain Epoch: 2 [8960/30016 (30%)]\tLoss: 0.663215\nTrain Epoch: 2 [9600/30016 (32%)]\tLoss: 0.678063\nTrain Epoch: 2 [10240/30016 (34%)]\tLoss: 0.329252\nTrain Epoch: 2 [10880/30016 (36%)]\tLoss: 0.597346\nTrain Epoch: 2 [11520/30016 (38%)]\tLoss: 0.701631\nTrain Epoch: 2 [12160/30016 (41%)]\tLoss: 0.436469\nTrain Epoch: 2 [12800/30016 (43%)]\tLoss: 0.484635\nTrain Epoch: 2 [13440/30016 (45%)]\tLoss: 0.334166\nTrain Epoch: 2 [14080/30016 (47%)]\tLoss: 0.391909\nTrain Epoch: 2 [14720/30016 (49%)]\tLoss: 0.508151\nTrain Epoch: 2 [15360/30016 (51%)]\tLoss: 0.416259\nTrain Epoch: 2 [16000/30016 (53%)]\tLoss: 0.356686\nTrain Epoch: 2 [16640/30016 (55%)]\tLoss: 0.406188\nTrain Epoch: 2 [17280/30016 (58%)]\tLoss: 0.717582\nTrain Epoch: 2 [17920/30016 (60%)]\tLoss: 0.322463\nTrain Epoch: 2 [18560/30016 (62%)]\tLoss: 0.713308\nTrain Epoch: 2 [19200/30016 (64%)]\tLoss: 0.486474\nTrain Epoch: 2 [19840/30016 (66%)]\tLoss: 0.370916\nTrain Epoch: 2 [20480/30016 (68%)]\tLoss: 0.453681\nTrain Epoch: 2 [21120/30016 (70%)]\tLoss: 0.339929\nTrain Epoch: 2 [21760/30016 (72%)]\tLoss: 0.503270\nTrain Epoch: 2 [22400/30016 (75%)]\tLoss: 0.363914\nTrain Epoch: 2 [23040/30016 (77%)]\tLoss: 0.569946\nTrain Epoch: 2 [23680/30016 (79%)]\tLoss: 0.385622\nTrain Epoch: 2 [24320/30016 (81%)]\tLoss: 0.560251\nTrain Epoch: 2 [24960/30016 (83%)]\tLoss: 0.700014\nTrain Epoch: 2 [25600/30016 (85%)]\tLoss: 0.483964\nTrain Epoch: 2 [26240/30016 (87%)]\tLoss: 0.375324\nTrain Epoch: 2 [26880/30016 (90%)]\tLoss: 0.397195\nTrain Epoch: 2 [27520/30016 (92%)]\tLoss: 0.387728\nTrain Epoch: 2 [28160/30016 (94%)]\tLoss: 0.463883\nTrain Epoch: 2 [28800/30016 (96%)]\tLoss: 0.671692\nTrain Epoch: 2 [29440/30016 (98%)]\tLoss: 0.200388\n\nTest set: Avg. loss: 0.0606, Accuracy: 9467/30016 (32%)\n\nTrain Epoch: 3 [0/30016 (0%)]\tLoss: 0.433216\nTrain Epoch: 3 [640/30016 (2%)]\tLoss: 0.626047\nTrain Epoch: 3 [1280/30016 (4%)]\tLoss: 0.614806\nTrain Epoch: 3 [1920/30016 (6%)]\tLoss: 0.351351\nTrain Epoch: 3 [2560/30016 (9%)]\tLoss: 0.372902\nTrain Epoch: 3 [3200/30016 (11%)]\tLoss: 0.315961\nTrain Epoch: 3 [3840/30016 (13%)]\tLoss: 0.629242\nTrain Epoch: 3 [4480/30016 (15%)]\tLoss: 0.325787\nTrain Epoch: 3 [5120/30016 (17%)]\tLoss: 0.332519\nTrain Epoch: 3 [5760/30016 (19%)]\tLoss: 0.428229\nTrain Epoch: 3 [6400/30016 (21%)]\tLoss: 0.375956\nTrain Epoch: 3 [7040/30016 (23%)]\tLoss: 0.369950\nTrain Epoch: 3 [7680/30016 (26%)]\tLoss: 0.362622\nTrain Epoch: 3 [8320/30016 (28%)]\tLoss: 0.520664\nTrain Epoch: 3 [8960/30016 (30%)]\tLoss: 0.621075\nTrain Epoch: 3 [9600/30016 (32%)]\tLoss: 0.418881\nTrain Epoch: 3 [10240/30016 (34%)]\tLoss: 0.219880\nTrain Epoch: 3 [10880/30016 (36%)]\tLoss: 0.499471\nTrain Epoch: 3 [11520/30016 (38%)]\tLoss: 0.484748\nTrain Epoch: 3 [12160/30016 (41%)]\tLoss: 0.372163\nTrain Epoch: 3 [12800/30016 (43%)]\tLoss: 0.318991\nTrain Epoch: 3 [13440/30016 (45%)]\tLoss: 0.298097\nTrain Epoch: 3 [14080/30016 (47%)]\tLoss: 0.514588\nTrain Epoch: 3 [14720/30016 (49%)]\tLoss: 0.333074\nTrain Epoch: 3 [15360/30016 (51%)]\tLoss: 0.374257\nTrain Epoch: 3 [16000/30016 (53%)]\tLoss: 0.249366\nTrain Epoch: 3 [16640/30016 (55%)]\tLoss: 0.413403\nTrain Epoch: 3 [17280/30016 (58%)]\tLoss: 0.644515\nTrain Epoch: 3 [17920/30016 (60%)]\tLoss: 0.345536\nTrain Epoch: 3 [18560/30016 (62%)]\tLoss: 0.406339\nTrain Epoch: 3 [19200/30016 (64%)]\tLoss: 0.398300\nTrain Epoch: 3 [19840/30016 (66%)]\tLoss: 0.237821\nTrain Epoch: 3 [20480/30016 (68%)]\tLoss: 0.485557\nTrain Epoch: 3 [21120/30016 (70%)]\tLoss: 0.381991\nTrain Epoch: 3 [21760/30016 (72%)]\tLoss: 0.561565\nTrain Epoch: 3 [22400/30016 (75%)]\tLoss: 0.319745\nTrain Epoch: 3 [23040/30016 (77%)]\tLoss: 0.636540\nTrain Epoch: 3 [23680/30016 (79%)]\tLoss: 0.355421\nTrain Epoch: 3 [24320/30016 (81%)]\tLoss: 0.471419\nTrain Epoch: 3 [24960/30016 (83%)]\tLoss: 0.373985\nTrain Epoch: 3 [25600/30016 (85%)]\tLoss: 0.348540\nTrain Epoch: 3 [26240/30016 (87%)]\tLoss: 0.196206\nTrain Epoch: 3 [26880/30016 (90%)]\tLoss: 0.278208\nTrain Epoch: 3 [27520/30016 (92%)]\tLoss: 0.475131\nTrain Epoch: 3 [28160/30016 (94%)]\tLoss: 0.369040\nTrain Epoch: 3 [28800/30016 (96%)]\tLoss: 0.359578\nTrain Epoch: 3 [29440/30016 (98%)]\tLoss: 0.251359\n\nTest set: Avg. loss: 0.0484, Accuracy: 9571/30016 (32%)\n\n" ], [ "fig = plt.figure()\nplt.plot(train_counter, train_losses, color='blue')\nplt.scatter(test_counter, test_losses, color='red')\nplt.legend(['Train Loss', 'Test Loss'], loc='upper right')\nplt.xlabel('number of training examples seen')\nplt.ylabel('negative log likelihood loss')\nfig", "_____no_output_____" ], [ "with torch.no_grad():\n _, _, output = network(test_loader[0][0])", "_____no_output_____" ], [ "fig = plt.figure()\nfor i in range(6):\n plt.subplot(2,3,i+1)\n plt.tight_layout()\n plt.imshow(test_loader[0][0][i][0], cmap='gray', interpolation='none')\n plt.title(\"Prediction: {}\".format(\n output.data.max(1, keepdim=True)[1][i].item()))\n plt.xticks([])\n plt.yticks([])\nfig", "_____no_output_____" ], [ "import copy\n\nh1 = copy.deepcopy(network)\nh2 = copy.deepcopy(network)\nh1.eval()\nnew_optimizer = optim.SGD(h2.parameters(), lr=learning_rate, momentum=momentum)\nlambda_c = 1.0\nbc_loss = bcloss.BCNLLLoss(h1, h2, lambda_c)", "_____no_output_____" ], [ "update_train_losses = []\nupdate_train_counter = []\nupdate_test_losses = []\nupdate_test_counter = [i*len(train_loader_b)*batch_size_train for i in range(n_epochs + 1)]", "_____no_output_____" ], [ "def train_update(epoch):\n for batch_idx, (data, target) in enumerate(train_loader_b):\n new_optimizer.zero_grad()\n loss = bc_loss(data, target)\n loss.backward()\n new_optimizer.step()\n if batch_idx % log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader_b)*batch_size_train,\n 100. * batch_idx / len(train_loader_b), loss.item()))\n update_train_losses.append(loss.item())\n update_train_counter.append(\n (batch_idx*64) + ((epoch-1)*len(train_loader_b)*batch_size_train))", "_____no_output_____" ], [ "def test_update():\n h2.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n _, _, output = h2(data)\n test_loss += F.nll_loss(output, target, reduction=\"sum\").item()\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).sum()\n test_loss /= len(train_loader_b)*batch_size_train\n update_test_losses.append(test_loss)\n print('\\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(train_loader_b)*batch_size_train,\n 100. * correct / (len(train_loader_b)*batch_size_train)))", "_____no_output_____" ], [ "test_update()\nfor epoch in range(1, n_epochs + 1):\n train_update(epoch)\n test_update()", "\nTest set: Avg. loss: 0.0484, Accuracy: 9571/30016 (32%)\n\nTrain Epoch: 1 [0/30016 (0%)]\tLoss: 0.187793\nTrain Epoch: 1 [640/30016 (2%)]\tLoss: 0.314032\nTrain Epoch: 1 [1280/30016 (4%)]\tLoss: 0.157210\nTrain Epoch: 1 [1920/30016 (6%)]\tLoss: 0.271693\nTrain Epoch: 1 [2560/30016 (9%)]\tLoss: 0.172420\nTrain Epoch: 1 [3200/30016 (11%)]\tLoss: 0.154311\nTrain Epoch: 1 [3840/30016 (13%)]\tLoss: 0.053996\nTrain Epoch: 1 [4480/30016 (15%)]\tLoss: 0.195913\nTrain Epoch: 1 [5120/30016 (17%)]\tLoss: 0.060688\nTrain Epoch: 1 [5760/30016 (19%)]\tLoss: 0.115756\nTrain Epoch: 1 [6400/30016 (21%)]\tLoss: 0.144222\nTrain Epoch: 1 [7040/30016 (23%)]\tLoss: 0.127553\nTrain Epoch: 1 [7680/30016 (26%)]\tLoss: 0.203719\nTrain Epoch: 1 [8320/30016 (28%)]\tLoss: 0.158996\nTrain Epoch: 1 [8960/30016 (30%)]\tLoss: 0.206717\nTrain Epoch: 1 [9600/30016 (32%)]\tLoss: 0.083080\nTrain Epoch: 1 [10240/30016 (34%)]\tLoss: 0.071567\nTrain Epoch: 1 [10880/30016 (36%)]\tLoss: 0.206395\nTrain Epoch: 1 [11520/30016 (38%)]\tLoss: 0.061903\nTrain Epoch: 1 [12160/30016 (41%)]\tLoss: 0.063054\nTrain Epoch: 1 [12800/30016 (43%)]\tLoss: 0.182085\nTrain Epoch: 1 [13440/30016 (45%)]\tLoss: 0.154939\nTrain Epoch: 1 [14080/30016 (47%)]\tLoss: 0.141559\nTrain Epoch: 1 [14720/30016 (49%)]\tLoss: 0.216437\nTrain Epoch: 1 [15360/30016 (51%)]\tLoss: 0.147652\nTrain Epoch: 1 [16000/30016 (53%)]\tLoss: 0.025959\nTrain Epoch: 1 [16640/30016 (55%)]\tLoss: 0.455275\nTrain Epoch: 1 [17280/30016 (58%)]\tLoss: 0.099623\nTrain Epoch: 1 [17920/30016 (60%)]\tLoss: 0.271166\nTrain Epoch: 1 [18560/30016 (62%)]\tLoss: 0.170574\nTrain Epoch: 1 [19200/30016 (64%)]\tLoss: 0.067997\nTrain Epoch: 1 [19840/30016 (66%)]\tLoss: 0.141764\nTrain Epoch: 1 [20480/30016 (68%)]\tLoss: 0.152821\nTrain Epoch: 1 [21120/30016 (70%)]\tLoss: 0.107717\nTrain Epoch: 1 [21760/30016 (72%)]\tLoss: 0.233322\nTrain Epoch: 1 [22400/30016 (75%)]\tLoss: 0.221370\nTrain Epoch: 1 [23040/30016 (77%)]\tLoss: 0.093659\nTrain Epoch: 1 [23680/30016 (79%)]\tLoss: 0.084277\nTrain Epoch: 1 [24320/30016 (81%)]\tLoss: 0.053813\nTrain Epoch: 1 [24960/30016 (83%)]\tLoss: 0.182935\nTrain Epoch: 1 [25600/30016 (85%)]\tLoss: 0.036450\nTrain Epoch: 1 [26240/30016 (87%)]\tLoss: 0.137724\nTrain Epoch: 1 [26880/30016 (90%)]\tLoss: 0.175103\nTrain Epoch: 1 [27520/30016 (92%)]\tLoss: 0.064044\nTrain Epoch: 1 [28160/30016 (94%)]\tLoss: 0.070072\nTrain Epoch: 1 [28800/30016 (96%)]\tLoss: 0.132992\nTrain Epoch: 1 [29440/30016 (98%)]\tLoss: 0.125697\n\nTest set: Avg. loss: 0.0280, Accuracy: 9748/30016 (32%)\n\nTrain Epoch: 2 [0/30016 (0%)]\tLoss: 0.064774\nTrain Epoch: 2 [640/30016 (2%)]\tLoss: 0.173727\nTrain Epoch: 2 [1280/30016 (4%)]\tLoss: 0.120233\nTrain Epoch: 2 [1920/30016 (6%)]\tLoss: 0.156266\nTrain Epoch: 2 [2560/30016 (9%)]\tLoss: 0.112449\nTrain Epoch: 2 [3200/30016 (11%)]\tLoss: 0.091798\nTrain Epoch: 2 [3840/30016 (13%)]\tLoss: 0.024527\nTrain Epoch: 2 [4480/30016 (15%)]\tLoss: 0.144569\nTrain Epoch: 2 [5120/30016 (17%)]\tLoss: 0.037021\nTrain Epoch: 2 [5760/30016 (19%)]\tLoss: 0.055271\nTrain Epoch: 2 [6400/30016 (21%)]\tLoss: 0.071087\nTrain Epoch: 2 [7040/30016 (23%)]\tLoss: 0.077232\nTrain Epoch: 2 [7680/30016 (26%)]\tLoss: 0.113851\nTrain Epoch: 2 [8320/30016 (28%)]\tLoss: 0.086933\nTrain Epoch: 2 [8960/30016 (30%)]\tLoss: 0.126416\nTrain Epoch: 2 [9600/30016 (32%)]\tLoss: 0.060134\nTrain Epoch: 2 [10240/30016 (34%)]\tLoss: 0.045356\nTrain Epoch: 2 [10880/30016 (36%)]\tLoss: 0.180100\nTrain Epoch: 2 [11520/30016 (38%)]\tLoss: 0.067510\nTrain Epoch: 2 [12160/30016 (41%)]\tLoss: 0.057529\nTrain Epoch: 2 [12800/30016 (43%)]\tLoss: 0.116505\nTrain Epoch: 2 [13440/30016 (45%)]\tLoss: 0.079541\nTrain Epoch: 2 [14080/30016 (47%)]\tLoss: 0.090319\nTrain Epoch: 2 [14720/30016 (49%)]\tLoss: 0.164027\nTrain Epoch: 2 [15360/30016 (51%)]\tLoss: 0.084880\nTrain Epoch: 2 [16000/30016 (53%)]\tLoss: 0.011989\nTrain Epoch: 2 [16640/30016 (55%)]\tLoss: 0.373237\nTrain Epoch: 2 [17280/30016 (58%)]\tLoss: 0.067686\nTrain Epoch: 2 [17920/30016 (60%)]\tLoss: 0.210395\nTrain Epoch: 2 [18560/30016 (62%)]\tLoss: 0.143066\nTrain Epoch: 2 [19200/30016 (64%)]\tLoss: 0.037438\nTrain Epoch: 2 [19840/30016 (66%)]\tLoss: 0.096844\nTrain Epoch: 2 [20480/30016 (68%)]\tLoss: 0.121761\nTrain Epoch: 2 [21120/30016 (70%)]\tLoss: 0.090457\nTrain Epoch: 2 [21760/30016 (72%)]\tLoss: 0.234806\nTrain Epoch: 2 [22400/30016 (75%)]\tLoss: 0.126038\nTrain Epoch: 2 [23040/30016 (77%)]\tLoss: 0.072192\nTrain Epoch: 2 [23680/30016 (79%)]\tLoss: 0.058036\nTrain Epoch: 2 [24320/30016 (81%)]\tLoss: 0.036218\nTrain Epoch: 2 [24960/30016 (83%)]\tLoss: 0.144304\nTrain Epoch: 2 [25600/30016 (85%)]\tLoss: 0.024255\nTrain Epoch: 2 [26240/30016 (87%)]\tLoss: 0.135833\nTrain Epoch: 2 [26880/30016 (90%)]\tLoss: 0.126680\nTrain Epoch: 2 [27520/30016 (92%)]\tLoss: 0.031605\nTrain Epoch: 2 [28160/30016 (94%)]\tLoss: 0.049616\nTrain Epoch: 2 [28800/30016 (96%)]\tLoss: 0.113463\nTrain Epoch: 2 [29440/30016 (98%)]\tLoss: 0.067239\n\nTest set: Avg. loss: 0.0233, Accuracy: 9791/30016 (33%)\n\nTrain Epoch: 3 [0/30016 (0%)]\tLoss: 0.043380\nTrain Epoch: 3 [640/30016 (2%)]\tLoss: 0.127507\nTrain Epoch: 3 [1280/30016 (4%)]\tLoss: 0.101459\nTrain Epoch: 3 [1920/30016 (6%)]\tLoss: 0.115581\nTrain Epoch: 3 [2560/30016 (9%)]\tLoss: 0.083779\nTrain Epoch: 3 [3200/30016 (11%)]\tLoss: 0.074234\nTrain Epoch: 3 [3840/30016 (13%)]\tLoss: 0.015534\nTrain Epoch: 3 [4480/30016 (15%)]\tLoss: 0.119388\nTrain Epoch: 3 [5120/30016 (17%)]\tLoss: 0.026608\nTrain Epoch: 3 [5760/30016 (19%)]\tLoss: 0.043011\nTrain Epoch: 3 [6400/30016 (21%)]\tLoss: 0.051572\nTrain Epoch: 3 [7040/30016 (23%)]\tLoss: 0.063801\nTrain Epoch: 3 [7680/30016 (26%)]\tLoss: 0.065052\nTrain Epoch: 3 [8320/30016 (28%)]\tLoss: 0.063846\nTrain Epoch: 3 [8960/30016 (30%)]\tLoss: 0.113324\nTrain Epoch: 3 [9600/30016 (32%)]\tLoss: 0.063456\nTrain Epoch: 3 [10240/30016 (34%)]\tLoss: 0.033673\nTrain Epoch: 3 [10880/30016 (36%)]\tLoss: 0.158807\nTrain Epoch: 3 [11520/30016 (38%)]\tLoss: 0.072090\nTrain Epoch: 3 [12160/30016 (41%)]\tLoss: 0.057743\nTrain Epoch: 3 [12800/30016 (43%)]\tLoss: 0.087218\nTrain Epoch: 3 [13440/30016 (45%)]\tLoss: 0.055660\nTrain Epoch: 3 [14080/30016 (47%)]\tLoss: 0.070236\nTrain Epoch: 3 [14720/30016 (49%)]\tLoss: 0.137697\nTrain Epoch: 3 [15360/30016 (51%)]\tLoss: 0.062384\nTrain Epoch: 3 [16000/30016 (53%)]\tLoss: 0.007788\nTrain Epoch: 3 [16640/30016 (55%)]\tLoss: 0.298692\nTrain Epoch: 3 [17280/30016 (58%)]\tLoss: 0.055365\nTrain Epoch: 3 [17920/30016 (60%)]\tLoss: 0.161824\nTrain Epoch: 3 [18560/30016 (62%)]\tLoss: 0.137108\nTrain Epoch: 3 [19200/30016 (64%)]\tLoss: 0.026783\nTrain Epoch: 3 [19840/30016 (66%)]\tLoss: 0.081656\nTrain Epoch: 3 [20480/30016 (68%)]\tLoss: 0.100504\nTrain Epoch: 3 [21120/30016 (70%)]\tLoss: 0.072531\nTrain Epoch: 3 [21760/30016 (72%)]\tLoss: 0.229085\nTrain Epoch: 3 [22400/30016 (75%)]\tLoss: 0.087314\nTrain Epoch: 3 [23040/30016 (77%)]\tLoss: 0.058883\nTrain Epoch: 3 [23680/30016 (79%)]\tLoss: 0.045408\nTrain Epoch: 3 [24320/30016 (81%)]\tLoss: 0.026812\nTrain Epoch: 3 [24960/30016 (83%)]\tLoss: 0.112134\nTrain Epoch: 3 [25600/30016 (85%)]\tLoss: 0.015544\nTrain Epoch: 3 [26240/30016 (87%)]\tLoss: 0.135921\nTrain Epoch: 3 [26880/30016 (90%)]\tLoss: 0.104146\nTrain Epoch: 3 [27520/30016 (92%)]\tLoss: 0.020319\nTrain Epoch: 3 [28160/30016 (94%)]\tLoss: 0.044700\nTrain Epoch: 3 [28800/30016 (96%)]\tLoss: 0.101523\nTrain Epoch: 3 [29440/30016 (98%)]\tLoss: 0.049281\n\nTest set: Avg. loss: 0.0209, Accuracy: 9814/30016 (33%)\n\n" ], [ "fig = plt.figure()\nplt.plot(update_train_counter, update_train_losses, color='blue')\nplt.scatter(update_test_counter, update_test_losses, color='red')\nplt.legend(['Train Loss', 'Test Loss'], loc='upper right')\nplt.xlabel('number of training examples seen')\nplt.ylabel('negative log likelihood loss')\nfig", "_____no_output_____" ], [ "h2.eval()\nh1.eval()", "_____no_output_____" ], [ "test_index = 2", "_____no_output_____" ], [ "with torch.no_grad():\n _, _, h1_output = h1(test_loader[test_index][0])\n _, _, h2_output = h2(test_loader[test_index][0])", "_____no_output_____" ], [ "h1_labels = h1_output.data.max(1)[1]\nh2_labels = h2_output.data.max(1)[1]\nexpected_labels = test_loader[test_index][1]", "_____no_output_____" ], [ "fig = plt.figure()\nfor i in range(6):\n plt.subplot(2,3,i+1)\n plt.tight_layout()\n plt.imshow(test_loader[test_index][0][i][0], cmap='gray', interpolation='none')\n plt.title(\"Prediction: {}\".format(\n h2_labels[i].item()))\n plt.xticks([])\n plt.yticks([])\nfig", "_____no_output_____" ], [ "trust_compatibility = scores.trust_compatibility_score(h1_labels, h2_labels, expected_labels)\nerror_compatibility = scores.error_compatibility_score(h1_labels, h2_labels, expected_labels)\n\nprint(f\"Error Compatibility Score: {error_compatibility}\")\nprint(f\"Trust Compatibility Score: {trust_compatibility}\")", "Error Compatibility Score: 0.45\nTrust Compatibility Score: 0.9989583333333333\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdfa52f944c7036de0aef86c85995de71f2112e
16,559
ipynb
Jupyter Notebook
TowardsDS/TowardsDS.ipynb
SokolovVadim/Big-Data
b18426dc2db7cc0612bd5545f72717de61c3c622
[ "MIT" ]
null
null
null
TowardsDS/TowardsDS.ipynb
SokolovVadim/Big-Data
b18426dc2db7cc0612bd5545f72717de61c3c622
[ "MIT" ]
null
null
null
TowardsDS/TowardsDS.ipynb
SokolovVadim/Big-Data
b18426dc2db7cc0612bd5545f72717de61c3c622
[ "MIT" ]
null
null
null
25.752722
209
0.445558
[ [ [ "Find out how many orders, how many products and how many sellers are in the data.\nHow many products have been sold at least once? Which is the product contained in more orders?", "_____no_output_____" ] ], [ [ "import pyspark\nfrom pyspark.context import SparkContext\nfrom pyspark.sql import SparkSession\nspark = SparkSession.builder \\\n .master(\"local\") \\\n .config(\"spark.sql.autoBroadcastJoinThreshold\", -1) \\\n .config(\"spark.executor.memory\", \"500mb\") \\\n .appName(\"Exercise1\") \\\n .getOrCreate()", "WARNING: An illegal reflective access operation has occurred\nWARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/usr/local/spark-3.2.0-bin-hadoop3.2/jars/spark-unsafe_2.12-3.2.0.jar) to constructor java.nio.DirectByteBuffer(long,int)\nWARNING: Please consider reporting this to the maintainers of org.apache.spark.unsafe.Platform\nWARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations\nWARNING: All illegal access operations will be denied in a future release\nUsing Spark's default log4j profile: org/apache/spark/log4j-defaults.properties\nSetting default log level to \"WARN\".\nTo adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).\n22/01/19 13:16:41 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable\n22/01/19 13:16:46 WARN Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041.\n" ], [ "sellers_table = spark.read.parquet(\"./sellers_parquet\")", "_____no_output_____" ], [ "products_table = spark.read.parquet(\"./products_parquet\")", "_____no_output_____" ], [ "sales_table = spark.read.parquet(\"./sales_parquet\")", "_____no_output_____" ], [ "print('num of sellers: ', sellers_table.count())", "num of sellers: 10\n" ], [ "print('num of products: ', products_table.count())", "num of products: 75000000\n" ], [ "print('num of sales: ', sales_table.count())", "[Stage 24:======================================================> (81 + 1) / 83]\r" ], [ "sales_table.select(\"order_id\").show(5)", "+--------+\n|order_id|\n+--------+\n| 1|\n| 2|\n| 3|\n| 4|\n| 5|\n+--------+\nonly showing top 5 rows\n\n" ], [ "sales_table.filter(sales_table[\"num_pieces_sold\"] > 55).count()", " \r" ], [ "from pyspark.sql.functions import countDistinct\nfrom pyspark.sql.functions import col\nfrom pyspark.sql.functions import count\nfrom pyspark.sql.functions import avg", "_____no_output_____" ], [ "print('num of products sold at least once')", "num of products sold at least once\n" ], [ "sales_table.agg(countDistinct(col(\"product_id\"))).show()", "[Stage 64:> (0 + 1) / 1]\r" ], [ "sales_table.groupBy(col(\"product_id\")).agg(count(\"*\").alias(\"cnt\")).orderBy(col(\"cnt\").desc()).show(10)", "[Stage 79:> (0 + 1) / 1]\r" ], [ "#sales_table.agg(col(sales_table.distinct())).show()\ndistinct_products = sales_table.select('product_id').distinct().collect()\n#df.select('column1').distinct().collect()", " \r" ], [ "len(distinct_products)", "_____no_output_____" ] ], [ [ "How many distinct products have been sold in each day?", "_____no_output_____" ] ], [ [ "sales_table.groupBy(col(\"date\")).agg(countDistinct(col(\"product_id\")).alias(\"distinct_products_sold\")).orderBy(\n col(\"distinct_products_sold\").desc()).show()", "[Stage 94:> (0 + 1) / 1]\r" ] ], [ [ "What is the average revenue of the orders?", "_____no_output_____" ] ], [ [ "print('average num of pieces sold')", "average num of pieces sold\n" ], [ "sales_table.agg(avg(col(\"num_pieces_sold\"))).show()", "[Stage 98:=====================================================> (80 + 1) / 83]\r" ], [ "# create a new column revenue_of_one_product = price * num_pieces_sold\nsales_table.join(products_table, sales_table[\"product_id\"] == products_table[\"product_id\"], \"inner\")\\\n .agg(avg(products_table[\"price\"] * sales_table[\"num_pieces_sold\"])).show()", "[Stage 105:===================================================> (14 + 1) / 15]\r" ] ], [ [ "For each seller, what is the average % contribution of an order to the seller's daily quota?\n### Example\nIf Seller_0 with `quota=250` has 3 orders:\nOrder 1: 10 products sold\nOrder 2: 8 products sold\nOrder 3: 7 products sold\nThe average % contribution of orders to the seller's quota would be:\nOrder 1: 10/105 = 0.04\nOrder 2: 8/105 = 0.032\nOrder 3: 7/105 = 0.028\nAverage % Contribution = (0.04+0.032+0.028)/3 = 0.03333", "_____no_output_____" ] ], [ [ "# for each seller in sellers table find quota.\n# For each seller find orders in sales_table.\n# contribution = sum(num_pieces_sold) / (num_orders * daily_target)", "_____no_output_____" ], [ "sellers_table.filter(sellers_table[\"daily_target\"] > 0).count()", "_____no_output_____" ], [ "print(sales_table.join(sellers_table, sales_table[\"seller_id\"] == sellers_table[\"seller_id\"], \"inner\").withColumn(\n \"ratio\", sales_table[\"num_pieces_sold\"]/sellers_table[\"daily_target\"]\n).groupBy(sales_table[\"seller_id\"]).agg(avg(\"ratio\")).show())", "22/01/19 16:13:13 WARN RowBasedKeyValueBatch: Calling spill() on RowBasedKeyValueBatch. Will not spill but return 0.\n22/01/19 16:13:13 WARN RowBasedKeyValueBatch: Calling spill() on RowBasedKeyValueBatch. Will not spill but return 0.\n22/01/19 16:13:15 WARN RowBasedKeyValueBatch: Calling spill() on RowBasedKeyValueBatch. Will not spill but return 0.\n22/01/19 16:13:15 WARN RowBasedKeyValueBatch: Calling spill() on RowBasedKeyValueBatch. Will not spill but return 0.\n22/01/19 16:13:18 WARN RowBasedKeyValueBatch: Calling spill() on RowBasedKeyValueBatch. Will not spill but return 0.\n22/01/19 16:13:18 WARN RowBasedKeyValueBatch: Calling spill() on RowBasedKeyValueBatch. Will not spill but return 0.\n[Stage 120:============================> (1 + 1) / 2]\r" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cbdfa713b561ac3afd460531176cef9e7432f4fa
4,126
ipynb
Jupyter Notebook
examples/introduction.ipynb
davidbrochart/ipyx
bb8a8dbdeb3443d9a76949b92fe03e98802ddcfe
[ "BSD-3-Clause" ]
3
2021-05-23T05:16:44.000Z
2021-08-25T05:19:50.000Z
examples/introduction.ipynb
davidbrochart/ipyx
bb8a8dbdeb3443d9a76949b92fe03e98802ddcfe
[ "BSD-3-Clause" ]
6
2021-05-23T09:52:08.000Z
2021-12-19T20:18:18.000Z
examples/introduction.ipynb
davidbrochart/ipyx
bb8a8dbdeb3443d9a76949b92fe03e98802ddcfe
[ "BSD-3-Clause" ]
null
null
null
17.191667
115
0.462191
[ [ [ "# Introduction", "_____no_output_____" ] ], [ [ "import time\nfrom ipyx import X, F", "_____no_output_____" ] ], [ [ "### Create a reactive variable from a value", "_____no_output_____" ] ], [ [ "x1 = X(0)\nx1.w", "_____no_output_____" ] ], [ [ "### Now `x2` depends on `x1`", "_____no_output_____" ] ], [ [ "x2 = x1 + 1\nx2.w", "_____no_output_____" ] ], [ [ "### You can also use any function", "_____no_output_____" ] ], [ [ "def my_func(x):\n time.sleep(3)\n return x + 1\n\nf = F(my_func)", "_____no_output_____" ], [ "x3 = f(x2 / 10)\nx3.w", "_____no_output_____" ], [ "x4 = f(x3)\nx4.w", "_____no_output_____" ] ], [ [ "### Now change a variable and see all its dependencies update", "_____no_output_____" ] ], [ [ "x1.v += 1", "_____no_output_____" ] ], [ [ "### Functions with keyword arguments are also supported", "_____no_output_____" ] ], [ [ "def foo(a, b=0):\n return a + b", "_____no_output_____" ], [ "foo = F(foo)", "_____no_output_____" ], [ "a = X(0)\na.w", "_____no_output_____" ], [ "b = X(0)\nb.w", "_____no_output_____" ], [ "c = foo(a, b=b)\nc.w", "_____no_output_____" ], [ "a.v += 1", "_____no_output_____" ], [ "b.v += 1", "_____no_output_____" ] ], [ [ "### Show dependency graph\n\nEach node corresponds to a variable. You can click on a node to see the operation applied to the variable.\n- The red node is the result.\n- A blue node is a source variable.\n- A green node is an intermediary variable.\n- A temporary variable doesn't have a name.", "_____no_output_____" ] ], [ [ "def bar(a, b):\n pass\nbar = F(bar)\nz1 = X(n=\"z1\")\nz2 = X(n=\"z2\")\nz3 = bar(z1, z2)\nz3.n = \"z3\"\nz0 = z1 + z2 * z3\nz0.n = \"z0\"\nz0.visualize()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cbdfac9d3f92a4a646e620798b49bd3c9793fc8e
20,197
ipynb
Jupyter Notebook
notebooks/ICLV.ipynb
mattwigway/s4tb
d0408357507aa855d7d42fec946c4746afa8d719
[ "CC-BY-4.0" ]
null
null
null
notebooks/ICLV.ipynb
mattwigway/s4tb
d0408357507aa855d7d42fec946c4746afa8d719
[ "CC-BY-4.0" ]
null
null
null
notebooks/ICLV.ipynb
mattwigway/s4tb
d0408357507aa855d7d42fec946c4746afa8d719
[ "CC-BY-4.0" ]
null
null
null
33.944538
182
0.436302
[ [ [ "# ICLV\n\nThis demonstrates an integrated choice and latent variable in [biogeme](http://biogeme.epfl.ch), using the biogeme example data.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport biogeme.database as bdb\nimport biogeme.biogeme as bio\nfrom biogeme.expressions import *\nimport biogeme.distributions\nimport biogeme.loglikelihood\nimport biogeme.models\nimport pickle", "_____no_output_____" ], [ "av = {\n 0: Variable('av'),\n 1: Variable('av'),\n 2: Variable('av')\n}", "_____no_output_____" ], [ "# estimate ICLV\n# use data from biogeme\nmnld = pd.read_csv('../data/optima.dat', sep='\\t').sort_values('ID')\nmnld['Choice'] = mnld.Choice.replace({-1: np.nan})\nmnld['age'] = mnld.age.replace({-1: np.nan})\nmnld['college'] = (mnld.Education >= 6).astype('int64')\n\nmnld['incomeChf'] = mnld.Income.map({\n 1: 1250,\n 2: 3250,\n 3: 5000,\n 4: 7000,\n 5: 9000,\n 6: 11000,\n -1: np.nan\n}) / 10000\nmnld['TimeCar'] /= 60\nmnld['TimePT'] /= 60\nmnld['TimeWalk'] = mnld.TimeCar * 35 / 3 # assume average car trip at 35 mph, average walk at 3 mph\nmnld['av'] = 1\n\ndb = bdb.Database('iclv', mnld.dropna(subset=['incomeChf', 'Choice', 'age']))", "_____no_output_____" ], [ "betas = {\n 'ascCar': Beta('ascCar', 0, None, None, 0),\n 'ascPt': Beta('ascPt', 0, None, None, 0),\n 'travelTime': Beta('travelTime', 0, None, None, 0),\n 'incCar': Beta('incCar', 0, None, None, 0),\n 'incPt': Beta('incPt', 0, None, None, 0),\n \n # Latent variable influences on utility\n 'envirWalk': Beta('envirWalk', 0, None, None, 0),\n 'envirPt': Beta('envirPt', 0, None, None, 0),\n \n # Latent variable measurement equations\n 'alphaGlobalWarming': Beta('alphaGlobalWarming', 0, None, None, 1),\n 'betaGlobalWarming': Beta('betaGlobalWarming', 1, None, None, 1),\n 'sigmaGlobalWarming': Beta('sigmaGlobalWarming', 1, None, None, 1),\n 'alphaEconomy': Beta('alphaEconomy', 0, None, None, 0),\n 'betaEconomy': Beta('betaEconomy', 0, None, None, 0),\n 'sigmaEconomy': Beta('sigmaEconomy', 1, None, None, 0),\n \n # Latent variable equation\n 'alphaEnvir': Beta('alphaEnvir', 0, None, None, 0),\n 'ageEnvir': Beta('ageEnvir', 0, None, None, 0),\n 'collegeEnvir': Beta('collegeEnvir', 0, None, None, 0),\n 'envirSigma': Beta('envirSigma', 1, None, None, 0)\n}", "_____no_output_____" ], [ "omega = RandomVariable('omega')\ndensity = biogeme.distributions.normalpdf(omega)", "_____no_output_____" ], [ "# Workaround for biogeme bug: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!searchin/biogeme/bioNormalPdf%7Csort:date/biogeme/SeWFrgN74Zk/gNfM-PCsAwAJ\ndef bioNormalPdf(x):\n return -x*x/2 - np.log((2*np.pi) ** 0.5)\n \ndef loglikelihoodregression(meas,model,sigma):\n t = (meas - model) / sigma\n f = bioNormalPdf(t) - sigma\n return f", "_____no_output_____" ], [ "latentEnvironment = betas['alphaEnvir'] + betas['ageEnvir'] * Variable('age') +\\\n betas['collegeEnvir'] * Variable('college') + betas['envirSigma'] * omega\n\nglobalWarming = betas['alphaGlobalWarming'] + betas['betaGlobalWarming'] * latentEnvironment\neconomy = betas['alphaEconomy'] + betas['betaEconomy'] * latentEnvironment\n\nglobalWarmingLikelihood = loglikelihoodregression(Variable('Envir05'), globalWarming, betas['sigmaGlobalWarming'])\neconomyLikelihood = loglikelihoodregression(Variable('Envir03'), economy, betas['sigmaEconomy'])", "_____no_output_____" ], [ "# 0 = pt, 1 = car, 2 = walk\nutilities = {\n 0: betas['ascPt'] + betas['travelTime'] * Variable('TimePT') + betas['incPt'] * Variable('incomeChf') + betas['envirPt'] * latentEnvironment,\n 1: betas['ascCar'] + betas['travelTime'] * Variable('TimeCar') + betas['incCar'] * Variable('incomeChf'),\n 2: betas['travelTime'] * Variable('TimeWalk') + betas['envirWalk'] * latentEnvironment\n}", "_____no_output_____" ], [ "condprob = biogeme.models.logit(utilities, av, Variable('Choice'))\ncondlike = log(condprob) + globalWarmingLikelihood + economyLikelihood\nloglike = Integrate(condlike + log(density), 'omega')", "_____no_output_____" ], [ "iclv = bio.BIOGEME(db, loglike)\niclv.modelName = 'iclv'\niclvRes = iclv.estimate()", "_____no_output_____" ], [ "pd.DataFrame(iclvRes.getGeneralStatistics()).transpose()[[0]]", "_____no_output_____" ], [ "res = iclvRes.getEstimatedParameters()", "_____no_output_____" ], [ "res.loc['ageEnvir',['Value', 'Std err']] *= 10 # convert to tens of years, lazily", "_____no_output_____" ], [ "res", "_____no_output_____" ], [ "print(res[['Value', 'Std err', 't-test', 'p-value']].round(2).to_latex())", "\\begin{tabular}{lrrrr}\n\\toprule\n{} & Value & Std err & t-test & p-value \\\\\n\\midrule\nageEnvir & -0.02 & 0.00 & -7.97 & 0.00 \\\\\nalphaEconomy & 5.72 & 0.16 & 36.28 & 0.00 \\\\\nalphaEnvir & 3.58 & 0.01 & 251.57 & 0.00 \\\\\nascCar & 6.67 & 0.51 & 12.97 & 0.00 \\\\\nascPt & 6.12 & 0.53 & 11.50 & 0.00 \\\\\nbetaEconomy & -0.80 & 0.04 & -18.08 & 0.00 \\\\\ncollegeEnvir & 0.32 & 0.01 & 32.39 & 0.00 \\\\\nenvirPt & 0.11 & 0.07 & 1.49 & 0.14 \\\\\nenvirSigma & -0.00 & 0.00 & -0.00 & 1.00 \\\\\nenvirWalk & 1.52 & 0.15 & 10.20 & 0.00 \\\\\nincCar & -1.03 & 0.09 & -11.27 & 0.00 \\\\\nincPt & -1.20 & 0.09 & -12.64 & 0.00 \\\\\nsigmaEconomy & 1.22 & 0.00 & 413.14 & 0.00 \\\\\ntravelTime & -0.60 & 0.01 & -61.32 & 0.00 \\\\\n\\bottomrule\n\\end{tabular}\n\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdfb465972cebd093de4d839eb5d6ce001cb021
429,669
ipynb
Jupyter Notebook
colab/example_ltsm.ipynb
NichaRoj/cubems-data-pipeline
a40c9fe03dc181f8a8bb45ab9014f88cd1bebb97
[ "MIT" ]
null
null
null
colab/example_ltsm.ipynb
NichaRoj/cubems-data-pipeline
a40c9fe03dc181f8a8bb45ab9014f88cd1bebb97
[ "MIT" ]
3
2021-05-11T10:32:43.000Z
2022-01-22T11:34:21.000Z
colab/example_ltsm.ipynb
NichaRoj/cubems-data-pipeline
a40c9fe03dc181f8a8bb45ab9014f88cd1bebb97
[ "MIT" ]
null
null
null
341.821002
176,306
0.905218
[ [ [ "<a href=\"https://colab.research.google.com/github/NichaRoj/cubems-data-pipeline/blob/master/colab/example_ltsm.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "#Pre Step", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport datetime as dt\nfrom tensorflow.python.keras.layers import Dense\nfrom tensorflow.python.keras.models import Sequential\nfrom sklearn.preprocessing import MinMaxScaler\nnp.random.seed(7)", "/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n import pandas.util.testing as tm\n" ], [ "from tensorflow.python.keras.layers import LSTM\nfrom sklearn.metrics import mean_squared_error", "_____no_output_____" ], [ "from google.colab import drive\ndrive.mount('/content/drive')", "Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n\nEnter your authorization code:\n··········\nMounted at /content/drive\n" ] ], [ [ "#Load Concated Dataframe", "_____no_output_____" ] ], [ [ "path = \"/content/drive/My Drive/Senior Project- Data Pipeline & Data Analytic/Cham5 Data/Bld_Load_Sum_All_Weather.csv\"\ndf = pd.read_csv(path)", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 11014 entries, 0 to 11013\nData columns (total 10 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Date 11014 non-null object \n 1 AC_Load(kW) 11014 non-null float64\n 2 Light_Load(kW) 11014 non-null float64\n 3 Plug_Load(kW) 11014 non-null float64\n 4 Total_Load(kW) 11014 non-null float64\n 5 temp(degF) 11014 non-null float64\n 6 dew(degF) 11014 non-null float64\n 7 humidity(%) 11014 non-null float64\n 8 windspeed(mph) 11014 non-null float64\n 9 solar(w/m2) 11014 non-null float64\ndtypes: float64(9), object(1)\nmemory usage: 860.6+ KB\n" ], [ "#Change to datetime dtype\ndf['Date']=pd.to_datetime(df['Date'])\n\n#set index to DateTime\ndf.set_index('Date', inplace=True)\n\ndf.info()", "<class 'pandas.core.frame.DataFrame'>\nDatetimeIndex: 11014 entries, 2018-07-01 00:00:00 to 2019-12-14 06:00:00\nData columns (total 9 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 AC_Load(kW) 11014 non-null float64\n 1 Light_Load(kW) 11014 non-null float64\n 2 Plug_Load(kW) 11014 non-null float64\n 3 Total_Load(kW) 11014 non-null float64\n 4 temp(degF) 11014 non-null float64\n 5 dew(degF) 11014 non-null float64\n 6 humidity(%) 11014 non-null float64\n 7 windspeed(mph) 11014 non-null float64\n 8 solar(w/m2) 11014 non-null float64\ndtypes: float64(9)\nmemory usage: 860.5 KB\n" ], [ "df.describe()", "_____no_output_____" ] ], [ [ "**Plot Graph Light Load**", "_____no_output_____" ] ], [ [ "#The pink color indicates missing values\nnum_ticks=19 #tick number for Y-axis\nplt.figure(figsize = (10,5))\nax = sns.heatmap(df.isnull(),cbar=False,\n yticklabels=['Jul18','Aug18','Sept18','Oct18','Nov18','Dec18','Jan19','Feb19','Mar19','Apr19','May19','Jun19','Jul19','Aug19','Sept19','Oct19','Nov19','Dec19',''])\nax.set_yticks(np.linspace(0,len(df),num_ticks,dtype=np.int))\nax.set_title('Dataframe missing values')\nplt.show()", "_____no_output_____" ], [ "plt.figure(figsize=(10,5))\ndf['Light_Load(kW)'].plot()\ndf['temp(degF)'].plot()\nplt.title('Light_Load vs Temp(F)')\nplt.legend(['Light_Load(kW)', 'temp(degF)'], loc='upper right')", "_____no_output_____" ] ], [ [ "#Prepare Dataframe for Light Load", "_____no_output_____" ] ], [ [ "df['LLd-1'] = df['Light_Load(kW)'].shift(1)\ndf['W']= df.index.dayofweek\ndf['H']= df.index.hour\ndf.head()", "_____no_output_____" ] ], [ [ "\n\n**Normalize Data**", "_____no_output_____" ] ], [ [ "# normalize the dataset\nscaler = MinMaxScaler(feature_range=(0,1))\ndata_ll=scaler.fit_transform(df)\n\nplt.figure(figsize=(15,5))\nplt.title('Normolize: Light_Load(kW)')\nplt.plot(data_ll[:,1]) #Light_Load(kW)\nplt.plot(data_ll[:,4]) #temp(degF)\t\nplt.legend(['Light_Load(kW)', 'temp(degF)'], loc='upper right')", "_____no_output_____" ] ], [ [ "**Split Train & Test: Light_Load(kW)**", "_____no_output_____" ] ], [ [ "n = int(len(data_ll)*0.8)\ntrainY_ll = data_ll[1:n,1] #(starting from row1 to remove nan value) \ntrainX_ll = data_ll[1:n,4:] \ntestY_ll = data_ll[n:len(data_ll),1] #Light_Load(kW)\ntestX_ll = data_ll[n:len(data_ll),4:] #starting from temp(F) col\n\nprint(trainY_ll.shape)\nprint(trainX_ll.shape)\nprint('== temp(degF) === dew(degF) === humidity(%) === windspeed(mph) === solar(W/m2 )=== ACLd-1 === W === H === Light_Load(kW) ======')\nfor i in range(5):\n print(trainX_ll[i], trainY_ll[i])\n\nprint(testY_ll.shape)\nprint(testX_ll.shape)\nprint('== temp(degF) === dew(degF) === humidity(%) === windspeed(mph) === solar(W/m2 )=== ACLd-1 === W === H === Light_Load(kW) ======')\nfor i in range(5):\n print(testX_ll[i,:], testY_ll[i])", "(8810,)\n(8810, 8)\n== temp(degF) === dew(degF) === humidity(%) === windspeed(mph) === solar(W/m2 )=== ACLd-1 === W === H === Light_Load(kW) ======\n[0.33366045 0.83754169 0.97931034 0.02222222 0. 0.29320245\n 1. 0.04347826] 0.29439725331723265\n[0.33783121 0.83039543 0.96551724 0.07407407 0. 0.29439725\n 1. 0.08695652] 0.2934701268829347\n[0.35132483 0.82491663 0.93678161 0.07407407 0. 0.29347013\n 1. 0.13043478] 0.29032964622298557\n[0.36898921 0.81562649 0.89770115 0.02222222 0. 0.29032965\n 1. 0.17391304] 0.33866081535508114\n[0.37782139 0.824202 0.89770115 0.01481481 0. 0.33866082\n 1. 0.2173913 ] 0.3387824005344354\n(2203,)\n(2203, 8)\n== temp(degF) === dew(degF) === humidity(%) === windspeed(mph) === solar(W/m2 )=== ACLd-1 === W === H === Light_Load(kW) ======\n[0.76422964 0.87541687 0.52298851 0.05185185 0.67883462 0.13909895\n 0.66666667 0.56521739] 0.16522176125942797\n[0.74730128 0.88899476 0.55287356 0.01481481 0.48054841 0.16522176\n 0.66666667 0.60869565] 0.1678572875292984\n[0.75171737 0.90471653 0.56436782 0.01481481 0.50145673 0.16785729\n 0.66666667 0.65217391] 0.16914215000937521\n[0.69504416 0.88637446 0.6 0.08148148 0.26255356 0.16914215\n 0.66666667 0.69565217] 0.23680053077617375\n[0.47473013 0.80371606 0.74597701 0.08888889 0.04970009 0.23680053\n 0.66666667 0.73913043] 0.22801238561113046\n" ] ], [ [ "**Reshape data before input into LTSM**", "_____no_output_____" ] ], [ [ "# reshape input to be [samples, time steps, features]\ntrainX_ll = trainX_ll.reshape((trainX_ll.shape[0], 1, 8))\ntestX_ll = testX_ll.reshape((testX_ll.shape[0], 1, 8))\nprint('trainX_ll.shape=', trainX_ll.shape)\nprint('testX_ll.shape=', testX_ll.shape)", "trainX_ll.shape= (8810, 1, 8)\ntestX_ll.shape= (2203, 1, 8)\n" ], [ "from tensorflow.keras.optimizers import Adam", "_____no_output_____" ] ], [ [ "#Create LSTM: Light Load lr=0.005", "_____no_output_____" ] ], [ [ "opt = Adam(lr=0.005)\n\nmodel = Sequential()\nmodel.add(LSTM(6, activation='sigmoid',return_sequences=True, input_shape=(1, 8)))\nmodel.add(LSTM(6, activation='sigmoid', input_shape=(1, 8)))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(loss='mean_squared_error', optimizer=opt)\nhistory = model.fit(trainX_ll, trainY_ll, validation_split=0.1, epochs=100, batch_size=24, verbose=1)", "Epoch 1/100\n143/331 [===========>..................] - ETA: 0s - loss: 0.0257" ], [ "print(model.summary())", "_____no_output_____" ] ], [ [ "#Presict & Calculate RMSE lr=0.005", "_____no_output_____" ] ], [ [ "#predict #Light_Load(kW)\ntestPredict_ll = model.predict(testX_ll)", "_____no_output_____" ], [ "#denormalize the test set\ntestY_ll = testY_ll*(df['Light_Load(kW)'].max()-df['Light_Load(kW)'].min())+df['Light_Load(kW)'].min() \n\n#denormalize the prediction\ntestPredict_ll = testPredict_ll*(df['Light_Load(kW)'].max()-df['Light_Load(kW)'].min())+df['Light_Load(kW)'].min() ", "_____no_output_____" ], [ "print(testY_ll.shape)\nprint(testPredict_ll.shape)\ntestPredict_ll.ravel().shape", "(2203,)\n(2203, 1)\n" ], [ "#plot testY vs testPredict\nplt.figure(figsize=(15,8))\nplt.plot(testY_ll, label='testY_ll')\nplt.plot(testPredict_ll, label='testPredict_ll')\nplt.legend(loc='upper right')\n\n#calculate RMSE and MAPE\nRMSE = np.sqrt(np.mean(np.square(testY_ll-testPredict_ll.ravel())))\nMAPE = np.mean(np.abs((testY_ll-testPredict_ll.ravel())/testY_ll))*100\n\nprint('RMSE=',RMSE)\nprint('MAPE=',MAPE)", "RMSE= 27.45523162731631\nMAPE= 12.549500358527247\n" ] ], [ [ "**Check model & Validation**", "_____no_output_____" ] ], [ [ "#Check model loss and validation loss\nplt.figure(figsize=(13,8))\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss: Light Load lr=0.005 epoch=100')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper right')\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cbdfc9375758419ece061f7bcb2657d1bdd25e84
5,159
ipynb
Jupyter Notebook
examples/meteorites/meteorites.ipynb
timgates42/pandas-profiling
2d304ef8abda4ecdbad82803bd8ba4a7f72a5e1f
[ "MIT" ]
1
2021-01-21T09:11:58.000Z
2021-01-21T09:11:58.000Z
examples/meteorites/meteorites.ipynb
timgates42/pandas-profiling
2d304ef8abda4ecdbad82803bd8ba4a7f72a5e1f
[ "MIT" ]
null
null
null
examples/meteorites/meteorites.ipynb
timgates42/pandas-profiling
2d304ef8abda4ecdbad82803bd8ba4a7f72a5e1f
[ "MIT" ]
1
2020-12-30T08:32:29.000Z
2020-12-30T08:32:29.000Z
23.665138
125
0.522776
[ [ [ "## Pandas Profiling: NASA Meteorites example\nSource of data: https://data.nasa.gov/Space-Science/Meteorite-Landings/gh4g-9sfh", "_____no_output_____" ], [ "The autoreload instruction reloads modules automatically before code execution, which is helpful for the update below.", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ] ], [ [ "Make sure that we have the latest version of pandas-profiling.", "_____no_output_____" ] ], [ [ "import sys\n\n!{sys.executable} -m pip install -U pandas-profiling[notebook]\n!jupyter nbextension enable --py widgetsnbextension", "_____no_output_____" ] ], [ [ "You might want to restart the kernel now.", "_____no_output_____" ], [ "### Import libraries", "_____no_output_____" ] ], [ [ "from pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nimport requests\n\nimport pandas_profiling\nfrom pandas_profiling.utils.cache import cache_file", "_____no_output_____" ] ], [ [ "### Load and prepare example dataset\nWe add some fake variables for illustrating pandas-profiling capabilities", "_____no_output_____" ] ], [ [ "file_name = cache_file(\n \"meteorites.csv\",\n \"https://data.nasa.gov/api/views/gh4g-9sfh/rows.csv?accessType=DOWNLOAD\",\n)\n\ndf = pd.read_csv(file_name)\n\n# Note: Pandas does not support dates before 1880, so we ignore these for this analysis\ndf[\"year\"] = pd.to_datetime(df[\"year\"], errors=\"coerce\")\n\n# Example: Constant variable\ndf[\"source\"] = \"NASA\"\n\n# Example: Boolean variable\ndf[\"boolean\"] = np.random.choice([True, False], df.shape[0])\n\n# Example: Mixed with base types\ndf[\"mixed\"] = np.random.choice([1, \"A\"], df.shape[0])\n\n# Example: Highly correlated variables\ndf[\"reclat_city\"] = df[\"reclat\"] + np.random.normal(scale=5, size=(len(df)))\n\n# Example: Duplicate observations\nduplicates_to_add = pd.DataFrame(df.iloc[0:10])\nduplicates_to_add[\"name\"] = duplicates_to_add[\"name\"] + \" copy\"\n\ndf = df.append(duplicates_to_add, ignore_index=True)", "_____no_output_____" ] ], [ [ "### Inline report without saving object", "_____no_output_____" ] ], [ [ "report = df.profile_report(\n sort=\"None\", html={\"style\": {\"full_width\": True}}, progress_bar=False\n)\nreport", "_____no_output_____" ] ], [ [ "### Save report to file", "_____no_output_____" ] ], [ [ "profile_report = df.profile_report(html={\"style\": {\"full_width\": True}})\nprofile_report.to_file(\"/tmp/example.html\")", "_____no_output_____" ] ], [ [ "### More analysis (Unicode) and Print existing ProfileReport object inline", "_____no_output_____" ] ], [ [ "profile_report = df.profile_report(\n explorative=True, html={\"style\": {\"full_width\": True}}\n)\nprofile_report", "_____no_output_____" ] ], [ [ "### Notebook Widgets", "_____no_output_____" ] ], [ [ "profile_report.to_widgets()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbdfcb15e55144031ca101db12a209273d3c08c3
818,312
ipynb
Jupyter Notebook
core_notebooks/measurements_in_cosmoDC2/cosmoDC2_comparison_profiles_in_Mpc.ipynb
LSSTDESC/cluster_magnification
8872a9737ed85b2153f8c36fec78f66c13029b6d
[ "BSD-2-Clause" ]
3
2021-08-18T12:25:38.000Z
2022-01-06T00:58:07.000Z
core_notebooks/measurements_in_cosmoDC2/cosmoDC2_comparison_profiles_in_Mpc.ipynb
LSSTDESC/cluster_magnification
8872a9737ed85b2153f8c36fec78f66c13029b6d
[ "BSD-2-Clause" ]
1
2021-09-28T20:17:11.000Z
2021-09-28T20:17:11.000Z
core_notebooks/measurements_in_cosmoDC2/cosmoDC2_comparison_profiles_in_Mpc.ipynb
LSSTDESC/cluster_magnification
8872a9737ed85b2153f8c36fec78f66c13029b6d
[ "BSD-2-Clause" ]
1
2021-08-18T12:25:41.000Z
2021-08-18T12:25:41.000Z
873.33191
310,808
0.948527
[ [ [ "import numpy as np\nimport os\nfrom astropy.table import Table\nfrom astropy.cosmology import FlatLambdaCDM\nfrom matplotlib import pyplot as plt\nfrom astropy.io import ascii\nfrom astropy.coordinates import SkyCoord \nimport healpy\nimport astropy.units as u\nimport pandas as pd\nimport matplotlib\nimport pyccl\nfrom scipy import stats\n\nos.environ['CLMM_MODELING_BACKEND'] = 'ccl' # here you may choose ccl, nc (NumCosmo) or ct (cluster_toolkit)\n\nimport clmm\nfrom clmm.support.sampler import fitters\n\nfrom importlib import reload \n\nimport sys\nsys.path.append('../../')\nfrom magnification_library import *", "_____no_output_____" ], [ "clmm.__version__", "_____no_output_____" ], [ "matplotlib.rcParams.update({'font.size': 16})", "_____no_output_____" ], [ "#define cosmology\n\n#astropy object\ncosmo = FlatLambdaCDM(H0=71, Om0=0.265, Tcmb0=0 , Neff=3.04, m_nu=None, Ob0=0.0448)\n\n#ccl object\ncosmo_ccl = pyccl.Cosmology(Omega_c=cosmo.Om0-cosmo.Ob0, Omega_b=cosmo.Ob0,\n h=cosmo.h, sigma8= 0.80, n_s=0.963)\n#clmm object\ncosmo_clmm = clmm.Cosmology(be_cosmo=cosmo_ccl)", "_____no_output_____" ], [ "path_file = '../../../'", "_____no_output_____" ], [ "key = 'LBGp'", "_____no_output_____" ] ], [ [ "## **Profiles measured with TreeCorr**", "_____no_output_____" ] ], [ [ "quant = np.load(path_file + \"output_data/binned_correlation_fct_Mpc_\"+key+\".npy\", allow_pickle=True)\nquant_NK = np.load(path_file + \"output_data/binned_correlation_fct_NK_Mpc_\"+key+\".npy\", allow_pickle=True)", "_____no_output_____" ] ], [ [ "## **Measuring profiles with astropy and CLMM**\n", "_____no_output_____" ], [ "## Open data", "_____no_output_____" ] ], [ [ "gal_cat_raw = pd.read_hdf(path_file+'input_data/cat_'+key+'.h5', key=key)\ndat = np.load(path_file+\"input_data/source_sample_properties.npy\", allow_pickle=True)\nmag_cut, alpha_cut, alpha_cut_err, mag_null, gal_dens, zmean = dat[np.where(dat[:,0]==key)][0][1:]\n\nprint (alpha_cut)\nmag_cut", "3.3193084709750664\n" ], [ "selection_source = (gal_cat_raw['ra']>50) & (gal_cat_raw['ra']<73.1) & (gal_cat_raw['dec']<-27.) & (gal_cat_raw['dec']>-45.)\nselection = selection_source & (gal_cat_raw['mag_i_lsst']<mag_cut) & (gal_cat_raw['redshift']>1.5)\n\ngal_cat = gal_cat_raw[selection]", "_____no_output_____" ], [ "[z_cl, mass_cl, n_halo] = np.load(path_file + \"output_data/halo_bin_properties.npy\", allow_pickle=True)", "_____no_output_____" ], [ "np.sum(n_halo)", "_____no_output_____" ] ], [ [ "## **Magnification profiles prediction**\n", "_____no_output_____" ] ], [ [ "def Mpc_to_arcmin(x_Mpc, z, cosmo=cosmo):\n return x_Mpc * cosmo.arcsec_per_kpc_proper(z).to(u.arcmin/u.Mpc).value\n\ndef arcmin_to_Mpc(x_arc, z, cosmo=cosmo):\n return x_arc * cosmo.kpc_proper_per_arcmin(z).to(u.Mpc/u.arcmin).value ", "_____no_output_____" ], [ "def magnification_biais_model(rproj, mass_lens, z_lens, alpha, z_source, cosmo_clmm, delta_so='200', massdef='mean', Mc_relation ='Diemer15'):\n \n conc = get_halo_concentration(mass_lens, z_lens, cosmo_clmm.be_cosmo, Mc_relation, mdef[0], delta_so )\n magnification = np.zeros(len(rproj))\n for k in range(len(rproj)):\n\n magnification[k] = np.mean(clmm.theory.compute_magnification(rproj[k], mdelta=mass_lens, cdelta=conc, \n z_cluster=z_lens, z_source=z_source, cosmo=cosmo_clmm, \n delta_mdef=delta_so, \n massdef = massdef,\n halo_profile_model='NFW', \n z_src_model='single_plane'))\n\n \n model = mu_bias(magnification, alpha) - 1. \n \n return model, magnification\n ", "_____no_output_____" ], [ "def get_halo_concentration(mass_lens, z_lens, cosmo_ccl, relation=\"Diemer15\", mdef=\"matter\", delta_so=200):\n mdef = pyccl.halos.massdef.MassDef(delta_so, mdef, c_m_relation=relation)\n concdef = pyccl.halos.concentration.concentration_from_name(relation)()\n conc = concdef.get_concentration(cosmo=cosmo_clmm.be_cosmo, M=mass_lens, a=cosmo_clmm.get_a_from_z(z=z_lens), mdef_other=mdef)\n return conc ", "_____no_output_____" ], [ "hist = plt.hist(gal_cat['redshift'][selection], bins=100, range=[1.8,3.1], density=True, stacked=True);\npdf_zsource = zpdf_from_hist(hist, zmin=0, zmax=10)\nplt.plot(pdf_zsource.x, pdf_zsource.y, 'r')\nplt.xlim(1,3.4)\n\nplt.xlabel('z source')\nplt.ylabel('pdf')", "_____no_output_____" ], [ "zint = np.linspace(0, 3.5, 1000)\nzrand = np.random.choice(zint, 1000, p=pdf_zsource(zint)/np.sum(pdf_zsource(zint)))", "_____no_output_____" ], [ "Mc_relation = \"Diemer15\"\nmdef = [\"matter\", \"mean\"] #differet terminology for ccl and clmm\ndelta_so=200\n\n\n#model with the full redshift distribution\nrp_Mpc = np.logspace(-2, 3, 100)\n\nmodel_mbias = np.zeros((rp_Mpc.size, len(z_cl), len(mass_cl)))\nmodel_magnification = np.zeros((rp_Mpc.size, len(z_cl), len(mass_cl)))\n\nfor i in np.arange(z_cl.shape[0]):\n for j in np.arange(mass_cl.shape[1]):\n #rp_Mpc = arcmin_to_Mpc(rp, z_cl[i,j], cosmo)\n models = magnification_biais_model(rp_Mpc, mass_cl[i,j], z_cl[i,j], alpha_cut, zrand, cosmo_clmm, delta_so, massdef=mdef[1], Mc_relation=Mc_relation)\n model_mbias[:,i,j] = models[0]\n model_magnification[:,i,j] = models[1]", "../../magnification_library.py:106: RuntimeWarning: invalid value encountered in power\n mu_bias = mu**(beta-1)\n" ] ], [ [ "## **Plotting figures**\n", "_____no_output_____" ], [ "## Example for one mass/z bin\n", "_____no_output_____" ] ], [ [ "i,j = 1,2\n\ncorr = np.mean(gal_cat['magnification']) - 1\n\nplt.fill_between(quant[i,j][0], y1= quant[i,j][1] - np.sqrt(np.diag(quant[i,j][2])),\\\n y2 = quant[i,j][1] + np.sqrt(np.diag(quant[i,j][2])),color = 'grey', alpha=0.4, label='measured')\n\nexpected_mu_bias = mu_bias(quant_NK[i,j][1] - corr, alpha_cut) - 1.\nexpected_mu_bias_err = expected_mu_bias * (alpha_cut -1 ) * np.sqrt(np.diag(quant_NK[i,j][2])) /(quant_NK[i,j][1]) \n\nplt.errorbar(quant_NK[i,j][0], expected_mu_bias, yerr = expected_mu_bias_err, fmt='r.', label = 'predicted from meas. $\\mu$')\n\n\nplt.plot(rp_Mpc, model_mbias[:,i,j],'k', lw=2, label='model (1 halo term)')\n\nplt.axvline(cosmo.kpc_proper_per_arcmin(z_cl[i,j]).to(u.Mpc/u.arcmin).value*healpy.nside2resol(4096, arcmin = True), linestyle=\"dotted\", color='grey', label ='healpix resol.')\n\n\nplt.xscale('log')\nplt.xlim(0.1,8)\nplt.ylim(-0.25,1)\nplt.grid()\n\nplt.xlabel('$\\\\theta$ [Mpc]')\nplt.ylabel('$\\delta_{\\mu}$')\n\nplt.legend(fontsize='small', ncol=1)\n", "_____no_output_____" ] ], [ [ "## Magnification biais profiles for cluster in mass/z bins", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(5,5, figsize=[20,15], sharex=True)\n\ncorr = np.mean(gal_cat['magnification']) - 1\n\nfor i,h in zip([0,1,2,3,4],range(5)):\n for j,k in zip([0,1,2,3,4],range(5)):\n \n ax = axes[5-1-k,h]\n \n ax.fill_between(quant[i,j][0], y1= quant[i,j][1] - np.sqrt(np.diag(quant[i,j][2])),\\\n y2 = quant[i,j][1] + np.sqrt(np.diag(quant[i,j][2])),color = 'grey', alpha=0.4)\n\n \n expected_mu_bias = mu_bias(quant_NK[i,j][1] - corr, alpha_cut) - 1.\n expected_mu_bias_err = expected_mu_bias * (alpha_cut -1 ) * np.sqrt(np.diag(quant_NK[i,j][2])) /(quant_NK[i,j][1]) \n\n ax.errorbar(quant_NK[i,j][0], expected_mu_bias, yerr = expected_mu_bias_err, fmt='r.', label = 'predicted from meas. $\\mu$')\n\n ax.axvline(cosmo.kpc_proper_per_arcmin(z_cl[i,j]).to(u.Mpc/u.arcmin).value*healpy.nside2resol(4096, arcmin = True), linestyle=\"dotted\", color='grey', label ='healpix resol.')\n\n ax.text(0.5, 0.80, \"<z>=\"+str(round(z_cl[i,j],2)), transform=ax.transAxes, fontsize='x-small')\n ax.text(0.5, 0.90, \"<M/1e14>=\"+str(round(mass_cl[i,j]/1e14,2)), transform=ax.transAxes, fontsize='x-small');\n \n ax.plot(rp_Mpc, model_mbias[:,i,j],'k--')\n ax.axvline(0, color='black')\n\n[axes[4,j].set_xlabel('$\\\\theta$ [Mpc]') for j in range(5)]\n[axes[i,0].set_ylabel('$\\delta_{\\mu}$') for i in range(5)]\n\nplt.tight_layout()\n\n\naxes[0,0].set_xscale('log')\naxes[0,0].set_xlim(0.1,8)\n\nfor i in range(axes.shape[0]):\n axes[4,i].set_ylim(-0.2,0.6)\n axes[3,i].set_ylim(-0.2,1.3)\n axes[2,i].set_ylim(-0.2,1.3)\n axes[1,i].set_ylim(-0.2,2.0)\n axes[0,i].set_ylim(-0.2,2.5)", "_____no_output_____" ] ], [ [ "## Fitting the mass from the magnification biais profiles using the NFW model ", "_____no_output_____" ] ], [ [ "def predict_function(radius_Mpc, logM, z_cl):\n mass_guess = 10**logM\n return magnification_biais_model(radius_Mpc, mass_guess, z_cl, alpha_cut, zrand, cosmo_clmm, delta_so, massdef=mdef[1], Mc_relation=Mc_relation)[0]\n", "_____no_output_____" ], [ "def fit_mass(predict_function, data_for_fit, z):\n popt, pcov = fitters['curve_fit'](lambda radius_Mpc, logM: predict_function(radius_Mpc, logM, z),\n data_for_fit[0], \n data_for_fit[1], \n np.sqrt(np.diag(data_for_fit[2])), bounds=[10.,17.], absolute_sigma=True, p0=(13.))\n logm, logm_err = popt[0], np.sqrt(pcov[0][0])\n return {'logm':logm, 'logm_err':logm_err,\n 'm': 10**logm, 'm_err': (10**logm)*logm_err*np.log(10)}", "_____no_output_____" ], [ "fit_mass_magnification = np.zeros(z_cl.shape, dtype=object)\n\nmass_eval = np.zeros((z_cl.shape))\nmass_min = np.zeros((z_cl.shape))\nmass_max = np.zeros((z_cl.shape))\n\nfor i in range(5):\n for j in range(5):\n fit_mass_magnification[i,j] = fit_mass(predict_function, quant[i,j], z_cl[i,j])\n \n mass_eval[i,j] = fit_mass_magnification[i,j]['m']\n mass_min[i,j] = fit_mass_magnification[i,j]['m'] - fit_mass_magnification[i,j]['m_err']\n mass_max[i,j] = fit_mass_magnification[i,j]['m'] + fit_mass_magnification[i,j]['m_err']", "../../magnification_library.py:106: RuntimeWarning: invalid value encountered in power\n mu_bias = mu**(beta-1)\n" ], [ "\nfig, ax = plt.subplots(1, 3, figsize=(18,4))\n\nax[0].errorbar(mass_cl[0,:]*0.90, mass_eval[0,:],\\\n yerr = (mass_eval[0,:] - mass_min[0,:], mass_max[0,:] - mass_eval[0,:]),fmt='-o', label =\"z=\"+str(round(z_cl[0,0],2)))\nax[0].errorbar(mass_cl[1,:]*0.95, mass_eval[1,:],\\\n yerr = (mass_eval[1,:] - mass_min[1,:], mass_max[1,:] - mass_eval[1,:]),fmt='-o', label =\"z=\"+str(round(z_cl[1,0],2)))\nax[0].errorbar(mass_cl[2,:]*1.00, mass_eval[2,:],\\\n yerr = (mass_eval[2,:] - mass_min[2,:], mass_max[2,:] - mass_eval[2,:]),fmt='-o', label =\"z=\"+str(round(z_cl[2,0],2)))\nax[0].errorbar(mass_cl[3,:]*1.05, mass_eval[3,:],\\\n yerr = (mass_eval[3,:] - mass_min[3,:], mass_max[3,:] - mass_eval[3,:]),fmt='-o', label =\"z=\"+str(round(z_cl[3,0],2)))\nax[0].errorbar(mass_cl[4,:]*1.10, mass_eval[4,:],\\\n yerr = (mass_eval[4,:] - mass_min[4,:], mass_max[4,:] - mass_eval[4,:]),fmt='-o', label =\"z=\"+str(round(z_cl[4,0],2)))\n\n\nax[0].set_xscale('log')\nax[0].set_yscale('log')\nax[0].plot((4e13, 5e14),(4e13,5e14), color='black', lw=2)\nax[0].legend(fontsize = 'small', ncol=1)\nax[0].set_xlabel(\"$M_{FoF}$ true [$M_{\\odot}$]\")\nax[0].set_ylabel(\"$M_{200,m}$ eval [$M_{\\odot}$]\")\nax[0].grid()\n\nax[1].errorbar(mass_cl[0,:]*0.96, mass_eval[0,:]/mass_cl[0,:],\\\n yerr = (mass_eval[0,:] - mass_min[0,:], mass_max[0,:] - mass_eval[0,:])/mass_cl[0,:],fmt='-o', label =\"z=\"+str(round(z_cl[0,0],2)))\nax[1].errorbar(mass_cl[1,:]*0.98, mass_eval[1,:]/mass_cl[1,:],\\\n yerr = (mass_eval[1,:] - mass_min[1,:], mass_max[1,:] - mass_eval[1,:])/mass_cl[1,:],fmt='-o', label =\"z=\"+str(round(z_cl[1,0],2)))\nax[1].errorbar(mass_cl[2,:]*1.00, mass_eval[2,:]/mass_cl[2,:],\\\n yerr = (mass_eval[2,:] - mass_min[2,:], mass_max[2,:] - mass_eval[2,:])/mass_cl[2,:],fmt='-o', label =\"z=\"+str(round(z_cl[2,0],2)))\nax[1].errorbar(mass_cl[3,:]*1.02, mass_eval[3,:]/mass_cl[3,:],\\\n yerr = (mass_eval[3,:] - mass_min[3,:], mass_max[3,:] - mass_eval[3,:])/mass_cl[3,:],fmt='-o', label =\"z=\"+str(round(z_cl[3,0],2)))\nax[1].errorbar(mass_cl[4,:]*1.04, mass_eval[4,:]/mass_cl[4,:],\\\n yerr = (mass_eval[4,:] - mass_min[4,:], mass_max[4,:] - mass_eval[4,:])/mass_cl[4,:],fmt='-o', label =\"z=\"+str(round(z_cl[4,0],2)))\n\nax[1].set_xlim(4e13, 5e14)\nax[1].set_xscale('log')\nax[1].axhline(1, color='black')\n#ax[1].legend()\nax[1].set_xlabel(\"$M_{FoF}$ true [$M_{\\odot}$]\")\nax[1].set_ylabel(\"$M_{200,m}$ eval/$M_{FoF}$ true\")\n\nax[2].errorbar(z_cl[0,:]*0.96, mass_eval[0,:]/mass_cl[0,:],\\\n yerr = (mass_eval[0,:] - mass_min[0,:], mass_max[0,:] - mass_eval[0,:])/mass_cl[0,:],fmt='-o', label =\"z=\"+str(round(z_cl[0,0],2)))\nax[2].errorbar(z_cl[1,:]*0.98, mass_eval[1,:]/mass_cl[1,:],\\\n yerr = (mass_eval[1,:] - mass_min[1,:], mass_max[1,:] - mass_eval[1,:])/mass_cl[1,:],fmt='-o', label =\"z=\"+str(round(z_cl[1,0],2)))\nax[2].errorbar(z_cl[2,:]*1.00, mass_eval[2,:]/mass_cl[2,:],\\\n yerr = (mass_eval[2,:] - mass_min[2,:], mass_max[2,:] - mass_eval[2,:])/mass_cl[2,:],fmt='-o', label =\"z=\"+str(round(z_cl[2,0],2)))\nax[2].errorbar(z_cl[3,:]*1.02, mass_eval[3,:]/mass_cl[3,:],\\\n yerr = (mass_eval[3,:] - mass_min[3,:], mass_max[3,:] - mass_eval[3,:])/mass_cl[3,:],fmt='-o', label =\"z=\"+str(round(z_cl[3,0],2)))\nax[2].errorbar(z_cl[4,:]*1.04, mass_eval[4,:]/mass_cl[4,:],\\\n yerr = (mass_eval[4,:] - mass_min[4,:], mass_max[4,:] - mass_eval[4,:])/mass_cl[4,:],fmt='-o', label =\"z=\"+str(round(z_cl[4,0],2)))\n\nax[2].axhline(1, color='black')\nax[2].set_ylabel(\"$M_{200,m}$ eval/$M_{FoF}$ true\")\nax[2].set_xlabel('z')\n\n\nplt.tight_layout()", "_____no_output_____" ], [ "np.save(path_file + \"output_data/fitted_mass_from_magnification_bias_\"+key+\"_\"+mdef[0]+str(delta_so)+\"_cM_\"+Mc_relation,[mass_eval, mass_min, mass_max])", "_____no_output_____" ] ], [ [ "## Comparison to the mass fitted from the magnification profile", "_____no_output_____" ] ], [ [ "mass_eval_mag, mass_min_mag, mass_max_mag = np.load(path_file + \"output_data/fitted_mass_from_magnification_\"+key+\"_\"+mdef[0]+str(delta_so)+\"_cM_\"+Mc_relation+\".npy\")", "_____no_output_____" ], [ "fig, ax = plt.subplots(1, 3, figsize=(18,4))# sharex=True )#,sharey=True)\n\ncolors = [\"blue\", \"green\" , \"orange\", \"red\", \"purple\"]\n\nax[0].errorbar(mass_eval_mag[0,:], mass_eval[0,:],xerr = (mass_eval_mag[0,:] - mass_min_mag[0,:], mass_max_mag[0,:] - mass_eval_mag[0,:]),\\\n yerr = (mass_eval[0,:] - mass_min[0,:], mass_max[0,:] - mass_eval[0,:]),\\\n fmt='.', color = colors[0], mfc='none', label =\"z=\"+str(round(z_cl[0,0],2)))\n\nax[0].errorbar(mass_eval_mag[1,:], mass_eval[1,:],xerr = (mass_eval_mag[1,:] - mass_min_mag[1,:], mass_max_mag[1,:] - mass_eval_mag[1,:]),\\\n yerr = (mass_eval[1,:] - mass_min[1,:], mass_max[1,:] - mass_eval[1,:]),\\\n fmt='.', color = colors[1], mfc='none', label =\"z=\"+str(round(z_cl[1,0],2)))\n\nax[0].errorbar(mass_eval_mag[2,:], mass_eval[2,:],xerr = (mass_eval_mag[2,:] - mass_min_mag[2,:], mass_max_mag[2,:] - mass_eval_mag[2,:]),\\\n yerr = (mass_eval[2,:] - mass_min[2,:], mass_max[2,:] - mass_eval[2,:]),\\\n fmt='.', color = colors[2], mfc='none', label =\"z=\"+str(round(z_cl[2,0],2)))\n\nax[0].errorbar(mass_eval_mag[3,:], mass_eval[3,:],xerr = (mass_eval_mag[3,:] - mass_min_mag[3,:], mass_max_mag[3,:] - mass_eval_mag[3,:]),\\\n yerr = (mass_eval[3,:] - mass_min[3,:], mass_max[3,:] - mass_eval[3,:]),\\\n fmt='.', color = colors[3], mfc='none', label =\"z=\"+str(round(z_cl[3,0],2)))\n\nax[0].errorbar(mass_eval_mag[4,:], mass_eval[4,:],xerr = (mass_eval_mag[4,:] - mass_min_mag[4,:], mass_max_mag[4,:] - mass_eval_mag[4,:]),\\\n yerr = (mass_eval[4,:] - mass_min[4,:], mass_max[4,:] - mass_eval[4,:]),\\\n fmt='.', color = colors[4], mfc='none', label =\"z=\"+str(round(z_cl[4,0],2)))\n\n\n\nax[0].set_xscale('log')\nax[0].set_yscale('log')\nax[0].plot((4e13, 5e14),(4e13,5e14), color='black', lw=2)\nax[0].legend(fontsize='small')\nax[0].set_xlabel(\"$M_{200,m}~eval~from~\\mu$[$M_{\\odot}$]\")\nax[0].set_ylabel(\"$M_{200,m}~eval~from~\\delta_{\\mu}$[$M_{\\odot}$]\")\nax[0].grid()\n\nratio = mass_eval/mass_eval_mag\nratio_err = ratio *( (0.5*(mass_max - mass_min))/mass_eval + (0.5*(mass_max_mag - mass_min_mag))/mass_eval_mag )\n\nax[1].errorbar(mass_cl[0,:]*0.96, ratio[0], yerr = ratio_err[0],fmt = 'o', color = colors[0])\nax[1].errorbar(mass_cl[1,:]*0.98, ratio[1], yerr = ratio_err[1],fmt = 'o', color = colors[1])\nax[1].errorbar(mass_cl[2,:]*1.00, ratio[2], yerr = ratio_err[2],fmt = 'o', color = colors[2])\nax[1].errorbar(mass_cl[3,:]*1.02, ratio[3], yerr = ratio_err[3],fmt = 'o', color = colors[3])\nax[1].errorbar(mass_cl[4,:]*1.04, ratio[4], yerr = ratio_err[4],fmt = 'o', color = colors[4])\n\nax[1].axhline(1, color='black')\n\nax[1].set_xlabel(\"$M_{FoF}$ true [$M_{\\odot}$]\")\nax[1].set_ylabel(\"$\\\\frac{M_{200,m}~eval~from~\\delta_{\\mu}}{M_{200,m}~eval~from~\\mu}$\")\n\nax[1].set_xlim(4e13, 5e14)\nax[1].set_xscale('log')\n\nax[2].errorbar(z_cl[0,:]*0.96, ratio[0], yerr = ratio_err[0], fmt = 'o', color = colors[0])\nax[2].errorbar(z_cl[1,:]*0.98, ratio[1], yerr = ratio_err[1], fmt = 'o', color = colors[1])\nax[2].errorbar(z_cl[2,:]*1.00, ratio[2], yerr = ratio_err[2], fmt = 'o', color = colors[2])\nax[2].errorbar(z_cl[3,:]*1.02, ratio[3], yerr = ratio_err[3], fmt = 'o', color = colors[3])\nax[2].errorbar(z_cl[4,:]*1.04, ratio[4], yerr = ratio_err[4], fmt = 'o', color = colors[4])\n\nax[2].axhline(1, color='black')\nax[2].set_ylabel(\"$\\\\frac{M_{200,m}~eval~from~\\mu}{M_{200,m}~eval~from~\\delta_{\\mu}}$\")\nax[2].set_xlabel('z')\n\nplt.tight_layout()", "_____no_output_____" ], [ "diff = (mass_eval - mass_eval_mag)/1e14\ndiff_err = (1/1e14) * np.sqrt((0.5*(mass_max - mass_min))**2 + (0.5*(mass_max_mag - mass_min_mag))**2)\n\nplt.hist((diff/diff_err).flatten());\n\nplt.xlabel('$\\chi$')\n\nplt.axvline(0, color='black')\nplt.axvline(-1, color='black', ls='--')\nplt.axvline(1, color='black', ls='--')\n\nplt.axvline(np.mean((diff/diff_err).flatten()), color='red')\nplt.axvline(np.mean((diff/diff_err).flatten()) - np.std((diff/diff_err).flatten()), color='red', ls=':')\nplt.axvline(np.mean((diff/diff_err).flatten()) + np.std((diff/diff_err).flatten()), color='red', ls=':')", "_____no_output_____" ], [ "print(\"$\\chi$ stats \\n\", \\\n \"mean\",np.round(np.mean((diff/diff_err).flatten()),2),\\\n \", mean err\", np.round(np.std((diff/diff_err).flatten())/np.sqrt(25),2),\\\n \", std\", np.round(np.std((diff/diff_err).flatten()),2),\\\n \", std approx err\", np.round(np.std((diff/diff_err).flatten())/np.sqrt(2*(25-1)),2))", "$\\chi$ stats \n mean 0.74 , mean err 0.26 , std 1.31 , std approx err 0.19\n" ] ], [ [ "## Profile plot with the model corresponding to the fitted mass", "_____no_output_____" ] ], [ [ "model_for_fitted_mass = np.zeros(z_cl.shape,dtype=object)\nmodel_for_fitted_mass_min = np.zeros(z_cl.shape,dtype=object)\nmodel_for_fitted_mass_max = np.zeros(z_cl.shape,dtype=object)\n\nfor i in range(z_cl.shape[0]):\n for j in range(z_cl.shape[1]):\n model_for_fitted_mass[i,j] = magnification_biais_model(rp_Mpc, mass_eval[i,j], z_cl[i,j], alpha_cut, zrand, cosmo_clmm, delta_so, massdef=mdef[1], Mc_relation=Mc_relation)[0]\n model_for_fitted_mass_min[i,j] = magnification_biais_model(rp_Mpc, mass_min[i,j], z_cl[i,j], alpha_cut, zrand, cosmo_clmm, delta_so, massdef=mdef[1], Mc_relation=Mc_relation)[0]\n model_for_fitted_mass_max[i,j] = magnification_biais_model(rp_Mpc, mass_max[i,j], z_cl[i,j], alpha_cut, zrand, cosmo_clmm, delta_so, massdef=mdef[1], Mc_relation=Mc_relation)[0]", "../../magnification_library.py:106: RuntimeWarning: invalid value encountered in power\n mu_bias = mu**(beta-1)\n" ], [ "fig, axes = plt.subplots(5,5, figsize=[20,15], sharex=True)\n\ncorr = np.mean(gal_cat['magnification']) - 1\n\nfor i,h in zip([0,1,2,3,4],range(5)):\n for j,k in zip([0,1,2,3,4],range(5)):\n \n ax = axes[5-1-k,h]\n \n ax.fill_between(quant[i,j][0], y1= quant[i,j][1] - np.sqrt(np.diag(quant[i,j][2])),\\\n y2 = quant[i,j][1] + np.sqrt(np.diag(quant[i,j][2])),color = 'grey', alpha=0.4)\n\n \n expected_mu_bias = mu_bias(quant_NK[i,j][1] - corr, alpha_cut) - 1.\n expected_mu_bias_err = expected_mu_bias * (alpha_cut -1 ) * np.sqrt(np.diag(quant_NK[i,j][2])) /(quant_NK[i,j][1]) \n\n ax.errorbar(quant_NK[i,j][0], expected_mu_bias, yerr = expected_mu_bias_err, fmt='r.', label = 'predicted from meas. $\\mu$')\n\n ax.axvline(cosmo.kpc_proper_per_arcmin(z_cl[i,j]).to(u.Mpc/u.arcmin).value*healpy.nside2resol(4096, arcmin = True), linestyle=\"dotted\", color='grey', label ='healpix resol.')\n\n ax.text(0.55, 0.80, \"<z>=\"+str(round(z_cl[i,j],2)), transform=ax.transAxes, fontsize='x-small')\n ax.text(0.55, 0.90, \"<M/1e14>=\"+str(round(mass_cl[i,j]/1e14,2)), transform=ax.transAxes, fontsize='x-small');\n \n ax.set_xlabel('$\\\\theta$ [Mpc]')\n ax.set_ylabel('$\\delta_{\\mu}$')\n\n ax.plot(rp_Mpc, model_mbias[:,i,j],'k--')\n \n ax.fill_between(rp_Mpc, y1 = model_for_fitted_mass_min[i,j], y2 = model_for_fitted_mass_max[i,j],color='red', alpha=0.5)\n \nplt.tight_layout()\n\n\naxes[0,0].set_xscale('log')\naxes[0,0].set_xlim(0.1,8)\n\nfor i in range(axes.shape[0]):\n axes[4,i].set_ylim(-0.2,0.6)\n axes[3,i].set_ylim(-0.2,1.3)\n axes[2,i].set_ylim(-0.2,1.3)\n axes[1,i].set_ylim(-0.2,2.0)\n axes[0,i].set_ylim(-0.2,2.5)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cbdfccc0124be0f735b7623624f20e9fff9e3de4
4,597
ipynb
Jupyter Notebook
tareas/tarea1.ipynb
dcabezas98/SPSI
0da25cd527d4590cd45d1f11a0c0247ed82b4fb6
[ "MIT" ]
null
null
null
tareas/tarea1.ipynb
dcabezas98/SPSI
0da25cd527d4590cd45d1f11a0c0247ed82b4fb6
[ "MIT" ]
null
null
null
tareas/tarea1.ipynb
dcabezas98/SPSI
0da25cd527d4590cd45d1f11a0c0247ed82b4fb6
[ "MIT" ]
null
null
null
21.087156
177
0.454427
[ [ [ "# Tareas de SPSI\n\n**David Cabezas Berrido y Patricia Córdoba Hidalgo**", "_____no_output_____" ] ], [ [ "from fractions import Fraction", "_____no_output_____" ] ], [ [ "# Tarea 1: Exponenciación rápida", "_____no_output_____" ], [ "### a)\nImplementamos el algoritmo de exponenciación similar al método de multiplicación del campesino ruso.\nTenemos una función recursiva que acaba cuando $b$ llega a 0. El número de llamadas es $O(\\log_2 b)$.", "_____no_output_____" ] ], [ [ "def e(a,b):\n if b==0:\n return 1\n if b>0 and b%2==0:\n return e(a*a,b/2)\n if b>0 and b%2==1:\n return e(a*a,(b-1)/2)*a", "_____no_output_____" ], [ "print(e(2,3),e(0,0))", "8 1\n" ] ], [ [ "### b)\nEs el mismo algoritmo que el anterior, salvo que devolvemos el resultado en el denominador cuando el exponente es negativo. ", "_____no_output_____" ] ], [ [ "def e(a,b):\n if b==0:\n return 1\n if b%2==0:\n return e(a*a,b/2)\n if b>0 and b%2==1:\n return e(a*a,(b-1)/2)*a\n if b<0 and b%2==1:\n return Fraction(1,e(a,-b))", "_____no_output_____" ], [ "print(e(-3,-2),e(2,-2),e(-3,-1))", "1/9 1/4 -1/3\n" ] ], [ [ "### c)\nImplementamos primero el algoritmo de Euclides visto en clase, con el fin de calcular el inverso en caso de que el exponente sea negativo.", "_____no_output_____" ] ], [ [ "def euclid(a,b):\n a0, a1 = a, b\n s0, s1 = 1, 0\n t0, t1 = 0, 1\n \n while a1 != 0:\n q = a0//a1\n a0, a1 = a1, a0%a1\n s0, s1 = s1, s0-s1*q\n t0, t1 = t1, t0-t1*q\n return a0, s0, t0", "_____no_output_____" ] ], [ [ "Es similar al anterior, pero vamos reduciendo módulo $n$ en cada iteración. Si el exponente es negativo sólo podemos devolver un resultado válido cuando exista el inverso.", "_____no_output_____" ] ], [ [ "def e(a,b,n):\n if b==0:\n return 1\n if b>0 and b%2==0:\n return e(a*a%n,b/2,n)\n if b>0 and b%2==1:\n return e(a*a%n,(b-1)/2,n)*a%n\n if b<0:\n d, u, v = euclid(a,n)\n if d == 1:\n return e(u,-b,n)\n else:\n print('no existe el inverso de ' + str(a) + ' mod '+ str(n))\n ", "_____no_output_____" ], [ "e(-3,-2,6)\ne(-16,3,21)", "no existe el inverso de -3 mod 6\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cbdfd179acc7a16070877e627f8be994800dc9d5
121,012
ipynb
Jupyter Notebook
active_learning_for_question_classification.ipynb
nikolay-bushkov/kaist_internship
b3c22a0f58e84bf6e176055cbcf176ca593eff7a
[ "Apache-2.0" ]
null
null
null
active_learning_for_question_classification.ipynb
nikolay-bushkov/kaist_internship
b3c22a0f58e84bf6e176055cbcf176ca593eff7a
[ "Apache-2.0" ]
null
null
null
active_learning_for_question_classification.ipynb
nikolay-bushkov/kaist_internship
b3c22a0f58e84bf6e176055cbcf176ca593eff7a
[ "Apache-2.0" ]
null
null
null
149.397531
49,898
0.879367
[ [ [ "[View in Colaboratory](https://colab.research.google.com/github/nikolay-bushkov/kaist_internship/blob/master/active_learning_for_question_classification.ipynb)", "_____no_output_____" ], [ "# Predicting question type on the Yahoo dataset", "_____no_output_____" ], [ "Based on https://developers.google.com/machine-learning/guides/text-classification/, https://github.com/cosmic-cortex/modAL/blob/f8df6021a1343d511d4c9b4c108ec5b683ce5487/examples/ranked_batch_mode.ipynb and https://doi.org/10.1145/3159652.3159733 (https://www.researchgate.net/publication/322488294_Identifying_Informational_vs_Conversational_Questions_on_Community_Question_Answering_Archives)", "_____no_output_____" ] ], [ [ "!pip3 install -q https://github.com/nikolay-bushkov/modAL/archive/feature/sparse_matrix_support.zip", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "from sklearn.preprocessing import FunctionTransformer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_classif\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.neural_network import MLPClassifier", "_____no_output_____" ] ], [ [ "## Data preparation", "_____no_output_____" ] ], [ [ "!wget -q http://files.deeppavlov.ai/datasets/yahoo_answers_data/train.csv", "_____no_output_____" ], [ "!wget -q http://files.deeppavlov.ai/datasets/yahoo_answers_data/valid.csv", "_____no_output_____" ], [ "train_ds = pd.read_csv('train.csv')", "_____no_output_____" ], [ "test_ds = pd.read_csv('valid.csv')", "_____no_output_____" ], [ "X_train_full_raw, y_train_full = train_ds['Title'].values.astype(np.unicode), train_ds['Label'].values", "_____no_output_____" ], [ "X_test_raw, y_test = test_ds['Title'].values.astype(np.unicode), test_ds['Label'].values", "_____no_output_____" ], [ "for text, target in zip(X_train_full_raw[2:4], y_train_full[2:4]):\n print(\"Target: {}\".format(target))\n print(text)", "Target: 1\nLadies, what strain or type of bud do you like to smoke the most?\nTarget: 0\nHow long does it take for an nds rom to upload onto the internet?\n" ], [ "transformation_pipe = Pipeline([\n ('featurizer', TfidfVectorizer(stop_words='english', ngram_range=(1, 3))),\n ('feature_selector', SelectKBest(f_classif, k=20000))\n])", "_____no_output_____" ], [ "X_train_full = transformation_pipe.fit_transform(X_train_full_raw, y_train_full)", "_____no_output_____" ], [ "X_test = transformation_pipe.transform(X_test_raw)", "_____no_output_____" ] ], [ [ "## Baseline model", "_____no_output_____" ] ], [ [ "from sklearn.metrics import roc_auc_score", "_____no_output_____" ], [ "class FCClassifierROCAUC(MLPClassifier):\n \"\"\"Replace default initialization parameters and scroing (ROC-AUC instead of accuracy).\"\"\"\n def __init__(self, hidden_layer_sizes=(32,32), alpha=0.01,\n batch_size=32, max_iter=1000, early_stopping=True, **kwargs):\n super(FCClassifierROCAUC, self).__init__(\n hidden_layer_sizes=hidden_layer_sizes,\n alpha=alpha,\n batch_size=batch_size,\n max_iter=max_iter,\n early_stopping=early_stopping,\n **kwargs)\n def score(self, X, y, sample_weight=None):\n if np.unique(self.classes_).shape[0] == np.unique(y).shape[0] == 2: # hack for beginning of training\n return roc_auc_score(y, self.predict(X), average='macro', sample_weight=sample_weight)\n else:\n return 0.5", "_____no_output_____" ], [ "clf = FCClassifierROCAUC()", "_____no_output_____" ], [ "%time clf.fit(X_train_full, y_train_full)", "CPU times: user 4.47 s, sys: 2.37 s, total: 6.84 s\nWall time: 5.07 s\n" ], [ "clf.score(X_train_full, y_train_full)", "_____no_output_____" ], [ "clf.score(X_test, y_test)", "_____no_output_____" ] ], [ [ "## Active learning part", "_____no_output_____" ] ], [ [ "from modAL.models import ActiveLearner", "_____no_output_____" ], [ "def random_sampling(classifier, X_pool, n_instances=1, **uncertainty_measure_kwargs):\n n_samples = X_pool.shape[0]\n query_idx = np.random.choice(range(n_samples), size=n_instances)\n return query_idx, X_pool[query_idx]", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "SEED_SIZE = 0\nQUERY_SIZE = 16\nQUERY_STEPS = (X_train_full.shape[0] - SEED_SIZE) // QUERY_SIZE", "_____no_output_____" ], [ "X_seed, X_pool, y_seed, y_pool = train_test_split(X_train_full, y_train_full, train_size=SEED_SIZE, random_state=42)", "/home/nab/PycharmProjects/work/venv/lib/python3.6/site-packages/sklearn/model_selection/_split.py:2026: FutureWarning: From version 0.21, test_size will always complement train_size unless both are specified.\n FutureWarning)\n" ], [ "from modAL.batch import uncertainty_batch_sampling", "_____no_output_____" ], [ "from tqdm import tqdm", "_____no_output_____" ], [ "queries = range(1, QUERY_STEPS + 1)", "_____no_output_____" ] ], [ [ "### Random sampling and uncertainty sampling (ranked-batch mode)", "_____no_output_____" ] ], [ [ "X_pool_rs, X_pool_us, y_pool_rs, y_pool_us = X_pool[:], X_pool[:], y_pool[:], y_pool[:]", "_____no_output_____" ], [ "rs_scores = list()\nus_scores = list()\nrs_mask = np.ones(X_pool.shape[0], np.bool)\nus_mask = np.ones(X_pool.shape[0], np.bool)", "_____no_output_____" ], [ "rs_learner = ActiveLearner(\n estimator=FCClassifierROCAUC(),\n query_strategy=random_sampling\n)\nus_learner = ActiveLearner(\n estimator=FCClassifierROCAUC(),\n query_strategy=uncertainty_batch_sampling\n)", "_____no_output_____" ], [ "for query_step in tqdm(queries):\n \n #random\n query_idx_rs, query_inst_rs = rs_learner.query(X_pool_rs, n_instances=QUERY_SIZE)\n rs_learner.teach(query_inst_rs, y_pool_rs[query_idx_rs])\n rs_mask[query_idx_rs] = 0\n X_pool_rs, y_pool_rs = X_pool_rs[rs_mask], y_pool_rs[rs_mask]\n rs_mask = np.ones(X_pool_rs.shape[0], np.bool)\n rs_scores.append(rs_learner.score(X_test, y_test))\n \n #uncertainty (batch) with cosine distances\n query_idx_us, query_inst_us = us_learner.query(X_pool_us, n_instances=QUERY_SIZE, metric='cosine', n_jobs=-2)\n us_learner.teach(query_inst_us, y_pool_us[query_idx_us])\n us_mask[query_idx_us] = 0\n X_pool_us, y_pool_us = X_pool_us[us_mask], y_pool_us[us_mask]\n us_mask = np.ones(X_pool_us.shape[0], np.bool)\n us_scores.append(us_learner.score(X_test, y_test))", " 0%| | 0/225 [00:00<?, ?it/s]/home/nab/PycharmProjects/work/venv/lib/python3.6/site-packages/sklearn/neural_network/multilayer_perceptron.py:358: UserWarning: Got `batch_size` less than 1 or larger than sample size. It is going to be clipped\n warnings.warn(\"Got `batch_size` less than 1 or larger than \"\n100%|██████████| 225/225 [32:25<00:00, 8.65s/it]\n" ], [ "plt.plot(rs_scores, label='Random sampling')\nplt.plot(us_scores, label='Uncertainty sampling (ranked-batch mode)')\nplt.title('Yahoo Question Classification')\nplt.xlabel('Query step')\nplt.ylabel('Test AUC-ROC')\nplt.legend()", "_____no_output_____" ], [ "X_pool_ubs, y_pool_ubs = X_pool[:], y_pool[:]", "_____no_output_____" ], [ "ubs_learner = ActiveLearner(\n estimator=FCClassifierROCAUC(),\n query_strategy=uncertainty_batch_sampling\n)", "_____no_output_____" ], [ "ubs_scores = list()\nubs_mask = np.ones(X_pool.shape[0], np.bool)", "_____no_output_____" ], [ "for query_step in tqdm(queries):\n #uncertainty (batch) with euclidean\n query_idx_ubs, query_inst_ubs = ubs_learner.query(X_pool_ubs, n_instances=QUERY_SIZE, n_jobs=-2)\n ubs_learner.teach(query_inst_ubs, y_pool_ubs[query_idx_ubs])\n ubs_mask[query_idx_ubs] = 0\n X_pool_ubs, y_pool_ubs = X_pool_ubs[ubs_mask], y_pool_ubs[ubs_mask]\n ubs_mask = np.ones(X_pool_ubs.shape[0], np.bool)\n ubs_scores.append(ubs_learner.score(X_test, y_test))", " 0%| | 0/225 [00:00<?, ?it/s]/home/nab/PycharmProjects/work/venv/lib/python3.6/site-packages/sklearn/neural_network/multilayer_perceptron.py:358: UserWarning: Got `batch_size` less than 1 or larger than sample size. It is going to be clipped\n warnings.warn(\"Got `batch_size` less than 1 or larger than \"\n100%|██████████| 225/225 [22:24<00:00, 5.98s/it]\n" ], [ "plt.plot(rs_scores, label='Random sampling')\nplt.plot(ubs_scores, label='Uncertainty sampling (ranked-batch mode, euclidean metric)')\nplt.title('Yahoo Question Classification')\nplt.xlabel('Query step')\nplt.ylabel('Test AUC-ROC')\nplt.legend()", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdfd40a452f5eccd0b6469d6fd84296cb6e6fcb
34,063
ipynb
Jupyter Notebook
Code/1_PK/2_intracellular/matthews2018.ipynb
kimheeye/ISL_PKPD
16774eeb9c9e8da299ce71e27e0e94b9b007b1a3
[ "MIT" ]
null
null
null
Code/1_PK/2_intracellular/matthews2018.ipynb
kimheeye/ISL_PKPD
16774eeb9c9e8da299ce71e27e0e94b9b007b1a3
[ "MIT" ]
null
null
null
Code/1_PK/2_intracellular/matthews2018.ipynb
kimheeye/ISL_PKPD
16774eeb9c9e8da299ce71e27e0e94b9b007b1a3
[ "MIT" ]
null
null
null
231.721088
29,980
0.914776
[ [ [ "import numpy as np\nimport pandas as pd\nfrom scipy.integrate import solve_ivp\nfrom lmfit import minimize, Parameters, report_fit\nimport random\nimport warnings\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "#Preliminaries\nPATH_TO_DATA = '../../../Data/Matthews2018/Digitized/Intracellular/'\n\ndata_5mg = pd.read_csv(PATH_TO_DATA+'ICPK5mg_shortTerm.csv')\ndata_025mg = pd.read_csv(PATH_TO_DATA+'ICPK025mg_shortTerm.csv')\ndata_075mg = pd.read_csv(PATH_TO_DATA+'ICPK075mg_shortTerm.csv')\n\ndata_5mg = data_5mg.dropna(axis='columns')\ndata_025mg = data_025mg.dropna(axis='columns')\ndata_075mg = data_075mg.dropna(axis='columns')\n\ndata_5mg.columns = ['time','conc']\ndata_025mg.columns = ['time','conc']\ndata_075mg.columns = ['time','conc']\n\ndatalist = [data_5mg, data_025mg, data_075mg]\n\nfor d in datalist:\n d['conc'] = 10**d['conc']\n\nt_observed = []; z_observed = []\nfor d in range(len(datalist)):\n t_observed.append(datalist[d].time.tolist())\n z_observed.append(datalist[d].conc.tolist())\n", "_____no_output_____" ], [ "#Compartment model linear PK\ndef model_TP_linear(t, z):\n Z0 = z[0]; Z1 = z[1]; Z2 = z[2]; Z3 = z[3]\n dZ0 = -ka*Z0\n dZ1 = (ka/Vc)*Z0 - k10*Z1 - k12*Z1 + k21*Z2\n dZ2 = k12*Z1 - k21*Z2\n dZ3 = k13*Z1 - k30*Z3\n d = [dZ0,dZ1,dZ2,dZ3]\n return d\n\ndef simulation(d, t_obs):\n #initial state of the system\n z0 = [d, 0, 0, 0]\n t0 = 0; tfinal = 25 #initial and final time of interest\n z = z0\n res = solve_ivp(model_TP_linear, (t0,tfinal), z, t_eval=t_obs)\n Z3List = list(res.y[3]); \n return Z3List ", "_____no_output_____" ], [ "#Estimated PK parameters\nka = 45.4382\nk10 = 0.2355\nk12 = 0.175\nk21 = 0.0259\nVc = 162.69\n\nk13 = 44.2394\nk30 = 0.00975\n\n\n#plot result \ncc = ['bo--','ro--','go--']; cs = ['bo-','ro-','go-'] #color\ndose_label = ['5mg', '0.25mg', '0.75mg'] #label\ndoses = [5, 0.25, 0.75] #drug doses\n \nfor i in range(len(datalist)):\n Z3 = simulation(doses[i], t_observed[i]) \n rss=round(np.sum(np.power(np.subtract(Z3,z_observed[i]),2)),3)\n plt.plot(t_observed[i],Z3,cs[i],label = dose_label[i]+' RSS='+str(round(rss,3)))\n plt.plot(t_observed[i],z_observed[i],cc[i],)\nplt.xlabel('time [hrs]', fontsize=14)\nplt.ylabel('ISL concentration PBMC \\n [pmol/million cells]', fontsize=14)\nplt.yscale('log')\nplt.legend(loc='best')\n#plt.title('short Term Measurements & Simulations')\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
cbdfda74611e397234735e0f8c6f80aa8706d7b7
22,078
ipynb
Jupyter Notebook
mission_to_mars.ipynb
DanZanoria/web-scraping-challenge-
3df9e1f420d3abf9e5350432e85e037511d89357
[ "ADSL" ]
null
null
null
mission_to_mars.ipynb
DanZanoria/web-scraping-challenge-
3df9e1f420d3abf9e5350432e85e037511d89357
[ "ADSL" ]
null
null
null
mission_to_mars.ipynb
DanZanoria/web-scraping-challenge-
3df9e1f420d3abf9e5350432e85e037511d89357
[ "ADSL" ]
null
null
null
34.282609
247
0.472914
[ [ [ "## Imports And Setting UP the Jupyter", "_____no_output_____" ] ], [ [ "import os\nfrom bs4 import BeautifulSoup as bs\nimport requests\nimport pymongo\nfrom splinter import Browser\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom splinter import Browser\nimport pandas as pd", "_____no_output_____" ], [ "\n#I am having a lot of issues with chromedriver so im including both ways to get it\n\n# executable_path = {'executable_path': ChromeDriverManager().install()}\n# browser = Browser('chrome', **executable_path, headless=False)\n\nexecutable_path = {'executable_path':r\"C:\\Users\\danza\\.wdm\\drivers\\chromedriver\\win32\\88.0.4324.96\\chromedriver.exe\"}\nbrowser = Browser('chrome', **executable_path, headless=False)\n", "_____no_output_____" ] ], [ [ "## Connecting to the Nasa Url", "_____no_output_____" ] ], [ [ "nasaurl = \"https://mars.nasa.gov/news/\"\n\nbrowser.visit(nasaurl)\nhtml = browser.html\nnsoup = bs(html, 'html.parser')\n# I want to see if this works. After confirming it works it will be commented out since it has no further need for nsoup\n# nsoup \n", "_____no_output_____" ] ], [ [ "## Things that are identified before obtaining the information we need through code\n### Inspect the Webpage \n#### item_list - is where the titles and paragraph are located\n#### slide to get each individual slides or news article\n#### content_title is what we need to get a title\n#### \"article_teaser_body\" is the class to get a paragraph", "_____no_output_____" ] ], [ [ "\n# Get the lastest 5 titles om the page. I would prefer if i can loop this this but for now this will do. I went through many variations of this code, and none of them went the way I wanted them. \nNtitle0 = nsoup.find_all(\"div\", class_ = \"content_title\")[0].text\nNtitle1 = nsoup.find_all(\"div\", class_ = \"content_title\")[1].text\nNtitle2 = nsoup.find_all(\"div\", class_ = \"content_title\")[2].text\nNtitle3 = nsoup.find_all(\"div\", class_ = \"content_title\")[3].text\nNtitle4 = nsoup.find_all(\"div\", class_ = \"content_title\")[4].text\n\n\n", "_____no_output_____" ], [ "\n# Get the 5 latest paragraphs of the page I would prefer if i can loop this this but for now this will do. \nNpar0 = nsoup.find_all('div', class_=\"article_teaser_body\")[0].text\nNpar1 = nsoup.find_all('div', class_=\"article_teaser_body\")[1].text\nNpar2 = nsoup.find_all('div', class_=\"article_teaser_body\")[2].text\nNpar3 = nsoup.find_all('div', class_=\"article_teaser_body\")[3].text\nNpar4 = nsoup.find_all('div', class_=\"article_teaser_body\")[4].text\n\n\n#I would prefer to to do a for a loop that would capture the title and paragraph on the same loop. But i couldnt figure it out. So this will do. Either way the result i intended would have been the same. \n", "_____no_output_____" ], [ "# Print the captured Variables and putting them in readable format. the print(\" \") is just so i can have an empty space as a seperator between each article/summary group\nprint(f\"News Title: \" + Ntitle0)\nprint(f\"Brief Summary: \" + Npar0)\nprint(\" \")\nprint(f\"News Title: \" + Ntitle1)\nprint(f\"Brief Summary: \" + Npar1)\nprint(\" \")\nprint(f\"News Title: \" + Ntitle2)\nprint(f\"Brief Summary: \" + Npar2)\nprint(\" \")\nprint(f\"News Title: \" + Ntitle3)\nprint(f\"Brief Summary: \" + Npar3)\nprint(\" \")\nprint(f\"News Title: \" + Ntitle4)\nprint(f\"Brief Summary: \" + Npar4)", "News Title: Mars Now\nBrief Summary: Even as the Perseverance rover approaches Mars, technology on board is paying off on Earth.\n \nNews Title: NASA's Perseverance Pays Off Back Home\nBrief Summary: The Martian moon Phobos orbits through a stream of charged atoms and molecules that flow off the Red Planet’s atmosphere, new research shows.\n \nNews Title: Could the Surface of Phobos Reveal Secrets of the Martian Past?\nBrief Summary: With a suite of new national and international spacecraft primed to explore the Red Planet after their arrival next month, NASA’s MAVEN mission is ready to provide support and continue its study of the Martian atmosphere.\n \nNews Title: NASA's MAVEN Continues to Advance Mars Science and Telecommunications Relay Efforts\nBrief Summary: Seven minutes of harrowing descent to the Red Planet is in the not-so-distant future for the agency’s Mars 2020 mission. \n \nNews Title: NASA's Perseverance Rover 22 Days From Mars Landing\nBrief Summary: Ingenuity, a technology experiment, is preparing to attempt the first powered, controlled flight on the Red Planet.\n" ], [ "# Images Scraping\n## Interesting Information before coding\n### link to Featured Image 'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/image/featured/mars3.jpg'\n### overall class = header\n### class = header-image\n\n", "_____no_output_____" ], [ "#setting up the scrap. By visiting the Website to scrap the image\nmarspicurl = \"https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/index.html\"\nbrowser.visit(marspicurl)\nphtml = browser.html\npsoup = bs(phtml, 'html.parser')\n\n#since I already I identified the link the featured image all i have to do is code it. Technically i dont have to do anything beyond this \nfeatured_image_url = 'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/image/featured/mars3.jpg'\nprint(featured_image_url)", "https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/image/featured/mars3.jpg\n" ] ], [ [ "# Mars Data Frame\n## Scrapping the page to obtain the diameter, weight, mass\n### Location of all the is in the class is tabled id = \"tablepress-comp-mars\"", "_____no_output_____" ] ], [ [ "#Connect to the Space Facts / Mars Page\nmarsfacturl= \"https://space-facts.com/mars/\"\n\n\n#Reading the website through pandas\nmars_read = pd.read_html(marsfacturl)\nmars_read", "_____no_output_____" ], [ "#The item we want is 0.\n\nMarsFact_df = mars_read[0]\n\nMarsFact_df\n", "_____no_output_____" ], [ "#Renaming the Column Names to give it a better description\nMarsFact_df.columns = [\"Data Types\" , \"Data Values\"]\nMarsFact_df", "_____no_output_____" ], [ "#I just wanted to bring up the comparison with Earth\nMarsEarthFact_df = mars_read[1]\nMarsEarthFact_df\n\n#Both 0 and 1 would have answered the questions. With about a 4 row difference, and 2 of the the rows in 1 are irrelavant to Earth. ", "_____no_output_____" ], [ "# Hemisphere Link Scraping\n# Not going to link to the website through this markdown like last time. I am purposelly keeping that error to remind this memo actually links things automatically\n", "_____no_output_____" ], [ "#setting up the page to scrape\n\nhemiurl = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\nbrowser.visit(hemiurl)\nhhtml = browser.html\nhsoup = bs(hhtml, 'html.parser')\n", "_____no_output_____" ], [ "# Obtaining the links andv put all those commentted section ins a dictionary. \n\nMarsHemisphere = { \"Cereberus\" :\" https://astropedia.astrogeology.usgs.gov/download/Mars/Viking/cerberus_enhanced.tif/full.jpg\",\n\"Schiaparelli\" : \"https://astropedia.astrogeology.usgs.gov/download/Mars/Viking/schiaparelli_enhanced.tif/full.jpg\",\n\"Syrtis Major\" : \"https://astropedia.astrogeology.usgs.gov/download/Mars/Viking/syrtis_major_enhanced.tif/full.jpg\",\n\"Valles Marineris\" : \"https://astropedia.astrogeology.usgs.gov/download/Mars/Viking/valles_marineris_enhanced.tif/full.jpg \"}\n\nMarsHemisphere", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
cbdfdaa6fe3aace5a4446860f618f773768dbe8e
44,070
ipynb
Jupyter Notebook
impl_result/_hw/SQA-Opt3.ipynb
allen880117/Simulated-Quantum-Annealing
84ce0a475a9f132502c4bb4e9b4ca5824cdb7630
[ "MIT" ]
2
2021-09-08T08:01:27.000Z
2021-11-21T00:08:56.000Z
src/host/SQA-Opt3.ipynb
allen880117/Simulated-Quantum-Annealing
84ce0a475a9f132502c4bb4e9b4ca5824cdb7630
[ "MIT" ]
null
null
null
src/host/SQA-Opt3.ipynb
allen880117/Simulated-Quantum-Annealing
84ce0a475a9f132502c4bb4e9b4ca5824cdb7630
[ "MIT" ]
null
null
null
112.710997
34,432
0.862696
[ [ [ "from __future__ import print_function\n\nimport sys\nimport numpy as np\nfrom time import time\nimport matplotlib.pyplot as plt \nfrom tqdm import tqdm\nimport math\nimport struct\nimport binascii\n\nsys.path.append('/home/xilinx')\nfrom pynq import Overlay\nfrom pynq import allocate", "_____no_output_____" ], [ "def float2bytes(fp):\n packNo = struct.pack('>f', np.float32(fp))\n return int(binascii.b2a_hex(packNo), 16)", "_____no_output_____" ], [ "print(\"Entry:\", sys.argv[0])\nprint(\"System argument(s):\", len(sys.argv))\nprint(\"Start of \\\"\" + sys.argv[0] + \"\\\"\")", "Entry: /usr/lib/python3/dist-packages/ipykernel_launcher.py\nSystem argument(s): 3\nStart of \"/usr/lib/python3/dist-packages/ipykernel_launcher.py\"\n" ], [ "# Overlay and IP\nol = Overlay(\"/home/xilinx/xrwang/SQA_Opt3.bit\")\nipSQA = ol.QuantumMonteCarloOpt3_0\nipDMAIn = ol.axi_dma_0", "_____no_output_____" ], [ "# Number of Spins and Number of Trotters and Wirte Trotters\nnumSpins = 1024\nnumTrotters = 8\ntrotters = np.random.randint(2, size=(numTrotters*numSpins))\nk = 0\nfor addr in tqdm(range(0x400, 0x2400, 0x04)):\n # 8 * 1024 * 1 Byte (it extend boolean into uint8)\n tmp = (trotters[k+3] << 24) + (trotters[k+2] << 16) + (trotters[k+1] << 8) + (trotters[k])\n ipSQA.write(addr, int(tmp))\n k += 4", "100%|██████████| 2048/2048 [00:00<00:00, 11870.73it/s]\n" ], [ "# Generate Random Numbers\nrndNum = np.ndarray(shape=(numSpins), dtype=np.float32)\nfor i in tqdm(range(numSpins)):\n# rndNum[i] = np.random.randn()\n rndNum[i] = i+1\nrndNum /= numSpins", "100%|██████████| 1024/1024 [00:00<00:00, 63996.06it/s]\n" ], [ "rndNum", "_____no_output_____" ], [ "# Generate J coupling\ninBuffer0 = allocate(shape=(numSpins,numSpins), dtype=np.float32)\nfor i in tqdm(range(numSpins)):\n for j in range(numSpins):\n inBuffer0[i][j] = - rndNum[i] * rndNum[j]", "100%|██████████| 1024/1024 [02:41<00:00, 6.35it/s]\n" ], [ "# Some Constant Kernel Arguments \nipSQA.write(0x10, numTrotters) # nTrot\nipSQA.write(0x18, numSpins) # nSpin\nfor addr in range(0x2400, 0x3400, 0x04):\n ipSQA.write(addr, 0) # h[i]", "_____no_output_____" ], [ "# Iterations Parameters\niter = 500\nmaxBeta = 8.0\nBeta = 1.0 / 4096.0\nG0 = 8.0\ndBeta = (maxBeta-Beta) / iter\n\n# Iterations\ntimeList = []\ntrottersList = []\n\nfor i in tqdm(range(iter)):\n\n# # Write Random Numbers (8*1024*4Bytes)\n# rn = np.random.uniform(0.0, 1.0, size=numTrotters*numSpins)\n# rn = np.log(rn) * numTrotters\n\n # Generate Jperp\n Gamma = G0 * (1.0 - i/iter)\n Jperp = -0.5 * np.log(np.tanh((Gamma/numTrotters) * Beta)) / Beta\n\n# # Write Random Nubmers\n# k = 0\n# for addr in range(0x4000, 0xC000, 0x04):\n# ipSQA.write(addr, float2bytes(rn[k]))\n# k += 1\n\n # Write Beta & Jperp\n ipSQA.write(0x3400, float2bytes(Jperp))\n ipSQA.write(0x3408, float2bytes(Beta))\n \n timeKernelStart = time()\n # Start Kernel\n ipSQA.write(0x00, 0x01)\n\n # Write Jcoup Stream\n ipDMAIn.sendchannel.transfer(inBuffer0) # Stream of Jcoup\n ipDMAIn.sendchannel.wait()\n\n # Wait at Here\n while (ipSQA.read(0x00) & 0x4) == 0x0:\n continue\n \n timeKernelEnd = time()\n timeList.append(timeKernelEnd - timeKernelStart)\n \n # Beta Incremental\n Beta += dBeta\n \n k = 0\n newTrotters=np.ndarray(shape=numTrotters*numSpins)\n for addr in range(0x400, 0x2400, 0x04):\n # 8 * 1024 * 1 Byte (it extend boolean into uint8)\n tmp = ipSQA.read(addr)\n newTrotters[k] = (tmp) & 0x01\n newTrotters[k+1] = (tmp>>8) & 0x01\n newTrotters[k+2] = (tmp>>16) & 0x01\n newTrotters[k+3] = (tmp>>24) & 0x01\n k += 4\n trottersList.append(newTrotters)\n \nprint(\"Kernel execution time: \" + str(np.sum(timeList)) + \" s\")", "100%|██████████| 500/500 [01:18<00:00, 6.38it/s]" ], [ "best = (0,0,0,0,10e22)\nsumEnergy = []\nk = 0\nfor trotters in tqdm(trottersList):\n a = 0\n b = 0\n sumE = 0\n k += 1\n for t in range(numTrotters):\n for i in range(numSpins):\n if trotters[t*numSpins+i] == 0:\n a += rndNum[i]\n else:\n b += rndNum[i]\n E = (a-b)**2\n sumE += E\n if best[4] > E :\n best = (k, t, a, b, E)\n sumEnergy.append(sumE)", "100%|██████████| 500/500 [00:58<00:00, 8.65it/s]\n" ], [ "plt.figure(figsize=(30,10))\nplt.plot(sumEnergy)", "_____no_output_____" ], [ "best", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbdff63ba4a878db4663a74866ca6fbd42b66697
658,667
ipynb
Jupyter Notebook
content/downloads/notebooks/PyMC3CustomExternalLikelihood.ipynb
mattpitkin/samplers-demo
127c869b870ce3e6b96e59bda0999bf2cc7d3849
[ "MIT" ]
8
2018-02-13T10:33:51.000Z
2021-09-08T05:03:40.000Z
content/downloads/notebooks/PyMC3CustomExternalLikelihood.ipynb
mattpitkin/samplers-demo
127c869b870ce3e6b96e59bda0999bf2cc7d3849
[ "MIT" ]
23
2018-02-13T09:50:41.000Z
2021-06-06T20:49:01.000Z
content/downloads/notebooks/PyMC3CustomExternalLikelihood.ipynb
mattpitkin/samplers-demo
127c869b870ce3e6b96e59bda0999bf2cc7d3849
[ "MIT" ]
1
2020-07-07T11:37:15.000Z
2020-07-07T11:37:15.000Z
598.244323
182,608
0.934518
[ [ [ "**NOTE: An version of this post is on the PyMC3 [examples](https://docs.pymc.io/notebooks/blackbox_external_likelihood.html) page.**\n\n<!-- PELICAN_BEGIN_SUMMARY -->\n\n[PyMC3](https://docs.pymc.io/index.html) is a great tool for doing Bayesian inference and parameter estimation. It has a load of [in-built probability distributions](https://docs.pymc.io/api/distributions.html) that you can use to set up priors and likelihood functions for your particular model. You can even create your own [custom distributions](https://docs.pymc.io/prob_dists.html#custom-distributions).\n\nHowever, this is not necessarily that simple if you have a model function, or probability distribution, that, for example, relies on an external code that you have little/no control over (and may even be, for example, wrapped `C` code rather than Python). This can be problematic went you need to pass parameters set as PyMC3 distributions to these external functions; your external function probably wants you to pass it floating point numbers rather than PyMC3 distributions!\n\n<!-- PELICAN_END_SUMMARY -->\n\n```python\nimport pymc3 as pm:\nfrom external_module import my_external_func # your external function!\n\n# set up your model\nwith pm.Model():\n # your external function takes two parameters, a and b, with Uniform priors\n a = pm.Uniform('a', lower=0., upper=1.)\n b = pm.Uniform('b', lower=0., upper=1.)\n \n m = my_external_func(a, b) # <--- this is not going to work!\n```\n\nAnother issue is that if you want to be able to use the gradient-based step samplers like [NUTS](https://docs.pymc.io/api/inference.html#module-pymc3.step_methods.hmc.nuts) and [Hamiltonian Monte Carlo (HMC)](https://docs.pymc.io/api/inference.html#hamiltonian-monte-carlo) then your model/likelihood needs a gradient to be defined. If you have a model that is defined as a set of Theano operators then this is no problem - internally it will be able to do automatic differentiation - but if yor model is essentially a \"black box\" then you won't necessarily know what the gradients are.\n\nDefining a model/likelihood that PyMC3 can use that calls your \"black box\" function is possible, but it relies on creating a [custom Theano Op](https://docs.pymc.io/advanced_theano.html#writing-custom-theano-ops). There are many [threads](https://discourse.pymc.io/search?q=as_op) on the PyMC3 [discussion forum](https://discourse.pymc.io/) about this (e.g., [here](https://discourse.pymc.io/t/custom-theano-op-to-do-numerical-integration/734), [here](https://discourse.pymc.io/t/using-pm-densitydist-and-customized-likelihood-with-a-black-box-function/1760) and [here](https://discourse.pymc.io/t/connecting-pymc3-to-external-code-help-with-understanding-theano-custom-ops/670)), but I couldn't find any clear example that described doing what I mention above. So, thanks to a very nice example [sent](https://discourse.pymc.io/t/connecting-pymc3-to-external-code-help-with-understanding-theano-custom-ops/670/7?u=mattpitkin) to me by [Jørgen Midtbø](https://github.com/jorgenem/), I have created what I hope is a clear description. Do let [me](https://twitter.com/matt_pitkin) know if you have any questions/spot any mistakes.\n\nIn the examples below, I'm going to create a very simple model and log-likelihood function in [Cython](http://cython.org/). I use Cython just as an example to show what you might need if calling external `C` codes, but you could in fact be using pure Python codes. The log-likelihood function I use is actually just a [Normal distribution](https://en.wikipedia.org/wiki/Normal_distribution), so this is obviously overkill (and I'll compare it to doing the same thing purely with PyMC3 distributions), but should provide a simple to follow demonstration.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n%load_ext Cython\n\nimport numpy as np\nimport pymc3 as pm\nimport theano\nimport theano.tensor as tt\n\n# for reproducibility here's some version info for modules used in this notebook\nimport platform\nimport cython\nimport IPython\nimport matplotlib\nimport emcee\nimport corner\nimport os\nprint(\"Python version: {}\".format(platform.python_version()))\nprint(\"IPython version: {}\".format(IPython.__version__))\nprint(\"Cython version: {}\".format(cython.__version__))\nprint(\"GSL version: {}\".format(os.popen('gsl-config --version').read().strip()))\nprint(\"Numpy version: {}\".format(np.__version__))\nprint(\"Theano version: {}\".format(theano.__version__))\nprint(\"PyMC3 version: {}\".format(pm.__version__))\nprint(\"Matplotlib version: {}\".format(matplotlib.__version__))\nprint(\"emcee version: {}\".format(emcee.__version__))\nprint(\"corner version: {}\".format(corner.__version__))", "WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\n" ] ], [ [ "First, I'll define my \"_super-complicated_\"&trade; model (a straight line!), which is parameterised by two variables (a gradient `m` and a y-intercept `c`) and calculated at a vector of points `x`. I'll define the model in [Cython](http://cython.org/) and call [GSL](https://www.gnu.org/software/gsl/) functions just to show that you could be calling some other `C` library that you need. In this case, the model parameters are all packed into a list/array/tuple called `theta`.\n\nI'll also define my \"_really-complicated_\"&trade; log-likelihood function (a Normal log-likelihood that ignores the normalisation), which takes in the list/array/tuple of model parameter values `theta`, the points at which to calculate the model `x`, the vector of \"observed\" data points `data`, and the standard deviation of the noise in the data `sigma`.", "_____no_output_____" ] ], [ [ "%%cython -I/usr/include -L/usr/lib/x86_64-linux-gnu -lgsl -lgslcblas -lm\n\nimport cython\ncimport cython\n\nimport numpy as np\ncimport numpy as np\n\n### STUFF FOR USING GSL (FEEL FREE TO IGNORE!) ###\n\n# declare GSL vector structure and functions\ncdef extern from \"gsl/gsl_block.h\":\n cdef struct gsl_block:\n size_t size\n double * data\n\ncdef extern from \"gsl/gsl_vector.h\":\n cdef struct gsl_vector:\n size_t size\n size_t stride\n double * data\n gsl_block * block\n int owner\n\n ctypedef struct gsl_vector_view:\n gsl_vector vector\n\n int gsl_vector_scale (gsl_vector * a, const double x) nogil\n int gsl_vector_add_constant (gsl_vector * a, const double x) nogil\n gsl_vector_view gsl_vector_view_array (double * base, size_t n) nogil\n\n###################################################\n\n\n# define your super-complicated model that uses load of external codes\ncpdef my_model(theta, np.ndarray[np.float64_t, ndim=1] x):\n \"\"\"\n A straight line!\n\n Note:\n This function could simply be:\n\n m, c = thetha\n return m*x + x\n\n but I've made it more complicated for demonstration purposes\n \"\"\"\n m, c = theta # unpack line gradient and y-intercept\n\n cdef size_t length = len(x) # length of x\n\n cdef np.ndarray line = np.copy(x) # make copy of x vector\n cdef gsl_vector_view lineview # create a view of the vector\n lineview = gsl_vector_view_array(<double *>line.data, length) \n\n # multiply x by m\n gsl_vector_scale(&lineview.vector, <double>m)\n\n # add c\n gsl_vector_add_constant(&lineview.vector, <double>c)\n\n # return the numpy array\n return line\n\n\n# define your really-complicated likelihood function that uses loads of external codes\ncpdef my_loglike(theta, np.ndarray[np.float64_t, ndim=1] x,\n np.ndarray[np.float64_t, ndim=1] data, sigma):\n \"\"\"\n A Gaussian log-likelihood function for a model with parameters given in theta\n \"\"\"\n\n model = my_model(theta, x)\n\n return -(0.5/sigma**2)*np.sum((data - model)**2)", "_____no_output_____" ] ], [ [ "Now, as things are, if we wanted to sample from this log-likelihood function, using certain prior distributions for the model parameters (gradient and y-intercept) using PyMC3 we might try something like this (using a [PyMC3 `DensityDist`](https://docs.pymc.io/prob_dists.html#custom-distributions)):\n\n```python\nimport pymc3 as pm\n\n# create/read in our \"data\" (I'll show this in the real example below)\nx = ...\nsigma = ...\ndata = ...\n\nwith pm.Model():\n # set priors on model gradient and y-intercept\n m = pm.Uniform('m', lower=-10., upper=10.)\n c = pm.Uniform('c', lower=-10., upper=10.)\n\n # create custom distribution \n pm.DensityDist('likelihood', my_loglike,\n observed={'theta': (m, c), 'x': x, 'data': data, 'sigma': sigma})\n \n # sample from the distribution\n trace = pm.sample(1000)\n```\n\nBut, this will give an error like:\n\n```\nValueError: setting an array element with a sequence.\n```\n\nThis is because `m` and `c` are Theano tensor-type objects.\n\nSo, what we actually need to do is create a [Theano Op](http://deeplearning.net/software/theano/extending/extending_theano.html). This will be a new class that wraps our log-likelihood function (or just our model function, if that is all that is required) into something that can take in Theano tensor objects, but internally can cast them as floating point values that can be passed to our log-likelihood function. I will do this below, initially without defining a [`grad()` method](http://deeplearning.net/software/theano/extending/op.html#grad) for the Op.", "_____no_output_____" ] ], [ [ "# define a theano Op for our likelihood function\nclass LogLike(tt.Op):\n\n \"\"\"\n Specify what type of object will be passed and returned to the Op when it is\n called. In our case we will be passing it a vector of values (the parameters\n that define our model) and returning a single \"scalar\" value (the\n log-likelihood)\n \"\"\"\n itypes = [tt.dvector] # expects a vector of parameter values when called\n otypes = [tt.dscalar] # outputs a single scalar value (the log likelihood)\n \n def __init__(self, loglike, data, x, sigma):\n \"\"\"\n Initialise the Op with various things that our log-likelihood function\n requires. Below are the things that are needed in this particular\n example.\n\n Parameters\n ----------\n loglike:\n The log-likelihood (or whatever) function we've defined\n data:\n The \"observed\" data that our log-likelihood function takes in\n x:\n The dependent variable (aka 'x') that our model requires\n sigma:\n The noise standard deviation that our function requires.\n \"\"\"\n\n # add inputs as class attributes\n self.likelihood = loglike\n self.data = data\n self.x = x\n self.sigma = sigma\n\n def perform(self, node, inputs, outputs):\n # the method that is used when calling the Op\n theta, = inputs # this will contain my variables\n \n # call the log-likelihood function\n logl = self.likelihood(theta, self.x, self.data, self.sigma)\n\n outputs[0][0] = np.array(logl) # output the log-likelihood", "_____no_output_____" ] ], [ [ "Now, let's use this Op to repeat the example shown above. To do this I'll create some data containing a straight line with additive Gaussian noise (with a mean of zero and a standard deviation of `sigma`). I'll set uniform prior distributions on the gradient and y-intercept. As I've not set the `grad()` method of the Op PyMC3 will not be able to use the gradient-based samplers, so will fall back to using the [Slice](https://docs.pymc.io/api/inference.html#module-pymc3.step_methods.slicer) sampler.", "_____no_output_____" ] ], [ [ "# set up our data\nN = 10 # number of data points\nsigma = 1. # standard deviation of noise\nx = np.linspace(0., 9., N)\n\nmtrue = 0.4 # true gradient\nctrue = 3. # true y-intercept\n\ntruemodel = my_model([mtrue, ctrue], x)\n\n# make data\ndata = sigma*np.random.randn(N) + truemodel\n\nndraws = 3000 # number of draws from the distribution\nnburn = 1000 # number of \"burn-in points\" (which we'll discard)\n\n# create our Op\nlogl = LogLike(my_loglike, data, x, sigma)\n\n# use PyMC3 to sampler from log-likelihood\nwith pm.Model():\n # uniform priors on m and c\n m = pm.Uniform('m', lower=-10., upper=10.)\n c = pm.Uniform('c', lower=-10., upper=10.)\n\n # convert m and c to a tensor vector\n theta = tt.as_tensor_variable([m, c])\n\n # use a DensityDist (use a lamdba function to \"call\" the Op)\n pm.DensityDist('likelihood', lambda v: logl(v), observed={'v': theta})\n \n trace = pm.sample(ndraws, tune=nburn, discard_tuned_samples=True)\n\n# plot the traces\n_ = pm.traceplot(trace, lines=(('m', {}, [mtrue]), ('c', {}, [ctrue])))\n\n# put the chains in an array (for later!)\nsamples_pymc3 = np.vstack((trace['m'], trace['c'])).T", "Auto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nInitializing NUTS failed. Falling back to elementwise auto-assignment.\nMultiprocess sampling (4 chains in 4 jobs)\nCompoundStep\n>Slice: [c]\n>Slice: [m]\nSampling 4 chains, 0 divergences: 100%|██████████| 16000/16000 [00:03<00:00, 4165.21draws/s]\nThe number of effective samples is smaller than 25% for some parameters.\n" ] ], [ [ "What if we wanted to use NUTS or HMC? If we knew the analytical derivatives of the model/likelihood function then we could add a [`grad()` method](http://deeplearning.net/software/theano/extending/op.html#grad) to the Op using that analytical form.\n\nBut, what if we don't know the analytical form. If our model/likelihood is purely Python and made up of standard maths operators and Numpy functions, then the [autograd](https://github.com/HIPS/autograd) module could potentially be used to find gradients (also, see [here](https://github.com/ActiveState/code/blob/master/recipes/Python/580610_Auto_differentiation/recipe-580610.py) for a nice Python example of automatic differentiation). But, if our model/likelihood truely is a \"black box\" then we can just use the good-old-fashioned [finite difference](https://en.wikipedia.org/wiki/Finite_difference) to find the gradients - this can be slow, especially if there are a large number of variables, or the model takes a long time to evaluate. Below, I've written a function that uses finite difference (the central difference) to find gradients - it uses an iterative method with successively smaller step sizes to check that the gradient converges. But, you could do something far simpler and just use, for example, the SciPy [`approx_fprime`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.approx_fprime.html) function.", "_____no_output_____" ] ], [ [ "import warnings\n\ndef gradients(vals, func, releps=1e-3, abseps=None, mineps=1e-9, reltol=1e-3,\n epsscale=0.5):\n \"\"\"\n Calculate the partial derivatives of a function at a set of values. The\n derivatives are calculated using the central difference, using an iterative\n method to check that the values converge as step size decreases.\n\n Parameters\n ----------\n vals: array_like\n A set of values, that are passed to a function, at which to calculate\n the gradient of that function\n func:\n A function that takes in an array of values.\n releps: float, array_like, 1e-3\n The initial relative step size for calculating the derivative.\n abseps: float, array_like, None\n The initial absolute step size for calculating the derivative.\n This overrides `releps` if set.\n `releps` is set then that is used.\n mineps: float, 1e-9\n The minimum relative step size at which to stop iterations if no\n convergence is achieved.\n epsscale: float, 0.5\n The factor by which releps if scaled in each iteration.\n \n Returns\n -------\n grads: array_like\n An array of gradients for each non-fixed value.\n \"\"\"\n\n grads = np.zeros(len(vals))\n\n # maximum number of times the gradient can change sign\n flipflopmax = 10.\n\n # set steps\n if abseps is None:\n if isinstance(releps, float):\n eps = np.abs(vals)*releps\n eps[eps == 0.] = releps # if any values are zero set eps to releps\n teps = releps*np.ones(len(vals))\n elif isinstance(releps, (list, np.ndarray)):\n if len(releps) != len(vals):\n raise ValueError(\"Problem with input relative step sizes\")\n eps = np.multiply(np.abs(vals), releps)\n eps[eps == 0.] = np.array(releps)[eps == 0.]\n teps = releps\n else:\n raise RuntimeError(\"Relative step sizes are not a recognised type!\")\n else:\n if isinstance(abseps, float):\n eps = abseps*np.ones(len(vals))\n elif isinstance(abseps, (list, np.ndarray)):\n if len(abseps) != len(vals):\n raise ValueError(\"Problem with input absolute step sizes\")\n eps = np.array(abseps)\n else:\n raise RuntimeError(\"Absolute step sizes are not a recognised type!\")\n teps = eps\n\n # for each value in vals calculate the gradient\n count = 0\n for i in range(len(vals)):\n # initial parameter diffs\n leps = eps[i]\n cureps = teps[i]\n\n flipflop = 0\n\n # get central finite difference\n fvals = np.copy(vals)\n bvals = np.copy(vals)\n\n # central difference\n fvals[i] += 0.5*leps # change forwards distance to half eps\n bvals[i] -= 0.5*leps # change backwards distance to half eps\n cdiff = (func(fvals)-func(bvals))/leps\n\n while 1:\n fvals[i] -= 0.5*leps # remove old step\n bvals[i] += 0.5*leps\n\n # change the difference by a factor of two\n cureps *= epsscale\n if cureps < mineps or flipflop > flipflopmax:\n # if no convergence set flat derivative (TODO: check if there is a better thing to do instead)\n warnings.warn(\"Derivative calculation did not converge: setting flat derivative.\")\n grads[count] = 0.\n break\n leps *= epsscale\n\n # central difference\n fvals[i] += 0.5*leps # change forwards distance to half eps\n bvals[i] -= 0.5*leps # change backwards distance to half eps\n cdiffnew = (func(fvals)-func(bvals))/leps\n\n if cdiffnew == cdiff:\n grads[count] = cdiff\n break\n\n # check whether previous diff and current diff are the same within reltol\n rat = (cdiff/cdiffnew)\n if np.isfinite(rat) and rat > 0.:\n # gradient has not changed sign\n if np.abs(1.-rat) < reltol:\n grads[count] = cdiffnew\n break\n else:\n cdiff = cdiffnew\n continue\n else:\n cdiff = cdiffnew\n flipflop += 1\n continue\n\n count += 1\n\n return grads", "_____no_output_____" ] ], [ [ "So, now we can just redefine our Op with a `grad()` method, right?\n\nIt's not quite so simple! The `grad()` method itself requires that its inputs are Theano tensor variables, whereas our `gradients` function above, like our `my_loglike` function, wants a list of floating point values. So, we need to define another Op that calculates the gradients. Below, I define a new version of the `LogLike` Op, called `LogLikeWithGrad` this time, that has a `grad()` method. This is followed by anothor Op called `LogLikeGrad` that, when called with a vector of Theano tensor variables, returns another vector of values that are the gradients (i.e., the [Jacobian](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant)) of our log-likelihood function at those values. Note that the `grad()` method itself does not return the gradients directly, but instead returns the [Jacobian](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant)-vector product (you can hopefully just copy what I've done and not worry about what this means too much!).", "_____no_output_____" ] ], [ [ "# define a theano Op for our likelihood function\nclass LogLikeWithGrad(tt.Op):\n\n itypes = [tt.dvector] # expects a vector of parameter values when called\n otypes = [tt.dscalar] # outputs a single scalar value (the log likelihood)\n\n def __init__(self, loglike, data, x, sigma):\n \"\"\"\n Initialise with various things that the function requires. Below\n are the things that are needed in this particular example.\n \n Parameters\n ----------\n loglike:\n The log-likelihood (or whatever) function we've defined\n data:\n The \"observed\" data that our log-likelihood function takes in\n x:\n The dependent variable (aka 'x') that our model requires\n sigma:\n The noise standard deviation that out function requires.\n \"\"\"\n\n # add inputs as class attributes\n self.likelihood = loglike\n self.data = data\n self.x = x\n self.sigma = sigma\n\n # initialise the gradient Op (below)\n self.logpgrad = LogLikeGrad(self.likelihood, self.data, self.x, self.sigma)\n\n def perform(self, node, inputs, outputs):\n # the method that is used when calling the Op\n theta, = inputs # this will contain my variables\n \n # call the log-likelihood function\n logl = self.likelihood(theta, self.x, self.data, self.sigma)\n\n outputs[0][0] = np.array(logl) # output the log-likelihood\n\n def grad(self, inputs, g):\n # the method that calculates the gradients - it actually returns the\n # vector-Jacobian product - g[0] is a vector of parameter values \n theta, = inputs # our parameters \n return [g[0]*self.logpgrad(theta)]\n\n\nclass LogLikeGrad(tt.Op):\n\n \"\"\"\n This Op will be called with a vector of values and also return a vector of\n values - the gradients in each dimension.\n \"\"\"\n itypes = [tt.dvector]\n otypes = [tt.dvector]\n\n def __init__(self, loglike, data, x, sigma):\n \"\"\"\n Initialise with various things that the function requires. Below\n are the things that are needed in this particular example.\n\n Parameters\n ----------\n loglike:\n The log-likelihood (or whatever) function we've defined\n data:\n The \"observed\" data that our log-likelihood function takes in\n x:\n The dependent variable (aka 'x') that our model requires\n sigma:\n The noise standard deviation that out function requires.\n \"\"\"\n\n # add inputs as class attributes\n self.likelihood = loglike\n self.data = data\n self.x = x\n self.sigma = sigma\n\n def perform(self, node, inputs, outputs):\n theta, = inputs\n\n # define version of likelihood function to pass to derivative function\n def lnlike(values):\n return self.likelihood(values, self.x, self.data, self.sigma)\n\n # calculate gradients\n grads = gradients(theta, lnlike)\n\n outputs[0][0] = grads", "_____no_output_____" ] ], [ [ "Now, let's re-run PyMC3 with our new \"grad\"-ed Op. This time it will be able to automatically use NUTS.\n\n_Aside: As an addition, I've also defined a `my_model_random` function (note that, in this case, it requires that the `x` variable needed by the model function is global). This is used by the `random` argument of [`DensityDist`](https://docs.pymc.io/api/distributions/utilities.html?highlight=densitydist#pymc3.distributions.DensityDist) to define a function to use to draw instances of the model using the sampled parameters for [posterior predictive](https://docs.pymc.io/api/inference.html?highlight=sample_posterior_predictive#pymc3.sampling.sample_posterior_predictive) checks. This is only really needed if you want to fo posterior predictive check, but otherwise can be left out._", "_____no_output_____" ] ], [ [ "# create our Op\nlogl = LogLikeWithGrad(my_loglike, data, x, sigma)\n\n\ndef my_model_random(point=None, size=None):\n \"\"\"\n Draw posterior predictive samples from model.\n \"\"\"\n\n return my_model((point[\"m\"], point[\"c\"]), x)\n\n\n# use PyMC3 to sampler from log-likelihood\nwith pm.Model() as opmodel:\n # uniform priors on m and c\n m = pm.Uniform('m', lower=-10., upper=10.)\n c = pm.Uniform('c', lower=-10., upper=10.)\n\n # convert m and c to a tensor vector\n theta = tt.as_tensor_variable([m, c])\n\n # use a DensityDist\n pm.DensityDist(\n 'likelihood',\n lambda v: logl(v),\n observed={'v': theta},\n random=my_model_random,\n )\n\n trace = pm.sample(ndraws, tune=nburn, discard_tuned_samples=True)\n\n# plot the traces\n_ = pm.traceplot(trace, lines=(('m', {}, [mtrue]), ('c', {}, [ctrue])))\n\n# put the chains in an array (for later!)\nsamples_pymc3_2 = np.vstack((trace['m'], trace['c'])).T", "Auto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nMultiprocess sampling (4 chains in 4 jobs)\nNUTS: [c, m]\nSampling 4 chains, 0 divergences: 100%|██████████| 16000/16000 [00:07<00:00, 2276.01draws/s]\nThe number of effective samples is smaller than 25% for some parameters.\n" ], [ "# just because we can, let's draw posterior predictive samples of the model\nppc = pm.sample_posterior_predictive(trace, samples=250, model=opmodel)\n\nfor vals in ppc['likelihood']:\n matplotlib.pyplot.plot(x, vals, color='b', alpha=0.05, lw=3)\nmatplotlib.pyplot.plot(x, my_model((mtrue, ctrue), x), 'k--', lw=2)", "/home/matthew/miniconda2/envs/samplers-demo/lib/python3.7/site-packages/pymc3/sampling.py:1247: UserWarning: samples parameter is smaller than nchains times ndraws, some draws and/or chains may not be represented in the returned posterior predictive sample\n \"samples parameter is smaller than nchains times ndraws, some draws \"\n100%|██████████| 250/250 [00:00<00:00, 4021.01it/s]\n" ] ], [ [ "Now, finally, just to check things actually worked as we might expect, let's do the same thing purely using PyMC3 distributions (because in this simple example we can!)", "_____no_output_____" ] ], [ [ "with pm.Model() as pymodel:\n # uniform priors on m and c\n m = pm.Uniform('m', lower=-10., upper=10.)\n c = pm.Uniform('c', lower=-10., upper=10.)\n\n # convert m and c to a tensor vector\n theta = tt.as_tensor_variable([m, c])\n\n # use a Normal distribution\n pm.Normal('likelihood', mu=(m*x + c), sd = sigma, observed=data)\n \n trace = pm.sample(ndraws, tune=nburn, discard_tuned_samples=True)\n\n# plot the traces\n_ = pm.traceplot(trace, lines=(('m', {}, [mtrue]), ('c', {}, [ctrue])))\n\n# put the chains in an array (for later!)\nsamples_pymc3_3 = np.vstack((trace['m'], trace['c'])).T", "Auto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nMultiprocess sampling (4 chains in 4 jobs)\nNUTS: [c, m]\nSampling 4 chains, 0 divergences: 100%|██████████| 16000/16000 [00:03<00:00, 4850.74draws/s]\nThe number of effective samples is smaller than 25% for some parameters.\n" ] ], [ [ "To check that they match let's plot all the examples together and also find the autocorrelation lengths.", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning) # supress emcee autocorr FutureWarning\n\nmatplotlib.rcParams['font.size'] = 22\n\nhist2dkwargs = {'plot_datapoints': False,\n 'plot_density': False,\n 'levels': 1.0 - np.exp(-0.5 * np.arange(1.5, 2.1, 0.5) ** 2)} # roughly 1 and 2 sigma\n\ncolors = ['r', 'g', 'b']\nlabels = ['Theanp Op (no grad)', 'Theano Op (with grad)', 'Pure PyMC3']\n\nfor i, samples in enumerate([samples_pymc3, samples_pymc3_2, samples_pymc3_3]):\n # get maximum chain autocorrelartion length\n autocorrlen = int(np.max(emcee.autocorr.integrated_time(samples, c=3)));\n print('Auto-correlation length ({}): {}'.format(labels[i], autocorrlen))\n\n if i == 0:\n fig = corner.corner(samples, labels=[r\"$m$\", r\"$c$\"], color=colors[i],\n hist_kwargs={'density': True}, **hist2dkwargs,\n truths=[mtrue, ctrue])\n else:\n corner.corner(samples, color=colors[i], hist_kwargs={'density': True},\n fig=fig, **hist2dkwargs)\n\nfig.set_size_inches(9, 9)", "Auto-correlation length (Theanp Op (no grad)): 5\nAuto-correlation length (Theano Op (with grad)): 4\nAuto-correlation length (Pure PyMC3): 4\n" ] ], [ [ "We can now check that the gradient Op works as we expect it to. First, just create and call the `LogLikeGrad` class, which should return the gradient directly (note that we have to create a [Theano function](http://deeplearning.net/software/theano/library/compile/function.html) to convert the output of the Op to an array). Secondly, we call the gradient from `LogLikeWithGrad` by using the [Theano tensor gradient](http://deeplearning.net/software/theano/library/gradient.html#theano.gradient.grad) function. Finally, we will check the gradient returned by the PyMC3 model for a Normal distribution, which should be the same as the log-likelihood function we defined. In all cases we evaluate the gradients at the true values of the model function (the straight line) that was created.", "_____no_output_____" ] ], [ [ "# test the gradient Op by direct call\ntheano.config.compute_test_value = \"ignore\"\ntheano.config.exception_verbosity = \"high\"\n\nvar = tt.dvector()\ntest_grad_op = LogLikeGrad(my_loglike, data, x, sigma)\ntest_grad_op_func = theano.function([var], test_grad_op(var))\ngrad_vals = test_grad_op_func([mtrue, ctrue])\n\nprint('Gradient returned by \"LogLikeGrad\": {}'.format(grad_vals))\n\n# test the gradient called through LogLikeWithGrad\ntest_gradded_op = LogLikeWithGrad(my_loglike, data, x, sigma)\ntest_gradded_op_grad = tt.grad(test_gradded_op(var), var)\ntest_gradded_op_grad_func = theano.function([var], test_gradded_op_grad)\ngrad_vals_2 = test_gradded_op_grad_func([mtrue, ctrue])\n\nprint('Gradient returned by \"LogLikeWithGrad\": {}'.format(grad_vals_2))\n\n# test the gradient that PyMC3 uses for the Normal log likelihood\ntest_model = pm.Model()\nwith test_model:\n m = pm.Uniform('m', lower=-10., upper=10.)\n c = pm.Uniform('c', lower=-10., upper=10.)\n\n pm.Normal('likelihood', mu=(m*x + c), sigma=sigma, observed=data)\n\n gradfunc = test_model.logp_dlogp_function([m, c], dtype=None)\n gradfunc.set_extra_values({'m_interval__': mtrue, 'c_interval__': ctrue})\n grad_vals_pymc3 = gradfunc(np.array([mtrue, ctrue]))[1] # get dlogp values\n\nprint('Gradient returned by PyMC3 \"Normal\" distribution: {}'.format(grad_vals_pymc3))", "Gradient returned by \"LogLikeGrad\": [9.48408954 0.33352422]\nGradient returned by \"LogLikeWithGrad\": [9.48408954 0.33352422]\nGradient returned by PyMC3 \"Normal\" distribution: [9.48408954 0.33352422]\n" ] ], [ [ "We can also do some [profiling](http://docs.pymc.io/notebooks/profiling.html) of the Op, as used within a PyMC3 Model, to check performance. First, we'll profile using the `LogLikeWithGrad` Op, and then doing the same thing purely using PyMC3 distributions.", "_____no_output_____" ] ], [ [ "# profile logpt using our Op\nopmodel.profile(opmodel.logpt).summary()", "Function profiling\n==================\n Message: /home/matthew/miniconda2/envs/samplers-demo/lib/python3.7/site-packages/pymc3/model.py:1023\n Time in 1000 calls to Function.__call__: 3.343105e-02s\n Time in Function.fn.__call__: 2.131295e-02s (63.752%)\n Time in thunks: 1.855898e-02s (55.514%)\n Total compile time: 6.649518e-02s\n Number of Apply nodes: 8\n Theano Optimizer time: 5.379820e-02s\n Theano validate time: 4.024506e-04s\n Theano Linker time (includes C, CUDA code generation/compiling): 4.861355e-03s\n Import time 0.000000e+00s\n Node make_thunk time 4.477501e-03s\n Node Elemwise{Composite{((i0 + Switch(Cast{int8}((GE(i1, i2) * LE(i1, i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 1)](TensorConstant{2.995732273553991}, c, TensorConstant{-10.0}, TensorConstant{10.0}, TensorConstant{-2.995732273553991}, TensorConstant{-inf}, TensorConstant{2.0}, c_interval__) time 1.496315e-03s\n Node Elemwise{Composite{((i0 + Switch(Cast{int8}((GE(i1, i2) * LE(i1, i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 1)](TensorConstant{2.995732273553991}, m, TensorConstant{-10.0}, TensorConstant{10.0}, TensorConstant{-2.995732273553991}, TensorConstant{-inf}, TensorConstant{2.0}, m_interval__) time 7.832050e-04s\n Node Elemwise{Composite{(i0 + (i1 * scalar_sigmoid(i2)))}}(TensorConstant{-10.0}, TensorConstant{20.0}, c_interval__) time 5.435944e-04s\n Node Elemwise{Composite{(i0 + (i1 * scalar_sigmoid(i2)))}}(TensorConstant{-10.0}, TensorConstant{20.0}, m_interval__) time 5.145073e-04s\n Node <__main__.LogLikeWithGrad object at 0x7fc0b82ae290>(MakeVector{dtype='float64'}.0) time 3.354549e-04s\n\nTime in all call to theano.grad() 5.761380e-01s\nTime since theano import 28.990s\nClass\n---\n<% time> <sum %> <apply time> <time per call> <type> <#call> <#apply> <Class name>\n 93.7% 93.7% 0.017s 1.74e-05s Py 1000 1 __main__.LogLikeWithGrad\n 3.8% 97.5% 0.001s 1.76e-07s C 4000 4 theano.tensor.elemwise.Elemwise\n 1.9% 99.4% 0.000s 1.74e-07s C 2000 2 theano.tensor.opt.MakeVector\n 0.6% 100.0% 0.000s 1.18e-07s C 1000 1 theano.tensor.elemwise.Sum\n ... (remaining 0 Classes account for 0.00%(0.00s) of the runtime)\n\nOps\n---\n<% time> <sum %> <apply time> <time per call> <type> <#call> <#apply> <Op name>\n 93.7% 93.7% 0.017s 1.74e-05s Py 1000 1 <__main__.LogLikeWithGrad object at 0x7fc0b82ae290>\n 1.9% 95.6% 0.000s 1.77e-07s C 2000 2 Elemwise{Composite{(i0 + (i1 * scalar_sigmoid(i2)))}}\n 1.9% 97.5% 0.000s 1.74e-07s C 2000 2 Elemwise{Composite{((i0 + Switch(Cast{int8}((GE(i1, i2) * LE(i1, i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 1)]\n 1.9% 99.4% 0.000s 1.74e-07s C 2000 2 MakeVector{dtype='float64'}\n 0.6% 100.0% 0.000s 1.18e-07s C 1000 1 Sum{acc_dtype=float64}\n ... (remaining 0 Ops account for 0.00%(0.00s) of the runtime)\n\nApply\n------\n<% time> <sum %> <apply time> <time per call> <#call> <id> <Apply name>\n 93.7% 93.7% 0.017s 1.74e-05s 1000 5 <__main__.LogLikeWithGrad object at 0x7fc0b82ae290>(MakeVector{dtype='float64'}.0)\n 1.5% 95.1% 0.000s 2.69e-07s 1000 1 Elemwise{Composite{(i0 + (i1 * scalar_sigmoid(i2)))}}(TensorConstant{-10.0}, TensorConstant{20.0}, m_interval__)\n 1.3% 96.4% 0.000s 2.38e-07s 1000 4 Elemwise{Composite{((i0 + Switch(Cast{int8}((GE(i1, i2) * LE(i1, i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 1)](TensorConstant{2.995732273553991}, m, TensorConstant{-10.0}, TensorConstant{10.0}, TensorConstant{-2.995732273553991}, TensorConstant{-inf}, TensorConstant{2.0}, m_interval__)\n 1.0% 97.4% 0.000s 1.85e-07s 1000 6 MakeVector{dtype='float64'}(__logp_m_interval__, __logp_c_interval__, __logp_likelihood)\n 0.9% 98.3% 0.000s 1.63e-07s 1000 2 MakeVector{dtype='float64'}(m, c)\n 0.6% 98.9% 0.000s 1.18e-07s 1000 7 Sum{acc_dtype=float64}(MakeVector{dtype='float64'}.0)\n 0.6% 99.5% 0.000s 1.10e-07s 1000 3 Elemwise{Composite{((i0 + Switch(Cast{int8}((GE(i1, i2) * LE(i1, i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 1)](TensorConstant{2.995732273553991}, c, TensorConstant{-10.0}, TensorConstant{10.0}, TensorConstant{-2.995732273553991}, TensorConstant{-inf}, TensorConstant{2.0}, c_interval__)\n 0.5% 100.0% 0.000s 8.54e-08s 1000 0 Elemwise{Composite{(i0 + (i1 * scalar_sigmoid(i2)))}}(TensorConstant{-10.0}, TensorConstant{20.0}, c_interval__)\n ... (remaining 0 Apply instances account for 0.00%(0.00s) of the runtime)\n\nHere are tips to potentially make your code run faster\n (if you think of new ones, suggest them on the mailing list).\n Test them first, as they are not guaranteed to always provide a speedup.\n - Try the Theano flag floatX=float32\n - Try installing amdlibm and set the Theano flag lib.amdlibm=True. This speeds up only some Elemwise operation.\n" ], [ "# profile using our PyMC3 distribution\npymodel.profile(pymodel.logpt).summary()", "Function profiling\n==================\n Message: /home/matthew/miniconda2/envs/samplers-demo/lib/python3.7/site-packages/pymc3/model.py:1023\n Time in 1000 calls to Function.__call__: 1.361871e-02s\n Time in Function.fn.__call__: 3.993511e-03s (29.324%)\n Time in thunks: 1.495838e-03s (10.984%)\n Total compile time: 1.101401e-01s\n Number of Apply nodes: 11\n Theano Optimizer time: 9.528971e-02s\n Theano validate time: 7.157326e-04s\n Theano Linker time (includes C, CUDA code generation/compiling): 7.575274e-03s\n Import time 8.027554e-04s\n Node make_thunk time 7.098913e-03s\n Node Elemwise{Composite{((i0 + Switch(Cast{int8}((GE((i1 + i2), i1) * LE((i1 + i2), i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 2)](TensorConstant{2.995732273553991}, TensorConstant{-10.0}, Elemwise{Composite{(i0 * scalar_sigmoid(i1))}}.0, TensorConstant{10.0}, TensorConstant{-2.995732273553991}, TensorConstant{-inf}, TensorConstant{2.0}, c_interval__) time 1.247644e-03s\n Node Elemwise{Composite{(i0 * scalar_sigmoid(i1))}}(TensorConstant{20.0}, c_interval__) time 1.117229e-03s\n Node Elemwise{Composite{((i0 + Switch(Cast{int8}((GE(i1, i2) * LE(i1, i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 1)](TensorConstant{2.995732273553991}, m, TensorConstant{-10.0}, TensorConstant{10.0}, TensorConstant{-2.995732273553991}, TensorConstant{-inf}, TensorConstant{2.0}, m_interval__) time 8.914471e-04s\n Node InplaceDimShuffle{x}(Elemwise{Composite{(i0 * scalar_sigmoid(i1))}}.0) time 7.741451e-04s\n Node InplaceDimShuffle{x}(m) time 6.864071e-04s\n\nTime in all call to theano.grad() 5.761380e-01s\nTime since theano import 29.161s\nClass\n---\n<% time> <sum %> <apply time> <time per call> <type> <#call> <#apply> <Class name>\n 57.3% 57.3% 0.001s 1.43e-07s C 6000 6 theano.tensor.elemwise.Elemwise\n 24.3% 81.6% 0.000s 1.82e-07s C 2000 2 theano.tensor.elemwise.DimShuffle\n 10.6% 92.2% 0.000s 7.89e-08s C 2000 2 theano.tensor.elemwise.Sum\n 7.8% 100.0% 0.000s 1.17e-07s C 1000 1 theano.tensor.opt.MakeVector\n ... (remaining 0 Classes account for 0.00%(0.00s) of the runtime)\n\nOps\n---\n<% time> <sum %> <apply time> <time per call> <type> <#call> <#apply> <Op name>\n 24.3% 24.3% 0.000s 1.82e-07s C 2000 2 InplaceDimShuffle{x}\n 13.7% 38.0% 0.000s 2.05e-07s C 1000 1 Elemwise{Composite{(i0 + (-sqr((i1 - ((i2 * i3) + i4)))))}}\n 11.7% 49.7% 0.000s 1.75e-07s C 1000 1 Elemwise{Composite{((i0 + Switch(Cast{int8}((GE(i1, i2) * LE(i1, i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 1)]\n 10.6% 60.2% 0.000s 7.89e-08s C 2000 2 Sum{acc_dtype=float64}\n 9.7% 70.0% 0.000s 1.45e-07s C 1000 1 Elemwise{Composite{(i0 + (i1 * scalar_sigmoid(i2)))}}\n 8.7% 78.7% 0.000s 1.30e-07s C 1000 1 Elemwise{Composite{(i0 * scalar_sigmoid(i1))}}\n 7.8% 86.5% 0.000s 1.17e-07s C 1000 1 MakeVector{dtype='float64'}\n 7.7% 94.2% 0.000s 1.16e-07s C 1000 1 Elemwise{Composite{((i0 + Switch(Cast{int8}((GE((i1 + i2), i1) * LE((i1 + i2), i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 2)]\n 5.8% 100.0% 0.000s 8.65e-08s C 1000 1 Elemwise{Mul}[(0, 1)]\n ... (remaining 0 Ops account for 0.00%(0.00s) of the runtime)\n\nApply\n------\n<% time> <sum %> <apply time> <time per call> <#call> <id> <Apply name>\n 15.4% 15.4% 0.000s 2.31e-07s 1000 3 InplaceDimShuffle{x}(m)\n 13.7% 29.2% 0.000s 2.05e-07s 1000 4 Elemwise{Composite{(i0 + (-sqr((i1 - ((i2 * i3) + i4)))))}}(TensorConstant{(1,) of -1..0664093453}, TensorConstant{[13.403875...78903567]}, InplaceDimShuffle{x}.0, TensorConstant{[0. 1. 2. .. 7. 8. 9.]}, InplaceDimShuffle{x}.0)\n 11.7% 40.8% 0.000s 1.75e-07s 1000 6 Elemwise{Composite{((i0 + Switch(Cast{int8}((GE(i1, i2) * LE(i1, i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 1)](TensorConstant{2.995732273553991}, m, TensorConstant{-10.0}, TensorConstant{10.0}, TensorConstant{-2.995732273553991}, TensorConstant{-inf}, TensorConstant{2.0}, m_interval__)\n 9.7% 50.5% 0.000s 1.45e-07s 1000 1 Elemwise{Composite{(i0 + (i1 * scalar_sigmoid(i2)))}}(TensorConstant{-10.0}, TensorConstant{20.0}, m_interval__)\n 8.9% 59.4% 0.000s 1.33e-07s 1000 2 InplaceDimShuffle{x}(Elemwise{Composite{(i0 * scalar_sigmoid(i1))}}.0)\n 8.7% 68.1% 0.000s 1.30e-07s 1000 0 Elemwise{Composite{(i0 * scalar_sigmoid(i1))}}(TensorConstant{20.0}, c_interval__)\n 7.8% 75.9% 0.000s 1.17e-07s 1000 9 MakeVector{dtype='float64'}(__logp_m_interval__, __logp_c_interval__, __logp_likelihood)\n 7.7% 83.7% 0.000s 1.16e-07s 1000 5 Elemwise{Composite{((i0 + Switch(Cast{int8}((GE((i1 + i2), i1) * LE((i1 + i2), i3))), i4, i5)) - ((i6 * scalar_softplus((-i7))) + i7))}}[(0, 2)](TensorConstant{2.995732273553991}, TensorConstant{-10.0}, Elemwise{Composite{(i0 * scalar_sigmoid(i1))}}.0, TensorConstant{10.0}, TensorConstant{-2.995732273553991}, TensorConstant{-inf}, TensorConstant{2.0}, c_interval__)\n 6.6% 90.3% 0.000s 9.94e-08s 1000 7 Sum{acc_dtype=float64}(Elemwise{Composite{(i0 + (-sqr((i1 - ((i2 * i3) + i4)))))}}.0)\n 5.8% 96.1% 0.000s 8.65e-08s 1000 8 Elemwise{Mul}[(0, 1)](TensorConstant{0.5}, Sum{acc_dtype=float64}.0)\n 3.9% 100.0% 0.000s 5.84e-08s 1000 10 Sum{acc_dtype=float64}(MakeVector{dtype='float64'}.0)\n ... (remaining 0 Apply instances account for 0.00%(0.00s) of the runtime)\n\nHere are tips to potentially make your code run faster\n (if you think of new ones, suggest them on the mailing list).\n Test them first, as they are not guaranteed to always provide a speedup.\n - Try the Theano flag floatX=float32\n - Try installing amdlibm and set the Theano flag lib.amdlibm=True. This speeds up only some Elemwise operation.\n" ] ], [ [ "The Jupyter notebook used to produce this page can be downloaded from [here](http://mattpitkin.github.io/samplers-demo/downloads/notebooks/PyMC3CustomExternalLikelihood.ipynb).", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cbdffcbe5b0b41341b958af6f566959bbc60c2f5
12,403
ipynb
Jupyter Notebook
examples/HighMap.ipynb
MarcSkovMadsen/panel-highcharts
a2b2b0ecb7b271ec477d57087b7d50ffdffe5e46
[ "MIT" ]
107
2021-04-04T14:11:27.000Z
2022-03-30T09:08:43.000Z
examples/HighMap.ipynb
MarcSkovMadsen/panel-highcharts
a2b2b0ecb7b271ec477d57087b7d50ffdffe5e46
[ "MIT" ]
8
2021-05-05T00:54:28.000Z
2022-03-31T09:37:07.000Z
examples/HighMap.ipynb
MarcSkovMadsen/panel-highcharts
a2b2b0ecb7b271ec477d57087b7d50ffdffe5e46
[ "MIT" ]
14
2021-05-03T00:15:11.000Z
2022-01-01T09:33:46.000Z
29.958937
264
0.475691
[ [ [ "![Panel HighCharts Logo](https://raw.githubusercontent.com/MarcSkovMadsen/panel-highcharts/main/assets/images/panel-highcharts-logo.png)\n\n# 📈 Panel HighMap Reference Guide\n\nThe [Panel](https://panel.holoviz.org) `HighMap` pane allows you to use the powerful [HighCharts](https://www.highcharts.com/) [Maps](https://www.highcharts.com/products/maps/) from within the comfort of Python 🐍 and Panel ❤️.\n\n## License\n\nThe `panel-highcharts` python package and repository is open source and free to use (MIT License), however the **Highcharts js library requires a license for commercial use**. For more info see the Highcharts license [FAQs](https://shop.highsoft.com/faq).\n\n## Parameters:\n\nFor layout and styling related parameters see the [Panel Customization Guide](https://panel.holoviz.org/user_guide/Customization.html).\n\n* **``object``** (dict): The initial user `configuration` of the `chart`.\n* **``object_update``** (dict) Incremental update to the existing `configuration` of the `chart`. \n* **``event``** (dict): Events like `click` and `mouseOver` if subscribed to using the `@` terminology.\n\n## Methods\n\n* **``add_series``**: The method adds a new series to the chart. Takes the `options`, `redraw` and `animation` arguments.\n___", "_____no_output_____" ], [ "# Usage\n\n## Imports\n\nYou must import something from panel_highcharts before you run `pn.extension('highmap')`", "_____no_output_____" ] ], [ [ "import panel_highcharts as ph", "_____no_output_____" ] ], [ [ "Additionally you can specify extra Highcharts `js_files` to include. `mapdata` can be supplied as a list. See the full list at [https://code.highcharts.com](https://code.highcharts.com)", "_____no_output_____" ] ], [ [ "ph.config.js_files(mapdata=[\"custom/europe\"]) # Imports https://code.highcharts.com/mapdata/custom/europe.js", "_____no_output_____" ], [ "import panel as pn\npn.extension('highmap')", "_____no_output_____" ] ], [ [ "## Configuration\n\nThe `HighChart` pane is configured by providing a simple `dict` to the `object` parameter. For examples see the HighCharts [demos](https://www.highcharts.com/demo).", "_____no_output_____" ] ], [ [ "configuration = {\n \"chart\": {\"map\": \"custom/europe\", \"borderWidth\": 1},\n \"title\": {\"text\": \"Nordic countries\"},\n \"subtitle\": {\"text\": \"Demo of drawing all areas in the map, only highlighting partial data\"},\n \"legend\": {\"enabled\": False},\n \"series\": [\n {\n \"name\": \"Country\",\n \"data\": [[\"is\", 1], [\"no\", 1], [\"se\", 1], [\"dk\", 1], [\"fi\", 1]],\n \"dataLabels\": {\n \"enabled\": True,\n \"color\": \"#FFFFFF\",\n \"formatter\": \"\"\"function () {\n if (this.point.value) {\n return this.point.name;\n }\n }\"\"\",\n },\n \"tooltip\": {\"headerFormat\": \"\", \"pointFormat\": \"{point.name}\"},\n }\n ],\n}", "_____no_output_____" ], [ "chart = ph.HighMap(object=configuration, sizing_mode=\"stretch_both\", min_height=600)\nchart", "_____no_output_____" ] ], [ [ "## Layout", "_____no_output_____" ] ], [ [ "settings = pn.WidgetBox(\n pn.Param(\n chart,\n parameters=[\"height\", \"width\", \"sizing_mode\", \"margin\", \"object\", \"object_update\", \"event\", ],\n widgets={\"object\": pn.widgets.LiteralInput, \"object_update\": pn.widgets.LiteralInput, \"event\": pn.widgets.StaticText},\n sizing_mode=\"fixed\", show_name=False, width=250,\n )\n)\npn.Row(settings, chart, sizing_mode=\"stretch_both\")", "_____no_output_____" ] ], [ [ "Try changing the `sizing_mode` to `fixed` and the `width` to `400`.", "_____no_output_____" ], [ "## Updates\n\nYou can *update* the chart by providing a partial `configuration` to the `object_update` parameter.", "_____no_output_____" ] ], [ [ "object_update = {\n \"title\": {\"text\": \"Panel HighMap - Nordic countries\"},\n}\nchart.object_update=object_update", "_____no_output_____" ] ], [ [ "Verify that the `title` and `series` was updated in the chart above.", "_____no_output_____" ], [ "## Events\n\nYou can subscribe to chart events using an the `@` notation as shown below. If you add a string like `@name`, then the key-value pair `'channel': 'name'` will be added to the `event` dictionary.", "_____no_output_____" ] ], [ [ "event_update = {\n \"series\": [\n {\n \"allowPointSelect\": \"true\",\n \"point\": {\n \"events\": {\n \"click\": \"@click;}\",\n \"mouseOver\": \"@mouseOverFun\",\n \"select\": \"@select\",\n \"unselect\": \"@unselect\",\n }\n },\n \"events\": {\n \"mouseOut\": \"@mouseOutFun\",\n }\n }\n ]\n}\nchart.object_update=event_update", "_____no_output_____" ] ], [ [ "Verify that you can trigger the `click`, `mouseOver`, `select`, `unselect` and `mouseOut` events in the chart above and that the relevant `channel` value is used.", "_____no_output_____" ], [ "## Javascript\n\nYou can use Javascript in the configuration via the `function() {...}` notation.", "_____no_output_____" ] ], [ [ "js_update = {\n \"series\": [\n {\n \"dataLabels\": {\n \"formatter\": \"\"\"function () {\n if (this.point.value) {\n if (this.point.name==\"Denmark\"){\n return \"❤️ \" + this.point.name;\n } else {\n return this.point.name;\n }\n }\n }\"\"\",\n }\n }\n ],\n}\nchart.object_update=js_update", "_____no_output_____" ] ], [ [ "Verify that the x-axis labels now has `km` units appended in the chart above.", "_____no_output_____" ], [ "# App\n\nFinally we can wrap it up into a nice app template.", "_____no_output_____" ] ], [ [ "chart.object =configuration = {\n \"chart\": {\"map\": \"custom/europe\", \"borderWidth\": 1},\n \"title\": {\"text\": \"Nordic countries\"},\n \"subtitle\": {\"text\": \"Demo of drawing all areas in the map, only highlighting partial data\"},\n \"legend\": {\"enabled\": False},\n \"series\": [\n {\n \"name\": \"Country\",\n \"data\": [[\"is\", 1], [\"no\", 1], [\"se\", 1], [\"dk\", 1], [\"fi\", 1]],\n \"dataLabels\": {\n \"enabled\": True,\n \"color\": \"#FFFFFF\",\n \"formatter\": \"\"\"function () {\n if (this.point.value) {\n if (this.point.name==\"Denmark\"){\n return \"❤️ \" + this.point.name;\n } else {\n return this.point.name;\n }\n }\n }\"\"\",\n },\n \"tooltip\": {\"headerFormat\": \"\", \"pointFormat\": \"{point.name}\"},\n \"allowPointSelect\": \"true\",\n \"point\": {\n \"events\": {\n \"click\": \"@click;}\",\n \"mouseOver\": \"@mouseOverFun\",\n \"select\": \"@select\",\n \"unselect\": \"@unselect\",\n }\n },\n \"events\": {\n \"mouseOut\": \"@mouseOutFun\",\n }\n }\n ],\n}", "_____no_output_____" ], [ "app = pn.template.FastListTemplate(\n site=\"Panel Highcharts\",\n title=\"HighMap Reference Example\", \n sidebar=[settings], \n main=[chart]\n).servable()", "_____no_output_____" ] ], [ [ "You can serve with `panel serve HighMap.ipynb` and explore the app at http://localhost:5006/HighMap.\n\nAdd the `--autoreload` flag to get *hot reloading* when you save the notebook.\n\n![HighMap Reference Guide](https://raw.githubusercontent.com/MarcSkovMadsen/panel-highcharts/main/assets/images/HighMapApp.gif)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cbe000692500545d6f36576b6cca9d65eb8dc92d
45,466
ipynb
Jupyter Notebook
matematicas_ipynb/Sympy.ipynb
amd77/presentaciones
06d1df8e5236c22d5f84d8cab887b5215d1456d5
[ "MIT" ]
null
null
null
matematicas_ipynb/Sympy.ipynb
amd77/presentaciones
06d1df8e5236c22d5f84d8cab887b5215d1456d5
[ "MIT" ]
null
null
null
matematicas_ipynb/Sympy.ipynb
amd77/presentaciones
06d1df8e5236c22d5f84d8cab887b5215d1456d5
[ "MIT" ]
null
null
null
56.200247
16,670
0.795935
[ [ [ "# SYMPY", "_____no_output_____" ] ], [ [ "# las funciones que usaremos durante la práctica\nfrom sympy import Symbol, symbols, factor, expand, simplify, solve, pprint, plot, Derivative, Integral, sin", "_____no_output_____" ], [ "x = Symbol('x')", "_____no_output_____" ], [ "x + x + 1", "_____no_output_____" ], [ "type(2*x)", "_____no_output_____" ], [ "type(2*x+1)", "_____no_output_____" ] ], [ [ "## Atajo para describir incógnitas de una vez", "_____no_output_____" ] ], [ [ "x = Symbol('x')\nx", "_____no_output_____" ], [ "y = Symbol('y')\ny", "_____no_output_____" ], [ "z = Symbol('z')\nz", "_____no_output_____" ], [ "# equivalente a\nx, y, z = symbols('x,y,z')\nx, y, z", "_____no_output_____" ] ], [ [ "## Simplificaciones básicas", "_____no_output_____" ] ], [ [ "x*y+x*y", "_____no_output_____" ], [ "x * (x+x)", "_____no_output_____" ], [ "x * y / y", "_____no_output_____" ] ], [ [ "## Expandir y factorizar", "_____no_output_____" ] ], [ [ "factor(x**2 - y**2)", "_____no_output_____" ], [ "factor(x**3 + 3*x**2*y + 3*x*y**2 + y**3)", "_____no_output_____" ], [ "expand((x - y)*(x + y))", "_____no_output_____" ], [ "expand((x - 1)*(x + 1)*(2*x+3))", "_____no_output_____" ] ], [ [ "## Evaluar", "_____no_output_____" ] ], [ [ "# evaluar en un punto f(1, 2)\nf = x*x + x*y + x*y + y*y\nf.subs({x: 1, y: 2})", "_____no_output_____" ], [ "# cambio de variable x -> 1-y\nf.subs({x: 1-y})", "_____no_output_____" ], [ "simplify(_)", "_____no_output_____" ], [ "# cambio de variable x -> 2-y**2\nf.subs({x: 2-y**2})", "_____no_output_____" ], [ "simplify(_)", "_____no_output_____" ], [ "expand(_)", "_____no_output_____" ] ], [ [ "## Despejando", "_____no_output_____" ] ], [ [ "a, b, c = symbols(\"a,b,c\")", "_____no_output_____" ], [ "f = x**2 + 5*x + 4 # f(x) = 0\nsolve(f, dict=True) # despeja (resuelve) x", "_____no_output_____" ], [ "f = a*x**2 + b*x + c # f(x, a, b, c) = 0\nsolve(f, x, dict=True) # despeja x", "_____no_output_____" ], [ "pprint(_)", "⎡⎧ _____________⎫ ⎧ ⎛ _____________⎞ ⎫⎤\n⎢⎪ ╱ 2 ⎪ ⎪ ⎜ ╱ 2 ⎟ ⎪⎥\n⎢⎨ -b + ╲╱ -4⋅a⋅c + b ⎬ ⎨ -⎝b + ╲╱ -4⋅a⋅c + b ⎠ ⎬⎥\n⎢⎪x: ─────────────────────⎪, ⎪x: ────────────────────────⎪⎥\n⎣⎩ 2⋅a ⎭ ⎩ 2⋅a ⎭⎦\n" ], [ "pprint(solve(f, a, dict=True))", "⎡⎧ -(b⋅x + c) ⎫⎤\n⎢⎪a: ───────────⎪⎥\n⎢⎨ 2 ⎬⎥\n⎢⎪ x ⎪⎥\n⎣⎩ ⎭⎦\n" ] ], [ [ "## Representando", "_____no_output_____" ] ], [ [ "plot(2*x**2 + 3*x)", "_____no_output_____" ], [ "plot(2*x**2 + 3*x, (x, -5, 5))", "_____no_output_____" ] ], [ [ "## Derivadas e integrales", "_____no_output_____" ] ], [ [ "Derivative(2*x**2+3*x+1, x).doit()", "_____no_output_____" ], [ "Derivative(2*sin(x)*x**2, x).doit()", "_____no_output_____" ], [ "Integral(4*x + 3, x).doit()", "_____no_output_____" ], [ "Integral(sin(x)**2, x).doit()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cbe0034919445a0cc57aec67d0ea5e9fcc68d4d0
91,761
ipynb
Jupyter Notebook
assets/nb-lessons/11_classification_metrics.ipynb
USDA-ARS-GBRU/ml-training-site
c446a968eccf4cd9fdf1adb33c08ba9fdde18965
[ "MIT" ]
1
2019-10-23T20:29:39.000Z
2019-10-23T20:29:39.000Z
assets/nb-lessons/11_classification_metrics.ipynb
USDA-ARS-GBRU/ml-training-site
c446a968eccf4cd9fdf1adb33c08ba9fdde18965
[ "MIT" ]
7
2019-06-14T13:26:23.000Z
2019-08-22T22:01:23.000Z
assets/nb-lessons/11_classification_metrics.ipynb
USDA-ARS-GBRU/ml-training-site
c446a968eccf4cd9fdf1adb33c08ba9fdde18965
[ "MIT" ]
5
2019-07-29T20:01:08.000Z
2020-09-09T19:12:42.000Z
89.522927
26,316
0.813777
[ [ [ "# Classification metrics\nAuthor: Geraldine Klarenberg\n\nBased on the Google Machine Learning Crash Course", "_____no_output_____" ], [ "## Tresholds\nIn previous lessons, we have talked about using regression models to predict values. But sometimes we are interested in **classifying** things: \"spam\" vs \"not spam\", \"bark\" vs \"not barking\", etc. \n\nLogistic regression is a great tool to use in ML classification models. We can use the outputs from these models by defining **classification thresholds**. For instance, if our model tells us there's a probability of 0.8 that an email is spam (based on some characteristics), the model classifies it as such. If the probability estimate is less than 0.8, the model classifies it as \"not spam\". The threshold allows us to map a logistic regression value to a binary category (the prediction).\n\nTresholds are problem-dependent, so they will have to be tuned for the specific problem you are dealing with.\n\nIn this lesson we will look at metrics you can use to evaluate a classification model's predictions, and what changing the threshold does to your model and predictions.", "_____no_output_____" ], [ "## True, false, positive, negative...\n\nNow, we could simply look at \"accuracy\": the ratio of all correct predictions to all predictions. This is simple, intuitive and straightfoward. \n\nBut there are some problems with this approach:\n* This approach does not work well if there is (class) imbalance; situations where certain negative or positive values or outcomes are rare; \n* and, most importantly: different kind of mistakes can have different costs...", "_____no_output_____" ], [ "### The boy who cried wolf...\n\nWe all know the story!\n\n![Illustration of the boy who cried wolf](../nb-images/wolfpic.jpg)\n\nFor this example, we define \"there actually is a wolf\" as a positive class, and \"there is no wolf\" as a negative class. The predictions that a model makes can be true or false for both classes, generating 4 outcomes:\n\n![An table showing a confusion matrix based on the story of the boy who cried wolf](../nb-images/confusionmatrix_wolf.png)", "_____no_output_____" ], [ "This table is also called a *confusion matrix*.\n\nThere are 2 metrics we can derive from these outcomes: precision and recall.\n\n## Precision\nPrecision asks the question what proportion of the positive predictions was actually correct?\n\nTo calculate the precision of your model, take all true positives divided by *all* positive predictions:\n$$\\text{Precision} = \\frac{TP}{TP+FP}$$\n\nBasically: **did the model cry 'wolf' too often or too little?**\n\n**NB** If your model produces no negative positives, the value of the precision is 1.0. Too many negative positives gives values greater than 1, too few gives values less than 1.", "_____no_output_____" ], [ "### Exercise\nCalculate the precision of a model with the following outcomes\n\ntrue positives (TP): 1 | false positives (FP): 1 \n-------|--------\n**false negatives (FN): 8** | **true negatives (TN): 90** ", "_____no_output_____" ], [ "## Recall\nRecall tries to answer the question what proportion of actual positives was answered correctly?\n\nTo calculate recall, divide all true positives by the true positives plus the false negatives:\n$$\\text{Recall} = \\frac{TP}{TP+FN}$$\n\nBasically: **how many wolves that tried to get into the village did the model actually get?**\n\n**NB** If the model produces no false negative, recall equals 1.0", "_____no_output_____" ], [ "### Exercise\nFor the same confusion matrix as above, calculate the recall.", "_____no_output_____" ], [ "## Balancing precision and recall\nTo evaluate your model, should look at **both** precision and recall. They are often in tension though: improving one reduces the other.\nLowering the classification treshold improves recall (your model will call wolf at every little sound it hears) but will negatively affect precision (it will call wolf too often).", "_____no_output_____" ], [ "### Exercise\n#### Part 1\nLook at the outputs of a model that classifies incoming emails as \"spam\" or \"not spam\".\n\n![Image of outcomes of a spam/not spam classification model](../nb-images/PrecisionVsRecallBase.svg)\n\nThe confusion matrix looks as follows\n\ntrue positives (TP): 8 | false positives (FP): 2 \n-------|--------\n**false negatives (FN): 3** | **true negatives (TN): 17** \n\nCalculate the precision and recall for this model.\n\n#### Part 2\nNow see what happens to the outcomes (below) if we increase the threshold\n\n![Image of outcomes of a spam/not spam classification model](../nb-images/PrecisionVsRecallRaiseThreshold.svg)\n\nThe confusion matrix looks as follows\n\ntrue positives (TP): 7 | false positives (FP): 4 \n-------|--------\n**false negatives (FN): 1** | **true negatives (TN): 18** \n\nCalculate the precision and recall again.\n\n**Compare the precision and recall from the first and second model. What do you notice?** ", "_____no_output_____" ], [ "## Evaluate model performance\nWe can evaluate the performance of a classification model at all classification thresholds. For all different thresholds, calculate the *true positive rate* and the *false positive rate*. The true positive rate is synonymous with recall (and sometimes called *sensitivity*) and is thus calculated as\n\n$ TPR = \\frac{TP} {TP + FN} $\n\nFalse positive rate (sometimes called *specificity*) is:\n\n$ FPR = \\frac{FP} {FP + TN} $\n\nWhen you plot the pairs of TPR and FPR for all the different thresholds, you get a Receiver Operating Characteristics (ROC) curve. Below is a typical ROC curve.\n\n![Image of an ROC curve](../nb-images/ROCCurve.svg)\n\nTo evaluate the model, we look at the area under the curve (AUC). The AUC has a probabilistic interpretation: it represents the probability that a random positive (green) example is positioned to the right of a random negative (red) example.\n\n![Image with predictions ranked according to logistic regression score](../nb-images/AUCPredictionsRanked.svg)\n\nSo if that AUC is 0.9, that's the probability the pair-wise prediction is correct. Below are a few visualizations of AUC results. On top are the distributions of the outcomes of the negative and positive outcomes at various thresholds. Below is the corresponding ROC.\n\n![Image with distributions of positive and negative classes - perfect](../nb-images/TowardsDataScienceAUC_perfect.png) \n![Image with AUC - perfect](../nb-images/TowardsDataScienceAUC_perfect2.png)\n**This AUC suggests a perfect model** (which is suspicious!)\n", "_____no_output_____" ], [ "![Image with distributions of positive and negative classes - normal](../nb-images/TowardsDataScienceAUC_normal.png)\n![Image with AUC - normal](../nb-images/TowardsDataScienceAUC_normal2.png)\n**This is what most AUCs look like**. In this case, AUC = 0.7 means that there is 70% chance the model will be able to distinguish between positive and negative classes.", "_____no_output_____" ], [ "![Image with distributions of positive and negative classes - worst](../nb-images/TowardsDataScienceAUC_worst.png)\n![Image with AUC - worst](../nb-images/TowardsDataScienceAUC_worst2.png)\n**This is actually the worst case scenario.** This model has no discrimination capacity at all... ", "_____no_output_____" ], [ "## Prediction bias\nLogistic regression should be unbiased, meaning that the average of the predictions should be more or less equal to the average of the observations. **Prediction bias** is the difference between the average of the predictions and the average of the labels in a data set.\n\nThis approach is not perfect, e.g. if your model almost always predicts the average there will not be much bias. However, if there **is** bias (\"significant nonzero bias\"), that means there is something something going on that needs to be checked, specifically that the model is wrong about the frequency of positive labels.\n\nPossible root causes of prediction bias are:\n* Incomplete feature set\n* Noisy data set\n* Buggy pipeline\n* Biased training sample\n* Overly strong regularization\n\n### Buckets and prediction bias\nFor logistic regression, this process is a bit more involved, as the labels assigned to an examples are either 0 or 1. So you cannot accurately predict the prediction bias based on one example. You need to group data in \"buckets\" and examine the prediction bias on that. Prediction bias for logistic regression only makes sense when grouping enough examples together to be able to compare a predicted value (for example, 0.392) to observed values (for example, 0.394). \n\nYou can create buckets by linearly breaking up the target predictions, or create quantiles. \n\nThe plot below is a calibration plot. Each dot represents a bucket with 1000 values. On the x-axis we have the average value of the predictions for that bucket and on the y-axis the average of the actual observations. Note that the axes are on logarithmic scales.\n\n![Image of a calibration plot with buckets](../nb-images/BucketingBias.svg)", "_____no_output_____" ], [ "## Coding\nRecall the logistic regression model we made in the previous lesson. That was a perfect fit, so not that useful when we look at the metrics we just discussed.\n\nIn the cloud plot with the sepal length and petal width plotted against each other, it is clear that the other two iris species are less separated. Let's use one of these as an example. We'll rework the example so we're classifying irises for being \"virginica\" or \"not virginica\". ", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\nimport pandas as pd\n\niris = load_iris()\n\nX = iris.data\ny = iris.target\n\ndf = pd.DataFrame(X, \n columns = ['sepal_length(cm)',\n 'sepal_width(cm)',\n 'petal_length(cm)',\n 'petal_width(cm)'])\n\ndf['species_id'] = y\n\nspecies_map = {0: 'setosa', 1: 'versicolor', 2: 'virginica'}\n\ndf['species_name'] = df['species_id'].map(species_map)\n\ndf.head()", "_____no_output_____" ] ], [ [ "Now extract the data we need and create the necessary dataframes again.", "_____no_output_____" ] ], [ [ "X = np.c_[X[:,0], X[:,3]]", "_____no_output_____" ], [ "y = []\nfor i in range(len(X)):\n if i > 99:\n y.append(1)\n else:\n y.append(0)\n\ny = np.array(y)\n\nplt.scatter(X[:,0], X[:,1], c = y)", "_____no_output_____" ] ], [ [ "Create our test and train data, and run a model. The default classification threshold is 0.5. If the predicted probability is > 0.5, the predicted result is 'virgnica'. If it is < 0.5, the predicted result is 'not virginica'.", "_____no_output_____" ] ], [ [ "random = np.random.permutation(len(X))\nx_train = X[random][30:]\nx_test = X[random][:30]\n\ny_train= y[random][30:]\ny_test = y[random][:30]", "_____no_output_____" ], [ "from sklearn.linear_model import LogisticRegression\n\nlog_reg = LogisticRegression()\nlog_reg.fit(x_train,y_train)", "_____no_output_____" ] ], [ [ "Instead of looking at the probabilities and the plot, like in the last lesson, let's run some classification metrics on the training dataset. \n\nIf you use \".score\", you get the mean accuracy.", "_____no_output_____" ] ], [ [ "log_reg.score(x_train, y_train)", "_____no_output_____" ] ], [ [ "Let's predict values and see what this ouput means and how we can look at other metrics.", "_____no_output_____" ] ], [ [ "predictions = log_reg.predict(x_train)\npredictions, y_train", "_____no_output_____" ] ], [ [ "There is a way to look at the confusion matrix. The output that is generated has the same structure as the confusion matrices we showed earlier:\n\ntrue positives (TP) | false positives (FP) \n-------|--------\n**false negatives (FN)** | **true negatives (TN)** ", "_____no_output_____" ] ], [ [ "from sklearn.metrics import confusion_matrix\nconfusion_matrix(y_train, predictions)", "_____no_output_____" ] ], [ [ "Indeed, for the accuracy calculation: we predicted 81 + 33 = 114 correct (true positives and true negatives), and 114/120 (remember, our training data had 120 points) = 0.95.\n\nThere is also a function to calculate recall and precision:\n\nSince we also have a testing data set, let's see what the metrics look like for that.", "_____no_output_____" ] ], [ [ "from sklearn.metrics import recall_score\nrecall_score(y_train, predictions)", "_____no_output_____" ], [ "from sklearn.metrics import precision_score\nprecision_score(y_train, predictions)", "_____no_output_____" ] ], [ [ "And, of course, there are also built-in functions to check the ROC curve and AUC! For these functions, the inputs are the labels of the original dataset and the predicted probabilities (- not the predicted labels -> **why?**). Remember what the two columns mean?", "_____no_output_____" ] ], [ [ "proba_virginica = log_reg.predict_proba(x_train)\nproba_virginica[0:10]", "_____no_output_____" ], [ "from sklearn.metrics import roc_curve\nfpr_model, tpr_model, thresholds_model = roc_curve(y_train, proba_virginica[:,1])", "_____no_output_____" ], [ "fpr_model", "_____no_output_____" ], [ "tpr_model", "_____no_output_____" ], [ "thresholds_model", "_____no_output_____" ] ], [ [ "Plot the ROC curve as follows", "_____no_output_____" ] ], [ [ "plt.plot(fpr_model, tpr_model,label='our model')\nplt.plot([0,1],[0,1],label='random')\nplt.plot([0,0,1,1],[0,1,1,1],label='perfect')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "The AUC:", "_____no_output_____" ] ], [ [ "from sklearn.metrics import roc_auc_score\nauc_model = roc_auc_score(y_train, proba_virginica[:,1])\nauc_model", "_____no_output_____" ] ], [ [ "You can use the ROC and AUC metric to evaluate competing models. Many people prefer to use these metrics to analyze each model’s performance because it does not require selecting a threshold and helps balance true positive rate and false positive rate.", "_____no_output_____" ], [ "Now let's do the same thing for our test data (but again, this dataset is fairly small, and K-fold cross-validation is recommended).", "_____no_output_____" ] ], [ [ "log_reg.score(x_test, y_test)", "_____no_output_____" ], [ "predictions = log_reg.predict(x_test)\npredictions, y_test", "_____no_output_____" ], [ "confusion_matrix(y_test, predictions)", "_____no_output_____" ], [ "recall_score(y_test, predictions)", "_____no_output_____" ], [ "precision_score(y_test, predictions)", "_____no_output_____" ], [ "proba_virginica = log_reg.predict_proba(x_test)\nfpr_model, tpr_model, thresholds_model = roc_curve(y_test, proba_virginica[:,1])", "_____no_output_____" ], [ "plt.plot(fpr_model, tpr_model,label='our model')\nplt.plot([0,1],[0,1],label='random')\nplt.plot([0,0,1,1],[0,1,1,1],label='perfect')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "auc_model = roc_auc_score(y_test, proba_virginica[:,1])\nauc_model", "_____no_output_____" ] ], [ [ "Learn more about the logistic regression function and options at https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
cbe00aa917931f6492a3975d7a924e703d207d1a
101,067
ipynb
Jupyter Notebook
src/controller/panoscDEMO/PaNOSC_DEMO-3_New_crystFEL.ipynb
ejcjason/crystalProject
890c6645a2e132f8b81e1dd485b61d66dd2521c3
[ "MIT" ]
1
2020-04-30T13:40:28.000Z
2020-04-30T13:40:28.000Z
src/controller/panoscDEMO/PaNOSC_DEMO-3_New_crystFEL.ipynb
JunCEEE/crystalProject
890c6645a2e132f8b81e1dd485b61d66dd2521c3
[ "MIT" ]
4
2020-05-19T13:38:27.000Z
2020-05-29T16:47:27.000Z
src/controller/panoscDEMO/PaNOSC_DEMO-3_New_crystFEL.ipynb
JunCEEE/crystalProject
890c6645a2e132f8b81e1dd485b61d66dd2521c3
[ "MIT" ]
2
2020-05-05T12:46:02.000Z
2020-06-05T20:40:35.000Z
309.073394
46,480
0.929661
[ [ [ "# Multi-panel detector", "_____no_output_____" ], [ "The AGIPD detector, which is already in use at the SPB experiment, consists of 16 modules of 512×128 pixels each. Each module is further divided into 8 ASICs (application-specific integrated circuit).", "_____no_output_____" ], [ "<img src=\"AGIPD.png\" width=\"300\" align=\"left\"/> <img src=\"agipd_geometry_14_1.png\" width=\"420\" align=\"right\"/> \n\n<div style=\"clear: both\"><small>Photo © European XFEL</small></div>", "_____no_output_____" ], [ "## Simulation Demonstration", "_____no_output_____" ] ], [ [ "import os, shutil, sys\nimport h5py\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport modules\nfrom extra_geom import AGIPD_1MGeometry\nmodules.load('maxwell' ,'openmpi/3.1.6')", "_____no_output_____" ], [ "SimExPath = '/gpfs/exfel/data/user/juncheng/simex-branch/Sources/python/'\nSimExExtLib = '/gpfs/exfel/data/user/juncheng/simex-branch/lib/python3.7/site-packages/'\nSimExBin = ':/gpfs/exfel/data/user/juncheng/miniconda3/envs/simex-branch/bin/'\nsys.path.insert(0,SimExPath)\nsys.path.insert(0,SimExExtLib)\nos.environ[\"PATH\"] += SimExBin\nfrom SimEx.Calculators.AbstractPhotonDiffractor import AbstractPhotonDiffractor\nfrom SimEx.Calculators.CrystFELPhotonDiffractor import CrystFELPhotonDiffractor\nfrom SimEx.Parameters.CrystFELPhotonDiffractorParameters import CrystFELPhotonDiffractorParameters\nfrom SimEx.Parameters.PhotonBeamParameters import PhotonBeamParameters\nfrom SimEx.Parameters.DetectorGeometry import DetectorGeometry, DetectorPanel\nfrom SimEx.Utilities.Units import electronvolt, joule, meter, radian", "initializing ocelot...\n" ] ], [ [ "## Data path setup", "_____no_output_____" ] ], [ [ "data_path = './diffr'", "_____no_output_____" ] ], [ [ "Clean up any data from a previous run:", "_____no_output_____" ] ], [ [ "if os.path.isdir(data_path):\n shutil.rmtree(data_path)\n\nif os.path.isfile(data_path + '.h5'):\n os.remove(data_path + '.h5')", "_____no_output_____" ] ], [ [ "## Set up X-ray Beam Parameters", "_____no_output_____" ] ], [ [ "beamParam = PhotonBeamParameters(\n photon_energy = 4972.0 * electronvolt, # photon energy in eV\n beam_diameter_fwhm=130e-9 * meter, # focus diameter in m\n pulse_energy=45e-3 * joule, # pulse energy in J\n photon_energy_relative_bandwidth=0.003, # relative bandwidth dE/E\n divergence=0.0 * radian, # Beam divergence in rad\n photon_energy_spectrum_type='tophat', # Spectrum type. Acceptable values are \"tophat\", \"SASE\", and \"twocolor\")\n)", "_____no_output_____" ] ], [ [ "## Detector Setting", "_____no_output_____" ] ], [ [ "geom = AGIPD_1MGeometry.from_quad_positions(quad_pos=[\n (-525, 625),\n (-550, -10),\n (520, -160),\n (542.5, 475),\n])", "_____no_output_____" ], [ "geom.inspect()", "_____no_output_____" ], [ "geom_file = 'agipd_simple_2d.geom'\ngeom.write_crystfel_geom(\n geom_file,\n dims=('frame', 'ss', 'fs'),\n adu_per_ev=1.0,\n clen=0.13, # Sample - detector distance in m\n photon_energy=4972, # eV\n data_path='/data/data',\n)", "_____no_output_____" ] ], [ [ "## Diffractor Settings", "_____no_output_____" ] ], [ [ "diffParam = CrystFELPhotonDiffractorParameters(\n sample='3WUL.pdb', # Looks up pdb file in cwd, if not found, queries from RCSB pdb mirror.\n uniform_rotation=True, # Apply random rotation\n number_of_diffraction_patterns=2, #\n powder=False, # Set xto True to create a virtual powder diffraction pattern (unested)\n intensities_file=None, # File that contains reflection intensities. If set to none, use uniform intensity distribution\n crystal_size_range=[1e-7, 1e-7], # Range ([min,max]) in units of metres of crystal size.\n poissonize=False, # Set to True to add Poisson noise.\n number_of_background_photons=0, # Change number to add uniformly distributed background photons.\n suppress_fringes=False, # Set to True to suppress side maxima between reflection peaks.\n beam_parameters=beamParam, # Beam parameters object from above\n detector_geometry=geom_file, # External file that contains the detector geometry in CrystFEL notation.\n)", "_____no_output_____" ], [ "diffractor = CrystFELPhotonDiffractor(\n parameters=diffParam, output_path=data_path\n)", "_____no_output_____" ] ], [ [ "## Run the simulation", "_____no_output_____" ] ], [ [ "diffractor.backengine()\ndiffractor.saveH5_geom()", "Renaming diffr_out-1.h5 to diffr_out_0000001.h5.\nRenaming diffr_out-2.h5 to diffr_out_0000002.h5.\nLinking all patterns into /gpfs/exfel/data/user/juncheng/crystalProject/src/controller/panoscDEMO/diffr.h5.\n" ], [ "data_f = h5py.File(data_path + '.h5', 'r')\nframe = data_f['data/0000001/data'][...].reshape(16, 512, 128)\n\nfig, ax = plt.subplots(figsize=(12, 10))\ngeom.plot_data_fast(frame, axis_units='m', ax=ax, vmax=1000);", "_____no_output_____" ] ], [ [ "This project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No. 823852.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cbe00afe3c3226301d4b262d0246eac3ec13cef0
6,054
ipynb
Jupyter Notebook
tour_model_eval/confirmed_trips_eval_all_bins.ipynb
GabrielKS/e-mission-eval-private-data
9cdb64ee344f85bf2b4b3e924f9ff9da0af73e58
[ "BSD-3-Clause" ]
null
null
null
tour_model_eval/confirmed_trips_eval_all_bins.ipynb
GabrielKS/e-mission-eval-private-data
9cdb64ee344f85bf2b4b3e924f9ff9da0af73e58
[ "BSD-3-Clause" ]
13
2020-06-27T03:41:07.000Z
2021-08-13T17:15:36.000Z
tour_model_eval/confirmed_trips_eval_all_bins.ipynb
GabrielKS/e-mission-eval-private-data
9cdb64ee344f85bf2b4b3e924f9ff9da0af73e58
[ "BSD-3-Clause" ]
3
2021-01-27T23:33:59.000Z
2021-08-03T22:30:42.000Z
24.510121
144
0.563099
[ [ [ "import logging\n\n# Our imports\nimport emission.core.get_database as edb\nimport emission.analysis.modelling.tour_model.cluster_pipeline as pipeline\nimport emission.analysis.modelling.tour_model.similarity as similarity\nimport emission.analysis.modelling.tour_model.featurization as featurization\nimport emission.analysis.modelling.tour_model.representatives as representatives\nimport emission.storage.decorations.analysis_timeseries_queries as esda\nimport pandas as pd\nfrom numpy import *\nimport confirmed_trips_eval_bins_clusters as evaluation", "_____no_output_____" ], [ "logger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)", "_____no_output_____" ], [ "participant_uuid_obj = list(edb.get_profile_db().find({\"install_group\": \"participant\"}, {\"user_id\": 1, \"_id\": 0}))\nall_users = [u[\"user_id\"] for u in participant_uuid_obj]", "_____no_output_____" ], [ "radius = 300", "_____no_output_____" ] ], [ [ "## Calculate the precision for all users", "_____no_output_____" ], [ "### Calculation from original user inputs", "_____no_output_____" ] ], [ [ "# this step doesn't change Spanish to English, nor does it convert purposes\nall_users_preci_noncvt=evaluation.precision_bin_all_users(all_users,radius)", "_____no_output_____" ], [ "all_users_preci_noncvt", "_____no_output_____" ], [ "# average precision for all users\nmean_preci_noncvt=round(mean([x for x in all_users_preci_noncvt if str(x) != 'nan']),2)\nmean_preci_noncvt", "_____no_output_____" ] ], [ [ "### Calculation from user inputs after changing Spanish to English", "_____no_output_____" ] ], [ [ "all_users_preci_sp2en=evaluation.precision_bin_all_users(all_users,radius,sp2en='True',cvt_purpose=None)", "_____no_output_____" ], [ "all_users_preci_sp2en", "_____no_output_____" ], [ "mean_preci_sp2en=round(mean([x for x in all_users_preci_sp2en if str(x) != 'nan']),2)\nmean_preci_sp2en", "_____no_output_____" ] ], [ [ "### Calculation from user input after converting purposes", "_____no_output_____" ] ], [ [ "all_users_preci_cvtpur=evaluation.precision_bin_all_users(all_users,radius,sp2en='True',cvt_purpose='True')", "_____no_output_____" ], [ "all_users_preci_cvtpur", "_____no_output_____" ], [ "mean_preci_cvtpur=round(mean([x for x in all_users_preci_cvtpur if str(x) != 'nan']),2)\nmean_preci_cvtpur", "_____no_output_____" ] ], [ [ "### Precision data frame", "_____no_output_____" ] ], [ [ "pd.set_option('max_colwidth',100)\npd.set_option('display.max_rows', None)", "_____no_output_____" ], [ "preci_df = pd.DataFrame(data = {'precision for every user':[all_users_preci_noncvt,all_users_preci_sp2en,all_users_preci_cvtpur],\n 'mean precision':[mean_preci_noncvt,mean_preci_sp2en,mean_preci_cvtpur]}, index = ['original user input',\n 'after translation',\n 'after converting purposes'])\npreci_df", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cbe03307838c5d1d8d7dd3a5d3c88396ec8b94a3
279,293
ipynb
Jupyter Notebook
notebooks/tbeucler_devlog/072_Custom_Loss_Physical_MSE_for_Quantile_Outputs.ipynb
tbeucler/CBRAIN-CAM
d2c21761894e182694c57d8383f8f011f73644fe
[ "MIT" ]
12
2019-03-30T07:40:07.000Z
2022-01-11T11:53:02.000Z
notebooks/tbeucler_devlog/072_Custom_Loss_Physical_MSE_for_Quantile_Outputs.ipynb
tbeucler/CBRAIN-CAM
d2c21761894e182694c57d8383f8f011f73644fe
[ "MIT" ]
null
null
null
notebooks/tbeucler_devlog/072_Custom_Loss_Physical_MSE_for_Quantile_Outputs.ipynb
tbeucler/CBRAIN-CAM
d2c21761894e182694c57d8383f8f011f73644fe
[ "MIT" ]
3
2019-05-08T16:59:50.000Z
2020-06-22T20:43:10.000Z
38.311797
1,572
0.487696
[ [ [ "tgb - 6/12/2021 - The goal is to see whether it would be possible to train a NN/MLR outputting results in quantile space while still penalizing them following the mean squared error in physical space.", "_____no_output_____" ], [ "tgb - 4/15/2021 - Recycling this notebook but fitting in percentile space (no scale_dict, use output in percentile units)", "_____no_output_____" ], [ "tgb - 4/15/2020\n- Adapting Ankitesh's notebook that builds and train a \"brute-force\" network to David Walling's hyperparameter search \n- Adding the option to choose between aquaplanet and real-geography data", "_____no_output_____" ] ], [ [ "import sys\nsys.path.insert(1,\"/home1/07064/tg863631/anaconda3/envs/CbrainCustomLayer/lib/python3.6/site-packages\") #work around for h5py\nfrom cbrain.imports import *\nfrom cbrain.cam_constants import *\nfrom cbrain.utils import *\nfrom cbrain.layers import *\nfrom cbrain.data_generator import DataGenerator\nfrom cbrain.climate_invariant import *\n\nimport tensorflow as tf\nphysical_devices = tf.config.experimental.list_physical_devices('GPU') \ntf.config.experimental.set_memory_growth(physical_devices[0], True)\ntf.config.experimental.set_memory_growth(physical_devices[1], True)\ntf.config.experimental.set_memory_growth(physical_devices[2], True)\n\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n\nfrom tensorflow import math as tfm\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nimport tensorflow_probability as tfp\nimport xarray as xr\nimport numpy as np\nfrom cbrain.model_diagnostics import ModelDiagnostics\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.image as imag\nimport scipy.integrate as sin\n# import cartopy.crs as ccrs\nimport matplotlib.ticker as mticker\n# from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER\nimport pickle\n# from climate_invariant import *\nfrom tensorflow.keras import layers\nimport datetime\nfrom climate_invariant_utils import *\nimport yaml\n", "/nfspool-0/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog\n" ] ], [ [ "## Global Variables", "_____no_output_____" ] ], [ [ "# Load coordinates (just pick any file from the climate model run)\n\n# Comet path below\n# coor = xr.open_dataset(\"/oasis/scratch/comet/ankitesh/temp_project/data/sp8fbp_minus4k.cam2.h1.0000-01-01-00000.nc\",\\\n# decode_times=False)\n\n# GP path below\npath_0K = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/fluxbypass_aqua/'\ncoor = xr.open_dataset(path_0K+\"AndKua_aqua_SPCAM3.0_sp_fbp_f4.cam2.h1.0000-09-02-00000.nc\")\n\nlat = coor.lat; lon = coor.lon; lev = coor.lev;\ncoor.close();", "_____no_output_____" ], [ "# Comet path below\n# TRAINDIR = '/oasis/scratch/comet/ankitesh/temp_project/PrepData/CRHData/'\n# path = '/home/ankitesh/CBrain_project/CBRAIN-CAM/cbrain/'\n\n# GP path below\nTRAINDIR = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/SPCAM_PHYS/'\npath = '/export/nfs0home/tbeucler/CBRAIN-CAM/cbrain/'\npath_nnconfig = '/export/nfs0home/tbeucler/CBRAIN-CAM/nn_config/'\n\n# Load hyam and hybm to calculate pressure field in SPCAM\npath_hyam = 'hyam_hybm.pkl'\nhf = open(path+path_hyam,'rb')\nhyam,hybm = pickle.load(hf)\n\n# Scale dictionary to convert the loss to W/m2\nscale_dict = load_pickle(path_nnconfig+'scale_dicts/009_Wm2_scaling.pkl')", "_____no_output_____" ] ], [ [ "New Data generator class for the climate-invariant network. Calculates the physical rescalings needed to make the NN climate-invariant", "_____no_output_____" ], [ "## Data Generators", "_____no_output_____" ], [ "### Choose between aquaplanet and realistic geography here", "_____no_output_____" ] ], [ [ "# GP paths below\n#path_aquaplanet = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/SPCAM_PHYS/'\n#path_realgeography = ''\n\n# GP /fast paths below\npath_aquaplanet = '/fast/tbeucler/climate_invariant/aquaplanet/'\n\n# Comet paths below\n# path_aquaplanet = '/oasis/scratch/comet/ankitesh/temp_project/PrepData/'\n# path_realgeography = '/oasis/scratch/comet/ankitesh/temp_project/PrepData/geography/'\n\npath = path_aquaplanet", "_____no_output_____" ] ], [ [ "### Data Generator using RH", "_____no_output_____" ] ], [ [ "#scale_dict_RH = load_pickle('/home/ankitesh/CBrain_project/CBRAIN-CAM/nn_config/scale_dicts/009_Wm2_scaling_2.pkl')\nscale_dict_RH = scale_dict.copy()\nscale_dict_RH['RH'] = 0.01*L_S/G, # Arbitrary 0.1 factor as specific humidity is generally below 2%\n\nin_vars_RH = ['RH','TBP','PS', 'SOLIN', 'SHFLX', 'LHFLX']\n# if path==path_realgeography: out_vars_RH = ['PTEQ','PTTEND','FSNT','FSNS','FLNT','FLNS']\n# elif path==path_aquaplanet: out_vars_RH = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS']\nif path==path_aquaplanet: out_vars_RH = ['PHQ','TPHYSTND','QRL','QRS']\n\n# New GP path below\nTRAINFILE_RH = '2021_01_24_O3_small_shuffle.nc'\nNORMFILE_RH = '2021_02_01_NORM_O3_RH_small.nc'\n \n# Comet/Ankitesh path below\n# TRAINFILE_RH = 'CI_RH_M4K_NORM_train_shuffle.nc'\n# NORMFILE_RH = 'CI_RH_M4K_NORM_norm.nc'\n# VALIDFILE_RH = 'CI_RH_M4K_NORM_valid.nc'", "_____no_output_____" ], [ "train_gen_RH = DataGenerator(\n data_fn = path+TRAINFILE_RH,\n input_vars = in_vars_RH,\n output_vars = out_vars_RH,\n norm_fn = path+NORMFILE_RH,\n input_transform = ('mean', 'maxrs'),\n output_transform = scale_dict_RH,\n batch_size=1024,\n shuffle=True,\n)", "_____no_output_____" ] ], [ [ "### Data Generator using QSATdeficit", "_____no_output_____" ], [ "We only need the norm file for this generator as we are solely using it as an input to determine the right normalization for the combined generator", "_____no_output_____" ] ], [ [ "# New GP path below\nTRAINFILE_QSATdeficit = '2021_02_01_O3_QSATdeficit_small_shuffle.nc'\nNORMFILE_QSATdeficit = '2021_02_01_NORM_O3_QSATdeficit_small.nc'", "_____no_output_____" ], [ "in_vars_QSATdeficit = ['QSATdeficit','TBP','PS', 'SOLIN', 'SHFLX', 'LHFLX']\n# if path==path_realgeography: out_vars_RH = ['PTEQ','PTTEND','FSNT','FSNS','FLNT','FLNS']\n# elif path==path_aquaplanet: out_vars_RH = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS']\nif path==path_aquaplanet: out_vars_QSATdeficit = ['PHQ','TPHYSTND','QRL','QRS']", "_____no_output_____" ], [ "train_gen_QSATdeficit = DataGenerator(\n data_fn = path+TRAINFILE_QSATdeficit,\n input_vars = in_vars_QSATdeficit,\n output_vars = out_vars_QSATdeficit,\n norm_fn = path+NORMFILE_QSATdeficit,\n input_transform = ('mean', 'maxrs'),\n output_transform = scale_dict,\n batch_size=1024,\n shuffle=True,\n)", "_____no_output_____" ] ], [ [ "### Data Generator using TNS", "_____no_output_____" ] ], [ [ "in_vars = ['QBP','TfromNS','PS', 'SOLIN', 'SHFLX', 'LHFLX']\nif path==path_aquaplanet: out_vars = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS']\nelif path==path_realgeography: out_vars = ['PTEQ','PTTEND','FSNT','FSNS','FLNT','FLNS']\n\nTRAINFILE_TNS = '2021_02_01_O3_TfromNS_small_shuffle.nc'\nNORMFILE_TNS = '2021_02_01_NORM_O3_TfromNS_small.nc'\nVALIDFILE_TNS = 'CI_TNS_M4K_NORM_valid.nc'", "_____no_output_____" ], [ "train_gen_TNS = DataGenerator(\n data_fn = path+TRAINFILE_TNS,\n input_vars = in_vars,\n output_vars = out_vars,\n norm_fn = path+NORMFILE_TNS,\n input_transform = ('mean', 'maxrs'),\n output_transform = scale_dict,\n batch_size=1024,\n shuffle=True,\n)", "_____no_output_____" ] ], [ [ "### Data Generator using BCONS", "_____no_output_____" ] ], [ [ "in_vars = ['QBP','BCONS','PS', 'SOLIN', 'SHFLX', 'LHFLX']\nif path==path_aquaplanet: out_vars = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS']\nelif path==path_realgeography: out_vars = ['PTEQ','PTTEND','FSNT','FSNS','FLNT','FLNS']\n\nTRAINFILE_BCONS = '2021_02_01_O3_BCONS_small_shuffle.nc'\nNORMFILE_BCONS = '2021_02_01_NORM_O3_BCONS_small.nc'", "_____no_output_____" ], [ "train_gen_BCONS = DataGenerator(\n data_fn = path+TRAINFILE_BCONS,\n input_vars = in_vars,\n output_vars = out_vars,\n norm_fn = path+NORMFILE_BCONS,\n input_transform = ('mean', 'maxrs'),\n output_transform = scale_dict,\n batch_size=1024,\n shuffle=True,\n)", "_____no_output_____" ] ], [ [ "### Data Generator using NSto220", "_____no_output_____" ] ], [ [ "in_vars = ['QBP','T_NSto220','PS', 'SOLIN', 'SHFLX', 'LHFLX']\nif path==path_aquaplanet: out_vars = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS']\nelif path==path_realgeography: out_vars = ['PTEQ','PTTEND','FSNT','FSNS','FLNT','FLNS']\n\nTRAINFILE_T_NSto220 = '2021_03_31_O3_T_NSto220_small.nc'\nNORMFILE_T_NSto220 = '2021_03_31_NORM_O3_T_NSto220_small.nc'", "_____no_output_____" ], [ "train_gen_T_NSto220 = DataGenerator(\n data_fn = path+TRAINFILE_T_NSto220,\n input_vars = in_vars,\n output_vars = out_vars,\n norm_fn = path+NORMFILE_T_NSto220,\n input_transform = ('mean', 'maxrs'),\n output_transform = scale_dict,\n batch_size=8192,\n shuffle=True,\n)", "_____no_output_____" ] ], [ [ "### Data Generator using LHF_nsDELQ", "_____no_output_____" ] ], [ [ "in_vars = ['QBP','TBP','PS', 'SOLIN', 'SHFLX', 'LHF_nsDELQ']\nif path==path_aquaplanet: out_vars = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS']\nelif path==path_realgeography: out_vars = ['PTEQ','PTTEND','FSNT','FSNS','FLNT','FLNS']\n\nTRAINFILE_LHF_nsDELQ = '2021_02_01_O3_LHF_nsDELQ_small_shuffle.nc'\nNORMFILE_LHF_nsDELQ = '2021_02_01_NORM_O3_LHF_nsDELQ_small.nc'", "_____no_output_____" ], [ "train_gen_LHF_nsDELQ = DataGenerator(\n data_fn = path+TRAINFILE_LHF_nsDELQ,\n input_vars = in_vars,\n output_vars = out_vars,\n norm_fn = path+NORMFILE_LHF_nsDELQ,\n input_transform = ('mean', 'maxrs'),\n output_transform = scale_dict,\n batch_size=8192,\n shuffle=True,\n)", "_____no_output_____" ] ], [ [ "### Data Generator using LHF_nsQ", "_____no_output_____" ] ], [ [ "in_vars = ['QBP','TBP','PS', 'SOLIN', 'SHFLX', 'LHF_nsQ']\nif path==path_aquaplanet: out_vars = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS']\nelif path==path_realgeography: out_vars = ['PTEQ','PTTEND','FSNT','FSNS','FLNT','FLNS']\n\nTRAINFILE_LHF_nsQ = '2021_02_01_O3_LHF_nsQ_small_shuffle.nc'\nNORMFILE_LHF_nsQ = '2021_02_01_NORM_O3_LHF_nsQ_small.nc'", "_____no_output_____" ], [ "train_gen_LHF_nsQ = DataGenerator(\n data_fn = path+TRAINFILE_LHF_nsQ,\n input_vars = in_vars,\n output_vars = out_vars,\n norm_fn = path+NORMFILE_LHF_nsQ,\n input_transform = ('mean', 'maxrs'),\n output_transform = scale_dict,\n batch_size=8192,\n shuffle=True,\n)", "_____no_output_____" ] ], [ [ "### Data Generator Combined (latest flexible version)", "_____no_output_____" ] ], [ [ "in_vars = ['QBP','TBP','PS', 'SOLIN', 'SHFLX', 'LHFLX']\n#if path==path_aquaplanet: out_vars=['PHQPERC','TPHYSTNDPERC','QRLPERC','QRSPERC']\nout_vars = ['PHQ','TPHYSTND','QRL','QRS']", "_____no_output_____" ], [ "# TRAINFILE = '2021_01_24_O3_TRAIN_shuffle.nc'\nNORMFILE = '2021_01_24_NORM_O3_small.nc'\n# VALIDFILE = '2021_01_24_O3_VALID.nc'\n# GENTESTFILE = 'CI_SP_P4K_valid.nc'\n\n# In physical space\nTRAINFILE = '2021_03_18_O3_TRAIN_M4K_shuffle.nc'\nVALIDFILE = '2021_03_18_O3_VALID_M4K.nc'\nTESTFILE_DIFFCLIMATE = '2021_03_18_O3_TRAIN_P4K_shuffle.nc'\nTESTFILE_DIFFGEOG = '2021_04_18_RG_TRAIN_M4K_shuffle.nc'\n\n# In percentile space\n#TRAINFILE = '2021_04_09_PERC_TRAIN_M4K_shuffle.nc'\n#TRAINFILE = '2021_01_24_O3_small_shuffle.nc'\n#VALIDFILE = '2021_04_09_PERC_VALID_M4K.nc'\n#TESTFILE = '2021_04_09_PERC_TEST_P4K.nc'", "_____no_output_____" ] ], [ [ "Old data generator by Ankitesh", "_____no_output_____" ], [ "Improved flexible data generator", "_____no_output_____" ] ], [ [ "train_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling=None,\n Tscaling=None,\n LHFscaling=None,\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=None,\n inp_div_Qscaling=None,\n inp_sub_Tscaling=None,\n inp_div_Tscaling=None,\n inp_sub_LHFscaling=None,\n inp_div_LHFscaling=None,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "valid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling=None,\n Tscaling=None,\n LHFscaling=None,\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=None,\n inp_div_Qscaling=None,\n inp_sub_Tscaling=None,\n inp_div_Tscaling=None,\n inp_sub_LHFscaling=None,\n inp_div_LHFscaling=None,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "test_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling=None,\n Tscaling=None,\n LHFscaling=None,\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=None,\n inp_div_Qscaling=None,\n inp_sub_Tscaling=None,\n inp_div_Tscaling=None,\n inp_sub_LHFscaling=None,\n inp_div_LHFscaling=None,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "test_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling=None,\n Tscaling=None,\n LHFscaling=None,\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=None,\n inp_div_Qscaling=None,\n inp_sub_Tscaling=None,\n inp_div_Tscaling=None,\n inp_sub_LHFscaling=None,\n inp_div_LHFscaling=None,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ] ], [ [ "## Add callback class to track loss on multiple sets during training", "_____no_output_____" ], [ "From [https://stackoverflow.com/questions/47731935/using-multiple-validation-sets-with-keras]", "_____no_output_____" ] ], [ [ "test_diffgeog_gen_CI[0][0].shape", "_____no_output_____" ], [ "np.argwhere(np.isnan(test_gen_CI[0][1]))", "_____no_output_____" ], [ "np.argwhere(np.isnan(test_gen_CI[0][0]))", "_____no_output_____" ], [ "class AdditionalValidationSets(Callback):\n def __init__(self, validation_sets, verbose=0, batch_size=None):\n \"\"\"\n :param validation_sets:\n a list of 3-tuples (validation_data, validation_targets, validation_set_name)\n or 4-tuples (validation_data, validation_targets, sample_weights, validation_set_name)\n :param verbose:\n verbosity mode, 1 or 0\n :param batch_size:\n batch size to be used when evaluating on the additional datasets\n \"\"\"\n super(AdditionalValidationSets, self).__init__()\n self.validation_sets = validation_sets\n self.epoch = []\n self.history = {}\n self.verbose = verbose\n self.batch_size = batch_size\n\n def on_train_begin(self, logs=None):\n self.epoch = []\n self.history = {}\n\n def on_epoch_end(self, epoch, logs=None):\n logs = logs or {}\n self.epoch.append(epoch)\n\n # record the same values as History() as well\n for k, v in logs.items():\n self.history.setdefault(k, []).append(v)\n\n # evaluate on the additional validation sets\n for validation_set in self.validation_sets:\n valid_generator,valid_name = validation_set\n #tf.print('Results')\n results = self.model.evaluate_generator(generator=valid_generator)\n #tf.print(results)\n\n for metric, result in zip(self.model.metrics_names,[results]):\n #tf.print(metric,result)\n valuename = valid_name + '_' + metric\n self.history.setdefault(valuename, []).append(result)", "_____no_output_____" ] ], [ [ "## Quick test to develop custom loss fx (no loss tracking across multiple datasets)", "_____no_output_____" ], [ "#### Input and Output Rescaling (T=BCONS)", "_____no_output_____" ] ], [ [ "Tscaling_name = 'BCONS'\ntrain_gen_T = train_gen_BCONS\n\ntrain_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\nvalid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\ndense_out = tf.keras.activations.sigmoid(dense_out)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_2 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 120) 7800 \n_________________________________________________________________\ntf_op_layer_Sigmoid (TensorF [(None, 120)] 0 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'", "_____no_output_____" ], [ "pdf = {}", "_____no_output_____" ], [ "for ipath,path in enumerate([TRAINFILE,VALIDFILE,TESTFILE_DIFFCLIMATE,TESTFILE_DIFFGEOG]):\n hf = open(pathPKL+'/'+path+'_PERC.pkl','rb')\n pdf[path] = pickle.load(hf)", "_____no_output_____" ], [ "def mse_physical(pdf):\n \n def loss(y_true,y_pred):\n y_true_physical = tf.identity(y_true)\n y_pred_physical = tf.identity(y_pred)\n for ilev in range(120):\n y_true_physical[:,ilev] = \\\n tfp.math.interp_regular_1d_grid(y_true[:,ilev],\n x_ref_min=0,x_ref_max=1,y_ref=pdf[:,ilev])\n y_pred_physical[:,ilev] = \\\n tfp.math.interp_regular_1d_grid(y_pred[:,ilev],\n x_ref_min=0,x_ref_max=1,y_ref=pdf[:,ilev])\n return tf.mean(tf.math.squared_difference(y_pred, y_true), axis=-1)\n \n return loss ", "_____no_output_____" ], [ "# model = load_model('model.h5', \n# custom_objects={'loss': asymmetric_loss(alpha)})", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), \n loss=mse_physical(pdf=np.float32(pdf['2021_03_18_O3_TRAIN_M4K_shuffle.nc']['PERC_array'][:,94:])))", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\n#save_name = '2021_06_12_LOGI_PERC_RH_BCONS_LHF_nsDELQ'\nsave_name = '2021_06_12_Test'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos])", "Epoch 1/20\n1577/5759 [=======>......................] - ETA: 27:04 - loss: 0.0337" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "## Models tracking losses across climates and geography (Based on cold Aquaplanet)", "_____no_output_____" ], [ "### MLR or Logistic regression", "_____no_output_____" ], [ "#### BF", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_4 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_MLR'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "#model.load_weights(path_HDF5+save_name+'.hdf5')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/20\n5758/5759 [============================>.] - ETA: 0s - loss: 341.8513" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "#### Input Rescaling (T=T-TNS)", "_____no_output_____" ] ], [ [ "Tscaling_name = 'TfromNS'\ntrain_gen_T = train_gen_TNS\n\ntrain_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\nvalid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_MLR_RH_TfromNS_LHF_nsDELQ'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/20\n5759/5759 [==============================] - 3237s 562ms/step - loss: 333.7198 - val_loss: 318.1690\nEpoch 2/20\n5759/5759 [==============================] - 3207s 557ms/step - loss: 310.0145 - val_loss: 306.5839\nEpoch 3/20\n5759/5759 [==============================] - 3198s 555ms/step - loss: 302.6933 - val_loss: 301.9040\nEpoch 4/20\n5758/5759 [============================>.] - ETA: 0s - loss: 299.3518" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "#### Input Rescaling (T=BCONS)", "_____no_output_____" ] ], [ [ "Tscaling_name = 'BCONS'\ntrain_gen_T = train_gen_BCONS\n\ntrain_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\nvalid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_MLR_RH_BCONS_LHF_nsDELQ'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "#### Input and Output Rescaling (T=T-TNS)", "_____no_output_____" ] ], [ [ "in_vars = ['QBP','TBP','PS', 'SOLIN', 'SHFLX', 'LHFLX']\nout_vars=['PHQPERC','TPHYSTNDPERC','QRLPERC','QRSPERC']", "_____no_output_____" ], [ "# TRAINFILE = '2021_01_24_O3_TRAIN_shuffle.nc'\nNORMFILE = '2021_01_24_NORM_O3_small.nc'\n# VALIDFILE = '2021_01_24_O3_VALID.nc'\n# GENTESTFILE = 'CI_SP_P4K_valid.nc'\n\n# In percentile space\nTRAINFILE = '2021_04_09_PERC_TRAIN_M4K_shuffle.nc'\nVALIDFILE = '2021_04_09_PERC_VALID_M4K.nc'\nTESTFILE_DIFFCLIMATE = '2021_04_09_PERC_TRAIN_P4K_shuffle.nc'\nTESTFILE_DIFFGEOG = '2021_04_24_RG_PERC_TRAIN_M4K_shuffle.nc'", "_____no_output_____" ], [ "Tscaling_name = 'TfromNS'\ntrain_gen_T = train_gen_TNS\n\ntrain_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\nvalid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\ndense_out = tf.keras.activations.sigmoid(dense_out)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_LOGI_PERC_RH_TfromNS_LHF_nsDELQ'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "#### Input and Output Rescaling (T=BCONS)", "_____no_output_____" ] ], [ [ "Tscaling_name = 'BCONS'\ntrain_gen_T = train_gen_BCONS\n\ntrain_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\nvalid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\ndense_out = tf.keras.activations.sigmoid(dense_out)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_LOGI_PERC_RH_BCONS_LHF_nsDELQ'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### NN", "_____no_output_____" ] ], [ [ "in_vars = ['QBP','TBP','PS', 'SOLIN', 'SHFLX', 'LHFLX']\n#if path==path_aquaplanet: out_vars=['PHQPERC','TPHYSTNDPERC','QRLPERC','QRSPERC']\nout_vars = ['PHQ','TPHYSTND','QRL','QRS']", "_____no_output_____" ], [ "# TRAINFILE = '2021_01_24_O3_TRAIN_shuffle.nc'\nNORMFILE = '2021_01_24_NORM_O3_small.nc'\n# VALIDFILE = '2021_01_24_O3_VALID.nc'\n# GENTESTFILE = 'CI_SP_P4K_valid.nc'\n\n# In physical space\nTRAINFILE = '2021_03_18_O3_TRAIN_M4K_shuffle.nc'\nVALIDFILE = '2021_03_18_O3_VALID_M4K.nc'\nTESTFILE_DIFFCLIMATE = '2021_03_18_O3_TRAIN_P4K_shuffle.nc'\nTESTFILE_DIFFGEOG = '2021_04_18_RG_TRAIN_M4K_shuffle.nc'", "_____no_output_____" ], [ "train_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling=None,\n Tscaling=None,\n LHFscaling=None,\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=None,\n inp_div_Qscaling=None,\n inp_sub_Tscaling=None,\n inp_div_Tscaling=None,\n inp_sub_LHFscaling=None,\n inp_div_LHFscaling=None,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "valid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling=None,\n Tscaling=None,\n LHFscaling=None,\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=None,\n inp_div_Qscaling=None,\n inp_sub_Tscaling=None,\n inp_div_Tscaling=None,\n inp_sub_LHFscaling=None,\n inp_div_LHFscaling=None,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "test_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling=None,\n Tscaling=None,\n LHFscaling=None,\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=None,\n inp_div_Qscaling=None,\n inp_sub_Tscaling=None,\n inp_div_Tscaling=None,\n inp_sub_LHFscaling=None,\n inp_div_LHFscaling=None,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "test_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling=None,\n Tscaling=None,\n LHFscaling=None,\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=None,\n inp_div_Qscaling=None,\n inp_sub_Tscaling=None,\n inp_div_Tscaling=None,\n inp_sub_LHFscaling=None,\n inp_div_LHFscaling=None,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\n", "_____no_output_____" ] ], [ [ "#### BF", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(densout)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_NN'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "#model.load_weights(path_HDF5+save_name+'.hdf5')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "#### Input Rescaling (T=T-TNS)", "_____no_output_____" ] ], [ [ "Tscaling_name = 'TfromNS'\ntrain_gen_T = train_gen_TNS\n\ntrain_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\nvalid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(densout)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_NN_RH_TfromNS_LHF_nsDELQ'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "#### Input Rescaling (T=BCONS)", "_____no_output_____" ] ], [ [ "Tscaling_name = 'BCONS'\ntrain_gen_T = train_gen_BCONS\n\ntrain_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\nvalid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=scale_dict,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(densout)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_NN_RH_BCONS_LHF_nsDELQ'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "#### Input and Output Rescaling (T=T-TNS)", "_____no_output_____" ] ], [ [ "in_vars = ['QBP','TBP','PS', 'SOLIN', 'SHFLX', 'LHFLX']\nout_vars=['PHQPERC','TPHYSTNDPERC','QRLPERC','QRSPERC']", "_____no_output_____" ], [ "# TRAINFILE = '2021_01_24_O3_TRAIN_shuffle.nc'\nNORMFILE = '2021_01_24_NORM_O3_small.nc'\n# VALIDFILE = '2021_01_24_O3_VALID.nc'\n# GENTESTFILE = 'CI_SP_P4K_valid.nc'\n\n# In percentile space\nTRAINFILE = '2021_04_09_PERC_TRAIN_M4K_shuffle.nc'\nVALIDFILE = '2021_04_09_PERC_VALID_M4K.nc'\nTESTFILE_DIFFCLIMATE = '2021_04_09_PERC_TRAIN_P4K_shuffle.nc'\nTESTFILE_DIFFGEOG = '2021_04_24_RG_PERC_TRAIN_M4K_shuffle.nc'", "_____no_output_____" ], [ "Tscaling_name = 'TfromNS'\ntrain_gen_T = train_gen_TNS\n\ntrain_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\nvalid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(densout)\ndense_out = tf.keras.activations.sigmoid(dense_out)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_NN_PERC_RH_TfromNS_LHF_nsDELQ'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "#### Input and Output Rescaling (T=BCONS)", "_____no_output_____" ] ], [ [ "Tscaling_name = 'BCONS'\ntrain_gen_T = train_gen_BCONS\n\ntrain_gen_CI = DataGeneratorCI(data_fn = path+TRAINFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\nvalid_gen_CI = DataGeneratorCI(data_fn = path+VALIDFILE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffclimate_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFCLIMATE,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')\n\ntest_diffgeog_gen_CI = DataGeneratorCI(data_fn = path+TESTFILE_DIFFGEOG,\n input_vars=in_vars,\n output_vars=out_vars,\n norm_fn=path+NORMFILE,\n input_transform=('mean', 'maxrs'),\n output_transform=None,\n batch_size=8192,\n shuffle=True,\n xarray=False,\n var_cut_off=None, \n Qscaling='RH',\n Tscaling=Tscaling_name,\n LHFscaling='LHF_nsDELQ',\n SHFscaling=None,\n output_scaling=False,\n interpolate=False,\n hyam=hyam,hybm=hybm,\n inp_sub_Qscaling=train_gen_RH.input_transform.sub,\n inp_div_Qscaling=train_gen_RH.input_transform.div,\n inp_sub_Tscaling=train_gen_T.input_transform.sub,\n inp_div_Tscaling=train_gen_T.input_transform.div,\n inp_sub_LHFscaling=train_gen_LHF_nsDELQ.input_transform.sub,\n inp_div_LHFscaling=train_gen_LHF_nsDELQ.input_transform.div,\n inp_sub_SHFscaling=None,\n inp_div_SHFscaling=None,\n lev=None, interm_size=40,\n lower_lim=6,is_continous=True,Tnot=5,\n epsQ=1e-3,epsT=1,mode='train')", "_____no_output_____" ], [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(densout)\ndense_out = tf.keras.activations.sigmoid(dense_out)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_26_NN_PERC_RH_BCONS_LHF_nsDELQ'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_diffclimate_gen_CI,'trainP4K'),(test_diffgeog_gen_CI,'trainM4K_RG')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "## Models tracking losses across climates/geography (Warm to Cold)", "_____no_output_____" ], [ "## Brute-Force Model", "_____no_output_____" ], [ "### Climate-invariant (T,Q,PS,S0,SHF,LHF)->($\\dot{T}$,$\\dot{q}$,RADFLUX)", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(64, activation='linear')(densout)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/oasis/scratch/comet/tbeucler/temp_project/CBRAIN_models/'\nsave_name = 'BF_temp'", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)\nearlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')\n# tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=0, update_freq=1000,embeddings_freq=1)", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen, epochs=Nep, validation_data=valid_gen,\\\n callbacks=[earlyStopping, mcp_save_pos])", "_____no_output_____" ] ], [ [ "### Ozone (T,Q,$O_{3}$,S0,PS,LHF,SHF)$\\rightarrow$($\\dot{q}$,$\\dot{T}$,lw,sw)", "_____no_output_____" ] ], [ [ "inp = Input(shape=(94,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(densout)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_01_25_O3'", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)\nearlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')\n# tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=0, update_freq=1000,embeddings_freq=1)", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_O3, epochs=Nep, validation_data=valid_gen_O3,\\\n callbacks=[earlyStopping, mcp_save_pos])", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_O3, epochs=Nep, validation_data=valid_gen_O3,\\\n callbacks=[earlyStopping, mcp_save_pos])", "_____no_output_____" ] ], [ [ "### No Ozone (T,Q,S0,PS,LHF,SHF)$\\rightarrow$($\\dot{q}$,$\\dot{T}$,lw,sw)", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(densout)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_01_25_noO3'", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "model.load_weights(path_HDF5+save_name+'.hdf5')", "_____no_output_____" ], [ "\nearlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')\n# tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=0, update_freq=1000,embeddings_freq=1)", "_____no_output_____" ], [ "# Nep = 15\n# model.fit_generator(train_gen_noO3, epochs=Nep, validation_data=valid_gen_noO3,\\\n# callbacks=[earlyStopping, mcp_save_pos])", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_noO3, epochs=Nep, validation_data=valid_gen_noO3,\\\n callbacks=[earlyStopping, mcp_save_pos])", "_____no_output_____" ] ], [ [ "### BF linear version", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\n# densout = Dense(128, activation='linear')(inp)\n# densout = LeakyReLU(alpha=0.3)(densout)\n# for i in range (6):\n# densout = Dense(128, activation='linear')(densout)\n# densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_15_MLR_PERC'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 15\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/15\n5759/5759 [==============================] - 1184s 206ms/step - loss: 0.0510 - val_loss: 0.0429\nEpoch 2/15\n5759/5759 [==============================] - 1035s 180ms/step - loss: 0.0419 - val_loss: 0.0427\nEpoch 3/15\n5759/5759 [==============================] - 753s 131ms/step - loss: 0.0417 - val_loss: 0.0425\nEpoch 4/15\n5759/5759 [==============================] - 726s 126ms/step - loss: 0.0416 - val_loss: 0.0424\nEpoch 5/15\n5759/5759 [==============================] - 765s 133ms/step - loss: 0.0415 - val_loss: 0.0424\nEpoch 6/15\n5759/5759 [==============================] - 713s 124ms/step - loss: 0.0415 - val_loss: 0.0424\nEpoch 7/15\n5759/5759 [==============================] - 756s 131ms/step - loss: 0.0415 - val_loss: 0.0423\nEpoch 8/15\n5759/5759 [==============================] - 766s 133ms/step - loss: 0.0415 - val_loss: 0.0423\nEpoch 9/15\n5759/5759 [==============================] - 763s 132ms/step - loss: 0.0415 - val_loss: 0.0423\nEpoch 10/15\n5759/5759 [==============================] - 729s 127ms/step - loss: 0.0414 - val_loss: 0.0424\nEpoch 11/15\n5759/5759 [==============================] - 774s 134ms/step - loss: 0.0414 - val_loss: 0.0422\nEpoch 12/15\n5759/5759 [==============================] - 744s 129ms/step - loss: 0.0414 - val_loss: 0.0423\nEpoch 13/15\n5759/5759 [==============================] - 750s 130ms/step - loss: 0.0414 - val_loss: 0.0421\nEpoch 14/15\n5759/5759 [==============================] - 731s 127ms/step - loss: 0.0414 - val_loss: 0.0423\nEpoch 15/15\n5759/5759 [==============================] - 744s 129ms/step - loss: 0.0414 - val_loss: 0.0425\n" ], [ "history.history", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### BF Logistic version", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\n# densout = Dense(128, activation='linear')(inp)\n# densout = LeakyReLU(alpha=0.3)(densout)\n# for i in range (6):\n# densout = Dense(128, activation='linear')(densout)\n# densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(inp)\ndense_out = tf.keras.activations.sigmoid(dense_out)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_3 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 120) 7800 \n_________________________________________________________________\ntf_op_layer_Sigmoid_1 (Tenso [(None, 120)] 0 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_15_Log_PERC'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 15\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/15\n5759/5759 [==============================] - 794s 138ms/step - loss: 0.0492 - val_loss: 0.0427\nEpoch 2/15\n5759/5759 [==============================] - 761s 132ms/step - loss: 0.0411 - val_loss: 0.0412\nEpoch 3/15\n5759/5759 [==============================] - 842s 146ms/step - loss: 0.0405 - val_loss: 0.0410\nEpoch 4/15\n5759/5759 [==============================] - 691s 120ms/step - loss: 0.0403 - val_loss: 0.0408\nEpoch 5/15\n5759/5759 [==============================] - 727s 126ms/step - loss: 0.0402 - val_loss: 0.0408\nEpoch 6/15\n5759/5759 [==============================] - 727s 126ms/step - loss: 0.0401 - val_loss: 0.0407\nEpoch 7/15\n5759/5759 [==============================] - 738s 128ms/step - loss: 0.0401 - val_loss: 0.0406\nEpoch 8/15\n5759/5759 [==============================] - 740s 129ms/step - loss: 0.0400 - val_loss: 0.0406\nEpoch 9/15\n5759/5759 [==============================] - 769s 133ms/step - loss: 0.0400 - val_loss: 0.0406\nEpoch 10/15\n5759/5759 [==============================] - 768s 133ms/step - loss: 0.0400 - val_loss: 0.0406\nEpoch 11/15\n5759/5759 [==============================] - 738s 128ms/step - loss: 0.0399 - val_loss: 0.0406\nEpoch 12/15\n5759/5759 [==============================] - 687s 119ms/step - loss: 0.0399 - val_loss: 0.0406\nEpoch 13/15\n5759/5759 [==============================] - 639s 111ms/step - loss: 0.0399 - val_loss: 0.0405\nEpoch 14/15\n5759/5759 [==============================] - 749s 130ms/step - loss: 0.0399 - val_loss: 0.0405\nEpoch 15/15\n5759/5759 [==============================] - 722s 125ms/step - loss: 0.0399 - val_loss: 0.0404\n" ], [ "history.history", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### BF NN version with test loss tracking", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(densout)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_2 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_15 (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_08_NN6L'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/20\n5759/5759 [==============================] - 2542s 441ms/step - loss: 342.0934 - val_loss: 329.9304\nEpoch 2/20\n5759/5759 [==============================] - 2701s 469ms/step - loss: 320.9061 - val_loss: 316.9567\nEpoch 3/20\n5759/5759 [==============================] - 2452s 426ms/step - loss: 311.2353 - val_loss: 309.6577\nEpoch 4/20\n5759/5759 [==============================] - 2254s 391ms/step - loss: 305.5034 - val_loss: 304.9600\nEpoch 5/20\n5759/5759 [==============================] - 1731s 301ms/step - loss: 301.7379 - val_loss: 301.6836\nEpoch 6/20\n5759/5759 [==============================] - 1117s 194ms/step - loss: 299.0327 - val_loss: 299.1967\nEpoch 7/20\n5759/5759 [==============================] - 816s 142ms/step - loss: 296.9427 - val_loss: 297.2431\nEpoch 8/20\n5759/5759 [==============================] - 713s 124ms/step - loss: 295.2764 - val_loss: 295.7120\nEpoch 9/20\n5759/5759 [==============================] - 694s 121ms/step - loss: 293.9242 - val_loss: 294.4352\nEpoch 10/20\n5759/5759 [==============================] - 691s 120ms/step - loss: 292.8106 - val_loss: 293.3954\nEpoch 11/20\n5759/5759 [==============================] - 712s 124ms/step - loss: 291.8827 - val_loss: 292.5364\nEpoch 12/20\n5759/5759 [==============================] - 722s 125ms/step - loss: 291.1030 - val_loss: 291.8280\nEpoch 13/20\n5759/5759 [==============================] - 700s 122ms/step - loss: 290.4395 - val_loss: 291.2006\nEpoch 14/20\n5759/5759 [==============================] - 699s 121ms/step - loss: 289.8687 - val_loss: 290.6818\nEpoch 15/20\n5759/5759 [==============================] - 702s 122ms/step - loss: 289.3730 - val_loss: 290.2150\nEpoch 16/20\n5759/5759 [==============================] - 703s 122ms/step - loss: 288.9378 - val_loss: 289.8255\nEpoch 17/20\n5759/5759 [==============================] - 684s 119ms/step - loss: 288.5535 - val_loss: 289.4663\nEpoch 18/20\n5759/5759 [==============================] - 694s 120ms/step - loss: 288.2098 - val_loss: 289.1482\nEpoch 19/20\n5759/5759 [==============================] - 691s 120ms/step - loss: 287.9012 - val_loss: 288.8622\nEpoch 20/20\n5759/5759 [==============================] - 700s 122ms/step - loss: 287.6209 - val_loss: 288.5948\n" ], [ "history.history", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### RH Logistic version", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\n# densout = Dense(128, activation='linear')(inp)\n# densout = LeakyReLU(alpha=0.3)(densout)\n# for i in range (6):\n# densout = Dense(128, activation='linear')(densout)\n# densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(inp)\ndense_out = tf.keras.activations.sigmoid(dense_out)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_4 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 120) 7800 \n_________________________________________________________________\ntf_op_layer_Sigmoid_2 (Tenso [(None, 120)] 0 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_15_Log_PERC_RH'", "_____no_output_____" ], [ "# history = AdditionalValidationSets([(train_gen_CI,valid_gen_CI,test_gen_CI)])\nhistory = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 15\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/15\n5759/5759 [==============================] - 1103s 191ms/step - loss: 0.0467 - val_loss: 0.0405\nEpoch 2/15\n5759/5759 [==============================] - 1136s 197ms/step - loss: 0.0392 - val_loss: 0.0394\nEpoch 3/15\n5759/5759 [==============================] - 1123s 195ms/step - loss: 0.0389 - val_loss: 0.0394\nEpoch 4/15\n5759/5759 [==============================] - 1115s 194ms/step - loss: 0.0388 - val_loss: 0.0393\nEpoch 5/15\n5759/5759 [==============================] - 1128s 196ms/step - loss: 0.0387 - val_loss: 0.0393\nEpoch 6/15\n5759/5759 [==============================] - 1082s 188ms/step - loss: 0.0387 - val_loss: 0.0393\nEpoch 7/15\n5759/5759 [==============================] - 1136s 197ms/step - loss: 0.0387 - val_loss: 0.0393\nEpoch 8/15\n5759/5759 [==============================] - 1069s 186ms/step - loss: 0.0387 - val_loss: 0.0392\nEpoch 9/15\n5759/5759 [==============================] - 1093s 190ms/step - loss: 0.0387 - val_loss: 0.0392\nEpoch 10/15\n5759/5759 [==============================] - 1121s 195ms/step - loss: 0.0387 - val_loss: 0.0393\nEpoch 11/15\n5759/5759 [==============================] - 1114s 193ms/step - loss: 0.0387 - val_loss: 0.0392\nEpoch 12/15\n5759/5759 [==============================] - 1146s 199ms/step - loss: 0.0387 - val_loss: 0.0392\nEpoch 13/15\n5759/5759 [==============================] - 1111s 193ms/step - loss: 0.0387 - val_loss: 0.0392\nEpoch 14/15\n5759/5759 [==============================] - 1079s 187ms/step - loss: 0.0386 - val_loss: 0.0392\nEpoch 15/15\n5759/5759 [==============================] - 1139s 198ms/step - loss: 0.0386 - val_loss: 0.0392\n" ], [ "history.history", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### RH linear version", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_03_19_MLR_RH'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/10\n 3/5759 [..............................] - ETA: 56:44 - loss: 362.5890 " ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### QSATdeficit linear version", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_03_19_MLR_QSATdeficit'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### TfromNS linear version", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_03_19_MLR_TfromNS'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### BCONS linear version", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_03_19_MLR_BCONS'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "_____no_output_____" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "## Mixed Model", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_03_19_MLR_RH_BCONS'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/10\n5759/5759 [==============================] - 8098s 1s/step - loss: 324.9880 - val_loss: 313.2678\nEpoch 2/10\n5759/5759 [==============================] - 12555s 2s/step - loss: 308.3165 - val_loss: 307.0678\nEpoch 3/10\n5759/5759 [==============================] - 13642s 2s/step - loss: 304.0913 - val_loss: 304.2872\nEpoch 4/10\n5759/5759 [==============================] - 10465s 2s/step - loss: 301.8938 - val_loss: 302.7330\nEpoch 5/10\n5759/5759 [==============================] - 7909s 1s/step - loss: 300.5873 - val_loss: 301.7510\nEpoch 6/10\n5759/5759 [==============================] - 8526s 1s/step - loss: 299.7002 - val_loss: 301.0397\nEpoch 7/10\n5759/5759 [==============================] - 7230s 1s/step - loss: 299.0066 - val_loss: 300.3937\nEpoch 8/10\n5759/5759 [==============================] - 8294s 1s/step - loss: 298.4328 - val_loss: 299.8434\nEpoch 9/10\n5759/5759 [==============================] - 8250s 1s/step - loss: 297.9426 - val_loss: 299.4925\nEpoch 10/10\n5759/5759 [==============================] - 8909s 2s/step - loss: 297.5149 - val_loss: 299.0509\n" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### RH+(T-TNS)", "_____no_output_____" ], [ "### RH+NSto220", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_03_31_MLR_RH_NSto220'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/10\n5759/5759 [==============================] - 10546s 2s/step - loss: 333.2154 - val_loss: 318.1506\nEpoch 2/10\n5759/5759 [==============================] - 10194s 2s/step - loss: 310.9067 - val_loss: 308.3093\nEpoch 3/10\n5759/5759 [==============================] - 9862s 2s/step - loss: 304.7300 - val_loss: 304.2289\nEpoch 4/10\n5759/5759 [==============================] - 11121s 2s/step - loss: 301.8291 - val_loss: 302.1135\nEpoch 5/10\n5759/5759 [==============================] - 10748s 2s/step - loss: 300.2339 - val_loss: 300.8775\nEpoch 6/10\n5759/5759 [==============================] - 10117s 2s/step - loss: 299.1923 - val_loss: 299.9938\nEpoch 7/10\n5759/5759 [==============================] - 10174s 2s/step - loss: 298.3948 - val_loss: 299.3052\nEpoch 8/10\n5759/5759 [==============================] - 9887s 2s/step - loss: 297.7428 - val_loss: 298.7333\nEpoch 9/10\n5759/5759 [==============================] - 10299s 2s/step - loss: 297.1934 - val_loss: 298.2455\nEpoch 10/10\n5759/5759 [==============================] - 10431s 2s/step - loss: 296.7218 - val_loss: 297.8241\n" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### RH+LHF_nsQ", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_2 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_03_19_MLR_RH_LHF_nsQ'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/10\n5759/5759 [==============================] - 7449s 1s/step - loss: 332.8352 - val_loss: 318.1170\nEpoch 2/10\n5759/5759 [==============================] - 5519s 958ms/step - loss: 311.1496 - val_loss: 308.7574\nEpoch 3/10\n5759/5759 [==============================] - 5822s 1s/step - loss: 305.3264 - val_loss: 304.9336\nEpoch 4/10\n5759/5759 [==============================] - 6582s 1s/step - loss: 302.6262 - val_loss: 302.9958\nEpoch 5/10\n5759/5759 [==============================] - 7103s 1s/step - loss: 301.1792 - val_loss: 301.9337\nEpoch 6/10\n5759/5759 [==============================] - 14946s 3s/step - loss: 300.2849 - val_loss: 301.1922\nEpoch 7/10\n5759/5759 [==============================] - 4869s 846ms/step - loss: 299.6383 - val_loss: 300.6844\nEpoch 8/10\n5759/5759 [==============================] - 5781s 1s/step - loss: 299.1321 - val_loss: 300.2569\nEpoch 9/10\n5759/5759 [==============================] - 6748s 1s/step - loss: 298.7180 - val_loss: 299.8978\nEpoch 10/10\n5759/5759 [==============================] - 4745s 824ms/step - loss: 298.3688 - val_loss: 299.6018\n" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### RH+TfromNS+LHF_nsDELQ NN version with test loss tracking", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndensout = Dense(128, activation='linear')(inp)\ndensout = LeakyReLU(alpha=0.3)(densout)\nfor i in range (6):\n densout = Dense(128, activation='linear')(densout)\n densout = LeakyReLU(alpha=0.3)(densout)\ndense_out = Dense(120, activation='linear')(densout)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_5\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_6 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_40 (Dense) (None, 128) 8320 \n_________________________________________________________________\nleaky_re_lu_35 (LeakyReLU) (None, 128) 0 \n_________________________________________________________________\ndense_41 (Dense) (None, 128) 16512 \n_________________________________________________________________\nleaky_re_lu_36 (LeakyReLU) (None, 128) 0 \n_________________________________________________________________\ndense_42 (Dense) (None, 128) 16512 \n_________________________________________________________________\nleaky_re_lu_37 (LeakyReLU) (None, 128) 0 \n_________________________________________________________________\ndense_43 (Dense) (None, 128) 16512 \n_________________________________________________________________\nleaky_re_lu_38 (LeakyReLU) (None, 128) 0 \n_________________________________________________________________\ndense_44 (Dense) (None, 128) 16512 \n_________________________________________________________________\nleaky_re_lu_39 (LeakyReLU) (None, 128) 0 \n_________________________________________________________________\ndense_45 (Dense) (None, 128) 16512 \n_________________________________________________________________\nleaky_re_lu_40 (LeakyReLU) (None, 128) 0 \n_________________________________________________________________\ndense_46 (Dense) (None, 128) 16512 \n_________________________________________________________________\nleaky_re_lu_41 (LeakyReLU) (None, 128) 0 \n_________________________________________________________________\ndense_47 (Dense) (None, 120) 15480 \n=================================================================\nTotal params: 122,872\nTrainable params: 122,872\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_09_NN7L_RH_TfromNS_LHF_nsDELQ'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 20\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/20\n5759/5759 [==============================] - 2906s 505ms/step - loss: 202.5537 - val_loss: 189.6939\nEpoch 2/20\n5759/5759 [==============================] - 2024s 352ms/step - loss: 185.1673 - val_loss: 182.6220\nEpoch 3/20\n5759/5759 [==============================] - 1676s 291ms/step - loss: 180.0439 - val_loss: 180.6006\nEpoch 4/20\n5759/5759 [==============================] - 1666s 289ms/step - loss: 177.2701 - val_loss: 176.7251\nEpoch 5/20\n5759/5759 [==============================] - 1665s 289ms/step - loss: 175.5439 - val_loss: 175.3660\nEpoch 6/20\n5759/5759 [==============================] - 1634s 284ms/step - loss: 174.3043 - val_loss: 174.8005\nEpoch 7/20\n5759/5759 [==============================] - 1668s 290ms/step - loss: 173.3022 - val_loss: 173.3208\nEpoch 8/20\n5759/5759 [==============================] - 1678s 291ms/step - loss: 172.4542 - val_loss: 172.6152\nEpoch 9/20\n5759/5759 [==============================] - 2503s 435ms/step - loss: 171.7443 - val_loss: 172.0109\nEpoch 10/20\n5758/5759 [============================>.] - ETA: 0s - loss: 171.1936" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### RH+TfromNS+LHF_nsQ", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_3 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_03_23_MLR_RH_TfromNS_LHF_nsQ'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/10\n5759/5759 [==============================] - 6478s 1s/step - loss: 334.0426 - val_loss: 318.8078\nEpoch 2/10\n5759/5759 [==============================] - 7037s 1s/step - loss: 310.9031 - val_loss: 307.7163\nEpoch 3/10\n5759/5759 [==============================] - 5910s 1s/step - loss: 304.0670 - val_loss: 303.4669\nEpoch 4/10\n5759/5759 [==============================] - 7744s 1s/step - loss: 301.0845 - val_loss: 301.4636\nEpoch 5/10\n5759/5759 [==============================] - 7767s 1s/step - loss: 299.5355 - val_loss: 300.3262\nEpoch 6/10\n5759/5759 [==============================] - 7525s 1s/step - loss: 298.5930 - val_loss: 299.6363\nEpoch 7/10\n5759/5759 [==============================] - 7967s 1s/step - loss: 297.9281 - val_loss: 299.1007\nEpoch 8/10\n5759/5759 [==============================] - 6677s 1s/step - loss: 297.4247 - val_loss: 298.6999\nEpoch 9/10\n5759/5759 [==============================] - 6912s 1s/step - loss: 297.0260 - val_loss: 298.3802\nEpoch 10/10\n5759/5759 [==============================] - 8484s 1s/step - loss: 296.6993 - val_loss: 298.1298\n" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### RH+BCONS+LHF_nsDELQ", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_4 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_03_23_MLR_RH_BCONS_LHF_nsDELQ'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/10\n5759/5759 [==============================] - 8133s 1s/step - loss: 330.7609 - val_loss: 316.7712\nEpoch 2/10\n5759/5759 [==============================] - 6660s 1s/step - loss: 310.4906 - val_loss: 307.8904\nEpoch 3/10\n5759/5759 [==============================] - 7116s 1s/step - loss: 304.7100 - val_loss: 303.9924\nEpoch 4/10\n5759/5759 [==============================] - 7062s 1s/step - loss: 301.7960 - val_loss: 301.8254\nEpoch 5/10\n5759/5759 [==============================] - 8137s 1s/step - loss: 300.0964 - val_loss: 300.5073\nEpoch 6/10\n5759/5759 [==============================] - 7596s 1s/step - loss: 298.9904 - val_loss: 299.6046\nEpoch 7/10\n5759/5759 [==============================] - 7545s 1s/step - loss: 298.1876 - val_loss: 298.9532\nEpoch 8/10\n5759/5759 [==============================] - 7470s 1s/step - loss: 297.5743 - val_loss: 298.4452\nEpoch 9/10\n5759/5759 [==============================] - 7456s 1s/step - loss: 297.0949 - val_loss: 298.0184\nEpoch 10/10\n5759/5759 [==============================] - 7469s 1s/step - loss: 296.7098 - val_loss: 297.6911\n" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### RH+NSto220+LHF_nsDELQ", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_2 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_01_MLR_RH_NSto220_LHF_nsDELQ'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/10\n5759/5759 [==============================] - 11407s 2s/step - loss: 333.0526 - val_loss: 317.6788\nEpoch 2/10\n5759/5759 [==============================] - 10810s 2s/step - loss: 310.2102 - val_loss: 307.3595\nEpoch 3/10\n5759/5759 [==============================] - 10216s 2s/step - loss: 303.6873 - val_loss: 302.9961\nEpoch 4/10\n5759/5759 [==============================] - 10683s 2s/step - loss: 300.5542 - val_loss: 300.6824\nEpoch 5/10\n5759/5759 [==============================] - 10550s 2s/step - loss: 298.8112 - val_loss: 299.3256\nEpoch 6/10\n5759/5759 [==============================] - 10292s 2s/step - loss: 297.7034 - val_loss: 298.4254\nEpoch 7/10\n5759/5759 [==============================] - 10560s 2s/step - loss: 296.9044 - val_loss: 297.7670\nEpoch 8/10\n5759/5759 [==============================] - 11866s 2s/step - loss: 296.3028 - val_loss: 297.2482\nEpoch 9/10\n5759/5759 [==============================] - 10787s 2s/step - loss: 295.8395 - val_loss: 296.8615\nEpoch 10/10\n5759/5759 [==============================] - 11359s 2s/step - loss: 295.4770 - val_loss: 296.5718\n" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ], [ [ "### RH+NSto220+LHF_nsQ", "_____no_output_____" ] ], [ [ "inp = Input(shape=(64,)) ## input after rh and tns transformation\ndense_out = Dense(120, activation='linear')(inp)\nmodel = tf.keras.models.Model(inp, dense_out)", "_____no_output_____" ], [ "model.summary()", "Model: \"model_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_3 (InputLayer) [(None, 64)] 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 120) 7800 \n=================================================================\nTotal params: 7,800\nTrainable params: 7,800\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(tf.keras.optimizers.Adam(), loss=mse)", "_____no_output_____" ], [ "# Where to save the model\npath_HDF5 = '/DFS-L/DATA/pritchard/tbeucler/SPCAM/HDF5_DATA/'\nsave_name = '2021_04_03_MLR_RH_NSto220_LHF_nsQ'", "_____no_output_____" ], [ "history = AdditionalValidationSets([(test_gen_CI,'testP4K')])", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')\nmcp_save_pos = ModelCheckpoint(path_HDF5+save_name+'.hdf5',save_best_only=True, monitor='val_loss', mode='min')", "_____no_output_____" ], [ "Nep = 10\nmodel.fit_generator(train_gen_CI, epochs=Nep, validation_data=valid_gen_CI,\\\n callbacks=[earlyStopping, mcp_save_pos, history])", "Epoch 1/10\n5759/5759 [==============================] - 9714s 2s/step - loss: 333.0516 - val_loss: 317.9425\nEpoch 2/10\n5759/5759 [==============================] - 6439s 1s/step - loss: 310.6932 - val_loss: 308.0465\nEpoch 3/10\n5759/5759 [==============================] - 5183s 900ms/step - loss: 304.5171 - val_loss: 304.0613\nEpoch 4/10\n5759/5759 [==============================] - 6201s 1s/step - loss: 301.7091 - val_loss: 302.0904\nEpoch 5/10\n5759/5759 [==============================] - 6448s 1s/step - loss: 300.2337 - val_loss: 301.0068\nEpoch 6/10\n5759/5759 [==============================] - 6364s 1s/step - loss: 299.3400 - val_loss: 300.3276\nEpoch 7/10\n5759/5759 [==============================] - 5246s 911ms/step - loss: 298.7033 - val_loss: 299.8050\nEpoch 8/10\n5759/5759 [==============================] - 5084s 883ms/step - loss: 298.2143 - val_loss: 299.3951\nEpoch 9/10\n5759/5759 [==============================] - 7377s 1s/step - loss: 297.8223 - val_loss: 299.0667\nEpoch 10/10\n5759/5759 [==============================] - 6087s 1s/step - loss: 297.4986 - val_loss: 298.8082\n" ], [ "hist_rec = history.history", "_____no_output_____" ], [ "hist_rec", "_____no_output_____" ], [ "pathPKL = '/export/home/tbeucler/CBRAIN-CAM/notebooks/tbeucler_devlog/PKL_DATA'\n\nhf = open(pathPKL+save_name+'_hist.pkl','wb')\n\nF_data = {'hist':hist_rec}\n\npickle.dump(F_data,hf)\nhf.close()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe0588cedae60968a078d6f1db0027c833c62f0
20,525
ipynb
Jupyter Notebook
pgaf/query_test.ipynb
AllenNeuralDynamics/ephys-framework-tests
ee940afeab54e5e25765a903a6b65f2e95be4c48
[ "MIT" ]
null
null
null
pgaf/query_test.ipynb
AllenNeuralDynamics/ephys-framework-tests
ee940afeab54e5e25765a903a6b65f2e95be4c48
[ "MIT" ]
3
2022-01-22T04:34:46.000Z
2022-01-26T02:14:21.000Z
pgaf/query_test.ipynb
AllenNeuralDynamics/ephys-framework-tests
ee940afeab54e5e25765a903a6b65f2e95be4c48
[ "MIT" ]
2
2022-01-21T22:38:27.000Z
2022-01-25T01:30:09.000Z
40.087891
355
0.439708
[ [ [ "import numpy as np\nimport pandas as pd\nimport json", "_____no_output_____" ], [ "from sqlalchemy import create_engine, select, literal_column, text\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy_schemadisplay import create_schema_graph\nfrom sqlalchemy.sql import func, distinct\n", "_____no_output_____" ], [ "from sqla_schema import *", "_____no_output_____" ], [ "with open('SECRETS','r') as f:\n conn_info = json.load(f)\n\nconn_string = f\"postgresql://{conn_info['user']}:{conn_info['password']}@{conn_info['host']}:5432/{conn_info['dbname']}\"\n\nengine = create_engine(conn_string)\nsession = sessionmaker(engine)()", "_____no_output_____" ], [ "ephys_sessions = session.\\\n query(Session.id,\n SessionType.name.label(\"session_type\"),\n Mouse.sex,\n Mouse.date_of_birth,\n Genotype.name.label(\"full_genotype\"),\n func.string_agg(distinct(Structure.abbreviation),literal_column(\"','\")).label(\"all_structures\")).\\\n join(SessionType).\\\n join(Mouse).\\\n join(Genotype).\\\n join(SessionProbe).\\\n join(Channel).\\\n join(Structure).\\\n filter(SessionType.name == \"brain_observatory_1.1\").\\\n filter(Mouse.sex == \"M\").\\\n group_by(Session.id, SessionType.id, Mouse.id, Genotype.id)\n\nprint(ephys_sessions)\n\ndf = pd.read_sql(ephys_sessions.statement, ephys_sessions.session.bind)\ndf", "SELECT session.id AS session_id, session_type.name AS session_type, mouse.sex AS mouse_sex, mouse.date_of_birth AS mouse_date_of_birth, genotype.name AS full_genotype, string_agg(DISTINCT structure.abbreviation, ',') AS all_structures \nFROM session JOIN session_type ON session_type.id = session.session_type_id JOIN mouse ON mouse.id = session.specimen_id JOIN genotype ON genotype.id = mouse.genotype_id JOIN session_probe ON session.id = session_probe.session_id JOIN channel ON session_probe.id = channel.session_probe_id JOIN structure ON structure.id = channel.structure_id \nWHERE session_type.name = %(name_1)s AND mouse.sex = %(sex_1)s GROUP BY session.id, session_type.id, mouse.id, genotype.id\n" ], [ "for r in session.query(UnitSpikeTimes).limit(3):\n st = np.array(r.spike_times)\n print(r.unit_id, st)", "950922146 [ 31.49003496 32.92370245 35.5053706 ... 9578.0161067 9578.03900672\n 9578.12100675]\n950922041 [ 26.97639903 27.05796574 27.11143244 ... 9577.51027313 9577.81670661\n 9577.89237331]\n950922383 [ 26.97859903 27.00989904 27.05436574 ... 9578.11914009 9578.12497342\n 9578.13414009]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
cbe05d7c01262092fedc0affcbd30ddc28bcac7e
59,733
ipynb
Jupyter Notebook
MSc Big Data Science/Data Mining/Assignment03_Anuja_Jyothi_Vijayakumar_190211413.ipynb
anujajyothiv/datascientist-2021
d20d845e5627fb7466a56a2bc819c24547841d58
[ "MIT" ]
null
null
null
MSc Big Data Science/Data Mining/Assignment03_Anuja_Jyothi_Vijayakumar_190211413.ipynb
anujajyothiv/datascientist-2021
d20d845e5627fb7466a56a2bc819c24547841d58
[ "MIT" ]
3
2021-12-17T19:31:50.000Z
2021-12-25T02:54:41.000Z
MSc Big Data Science/Data Mining/Assignment03_Anuja_Jyothi_Vijayakumar_190211413.ipynb
Anuja-Jyothi/github-slideshow
d20d845e5627fb7466a56a2bc819c24547841d58
[ "MIT" ]
null
null
null
50.750212
14,728
0.624613
[ [ [ "# Association Analysis", "_____no_output_____" ] ], [ [ "dataset = [['Milk', 'Onion', 'Nutmeg', 'Kidney Beans', 'Eggs', 'Yogurt'],\n ['Dill', 'Onion', 'Nutmeg', 'Kidney Beans', 'Eggs', 'Yogurt'],\n ['Milk', 'Apple', 'Kidney Beans', 'Eggs'],\n ['Milk', 'Unicorn', 'Corn', 'Kidney Beans', 'Yogurt'],\n ['Corn', 'Onion', 'Onion', 'Kidney Beans', 'Ice cream', 'Eggs']]\nfrom mlxtend.preprocessing import TransactionEncoder \nfrom mlxtend.frequent_patterns import apriori\nimport pandas as pd\n\nte = TransactionEncoder()\nte_ary = te.fit_transform(dataset)\n\ndf = pd.DataFrame(te_ary, columns=te.columns_)\n\nfrequent_itemsets = apriori(df, min_support=0.6, use_colnames=True)\ndisplay(frequent_itemsets)", "_____no_output_____" ], [ "from mlxtend.frequent_patterns import association_rules\nstrong_rules = association_rules(frequent_itemsets, metric=\"confidence\", min_threshold=0.7)\ndisplay(strong_rules)", "_____no_output_____" ] ], [ [ "### 1. What is the advantage of using the Apriori algorithm in comparison with computing the support of every subset of an itemset in order to find the frequent itemsets in a transaction dataset? [0.5 marks out of 5]", "_____no_output_____" ], [ "1. In Apriori Algorithm, the level wise generation of frequent itemsets uses the Apriori property to reduce the search space.\n2. According to the property, \"All nonempty subsets of a frequent itemset must also be frequent\". \n3. So suppose for ['Milk', 'Apple', 'Kidney Beans', 'Eggs'], if any of its subsets is not frequent, this itemset is removed from the frequent itemsets.\n4. Thus Apriori Algorithm eliminates unwanted supersets by checking non frequent subsets. \n5. Also after each join step, candidates that do not have the minimum support(or confidence) threshold are removed. \n6. Thus they are not used further in successive higher level joins of the candidates.\n7. At each level the subsets are filtered out using the minimum support(or confidence) threshold and the supersets are filtered out using the \"Apriori property\". \n8. This considerably reduces the computation and search space.", "_____no_output_____" ], [ "### 2. Let $\\mathcal{L}_1$ denote the set of frequent $1$-itemsets. For $k \\geq 2$, why must every frequent $k$-itemset be a superset of an itemset in $\\mathcal{L}_1$? [0.5 marks out of 5]\n", "_____no_output_____" ], [ "1. $\\mathcal{L}_1$ is a set of frequent $1$-itemsets. This is the lowest level of the itemset where certain (support or confidence) threshold is used to eliminate non frequent itemsets. \n2. Any higher level itemset is formed from this itemset. For example $\\mathcal{L}_2$ will contain only the joinable itemsets of $\\mathcal{L}_1$, $\\mathcal{L}_3$ will contain only the joinable itemsets of $\\mathcal{L}_1$ and $\\mathcal{L}_2$ and so on. \n3. Thus eventually a $k-itemset$ will be a superset of $1-itemsets$ through $(k-1)itemsets$.\n4. Moreover, $\\mathcal{L}_{(k-1)} $ is used to find $\\mathcal{L}_k$ for every $k \\geq 2$ which further implies that every frequent $k$-itemset is a superset of an itemset in $\\mathcal{L}_1$\n", "_____no_output_____" ], [ "### 3. Let $\\mathcal{L}_2 = \\{ \\{1,2\\}, \\{1,5\\}, \\{2, 3\\}, \\{3, 4\\}, \\{3, 5\\}\\}$. Compute the set of candidates $\\mathcal{C}_3$ that is obtained by joining every pair of joinable itemsets from $\\mathcal{L}_2$. [0.5 marks out of 5]", "_____no_output_____" ], [ "1. Each of the itemsets are already sorted and they are of same length. \n2. Therefore join can be performed if the two itemsets that are being joined have same items in the itemset expect for the last item.\n3. Only the following itemset can be joined. \n\n| Joining Itemset: | | $\\mathcal{C}_3$ Itemset | \n|:-||:-|\n|\\{1,2\\} \\{1,5\\}| |{1,2,5} |\n|\\{3,4\\} \\{3,5\\}||{3,4,5} |", "_____no_output_____" ], [ "### 4. Let $S_1$ denote the support of the association rule $\\{ \\text{popcorn, soda} \\} \\Rightarrow \\{ \\text{movie} \\}$. Let $S_2$ denote the support of the association rule $\\{ \\text{popcorn} \\} \\Rightarrow \\{ \\text{movie} \\}$. What is the relationship between $S_1$ and $S_2$? [0.5 marks out of 5]", "_____no_output_____" ], [ "1. $S_1$ denote the support of the association rule $\\{ \\text{popcorn, soda} \\} \\Rightarrow \\{ \\text{movie} \\}$\n2. $S_2$ denote the support of the association rule $\\{ \\text{popcorn} \\} \\Rightarrow \\{ \\text{movie} \\}$\n3. $\\{ \\text{popcorn, soda} \\}$ is a superset of $\\{ \\text{popcorn} \\} $\n4. Support of subset is greater than or equal the support of superset. Therefore $S_2$ $\\geq$ $S_1$ \n\n", "_____no_output_____" ], [ "### 5. What is the support of the rule $\\{ \\} \\Rightarrow \\{ \\text{Kidney Beans} \\}$ in the transaction dataset used in the tutorial presented above? [0.5 marks out of 5]\n", "_____no_output_____" ] ], [ [ "frequent_itemsets = apriori(df, min_support=0.6, use_colnames=True)\ndisplay(frequent_itemsets[frequent_itemsets['itemsets'] == frozenset({'Kidney Beans'})])", "_____no_output_____" ] ], [ [ "1. As per the dataset provided, {Kidney Beans} occurs 5 times in the dataset of 5 transactions. \n2. Support = transactions_where_item(s)_occur / total_transactions = 5/5 = 1\n3. The same is confirmed by the code above wherein using the apriori function, the frequent_itemsets are gathered based on the min_support of 0.6.\n4. Then the itemset \"Kidney Beans\" is displayed. It shows the same support of 1.0", "_____no_output_____" ], [ "### 6. In the transaction dataset used in the tutorial presented above, what is the maximum length of a frequent itemset for a support threshold of 0.2? [0.5 marks out of 5]", "_____no_output_____" ] ], [ [ "frequent_itemsets = apriori(df, min_support=0.2, use_colnames=True)\nfrequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x)) # length of each frozenset\nbiggest = frequent_itemsets['length'].max() \ndisplay(frequent_itemsets[frequent_itemsets['length']== biggest])", "_____no_output_____" ] ], [ [ "1. The frequent itemsets having the support threshold of 0.2 are gathered using the function apriori by setting min_support=0.2 and stored in the dataframe frequent_itemsets\n2. The \"length\" column is added to the frequent_itemset dataframe.\n3. Using lambda, the length of each 'itemsets' is gathered and stored in the length column of the dataframe.\n4. The max function is used to get the maximum length and stored in the variable \"biggest\".\n5. Finally the frequent_itemsets having the \"biggest\" length is displayed by checking the length of each \"frequent_itemsets['length'] == biggest\"\n6. The maximum length of a frequent itemset for a support threshold of 02 is 6 and two itemsets have been identified to have that length. ", "_____no_output_____" ], [ "### 7. Implement a function that receives a ``DataFrame`` of frequent itemsets and a **strong** association rule (represented by a ``frozenset`` of antecedents and a ``frozenset`` of consequents). This function should return the corresponding Kulczynski measure. Include the code in your report. [1 mark out of 5]\n", "_____no_output_____" ] ], [ [ "def KulczynskiMeasure(frequentItemset, antecedent, consequent):\n actualItemset = frozenset().union(antecedent, consequent)\n supportofA = frequentItemset[frequentItemset['itemsets'] == antecedent]['support'].iloc[0]\n supportofB = frequentItemset[frequentItemset['itemsets'] == consequent]['support'].iloc[0]\n supportofAUB = frequentItemset[frequentItemset['itemsets'] == actualItemset]['support'].iloc[0]\n vAtoB = supportofAUB/supportofA\n vBtoA = supportofAUB/supportofB\n return (vAtoB+vBtoA)/2 ", "_____no_output_____" ], [ "print(\"Kulczynski Measure of Strong Rule having two way assocation for\", \n frozenset({'Eggs'}), \"and\", \n frozenset({'Kidney Beans'}), \"is\",\n KulczynskiMeasure(frequent_itemsets, frozenset({'Eggs'}), frozenset({'Kidney Beans'}))) ", "Kulczynski Measure of Strong Rule having two way assocation for frozenset({'Eggs'}) and frozenset({'Kidney Beans'}) is 0.9\n" ] ], [ [ "1. The function KulczynskiMeasure created with three input parameters. \n2. The parameters include the following: \n frequentItemset -> It is a dataframe of frequent itemsets that are identified using the apriori function, setting a minimum support threshold. \n -> The dataframe also contains the support of each frequent itemset\n antecedent -> It is a frozenset of antecedent\n consequent -> It is a frozenset of consequent\n3. It is assumed that antecedent and the consequent passed to this function is a strong association rule. ie.; A => B and B => A exist.\n4. Using the union function a new set of combined antecedent and consequent is created to gather supportAUB\n5. If the antecedent is present in the frequentItemset, the corresponding support is stored in supportofA\n6. If the consequent is present in the frequentItemset, the corresponding support is stored in supportofB\n7. If the union(antecedent, consequent) frozenset is present in the frequentItemset, the corresponding support is stored in supportofAUB\n8. The confidence of A => B is calculated by dividing the support of AUB by Support of A\n9. The confidence of B => A is calculated by dividing the support of AUB by Support of B\n10. The Kulczynski Measure is the average of confidence of A => B and confidence of B => A given by the following formula and same is used in the code \n$K_{A,B}$ = $\\frac{V_{{A}\\Rightarrow {B}} + V_{{B}\\Rightarrow {A}}}{2}$\n11. the function is called in the print statement and output is displayed below the code ", "_____no_output_____" ], [ "### 8. Implement a function that receives a ``DataFrame`` of frequent itemsets and a **strong** association rule (represented by a ``frozenset`` of antecedents and a ``frozenset`` of consequents). This function should return the corresponding imbalance ratio. Include the code in your report. [1 mark out of 5]\n", "_____no_output_____" ] ], [ [ "def ImbalanceRatio(frequentItemset, antecedent, consequent):\n actualItemset = frozenset().union(antecedent, consequent)\n supportofA = frequentItemset[frequentItemset['itemsets'] == antecedent]['support'].iloc[0]\n supportofB = frequentItemset[frequentItemset['itemsets'] == consequent]['support'].iloc[0]\n supportofAUB = frequentItemset[frequentItemset['itemsets'] == actualItemset]['support'].iloc[0]\n return abs(supportofA-supportofB)/(supportofA+supportofB-supportofAUB)", "_____no_output_____" ], [ "print(\"Imbalance Ratio of Strong Rule having two way assocation for\", \n frozenset({'Eggs'}), \"and\", \n frozenset({'Kidney Beans'}), \"is\",\n ImbalanceRatio(frequent_itemsets, frozenset({'Eggs'}), frozenset({'Kidney Beans'}))) ", "Imbalance Ratio of Strong Rule having two way assocation for frozenset({'Eggs'}) and frozenset({'Kidney Beans'}) is 0.19999999999999996\n" ] ], [ [ "1. The function KulczynskiMeasure created with three input parameters. \n2. The parameters include the following: \n frequentItemset -> It is a dataframe of frequent itemsets that are identified using the apriori function, setting a minimum support threshold. \n -> The dataframe also contains the support of each frequent itemset\n antecedent -> It is a frozenset of antecedent\n consequent -> It is a frozenset of consequent\n3. It is assumed that antecedent and the consequent passed to this function is a strong association rule. ie.; A => B and B => A exist.\n4. Using the union function a new set of combined antecedent and consequent is created to gather supportAUB\n5. If the antecedent is present in the frequentItemset, the corresponding support is stored in supportofA\n6. If the consequent is present in the frequentItemset, the corresponding support is stored in supportofB\n7. If the union(antecedent, consequent) frozenset is present in the frequentItemset, the corresponding support is stored in supportofAUB\n8. The Imbalance ratio is given by the following formula and the same is implemented using support values.\n$I_{A,B}$ = $\\frac{|N_{A} - N_{B}|} {N_{A} + N_{B} - N_{AUB}}$\n9. the function is called in the print statement and output is displayed below the code ", "_____no_output_____" ], [ "# Outlier Detection", "_____no_output_____" ], [ "## 1. For an application on credit card fraud detection, we are interested in detecting contextual outliers. Suggest 2 possible contextual attributes and 2 possible behavioural attributes that could be used for this application, and explain why each of your suggested attribute should be considered as either contextual or behavioural. [0.5 marks out of 5]", "_____no_output_____" ], [ "Contextual Attribute: Income Level, Bank Balance, Age, Gender, Transaction Mode\nBehavioural Attribute: Expenditure Patterns, Credit Limit", "_____no_output_____" ], [ "## 2. Assume that you are provided with the [University of Wisconsin breast cancer dataset](https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data) from the Week 3 lab, and that you are asked to detect outliers from this dataset. Additional information on the dataset attributes can be found [online](https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.names). Explain one possible outlier detection method that you could apply for detecting outliers for this particular dataset, explain what is defined as an outlier for your suggested approach given this particular dataset, and justify why would you choose this particular method for outlier detection. [1 mark out of 5]\n\n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\ndata = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data', header=None)\ndata.columns = ['Sample code', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape',\n 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin',\n 'Normal Nucleoli', 'Mitoses','Class']\ndata = data.drop(['Sample code'],axis=1)\ndata = data.replace('?',np.NaN)\ndata2 = data['Bare Nuclei']\ndata2 = data2.fillna(data2.median())\ndata2 = data.dropna() \ndata2 = data.drop(['Class'],axis=1)\ndata2['Bare Nuclei'] = pd.to_numeric(data2['Bare Nuclei'])\ndata2.boxplot(figsize=(20,3))", "_____no_output_____" ] ], [ [ "## 3. The monthly rainfall in the London borough of Tower Hamlets in 2018 had the following amount of precipitation (measured in mm, values from January-December 2018): {22.93, 20.59, 25.65, 23.74, 25.24, 4.55, 23.45, 28.18, 23.52, 22.32, 26.73, 23.42}. Assuming that the data is based on a normal distribution, identify outlier values in the above dataset using the maximum likelihood method. [1 mark out of 5]\n\n", "_____no_output_____" ] ], [ [ "df=pd.DataFrame(np.array([22.93, 20.59, 25.65, 23.74, 25.24, 4.55, 23.45, 28.18, 23.52, 22.32, 26.73, 23.42]),columns=['data'])\n\nimport numpy as np\nmean = np.array(np.mean(df))\nstandard_deviation = np.array(np.std(df))\nmle = df.values-c\n\nh=mle[5]\ndisplay(h)\n\nj=h/b\n\ndisplay(j)", "_____no_output_____" ] ], [ [ "$ Precipitation = {22.93, 20.59, 25.65, 23.74, 25.24, 4.55, 23.45, 28.18, 23.52, 22.32, 26.73, 23.42} $\n\n$Mean, \\mu = \\frac {22.93 + 20.59 + 25.65 + 23.74 + 25.24 + 4.55 + 23.45 + 28.18 + 23.52 + 22.32 + 26.73 + 23.42}{12}$\n\n> $Mean, \\mu = 22.53$\n\n$Standard Deviation,\\sigma = \\sqrt {\\frac {(22.93-22.53)^2 + (20.59-22.53)^2 + (25.65-22.53)^2 + (23.74-22.53)^2 + (25.24-22.53)^2 + (4.55-22.53)^2 + (23.45-22.53)^2 + (28.18-22.53)^2 + (23.52-22.53)^2 + (22.32-22.53)^2 + (26.73-22.53)^2 + (23.42-22.53)^2}{12}}$\n\n$Standard Deviation, \\sigma = \\sqrt {\\frac {0.16 + 3.76 + 9.73 + 1.46 + 7.34 + 323.28 + 0.85 + 31.92 + 0.98 + 0.04 + 17.64 + 0.79}{12}}$\n\n$Standard Deviation, \\sigma = \\sqrt {\\frac {397.95}{12}}$\n\n$Standard Deviation, \\sigma = \\sqrt {{33.16}}$\n\n> $Standard Deviation, \\sigma = 5.76$\n\n\nFinding Most Deviating Value:\n\n|data point - mean ||gives|\n|:-||:-|\n|22.93 - 22.53||0.4|\n|20.59 - 22.53||-1.94|\n|25.65 - 22.53||3.12|\n|23.74 - 22.53||1.21|\n|25.24 - 22.53||2.71|\n|4.55 - 22.53||-17.98|\n|23.45 - 22.53||0.92|\n|28.18 - 22.53||5.65|\n|23.52 - 22.53||0.99|\n|22.32 - 22.53||-0.21|\n|26.73 - 22.53||4.2|\n|23.42 - 22.53||0.89|\n\nThe most deviating value is -17.98 which implies 4.55 as the outlier\n\nIn a normal distribution, $\\mu$ $3\\sigma$", "_____no_output_____" ], [ "## 4. You are provided with the graduation rate dataset used in the Week 4 lab (file graduation_rate.csv in the Week 4 lab supplementary data). For the 'high school gpa' attribute, compute the relative frequency (i.e. frequency normalised by the size of the dataset) of each value. Show these computed relative frequencies in your report. Two new data points are included in the dataset, one with a 'high school gpa' value of 3.6, and one with a 'high school gpa' value of 2.8. Using the above computed relative frequencies, which of the two new data points would you consider as an outlier and why? [0.5 marks out of 5]\n\n", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ndf = pd.read_csv('graduation_rate.csv')\n\nprint('Dataset (head and tail):')\ndisplay(df)", "_____no_output_____" ], [ "print(\"high school gpa:\")\nfreq_education = df['high school gpa'].value_counts()/len(df)\ndisplay(freq_education)\ng= pd.DataFrame(freq_education)\ndisplay(g)", "_____no_output_____" ], [ "import numpy as np\ndef removeOutliers(x, outlierConstant):\n a= np.array(x)\n upper_quartile = np.percentile(a,75)\n print(upper_quartile)\n lower_quartile = np.percentile(a,25)\n print(lower_quartile)\n IQR = (upper_quartile - lower_quartile) * outlierConstant\n print(IQR)\n quartileSet = (lower_quartile - IQR, upper_quartile + IQR)\n resultList = []\n for y in a.tolist():\n if y >= quartileSet[0] and y <=quartileSet[1]:\n resultList.append(y)\n return resultList\nremoveOutliers(g,4)", "_____no_output_____" ] ], [ [ "## 5. Using the stock prices dataset used in sections 1 and 2, estimate the outliers in the dataset using the one-class SVM classifier approach. As input to the classifier, use the percentage of changes in the daily closing price of each stock, as was done in section 1 of the notebook. Plot a 3D scatterplot of the dataset, where each object is color-coded according to whether it is an outlier or an inlier. Also compute a histogram and the frequencies of the estimated outlier and inlier labels. In terms of the plotted results, how does the one-class SVM approach for outlier detection differ from the parametric and proximity-based methods used in the lab notebook? What percentage of the dataset objects are classified as outliers? [1 mark out of 5]\n\n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nfrom sklearn.svm import OneClassSVM\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n#stores classifier in a variable\nocs= OneClassSVM\n\n#Load CSV file, set the 'Date' values as the index of each row\n#display the first rows of the dataframe\nstocks = pd.read_csv('stocks.csv', header='infer') \nstocks.index = stocks['Date']\nstocks = stocks.drop(['Date'],axis=1)\nstocks.head()", "_____no_output_____" ], [ "N,d = stocks.shape\n#Compute delta\n#this denotes the percentage of changes in daily closing price of each stock\ndelta = pd.DataFrame(100*np.divide(stocks.iloc[1:,:].values-stocks.iloc[:N-1,:]\n .values, stocks.iloc[:N-1,:].values),columns=stocks.columns, \n index=stocks.iloc[1:].index)\ndelta", "_____no_output_____" ], [ "# Extracting the values from the dataframe\ndata = delta.values\n\n# Split dataset into input and output elements\nX, y = data[:, :-1], data[:, -1]\n\n# Summarize the shape of the dataset\nprint(X.shape, y.shape)", "_____no_output_____" ], [ "clf = ocs(nu=0.01,gamma='auto')\n# Perform fit on input data and returns labels for that input data.\nsvm = clf.fit_predict(delta) \n#stores the finded value in the list\nb= list(svm)\n# Print labels: -1 for outliers and 1 for inliers.\nprint(b)", "_____no_output_____" ], [ "# Plot 3D scatterplot of outlier scores\nfig = plt.figure(figsize=(10,6))\nax = fig.add_subplot(111, projection='3d')\np = ax.scatter(delta.MSFT,delta.F,delta.BAC,c=b,cmap='jet')\nax.set_xlabel('Microsoft')\nax.set_ylabel('Ford')\nax.set_zlabel('Bank of America')\nfig.colorbar(p)\nplt.show()", "_____no_output_____" ], [ "#to find the percentage of outliers and inliers\ndf= pd.Series(b).value_counts()\nprint(df)", "_____no_output_____" ], [ "Fi=(df/len(b))\nFi", "_____no_output_____" ], [ "#plot histogram for outliers and inliers\nsns.set_style('darkgrid')\nsns.distplot(b)", "_____no_output_____" ] ], [ [ "### 6. This question will combine concepts from both data preprocessing and outlier detection. Using the house prices dataset from Section 3 of this lab notebook, perform dimensionality reduction on the dataset using PCA with 2 principal components (make sure that the dataset is z-score normalised beforehand, and remember that PCA should only be applied on the input attributes). Then, perform outlier detection on the pre-processed dataset using the k-nearest neighbours approach using k=2. Display a scatterplot of the two principal components, where each object is colour-coded according to the computed outlier score. [1 marks out of 5]", "_____no_output_____" ] ], [ [ "import pandas as pd\nfrom pandas import read_csv\nfrom scipy.stats import zscore\nfrom sklearn.decomposition import PCA\nfrom sklearn.neighbors import NearestNeighbors\nimport numpy as np\nfrom scipy.spatial import distance\nfrom numpy import sqrt\nfrom numpy import hstack\nimport matplotlib.pyplot as plt\n\n#Loading the dataset\nurl = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/housing.csv'\ndf = read_csv(url, header=None)\n\n#Extracting the values from the dataframe\ndata = df.values\n\n#Split dataset into input and output elements\nX, y = data[:, :-1], data[:, -1]\n\n#Summarize the shape of the dataset\nprint(X.shape, y.shape)\n\n#z score normalization is done\nX_normalized = zscore(X)\n\n#Principal component analysis is done for 2 components\npca = PCA(n_components=2)\n\n#pca is fit transformed of X_normalized data(array)\nprincipalComponents = pca.fit_transform(X_normalized)\n\nknn = 2\nnbrs = NearestNeighbors(n_neighbors=knn, \n metric=distance.euclidean).fit(principalComponents)\ncenters = nbrs.kneighbors(principalComponents)\n\nprint(\"Centers:\\n\",centers)\n\n#calculating distance of each sample from the center\n#calculating for distancecenter1\ndistancecenter1 = sqrt(((principalComponents-centers[0])**2).sum(axis=1))\n#calculating for distancecenter2\ndistancecenter2 = sqrt(((principalComponents-centers[1])**2).sum(axis=1))\n#combining both the arrays and finding minimum value for each row in dataset\ndistance = hstack((distancecenter1.reshape(-1,1),distancecenter2.reshape(-1,1))).min(axis=1)\n\n#scatter plot with color as distance values from centres\nplt.scatter(principalComponents[:,0],principalComponents[:,1],c=distance, cmap='nipy_spectral')\n#colorbar is added\nplt.colorbar()\n#labeling of plot\nplt.xlabel(\"Principal_Components 1\")\nplt.ylabel(\"Principal_Components 2\")\nplt.title(\"outlier score\")\n#displaying the plot\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cbe06b24f279dbd080db4cd7d00672422f1148b9
8,532
ipynb
Jupyter Notebook
session/similarity/augmenting.ipynb
leowmjw/Malaya
33f39835eca08c238d2dd68aeca3b09c5d0a45ab
[ "MIT" ]
31
2019-05-02T20:47:35.000Z
2021-11-01T06:05:55.000Z
session/similarity/augmenting.ipynb
leowmjw/Malaya
33f39835eca08c238d2dd68aeca3b09c5d0a45ab
[ "MIT" ]
2
2019-05-30T22:10:40.000Z
2020-02-17T08:07:20.000Z
session/similarity/augmenting.ipynb
leowmjw/Malaya
33f39835eca08c238d2dd68aeca3b09c5d0a45ab
[ "MIT" ]
15
2019-05-02T10:30:34.000Z
2022-03-04T08:21:14.000Z
23.184783
110
0.482419
[ [ [ "import json\nimport glob\nimport re\nimport malaya", "_____no_output_____" ], [ "tokenizer = malaya.preprocessing._SocialTokenizer().tokenize\n\ndef is_number_regex(s):\n if re.match(\"^\\d+?\\.\\d+?$\", s) is None:\n return s.isdigit()\n return True\n\ndef detect_money(word):\n if word[:2] == 'rm' and is_number_regex(word[2:]):\n return True\n else:\n return False\n\ndef preprocessing(string):\n tokenized = tokenizer(string)\n tokenized = [w.lower() for w in tokenized if len(w) > 2]\n tokenized = ['<NUM>' if is_number_regex(w) else w for w in tokenized]\n tokenized = ['<MONEY>' if detect_money(w) else w for w in tokenized]\n return tokenized", "_____no_output_____" ], [ "left, right, label = [], [], []\nfor file in glob.glob('quora/*.json'):\n with open(file) as fopen:\n x = json.load(fopen)\n for i in x:\n splitted = i[0].split(' <> ')\n if len(splitted) != 2:\n continue\n left.append(splitted[0])\n right.append(splitted[1])\n label.append(i[1])", "_____no_output_____" ], [ "len(left), len(right), len(label)", "_____no_output_____" ], [ "with open('synonym0.json') as fopen:\n s = json.load(fopen)\n \nwith open('synonym1.json') as fopen:\n s1 = json.load(fopen)", "_____no_output_____" ], [ "synonyms = {}\nfor l, r in (s + s1):\n if l not in synonyms:\n synonyms[l] = r + [l]\n else:\n synonyms[l].extend(r)\nsynonyms = {k: list(set(v)) for k, v in synonyms.items()}", "_____no_output_____" ], [ "import random\n\ndef augmentation(s, maximum = 0.8):\n s = s.lower().split()\n for i in range(int(len(s) * maximum)):\n index = random.randint(0, len(s) - 1)\n word = s[index]\n sy = synonyms.get(word, [word])\n sy = random.choice(sy)\n s[index] = sy\n return s", "_____no_output_____" ], [ "train_left, test_left = left[:-50000], left[-50000:]\ntrain_right, test_right = right[:-50000], right[-50000:]\ntrain_label, test_label = label[:-50000], label[-50000:]", "_____no_output_____" ], [ "len(train_left), len(test_left)", "_____no_output_____" ], [ "aug = [' '.join(augmentation(train_left[0])) for _ in range(10)] + [train_left[0].lower()]\naug = list(set(aug))\naug", "_____no_output_____" ], [ "aug = [' '.join(augmentation(train_right[0])) for _ in range(10)] + [train_right[0].lower()]\naug = list(set(aug))\naug", "_____no_output_____" ], [ "train_label[0]", "_____no_output_____" ], [ "from tqdm import tqdm\n\nLEFT, RIGHT, LABEL = [], [], []\nfor i in tqdm(range(len(train_left))):\n aug_left = [' '.join(augmentation(train_left[i])) for _ in range(3)] + [train_left[i].lower()]\n aug_left = list(set(aug_left))\n \n aug_right = [' '.join(augmentation(train_right[i])) for _ in range(3)] + [train_right[i].lower()]\n aug_right = list(set(aug_right))\n \n for l in aug_left:\n for r in aug_right:\n LEFT.append(l)\n RIGHT.append(r)\n LABEL.append(train_label[i])", "100%|██████████| 353831/353831 [00:46<00:00, 7536.26it/s]\n" ], [ "len(LEFT), len(RIGHT), len(LABEL)", "_____no_output_____" ], [ "for i in tqdm(range(len(LEFT))):\n LEFT[i] = preprocessing(LEFT[i])\n RIGHT[i] = preprocessing(RIGHT[i])", "100%|██████████| 4136391/4136391 [10:34<00:00, 6523.13it/s]\n" ], [ "for i in tqdm(range(len(test_left))):\n test_left[i] = preprocessing(test_left[i])\n test_right[i] = preprocessing(test_right[i])", "100%|██████████| 50000/50000 [00:06<00:00, 7268.75it/s]\n" ], [ "with open('train-similarity.json', 'w') as fopen:\n json.dump({'left': LEFT, 'right': RIGHT, 'label': LABEL}, fopen)", "_____no_output_____" ], [ "with open('test-similarity.json', 'w') as fopen:\n json.dump({'left': test_left, 'right': test_right, 'label': test_label}, fopen)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe06efe8991869fb3574d2e9c704f827d52ceb7
367,105
ipynb
Jupyter Notebook
notebooks/01_choose_variables.ipynb
PiotrekGa/tww_stats
ab00b3096648d925133bd5841d5977b33a18e0d4
[ "MIT" ]
null
null
null
notebooks/01_choose_variables.ipynb
PiotrekGa/tww_stats
ab00b3096648d925133bd5841d5977b33a18e0d4
[ "MIT" ]
null
null
null
notebooks/01_choose_variables.ipynb
PiotrekGa/tww_stats
ab00b3096648d925133bd5841d5977b33a18e0d4
[ "MIT" ]
null
null
null
57.784511
28,764
0.533283
[ [ [ "import pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.model_selection import KFold\nfrom sklearn.pipeline import make_union, make_pipeline\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.base import TransformerMixin\nfrom sklearn.model_selection import cross_val_score\n\nfrom lightgbm import LGBMRegressor\nimport optuna\n\nfrom twws.select_variables import Selector, get_units_only\nfrom twws.variables_list import category_columns, non_object_columns\n\npd.set_option('display.max_rows', None)", "_____no_output_____" ], [ "df = pd.read_csv('../data/data.csv')", "/Users/piotr.gabrys/.local/share/virtualenvs/tww_stats-PBBeHRjs/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3145: DtypeWarning: Columns (617) have mixed types.Specify dtype option on import or set low_memory=False.\n has_raised = await self.run_ast_nodes(code_ast.body, cell_name,\n" ], [ "df = get_units_only(df)", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df.missile_primary__ignition_amount = df.missile_primary__ignition_amount.map({'True': 1, '0': 0, '25': 25})", "_____no_output_____" ], [ "for col in non_object_columns:\n df[col] = df[col] * 1\n df[col] = df[col].fillna(-1)", "_____no_output_____" ], [ "for col in category_columns:\n df[col] = df[col].fillna('missing')", "_____no_output_____" ], [ "df = df.loc[:, non_object_columns + category_columns + ['name']]", "_____no_output_____" ], [ "df = df.sample(frac=1)", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "y = df.multiplayer_cost.apply(np.log)\nx = df.drop('multiplayer_cost', axis=1)", "_____no_output_____" ], [ "columns_to_remove = ['multiplayer_cost', \n 'speed',\n 'charge_speed', \n 'missile_primary__total_accuracy',\n 'knock_interrupts_ignore_chance',\n 'missile_primary__reload_time',\n 'missile_primary__ammo',\n 'deceleration',\n 'unit_size',\n 'melee__ap_damage']", "_____no_output_____" ], [ "for col in columns_to_remove:\n non_object_columns.remove(col)", "_____no_output_____" ], [ "features = [\"melee_defence\",\n\"health\",\n\"melee_attack\",\n\"leadership\",\n\"armour\",\n\"health_per_entity\",\n\"run_speed\",\n\"missile_primary__damage\",\n\"charge_bonus\",\n\"melee__ap_ratio\",\n\"melee__base_damage\",\n\"mass\",\n\"melee__damage\",\n\"height\",\n\"melee__melee_attack_interval\",\n\"acceleration\",\n\"melee__bonus_v_large\",\n\"melee__bonus_v_infantry\",\n\"melee__splash_attack_max_attacks\",\n\"parry_chance\",\n\"reload\",\n\"hit_reactions_ignore_chance\",\n\"melee__weapon_length\",\n\"damage_mod_physical\",\n\"accuracy\",\n\"combat_reaction_radius\",\n\"fly_speed\",\n\"melee__splash_attack_power_multiplier\"]\n\nmodel = make_pipeline(\n Selector(features),\n LGBMRegressor(objective='mae')\n)", "_____no_output_____" ], [ "def objective(trial): \n \n lgbmregressor__num_leaves = trial.suggest_int('lgbmregressor__num_leaves', 2, 500) \n lgbmregressor__max_depth = trial.suggest_int('lgbmregressor__max_depth', 2, 150) \n lgbmregressor__n_estimators = trial.suggest_int('lgbmregressor__n_estimators', 10, 500) \n lgbmregressor__subsample_for_bin = trial.suggest_int('lgbmregressor__subsample_for_bin', 2000, 500_000) \n lgbmregressor__min_child_samples = trial.suggest_int('lgbmregressor__min_child_samples', 4, 500) \n lgbmregressor__reg_alpha = trial.suggest_uniform('lgbmregressor__reg_alpha', 0.0, 1.0) \n lgbmregressor__colsample_bytree = trial.suggest_uniform('lgbmregressor__colsample_bytree', 0.6, 1.0) \n lgbmregressor__learning_rate = trial.suggest_loguniform('lgbmregressor__learning_rate', 1e-5, 1e-0) \n \n\n params = {\n 'lgbmregressor__num_leaves': lgbmregressor__num_leaves,\n 'lgbmregressor__max_depth': lgbmregressor__max_depth,\n 'lgbmregressor__n_estimators': lgbmregressor__n_estimators,\n 'lgbmregressor__subsample_for_bin': lgbmregressor__subsample_for_bin,\n 'lgbmregressor__min_child_samples': lgbmregressor__min_child_samples,\n 'lgbmregressor__reg_alpha': lgbmregressor__reg_alpha,\n 'lgbmregressor__colsample_bytree': lgbmregressor__colsample_bytree,\n 'lgbmregressor__learning_rate': lgbmregressor__learning_rate\n }\n \n model.set_params(**params)\n \n cv = KFold(n_splits=8)\n\n return - np.mean(cross_val_score(model, x, y, cv=8, scoring='neg_median_absolute_error'))", "_____no_output_____" ], [ "study = optuna.create_study()\nstudy.optimize(objective, n_trials=200)", "[I 2020-08-31 22:20:02,350] Trial 0 finished with value: 0.14737546944923458 and parameters: {'lgbmregressor__num_leaves': 348, 'lgbmregressor__max_depth': 126, 'lgbmregressor__n_estimators': 170, 'lgbmregressor__subsample_for_bin': 423284, 'lgbmregressor__min_child_samples': 14, 'lgbmregressor__reg_alpha': 0.31969613171562405, 'lgbmregressor__colsample_bytree': 0.712877649769243, 'lgbmregressor__learning_rate': 0.8253331720972363}. Best is trial 0 with value: 0.14737546944923458.\n[I 2020-08-31 22:20:02,486] Trial 1 finished with value: 0.3839822719476453 and parameters: {'lgbmregressor__num_leaves': 475, 'lgbmregressor__max_depth': 96, 'lgbmregressor__n_estimators': 453, 'lgbmregressor__subsample_for_bin': 268797, 'lgbmregressor__min_child_samples': 313, 'lgbmregressor__reg_alpha': 0.5768276503094326, 'lgbmregressor__colsample_bytree': 0.9675717653060747, 'lgbmregressor__learning_rate': 3.484436665751464e-05}. Best is trial 0 with value: 0.14737546944923458.\n[I 2020-08-31 22:20:02,663] Trial 2 finished with value: 0.3839822719476453 and parameters: {'lgbmregressor__num_leaves': 467, 'lgbmregressor__max_depth': 133, 'lgbmregressor__n_estimators': 412, 'lgbmregressor__subsample_for_bin': 190570, 'lgbmregressor__min_child_samples': 322, 'lgbmregressor__reg_alpha': 0.9629750928647622, 'lgbmregressor__colsample_bytree': 0.8642588954136708, 'lgbmregressor__learning_rate': 0.5994935449378537}. Best is trial 0 with value: 0.14737546944923458.\n[I 2020-08-31 22:20:02,832] Trial 3 finished with value: 0.34717600833486206 and parameters: {'lgbmregressor__num_leaves': 108, 'lgbmregressor__max_depth': 99, 'lgbmregressor__n_estimators': 102, 'lgbmregressor__subsample_for_bin': 95176, 'lgbmregressor__min_child_samples': 93, 'lgbmregressor__reg_alpha': 0.27710065689506425, 'lgbmregressor__colsample_bytree': 0.8814757476772961, 'lgbmregressor__learning_rate': 0.0017407612447589034}. Best is trial 0 with value: 0.14737546944923458.\n[I 2020-08-31 22:20:02,959] Trial 4 finished with value: 0.3839822719476453 and parameters: {'lgbmregressor__num_leaves': 223, 'lgbmregressor__max_depth': 82, 'lgbmregressor__n_estimators': 360, 'lgbmregressor__subsample_for_bin': 242618, 'lgbmregressor__min_child_samples': 332, 'lgbmregressor__reg_alpha': 0.8897608952336782, 'lgbmregressor__colsample_bytree': 0.8553947762091625, 'lgbmregressor__learning_rate': 0.0020442558957870557}. Best is trial 0 with value: 0.14737546944923458.\n[I 2020-08-31 22:20:03,080] Trial 5 finished with value: 0.3839822719476453 and parameters: {'lgbmregressor__num_leaves': 370, 'lgbmregressor__max_depth': 127, 'lgbmregressor__n_estimators': 334, 'lgbmregressor__subsample_for_bin': 51660, 'lgbmregressor__min_child_samples': 394, 'lgbmregressor__reg_alpha': 0.5281695661057111, 'lgbmregressor__colsample_bytree': 0.6756653444281262, 'lgbmregressor__learning_rate': 0.34920827495721857}. Best is trial 0 with value: 0.14737546944923458.\n[I 2020-08-31 22:20:03,486] Trial 6 finished with value: 0.12364565243822284 and parameters: {'lgbmregressor__num_leaves': 239, 'lgbmregressor__max_depth': 56, 'lgbmregressor__n_estimators': 382, 'lgbmregressor__subsample_for_bin': 69165, 'lgbmregressor__min_child_samples': 80, 'lgbmregressor__reg_alpha': 0.8661144335257731, 'lgbmregressor__colsample_bytree': 0.8762786969597527, 'lgbmregressor__learning_rate': 0.16795552297943322}. Best is trial 6 with value: 0.12364565243822284.\n[I 2020-08-31 22:20:03,782] Trial 7 finished with value: 0.3828606951072776 and parameters: {'lgbmregressor__num_leaves': 358, 'lgbmregressor__max_depth': 17, 'lgbmregressor__n_estimators': 385, 'lgbmregressor__subsample_for_bin': 495990, 'lgbmregressor__min_child_samples': 140, 'lgbmregressor__reg_alpha': 0.3279242769369586, 'lgbmregressor__colsample_bytree': 0.8469268633330606, 'lgbmregressor__learning_rate': 2.070869807401965e-05}. Best is trial 6 with value: 0.12364565243822284.\n[I 2020-08-31 22:20:03,955] Trial 8 finished with value: 0.38347914403549405 and parameters: {'lgbmregressor__num_leaves': 182, 'lgbmregressor__max_depth': 4, 'lgbmregressor__n_estimators': 180, 'lgbmregressor__subsample_for_bin': 17896, 'lgbmregressor__min_child_samples': 143, 'lgbmregressor__reg_alpha': 0.21630995964805855, 'lgbmregressor__colsample_bytree': 0.6019427011367043, 'lgbmregressor__learning_rate': 2.3791763139968034e-05}. Best is trial 6 with value: 0.12364565243822284.\n[I 2020-08-31 22:20:04,059] Trial 9 finished with value: 0.3839822719476453 and parameters: {'lgbmregressor__num_leaves': 144, 'lgbmregressor__max_depth': 16, 'lgbmregressor__n_estimators': 206, 'lgbmregressor__subsample_for_bin': 311954, 'lgbmregressor__min_child_samples': 301, 'lgbmregressor__reg_alpha': 0.6795661318977944, 'lgbmregressor__colsample_bytree': 0.8951917712203876, 'lgbmregressor__learning_rate': 0.07016677190189935}. Best is trial 6 with value: 0.12364565243822284.\n[I 2020-08-31 22:20:04,780] Trial 10 finished with value: 0.11093896318438906 and parameters: {'lgbmregressor__num_leaves': 16, 'lgbmregressor__max_depth': 51, 'lgbmregressor__n_estimators': 275, 'lgbmregressor__subsample_for_bin': 127791, 'lgbmregressor__min_child_samples': 4, 'lgbmregressor__reg_alpha': 0.7814853586911557, 'lgbmregressor__colsample_bytree': 0.9891105929063413, 'lgbmregressor__learning_rate': 0.021704615803482995}. Best is trial 10 with value: 0.11093896318438906.\n[I 2020-08-31 22:20:05,063] Trial 11 finished with value: 0.1359771402722577 and parameters: {'lgbmregressor__num_leaves': 3, 'lgbmregressor__max_depth': 53, 'lgbmregressor__n_estimators': 295, 'lgbmregressor__subsample_for_bin': 134771, 'lgbmregressor__min_child_samples': 4, 'lgbmregressor__reg_alpha': 0.7912136068069182, 'lgbmregressor__colsample_bytree': 0.9943798059989396, 'lgbmregressor__learning_rate': 0.029704649632590594}. Best is trial 10 with value: 0.11093896318438906.\n[I 2020-08-31 22:20:05,361] Trial 12 finished with value: 0.14166476064051187 and parameters: {'lgbmregressor__num_leaves': 8, 'lgbmregressor__max_depth': 44, 'lgbmregressor__n_estimators': 257, 'lgbmregressor__subsample_for_bin': 149109, 'lgbmregressor__min_child_samples': 68, 'lgbmregressor__reg_alpha': 0.997416567324262, 'lgbmregressor__colsample_bytree': 0.9539483447350176, 'lgbmregressor__learning_rate': 0.0170451319773027}. Best is trial 10 with value: 0.11093896318438906.\n[I 2020-08-31 22:20:05,666] Trial 13 finished with value: 0.36095670609100783 and parameters: {'lgbmregressor__num_leaves': 73, 'lgbmregressor__max_depth': 53, 'lgbmregressor__n_estimators': 466, 'lgbmregressor__subsample_for_bin': 31909, 'lgbmregressor__min_child_samples': 230, 'lgbmregressor__reg_alpha': 0.7771743328058751, 'lgbmregressor__colsample_bytree': 0.7510697519539137, 'lgbmregressor__learning_rate': 0.00027967694428802616}. Best is trial 10 with value: 0.11093896318438906.\n[I 2020-08-31 22:20:05,792] Trial 14 finished with value: 0.2023502300348337 and parameters: {'lgbmregressor__num_leaves': 279, 'lgbmregressor__max_depth': 49, 'lgbmregressor__n_estimators': 32, 'lgbmregressor__subsample_for_bin': 76846, 'lgbmregressor__min_child_samples': 187, 'lgbmregressor__reg_alpha': 0.8513891170245845, 'lgbmregressor__colsample_bytree': 0.9407596264683925, 'lgbmregressor__learning_rate': 0.11408956571289046}. Best is trial 10 with value: 0.11093896318438906.\n[I 2020-08-31 22:20:07,304] Trial 15 finished with value: 0.11771366854778548 and parameters: {'lgbmregressor__num_leaves': 40, 'lgbmregressor__max_depth': 71, 'lgbmregressor__n_estimators': 302, 'lgbmregressor__subsample_for_bin': 191118, 'lgbmregressor__min_child_samples': 4, 'lgbmregressor__reg_alpha': 0.6668528744066189, 'lgbmregressor__colsample_bytree': 0.789114329340918, 'lgbmregressor__learning_rate': 0.009472484994735079}. Best is trial 10 with value: 0.11093896318438906.\n" ], [ "features = [\"melee_defence\",\n\"health\",\n\"melee_attack\",\n\"leadership\",\n\"armour\",\n\"health_per_entity\",\n\"run_speed\",\n\"missile_primary__damage\",\n\"charge_bonus\",\n\"melee__ap_ratio\",\n\"melee__base_damage\",\n\"mass\",\n\"melee__damage\",\n\"height\",\n\"melee__melee_attack_interval\",\n\"acceleration\",\n\"melee__bonus_v_large\",\n\"melee__bonus_v_infantry\",\n\"melee__splash_attack_max_attacks\",\n\"parry_chance\",\n\"reload\",\n\"hit_reactions_ignore_chance\",\n\"melee__weapon_length\",\n\"damage_mod_physical\",\n\"accuracy\",\n\"combat_reaction_radius\",\n\"fly_speed\",\n\"melee__splash_attack_power_multiplier\"]\n\nmodel = make_pipeline(\n Selector(features),\n LGBMRegressor(objective='mae')\n)\n\nbest_params = {'lgbmregressor__num_leaves': 434,\n 'lgbmregressor__max_depth': 110,\n 'lgbmregressor__n_estimators': 256,\n 'lgbmregressor__subsample_for_bin': 82449,\n 'lgbmregressor__min_child_samples': 4,\n 'lgbmregressor__reg_alpha': 0.14126751650012037,\n 'lgbmregressor__colsample_bytree': 0.7745213812855362,\n 'lgbmregressor__learning_rate': 0.04242070860113767}\n\nmodel.set_params(**best_params)", "_____no_output_____" ], [ "cv = KFold(n_splits=8)\n\nys = []\nyhats = []\nxs = []\nfor train_index, test_index in cv.split(x):\n x_train, x_test = x.iloc[train_index, :], x.iloc[test_index, :]\n y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n model.fit(x_train, y_train)\n yhat = model.predict(x_test)\n ys.append(y_test.values)\n yhats.append(yhat)\n xs.append(x_test.name.values)\n print(np.median(np.abs((yhat - y_test.values))), np.median(np.abs((np.exp(yhat) - np.exp(y_test.values)))))\n\nys = np.concatenate(ys)\nyhats = np.concatenate(yhats)\nxs = pd.DataFrame(np.concatenate(xs), columns=['name'])\n\nxs['yhat'] = np.exp(yhats).reshape(-1, 1)\nxs['y'] = np.exp(ys).reshape(-1, 1)\nxs['res'] = xs.yhat - xs.y\nxs['res_perc'] = xs.yhat / xs.y - 1\n\nxs.sort_values(by='res_perc', ascending=False, inplace=True)", "0.10286667457071186 80.474515325337\n0.08889552539397405 59.492918219037335\n0.10855460714420495 83.90862299254013\n0.1181555395152496 99.57712932134118\n0.10525263584371469 100.05377391017885\n0.09132697837402581 72.75645094302126\n0.10249711312229426 91.14735363981356\n0.09214808467456237 78.13196470080993\n" ], [ "sns.regplot(xs.y, xs.yhat, scatter=False)\nsns.scatterplot(xs.y, xs.yhat, alpha=0.1);", "_____no_output_____" ], [ "np.abs(xs.res).median()", "_____no_output_____" ], [ "xs", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe0822ca36a5e5a914e795811362e5b9f92d696
6,004
ipynb
Jupyter Notebook
populate_db/Notebooks/Polymer_Data.ipynb
LDWLab/DESIRE
fda3e10c6fdfe5ce47c151d506239dbc9f65f2f0
[ "MIT" ]
null
null
null
populate_db/Notebooks/Polymer_Data.ipynb
LDWLab/DESIRE
fda3e10c6fdfe5ce47c151d506239dbc9f65f2f0
[ "MIT" ]
null
null
null
populate_db/Notebooks/Polymer_Data.ipynb
LDWLab/DESIRE
fda3e10c6fdfe5ce47c151d506239dbc9f65f2f0
[ "MIT" ]
null
null
null
34.308571
191
0.563458
[ [ [ "# Script for uploading our rProtein sequences\n\nUses a pregenerated csv file with the columns:\n\n*Txid*, *Accession*, *Origin database*, *Description*, and *Full sequence*\n\nUpdates tables: **Polymer_Data**, **Polymer_metadata**, and **Residues**", "_____no_output_____" ] ], [ [ "#!/usr/bin/env python3\nimport csv, sys, getopt, getpass, mysql.connector\n\ndef usage():\n\tprint (\\\n\t\"USAGE:\\n./upload_accession.py -c [csv_file_path]-h\\n\\\n\t-c: defines path to csv file with txids, accessions, database, protein name, description, and sequence.\\tREQUIRED\\n\\\n\t-h: prints this\\\n\")\n\ntry:\n\topts, args = getopt.getopt(sys.argv[1:], 'c:h', ['csv=', 'help'])\nexcept getopt.GetoptError:\n\tusage()\n\tsys.exit(2)\n\nfor opt, arg in opts:\n\tif opt in ('-h', '--help'):\n\t\tusage()\n\t\tsys.exit(2)\n\telif opt in ('-c', '--csv'):\n\t\tcsv_path = arg\n\telse:\n\t\tusage()\n\t\tsys.exit(2)\n\nuname = input(\"User name: \")\npw = getpass.getpass(\"Password: \")\ncnx = mysql.connector.connect(user=uname, password=pw, host='130.207.36.75', database='SEREB')\ncursor = cnx.cursor()\n\ndef read_csv(csv_path):\n\twith open(csv_path, 'r') as csv_file:\n\t\treader = csv.reader(csv_file)\n\t\tcsv_list = list(reader)\n\treturn csv_list\n\ndef superkingdom_info(ID):\n\t'''\n\tGets the superkingdom for a strain ID\n\t'''\n\t#print(ID)\n\tcursor.execute(\"SELECT SEREB.TaxGroups.groupName FROM SEREB.Species_TaxGroup\\\n\t\tINNER JOIN SEREB.TaxGroups ON SEREB.Species_TaxGroup.taxgroup_id=SEREB.TaxGroups.taxgroup_id\\\n\t\tINNER JOIN SEREB.Species ON SEREB.Species_TaxGroup.strain_id=SEREB.Species.strain_id\\\n\t\tWHERE SEREB.TaxGroups.groupLevel = 'superkingdom' AND SEREB.Species.strain_id = '\"+ID+\"'\")\n\tresults = cursor.fetchall()\n\t#print(ID,results)\n\ttry:\n\t\tsuperkingdom=(results[0][0])\n\texcept:\n\t\traise ValueError (\"No result for specie \"+str(ID)+\" in the MYSQL query\")\n\treturn superkingdom\n\ndef check_nomo_id(occur, prot_name):\n\t'''\n\tGets nom_id for new name and superkingdom\n\t'''\n\tcursor.execute(\"SELECT SEREB.Nomenclature.nom_id FROM SEREB.Nomenclature\\\n\t\tINNER JOIN SEREB.Old_name ON SEREB.Nomenclature.nom_id=SEREB.Old_name.nomo_id\\\n\t\tWHERE SEREB.Old_name.old_name = '\"+prot_name+\"' AND SEREB.Old_name.N_B_Y_H_A = 'BAN' AND SEREB.Nomenclature.occurrence = '\"+occur+\"'\")\n\tresult = cursor.fetchall()\n\t#nom_id=result[0][0]\n\ttry:\n\t\tnom_id=result[0][0]\n\texcept:\n\t\traise ValueError (\"No result for nom_id \"+prot_name+\" and occurrence \"+occur+\" in the MYSQL query\")\n\treturn nom_id\n\ndef upload_resi(poldata_id, fullseq):\n\ti = 1\n\tfor resi in fullseq:\n\t\tquery = \"INSERT INTO `SEREB`.`Residues`(`PolData_id`,`resNum`,`unModResName`) VALUES('\"+poldata_id+\"','\"+str(i)+\"','\"+resi+\"')\"\n\t\tcursor.execute(query)\n\t\t#print(query)\n\t\ti+=1\n\treturn True\n\ndef main():\n\tcsv_list = read_csv(csv_path)\n\tfor entry in csv_list:\n\t\tsuperK = superkingdom_info(entry[0])\n\t\tnom_id = check_nomo_id(superK[0], entry[3])\t\n\t\tquery = \"INSERT INTO `SEREB`.`Polymer_Data`(`GI`,`strain_ID`,`nomgd_id`, `GeneDescription`) VALUES('\"+entry[1]+\"','\"+str(entry[0])+\"','\"+str(nom_id)+\"','\"+entry[4]+\"')\"\n\t\tprint(query)\n\t\tcursor.execute(query)\n\t\tlastrow_id = str(cursor.lastrowid)\n\t\tquery = \"INSERT INTO `SEREB`.`Polymer_metadata`(`polymer_id`,`accession_type`,`polymer_type`, `Fullseq`) VALUES('\"+str(lastrow_id)+\"','LDW-prot','protein','\"+entry[5]+\"')\"\n\t\tcursor.execute(query)\n\t\t#print(query)\n\t\tupload_resi(str(lastrow_id), entry[5])\n\t\n\nif __name__ == \"__main__\":\n\tmain()\n\n#cnx.commit()\ncursor.close()\ncnx.close()\nprint(\"Success!\")", "USAGE:\n./upload_accession.py -c [csv_file_path]-h\n\t-c: defines path to csv file with txids, accessions, database, protein name, description, and sequence.\tREQUIRED\n\t-h: prints this\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
cbe08f31a69a587298a1348806d58c36287ffb41
81,013
ipynb
Jupyter Notebook
examples/notebooks/Tone and chirp calibration.ipynb
NCRAR/psiexperiment
c3f8580b2b155ce42ebb936019d862c4343b545c
[ "MIT" ]
null
null
null
examples/notebooks/Tone and chirp calibration.ipynb
NCRAR/psiexperiment
c3f8580b2b155ce42ebb936019d862c4343b545c
[ "MIT" ]
null
null
null
examples/notebooks/Tone and chirp calibration.ipynb
NCRAR/psiexperiment
c3f8580b2b155ce42ebb936019d862c4343b545c
[ "MIT" ]
null
null
null
260.491961
32,668
0.895609
[ [ [ "%matplotlib inline\nimport numpy as np\nimport pylab as pl\n\nfrom psi.application import get_default_io, get_default_calibration, get_calibration_file\nfrom psi.controller import util\nfrom psi.controller.calibration.api import FlatCalibration, PointCalibration\nfrom psi.controller.calibration.util import load_calibration, psd, psd_df, db, dbtopa\nfrom psi.controller.calibration import tone\nfrom psi.core.enaml.api import load_manifest_from_file\n\nfrequencies = [250, 500, 1000, 2000, 4000, 8000, 16000, 32000]\n\nio_file = get_default_io()\ncal_file = get_calibration_file(io_file)\nprint(cal_file)\nio_manifest = load_manifest_from_file(io_file, 'IOManifest')\nio = io_manifest()\naudio_engine = io.find('NI_audio')\n\nchannels = audio_engine.get_channels(active=False)\nload_calibration(cal_file, channels)\n\nmic_channel = audio_engine.get_channel('microphone_channel')\nmic_channel.gain = 40\n\ncal_mic_channel = audio_engine.get_channel('reference_microphone_channel')\ncal_mic_channel.gain = 0\n\nspeaker_channel = audio_engine.get_channel('speaker_1')\nprint(speaker_channel.calibration)", "c:\\users\\lbhb\\projects\\psi2\\data\\io\\default\\default.json\n<psi.controller.calibration.calibration.FlatCalibration object at 0x000001F7B8A14EC8>\n" ], [ "fixed_gain_result = tone.tone_sens(\n frequencies=frequencies,\n engine=audio_engine,\n ao_channel_name='speaker_1',\n ai_channel_names=['reference_microphone_channel', 'microphone_channel'],\n gains=-30,\n debug=True,\n duration=0.1,\n iti=0,\n trim=0.01,\n repetitions=2,\n)", "_____no_output_____" ], [ "fixed_gain_result['norm_spl'].unstack('channel_name').eval('microphone_channel-reference_microphone_channel')", "_____no_output_____" ], [ "rms = fixed_gain_result.loc['reference_microphone_channel']['rms'].loc[1000]\nfigure, axes = pl.subplots(3, 2)\n\nfor ax, freq in zip(axes.ravel(), frequencies):\n w = fixed_gain_result.loc['microphone_channel', freq]['waveform'].T\n ax.plot(w)\n ax.set_title(freq)\n", "_____no_output_____" ], [ "figure, axes = pl.subplots(3, 2)\n\nfor ax, freq in zip(axes.ravel(), frequencies):\n w = fixed_gain_result.loc['reference_microphone_channel', freq]['waveform'].T\n ax.plot(w)\n ax.set_title(freq)", "_____no_output_____" ], [ "tone_sens = fixed_gain_result.loc['microphone_channel', 'sens']\ncalibration = PointCalibration(tone_sens.index, tone_sens.values)\ngains = calibration.get_gain(frequencies, 80)", "_____no_output_____" ], [ "variable_gain_result = tone.tone_spl(\n frequencies=frequencies,\n engine=audio_engine,\n ao_channel_name='speaker_1',\n ai_channel_names=['microphone_channel'],\n gains=gains,\n debug=True,\n duration=0.1,\n iti=0,\n trim=0.01,\n repetitions=2,\n)\n\nvariable_gain_result['spl']", "_____no_output_____" ], [ "from psiaudio.stim import ChirpFactory\n\nfactory = ChirpFactory(fs=speaker_channel.fs,\n start_frequency=500,\n end_frequency=50000,\n duration=0.02,\n level=-40,\n calibration=FlatCalibration.as_attenuation())\n\nn = factory.n_samples_remaining()\nchirp_waveform = factory.next(n)\n\nresult = util.acquire(audio_engine, chirp_waveform, 'speaker_1', ['microphone_channel'], repetitions=64, trim=0)", "_____no_output_____" ], [ "chirp_response = result['microphone_channel'][0]\nchirp_psd = psd_df(chirp_response, mic_channel.fs)\nchirp_psd_mean = chirp_psd.mean(axis=0)\nchirp_psd_mean_db = db(chirp_psd_mean)\n\nsignal_psd = db(psd_df(chirp_waveform, speaker_channel.fs))\n\nfreq = chirp_psd.columns.values\nchirp_spl = mic_channel.calibration.get_spl(freq, chirp_psd)\nchirp_spl_mean = chirp_spl.mean(axis=0)\nchirp_sens = signal_psd - chirp_spl_mean - db(20e-6)", "_____no_output_____" ], [ "chirp_sens.loc[1000]", "_____no_output_____" ], [ "figure, axes = pl.subplots(1, 3, figsize=(12, 3))\n\nchirp_response_mean = np.mean(chirp_response, axis=0)\nprint(chirp_response_mean.min(), chirp_response_mean.max())\naxes[0].plot(chirp_response_mean)\n\nfreq = chirp_spl_mean.index.values\naxes[1].semilogx(freq[1:], chirp_spl_mean[1:])\nx = psd_df(chirp_response_mean, mic_channel.fs)\ny = mic_channel.calibration.get_spl(x.index, x.values)\naxes[1].semilogx(freq[1:], y[1:], 'r')\naxes[1].axis(xmin=500, xmax=50000)\n\naxes[2].semilogx(freq[1:], chirp_sens[1:])\naxes[2].plot(tone_sens, 'ko')\naxes[2].axis(xmin=500, xmax=50000)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe0a7d6b9f0999dd9cef020947e5456ec64c3e5
284,892
ipynb
Jupyter Notebook
examples/Taylor models example.ipynb
UnofficialJuliaMirror/TaylorModels.jl-314ce334-5f6e-57ae-acf6-00b6e903104a
2bdb94bd3cf2da01015fe00f154ea7b82915f5bf
[ "MIT" ]
44
2018-05-07T02:41:24.000Z
2022-03-08T05:20:38.000Z
examples/Taylor models example.ipynb
UnofficialJuliaMirror/TaylorModels.jl-314ce334-5f6e-57ae-acf6-00b6e903104a
2bdb94bd3cf2da01015fe00f154ea7b82915f5bf
[ "MIT" ]
115
2018-04-16T17:33:58.000Z
2022-03-04T20:38:34.000Z
examples/Taylor models example.ipynb
UnofficialJuliaMirror/TaylorModels.jl-314ce334-5f6e-57ae-acf6-00b6e903104a
2bdb94bd3cf2da01015fe00f154ea7b82915f5bf
[ "MIT" ]
12
2019-03-05T19:24:02.000Z
2022-03-08T10:39:28.000Z
66.023638
233
0.56732
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cbe0acc16eebbf482a136f17db18f47836843bd6
2,316
ipynb
Jupyter Notebook
part02-machine-learning/2_3_naive_bayes.ipynb
edgardeng/machine-learning-pytorch
24a060894f5226b5ef20cc311db72f1adc037548
[ "MIT" ]
null
null
null
part02-machine-learning/2_3_naive_bayes.ipynb
edgardeng/machine-learning-pytorch
24a060894f5226b5ef20cc311db72f1adc037548
[ "MIT" ]
null
null
null
part02-machine-learning/2_3_naive_bayes.ipynb
edgardeng/machine-learning-pytorch
24a060894f5226b5ef20cc311db72f1adc037548
[ "MIT" ]
null
null
null
18.380952
79
0.455095
[ [ [ "## 朴素贝叶斯 Naive Bayes\n\n> 以贝叶斯定理为基础,用于不同相互独立特征下的分类\n\n[搞懂朴素贝叶斯公式](https://blog.csdn.net/fisherming/article/details/79509025)\n[sklearn文档-朴素贝叶斯](https://sklearn.apachecn.org/docs/master/10.html)\n\n\n优点:\n\n(1) 算法逻辑简单,易于实现\n\n(2)分类过程中时空开销小\n\n缺点:\n\n 在属性个数比较多或者属性之间相关性较大时,分类效果不好. 朴素贝叶斯模型假设属性之间相互独立\n\n\n贝叶斯公式:", "_____no_output_____" ], [ "$P(B|A) = P(A|B)P(B) / P(A)$", "_____no_output_____" ], [ "### 高斯模型", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom sklearn.naive_bayes import GaussianNB\nX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])\nY = np.array([1, 1, 1, 2, 2, 2])", "_____no_output_____" ], [ "net = GaussianNB()\nnet.fit(X,Y)\nprint(net.predict([[-0.8,-1]]))\n\nnet_pf = GaussianNB()\nnet_pf.partial_fit(X,Y,np.unique(Y))\nprint(net.predict([[-0.8,-1]]))", "[1]\n[1]\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ] ]
cbe0d0aec584c383ae936f28e4d69955a0cf9b7c
10,185
ipynb
Jupyter Notebook
Robust Design/PracticMaterial_1/Code1_(1) Data Handling & 2D Graph Plotting.ipynb
nosy0411/Data_analysis_project
32e3bc18523567a30fa2c56aceeb0e57ee7f654f
[ "MIT" ]
null
null
null
Robust Design/PracticMaterial_1/Code1_(1) Data Handling & 2D Graph Plotting.ipynb
nosy0411/Data_analysis_project
32e3bc18523567a30fa2c56aceeb0e57ee7f654f
[ "MIT" ]
null
null
null
Robust Design/PracticMaterial_1/Code1_(1) Data Handling & 2D Graph Plotting.ipynb
nosy0411/Data_analysis_project
32e3bc18523567a30fa2c56aceeb0e57ee7f654f
[ "MIT" ]
null
null
null
22.88764
119
0.46863
[ [ [ "## 라이브러리(패키지) import", "_____no_output_____" ], [ "데이터프레임, 행렬, 그래프 그리기 위한 라이브러리", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## 데이터 불러오기", "_____no_output_____" ], [ "현재폴더 데이터 불러오기", "_____no_output_____" ] ], [ [ "ExampleData = pd.read_csv('./ExampleData', sep=',', header=None)\nExampleData", "_____no_output_____" ] ], [ [ "하위폴더 데이터 불러오기", "_____no_output_____" ] ], [ [ "path = './Subfolder/ExampleData2' # 파일 경로\nExampleData2 = pd.read_csv(path, sep=',',names=['time', 'Accelerometer', 'Voltage', 'Current'])\nExampleData2", "_____no_output_____" ] ], [ [ "## 데이터 핸들링 (Handling)", "_____no_output_____" ], [ "시간열(time column) 제거한 센서 데이터 추출방법 1", "_____no_output_____" ] ], [ [ "SensorDataOnly = ExampleData.iloc[:,1:]\nSensorDataOnly", "_____no_output_____" ] ], [ [ "시간열(time column) 제거한 센서 데이터 추출방법 2", "_____no_output_____" ] ], [ [ "Data = ExampleData.drop(0, axis=1)\nData", "_____no_output_____" ] ], [ [ "데이터에 열 추가하기 (행 개수가 일치해야함)", "_____no_output_____" ] ], [ [ "Data = pd.concat([pd.DataFrame(np.arange (0 , 0.2167 , 1/12800)) , Data], axis=1)\nData", "_____no_output_____" ] ], [ [ "0.01초부터 0.02초까지 해당하는 데이터 추출", "_____no_output_____" ] ], [ [ "StartPoint = np.where(ExampleData.iloc[:,0].values == 0.01)[0][0]\nEndPoint = np.where(ExampleData.iloc[:,0].values == 0.02)[0][0]\n\nStartPoint, EndPoint", "_____no_output_____" ], [ "NewData = ExampleData.iloc[StartPoint:EndPoint, :]\nNewData", "_____no_output_____" ] ], [ [ "데이터를 파일(.csv)로 저장", "_____no_output_____" ] ], [ [ "path = './Subfolder/NewData_1'\nNewData.to_csv(path , sep=',' , header=None , index=None)", "_____no_output_____" ] ], [ [ "데이터 행렬바꾸기", "_____no_output_____" ] ], [ [ "Data = np.transpose(Data)\nData.shape", "_____no_output_____" ], [ "# 행렬 다시 바꾸기 (원래 행렬 복원)\nData = np.transpose(Data)\nData.shape", "_____no_output_____" ] ], [ [ "## 데이터 그래프 그리기", "_____no_output_____" ], [ "그리드, 라벨, 제목, 범례 표시 등", "_____no_output_____" ] ], [ [ "# ExampleData 0열 (1번째 열) = 시간\n# ExampleData 1열 (2번째 열) = 가속도 센서 데이터\n\nplt.plot(ExampleData.iloc[:,0], ExampleData.iloc[:,1])\nplt.grid() # 그리드 표시\nplt.xlabel('time(s)') # x 라벨 표시\nplt.ylabel('Acceleration(g)') # y 라벨 표시\nplt.title('Spot Welding Acceleration Data') # 제목 표시\nplt.legend(['Acc'], loc = 'upper right', fontsize=10) # 범례 표시\n#plt.xlim(0,0.02) # x축 범위 설정\nplt.ylim(-1.5,1.5) # y축 범위 설정\nplt.show()", "_____no_output_____" ], [ "# ExampleData 0열 (1번째 열) = 시간\n# ExampleData 2열 (3번째 열) = 전압 센서 데이터\n\nplt.plot(ExampleData.iloc[:,0], ExampleData.iloc[:,2])\nplt.grid() # 그리드 표시\nplt.xlabel('time(s)') # x 라벨 표시\nplt.ylabel('Voltage(V)') # y 라벨 표시\nplt.title('Spot Welding Voltage Data') # 제목 표시\nplt.legend(['Voltage'], loc = 'upper right', fontsize=10) # 범례 표시\nplt.show()", "_____no_output_____" ], [ "# ExampleData 0열 (1번째 열) = 시간\n# ExampleData 3열 (4번째 열) = 전류 센서 데이터\n\nplt.plot(ExampleData.iloc[:,0], ExampleData.iloc[:,3])\nplt.grid() # 그리드 표시\nplt.xlabel('time(s)') # x 라벨 표시\nplt.ylabel('Current(kA)') # y 라벨 표시\nplt.title('Spot Welding Current Data') # 제목 표시\nplt.legend(['Current'], loc = 'upper right', fontsize=10) # 범례 표시\nplt.show()\n", "_____no_output_____" ] ], [ [ "그래프 모양 변경 등", "_____no_output_____" ] ], [ [ "plt.figure(figsize = (12,9))\nplt.plot(ExampleData.iloc[:100,0],ExampleData.iloc[:100,1],\n linestyle = '-.', \n linewidth = 2.0, \n color = 'b', \n marker = 'o', \n markersize = 8, \n markeredgecolor = 'g', \n markeredgewidth = 1.5, \n markerfacecolor = 'r', \n alpha = 0.5)\n\nplt.grid()\nplt.xlabel('time(s)') \nplt.ylabel('Acceleration(g)')\nplt.title('Spot Welding Acceleration Data') \nplt.legend(['Acc'], loc = 'upper right', fontsize=10)", "_____no_output_____" ] ], [ [ "그래프 겹쳐서 그리기", "_____no_output_____" ] ], [ [ "DataLength = 100 # 데이터 길이 100개까지만 제한 (~100/12800 초까지)\n\nplt.plot(ExampleData.iloc[:DataLength,0],ExampleData.iloc[:DataLength,1])\nplt.plot(ExampleData.iloc[:DataLength,0],ExampleData.iloc[:DataLength,2])\nplt.plot(ExampleData.iloc[:DataLength,0],ExampleData.iloc[:DataLength,3])\n\nplt.xlabel('time(s)')\nplt.ylabel('Acceleration(g)')\nplt.title('Spot Welding Acceleration Data')\nplt.legend(['Acc', 'Voltage', 'Current'], loc = 'upper right', fontsize=10)\n\nplt.grid()\nplt.show()", "_____no_output_____" ] ], [ [ "### ****** 필독 !! 실습과제 주의사항 ******", "_____no_output_____" ], [ "- 각자의 \"수강생 번호\" 확인 (아이캠퍼스 공지) \n- 제출하는 실습과제 파일에 \"수강생 번호\"를 기준으로 작성 (이름, 학번 등 작성X)\n- 각 실습과제에 대한 구체적인 파일 이름은 매번 개별 안내 \n (수강생 번호 123번 학생 과제파일 예시 : 'ST123_HW2_1.csv' )\n- 과제 파일이름 양식 지키지 않을 시 감점!", "_____no_output_____" ], [ "# [실습 과제 1]", "_____no_output_____" ], [ "## 1. ExampleData의 0.03초 ~ 0.05초에 대하여 '센서 데이터'만 추출해서 파일 저장\n#### >>>>>> 저장된 데이터 파일 제출\n#### >>>>>> 데이터 이름 : ST(수강생 번호)_HW1_1 (예시 : 'ST000_HW1_1' // 'ST00_HW1_1' // 'ST0_HW1_1')\n#### >>>>>> 데이터 이름 중 'ST' , 'HW' 등 영어는 모두 대문자", "_____no_output_____" ], [ " ", "_____no_output_____" ], [ "## 2. 위의 0.03~0.05초 센서 데이터(3개)에 대하여 실습코드 마지막 셀과 같이 그래프 겹쳐 그리기\n#### >>>>>> 1번 항목 (ExampleData 에서 0.03~0.05초 센서데이터만 추출) ~ 2번 항목 (그래프) 수행한 코드파일(ipynb) 제출\n#### >>>>>> 코드파일 이름 : ST(수강생 번호)_HW1_2 (예시 : 'ST000_HW1_2.ipynb' // 'ST00_HW1_2..ipynb' // 'ST0_HW1_2.ipynb')\n#### >>>>>> 코드파일 이름 중 'ST' , 'HW' 등 영어는 모두 대문자", "_____no_output_____" ], [ "## ***** 1번 파일(데이터), 2번 파일(코드) 함께 zip파일로 압축하여 제출\n### >>> 압축파일 이름 ST(수강생 번호)_HW1 (예시 : 'ST000_HW1.zip' // 'ST00_HW1' // 'ST0_HW1)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cbe0d1ec5c14fa8faf5a7273d2fc742d9731a1d0
53,014
ipynb
Jupyter Notebook
notebooks/IEEE_BigData_2017.ipynb
mmisiewicz/ArchiveSpark
62edff7888c8b6922df2f5553b6a75620eb7f012
[ "MIT" ]
131
2015-08-06T23:15:44.000Z
2022-03-02T19:42:08.000Z
notebooks/IEEE_BigData_2017.ipynb
mmisiewicz/ArchiveSpark
62edff7888c8b6922df2f5553b6a75620eb7f012
[ "MIT" ]
24
2017-01-30T23:52:31.000Z
2021-07-13T09:01:30.000Z
notebooks/IEEE_BigData_2017.ipynb
helgeho/ArchiveSpark
c20a2519f8ac388e1aef4d8e8ae4ec4f73ceeaca
[ "MIT" ]
17
2015-08-07T02:07:23.000Z
2021-11-25T12:27:44.000Z
46.019097
8,953
0.51294
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cbe0d3c2ca7a2cad0cfbbf809c8e685bf5a9f6b7
23,599
ipynb
Jupyter Notebook
2. numpy_basics.ipynb
therajmaurya/Machine-Learning-Workshop-Content
f3657c9d8002fee76f7c94c50a0ff383f1e5b95e
[ "MIT" ]
null
null
null
2. numpy_basics.ipynb
therajmaurya/Machine-Learning-Workshop-Content
f3657c9d8002fee76f7c94c50a0ff383f1e5b95e
[ "MIT" ]
null
null
null
2. numpy_basics.ipynb
therajmaurya/Machine-Learning-Workshop-Content
f3657c9d8002fee76f7c94c50a0ff383f1e5b95e
[ "MIT" ]
null
null
null
42.444245
13,296
0.731302
[ [ [ "# Intoduction\nThe numpy package (module) is used in almost all numerical computation using Python. It is a package that provide high-performance vector, matrix and higher-dimensional data structures for Python. \n", "_____no_output_____" ], [ "To use numpy", "_____no_output_____" ] ], [ [ "from numpy import *", "_____no_output_____" ] ], [ [ "# Creating numpy arrays", "_____no_output_____" ] ], [ [ "# a vector: the argument to the array function is a Python list\nv = array([1,2,3,4])\nv", "_____no_output_____" ], [ "# a matrix: the argument to the array function is a nested Python list\nM = array([[1, 2], [3, 4]])\n\nM", "_____no_output_____" ] ], [ [ "The v and M objects are both of the type ndarray that the numpy module provides.\n", "_____no_output_____" ] ], [ [ "type(v), type(M)", "_____no_output_____" ] ], [ [ "The difference between the v and M arrays is only their shapes. We can get information about the shape of an array by using the ndarray.shape property.\n", "_____no_output_____" ] ], [ [ "v.shape", "_____no_output_____" ], [ "v.reshape\nv.shape", "_____no_output_____" ], [ "M.shape", "_____no_output_____" ] ], [ [ "linspace and logspace", "_____no_output_____" ] ], [ [ "# using linspace, both end points ARE included\nlinspace(0, 10, 25)", "_____no_output_____" ], [ "logspace(0, 10, 10, base=e)", "_____no_output_____" ] ], [ [ "# Manipulating arrays", "_____no_output_____" ], [ "Indexing\n\nWe can index elements in an array using square brackets and indices:\n", "_____no_output_____" ] ], [ [ "# v is a vector, and has only one dimension, taking one index\nv[0]\n", "_____no_output_____" ], [ "# M is a matrix, or a 2 dimensional array, taking two indices \nM[1,1]", "_____no_output_____" ] ], [ [ "The same thing can be achieved with using : instead of an index:\n", "_____no_output_____" ] ], [ [ "M[1,:] # row 1\n", "_____no_output_____" ] ], [ [ "# Linear algebra", "_____no_output_____" ], [ "\n\nVectorizing code is the key to writing efficient numerical calculation with Python/Numpy. That means that as much as possible of a program should be formulated in terms of matrix and vector operations, like matrix-matrix multiplication.\nScalar-array operations\n\nWe can use the usual arithmetic operators to multiply, add, subtract, and divide arrays with scalar numbers.\n", "_____no_output_____" ] ], [ [ "v1 = arange(0, 5)", "_____no_output_____" ], [ "v1 * 2", "_____no_output_____" ], [ "v1 + 2", "_____no_output_____" ], [ "A=array([[1, 2], [3, 4]])", "_____no_output_____" ], [ "A * 2, A + 2", "_____no_output_____" ], [ "A=A+A\nA", "_____no_output_____" ] ], [ [ "# Plotting", "_____no_output_____" ], [ "It is a part of visualisation", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "x=arange(0,3*pi,0.1) #arange is a numpy function\ny=sin(x)\nplt.plot(x,y)\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
cbe0ee7e250215e2fd2e6597d57fc6f1c7aa3af4
79,744
ipynb
Jupyter Notebook
Model_Traning & Dataset/traning.ipynb
R4j4n/Eye-Gaze_and_Blink-detection-using-Neural-Network
f68459d9603fe5b40654a8cefbf346eaff2832c4
[ "MIT" ]
8
2020-09-08T14:06:42.000Z
2022-02-24T06:57:58.000Z
Model_Traning & Dataset/traning.ipynb
R4j4n/Eye-Gaze_and_Blink-detection-using-Neural-Network
f68459d9603fe5b40654a8cefbf346eaff2832c4
[ "MIT" ]
4
2021-01-04T05:59:39.000Z
2022-03-17T06:55:53.000Z
Model_Traning & Dataset/traning.ipynb
R4j4n/Eye-Gaze_and_Blink-detection-using-Neural-Network
f68459d9603fe5b40654a8cefbf346eaff2832c4
[ "MIT" ]
2
2021-03-09T09:01:27.000Z
2021-05-12T20:16:54.000Z
203.428571
20,643
0.70557
[ [ [ "image_shape = (56,64,1)\ntrain_path = \"D:\\\\Projects\\\\EYE_GAME\\\\eye_img\\\\datav2\\\\train\\\\\"\ntest_path = \"D:\\\\Projects\\\\EYE_GAME\\\\eye_img\\\\datav2\\\\test\\\\\"\n", "_____no_output_____" ], [ "import os\nimport pandas as pd\nfrom glob import glob\nimport numpy as np \nimport matplotlib as plt\nfrom matplotlib.image import imread \nimport seaborn as sns \nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Activation, Dropout, Flatten, Dense, Conv2D, MaxPooling2D\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n%matplotlib inline\n", "_____no_output_____" ], [ "os.listdir(train_path)", "_____no_output_____" ], [ "\nimg=imread(train_path+'left\\\\'+'68.jpg')", "_____no_output_____" ], [ "folders=glob(test_path + '/*')\n", "_____no_output_____" ], [ "traindata_gen=ImageDataGenerator(\n rotation_range=10,\n rescale=1/255.,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.1,\n zoom_range=0.1,\n fill_mode='nearest'\n )\n\ntestdata_gen=ImageDataGenerator(\n \n rescale=1./255)", "_____no_output_____" ], [ "traindata_gen.flow_from_directory(train_path)", "Found 3622 images belonging to 3 classes.\n" ], [ "model = Sequential()\n\nmodel.add(Conv2D(filters=32, kernel_size=(3,3), strides=1, padding='same',input_shape=image_shape, activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(filters=64, kernel_size=(3,3), strides=1, padding='same',input_shape=image_shape, activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(filters=128, kernel_size=(3,3), strides=1, padding='same',input_shape=image_shape, activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\n\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(len(folders)))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])", "_____no_output_____" ], [ "model.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 56, 64, 32) 320 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 28, 32, 32) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 28, 32, 64) 18496 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 14, 16, 64) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 14, 16, 128) 73856 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 7, 8, 128) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 7168) 0 \n_________________________________________________________________\ndense (Dense) (None, 512) 3670528 \n_________________________________________________________________\nactivation (Activation) (None, 512) 0 \n_________________________________________________________________\ndropout (Dropout) (None, 512) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 3) 1539 \n_________________________________________________________________\nactivation_1 (Activation) (None, 3) 0 \n=================================================================\nTotal params: 3,764,739\nTrainable params: 3,764,739\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "from tensorflow.keras.callbacks import EarlyStopping\nearly_stop = EarlyStopping(monitor='val_loss',patience=2)", "_____no_output_____" ], [ "batch_size = 32\ntraning_set=traindata_gen.flow_from_directory(train_path,\n target_size =image_shape[:2],\n batch_size = batch_size,\n color_mode=\"grayscale\",\n class_mode = 'categorical')", "Found 3622 images belonging to 3 classes.\n" ], [ "testing_set=testdata_gen.flow_from_directory(test_path,\n target_size = image_shape[:2],\n batch_size = batch_size,\n color_mode=\"grayscale\",\n class_mode = 'categorical',\n shuffle=False)", "Found 831 images belonging to 3 classes.\n" ], [ "testing_set.class_indices", "_____no_output_____" ], [ "result = model.fit(\n traning_set,\n epochs=8,\n validation_data=testing_set,\n callbacks=[early_stop]\n \n)", "Epoch 1/8\n114/114 [==============================] - 36s 318ms/step - loss: 0.2817 - accuracy: 0.8755 - val_loss: 0.0243 - val_accuracy: 0.9964\nEpoch 2/8\n114/114 [==============================] - 4s 37ms/step - loss: 0.0665 - accuracy: 0.9796 - val_loss: 0.0302 - val_accuracy: 0.9856\nEpoch 3/8\n114/114 [==============================] - 4s 36ms/step - loss: 0.0440 - accuracy: 0.9859 - val_loss: 0.0425 - val_accuracy: 0.9795\n" ], [ "losses = pd.DataFrame(model.history.history)", "_____no_output_____" ], [ "losses[['loss','val_loss']].plot()", "_____no_output_____" ], [ "losses[['loss','val_loss']].plot()\n", "_____no_output_____" ], [ "model.metrics_names", "_____no_output_____" ], [ "model.save('gazev3.1.h5')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe0f073e72cbc2a8838e6cc7da193b0d165ecdc
83,749
ipynb
Jupyter Notebook
sopron_2018_notebooks/pySUMMA_Demo_Example_Fig8_left_Using_TestCase_in_Local.ipynb
samarthsing/pysumma
b939f4761ac6adb2f50f87991147c69ce7d21b9e
[ "BSD-3-Clause" ]
null
null
null
sopron_2018_notebooks/pySUMMA_Demo_Example_Fig8_left_Using_TestCase_in_Local.ipynb
samarthsing/pysumma
b939f4761ac6adb2f50f87991147c69ce7d21b9e
[ "BSD-3-Clause" ]
null
null
null
sopron_2018_notebooks/pySUMMA_Demo_Example_Fig8_left_Using_TestCase_in_Local.ipynb
samarthsing/pysumma
b939f4761ac6adb2f50f87991147c69ce7d21b9e
[ "BSD-3-Clause" ]
null
null
null
116.642061
60,393
0.829896
[ [ [ "## Modeling the Impact of Root Distributions Parameterizations on Total Evapotranspiration in the Reynolds Mountain East catchment using pySUMMA", "_____no_output_____" ], [ "## 1. Introduction", "_____no_output_____" ], [ "One part of the Clark et al. (2015) study explored the impact of root distribution on total evapotranspiration (ET) using a SUMMA model for the Reynolds Mountain East catchment. This study looked at sensitivity of different root distribution exponents (0.25, 0.5, 1.0). The sensitivity of evapotranspiration to the distribution of roots, which dictates the capability of plants to access water. \n\nIn this Jupyter Notebook, the pySUMMA library is used to reproduce this analysis. According to the application of different root distribution exponenets (0.25, 0.5, 1.0), the sensitivity of result describes. \nThe Results section shows how to use pySUMMA and the Pandas library to reproduce Figure 8(left) from Clark et al. (2015). \n\nCollectively, this Jupyter Notebook serves as an example of how hydrologic modeling can be conducted directly within a Jupyter Notebook by leveraging the pySUMMA library. ", "_____no_output_____" ], [ "## 2. Background", "_____no_output_____" ], [ "### The Transpiration from soil layers available in SUMMA", "_____no_output_____" ] ], [ [ "#import libraries to display equations within the notebook\nfrom IPython.display import display, Math, Latex", "_____no_output_____" ] ], [ [ "\\begin{equation*}\n(S_{et}^{soil})_j = \\frac{(f_{roots})_j(\\beta_{v})_j}{\\beta_v} \\frac{(Q_{trans}^{veg})}{L_{vap}\\rho_{liq}(\\Delta z)_j} + (S_{evap}^{soil})_j \n\\end{equation*}\n\nThe transpiration sink term $(S_{et}^{soil})_j$ is computted for a given soil layer $j$.\n\n$Q_{trans}^{veg} (W/m^2)$ : the transpiration flux, $(\\beta_{v})_j$ : the soil water stress for the j-th soil layer\n\n$\\beta_v$ : the total water availability stress factor, $(f_{roots})_j$ : the fraction of roots in the j-th soil layer\n\n$(\\Delta z)_j$ : the depth of the j-th soil layer, $L_{vap} (J/kg), \\rho_{liq} (kg/m^3)$ : respectively the latent heat of vaporization and the intrinsic density of liquid water\n\n$(S_{evap}^{soil})_j (s^{-1})$ : the ground evaporation (only defined for the upper-most soil layer)", "_____no_output_____" ], [ "The above images are taken from the Stomal Resistance Method section within the manual Structure for Unifying Multiple Modeling Alternatives (SUMMA), Version 1.0: Technical Description (April, 2015).", "_____no_output_____" ], [ "## 3. Methods", "_____no_output_____" ], [ "### 1) Study Area", "_____no_output_____" ], [ "#### The Reynolds Mountain East catchment is located in southwestern Idaho as shown in the figure below.", "_____no_output_____" ] ], [ [ "from ipyleaflet import Map, GeoJSON\nimport json", "_____no_output_____" ], [ "m = Map(center=[43.06745, -116.75489], zoom=15)\nwith open('reynolds_geojson_latlon.geojson') as f:\n data = json.load(f)\ng = GeoJSON(data=data)\nm.add_layer(g)\nm", "_____no_output_____" ] ], [ [ "### 2) Create pySUMMA Simulation Object", "_____no_output_____" ] ], [ [ "from pysumma.Simulation import Simulation\nfrom pysumma.Plotting import Plotting", "_____no_output_____" ], [ "# create a pySUMMA simulation object using the SUMMA 'file manager' input file \nS = Simulation('/glade/u/home/ydchoi/summaTestCases_2.x/settings/wrrPaperTestCases/figure08/summa_fileManager_riparianAspenPerturbRoots.txt')", "_____no_output_____" ] ], [ [ "### 4) Check root Distribution Exponents", "_____no_output_____" ] ], [ [ "# create a trial parameter object to check root distribution exponents\nrootDistExp = Plotting(S.setting_path.filepath+S.para_trial.value)", "_____no_output_____" ], [ "# open netCDF file\nhru_rootDistExp = rootDistExp.open_netcdf()", "_____no_output_____" ], [ "# check root distribution exponents at each hru\nhru_rootDistExp['rootDistExp']", "_____no_output_____" ] ], [ [ "### 5) Run SUMMA for the different root Distribution Exponents with Develop version of Docker image", "_____no_output_____" ] ], [ [ "# set the simulation start and finish times\nS.decision_obj.simulStart.value = \"2007-07-01 00:00\"\nS.decision_obj.simulFinsh.value = \"2007-08-20 00:00\"", "_____no_output_____" ], [ "# set SUMMA executable file\nS.executable = \"/glade/u/home/ydchoi/summa/bin/summa.exe\"", "_____no_output_____" ], [ "# run the model giving the output the suffix \"rootDistExp\"\nresults_rootDistExp, output_path = S.execute(run_suffix=\"rootDistExp_local\", run_option = 'local')", "_____no_output_____" ] ], [ [ "## 4. Results", "_____no_output_____" ], [ "### Recreate the Figure 8 plot from Clark et al., 2015: The total ET Sensitivity with different root Distribution Exponents", "_____no_output_____" ] ], [ [ "from pysumma.Plotting import Plotting\nfrom jupyterthemes import jtplot\nimport matplotlib.pyplot as plt\nimport pandas as pd\njtplot.figsize(x=10, y=10)", "_____no_output_____" ] ], [ [ "#### 4.1) Create function to calculate Total ET of hour of day from SUMMA output for the period 1 June to 20 August 2007", "_____no_output_____" ] ], [ [ "def calc_total_et(et_output_df):\n # Total Evapotranspiration = Canopy Transpiration + Canopy Evaporation + Ground Evaporation\n # Change unit from kgm-2s-1 to mm/hr (mulpitle 3600)\n total_et_data = (et_output_df['scalarCanopyTranspiration'] + et_output_df['scalarCanopyEvaporation'] + et_output_df['scalarGroundEvaporation'])*3600\n # create dates(X-axis) attribute from ouput netcdf\n dates = total_et_data.coords['time'].data\n # create data value(Y-axis) attribute from ouput netcdf\n data_values = total_et_data.data\n # create two dimensional tabular data structure \n total_et_df = pd.DataFrame(data_values, index=dates)\n # round time to nearest hour (ex. 2006-10-01T00:59:59.99 -> 2006-10-01T01:00:00)\n total_et_df.index = total_et_df.index.round(\"H\")\n # set the time period to display plot \n total_et_df = total_et_df.loc[\"2007-06-01\":\"2007-08-20\"]\n # resample data by the average value hourly\n total_et_df_hourly = total_et_df.resample(\"H\").mean()\n # resample data by the average for hour of day\n total_et_by_hour = total_et_df_hourly.groupby(total_et_df_hourly.index.hour).mean()\n return total_et_by_hour", "_____no_output_____" ] ], [ [ "#### 4.2) Get hour of day output of the Parameterization of Root Distributions for the period 1 June to 20 August 2007", "_____no_output_____" ] ], [ [ "rootDistExp_hour = calc_total_et(results_rootDistExp)", "_____no_output_____" ], [ "# create each hru(1~3) object\nrootDistExp_hru_1 = rootDistExp_hour[0]\nrootDistExp_hru_2 = rootDistExp_hour[1]\nrootDistExp_hru_3 = rootDistExp_hour[2]", "_____no_output_____" ] ], [ [ "#### 4.3) Combine the Parameterization of Root Distributions into a single Pandas Dataframe", "_____no_output_____" ] ], [ [ "# Combine ET for each hru(1~3)\nET_Combine = pd.concat([rootDistExp_hru_1, rootDistExp_hru_2, rootDistExp_hru_3], axis=1)\n# add label \nET_Combine.columns = ['hru_1(Root Exp = 1.0)', 'hru_2(Root Exp = 0.5)', 'hru_3(Root Exp = 0.25)']", "_____no_output_____" ], [ "ET_Combine", "_____no_output_____" ] ], [ [ "#### 4.4) Add obervation data in Aspen station in Reynolds Mountain East to the plot", "_____no_output_____" ] ], [ [ "# create pySUMMA Plotting Object\nVal_eddyFlux = Plotting('/glade/u/home/ydchoi/summaTestCases_2.x/testCases_data/validationData/ReynoldsCreek_eddyFlux.nc')", "_____no_output_____" ], [ "# read Total Evapotranspiration(LE-wpl) from validation netcdf file\nObs_Evapotranspitaton = Val_eddyFlux.ds['LE-wpl']\n# create dates(X-axis) attribute from validation netcdf file\ndates = Obs_Evapotranspitaton.coords['time'].data\n# Change unit from Wm-2 to mm/hr (1 Wm-2 = 0.0864 MJm-2day-1, 1 MJm-2day-1 = 0.408 mmday-1, 1day = 24h)\ndata_values = Obs_Evapotranspitaton.data*0.0864*0.408/24\n# create two dimensional tabular data structure \ndf = pd.DataFrame(data_values, index=dates)\n# set the time period to display plot\ndf_filt = df.loc[\"2007-06-01\":\"2007-08-20\"]\n# select aspen obervation station among three different stations\ndf_filt.columns = ['-','Observation (aspen)','-']\n# resample data by the average for hour of day\ndf_gp_hr = df_filt.groupby([df_filt.index.hour, df_filt.index.minute]).mean()\n# reset index so each row has an hour an minute column\ndf_gp_hr.reset_index(inplace=True)\n# add hour and minute columns for plotting\nxvals = df_gp_hr.reset_index()['level_0'] + df_gp_hr.reset_index()['level_1']/60.", "_____no_output_____" ] ], [ [ "#### 4.5) Plotting output of the Parameterization of Root Distributions and observation data", "_____no_output_____" ] ], [ [ "# create plot with the Parameterization of Root Distributions(Root Exp : 1.0, 0.5, 0.25 )\nET_Combine_Graph = ET_Combine.plot()\n# invert y axis\nET_Combine_Graph.invert_yaxis()\n# plot scatter with x='xvals', y='Observation (aspen)'\nET_Combine_Graph.scatter(xvals, df_gp_hr['Observation (aspen)'])\n# add x, y label\nET_Combine_Graph.set(xlabel='Time of day (hr)', ylabel='Total evapotranspiration (mm h-1) ')\n# show up the legend\nET_Combine_Graph.legend()", "_____no_output_____" ] ], [ [ "## 5. Discussion", "_____no_output_____" ], [ "As stated in Clark et al., 2015, the following insights can be gained from this analysis:\n\n* The simulation in Figure 8 illustrates the sensitivity of evapotranspiration to the distribution of roots, which dictates the capability of plants to access water\n\n* The results in Figure 8 demonstrate strong sensitivities the rooting profile. Lower root distribution exponents place more roots near the surface. This makes it more difficult for plants to extract soil water lower in the soil profile, and decreases transpiration", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cbe0f82d8d10cd96ca98d33ada1e3338debd15b8
73,003
ipynb
Jupyter Notebook
notebooks/Experimental/Ishan/ADP Demo/Data Owner - Canada.ipynb
Noob-can-Compile/PySyft
156cf93489b16dd0205b0058d4d23d56b3a91ab8
[ "Apache-2.0" ]
null
null
null
notebooks/Experimental/Ishan/ADP Demo/Data Owner - Canada.ipynb
Noob-can-Compile/PySyft
156cf93489b16dd0205b0058d4d23d56b3a91ab8
[ "Apache-2.0" ]
null
null
null
notebooks/Experimental/Ishan/ADP Demo/Data Owner - Canada.ipynb
Noob-can-Compile/PySyft
156cf93489b16dd0205b0058d4d23d56b3a91ab8
[ "Apache-2.0" ]
null
null
null
42.468296
1,593
0.446735
[ [ [ "### Trade Demo\n\n#### Goal: \n- Load the trade data for the country `Canada`\n- Launch a domain node for canada\n- Login into the domain node\n- Format the `Canada` trade dataset and convert to Numpy array\n- Convert the dataset to a private tensor\n- Upload `Canada's` trade on the domain node\n- Create a Data Scientist User", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2\n\nimport pandas as pd\n\ncanada = pd.read_csv(\"../../trade_demo/datasets/ca - feb 2021.csv\")", "/Users/ishanmishra/PycharmProjects/PySyft/.tox/syft.jupyter/lib/python3.9/site-packages/IPython/core/interactiveshell.py:3441: DtypeWarning: Columns (14) have mixed types.Specify dtype option on import or set low_memory=False.\n exec(code_obj, self.user_global_ns, self.user_ns)\n" ] ], [ [ "### Step 1: Load the dataset\n\nWe have trade data for the country, which has provided data from Feb 2021. They key colums are:\n\n- Commodity Code: the official code of that type of good\n- Reporter: the country claiming the import/export value\n- Partner: the country being claimed about\n- Trade Flow: the direction of the goods being reported about (imports, exports, etc)\n- Trade Value (US$): the declared USD value of the good\n\nLet's have a quick look at the top five rows of the dataset.", "_____no_output_____" ] ], [ [ "canada.head()", "_____no_output_____" ] ], [ [ "### Step 2: Spin up the Domain Node (if you haven't already)\n\nSKIP THIS STEP IF YOU'VE ALREADY RUN IT!!!\n\nAs the main requirement of this demo is to perform analysis on the Canada's trade dataset. So, we need to spin up a domain node for Canada.\n\nAssuming you have [Docker](https://www.docker.com/) installed and configured with >=8GB of RAM, navigate to PySyft/packages/hagrid and run the following commands in separate terminals (can be done at the same time):\n\n\n```bash\n# install hagrid cli tool\npip install -e .\n```\n\n```bash\nhagrid launch Canada domain\n```\n\n<div class=\"alert alert-block alert-info\">\n <b>Quick Tip:</b> Don't run this now, but later when you want to stop these nodes, you can simply run the same argument with the \"stop\" command. So from the PySyft/grid directory you would run. Note that these commands will delete the database by default. Add the flag \"--keep_db=True\" to keep the database around. Also note that simply killing the thread created by ./start is often insufficient to actually stop all nodes. Run the ./stop script instead. To stop the nodes listed above (and delete their databases) run:\n\n```bash\nhagrid land Canada\n```\n</div>", "_____no_output_____" ], [ "### Step 3: Login into the Domain as the Admin User", "_____no_output_____" ] ], [ [ "import syft as sy\n\n# Let's login into the domain node\ndomain_node = sy.login(email=\"[email protected]\", password=\"changethis\", port=8081)", "Connecting to http://localhost:8081... done! \t Logging into adp... done!\n" ], [ "canada.head()", "_____no_output_____" ], [ "canada[canada[\"Partner\"] == \"Egypt\"]", "_____no_output_____" ], [ "# For, simplicity we will upload the first 10000 rows of the dataset.\ncanada = canada[:10000]", "_____no_output_____" ] ], [ [ "### Step 4: Format dataset and convert to numpy array", "_____no_output_____" ] ], [ [ "# In order to the convert the whole dataset into an numpy array,\n# We need to format string to integer values.", "_____no_output_____" ], [ "# Let's create a function that converts string to int.\n\nimport hashlib\nfrom math import isnan, nan\n\nhash_db = {}\nhash_db[nan] = nan\n\n\ndef convert_string(s: str, digits: int = 15):\n \"\"\"Maps a string to a unique hash using SHA, converts it to a hash or an int\"\"\"\n if type(s) is str:\n new_hash = int(hashlib.sha256(s.encode(\"utf-8\")).hexdigest(), 16) % 10 ** digits\n hash_db[s] = new_hash\n return new_hash\n else:\n return s", "_____no_output_____" ], [ "# Let's filter out the string/object type columns\nstring_cols = []\nfor col, dtype in canada.dtypes.items():\n if dtype in ['object', 'str']:\n string_cols.append(col)\n\n# Convert string values to integer\nfor col in canada.columns:\n canada[col] = canada[col].map(lambda x: convert_string(x))", "_____no_output_____" ], [ "# Let's checkout the formatted dataset\ncanada.head()", "_____no_output_____" ], [ "# Great !!! now let's convert the whole dataset to numpy array.\nnp_dataset = canada.values\n\n# Type cast to float values to prevent overflow\nnp_dataset = np_dataset.astype(float) ", "_____no_output_____" ] ], [ [ "### Step 5: Converting the dataset to private tensors", "_____no_output_____" ] ], [ [ "from syft.core.adp.entity import DataSubject", "_____no_output_____" ], [ "# The 'Partner' column i.e the countries to which the data is exported\n# is private, therefore let's create entities for each of the partner defined\n\nentities = [DataSubject(name=partner) for partner in canada[\"Partner\"]]", "_____no_output_____" ], [ "# Let's convert the whole dataset to a private tensor\n\nprivate_dataset_tensor = sy.Tensor(np_dataset).private(0.01, 1e15, entity=DataSubject(name=\"Canada\")).tag(\"private_canada_trade_dataset\")", "_____no_output_____" ], [ "private_dataset_tensor[:, 0]", "_____no_output_____" ] ], [ [ "### Step 6: Upload Canada's trade data on the domain", "_____no_output_____" ] ], [ [ "# Awesome, now let's upload the dataset to the domain.\n# For, simplicity we will upload the first 10000 rows of the dataset.\n\ndomain_node.load_dataset(\n assets={\"feb2020\": private_dataset_tensor},\n name=\"Canada Trade Data - First 10000 rows\",\n description=\"\"\"A collection of reports from Canada's statistics \n bureau about how much it thinks it imports and exports from other countries.\"\"\",\n)", "_____no_output_____" ], [ "private_dataset_tensor.send(domain_node)", "_____no_output_____" ] ], [ [ "Cool !!! The dataset was successfully uploaded onto the domain.", "_____no_output_____" ] ], [ [ "# Now, let's check datasets available on the domain.\ndomain_node.store.pandas", "_____no_output_____" ] ], [ [ "### Step 7: Create a Data Scientist User\n\nOpen http://localhost:8081, login is the root user (username: [email protected], password:changethis), and create a user with the following attributes:\n\n- Name: Sheldon Cooper\n- Email: [email protected]\n- Password: bazinga", "_____no_output_____" ] ], [ [ "# Alternatively, you can create the same from the notebook itself.\ndomain_node.users.create(\n **{\n \"name\": \"Sheldon Cooper\",\n \"email\": \"[email protected]\",\n \"password\": \"bazinga\",\n },\n)", "[2021-08-12T14:22:58.514201-0400][CRITICAL][logger]][44906] UnknownPrivateException has been triggered.\n" ], [ "domain_node.users.create(\n **{\n \"name\": \"Leonard Hodfstadder\",\n \"email\": \"[email protected]\",\n \"password\": \"penny\",\n },\n)", "_____no_output_____" ] ], [ [ "```\nGreat !!! We were successfully able to create a new user.\nNow, let's move to the Data Scientist notebook, to check out their experience.\n```", "_____no_output_____" ], [ "### Step 8: Decline request to download entire datsaet", "_____no_output_____" ] ], [ [ "# Let's check if there are any requests pending for approval.\ndomain_node.requests.pandas", "_____no_output_____" ], [ "domain_node.requests[-1].accept()", "_____no_output_____" ], [ "# Looks like the DS wants to download the whole dataset. We cannot allow that.\n# Let's select and deny this request.\ndomain_node.requests[0].deny()", "_____no_output_____" ] ], [ [ "### STOP: Return to Data Scientist - Canada.ipynb - STEP 3!!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
cbe10968554d2c2042bc982d72c09a628a549e5f
5,093
ipynb
Jupyter Notebook
notebooks/01 - Review of Supervised Learning.ipynb
unhoang/ml-workshop-2-of-4
12aa307e19b9e28f7c7ca94a16a9a00a52a6baa1
[ "MIT" ]
null
null
null
notebooks/01 - Review of Supervised Learning.ipynb
unhoang/ml-workshop-2-of-4
12aa307e19b9e28f7c7ca94a16a9a00a52a6baa1
[ "MIT" ]
null
null
null
notebooks/01 - Review of Supervised Learning.ipynb
unhoang/ml-workshop-2-of-4
12aa307e19b9e28f7c7ca94a16a9a00a52a6baa1
[ "MIT" ]
1
2020-01-27T07:13:58.000Z
2020-01-27T07:13:58.000Z
20.051181
254
0.531907
[ [ [ "# Review of Supervised Learning with scikit-learn", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport sklearn\nsklearn.set_config(print_changed_only=True)", "_____no_output_____" ], [ "# read data.\n# you can find a description in data/bank-campaign-desc.txt\ndata = pd.read_csv(\"data/bank-campaign.csv\")", "_____no_output_____" ], [ "data.shape", "_____no_output_____" ], [ "data.columns", "_____no_output_____" ], [ "data.head()", "_____no_output_____" ], [ "y = data.target", "_____no_output_____" ], [ "X = data.drop(\"target\", axis=1)", "_____no_output_____" ], [ "X.shape", "_____no_output_____" ], [ "y.shape", "_____no_output_____" ], [ "y.head()", "_____no_output_____" ], [ "data.target.value_counts()", "_____no_output_____" ], [ "data.target.value_counts() / data.target.size", "_____no_output_____" ] ], [ [ "Splitting the data:", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=.2, random_state=42, stratify=y)", "_____no_output_____" ], [ "np.sum(y_train == \"yes\") / len(y_train)", "_____no_output_____" ], [ "np.sum(y_test == \"yes\") / len(y_test)", "_____no_output_____" ], [ "# import model\nfrom sklearn.linear_model import LogisticRegression\n# instantiate model, set parameters\nlr = LogisticRegression(C=0.1)\n# fit model\nlr.fit(X_train, y_train)", "_____no_output_____" ] ], [ [ "Make predictions:", "_____no_output_____" ] ], [ [ "lr.score(X_train, y_train)", "_____no_output_____" ], [ "(y_train == \"no\").mean()", "_____no_output_____" ], [ "lr.score(X_test, y_test)", "_____no_output_____" ] ], [ [ "# Exercise\nLoad the dataset ``data/bike_day_raw.csv``, which has the regression target ``cnt``.\nThis dataset is hourly bike rentals in the citybike platform. The ``cnt`` column is the number of rentals, which we want to predict from date and weather data.\n\nSplit the data into a training and a test set using ``train_test_split``.\nUse the ``LinearRegression`` class to learn a regression model on this data. You can evaluate with the ``score`` method, which provides the $R^2$ or using the ``mean_squared_error`` function from ``sklearn.metrics`` (or write it yourself in numpy).", "_____no_output_____" ] ], [ [ "# %load solutions/bike_regression.py", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cbe109c429a26ebf9a05f218027903a6eec5e4e7
24,251
ipynb
Jupyter Notebook
notebooks/verify-datasets.ipynb
agriculture-vlab/agriculture-vlab
039ba44f0c2e0b766ca05d827351e5e2205503f8
[ "MIT" ]
null
null
null
notebooks/verify-datasets.ipynb
agriculture-vlab/agriculture-vlab
039ba44f0c2e0b766ca05d827351e5e2205503f8
[ "MIT" ]
4
2021-11-15T16:05:26.000Z
2022-03-22T17:07:51.000Z
notebooks/verify-datasets.ipynb
agriculture-vlab/agriculture-vlab
039ba44f0c2e0b766ca05d827351e5e2205503f8
[ "MIT" ]
null
null
null
49.190669
106
0.64253
[ [ [ "import numpy as np\nimport xarray as xr\n\nfrom xcube.core.store import new_data_store\nfrom avl.verify import verify_dataset, ERROR", "_____no_output_____" ], [ "bucket_name = 'agriculture-vlab-data-staging'", "_____no_output_____" ], [ "store = new_data_store('s3', root=bucket_name, max_depth=5, storage_options=dict(anon=True))\n# list(store.get_data_ids())", "_____no_output_____" ], [ "\nstore = new_data_store('s3', \n root='agriculture-vlab-data-staging',\n max_depth=5, \n storage_options=dict(anon=True))\nds = store.open_data(\"avl/l2a-s1/bel/S1_L2_COH_VV_31UFR.zarr\", \n decode_cf=False)\nnp.all(ds.x.diff(dim='x') > 0), np.all(ds.y.diff(dim='y') < 0)", "_____no_output_____" ], [ "ds.x.values", "_____no_output_____" ], [ "report = {}\nfor data_id in store.get_data_ids():\n try:\n # We use xarray to open the cube with \n #store = s3fs.S3Map(f'{bucket_name}/{data_id}', s3=s3)\n #cube = xr.open_zarr(store, decode_cf=False) \n dataset = store.open_data(data_id, decode_cf=False)\n issues = verify_dataset(dataset, level=ERROR)\n if not issues:\n print(f\"Dataset {data_id}: OK\")\n else:\n print(f\"Dataset {data_id}: ERROR\")\n report[data_id] = issues\n except Exception as e:\n print(f\"Error for {data_id!r}: {e}\")\n\nreport", "Dataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UCQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UCR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UDQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UDR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UDS.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UDT.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UDU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UEQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UER.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UES.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UET.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UEU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UFQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UFR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UFS.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UFT.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UFU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UGQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UGR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UGS.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UGT.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_31UGU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32ULA.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32ULB.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32ULC.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32ULD.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32ULV.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32UMA.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32UMB.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32UMC.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32UMD.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32UMV.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32UNA.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32UNB.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32UNC.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VH_32UND.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UCQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UCR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UDQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UDR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UDS.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UDT.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UDU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UEQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UER.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UES.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UET.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UEU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UEV.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UFQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UFR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UFS.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UFT.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UFU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UGQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UGR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UGS.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UGT.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UGU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_31UGV.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32ULA.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32ULB.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32ULC.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32ULD.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32ULE.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32ULV.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32UMA.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32UMB.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32UMC.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32UMD.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32UMV.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32UNA.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32UNB.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32UNC.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_BCK_VV_32UND.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UCR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UDQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UDR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UDS.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UDT.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UEQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UER.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UES.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UET.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UEU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UFQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UFR.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UFS.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UFT.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UFU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UGR.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UGS.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UGT.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_31UGU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32ULA.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32ULB.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32ULC.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32ULD.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32UMA.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32UMB.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32UMC.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32UMD.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32UMV.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32UNA.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32UNB.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32UNC.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VH_32UND.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UCR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UDQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UDR.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UDS.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UDT.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UEQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UER.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UES.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UET.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UEU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UFQ.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UFR.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UFS.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UFT.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UFU.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UGR.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UGS.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UGT.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_31UGU.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32ULA.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32ULB.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32ULC.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32ULD.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32UMA.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32UMB.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32UMC.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32UMD.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32UMV.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32UNA.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32UNB.zarr: OK\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32UNC.zarr: ERROR\nDataset avl/l2a-s1/bel/S1_L2_COH_VV_32UND.zarr: OK\nDataset avl/l2a-s1/fra/S1_L2_BCK_VH_30TWT.zarr: OK\nDataset avl/l2a-s1/fra/S1_L2_BCK_VH_30TXT.zarr: OK\nDataset avl/l2a-s1/fra/S1_L2_BCK_VV_30TWT.zarr: OK\nDataset avl/l2a-s1/fra/S1_L2_BCK_VV_30TXT.zarr: OK\nDataset avl/l2a-s1/fra/S1_L2_COH_VH_30TWT.zarr: ERROR\nDataset avl/l2a-s1/fra/S1_L2_COH_VH_30TXT.zarr: ERROR\nDataset avl/l2a-s1/fra/S1_L2_COH_VV_30TWT.zarr: ERROR\nDataset avl/l2a-s1/fra/S1_L2_COH_VV_30TXT.zarr: ERROR\nDataset avl/l2comp/2019/bel/S1_L2COMP_BCK_ASC_VH_W_31UFR.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_BCK_ASC_VH_W_31UFS.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_BCK_ASC_VV_W_31UFR.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_BCK_ASC_VV_W_31UFS.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_BCK_DESC_VH_W_31UFR.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_BCK_DESC_VH_W_31UFS.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_BCK_DESC_VV_W_31UFR.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_BCK_DESC_VV_W_31UFS.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_COHE_ASC_VH_W_31UFR.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_COHE_ASC_VH_W_31UFS.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_COHE_ASC_VV_W_31UFR.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_COHE_ASC_VV_W_31UFS.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_COHE_DESC_VH_W_31UFR.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_COHE_DESC_VH_W_31UFS.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_COHE_DESC_VV_W_31UFR.zarr: OK\nDataset avl/l2comp/2019/bel/S1_L2COMP_COHE_DESC_VV_W_31UFS.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_BCK_ASC_VH_W_30TWT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_BCK_ASC_VH_W_30TXT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_BCK_ASC_VV_W_30TWT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_BCK_ASC_VV_W_30TXT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_BCK_DESC_VH_W_30TWT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_BCK_DESC_VH_W_30TXT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_BCK_DESC_VV_W_30TWT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_BCK_DESC_VV_W_30TXT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_COHE_ASC_VH_W_30TWT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_COHE_ASC_VH_W_30TXT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_COHE_ASC_VV_W_30TWT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_COHE_ASC_VV_W_30TXT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_COHE_DESC_VH_W_30TWT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_COHE_DESC_VH_W_30TXT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_COHE_DESC_VV_W_30TWT.zarr: OK\nDataset avl/l2comp/2019/fra/S1_L2COMP_COHE_DESC_VV_W_30TXT.zarr: OK\nDataset avl/l3b/2020/bel/S2_L3B_FAPAR_31UFR.zarr: OK\nDataset avl/l3b/2020/bel/S2_L3B_FAPAR_31UFS.zarr: OK\nDataset avl/l3b/2020/bel/S2_L3B_FCOVER_31UFR.zarr: OK\nDataset avl/l3b/2020/bel/S2_L3B_FCOVER_31UFS.zarr: OK\nDataset avl/l3b/2020/bel/S2_L3B_LAI_31UFR.zarr: OK\nDataset avl/l3b/2020/bel/S2_L3B_LAI_31UFS.zarr: OK\nDataset avl/l3b/2020/bel/S2_L3B_NDVI_31UFR.zarr: OK\nDataset avl/l3b/2020/bel/S2_L3B_NDVI_31UFS.zarr: OK\nDataset avl/l3b/bel/S2_L3B_FAPAR_31UFR.zarr: OK\nDataset avl/l3b/bel/S2_L3B_FAPAR_31UFS.zarr: ERROR\nDataset avl/l3b/bel/S2_L3B_FCOVER_31UFR.zarr: OK\nDataset avl/l3b/bel/S2_L3B_FCOVER_31UFS.zarr: ERROR\nDataset avl/l3b/bel/S2_L3B_LAI_31UFR.zarr: OK\nDataset avl/l3b/bel/S2_L3B_LAI_31UFS.zarr: ERROR\nDataset avl/l3b/bel/S2_L3B_NDVI_31UFR.zarr: OK\nDataset avl/l3b/bel/S2_L3B_NDVI_31UFS.zarr: ERROR\nDataset avl/l3b/fra/S2_L3B_FAPAR_30TWT.zarr: OK\nDataset avl/l3b/fra/S2_L3B_FAPAR_30TXT.zarr: OK\nDataset avl/l3b/fra/S2_L3B_FCOVER_30TWT.zarr: OK\nDataset avl/l3b/fra/S2_L3B_FCOVER_30TXT.zarr: OK\nDataset avl/l3b/fra/S2_L3B_LAI_30TWT.zarr: OK\nDataset avl/l3b/fra/S2_L3B_LAI_30TXT.zarr: OK\nDataset avl/l3b/fra/S2_L3B_NDVI_30TWT.zarr: OK\nDataset avl/l3b/fra/S2_L3B_NDVI_30TXT.zarr: OK\n" ], [ "import json\nwith open(\"dataset-verification-details.json\", \"w\") as fp:\n json.dump(report, fp, indent=2)", "_____no_output_____" ] ], [ [ "---\n\n", "_____no_output_____" ] ], [ [ "import s3fs\ns3 = s3fs.S3FileSystem(anon=False)\nstore = s3fs.S3Map('agriculture-vlab-data-staging/avl/l2a-s1/bel/S1_L2_COH_VV_31UFR.zarr', s3=s3)\nds = xr.open_zarr(store)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cbe11347551426ef637f39b4e788d65213091224
42,843
ipynb
Jupyter Notebook
vypin/vishal/Training.ipynb
talasila/amazon-sagemaker-architecting-for-ml
11953ae6a2cf9bbe00ac20c3dc71da333a438de1
[ "MIT" ]
null
null
null
vypin/vishal/Training.ipynb
talasila/amazon-sagemaker-architecting-for-ml
11953ae6a2cf9bbe00ac20c3dc71da333a438de1
[ "MIT" ]
null
null
null
vypin/vishal/Training.ipynb
talasila/amazon-sagemaker-architecting-for-ml
11953ae6a2cf9bbe00ac20c3dc71da333a438de1
[ "MIT" ]
null
null
null
63.471111
7,288
0.632239
[ [ [ "import boto3\nimport sagemaker\nimport pandas as pd\nfrom sagemaker import get_execution_role\nfrom sagemaker.amazon.amazon_estimator import get_image_uri\nfrom sagemaker import RandomCutForest\n\nbucket = 'anomaly-detection-team-vypin' # <--- specify a bucket you have access to\nprefix = 'vishal/sagemaker/rcf-benchmarks'\n\n\ns3_training_data_location='s3://anomaly-detection-team-vypin/vishal/train.csv'\ncleaned_data=pd.read_csv(s3_training_data_location)\ncleaned_data.shape", "_____no_output_____" ], [ "session=sagemaker.Session()\nexecution_role = get_execution_role()\n\ntrain_data = sagemaker.s3_input(\n s3_data=s3_training_data_location,\n content_type='text/csv;label_size=0',\n distribution='ShardedByS3Key')\n\n# specify general training job information\nrcf = RandomCutForest(role=execution_role,\n train_instance_count=1,\n train_instance_type='ml.m4.xlarge',\n base_job_name='vishal',\n data_location='s3://{}/{}/'.format(bucket, prefix),\n output_path='s3://{}/{}/output'.format(bucket, prefix),\n num_samples_per_tree=512,\n num_trees=50)\n\nrcf.fit(rcf.record_set(cleaned_data.as_matrix()))\n#rcf.fit({'train': train_data})", "INFO:sagemaker:Creating training-job with name: vishal-2019-03-07-18-30-38-812\n" ], [ "rcf_inference = rcf.deploy(\n initial_instance_count=1,\n instance_type='ml.m4.xlarge',\n)\n\nprint('Endpoint name: {}'.format(rcf_inference.endpoint))", "INFO:sagemaker:Creating model with name: randomcutforest-2019-03-07-18-35-52-893\nINFO:sagemaker:Creating endpoint with name vishal-2019-03-07-18-30-38-812\n" ], [ "from sagemaker.predictor import csv_serializer, json_deserializer\n\nrcf_inference.content_type = 'text/csv'\nrcf_inference.serializer = csv_serializer\nrcf_inference.accept = 'application/json'\nrcf_inference.deserializer = json_deserializer\n\ncleaned_data_numpy = cleaned_data.as_matrix()\nprint(cleaned_data_numpy[:6])\n", "[[5.22000000e+02 4.06348000e+03 2.01730000e+04 1.61095200e+04\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 1.00000000e+00 0.00000000e+00]\n [2.75000000e+02 9.83906350e+05 0.00000000e+00 0.00000000e+00\n 1.00395351e+06 1.98785986e+06 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 1.00000000e+00]\n [3.60000000e+01 3.88991900e+04 0.00000000e+00 0.00000000e+00\n 1.24649240e+05 1.63548430e+05 0.00000000e+00 1.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00]\n [3.58000000e+02 1.80673400e+04 4.23778000e+05 4.05710660e+05\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 1.00000000e+00 0.00000000e+00]\n [1.70000000e+01 4.24320010e+05 1.59407000e+05 0.00000000e+00\n 0.00000000e+00 2.07061960e+05 0.00000000e+00 1.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00]\n [4.03000000e+02 1.34374500e+04 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 1.00000000e+00 0.00000000e+00]]\n" ], [ "results = rcf_inference.predict(cleaned_data_numpy[:6])", "_____no_output_____" ], [ "s3_validation_data_location='s3://anomaly-detection-team-vypin/vishal/validation.csv'\ns3_validation_results_location='s3://anomaly-detection-team-vypin/vishal/batchtransofrm_results'\n# Initialize the transformer object\ntransformer = rcf.transformer(\n instance_type='ml.c4.xlarge',\n instance_count=1,\n strategy='MultiRecord',\n assemble_with='Line',\n output_path=s3_validation_results_location\n )\n# Start a transform job\ntransformer.transform(s3_validation_data_location, content_type='text/csv', split_type='Line')\n# Then wait until the transform job has completed\ntransformer.wait()\n\n", "INFO:sagemaker:Creating model with name: vishal-2019-03-07-18-30-38-812\nINFO:sagemaker:Creating transform job with name: vishal-2019-03-07-18-42-19-306\n" ], [ "import json\n\ns3 = boto3.resource('s3')\ns3.Bucket('anomaly-detection-team-vypin').download_file('vishal/batchtransofrm_results/validation.csv.out', 'validation.csv.out')\n\n#results=pd.read_csv('s3://anomaly-detection-team-vypin/vishal/batchtransofrm_results/validation.csv.out')", "_____no_output_____" ], [ "import sys\nfo = open(\"validation.csv.out\", \"r\")\nresults=fo.readlines()", "_____no_output_____" ], [ "\nscores = [json.loads(datum)['score'] for datum in results]\n", "_____no_output_____" ], [ "validation_data=pd.read_csv('s3://anomaly-detection-team-vypin/vishal/validation_full_data.csv')", "_____no_output_____" ], [ "#validation_data.head()\nvalidation_data.shape", "_____no_output_____" ], [ "validation_data['score']=scores\n", "_____no_output_____" ], [ "validation_data.head()", "_____no_output_____" ], [ "score_vs_fraud=validation_data[['isFraud','score']]", "_____no_output_____" ], [ "score_vs_fraud.head()", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\nscore_vs_fraud.plot(kind='scatter',x='isFraud',y='score')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe1179d109b757d09c1b290005139820a16c2a0
105,888
ipynb
Jupyter Notebook
Pseudomodular_Lab.ipynb
carmengg/pseudomodular_groups
7f15db4d2981145ce26ef27bfbd427292d507134
[ "MIT" ]
null
null
null
Pseudomodular_Lab.ipynb
carmengg/pseudomodular_groups
7f15db4d2981145ce26ef27bfbd427292d507134
[ "MIT" ]
null
null
null
Pseudomodular_Lab.ipynb
carmengg/pseudomodular_groups
7f15db4d2981145ce26ef27bfbd427292d507134
[ "MIT" ]
null
null
null
38.972396
245
0.394917
[ [ [ "import math\nimport random\nfrom array import *\nfrom math import gcd as bltin_gcd\nfrom fractions import Fraction\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n#import RationalMatrices as Qmtx", "_____no_output_____" ], [ "##########################################\n ###### Methods for Qmatrix #####\n# --------------------------------------------\ndef printQmtx(M):\n print('(' , M[0,0],' ', M[0,1], ')')\n print('(' , M[1,0],' ', M[1,1], ')')\n return\n \n# --------------------------------------------\ndef det(M):\n return M[0,0]*M[1,1]-M[1,0]*M[0,1]\n\n# --------------------------------------------\ndef tr(M):\n return M[0,0]+M[1,1]\n\n\n# --------------------------------------------\ndef multiply(N,M):\n# Returns the product NM, each entry in N, M and NM is Fraction\n a1=M[0,0].numerator\n b1=M[0,0].denominator\n\n a2=M[0,1].numerator\n b2=M[0,1].denominator \n\n a3=M[1,0].numerator\n b3=M[1,0].denominator\n \n a4=M[1,1].numerator\n b4=M[1,1].denominator\n \n c1=N[0,0].numerator\n d1=N[0,0].denominator\n\n c2=N[0,1].numerator\n d2=N[0,1].denominator \n\n c3=N[1,0].numerator\n d3=N[1,0].denominator\n \n c4=N[1,1].numerator\n d4=N[1,1].denominator\n \n R00 = Fraction(a1*d2*c1*b3 + a3*b1*c2*d1 , d1*d2*b1*b3)\n R01 = Fraction(a2*c1*d2*b4 + c2*a4*b2*d1 , b2*d1*d2*b4)\n R10 = Fraction(a1*b3*c3*d4 + a3*b1*c4*d3 , d3*d4*b1*b3)\n R11 = Fraction(a2*c3*b4*d4 + c4*a4*b2*d3 , b2*b4*d3*d4)\n \n return np.matrix( [ (R00,R01) , (R10, R11) ] )\n\n# --------------------------------------------\ndef mult(k,M):\n a1=M[0,0].numerator\n b1=M[0,0].denominator\n\n a2=M[0,1].numerator\n b2=M[0,1].denominator \n\n a3=M[1,0].numerator\n b3=M[1,0].denominator\n \n a4=M[1,1].numerator\n b4=M[1,1].denominator\n\n return np.matrix( [ (Fraction(k*a1,b1),Fraction(k*a2,b2)) , ( Fraction(k*a3,b3), Fraction(k*a4,b4))] ) \n\n# --------------------------------------------\ndef inverse(M):\n a1=M[0,0].numerator\n b1=M[0,0].denominator\n\n a2=M[0,1].numerator\n b2=M[0,1].denominator \n\n a3=M[1,0].numerator\n b3=M[1,0].denominator\n \n a4=M[1,1].numerator\n b4=M[1,1].denominator\n \n dnum = a1*a4*b2*b3-a2*a3*b1*b4 # Numerator and denominator of determinant\n ddem = b1*b2*b3*b4\n \n N = np.matrix([(Fraction(dnum*a4,ddem*b4) ,Fraction(-dnum*a2,ddem*b2)),(Fraction(-dnum*a3,ddem*b3) ,Fraction(dnum*a1,ddem*b1))])\n \n return N", "_____no_output_____" ], [ "def mob_transf(M, a):\n # Mobius transofrmation associated to matrix M, where \n # M has all type Fraction entries (rational)\n # a must be Fraction or string INF\n # a is assumed to be rational on x-axis (imaginary coord =0)\n # returns a Fraction or string INF if it sends a to oo \n \n a1=M[0,0].numerator\n b1=M[0,0].denominator\n \n \n a3=M[1,0].numerator\n b3=M[1,0].denominator\n \n if( a == \"INF\"):\n if (a3 == 0):\n return \"INF\"\n else:\n return Fraction(a1*b3, a3*b1) \n \n x=a.numerator\n y=a.denominator\n \n a4=M[1,1].numerator\n b4=M[1,1].denominator\n \n if (a3*b4*x + a4*b3*y) ==0:\n return \"INF\"\n \n a2=M[0,1].numerator\n b2=M[0,1].denominator\n \n \n # print('type of matrix entry', type (M[0,0]))\n p=(b3*b4*y)*(a1*b2*x + a2*b1*y)\n q=(b1*b2*y)*(a3*b4*x + a4*b3*y)\n# print('p=',p)\n# print('q=',q)\n# return Decimal(p/q)\n return Fraction(p,q)\n\n\n# --------------------------------------------\ndef sends2inf(M, a):\n # the type of both M and x is Fraction\n # x is assumed to be rational on (imaginary coord =0)\n # returns a Fraction\n x=a.numerator\n y=a.denominator\n \n a3=M[1,0].numerator\n b3=M[1,0].denominator\n \n a4=M[1,1].numerator\n b4=M[1,1].denominator\n \n if (a3*b4*x + a4*b3*y) ==0:\n return True\n else:\n return False\n \n# --------------------------------------------\ndef toinfelement(M):\n \n a3=M[1,0].numerator\n b3=M[1,0].denominator\n \n a4=M[1,1].numerator\n b4=M[1,1].denominator\n\n return Fraction(-a4*b3,b4*a3)\n\n\n", "_____no_output_____" ], [ "class jigsawset:\n # the jigsaw will be formed with triangles from the jigsaw set\n # it only admits at most two different types of tiles.\n \n def __init__(self, tiles=[1,2], sign=[1,0]): \n #Default jigsaw is generated by Delta(1,1,1) in canonical position\n jigsawset.tiles=tiles # types of the tiles \n jigsawset.sign=sign # number of tiles of each type\n \n #Length of fundamental interval of group generated by self\n jigsawset.L = l=self.sign[0]*(2+self.tiles[0]) +self.sign[1]*(2+self.tiles[1])\n\n def size(self): # numer of triangles in the jigsawset (with multiplicity)\n return self.sign[0]+self.sign[1]\n \n def print(self):\n print('************** JIGSAW.print ******************')\n print(\"tile types:\", self.tiles)\n print(\"signature:\", self.sign)\n print('************** ************ ******************')\n print('')", "_____no_output_____" ], [ "################################################################################\ndef Jigsaw_vertices(jigsawset): \n# Returns the x-coords of the vertices of the jigsaw formed by tiles glued from jigsawset \n# assuming they all have inf as a common vertex and a Delta(1) is in standard position\n# Coords go from negative to positive.\n# vertex at infinity is not included in the list\n# Type of vertices is integer\n\n vertices=[-1,0] #Jigsaw always has the tile [infty, -1,0]\n i=1\n while i<jigsawset.sign[0]: #First glue all 1-tiles to the left (negative vertices)\n vertices.insert(0,-(i+1))\n i+=1 \n j=0\n while j<jigsawset.sign[1]: #Then glue all n-tiles to the right (positive vertices)\n if (j%3 != 1):\n vertices.append(vertices[i]+1)\n if(j%3 ==1):\n vertices.append(vertices[i]+jigsawset.tiles[1])\n i+=1\n j+=1\n return vertices\n# ################################################################################\n ###### TEST for Jigsaw_vertices #####\n# JS= jigsawset([1,2],[4,6])\n# JS.print()\n# Jigsaw_vertices(JS)\n\n\n\n", "_____no_output_____" ], [ "################################################################################\n################################################################################\n\n# ......... rotation_info(n, v2,v3) .........\n# Say (m,y) is the (unknown) point of rotation of the geodesic [v2,v3] with side type k,\n# the function returns (m,y^2), m and y^2 are Fraction type\n# This is done to have only integer values, since y is often a square root\n# Uses proposition 4.3 to consider different cases according to side_type.\n# v2,v3 = vertices of ideal side, assumed to come from tiles of the type [infty, v2, v3]\n# n = type of the side [v2,v3]\n# isfrac = whether the distance of the rotation point from midpoint is n or 1/n, \n# both are considered type n, so we need to specify if it is a fraction\n\n\ndef rotation_info(n,isfrac,v2,v3): #renamed from info_for_rotation\n l= v3-v2\n if(n==1): \n #side_type==1 => edge [v2, v3] is a semi-circle of diameter n (n=type of triangle)\n return ( Fraction(2*v2+l,2) , Fraction(l*l,4) ) \n \n if(isfrac == False): #Input n represents the integer n>1\n #side_type>1 => edge [v2, v3] is a semi-circle of diameter 1\n return ( Fraction(n+(1+n)*v2,1+n), Fraction(n,(1+n)*(1+n)) )\n \n if(isfrac == True): #Input n represents the fraction 1/n \n #side_type>1 => edge [v2, v3] is a semi-circle of diameter 1\n return ( Fraction(1+(1+n)*v2,1+n), Fraction(n,(1+n)*(1+n)) )\n\n \n################################################################################\n################################################################################\n\n\ndef rotation_points(jigsawset): \n #Given jigsaw set returns a list in CCW order with the rotation points on exterior sides\n # ** The y-coord of every point is the square of the actual coordinate **\n # renamed from info_rotation_points\n \n V = Jigsaw_vertices(jigsawset)\n \n #By construction first midpoint is on vertical side of a type 1 tile. \n points=[(Fraction(V[0]),Fraction(1))] \n i=0\n \n # Add all midpoints of type 1 tiles\n N=jigsawset.sign[0]\n while i<N: \n points.append(rotation_info(1,0,V[i],V[i+1]))\n i+=1 \n \n # Now add all midpoints of type n tiles\n # taking gluing rotation into account (prop 4.3)\n \n N+=jigsawset.sign[1] \n j=1\n while i<N: \n if(j%3==1):\n type=jigsawset.tiles[1]\n isfrac= True\n if(j%3==2):\n type=1\n isfrac = False\n if(j%3==0):\n type=jigsawset.tiles[1]\n isfrac = False\n \n points.append(rotation_info(type,isfrac,V[i],V[i+1]))\n i+=1\n j+=1 \n \n # Last midpoint is from vertical side \n if(jigsawset.sign[1]==0):\n points.append((Fraction(V[i]),Fraction(1)))\n \n else: # The right vertical side of the last tile you glued (prop 4.3 - 5)\n j= j-1\n if(j%3==0):\n points.append( (Fraction(V[i]) , Fraction(1)) )\n else:\n points.append( (Fraction(V[i]) , Fraction(jigsawset.tiles[1],1)) )\n\n return points\n\n# ################################################################################\n#JS= jigsawset([1,2],[1,0])\n#JS.print()\n\n#R = rotation_points(JS)\n\n#print('********* ROTATION POINTS WITH INFO *********')\n#print('recall y-coord is the square of the actual coordinate')\n#for i in range (0,JS.size()+2):\n# print('(' , R[i][0],',', R[i][1], ')')\n\n", "_____no_output_____" ], [ "#################################################################################\ndef pi_rotation_special(x,y2):\n # Given the point (x,y^2) returns the matrix representing pi rotation about (x,y)\n # This can be calculated to be:\n # ( -x y^2+x^2 )\n # ( -1 x )\n # Matrix is in GL(2,Q) (det may not be 1). that's ok since we only use it as a mob transf\n # Coordinates of matrix are type Fraction, so assumes inputs are integers\n \n Rotation = np.matrix( [ (Fraction(-x),Fraction(y2+x*x)) , (Fraction(-1), Fraction(x))] )\n \n return Rotation \n\n\n#################################################################################\n ###### TEST FOR pi_rotation_special #####\n# print('---------------')\n# Q= pi_rotation_special(Fraction(-1,2),Fraction(1,4)) # <--- recall y is squared for this function\n# printQmtx(Q)", "_____no_output_____" ], [ "################################################################################\n\ndef jigsaw_generators(jigsawset):\n # Returns a list TAU with the matrices that represent rotations around \n # midpoints of exterior sides of jigsaw formed by jigsaw set\n # coordinates of the matrices are type Fraction\n # renamed from jigsaw_generators_Q\n \n P = rotation_points(jigsawset)\n N = jigsawset.size()\n TAU=[]\n for i in range (0, N+2):\n TAU.append(pi_rotation_special(P[i][0],P[i][1]))\n return TAU\n\n################################################################################\n ###### TEST for jigsaw_generators #####\nJS= jigsawset([1,2],[1,1])\nJS.print()\n\nQ = rotation_points(JS)\n\nprint('')\n\nprint('********* ROTATION POINTS WITH INFO *********')\nprint('recall y-coord is the square of the actual coordinate')\nfor i in range (0,JS.size()+2):\n print('(' , Q[i][0],',', Q[i][1], ')')\n \nprint('')\n\nTAU = jigsaw_generators(JS)\n \nprint('')\nprint('**************************************************')\nfor i in range (0,JS.size() +2):\n print('rotation about', '(' , Q[i][0],', sqrt(', Q[i][1], ') ) ' , 'is')\n print('T',i, '=')\n printQmtx(TAU[i])\n print('***')\n ", "************** JIGSAW.print ******************\ntile types: [1, 2]\nsignature: [1, 1]\n************** ************ ******************\n\n\n********* ROTATION POINTS WITH INFO *********\nrecall y-coord is the square of the actual coordinate\n( -1 , 1 )\n( -1/2 , 1/4 )\n( 1/3 , 2/9 )\n( 1 , 2 )\n\n\n**************************************************\nrotation about ( -1 , sqrt( 1 ) ) is\nT 0 =\n( 1 2 )\n( -1 -1 )\n***\nrotation about ( -1/2 , sqrt( 1/4 ) ) is\nT 1 =\n( 1/2 1/2 )\n( -1 -1/2 )\n***\nrotation about ( 1/3 , sqrt( 2/9 ) ) is\nT 2 =\n( -1/3 1/3 )\n( -1 1/3 )\n***\nrotation about ( 1 , sqrt( 2 ) ) is\nT 3 =\n( -1 3 )\n( -1 1 )\n***\n" ], [ "def calculateToInf(vertex,generator): \n # Returns an array transf where \n # transf[i][0] = sends vertex[i] to infinity\n # Not optimized\n \n transf = []\n n = len(generator)\n \n for i in range (0,n-1): # There is one less vertex than generators\n word = 0\n M = np.matrix([(Fraction(1), Fraction(0)), (Fraction(0),Fraction(1))])\n for j in range (i+1,n):\n M = multiply(generator[j],M)\n word = (j+1)*10**(j-i-1) + word # generators indices start from 1 when printed\n transf.append((M,word))\n #print(word)\n if(sends2inf(M,vertex[i]) == False):\n print('error', i)\n \n return transf", "_____no_output_____" ], [ "################################################################################\n\nclass JigsawGroup (object):\n def __init__(self, tiles=[1,2], sign=[1,0]): \n #Default group is the one generated by canonical Delta(1,1,1)\n \n JigsawGroup.tiles = tiles\n JigsawGroup.sign = sign\n JigsawGroup.Jset = jigsawset(tiles,sign)\n \n # Following attributes are shared with WeirGroup class\n\n JigsawGroup.rank = sign[0]+sign[1]+2 #Generators = number of exterior sides of jigsaw\n JigsawGroup.vertices = Jigsaw_vertices(self.Jset)\n JigsawGroup.pts_Y2 = rotation_points(self.Jset)\n JigsawGroup.generators = jigsaw_generators(self.Jset)\n\n #? don't remember what this does\n JigsawGroup.RotationsToInf = calculateToInf(self.vertices, self.generators)\n\n #Length of fundamental interval of group, calculated using Lou, Tan & Vo 4.5\n JigsawGroup.L = self.Jset.sign[0]*(2+self.Jset.tiles[0]) +self.Jset.sign[1]*(2+self.Jset.tiles[1])\n \n def print(self):\n print(' ****** print Jigsaw Group ******')\n print(' ')\n print('This group comes from a jigsaw with ', self.sign[0],' tiles of type', self.tiles[0])\n print(' and', self.sign[1],'tiles of type', self.tiles[1],'.')\n print('Length of fund interval = ', self.L)\n print(\"Number of generators:\",self.rank, '. These are:')\n print(' ')\n for i in range (0,self.rank):\n print('rotation about', '(' , self.pts_Y2[i][0],', sqrt(', self.pts_Y2[i][1], ') ) ' , 'is')\n print('T',i+1, '=')\n printQmtx(self.generators[i])\n #det=detQmatrix(self.generators[i])\n #print('det(T',i,')=', det)\n print('')\n print('The jigsaw has vertices (apart from oo):')\n for i in range(0, len(self.vertices)):\n print('(',self.vertices[i], ',0)')\n return \n \n def printNOGENS(self):\n print(' ****** print Jigsaw Group ******')\n print(' ')\n print('This group comes from a jigsaw with ', self.sign[0],' tiles of type', self.tiles[0])\n print(' and', self.sign[1],'tiles of type', self.tiles[1],'.')\n print('Length of fund interval = ', self.L)\n print(\"Number of generators:\",self.rank)\n print(' ')\n print('The jigsaw has vertices (apart from oo):')\n print(self.vertices)\n return\n \n def printSet(self):\n self.Jset.print()\n\n################################################################################\n ##### CHECK Jigsawgroup class ####\nJG= JigsawGroup([1,2],[1,1])\nJG.print()\n\nprint('***********')\nprint('The words of the transformations that send vertices to oo')\nfor i in range (0,JG.rank-1):\n print(JG.RotationsToInf[i][1])", " ****** print Jigsaw Group ******\n \nThis group comes from a jigsaw with 1 tiles of type 1\n and 1 tiles of type 2 .\nLength of fund interval = 7\nNumber of generators: 4 . These are:\n \nrotation about ( -1 , sqrt( 1 ) ) is\nT 1 =\n( 1 2 )\n( -1 -1 )\n\nrotation about ( -1/2 , sqrt( 1/4 ) ) is\nT 2 =\n( 1/2 1/2 )\n( -1 -1/2 )\n\nrotation about ( 1/3 , sqrt( 2/9 ) ) is\nT 3 =\n( -1/3 1/3 )\n( -1 1/3 )\n\nrotation about ( 1 , sqrt( 2 ) ) is\nT 4 =\n( -1 3 )\n( -1 1 )\n\nThe jigsaw has vertices (apart from oo):\n( -1 ,0)\n( 0 ,0)\n( 1 ,0)\n***********\nThe words of the transformations that send vertices to oo\n432\n43\n4\n" ], [ "# SPECIAL EXAMPLE: WEIRSTRASS GROUPS\n\n################################################################################\ndef generatorsWeirGroup(k1,k2,k3):\n # Calculates generators according to equation (2) in paper\n # Determinant may not be 1, and type of entries is Fraction\n T1 = np.matrix( [(k1, 1+k1),(-k1,-k1)])\n T2 = np.matrix( [(1, 1),(-k2-1,-1)])\n T3 = np.matrix( [(0, k3),(-1,0)])\n \n return [T1, T2, T3]\n\ndef info_rotation_points_Wgrp(k1,k2,k3): \n # Given k1,k2,k3 Fractions, returns a list in CCW order with the rotation points on exterior sides\n # y-coordinate is squared to avoid floating point error\n # Calculations come from equation (1) in paper\n x1 = (Fraction(-1,1),Fraction(k1.denominator,k1.numerator))\n \n a2 = k2.numerator\n b2 = k2.denominator\n x2 = (Fraction(-b2,a2+b2), Fraction(b2*a2 , b2*b2+2*a2*b2+a2*a2))\n \n x3 = (Fraction(0,1),Fraction(k3.numerator,k3.denominator))\n \n return [x1, x2, x3]\n\n################################################################################\n\nclass WeirGroup (object):\n def __init__(self, k2=Fraction(1,1), k3=Fraction(1,1)): \n #Default group is the one generated by canonical Delta(1,1,1)\n # k1, k2, k3 are fractions\n WeirGroup.k2 = k2\n WeirGroup.k3 = k3\n WeirGroup.k1 = Fraction(k2.denominator*k3.denominator,k2.numerator*k3.numerator)\n \n # The following attributes are shared with JigsawGroup class\n \n WeirGroup.rank = 3 #Generators = number of exterior sides of jigsaw \n WeirGroup.vertices = [-1,0] #Vertices of triangle are -1,0, inf\n WeirGroup.pts_Y2 = info_rotation_points_Wgrp(self.k1, self.k2, self.k3)\n WeirGroup.generators = generatorsWeirGroup(self.k1,self.k2,self.k3)\n\n WeirGroup.RotationsToInf = calculateToInf(self.vertices, self.generators)\n \n WeirGroup.L = np.absolute(1 + k3+ k2*k3) #Length of fundamental interval of group\n \n# def L(self):\n# return self.Length\n \n def print(self):\n print(' ****** print Weirstrass Group ******')\n print( ' ')\n print('This is the Weirstrass group with parmameters k1=',self.k1,', k2=', self.k2,', k3=', self.k3,'.')\n print('Length of fund interval = ', self.L)\n print('Its generators are:')\n print(' ')\n for i in range (0,3):\n print('rotation about', '(' , self.pts_Y2[i][0],', sqrt(', self.pts_Y2[i][1], ') ) ' , 'is')\n print('T',i+1, '=')\n printQmtx(self.generators[i])\n print('')\n################################################################################\n##### Test for WeirGroup class ######\nW = WeirGroup(Fraction(1,3),Fraction(3,1))\nW.print()\n\n", " ****** print Weirstrass Group ******\n \nThis is the Weirstrass group with parmameters k1= 1 , k2= 1/3 , k3= 3 .\nLength of fund interval = 5\nIts generators are:\n \nrotation about ( -1 , sqrt( 1 ) ) is\nT 1 =\n( 1 2 )\n( -1 -1 )\n\nrotation about ( -3/4 , sqrt( 3/16 ) ) is\nT 2 =\n( 1 1 )\n( -4/3 -1 )\n\nrotation about ( 0 , sqrt( 3 ) ) is\nT 3 =\n( 0 3 )\n( -1 0 )\n\n" ], [ "################################################################################\n \ndef locateQ(x,y,vertices):\n# returns k, where 0<=k<=N is the index of the vertex that forms the right endpoint \n# of interval where x/y is. N = len(vertices)\n# k=0 => x/y in [oo,v0]\n# 1<=k <= N-1 => x/y in [vk-1,vk]\n# k = N => x/y in [vN-1, oo]\n\n N = len(vertices)\n X = np.full(N,Fraction(x,y))\n# print('vertices=',vertices)\n\n comparison = X<=vertices\n \n lower = np.full(N,1)\n upper = np.full(N,0)\n \n if(comparison == lower).all(): # x is in (inf, v0)\n #print(x,'/',y,'is in [ oo,', vertices[0],']')\n return 0\n if(comparison == upper).all(): # x is in (vN, inf)\n #print(x,'/',y,'is in [', vertices[N-1],',oo]')\n return N \n\n k=0\n while(comparison[k] == comparison[k+1]):\n k+=1\n #print(x,'/',y, 'is in [', vertices[k],',',vertices[k+1],']')\n return k+1\n\n################################################################################\n\nprint('###### locateQ TEST #######')\nk = locateQ(2,33,[-1,0,1])\nprint('k=',k) \nprint('##########################')\n\n", "###### locateQ TEST #######\nk= 2\n##########################\n" ], [ "################################################################################\n################################################################################\ndef is_cusp(Group, a, maxL, currentL):\n # Checks if a (Fraction type) is a cusp of Jigsawgroup in at most maxL steps\n # To do that it follows the path to a and sees if applying succesive transformations\n # takes a to a vertex of the fundamental domain of JigsawGroup\n # Assumes a !=infinity\n \n if currentL>maxL:\n return False\n\n currentL +=1 #You will give one more tile a chance\n \n x = a.numerator\n y = a.denominator\n\n k=locateQ(x,y, Group.vertices)\n \n if(k!= Group.rank-1): #k=rank => x is bigger than all vertices\n # rank of group goes from 1 to N, vertices go from 0 to N-2\n if(a == Group.vertices[k]): #If you found that x is vertex of the jigsaw\n return True\n\n M = Group.generators[k] # generator corresponding to interval x is on\n if(sends2inf(M,a)==True):\n return True\n \n # If it was not a cusp in this step, rotate by M and try again\n \n a = mob_transf(M,a) \n #print('x transform=', x)\n #print('*************')\n \n return is_cusp(Group,a,maxL,currentL)\n \n################################################################################\n\nJG= JigsawGroup([1,2],[1,1])\nW = WeirGroup(Fraction(1,3), Fraction(3,1)) # This group has specials 1, 2\n#JG.print()\n\n#def is_cusp_word(JigsawGroup, x, maxL, currentL):\nprint(is_cusp(JG,Fraction(3,1), 2,0)) # Group, rational, iterations, 0\nprint(is_cusp(W,Fraction(2,1), 2,0)) # Group, rational, iterations, 0)", "True\nFalse\n" ], [ "################################################################################\n\ndef check_cusps(Maxden, Group): \n # Checks if rationals up to denominator MaxDen in the fundamental interval of JigsawGroup\n # are cusps of the JigsawGroup by approximatin by maxL=100 rotations\n \n L = Group.L # Length of fundamental interval of JG\n maxL = 100 # Maximum number of iterations done to find the cusp\n q=1\n while(q<=Maxden):\n p=0 \n while(p/q <= L ):\n if(bltin_gcd(p, q)==1):\n \n siesonoes = is_cusp(Group, Fraction(p,q), maxL,0) \n if(siesonoes == False):\n print('****** CHECK_CUSPS RESULTS ******')\n print('Bad news...')\n print('I found', p,'/', q, 'is not a cusp when doing ',maxL,'rotations towards it.')\n return False\n p+=1\n q+=1\n print('****** CHECK_CUSPS RESULTS ******')\n print('Good news!')\n print('All rationals with denominator at most', Maxden, 'which are less than fund length=', L, 'are cusps!')\n print(' ')\n return True \n\n################################################################################\n\nJG= JigsawGroup([1,2],[1,1])\nW = WeirGroup(Fraction(1,3), Fraction(3,1)) # This group has specials 1, 2\n\n#JG.print()\nesonoes = False\n#def check_cusps(Maxden, maxL, JigsawGroup) \ncheck_cusps(50,JG)\ncheck_cusps(10,W)", "****** CHECK_CUSPS RESULTS ******\nGood news!\nAll rationals with denominator at most 50 which are less than fund length= 7 are cusps!\n \n****** CHECK_CUSPS RESULTS ******\nBad news...\nI found 1 / 1 is not a cusp when doing 100 rotations towards it.\n" ], [ "################################################################################\ndef IS_CUSP_WORD (Group, a, maxL, currentL, word, M):\n # Checks if a (Fraction type) is a cusp of Jigsawgroup in at most maxL steps\n # RECURSIVE (this is inner function of is_cusp_word)\n # - currentL, word, M are parameters for the recursion\n # Assumes a !=infinity\n # Returns tuple (True/False, word, a, M), \n # where - T/F indicates if a is a cusp, \n # - M = matrix in group s.t. M(a) = infty\n # - word is M as word in terms of generators of Group\n # - a = last number in the iteration \n\n \n if currentL>maxL:\n return (False, word, a, M)\n\n currentL +=1 #You will give one more tile a chance\n \n x = a.numerator\n y = a.denominator\n\n k=locateQ(x,y, Group.vertices) \n \n \n if(k!= Group.rank-1): #k=rank => x is bigger than all vertices\n # rank of group goes from 1 to N, vertices go from 0 to N-2\n if(a == Group.vertices[k]): #If you found that x is vertex of the jigsaw\n word = int(str(Group.RotationsToInf[k][1]) + str(word)) \n M = multiply(Group.RotationsToInf[k][0],M) # Multiplie by adequate matrix to send to oo\n \n return (True,word, a, M)\n\n N = Group.generators[k] # generator corresponding to interval x is on\n \n word = (10**currentL)*(k+1)+word # Update word and transformation\n\n M = multiply(N,M)\n\n if(sends2inf(N,a)==True):\n return (True,word, a, M)\n \n # If it was not a cusp in this step, rotate by M and try again\n a = mob_transf(N,Fraction(x,y))\n\n return IS_CUSP_WORD(Group,a,maxL,currentL,word,M)\n\n#---------------------------------------------------\n\ndef is_cusp_word (Group, a, maxL):\n Id = np.matrix( [ (Fraction(1),Fraction(0)) , (Fraction(0), Fraction(1)) ] )\n return IS_CUSP_WORD(Group, a, maxL,0,0,Id)\n\n#---------------------------------------------------\n\ndef is_cusp_word_PRINT (Group, a, maxL):\n Id = np.matrix( [ (Fraction(1),Fraction(0)) , (Fraction(0), Fraction(1)) ] )\n R= IS_CUSP_WORD(Group, a, maxL,0,0,Id)\n print('--------- is_cusp_word RESULTS ---------')\n if (R[0]==True):\n print('TRUE')\n print(a,' is a cusp, sent to infinity by the element')\n printQmtx(R[3])\n print('word in generators: ',R[1])\n else:\n print('FALSE')\n print('could not determine if', a, 'is a cusp by doing', maxL, 'iterations')\n print('closest approximation:')\n printQmtx(R[3])\n print('word in generators: ',R[1])\n\n \n return\n\n\n\n\n################################################################################\n################################################################################\n\ndef explore_cusps(Maxden, Group):\n # Checks all rationals with denominator leq Maxden inside the fundamental interval \n # of Group to see if they are cusps or not\n # For each rational x it creates a tuple (True/False, word, x, M )\n # where M(x)= oo and word is the word of M in the generators of Group\n # returns ???\n\n \n L = Group.L # Length of fundamental interval of JG\n maxL = 100 # Maximum number of iterations done to find the cusp \n\n wordscusps =[]\n Id = np.matrix( [ (Fraction(1),Fraction(0)) , (Fraction(0), Fraction(1)) ] )\n q=1\n while(q<=Maxden):\n p=0\n while(p/q <= L ):\n if(bltin_gcd(p, q)==1): \n word = is_cusp_word(Group, Fraction(p,q), maxL) #,0,0,Id) \n goodword = (word[0], word[1], Fraction(p,q), word[3]) # is_cusp_word changes the cusp\n wordscusps.append(goodword)\n p+=1\n q+=1\n return wordscusps\n\n################################################################################\ndef print_explore_cusps(Maxden, Group):\n # Prints the results of explore_cusps\n print('****** explore_cusps RESULTS ******')\n L = Group.L # Length of fundamental interval of JG\n maxL = 100 # Maximum number of iterations done to find the cusp \n Id = np.matrix( [ (Fraction(1),Fraction(0)) , (Fraction(0), Fraction(1)) ] )\n q=1\n while(q<=Maxden):\n p=0\n while(p/q <= L ):\n if(bltin_gcd(p, q)==1): \n word = is_cusp_word(Group, Fraction(p,q), maxL)#,0,0,Id) \n #print(p,'/', q, siesonoes) \n if(word[0] == False):\n print('False: ', p,'/', q, ', approximation = ', word[1])\n else:\n print('True: ', p,'/', q, 'is cusp, -> infty by ', word[1])\n \n \n p+=1\n q+=1\n print(' ')\n print(' ')\n return ", "_____no_output_____" ], [ "JG= JigsawGroup([1,2],[1,1])\nW = WeirGroup(Fraction(1,3), Fraction(3,1)) # This group has specials 1, 2\n\n\n#JG.print()\nM = np.matrix( [ (Fraction(1),Fraction(0)) , (Fraction(0), Fraction(1)) ] )\nprintQmtx(M)\nis_cusp_word(JG,Fraction(4,1), 8)\n\nV = explore_cusps(2,JG)\n\nprint_explore_cusps(3,JG)\nprint_explore_cusps(3,W)", "( 1 0 )\n( 0 1 )\n****** explore_cusps RESULTS ******\nTrue: 0 / 1 is cusp, -> infty by 430\nTrue: 1 / 1 is cusp, -> infty by 40\nTrue: 2 / 1 is cusp, -> infty by 43240\nTrue: 3 / 1 is cusp, -> infty by 4340\nTrue: 4 / 1 is cusp, -> infty by 340\nTrue: 5 / 1 is cusp, -> infty by 432340\nTrue: 6 / 1 is cusp, -> infty by 2340\nTrue: 7 / 1 is cusp, -> infty by 4312340\n \nTrue: 1 / 2 is cusp, -> infty by 43230\nTrue: 3 / 2 is cusp, -> infty by 2140\nTrue: 5 / 2 is cusp, -> infty by 431240\nTrue: 7 / 2 is cusp, -> infty by 4324340\nTrue: 9 / 2 is cusp, -> infty by 431340\nTrue: 11 / 2 is cusp, -> infty by 42340\nTrue: 13 / 2 is cusp, -> infty by 212340\n \nTrue: 1 / 3 is cusp, -> infty by 30\nTrue: 2 / 3 is cusp, -> infty by 431230\nTrue: 4 / 3 is cusp, -> infty by 43232140\nTrue: 5 / 3 is cusp, -> infty by 43140\nTrue: 7 / 3 is cusp, -> infty by 240\nTrue: 8 / 3 is cusp, -> infty by 43241240\nTrue: 10 / 3 is cusp, -> infty by 214340\nTrue: 11 / 3 is cusp, -> infty by 434340\nTrue: 13 / 3 is cusp, -> infty by 21340\nTrue: 14 / 3 is cusp, -> infty by 41340\nTrue: 16 / 3 is cusp, -> infty by 43232340\nTrue: 17 / 3 is cusp, -> infty by 43242340\nTrue: 19 / 3 is cusp, -> infty by 4212340\nTrue: 20 / 3 is cusp, -> infty by 431212340\n \n \n****** explore_cusps RESULTS ******\nTrue: 0 / 1 is cusp, -> infty by 30\nFalse: 1 / 1 , approximation = 312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312130\nFalse: 2 / 1 , approximation = 213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213130\nTrue: 3 / 1 is cusp, -> infty by 3230\nTrue: 4 / 1 is cusp, -> infty by 230\nTrue: 5 / 1 is cusp, -> infty by 31230\n \nTrue: 1 / 2 is cusp, -> infty by 3232130\nTrue: 3 / 2 is cusp, -> infty by 3130\nTrue: 5 / 2 is cusp, -> infty by 23130\nFalse: 7 / 2 , approximation = 213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213230\nFalse: 9 / 2 , approximation = 121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121230\n \nFalse: 1 / 3 , approximation = 121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131212132130\nTrue: 2 / 3 is cusp, -> infty by 323212130\nTrue: 4 / 3 is cusp, -> infty by 312312312130\nTrue: 5 / 3 is cusp, -> infty by 313213213130\nTrue: 7 / 3 is cusp, -> infty by 2313130\nFalse: 8 / 3 , approximation = 131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121313123130\nTrue: 10 / 3 is cusp, -> infty by 323213230\nFalse: 11 / 3 , approximation = 312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121313230\nFalse: 13 / 3 , approximation = 131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312121230\nTrue: 14 / 3 is cusp, -> infty by 23121230\n \n \n" ], [ "def check(wordscusps):\n N = len(wordscusps)\n\n #onlycusps = wordscusps\n onlycusps=[] #Only checks if the cusps \n for i in range(0,N):\n if(wordscusps[i][0] == True):\n onlycusps.append(wordscusps[i])\n \n N= len(onlycusps) \n for i in range(0,N):\n\n M = onlycusps[i][3]\n a = onlycusps[i][2]\n\n if(sends2inf(M,a) == False): #only checks that M(a)=oo\n\n #if(vertices.count(r) == 0): #Option to check if M(a) \\in vertices\n print('***** message from CHECK in killer intervals *****')\n print('NO GO: ', a , 'is marked as cusp but does not get sent to oo by corresponding matrix.')\n print(' ')\n return False\n #print('***************')\n #print(len(onlycusps))\n #print(len(wordscusps))\n if (len(onlycusps) == len(wordscusps)): \n #print('***** message from CHECK in killer intervals *****')\n #print('GO! : all the cusps in the list are cusps and matrices correspond.')\n print(' ')\n else:\n #print('***** message from CHECK in killer intervals *****')\n #print('OK : all the elements marked as cusps get set to oo by their matrix, but there were non-cusps in the list')\n print(' ')\n return True\n \n ", "_____no_output_____" ], [ "def prepare_matrix(M):\n# To compute the killer intervals we need to send a representative of M(oo)=x \n# that has integer entries (3.1). To do so we multiply the entries of M by \n# a common denominator so they are in Z and then reduce them \n\n a1=M[0,0].numerator\n b1=M[0,0].denominator\n\n a2=M[0,1].numerator\n b2=M[0,1].denominator \n\n a3=M[1,0].numerator\n b3=M[1,0].denominator\n \n a4=M[1,1].numerator\n b4=M[1,1].denominator\n \n a11 = a1*b2*b3*b4\n a22 = a2*b1*b3*b4\n a33 = a3*b1*b2*b4\n a44 = a4*b1*b2*b3\n \n cdiv = bltin_gcd(a11,a22)\n cdiv = bltin_gcd(cdiv,a33)\n cdiv = bltin_gcd(cdiv, a44)\n \n M00 = Fraction(a11,cdiv)\n M01 = Fraction(a22, cdiv)\n M10 = Fraction(a33, cdiv)\n M11 = Fraction(a44, cdiv)\n \n if M10 < 0:\n M00 = -M00\n M01 = -M01\n M10 = -M10\n M11 = -M11\n \n M = np.matrix( [ (M00, M01), (M10, M11)] )\n return M\n################################################################################\n################################################################################\n\n\n", "_____no_output_____" ], [ "def matrix_infty_to_cusp(M):\n # Given that the matrix M sends a known cusp to infinity\n # returns a matrix corresponding to M^(-1) with all coordinates in Z and gcd=1\n # see proposition 3.1 in paper\n \n N = inverseQmatrix(M)\n N = prepare_matrix(N)\n return N\n################################################################################\ndef killing_interval(M):\n # Given a matrix M representing an element in Jigsawgroup, of the form of prop 3.1\n # returns the killer interval (tuple) of the cusp M(oo)=M[0,0]/M[1,0] associated to M \n \n return ( Fraction(M[0,0] -1, M[1,0]), Fraction(M[0,0]+1,M[1,0]))\n \n################################################################################\ndef generate_killer_intervals(wordscusps):\n# wordscusps is an array of the form (True/False, word, a, M)\n # where - T/F indicates if a is a cusp, \n # - M = matrix in group s.t. M(a) = infty\n # - word is M as word in terms of generators of Group\n # coming from function is_cusp_word\n# Returns an array where each element is a tuple:\n# (killer_interval, cusp corresponding to killer interval)\n\n if(check(wordscusps) == False):\n print('******* generate_killer_intervals MESSAGE *******')\n print('Alert! There are false cusps in your array.')\n return\n \n killers = [] \n\n onlycusps=[] # First separates all the cusps from wordscusps\n for i in range(0, len(wordscusps)):\n if(wordscusps[i][0] == True):\n onlycusps.append(wordscusps[i])\n\n for i in range(0, len(onlycusps)):\n N = inverse(onlycusps[i][3])\n N = prepare_matrix(N)\n killers.append( (killing_interval(N), onlycusps[i][2]) )\n \n return killers\n\n################################################################################\ndef killer_intervals(maxden, Group):\n# Returns an array of tuples, where each element is:\n # (killer_interval, cusp corresponding to killer interval)\n# Cusps of Group are calculated up denominator maxden.\n# (old tell_killer_intervals)\n\n # Max#iterations to find cusps = 100 (defined @ explore_cusps)\n V = explore_cusps(maxden, Group) #maxden, maxL, group\n return generate_killer_intervals(V)", "_____no_output_____" ], [ "def print_killer_intervals(maxden, Group):\n# Prints cusps and corresponding killer intervals of Group (up to denominator maxden)\n# return is void.\n \n # Max#iterations to find cusps = 100 (defined @ explore_cusps)\n V = explore_cusps(maxden, Group) \n \n killers = generate_killer_intervals(V)\n print('')\n \n intervals = []\n for i in range (0, len(killers)):\n intervals.append( killers[i][0])\n\n for i in range (0, len(killers)):\n print('killer around ', killers[i][1], ':')\n print(intervals[i][0],',',intervals[i][1])\n print(' ')\n \n return\n\n#####################################################################\n\n# ***** Calculate killer intervals for all the cusps found among \n# ***** the rationals up tp denominator Maxden (first parementer)\nJG= JigsawGroup([1,2],[1,1])\nprint_killer_intervals(2,JigsawGroup)\n", " \n\nkiller around 0 :\n-1 , 1\n \nkiller around 1 :\n0 , 2\n \nkiller around 2 :\n3/2 , 5/2\n \nkiller around 3 :\n2 , 4\n \nkiller around 4 :\n3 , 5\n \nkiller around 5 :\n4 , 6\n \nkiller around 6 :\n5 , 7\n \nkiller around 7 :\n6 , 8\n \nkiller around 1/2 :\n1/4 , 3/4\n \nkiller around 3/2 :\n5/4 , 7/4\n \nkiller around 5/2 :\n9/4 , 11/4\n \nkiller around 7/2 :\n13/4 , 15/4\n \nkiller around 9/2 :\n4 , 5\n \nkiller around 11/2 :\n5 , 6\n \nkiller around 13/2 :\n6 , 7\n \n" ], [ "################################################################################\n################################################################################\ndef do_intervals_cover(x,y, cusps, Xend,Yend, cover):\n# if possible, finds a subcollection of given intervals that covers [Xend, Yend]\n# x,y are arrays with endpoints of opencover\n# [Xend, Yend] is the interval you are trying to cover\n# cover has to be externally initialized to []\n# if cover covers: returns subcover that covers\n# else: returns False\n#previous does_cover_cover4\n\n checkX = [] # Find all intervals that contain Xend of interval\n checkY = []\n checkCusp = []\n \n # Method 1: when Xend is cusp of Group\n\n # if X end is cusp and endpoint of some open in cover \n if(Xend in cusps and Xend in x ): \n \n # Add killer interval of the cusp to cover\n k = cusps.index(Xend) \n cover.append((x[k], y[k], cusps[k])) \n if(y[k]>Yend): # If that interval covers, finish\n return cover\n \n # Look for the cusps that have Xend as x-endpt of their killer interval\n for i in range (0, len(x)):\n if(Xend==x[i] and y[k]<y[i]):\n checkX.append(x[i])\n checkY.append(y[i])\n checkCusp.append(cusps[i])\n if(len(checkX) == 0): \n Xend = y[k] \n \n \n # Method 2: if Xend not a (known) cusp of Group\n else:\n \n for i in range (0,len(x)): # Find all intervals that contain Xend of interval\n if(x[i]<Xend and Xend<y[i]):\n checkX.append(x[i])\n checkY.append(y[i])\n checkCusp.append(cusps[i])\n\n if(len(checkX) == 0): # The cover doesn't cover Xend of interval\n print(' ****** do_intervals_cover RESULTS ****** ')\n print('did not cover', Xend)\n return False\n \n # From the intervals that contain Xend, find the one that covers the most \n \n if(len(checkX)!=0):\n maxi = 0 \n for i in range (1,len(checkY)):\n if(checkY[i]>checkY[i-1]):\n maxi=i\n cover.append((checkX[maxi], checkY[maxi], checkCusp[maxi]))\n \n\n if(checkY[maxi]> Yend): # That intervals covers!\n return cover\n \n Xend = checkY[maxi] # Construct new interval and new cover\n \n \n newx = []\n newy = []\n newcusps = []\n for i in range(0,len(y)): # Only keep the opens that have a chance of covering remainin interval\n if(y[i]>Xend):\n newx.append(x[i])\n newy.append(y[i])\n newcusps.append(cusps[i])\n \n return do_intervals_cover( newx, newy, newcusps, Xend,Yend, cover)\n\n################################################################################\n################################################################################\n\ndef check_cover(x,y, Xend, Yend):\n# Checks if the cover given by do_intervals_cover indeed covers interval [Xend,Yend]\n if(x[0]> Xend):\n return False\n if(y[len(y)-1]< Yend):\n return False\n\n for i in range (0,len(x)-1):\n if y[i]<x[i+1]: #there is a gap between intervals\n return False\n return True\n\n", "_____no_output_____" ], [ "################################################################################\n################################################################################\n\ndef cover_with_killers(Group,maxden):\n# checks if the collection of killer intervals corresponding to cusps in Group \n# (up to denom maxden) cover the fundamenta interval of the Group\n# It also prints the results\n# ... can be altered to return : False if it intervals don't cover\n# cover (subcollection of killer intervals) that cover ...\n\n \n#previous cover_with_killers4\n \n # Generates killer intervals for all cusps with den<=maxden\n killers = killer_intervals(maxden, Group) \n \n # Separate intervals and cusps\n intervals = []\n cusps = []\n for i in range (0, len(killers)):\n intervals.append( killers[i][0])\n cusps.append(killers[i][1])\n\n # Separate x and y ends of intervals\n x = []\n y = []\n for i in range(0, len(intervals)):\n x.append(intervals[i][0])\n y.append(intervals[i][1])\n\n # See if the killer interval collection covers\n cover = do_intervals_cover(x,y, cusps, 0,Group.L, [])\n if( cover == False):\n print(' ****** cover_with_killers RESULTS ****** ')\n print('Bad news...')\n print('The cover generated by the cusps found in group does not cover the fundamental interval.')\n print(' ')\n return \n \n # Double check the cover covers\n x=[]\n y=[]\n for i in range(0, len(cover)):\n x.append(cover[i][0])\n y.append(cover[i][1])\n siono = check_cover(x, y, 0, Group.L)\n \n if(siono == True):\n print(' ****** cover_with_killers RESULTS ****** ')\n print('Good news!')\n print('The cover generated by the cusps found among rationals with denominator at most', maxden,'covers the fundamental interval [0,', Group.L,'].')\n print('The cover has', len(cover),' intervals:')\n for i in range(0, len(cover)):\n print(cover[i][2] ,' ---' , cover[i][0], ' , ', cover[i][1] )\n print(' ')\n return \n print(' ****** cover_with_killers RESULTS ****** ')\n print('Bad news...')\n print('The program computed a false cover.')\n print(' ')\n return \n\n################################################################################", "_____no_output_____" ], [ "#####################################################################\n######## everything that can be done with the previous code #########\n\n# ***** generate a jigsaw group ***** #\nJG= JigsawGroup([1,4],[1,2])\nprint('fundamental interval = [0,', JG.L,']')\nJG.printNOGENS()\n\n# ***** generate a Weirstrass group *****\n\n\n\n# ***** check if rationals up to denominator Maxden are cusps ***** #\n# ***** for a given rational stops after 100 iterations ****** #\n#esonoes = False\n#def check_cusps(Maxden, maxL, JigsawGroup) \n#check_cusps(20,50,JG)\n\n\n\n# ***** check if rationals up to denominator Maxden are cusps ***** #\n# ***** for a given rational stops after 100 iterations ****** #\n#print_check_cusps(20,50,JG)\n#print(' ')\n\n\n# ***** Calculate killer intervals for all the cusps found among \n# ***** the rationals up tp denominator Maxden (first parementer)\n#JG= JigsawGroup([1,3],[1,1])\n#print_killer_intervals(2,JigsawGroup)\ncover_with_killers(JG, 7)\n\n##AQUI\n\n#W2 = WeirGroup(Fraction(3,2),Fraction(2,5))\n#cover_with_killers(W2, 10)\n\n#W6 = WeirGroup(Fraction(9,5),Fraction(5,7))\n#cover_with_killers(W6, 50)", "fundamental interval = [0, 15 ]\n ****** print Jigsaw Group ******\n \nThis group comes from a jigsaw with 1 tiles of type 1\n and 2 tiles of type 4 .\nLength of fund interval = 15\nNumber of generators: 5\n \nThe jigsaw has vertices (apart from oo):\n[-1, 0, 1, 5]\n \n ****** cover_with_killers RESULTS ****** \nGood news!\nThe cover generated by the cusps found among rationals with denominator at most 7 covers the fundamental interval [0, 15 ].\nThe cover has 19 intervals:\n0 --- -1 , 1\n1 --- 0 , 2\n2 --- 1 , 3\n3 --- 2 , 4\n4 --- 15/4 , 17/4\n5 --- 4 , 6\n6 --- 5 , 7\n7 --- 6 , 8\n8 --- 31/4 , 33/4\n25/3 --- 8 , 26/3\n61/7 --- 60/7 , 62/7\n9 --- 17/2 , 19/2\n29/3 --- 28/3 , 10\n10 --- 39/4 , 41/4\n11 --- 10 , 12\n12 --- 11 , 13\n13 --- 12 , 14\n14 --- 13 , 15\n15 --- 14 , 16\n \n" ], [ "# -------------------------------------------------------------------------------\n# ------------ THIS SECTION OF THE CODE DEALS WITH FINDING SPECIALS -------------\n# -------------------------------------------------------------------------------\n\ndef look_for_wholes(Group, maxL):\n# Tries to build a cover with killer intervals whose endpoints are cusps, \n# starting with the killer interval around 0.\n# if at some stage it cannot continue, it returns the number that could not be\n# determined to be a cusp.\n\n L = Group.L\n x = 0\n Id = np.matrix( [ (Fraction(1),Fraction(0)) , (Fraction(0), Fraction(1)) ] )\n k=0\n# maxL=1000\n \n Yends = []\n\n while( x< L and k<maxL):\n #is_cusp_word(Group, a, maxL, currentL, word, M):\n info = IS_CUSP_WORD(Group, x, maxL, 0,0, Id ) # has form (T/F, word, cusp, M)\n \n if(info[0]== False):\n print(' ***** look_for_wholes RESULTS ***** ')\n print(x, 'is not a cusp of the group (up to', maxL ,' rotations)')\n print('An approximation to it is', info[1])\n print(' ')\n return\n \n k_interval = generate_killer_intervals([(info[0], info[1], x, info[3])]) \n # has form [(endX,endY) , cusp]\n \n # Take left end of killer interval around x and repeat process\n x= k_interval[0][0][1] \n Yends.append(x)\n k+=1\n \n if(k == maxL):\n print(' ***** look_for_wholes RESULTS ***** ')\n print('Did not cover the interval. Endpoints were:')\n for i in range (0, len(Yends)):\n print(Yends[i])\n print(' ')\n return \n if( x>= L):\n print(' ***** look_for_wholes RESULTS ***** ')\n print('A cover was generated!')\n print(' ')\n return\n\n \n# -------------------------------------------------------------------------------\n\n\n\nW = WeirGroup(Fraction(1,3), Fraction(3,1)) # This group has specials 1, 2\nlook_for_wholes(W,200)\n\n#W = WeirGroup(Fraction(2,5), Fraction(5,7)) # This group has specials 1, 2\n# look_for_wholes(W,1755)\n\n", " \n ***** look_for_wholes RESULTS ***** \n1 is not a cusp of the group (up to 200 rotations)\nAn approximation to it is 3121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312131213121312130\n \n" ], [ "################################################################################\n\ndef word2mtx(Group, word):\n# word is a sequence of digits where each represents a generator in the group.\n# retunrs the matrix X corresponding to this word\n\n if word % 10 == 0:\n word = Fraction(word, 10)\n L = len(str(word)) # !!! assumes each digit represents a generator\n X = np.matrix( [ (Fraction(1),Fraction(0)) , (Fraction(0), Fraction(1)) ] )\n for i in range(0,L):\n k = int(word % 10)\n X = multiply(X,Group.generators[k-1])\n word = Fraction(word - k,10)\n return X\n\n################################################################################\ndef subword2mtx(Group, word, i, j): \n # Returns (subword, M) where \n # - subword = subword of word going from the i-th digit to the j-th (including both)\n # - M = transformation corresponding to subword according to Group.generators\n out = word % (10**i)\n word = word % (10**j) - out\n word = Fraction(word, 10**i)\n \n M = word2mtx(Group, word)\n \n return (word,M)\n\ndef conjugate_word(Group, word, subword, j):\n # Conjugates subword by the first j digits of word\n # Returns tuple (conjugated_word, M) where \n # - M= matrix corresponding to conjugated_word according to Group.generators\n \n for i in range(0, j):\n k = int(word % 10) # !!! Only work for at most 9 generators. (8 tiles)\n subword = int( str(k) + str(subword) + str(k))\n word = Fraction(word - k,10)\n \n return(subword, word2mtx(Group, subword))\n \n \n\n################################################################################\ndef check_special(Group, a,maxL):\n# Given a (rational type), the function tries to determine if it is a special for Group\n# maxL = max number of iterations allowed\n# prints results\n \n\n #maxL=400 #digits in word\n Id = np.matrix( [ (Fraction(1),Fraction(0)) , (Fraction(0), Fraction(1)) ] )\n \n info = IS_CUSP_WORD(Group, a, maxL, 0,0, Id )\n word = int(Fraction(info[1], 10)) # Adjust because words always have 0 at the beginning.\n \n # If a is a cusp, finish.\n if(info[0] == True):\n print(' ****** check_special RESULTS ******')\n print('This is a cusp! :', a)\n print('Sent to oo by:')\n printQmtx(info[3])\n print('its word has length ',len(str(word)),'and it is:', word)\n print(' ')\n return \n\n \n woord = word # Need a copy because word is going to get destroyed\n orbit = [a]\n distinct = True\n i = 0\n \n while( distinct==True and i<maxL):\n k = int(word % 10) # !!! Only works for at most 9 generators. (less than 8 tiles)\n M = Group.generators[k-1]\n \n newpoint = mob_transf(M, orbit[i])\n\n # Check if you are returning to newpoint\n if( newpoint in orbit): \n j=0\n while(orbit[j]!= newpoint):\n j+=1\n # Have to conjugate the word of the first special found to get the word for a\n #subword = (word, matrix)\n subword = subword2mtx(Group, woord, j, i+1) #element in group that fixes element orbit[j]=orbit[i]\n subword = conjugate_word(Group, woord, subword[0], j) # Conjugates subword by the first j digits of word\n \n print(' ****** check_special RESULTS ******')\n print(i,':',newpoint,'= first appearance',j,':',orbit[j])\n print('This is a special:', a)\n print('Fixed by Mobius transf=')\n printQmtx(subword[1])\n trace= tr(subword[1])*tr(subword[1])/det(subword[1])\n print('as en element in PSL(2,R) this has trace',trace )\n if np.absolute(trace)>4:\n print(' hyperbolic')\n if np.absolute(trace)<4:\n print(' elliptic')\n if np.absolute(trace)==4:\n print(' parabolic')\n print('its word has length ',len(str(subword[0])) ,' and it is', subword[0]) \n print(' ')\n return \n \n orbit.append(newpoint)\n word = Fraction(word - k,10)\n i+=1\n\n if i== maxL:\n print(' ****** check_special RESULTS ******')\n print('Could not determine if',a,' is a cusp or a special. (', maxL,' steps)')\n print(' ')\n return \n\n", "_____no_output_____" ], [ "#W3 = WeirGroup(Fraction(1,3), Fraction(3,1)) # This group has specials 1, 2\n#check_special(W3, Fraction(1,1),10)\n#check_special(W3, Fraction(2,1),10)\n\n#AAAA\n\nW = WeirGroup(Fraction(1,3), Fraction(3,1)) # This group has specials 1, 2\nW.print()\ncheck_special(W, Fraction(1,1),80)\n\n", " ****** print Weirstrass Group ******\n \nThis is the Weirstrass group with parmameters k1= 1 , k2= 1/3 , k3= 3 .\nLength of fund interval = 5\nIts generators are:\n \nrotation about ( -1 , sqrt( 1 ) ) is\nT 1 =\n( 1 2 )\n( -1 -1 )\n\nrotation about ( -3/4 , sqrt( 3/16 ) ) is\nT 2 =\n( 1 1 )\n( -4/3 -1 )\n\nrotation about ( 0 , sqrt( 3 ) ) is\nT 3 =\n( 0 3 )\n( -1 0 )\n\n ****** check_special RESULTS ******\n3 : 1 = first appearance 0 : 1\nThis is a special: 1\nFixed by Mobius transf=\n( 1 2 )\n( 2/3 7/3 )\nas en element in PSL(2,R) this has trace 100/9\n hyperbolic\nits word has length 4 and it is 1213\n \n" ], [ "# -------------------------------------------------------------------------------\n# ------- THIS SECTION OF THE CODE DEALS WITH TILING THE VERTICAL STRIPE --------\n# -------------------------------------------------------------------------------\n\n\ndef calculate_side_types(n, k):\n # n = type of the triangle\n # k = how many vertices on x-axis\n # returns an array sidetypes, where sidetypes[i] is the type of the side \n # from the i-th vertex to the (i+1)-vertex. \n # First vertex is assumed to be oo and then goes in CCW. \n \n sidetypes = [1,1] # Jigsaw always has first tile type Delta(1,1,1)\n for i in range (0,k-2):\n if(i%3 == 0):\n sidetypes.append(3) # 3 = 1/n\n if (i%3 == 1):\n sidetypes.append(1) # 1 = 1\n if(i%3 == 2):\n sidetypes.append(2) # 2 = n \n # Vertical side from last vertex to infty\n if ( sidetypes[k-1] == 1):\n sidetypes.append(3)\n if ( sidetypes[k-1] == 2):\n sidetypes.append(1)\n if ( sidetypes[k-1] == 3):\n sidetypes.append(2)\n \n return sidetypes\n\ndef cover_by_vertical_rotations(Group):\n# Returns list of vertices of the tiling (given by Group)\n# that have a vertex on the fundamental interval\n \n sidetype = calculate_side_types(Group.sign[1], len(Group.vertices))\n vertices = list(Group.vertices)\n cusps = list(Group.vertices) # Where we save all the generated non-oo cusps.\n vertices.insert(0, \"INF\") # now sydetipe[i] = sidetype from vertices[i] to vertices[i+1]\n \n L = Group.L #length of fund interval\n numV = len(vertices)\n k = numV-1\n largest = vertices[k]\n \n n = Group.tiles[1]\n\n while(largest < L ):\n # calculate rotation about [largest, oo], take side type into account\n if (sidetype[k] == 1):\n R = pi_rotation_special(largest, 1)\n else:\n R = pi_rotation_special(largest, n) # propostion 4.3 5)\n for i in range (0,len(vertices)):\n a = vertices.pop(numV-1)\n x = mob_transf(R, a)\n vertices.insert(0,x)\n if ( i!= numV-k-1):\n cusps.append(x)\n largest = max(cusps)\n k = vertices.index(largest)\n \n cusps = sorted(set(cusps))\n return cusps\n \n############################################################################\nJG = JigsawGroup([1,4],[1,3])\nprint('length of fund interval: ', JG.L)\nC = cover_by_vertical_rotations(JG)\nfor i in range(0, len(C)):\n print(C[i])\n\n\n#is_cusp(JG, Fraction(10,1), 3, 0)\n ", "length of fund interval: 21\n-1\n0\n1\n5\n6\n43/7\n37/6\n31/5\n7\n11\n35/3\n59/5\n12\n61/5\n13\n15\n17\n89/5\n107/6\n18\n19\n39/2\n119/6\n139/7\n20\n21\n22\n26\n27\n" ], [ "W = WeirGroup(Fraction(1,4),Fraction(4,1))\ncover_with_killers(W, 10)\n\n", " \n ****** cover_with_killers RESULTS ****** \nGood news!\nThe cover generated by the cusps found among rationals with denominator at most 10 covers the fundamental interval [0, 6 ].\nThe cover has 7 intervals:\n0 --- -1 , 1\n1 --- 0 , 2\n2 --- 1 , 3\n3 --- 2 , 4\n4 --- 3 , 5\n5 --- 4 , 6\n6 --- 5 , 7\n \n" ], [ "JG = JigsawGroup([1,4],[1,4])\n\n#print_explore_cusps(3,JG)\nis_cusp_word(JG, Fraction(22,1), 10)\n\n#JG.print()\n", "_____no_output_____" ], [ "M= np.matrix( [ (Fraction(-5,1),Fraction(29,1)) , (Fraction(-1,1), Fraction(5,1)) ] )\na=mob_transf(M,Fraction(6,1))\nprint(a)", "1\n" ], [ "N= np.matrix( [ (Fraction(-6,1),Fraction(37,1)) , (Fraction(-1,1), Fraction(6,1)) ] )\na=mob_transf(N,Fraction(15,1))\n#print(a)\nM = inverse(N)\nb=mob_transf(N,Fraction(4,1))\nprint(b)", "13/2\n" ], [ "K= np.matrix( [ (Fraction(-1,5),Fraction(1,5)) , (Fraction(-1,1), Fraction(1,5)) ] )\nc=mob_transf(M,Fraction(6,1))\nprint(c)", "INF\n" ], [ "J=pi_rotation_special(Fraction(33,5),Fraction(4,25))\nprint(mob_transf(J,Fraction(6,1)))\n", "103/15\n" ], [ "#*** Calculating contraction constant of 4 = m+3\n\nt1 = np.matrix( [ (Fraction(1,1),Fraction(2,1)) , (Fraction(-1,1), Fraction(-1,1)) ] )\nt2 = np.matrix( [ (Fraction(1,1),Fraction(1,1)) , (Fraction(-2,1), Fraction(-1,1)) ] )\nT9 =np.matrix( [ (Fraction(1,1),Fraction(-9,1)) , (Fraction(0,1), Fraction(1,1)) ] )\nT9i=np.matrix( [ (Fraction(1,1),Fraction(9,1)) , (Fraction(0,1), Fraction(1,1)) ] )\nM = np.matrix( [ (Fraction(-5,1),Fraction(29,1)) , (Fraction(-1,1), Fraction(5,1)) ] )\n\nB=M\nprint(mob_transf(B,Fraction(4,1)))\n\nB=multiply(T9,M)\nprint(mob_transf(B,Fraction(4,1)))\n\nB=multiply(t2,B)\nprint(mob_transf(B,Fraction(4,1)))\n\nB=multiply(t1,B)\nprint(mob_transf(B,Fraction(4,1)))\n\n\nprintQmtx(B)", "9\n0\n-1\nINF\n( -11 43 )\n( 4 -16 )\n" ], [ "#*** Calculating contraction constant of 11/3 = m+2 + 2/3\nt1 = np.matrix( [ (Fraction(1,1),Fraction(2,1)) , (Fraction(-1,1), Fraction(-1,1)) ] )\nT9 = np.matrix( [ (Fraction(1,1),Fraction(-9,1)) , (Fraction(0,1), Fraction(1,1)) ] )\nM = np.matrix( [ (Fraction(-5,1),Fraction(29,1)) , (Fraction(-1,1), Fraction(5,1)) ] )\n\n\nB=M\nprint(mob_transf(B,Fraction(11,3)))\n\nB=multiply(T9,M)\nprint(mob_transf(B,Fraction(11,3)))\n\nB=multiply(t1,B)\nprint(mob_transf(B,Fraction(11,3)))\n\n\nprintQmtx(B)", "8\n-1\nINF\n( 2 -6 )\n( -3 11 )\n" ], [ "#*** Calculating contraction constant of 7/3 = m+2 0 2/3\nt2 = np.matrix( [ (Fraction(1,1),Fraction(1,1)) , (Fraction(-2,1), Fraction(-1,1)) ] )\nT7 = np.matrix( [ (Fraction(1,1),Fraction(-7,1)) , (Fraction(0,1), Fraction(1,1)) ] )\nM = np.matrix( [ (Fraction(-5,1),Fraction(29,1)) , (Fraction(-1,1), Fraction(5,1)) ] )\n\nB=M\nprint(mob_transf(B,Fraction(7,3)))\n\nB=multiply(T7,M)\nprint(mob_transf(B,Fraction(7,3)))\n\nB=multiply(t2,B)\nprint(mob_transf(B,Fraction(7,3)))\n\n\nprintQmtx(B)", "13/2\n-1/2\nINF\n( 1 -1 )\n( -3 7 )\n" ], [ "#*** Calculating contraction constant of 2 = m+1 \nA = np.matrix( [ (Fraction(-7,1),Fraction(50,1)) , (Fraction(-1,1), Fraction(7,1)) ] )\nB = np.matrix( [ (Fraction(-17,1),Fraction(145,1)) , (Fraction(-2,1), Fraction(17,1)) ] )\nM = np.matrix( [ (Fraction(-5,1),Fraction(29,1)) , (Fraction(-1,1), Fraction(5,1)) ] )\n\n\nC=M\nprint(mob_transf(C,Fraction(2,1)))\n\nC=multiply(A,C)\nprint(mob_transf(C,Fraction(2,1)))\n\nC=multiply(B,C)\nprint(mob_transf(C,Fraction(2,1)))\n\n\nprintQmtx(C)", "19/3\n17/2\nINF\n( -35 71 )\n( -4 8 )\n" ], [ "# ################################################################################\n ###### TEST for Jigsaw_vertices #####\n# JS= jigsawset([1,2],[4,6])\n# JS.print()\n# Jigsaw_vertices(JS)", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "################################################################################\ndef find_special_in_orbit(Group, a,maxL):\n# Given a (rational type), the function tries to determine if there is a special in the orbit of a\n# orbit is calculated ....\n# maxL = max number of iterations allowed\n# prints results\n \n\n #maxL=400 #digits in word\n Id = np.matrix( [ (Fraction(1),Fraction(0)) , (Fraction(0), Fraction(1)) ] )\n \n info = IS_CUSP_WORD(Group, a, maxL, 0,0, Id )\n word = int(Fraction(info[1], 10)) # Adjust because words always have 0 at the beginning.\n \n # If a is a cusp, finish.\n if(info[0] == True):\n print(' ****** check_special RESULTS ******')\n print('This is a cusp! :', a)\n print('Sent to oo by:')\n printQmtx(info[3])\n print('its word has length ',len(str(word)),'and it is:', word)\n print(' ')\n return \n\n \n woord = word # Need a copy because word is going to get destroyed\n orbit = [a]\n distinct = True\n i = 0\n \n while( distinct==True and i<maxL):\n k = int(word % 10) # !!! Only works for at most 9 generators. (less than 8 tiles)\n M = Group.generators[k-1]\n \n newpoint = mob_transf(M, orbit[i])\n\n # Check if you are returning to newpoint\n if( newpoint in orbit): \n j=0\n while(orbit[j]!= newpoint):\n j+=1\n # Have to conjugate the word of the first special found to get the word for a\n #subword = (word, matrix)\n subword = subword2mtx(Group, woord, j, i+1) #element in group that fixes element orbit[j]=orbit[i]\n \n print(' ****** check_special RESULTS ******')\n print('This is a special:', a)\n print(i,':',newpoint,' first appearance =',j,':',orbit[j])\n print(orbit[j], 'fixed by Mobius transf=')\n printQmtx(subword[1])\n trace= tr(subword[1])*tr(subword[1])/det(subword[1])\n print('as en element in PSL(2,R) this has trace',trace )\n if np.absolute(trace)>4:\n print(' hyperbolic')\n if np.absolute(trace)<4:\n print(' elliptic')\n if np.absolute(trace)==4:\n print(' parabolic')\n print('its word has length ',len(str(subword[0])) ,' and it is', subword[0]) \n print(' ')\n return subword[1]\n \n orbit.append(newpoint)\n word = Fraction(word - k,10)\n i+=1\n\n if i== maxL:\n print(' ****** check_special RESULTS ******')\n print('Could not determine if',a,' is a cusp or a special. (', maxL,' steps)')\n print(' ')\n return ", "_____no_output_____" ], [ "\n# --------------------------------------------\ndef fixpts (M): # this does not work, use fixpts2 in \"workspace looking for specials\"\n \n d= det(M) #checkpoint\n if d!= 1:\n if d!= -1:\n print('matrix is not in PSL(2,R)')\n return\n# if d==-1:\n# M=-1*M\n \n a3=M[1,0].numerator\n b3=M[1,0].denominator\n \n if a3==0: #** fill this\n return\n \n a1=M[0,0].numerator\n b1=M[0,0].denominator\n\n a4=M[1,1].numerator\n b4=M[1,1].denominator\n \n disD = (a1**2)*(b4**2) +2*a1*a4*b1*b4 + (a4**2)*(b1**2)-4*(b1**2)*(b4**2) #denominator of discriminant\n\n if disD == 0:\n print('parabolic element')\n #fill this\n return \n \n if disD <0:\n print('elliptic element')\n #fill this\n return \n\n\n disN = (b1**2)*(b4**2) #numerator of discriminant\n init = Fraction(a1*b4-a4*b1,b1*b4)\n div = Fraction(b3,2*a3)\n\n \n rootD = int(math.sqrt(disD))\n if (rootD**2 == disD):\n \n rootN = int(math.sqrt(disN))\n if (rootN**2 == disN): \n \n disc = Fraction(rootD, rootN)\n root1 = (init + disc)*div #all these are fraction type\n root2 = (init - disc)*div\n print('Fixed pts (calculated exactly):')\n print(root1, ' , ',root2)\n return [root1, root2]\n disc= math.sqrt(Fraction(disD,disN))\n root1 = (init + disc)*div\n root2 = (init - disc)*div \n print('Fixed pts (float approximation):')\n print(root1, ' , ',root2)\n \n return [root1, root2]\n\n\n\n \n \n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe11c8a9b833da7687a8bc20f6340c9d3515484
100,252
ipynb
Jupyter Notebook
Starter_Code/lstm_stock_predictor_fng.ipynb
aliabolhassani/LSTM-Stock-Predictor
202b4667ca2e6fbcd9ef90b5800e8010f917782d
[ "ADSL" ]
null
null
null
Starter_Code/lstm_stock_predictor_fng.ipynb
aliabolhassani/LSTM-Stock-Predictor
202b4667ca2e6fbcd9ef90b5800e8010f917782d
[ "ADSL" ]
null
null
null
Starter_Code/lstm_stock_predictor_fng.ipynb
aliabolhassani/LSTM-Stock-Predictor
202b4667ca2e6fbcd9ef90b5800e8010f917782d
[ "ADSL" ]
1
2022-03-05T02:23:02.000Z
2022-03-05T02:23:02.000Z
113.151242
41,862
0.693143
[ [ [ "# LSTM Stock Predictor Using Fear and Greed Index\n\nIn this notebook, you will build and train a custom LSTM RNN that uses a 10 day window of Bitcoin fear and greed index values to predict the 11th day closing price. \n\nYou will need to:\n\n1. Prepare the data for training and testing\n2. Build and train a custom LSTM RNN\n3. Evaluate the performance of the model", "_____no_output_____" ], [ "## Data Preparation\n\nIn this section, you will need to prepare the training and testing data for the model. The model will use a rolling 10 day window to predict the 11th day closing price.\n\nYou will need to:\n1. Use the `window_data` function to generate the X and y values for the model.\n2. Split the data into 70% training and 30% testing\n3. Apply the MinMaxScaler to the X and y values\n4. Reshape the X_train and X_test data for the model. Note: The required input format for the LSTM is:\n\n```python\nreshape((X_train.shape[0], X_train.shape[1], 1))\n```", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nfrom numpy.random import seed\nfrom tensorflow import random\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import LSTM, Dense, Dropout\n\n%matplotlib inline", "_____no_output_____" ], [ "# Set the random seed for reproducibility\n# Note: This is for the homework solution, but it is good practice to comment this out and run multiple experiments to evaluate your model\nseed(1)\nrandom.set_seed(2)", "_____no_output_____" ], [ "# Load the fear and greed sentiment data for Bitcoin\ndf = pd.read_csv('btc_sentiment.csv', index_col=\"date\", infer_datetime_format=True, parse_dates=True)\ndf = df.drop(columns=\"fng_classification\")\ndf.head()", "_____no_output_____" ], [ "# Load the historical closing prices for Bitcoin\ndf2 = pd.read_csv('btc_historic.csv', index_col=\"Date\", infer_datetime_format=True, parse_dates=True)['Close']\ndf2 = df2.sort_index()\ndf2.tail()", "_____no_output_____" ], [ "# Join the data into a single DataFrame\ndf = df.join(df2, how=\"inner\")\ndf.tail()", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "# This function accepts the column number for the features (X) and the target (y)\n# It chunks the data up with a rolling window of Xt-n to predict Xt\n# It returns a numpy array of X any y\ndef window_data(df, window, feature_col_number, target_col_number):\n X = []\n y = []\n for i in range(len(df) - window - 1):\n features = df.iloc[i:(i + window), feature_col_number]\n target = df.iloc[(i + window), target_col_number]\n X.append(features)\n y.append(target)\n return np.array(X), np.array(y).reshape(-1, 1)", "_____no_output_____" ], [ "# Predict Closing Prices using a 10 day window of previous fng values\n# Then, experiment with window sizes anywhere from 1 to 10 and see how the model performance changes\nwindow_size = 10\n\n# Column index 0 is the 'fng_value' column\n# Column index 1 is the `Close` column\nfeature_column = 0\ntarget_column = 1\nX, y = window_data(df, window_size, feature_column, target_column)", "_____no_output_____" ], [ "# Use 70% of the data for training and the remaineder for testing\nsplit = int(0.7 * len(X))\n\nX_train = X[: split]\nX_test = X[split:]\n\ny_train = y[: split]\ny_test = y[split:]", "_____no_output_____" ], [ "# Use the MinMaxScaler to scale data between 0 and 1.\n# Creating a MinMaxScaler object\nscaler = MinMaxScaler()\n\n# Fitting the MinMaxScaler object with the features data X\nscaler.fit(X)\n\n# Scaling the features training and testing sets\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\n# Fitting the MinMaxScaler object with the target data Y\nscaler.fit(y)\n\n# Scaling the target training and testing sets\ny_train_scaled = scaler.transform(y_train)\ny_test_scaled = scaler.transform(y_test)", "_____no_output_____" ], [ "# Reshape the features for the model\nX_train_scaled = X_train_scaled.reshape((X_train_scaled.shape[0], X_train_scaled.shape[1], 1))\nX_test_scaled = X_test_scaled.reshape((X_test_scaled.shape[0], X_test_scaled.shape[1], 1))", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "## Build and Train the LSTM RNN\n\nIn this section, you will design a custom LSTM RNN and fit (train) it using the training data.\n\nYou will need to:\n1. Define the model architecture\n2. Compile the model\n3. Fit the model to the training data\n\n### Hints:\nYou will want to use the same model architecture and random seed for both notebooks. This is necessary to accurately compare the performance of the FNG model vs the closing price model. ", "_____no_output_____" ] ], [ [ "# Build the LSTM model. \n# The return sequences need to be set to True if you are adding additional LSTM layers, but \n# You don't have to do this for the final layer. \n# Note: The dropouts help prevent overfitting\n# Note: The input shape is the number of time steps and the number of indicators\n# Note: Batching inputs has a different input shape of Samples/TimeSteps/Features\n\n# Defining the LSTM RNN model.\nmodel = Sequential()\n\n# Initial model setup\nnumber_units = 50\ndropout_fraction = 0.2\n\n# Layer 1\nmodel.add(LSTM(\n units=number_units,\n return_sequences=True,\n input_shape=(X_train_scaled.shape[1], 1))\n )\nmodel.add(Dropout(dropout_fraction))\n\n# Layer 2\nmodel.add(LSTM(units=number_units, return_sequences=True))\nmodel.add(Dropout(dropout_fraction))\n\n# Layer 3\nmodel.add(LSTM(units=number_units))\nmodel.add(Dropout(dropout_fraction))\n\n# Output layer\nmodel.add(Dense(1))", "_____no_output_____" ], [ "# Compile the model\nmodel.compile(optimizer=\"adam\", loss=\"mean_squared_error\")", "_____no_output_____" ], [ "# Summarize the model\nmodel.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nlstm (LSTM) (None, 10, 50) 10400 \n_________________________________________________________________\ndropout (Dropout) (None, 10, 50) 0 \n_________________________________________________________________\nlstm_1 (LSTM) (None, 10, 50) 20200 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 10, 50) 0 \n_________________________________________________________________\nlstm_2 (LSTM) (None, 50) 20200 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 50) 0 \n_________________________________________________________________\ndense (Dense) (None, 1) 51 \n=================================================================\nTotal params: 50,851\nTrainable params: 50,851\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "# Train the model\n# Use at least 10 epochs\n# Do not shuffle the data\n# Experiement with the batch size, but a smaller batch size is recommended\nmodel.fit(X_train_scaled, y_train_scaled, epochs=50, shuffle=False, batch_size=10, verbose=1)", "Epoch 1/50\n38/38 [==============================] - 8s 26ms/step - loss: 0.0710\nEpoch 2/50\n38/38 [==============================] - 1s 24ms/step - loss: 0.0635\nEpoch 3/50\n38/38 [==============================] - 1s 31ms/step - loss: 0.0719\nEpoch 4/50\n38/38 [==============================] - 1s 30ms/step - loss: 0.0616\nEpoch 5/50\n38/38 [==============================] - 1s 30ms/step - loss: 0.0577\nEpoch 6/50\n38/38 [==============================] - 1s 36ms/step - loss: 0.0547\nEpoch 7/50\n38/38 [==============================] - 1s 26ms/step - loss: 0.0521\nEpoch 8/50\n38/38 [==============================] - 1s 23ms/step - loss: 0.0499\nEpoch 9/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0513\nEpoch 10/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0494\nEpoch 11/50\n38/38 [==============================] - 1s 21ms/step - loss: 0.0484\nEpoch 12/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0484\nEpoch 13/50\n38/38 [==============================] - 1s 20ms/step - loss: 0.0489\nEpoch 14/50\n38/38 [==============================] - 1s 18ms/step - loss: 0.0474\nEpoch 15/50\n38/38 [==============================] - 1s 20ms/step - loss: 0.0467\nEpoch 16/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0448\nEpoch 17/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0440\nEpoch 18/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0440\nEpoch 19/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0433\nEpoch 20/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0436\nEpoch 21/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0444\nEpoch 22/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0433\nEpoch 23/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0442\nEpoch 24/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0425\nEpoch 25/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0423\nEpoch 26/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0423\nEpoch 27/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0411\nEpoch 28/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0422\nEpoch 29/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0422\nEpoch 30/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0415\nEpoch 31/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0418\nEpoch 32/50\n38/38 [==============================] - 1s 24ms/step - loss: 0.0407\nEpoch 33/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0398\nEpoch 34/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0403\nEpoch 35/50\n38/38 [==============================] - 1s 20ms/step - loss: 0.0400\nEpoch 36/50\n38/38 [==============================] - 1s 22ms/step - loss: 0.0390\nEpoch 37/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0392\nEpoch 38/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0385\nEpoch 39/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0379\nEpoch 40/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0391\nEpoch 41/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0386\nEpoch 42/50\n38/38 [==============================] - 1s 20ms/step - loss: 0.0380\nEpoch 43/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0403\nEpoch 44/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0381\nEpoch 45/50\n38/38 [==============================] - 1s 20ms/step - loss: 0.0375\nEpoch 46/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0376\nEpoch 47/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0383\nEpoch 48/50\n38/38 [==============================] - 1s 20ms/step - loss: 0.0390\nEpoch 49/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0371\nEpoch 50/50\n38/38 [==============================] - 1s 19ms/step - loss: 0.0393\n" ] ], [ [ "---", "_____no_output_____" ], [ "## Model Performance\n\nIn this section, you will evaluate the model using the test data. \n\nYou will need to:\n1. Evaluate the model using the `X_test` and `y_test` data.\n2. Use the X_test data to make predictions\n3. Create a DataFrame of Real (y_test) vs predicted values. \n4. Plot the Real vs predicted values as a line chart\n\n### Hints\nRemember to apply the `inverse_transform` function to the predicted and y_test values to recover the actual closing prices.", "_____no_output_____" ] ], [ [ "# Evaluate the model\nmodel.evaluate(X_test_scaled, y_test_scaled)", "5/5 [==============================] - 0s 10ms/step - loss: 0.0772\n" ], [ "# Make some predictions\npredicted = model.predict(X_test_scaled)", "_____no_output_____" ], [ "# Recover the original prices instead of the scaled version\npredicted_prices = scaler.inverse_transform(predicted)\nreal_prices = scaler.inverse_transform(y_test_scaled.reshape(-1, 1))", "_____no_output_____" ], [ "# Create a DataFrame of Real and Predicted values\nstocks = pd.DataFrame({\n \"Real\": real_prices.ravel(),\n \"Predicted\": predicted_prices.ravel()\n}, index = df.index[-len(real_prices): ]) \nstocks.head()", "_____no_output_____" ], [ "# Plot the real vs predicted values as a line chart\nstocks.plot(title=\"Real Vs. Predicted Prices\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ] ]