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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4aab64f7313fdafcf4c52781858a57f1facf313b
| 297,754 |
ipynb
|
Jupyter Notebook
|
notebooks/click-sequence-model.ipynb
|
DJCordhose/ux-by-tfjs
|
d8b5e8059a406264b430250e95107e2cacf7eb68
|
[
"Apache-2.0"
] | 18 |
2019-03-22T19:42:31.000Z
|
2022-03-04T22:43:42.000Z
|
notebooks/click-sequence-model.ipynb
|
DJCordhose/ux-by-tfjs
|
d8b5e8059a406264b430250e95107e2cacf7eb68
|
[
"Apache-2.0"
] | 6 |
2021-03-01T22:27:25.000Z
|
2022-03-03T22:16:17.000Z
|
notebooks/click-sequence-model.ipynb
|
DJCordhose/ux-by-tfjs
|
d8b5e8059a406264b430250e95107e2cacf7eb68
|
[
"Apache-2.0"
] | 3 |
2019-04-01T10:02:01.000Z
|
2019-09-30T15:29:41.000Z
| 167.277528 | 100,732 | 0.828503 |
[
[
[
"<a href=\"https://colab.research.google.com/github/DJCordhose/ux-by-tfjs/blob/master/notebooks/click-sequence-model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Training on Sequences of Clicks on the Server\n\nMake sure to run this from top to bottom to export model, otherwise names of layers cause tf.js to bail out",
"_____no_output_____"
]
],
[
[
"# Gives us a well defined version of tensorflow\n\ntry:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass",
"TensorFlow 2.x selected.\n"
],
[
"import tensorflow as tf\nprint(tf.__version__)",
"2.0.0-rc0\n"
],
[
"# a small sanity check, does tf seem to work ok?\nhello = tf.constant('Hello TF!')\nprint(\"This works: {}\".format(hello))",
"This works: b'Hello TF!'\n"
],
[
"# this should return True even on Colab\ntf.test.is_gpu_available()",
"_____no_output_____"
],
[
"tf.test.is_built_with_cuda()",
"_____no_output_____"
],
[
"tf.executing_eagerly()",
"_____no_output_____"
]
],
[
[
"## load data",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nprint(pd.__version__)",
"0.24.2\n"
],
[
"import numpy as np\nprint(np.__version__)",
"1.16.5\n"
],
[
"# local\n# URL = '../data/click-sequence.json'\n\n# remote\nURL = 'https://raw.githubusercontent.com/DJCordhose/ux-by-tfjs/master//data/click-sequence.json'\n\n\ndf = pd.read_json(URL, typ='series')",
"_____no_output_____"
],
[
"len(df)",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"type(df[0])",
"_____no_output_____"
],
[
"df[0], df[1]",
"_____no_output_____"
],
[
"all_buttons = set()\nfor seq in df:\n for button in seq:\n all_buttons.add(button)\n\nall_buttons.add('<START>')\nall_buttons.add('<EMPTY>')\n\nall_buttons = list(all_buttons)\n\nall_buttons",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer, LabelEncoder\nencoder = LabelEncoder()\nencoder.fit(all_buttons)\nencoder.classes_",
"_____no_output_____"
],
[
"transfomed_labels = [encoder.transform(seq) for seq in df if len(seq) != 0]\ntransfomed_labels",
"_____no_output_____"
]
],
[
[
"## pre-process data into chunks",
"_____no_output_____"
]
],
[
[
"empty = encoder.transform(['<EMPTY>'])\nstart = encoder.transform(['<START>'])\nchunk_size = 5",
"_____no_output_____"
],
[
"# [ 1, 11, 7, 11, 6] => [[[0, 0, 0, 0, 1], 11], [[0, 0, 0, 1, 11], 7], [[0, 0, 1, 11, 7], 11], [[0, 1, 11, 7, 11], 6]]\n\ndef create_sequences(seq, chunk_size, empty, start):\n # all sequences implicitly start\n seq = np.append(start, seq)\n # if sequence is too short, we pad it to minimum size at the beginning\n seq = np.append(np.full(chunk_size - 1, empty), seq)\n \n seqs = np.array([])\n for index in range(chunk_size, len(seq)):\n y = seq[index]\n x = seq[index-chunk_size : index]\n seqs = np.append(seqs, [x, y])\n return seqs",
"_____no_output_____"
],
[
"\n# seq = transfomed_labels[0]\n# seq = transfomed_labels[9]\nseq = transfomed_labels[3]\nseq",
"_____no_output_____"
],
[
"create_sequences(seq, chunk_size, empty, start)",
"_____no_output_____"
],
[
"seqs = np.array([])\nfor seq in transfomed_labels:\n seqs = np.append(seqs, create_sequences(seq, chunk_size, empty, start))\nseqs = seqs.reshape(-1, 2)\nseqs.shape",
"_____no_output_____"
],
[
"X = seqs[:, 0]\n# X = X.reshape(-1, chunk_size)\nX = np.vstack(X).astype('int32')\nX.dtype, X.shape",
"_____no_output_____"
],
[
"y = seqs[:, 1].astype('int32')\ny.dtype, y.shape, y",
"_____no_output_____"
]
],
[
[
"## Training",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import Dense, LSTM, GRU, SimpleRNN, Embedding, BatchNormalization, Dropout\nfrom tensorflow.keras.models import Sequential, Model\n\nembedding_dim = 2\nn_buttons = len(encoder.classes_)\n\ndropout = .6\nrecurrent_dropout = .6\n\nmodel = Sequential()\nmodel.add(Embedding(name='embedding',\n input_dim=n_buttons, \n output_dim=embedding_dim, \n input_length=chunk_size))\n\nmodel.add(SimpleRNN(units=50, activation='relu', name=\"RNN\", recurrent_dropout=recurrent_dropout))\n# model.add(GRU(units=25, activation='relu', name=\"RNN\", recurrent_dropout=0.5))\n# model.add(LSTM(units=25, activation='relu', name=\"RNN\", recurrent_dropout=0.5))\n\nmodel.add(BatchNormalization())\nmodel.add(Dropout(dropout))\n\nmodel.add(Dense(units=n_buttons, name='softmax', activation='softmax'))\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()",
"WARNING:tensorflow:Large dropout rate: 0.6 (>0.5). In TensorFlow 2.x, dropout() uses dropout rate instead of keep_prob. Please ensure that this is intended.\nWARNING:tensorflow:Large dropout rate: 0.6 (>0.5). In TensorFlow 2.x, dropout() uses dropout rate instead of keep_prob. Please ensure that this is intended.\nModel: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding (Embedding) (None, 5, 2) 28 \n_________________________________________________________________\nRNN (SimpleRNN) (None, 50) 2650 \n_________________________________________________________________\nbatch_normalization (BatchNo (None, 50) 200 \n_________________________________________________________________\ndropout (Dropout) (None, 50) 0 \n_________________________________________________________________\nsoftmax (Dense) (None, 14) 714 \n=================================================================\nTotal params: 3,592\nTrainable params: 3,492\nNon-trainable params: 100\n_________________________________________________________________\n"
],
[
"%%time\n\nEPOCHS = 1000\nBATCH_SIZE = 100\n\nhistory = model.fit(X, y, \n batch_size=BATCH_SIZE,\n epochs=EPOCHS, verbose=0, validation_split=0.2)",
"WARNING:tensorflow:Large dropout rate: 0.6 (>0.5). In TensorFlow 2.x, dropout() uses dropout rate instead of keep_prob. Please ensure that this is intended.\nWARNING:tensorflow:Large dropout rate: 0.6 (>0.5). In TensorFlow 2.x, dropout() uses dropout rate instead of keep_prob. Please ensure that this is intended.\nWARNING:tensorflow:Entity <function Function._initialize_uninitialized_variables.<locals>.initialize_variables at 0x7fe6b0a68d90> 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: Entity <function Function._initialize_uninitialized_variables.<locals>.initialize_variables at 0x7fe6b0a68d90> 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:Large dropout rate: 0.6 (>0.5). In TensorFlow 2.x, dropout() uses dropout rate instead of keep_prob. Please ensure that this is intended.\nWARNING:tensorflow:Large dropout rate: 0.6 (>0.5). In TensorFlow 2.x, dropout() uses dropout rate instead of keep_prob. Please ensure that this is intended.\nCPU times: user 59.5 s, sys: 4.53 s, total: 1min 4s\nWall time: 45.9 s\n"
],
[
"loss, accuracy = model.evaluate(X, y, batch_size=BATCH_SIZE)\naccuracy",
"\r279/1 [==================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================] - 0s 48us/sample - loss: 1.4925 - accuracy: 0.5269\n"
],
[
"%matplotlib inline\n\nimport matplotlib.pyplot as plt\n\n# plt.yscale('log')\nplt.ylabel('loss')\nplt.xlabel('epochs')\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\n\nplt.legend(['loss', 'val_loss'])",
"_____no_output_____"
],
[
"plt.ylabel('accuracy')\nplt.xlabel('epochs')\n\n# TF 2.0\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\n# plt.plot(history.history['acc'])\n# plt.plot(history.history['val_acc'])\n\nplt.legend(['accuracy', 'val_accuracy'])",
"_____no_output_____"
],
[
"model.predict([[X[0]]])",
"_____no_output_____"
],
[
"model.predict([[X[0]]]).argmax()",
"_____no_output_____"
],
[
"y[0]",
"_____no_output_____"
],
[
"y_pred = model.predict([X]).argmax(axis=1)\ny_pred",
"_____no_output_____"
],
[
"y",
"_____no_output_____"
],
[
"# TF 2.0\ncm = tf.math.confusion_matrix(labels=tf.constant(y, dtype=tf.int64), predictions=tf.constant(y_pred, dtype=tf.int64))\ncm",
"_____no_output_____"
],
[
"import seaborn as sns\n\nclasses = encoder.classes_\n\nplt.figure(figsize=(8, 8))\n\nsns.heatmap(cm, annot=True, fmt=\"d\", xticklabels=classes, yticklabels=classes);",
"_____no_output_____"
],
[
"embedding_layer = model.get_layer('embedding')\nembedding_model = Model(inputs=model.input, outputs=embedding_layer.output)\nembeddings_2d = embedding_model.predict(X)\nembeddings_2d.shape",
"_____no_output_____"
],
[
"encoder.classes_",
"_____no_output_____"
],
[
"encoded_classes = encoder.transform(encoder.classes_)",
"_____no_output_____"
],
[
"same_button_seqs = np.repeat(encoded_classes, 5).reshape(14, 5)",
"_____no_output_____"
],
[
"embeddings_2d = embedding_model.predict(same_button_seqs)\nembeddings_2d.shape",
"_____no_output_____"
],
[
"only_first = embeddings_2d[:, 0, :]\nonly_first",
"_____no_output_____"
],
[
"# for printing only\nplt.figure(figsize=(10,10))\n# plt.figure(dpi=600)\n# plt.figure(dpi=300)\n\nplt.axis('off')\n\n\nplt.scatter(only_first[:, 0], only_first[:, 1], s=200)\nfor name, x_pos, y_pos in zip(encoder.classes_, only_first[:, 0], only_first[:, 1]):\n# print(name, (x_pos, y_pos))\n plt.annotate(name, (x_pos, y_pos), rotation=-60, size=25)",
"_____no_output_____"
],
[
"from sklearn.decomposition import PCA\nimport numpy as np\n\nembeddings_1d = PCA(n_components=1).fit_transform(only_first)\n\n# for printing only\nplt.figure(figsize=(25,5))\n# plt.figure(dpi=300)\n\nplt.axis('off')\n\nplt.scatter(embeddings_1d, np.zeros(len(embeddings_1d)), s=80)\nfor name, x_pos in zip(encoder.classes_, embeddings_1d):\n plt.annotate(name, (x_pos, 0), rotation=-45)",
"_____no_output_____"
]
],
[
[
"## Convert Model into tfjs format\n\n* https://www.tensorflow.org/js/tutorials/conversion/import_keras",
"_____no_output_____"
]
],
[
[
"!pip install -q tensorflowjs",
"\u001b[K |████████████████████████████████| 51kB 2.0MB/s \n\u001b[K |████████████████████████████████| 17.3MB 7.3MB/s \n\u001b[K |████████████████████████████████| 81kB 22.5MB/s \n\u001b[K |████████████████████████████████| 2.8MB 37.9MB/s \n\u001b[K |████████████████████████████████| 109.2MB 337kB/s \n\u001b[K |████████████████████████████████| 317kB 37.4MB/s \n\u001b[K |████████████████████████████████| 256kB 45.0MB/s \n\u001b[K |████████████████████████████████| 890kB 47.3MB/s \n\u001b[K |████████████████████████████████| 655kB 43.4MB/s \n\u001b[?25h Building wheel for PyInquirer (setup.py) ... \u001b[?25l\u001b[?25hdone\n Building wheel for regex (setup.py) ... \u001b[?25l\u001b[?25hdone\n\u001b[31mERROR: google-colab 1.0.0 has requirement six~=1.12.0, but you'll have six 1.11.0 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"
],
[
"model.save('ux.h5', save_format='h5')",
"_____no_output_____"
],
[
"!ls -l",
"total 88\ndrwxr-xr-x 1 root root 4096 Aug 27 16:17 sample_data\n-rw-r--r-- 1 root root 82488 Sep 15 08:56 ux.h5\n"
],
[
"!tensorflowjs_converter --input_format keras ux.h5 tfjs",
"Traceback (most recent call last):\n File \"/usr/local/bin/tensorflowjs_converter\", line 6, in <module>\n from tensorflowjs.converters.converter import pip_main\n File \"/usr/local/lib/python3.6/dist-packages/tensorflowjs/__init__.py\", line 21, in <module>\n from tensorflowjs import converters\n File \"/usr/local/lib/python3.6/dist-packages/tensorflowjs/converters/__init__.py\", line 24, in <module>\n from tensorflowjs.converters.tf_saved_model_conversion_v2 import convert_tf_saved_model\n File \"/usr/local/lib/python3.6/dist-packages/tensorflowjs/converters/tf_saved_model_conversion_v2.py\", line 36, in <module>\n import tensorflow_hub as hub\n File \"/usr/local/lib/python3.6/dist-packages/tensorflow_hub/__init__.py\", line 29, in <module>\n from tensorflow_hub.estimator import LatestModuleExporter\n File \"/usr/local/lib/python3.6/dist-packages/tensorflow_hub/estimator.py\", line 63, in <module>\n class LatestModuleExporter(tf_v1.estimator.Exporter):\nAttributeError: module 'tensorflow_hub.tf_v1' has no attribute 'estimator'\n"
],
[
"!ls -l tfjs",
"ls: cannot access 'tfjs': No such file or directory\n"
]
],
[
[
"Download using _Files_ menu on the left",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aab8cbea76fa053248fa79da0a24407bca96b73
| 841,054 |
ipynb
|
Jupyter Notebook
|
tutorial_squid_sim.ipynb
|
ucd-squidlab/SQUID_numerical_models
|
dafefda35fcbe24a383a753c74e772b3ce800b13
|
[
"MIT"
] | 1 |
2019-12-02T05:49:47.000Z
|
2019-12-02T05:49:47.000Z
|
tutorial_squid_sim.ipynb
|
fordskydog/SQUID_models
|
f01d01457ed127301813d3fec7c76802af8e511e
|
[
"MIT"
] | null | null | null |
tutorial_squid_sim.ipynb
|
fordskydog/SQUID_models
|
f01d01457ed127301813d3fec7c76802af8e511e
|
[
"MIT"
] | null | null | null | 1,031.968098 | 149,536 | 0.955408 |
[
[
[
"### Introduction\n\nThis is an instruction set for running SQUID simulations using a handful of packages writen in python 3. Each package is created around a SQUID model and includes a solver and some utilities to use the solver indirectly to produce more complicated output.\n\nThis tutorial will walk through using the **noisy_squid.py** package. Includeded in each SQUID package are:\n**basic model** - gives timeseries output of the state of the SQUID\n**vj_timeseries()** - gives a plot and csv file of the timeseries state of the SQUID\n**iv_curve()** - gives contour plot (discrete values of one parameter) of I-V curve and csv file\n**vphi_curve()** - gives countour plot (discrete values of one parameter) of V-PHI curve and csv file\n**transfer_fn()** - gives plots of average voltage surface and transfer function surface as well as csv files for each. Returns array of average voltage over the input parameter space in i and phia\n\nAssociated with each package:\n**dev_package_name.ipynb** - a jupyter notebook used in develping model and utilities\n**package_name.ipynb** - a refined jupyter notebook with helpful explanations of how the model and utilities work\n**package_name.py** - a python 3 file containing only code, inteded for import into python session of some sort\n\n\n### Packages\n\nThere are four packages, **noisy_single_junction.py**, **quiet_squid.py**, **noisy_squid.py**, and **noisy_squid_2nd_order.py**. The first is somewhat separate and documentation is provided in the jupyter notebook for that file.\n\nEach package requires simulation inputs, namely the time step size tau, the number of steps to simulate **nStep**, an initial state vector **s**. Also required are a set of input parameters **i** and **phia**, and physical parameters **alpha**, **betaL**, **eta**, **rho** at a minimum. The two more detailed solvers require a noise parameter **Gamma**, and perhaps two more parameters **betaC** and **kappa**. These are all supplied as one array of values called par.\n\nThe other three are useful to simulate a two-junction SQUID in different circumstances.\n\n**quiet_squid.py** simulates a two-junction SQUID with no thermal noise and no appreciable shot noise. This model is first order and so does not account for capacitive effects. This model assumes no noise, and no capacitance. Use this model if the dynamics of the system without noise are to be investigated.\n\n**noisy_squid.py** is similar to the above, but includes the effects of thermal Johnson noise in the junctions. This model is also first order, assuming negligible effects from capacitance. It is sometimes necessary and or safe to assume negligible effects from capacitance, or zero capacitance. It will be necessary to use the first order model in this case, as setting capacitance to zero in the second order model will result in divide by zero errors.\n\n**noisy_squid_2nd_order.py** is similar to the above, but includes second order effects due to capacitance. This model should be used if capacitance should be considered non-zero.",
"_____no_output_____"
],
[
"#### Prerequisites\n\nThe only prerequisite is to have python 3 installed on your machine. You may prefer to use some python environment like jupyter notebook or Spyder. The easiest way to get everything is by downloading and installing the latest distribution of **Anaconda**, which will install python 3, juputer notebook, and Spyder as well as providing convenient utilities for adding community provided libraries. Anaconda download link provided:\n\nhttps://www.anaconda.com/distribution/\n\nWorking from the console is easy enough, but working in your prefered development environment will be easier.",
"_____no_output_____"
],
[
"### Prepare a file for output\n\nThis tutorial will work out of the console, but the same commands will work for a development environment.\n\nCreate a file folder in a convenient location on your computer. Place the relevant python file described above in the file. Output files including csv data files and png plots will be stored in this file folder. All file outputs are named like **somethingDatetime.csv** or .png.",
"_____no_output_____"
],
[
"### Open a python environment\n\nThese packages can be used directly from the console or within your favorite python development environment.\n\nThis tutorial will assume the user is working from the console. Open a command prompt. You can do this on Windows by typing \"cmd\" in the start search bar and launching **Command Prompt**. Change directory to the file folder created in the step above.\n\n***cd \"file\\tree\\folder\"***\n\nWith the command prompt indicating you are in the folder, type \"python\" and hit enter. If there are multiple instances (different iterations) of python on your machine, this may need to be accounted for in launching the correct version. See the internet for help on this.\n\nIf you have a favorite python environment, be sure to launch in the folder or change the working directory of the development environment to the folder you created. If you do not wish to change the working directory, place the package .py file in the working directory.",
"_____no_output_____"
],
[
"### Load the relevant package\n\nWith python running, at the command prompt in the console, import the python file containing the model needed.\n\nIn this tutorial we will use the first order model including noise, **noisy_squid.py**. Type \"import noisy_squid\". Execute the command by hitting enter on the console. It may be easier to give the package a nickname, as we will have to type it every time we call a function within it. Do this by instead typing \"import noisy_squid as nickname\", as below.",
"_____no_output_____"
]
],
[
[
"import noisy_squid as ns",
"_____no_output_____"
]
],
[
[
"We need a standard package called **numpy** as well. This library includes some tools we need to create input, namely numpy arrays. Type \"import numpy as np\" and hit enter.\n\nThe code inside the packages aslo relies on other standard packages. Those are loaded from within the package.",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
]
],
[
[
"#### Getting Help\n\nYou can access the short help description of each model and utility by typing:\n\n***?package_name.utiltiy_name()***\n\nExample:",
"_____no_output_____"
]
],
[
[
"?ns.transfer_fn()",
"_____no_output_____"
]
],
[
[
"### noisy_squid.noisySQUID()\n\nThe model itself, **noisySQUID()** can be run and gives a timeseries output array for the state of the system.\n\nIncluded in the output array are **delta_1**, **delta_2**, **j**, **v_1**, **v_2**, and **v** at each simulated moment in time.\n\nTo run, first we need to set up some parameters. To see detailed explanations of these, see the developement log in the jupyter notebook associated with the package.\n\nParameter definitions can be handled in the function call or defined before the function call.\n\nAn example of the former: Define values using parameter names, build a parameter array, and finally call the function. Remember, s and par are numpy arrays.",
"_____no_output_____"
]
],
[
[
"# define values\nnStep = 8000\ntau = .1\ns = np.array([0.,0.])\nalpha = 0.\nbetaL = 1.\neta = 0.\nrho = 0.\ni = 1.5\nphia = .5\nGamma = .05\npar = np.array([alpha,betaL,eta,rho,i,phia,Gamma])",
"_____no_output_____"
]
],
[
[
"Now we can call the simulation. Type \n\n***noisy_squid.noisySQUID(nStep,tau,s,par)***\n\nto call the function. We may wish to define a new variable to hold the simple array output. We can then show the output by typing the variable again. We do this below by letting **S** be the output. **S** will take on the form of the output, here an array.",
"_____no_output_____"
]
],
[
[
"S = noisy_squid.noisySQUID(nStep,tau,s,par)",
"_____no_output_____"
]
],
[
[
"The shortcut method is to call the function only, replacing varibles with values. This example includes a linebreak \"\\\". You can just type it out all in one line if it will fit.",
"_____no_output_____"
]
],
[
[
"S = noisy_squid.noisySQUID(8000,.1,np.array([0.,0.]),\\\n np.array([0.,1.,0.,0.,1.5,.5,.05]))",
"_____no_output_____"
]
],
[
[
"We can check the output. Have a look at **S** by typing it.",
"_____no_output_____"
]
],
[
[
"S",
"_____no_output_____"
]
],
[
[
"This doesn't mean much. Since the voltage accross the circuit, **v**, is stored in **S** as the 7th row (index 6), we can plot the voltage timeseries. The time **theta** is stored as the first row (index 0). We will need the ploting package **matplotlib.pyplot** to do this.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.plot(S[0],S[6])\nplt.xlabel(r'time, $\\theta$')\nplt.ylabel(r'ave voltage, $v$')",
"_____no_output_____"
]
],
[
[
"This model will be useful if you wish to extend the existing utilites here or develop new utilities. To explore the nature of SQUID parameter configurations, it may be easier to start with the other utilities provided.",
"_____no_output_____"
],
[
"### noisy_squid.vj_timeseries()\n\nuse \"**'package_name'.vj_timeseries()**\" or \"**'package_nickname'.vj_timeseries()**\".\n\nThis utility does the same as the funciton described above, but gives a plot of the output and creates a csv of the timeseries output array. These are named **timeseries'datetime'.csv** and .png. The plot includes the voltage timeseries and the circulating current time series. The csv file contains metadata describing the parameters.\n\nTo run this, define parameters as described above, and call the function. This time,we will change the value of **nStep** to be shorter so we can see some detail in the trace.\n\nThis utility does not return anything to store. The only output is the plot and the csv file, so don't bother storing the function call output.",
"_____no_output_____"
]
],
[
[
"# define values\nnStep = 800\ntau = .1\ns = np.array([0.,0.])\nalpha = 0.\nbetaL = 1.\neta = 0.\nrho = 0.\ni = 1.5\nphia = .5\nGamma = .05\npar = np.array([alpha,betaL,eta,rho,i,phia,Gamma])",
"_____no_output_____"
],
[
"ns.vj_timeseries(nStep,tau,s,par)",
"csv file written out: timeseries20191201023401.csv\npng file written out: timeseris20191201023401.png\n"
]
],
[
[
"### noisy_squid.iv_curve()\n\nThis utility is used to create plots and data of the average voltage output of the SQUID vs the applied bias current. We can sweep any of the other parameters and create contours. The utility outputs a data file and plot, **IV'datetime'.csv** and .png.\n\nDefine the parameter array as normal. The parameter to sweep will be passed separately as a list of values at which to draw contours. If a value for the parameter to sweep is passed in **par**, it will simply be ignored in favor of the values in the list.\n\nA list is defined by square brackets and values are separated by a comma. This parameter list must be a list and not an array.\n\nThe name of the list should be different than parameter name it represents. In this case, I wish to look at three contours corresponding to values of the applied flux **phia**. I name a list **Phi** and give it values.\n\nPlace the parameter list in the function call by typing the **parameter_name=List_name**. In this case, **phia=Phi**.\n\nThis utility has no console output, so don't bother storing it in a variable.",
"_____no_output_____"
]
],
[
[
"Phi = [.2,.8,1.6]",
"_____no_output_____"
],
[
"ns.iv_curve(nStep,tau,s,par,phia=Phi)",
"Progress: [####################] 100.0%\ncsv file written out: IV20191201024600.csv\npng file written out: IV20191201024600.png\n"
]
],
[
[
"This curve is very noisy. To get finer detail, increase **nStep** and decrease **tau**.\n\nThe underlying numerical method is accurate but slow. Computation time considerations must be considered from here on. I recommend testing a set of parameters with a small number of large steps first, then adjusting for more detail as needed.\n\nFrom here on, the utilities are looking at average voltage. To get an accurate average voltage you need lots of voltage values, and thus large **nStep**. The error in the underlying Runge-Kutta 4th order method is determined by the size of the time step, smaller = less error. Thus, a more accurate timeseries is provided by a smaller time step **tau**. A more accurate timeseries will result in better convergence of the model to the expected physical output, thus finer detail. \n\nComputation time will grow directly with the size of **nStep** but will be uneffected by the size of **tau**. If **tau** is larger than one, there will be instability in the method, it will likely not work. There is a minimum size for **tau** as well, to insure stability. Something on the order of 0.1 to 0.01 will usually suffice.\n\nThese parameters are your tradeoff control in detail vs computation time.\n\nAt any rate, the erratic effect of noise is best dampened by using a larger **nStep**.\n\nLets try it with 10 times as many time steps.",
"_____no_output_____"
]
],
[
[
"nStep = 8000\ntau = .1",
"_____no_output_____"
],
[
"ns.iv_curve(nStep,tau,s,par,phia=Phi)",
"Progress: [####################] 100.0%\ncsv file written out: IV20191201025539.csv\npng file written out: IV20191201025539.png\n"
]
],
[
[
"This looks better. To get a usable plot, it will probably be necessary to set **nStep** on the order of 10^4 to 10^6. Start lower if possible.\n\nLets try **nStep**=8\\*10^5.",
"_____no_output_____"
]
],
[
[
"nStep = 80000",
"_____no_output_____"
],
[
"ns.iv_curve(nStep,tau,s,par,phia=Phi)",
"Progress: [####################] 100.0%\ncsv file written out: IV20191201040138.csv\npng file written out: IV20191201040138.png\n"
]
],
[
[
"We can look at a sweep of a different parameter by reseting **phia** to say .2, and creating a list to represent a different parameter. Lets sweep **betaL**.",
"_____no_output_____"
]
],
[
[
"phia = .2\nBeta = [.5,1.,2.]",
"_____no_output_____"
],
[
"ns.iv_curve(nStep,tau,s,par,betaL=Beta)",
"Progress: [####################] 100.0%\ncsv file written out: IV20191201030410.csv\npng file written out: IV20191201030410.png\n"
]
],
[
[
"### noisy_squid.vphi_curve()\n\nThis utility is used to create plots and data of the average voltage output of the SQUID vs the applied magnatic flux. We can sweep any of the other parameters and create contours. The utility outputs a data file and plot, **VPhi'datetime'.csv** and .png.\n\nDefine the parameter array as normal. The parameter to sweep will be passed separately as a list of values at which to draw contours. If a value for the parameter to sweep is passed in **par**, it will simply be ignored in favor of the values in the list.\n\nA list is defined by square brackets and values are separated by a comma. This parameter list must be a list and not an array.\n\nThe name of the list should be different than parameter name it represents. In this case, I wish to look at three contours corresponding to values of the inductance constant **betaL**. I named a list **Beta** above and gave it values.\n\nPlace the parameter list in the function call by typing the **parameter_name=List_name**. In this case, **betaL=Beta**.\n\nThis utility has no console output, so don't bother storing it in a variable.\n\nThis utility can be computationally expensive. See the notes on this in the **noisy_squid.iv_curve()** section.",
"_____no_output_____"
]
],
[
[
"ns.vphi_curve(nStep,tau,s,par,betaL=Beta)",
"Progress: [####################] 100.0%\ncsv file written out: VPhi20191201030635.csv\npng file written out: VPhi20191201030635.png\n"
]
],
[
[
"### noisy_squid.transfer_fn()\n\nThis utility creates the average voltage surface in bias current / applied flux space. It also calculates the partial derivative of the average voltage surface with respec to applied flux and returns this as the transfer funcion. These are named **AveVsurface'datetime'.png** and .csv, and **TransferFn'datetime'.png** and .csv. This utility also returns an array of average voltage values over the surface which can be stored for further manipulation.\n\nThis utility requires us to define an axis for both **i** and **phia**. We do this by making an array for each. We can define the individual elements of the array, but there is an easier way. We can make an array of values evenly spaced across an interval using **np.arange(start, stop+step, step)** as below.\n\nPass the other parameters as in the instructions under **noisy_squid()**. You may want to start with a smaller value for **nStep**.",
"_____no_output_____"
]
],
[
[
"nStep = 800\ni = np.arange(-3.,3.1,.1)\nphia = np.arange(-1.,1.1,.1)",
"_____no_output_____"
],
[
"vsurf = ns.transfer_fn(nStep,tau,s,par,i,phia)",
"Progress: [####################] 100.0%\ncsv file written out: AveVsurface20191201032043.csv\npng file written out: AveVsurface20191201032043.png\ncsv file written out: TransferFn20191201032043.csv\n"
]
],
[
[
"The average voltage surface looks ok, but not great. Noisy spots in the surface will negatively effect the transfer function determination. The transfer function surface has large derivatives in the corner which over saturate the plot hiding detail in most of the surface. To fix this, we need a truer average voltage surface. We need more time steps. If you have some time, try **nStep**=8000.\n\nNote that it may be possible to clean the data from the csv file and recover some detail in plotting. Be careful...",
"_____no_output_____"
]
],
[
[
"nStep = 8000",
"_____no_output_____"
],
[
"vsurf = ns.transfer_fn(nStep,tau,s,par,i,phia)",
"Progress: [####################] 100.0%\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",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aab991962b91f5e8b6e91c9350c9f4d36f0e539
| 9,809 |
ipynb
|
Jupyter Notebook
|
classic-machine-learning/fp_tree_prefixspan.ipynb
|
yefang008514/machinelearning
|
396c6301397aeb1ffb5aaa0387fdc13b5b76259a
|
[
"MIT"
] | 6,693 |
2018-09-13T05:46:51.000Z
|
2022-03-31T06:31:43.000Z
|
classic-machine-learning/fp_tree_prefixspan.ipynb
|
JinhuaSu/machinelearning
|
17302f708146ad46838b3782bf735364fa3cf16d
|
[
"MIT"
] | 18 |
2018-11-29T09:36:25.000Z
|
2021-06-30T03:04:57.000Z
|
classic-machine-learning/fp_tree_prefixspan.ipynb
|
JinhuaSu/machinelearning
|
17302f708146ad46838b3782bf735364fa3cf16d
|
[
"MIT"
] | 3,444 |
2018-09-14T01:36:45.000Z
|
2022-03-31T06:30:54.000Z
| 38.01938 | 166 | 0.462534 |
[
[
[
"Copyright (C) 2016 - 2019 Pinard Liu([email protected])\n\nhttps://www.cnblogs.com/pinard\n\nPermission given to modify the code as long as you keep this declaration at the top\n\n用Spark学习FP Tree算法和PrefixSpan算法 https://www.cnblogs.com/pinard/p/6340162.html",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\n\n#下面这些目录都是你自己机器的Spark安装目录和Java安装目录\nos.environ['SPARK_HOME'] = \"C:/Tools/spark-2.2.0-bin-hadoop2.6/\"\nos.environ['PYSPARK_PYTHON'] = \"C:/Users/tata/AppData/Local/Programs/Python/Python36/python.exe\"\n\nsys.path.append(\"C:/Tools/spark-2.2.0-bin-hadoop2.6/bin\")\nsys.path.append(\"C:/Tools/spark-2.2.0-bin-hadoop2.6/python\")\nsys.path.append(\"C:/Tools/spark-2.2.0-bin-hadoop2.6/python/pyspark\")\nsys.path.append(\"C:/Tools/spark-2.2.0-bin-hadoop2.6/python/lib\")\nsys.path.append(\"C:/Tools/spark-2.2.0-bin-hadoop2.6/python/lib/pyspark.zip\")\nsys.path.append(\"C:/Tools/spark-2.2.0-bin-hadoop2.6/python/lib/py4j-0.10.4-src.zip\")\nsys.path.append(\"C:/Program Files/Java/jdk1.8.0_171\")\n\nfrom pyspark import SparkContext\nfrom pyspark import SparkConf\n\n\nsc = SparkContext(\"local\",\"testing\")",
"_____no_output_____"
],
[
"print (sc)",
"<SparkContext master=local appName=testing>\n"
],
[
"from pyspark.mllib.fpm import FPGrowth\ndata = [[\"A\", \"B\", \"C\", \"E\", \"F\",\"O\"], [\"A\", \"C\", \"G\"], [\"E\",\"I\"], [\"A\", \"C\",\"D\",\"E\",\"G\"], [\"A\", \"C\", \"E\",\"G\",\"L\"],\n [\"E\",\"J\"],[\"A\",\"B\",\"C\",\"E\",\"F\",\"P\"],[\"A\",\"C\",\"D\"],[\"A\",\"C\",\"E\",\"G\",\"M\"],[\"A\",\"C\",\"E\",\"G\",\"N\"]]\nrdd = sc.parallelize(data, 2)\n#支持度阈值为20%\nmodel = FPGrowth.train(rdd, 0.2, 2)",
"_____no_output_____"
],
[
"sorted(model.freqItemsets().collect())",
"_____no_output_____"
],
[
"from pyspark.mllib.fpm import PrefixSpan\ndata = [\n [['a'],[\"a\", \"b\", \"c\"], [\"a\",\"c\"],[\"d\"],[\"c\", \"f\"]],\n [[\"a\",\"d\"], [\"c\"],[\"b\", \"c\"], [\"a\", \"e\"]],\n [[\"e\", \"f\"], [\"a\", \"b\"], [\"d\",\"f\"],[\"c\"],[\"b\"]],\n [[\"e\"], [\"g\"],[\"a\", \"f\"],[\"c\"],[\"b\"],[\"c\"]]\n ]\nrdd = sc.parallelize(data, 2)\nmodel = PrefixSpan.train(rdd, 0.5,4)",
"_____no_output_____"
],
[
"sorted(model.freqSequences().collect())",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaba1677e740955f86a2230c3c6cde86bf20bd2
| 181,900 |
ipynb
|
Jupyter Notebook
|
learn-calc-with-python.ipynb
|
codingEzio/code_python_learn_math
|
bd7869d05e1b4ec250cc5fa13470a960b299654e
|
[
"Unlicense"
] | null | null | null |
learn-calc-with-python.ipynb
|
codingEzio/code_python_learn_math
|
bd7869d05e1b4ec250cc5fa13470a960b299654e
|
[
"Unlicense"
] | null | null | null |
learn-calc-with-python.ipynb
|
codingEzio/code_python_learn_math
|
bd7869d05e1b4ec250cc5fa13470a960b299654e
|
[
"Unlicense"
] | null | null | null | 201.439646 | 36,888 | 0.917147 |
[
[
[
"## Learn Calculus with Python ",
"_____no_output_____"
],
[
"#### start",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nx = np.arange(0,100,0.1)\ny = np.cos(x)\n\nplt.plot(x,y)\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### normal function ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"def f(x):\n return x**3 / (25)\n\nf(30)\nf(10)",
"_____no_output_____"
],
[
"# num -> smooth ( how many dots )\nx = np.linspace(-30,30,num=1000) \ny = f(x)\n\nplt.plot(x,y)",
"_____no_output_____"
]
],
[
[
"#### exp",
"_____no_output_____"
]
],
[
[
"def exp(x):\n return np.e**x\n\n\nexp(2)\nnp.exp(2)\n\n\nxz = np.linspace(1, 20, num=100)\nyz = exp(xz)\n\nplt.plot(xz, yz)",
"_____no_output_____"
],
[
"def exp2(x):\n sum = 0\n for k in range(100):\n sum += float(x**k)/np.math.factorial(k)\n return sum\n\nexp2(1)\nexp(1)",
"_____no_output_____"
]
],
[
[
"#### log",
"_____no_output_____"
]
],
[
[
"# pick 100 items between 1 and 500 isometricly\nx = np.linspace(1,500,100,endpoint=False)\n\ny1 = np.log2(x)\ny2 = np.log(x)\ny3 = np.log10(x)\n\nplt.plot(x,y1,'red',x,y2,'green',x,y3,'blue')",
"_____no_output_____"
]
],
[
[
"#### trigonometric",
"_____no_output_____"
]
],
[
[
"pi_val = np.pi\npi_range = np.linspace(-2*pi_val,2*pi_val )\n\nplt.plot(\n pi_range,\n np.sin(pi_range)\n)\n\nplt.plot(\n pi_range,\n np.cos(pi_range)\n)",
"_____no_output_____"
]
],
[
[
"#### f(g(x))",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"f = lambda x:x+20\ng = lambda x:x**2\nh = lambda x:f(g(x))\n\nx = np.array(range(-30,30))\nplt.plot(x,h(x),'bs')",
"_____no_output_____"
]
],
[
[
"#### f<sup>-1</sup>(x)",
"_____no_output_____"
]
],
[
[
"w = lambda x: x**2\nwinv = lambda x: np.sqrt(x)\n\nx = np.linspace(0,2,100)\n\nplt.plot(x,w(x),'b',x,winv(x),'r',x,x,'g-.')",
"_____no_output_____"
]
],
[
[
"#### *higher order functions*",
"_____no_output_____"
]
],
[
[
"def horizontal_shift(f,W):\n return lambda x: f(x-W)\n\ng = lambda x:x**2\n\nx = np.linspace(-20,20,100)\nshifted_g = horizontal_shift(g,5)\n\nplt.plot(x,g(x),'b',x,shifted_g(x),'r')",
"_____no_output_____"
]
],
[
[
"<hr>",
"_____no_output_____"
],
[
"#### Euler's Formula",
"_____no_output_____"
]
],
[
[
"# 即'欧拉公式'\n\nrules_of_imaginary_number = '''\ni^0 = 1 i^1 = i i^2 = -1 i^3 = -i\ni^4 = 1 i^5 = i i^6 = -1 i^7 = -i '''\n\neuler_equation = '''\ne^(i*x) = cos(x) + i*sin(x) \ne^(i*pi) + 1 = 0 <= (if x=pi) '''\n\n# --- sympy ---\n\nfrom sympy import Symbol,expand,E,I\n\nz = Symbol('z',real=True)\nexpand(E**(I*z),complex=True)\n\n# --- numpy ---\n\nx = np.linspace(-np.pi,np.pi)\nlhs = np.e**(1j*x)\nrhs = np.cos(x) + 1j*np.sin(x)\n\nsum(lhs==rhs)\nlen(x)",
"_____no_output_____"
]
],
[
[
"#### Higher Derivatives",
"_____no_output_____"
]
],
[
[
"from sympy.abc import x,y\n\nf = x**4\n\nf.diff(x,2)\nf.diff(x).diff(x)",
"_____no_output_____"
]
],
[
[
"#### Ordinary Differential Equations",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sympy import *\n\n\nt = Symbol('t')\nc = Symbol('c')\ndomain = np.linspace(-3,3,100)\n\nv = t**3-3*t-6\na = v.diff()",
"_____no_output_____"
],
[
"for p in np.linspace(-2,2,20):\n slope = a.subs(t,p)\n intercept = solve(slope*p+c-v.subs(t,p),c)[0]\n lindomain = np.linspace(p-1,p+1,20)\n plt.plot(lindomain,slope*lindomain+intercept,'red',linewidth=1)\n \nplt.plot(domain,[v.subs(t,i) for i in domain],linewidth=3)",
"_____no_output_____"
]
],
[
[
"<hr>",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4aaba2a41d930b19714de901e49ba39cde295987
| 191,884 |
ipynb
|
Jupyter Notebook
|
Working Notebooks/Base_scrape_1.ipynb
|
JGarrechtMetzger/Project2
|
5c6e7f1ef432f9e90e73b902a58c32359926fa0f
|
[
"MIT"
] | null | null | null |
Working Notebooks/Base_scrape_1.ipynb
|
JGarrechtMetzger/Project2
|
5c6e7f1ef432f9e90e73b902a58c32359926fa0f
|
[
"MIT"
] | null | null | null |
Working Notebooks/Base_scrape_1.ipynb
|
JGarrechtMetzger/Project2
|
5c6e7f1ef432f9e90e73b902a58c32359926fa0f
|
[
"MIT"
] | null | null | null | 33.152039 | 251 | 0.398704 |
[
[
[
"# Imports",
"_____no_output_____"
]
],
[
[
"from bs4 import BeautifulSoup\nimport numpy as np\nimport pandas as pd\nimport requests",
"_____no_output_____"
]
],
[
[
"# Website URL list construction",
"_____no_output_____"
]
],
[
[
"## The 'target_url' is the homepage of the target website\n## The 'url_prefix' is the specific URL you use to append with the\n## for-loop below.\n\ntarget_url = 'https://sfbay.craigslist.org'\nurl_prefix = 'https://sfbay.craigslist.org/d/musical-instruments/search/msa?s='\n\npages = ['120','240','360','480','600','720','840',\n '960','1080','1200','1320','1440','1560','1680',\n '1800','1920','2040','2160','2280','2400','2520',\n '2640','2760','2880','3000']\n \n## This tests to make sure the URL list compiler is working\n## on 3 pages.\n# pages = ['120', '240', '360']\n\nurl_list = []\n\n## This loop takes the base URL and adds just the string from the\n## 'pages' object above so that each 'url' that goes into the\n## 'url_list' is in the correct step of 120 results.\n\nfor page in pages:\n url = url_prefix + page\n url_list.append(url)",
"_____no_output_____"
],
[
"## This prints the 'url_list' as a QC check.\n\nurl_list",
"_____no_output_____"
]
],
[
[
"# Scraping for-loop\n\n* This is what I'm calling a \"dynamic\" scraping function. It's dynamic in the sense that it collects and defines the html as objects in real time. \n* Another method would be what I'm calling \"static\" scraping where the output from the 'url in url_list' for-loop is put into a list outside of the function with the entirity of the url's html. The scraping then happens to a static object.\n* Choose ** **ONE** ** approach: Dynamic or Static ",
"_____no_output_____"
],
[
"## The \"dynamic\" method",
"_____no_output_____"
]
],
[
[
"''' \n ****NOTE****\nThe two empty lists 'df_list' and 'each_html_output' will\nneed to be empty. Therefore, make sure to restart the kernal before\nrunning this cell.\n\n'''\n\ndf_list = []\neach_html_output = []\n\ndef attribute_scraping(starting_url):\n \n \"\"\" \n These are the 5 attributes I am scraping from Craigslist. Any\n additional pieces of information to be made into objects will\n require \n \n * adding an empty list\n \n *an additional for-loop or if statement depending on the find \n target\n \n * adding to the dictionary at the end of the this function\n \n * adding to the print statement set at the end of this function\n \"\"\"\n \n has_pics_bool = []\n price = []\n just_titles = []\n HOOD_list = []\n just_posted_datetimes = []\n \n \"\"\"\n Parameters\n ----------\n response = requests.get(url)\n * This makes a request to the URL and returns a status code\n \n page = response.text\n * the html text (str object) from the 'get(url)'\n \n soup = BeautifulSoup(page, 'html.parser')\n * makes a BeautifulSoup object called 'page'\n * utilizes the parser designated in quotes as the second\n input of the method\n \n results = soup.find_all('li', class_='result-row')\n * returns an element ResultSet object.\n * this is the html text that was isolated from using the \n 'find()' or 'find_all()' methods.\n * 'li' is an html list tag.\n * 'class_' is the designator for a class attribute.\n - Here this corresponds with the 'result_row' class \n \n \"\"\"\n for url in url_list:\n response = requests.get(url)\n page = response.text\n soup = BeautifulSoup(page, 'html.parser')\n results = soup.find_all('li', class_='result-row')\n \n for res in results:\n \"\"\"PRICE\"\"\"\n ## Loop for finding PRICE for a single page of 120 results\n p = res.find('span', class_='result-price').text\n price.append(p)\n\n \"\"\"PICS\"\"\"\n ## Loop for finding the boolean HAS PICS of a single page of \n ## 120 results. This tests whether >=1 picture is an attribute\n ## of the post.\n if res.find('span', class_='pictag') is None:\n has_pics_bool.append(\"False\")\n else:\n has_pics_bool.append('True')\n\n\n \"\"\"NEIGHBORHOOD\"\"\"\n ## Loop for finding NEIGHBORHOOD name for a single page of 120\n ## results. This includes the drop down menu choices on\n ## Craigslist as well as the manually entered neighborhoods.\n if res.find('span', class_=\"result-hood\") is None:\n HOOD_list.append(\"NONE\")\n else: \n h = res.find('span', class_=\"result-hood\").text\n HOOD_list.append(h)\n\n \"\"\"TITLE\"\"\" \n ## Loop for finding TITLE for a single page of 120 results \n titles=soup.find_all('a', class_=\"result-title hdrlnk\")\n for title in titles:\n just_titles.append(title.text) \n\n \"\"\"DATETIME\"\"\"\n ## Loop for finding DATETIME for a single page of 120 results \n posted_datetimes=soup.find_all(class_='result-date')\n for posted_datetime in posted_datetimes:\n if posted_datetime.has_attr('datetime'):\n just_posted_datetimes.append(posted_datetime['datetime']) \n \n # Compilation dictionary of for-loop results \n comp_dict = {'price': price, \n 'pics': has_pics_bool,\n 'hood': HOOD_list,\n 'title': just_titles,\n 'datetimes': just_posted_datetimes}\n\n \n return comp_dict\n\n print(len(price))\n print(len(has_pics_bool))\n print(len(HOOD_list))\n print(len(just_titles))\n print(len(just_posted_datetimes))",
"_____no_output_____"
]
],
[
[
"Run the function and check the output dictionary.",
"_____no_output_____"
]
],
[
[
"base_dict = attribute_scraping(target_url)\nbase_dict",
"_____no_output_____"
]
],
[
[
"Construct dataframe using dictionary",
"_____no_output_____"
]
],
[
[
"df_base = pd.DataFrame(base_dict)\ndf_base",
"_____no_output_____"
]
],
[
[
"Sort the results by the 'datetime' to order them by posting time.",
"_____no_output_____"
]
],
[
[
"df_base.sort_values('datetimes')",
"_____no_output_____"
]
],
[
[
"Convert to csv for import into regression notebook",
"_____no_output_____"
]
],
[
[
"df_base.to_csv('/Users/johnmetzger/Desktop/Coding/Project2/base_scrape.csv', index = False)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aaba4744cd3f73251a80d43b5a70ea240ac47d8
| 60,847 |
ipynb
|
Jupyter Notebook
|
assignments/week02/version_score_88/C2W2_Assignment.ipynb
|
camara94/convolutional-neural-networks-tensorflow
|
7a370fc692f53a0695242d6d8d10acb572a81437
|
[
"MIT"
] | 1 |
2022-03-28T10:37:08.000Z
|
2022-03-28T10:37:08.000Z
|
assignments/week02/version_score_88/C2W2_Assignment.ipynb
|
camara94/convolutional-neural-networks-tensorflow
|
7a370fc692f53a0695242d6d8d10acb572a81437
|
[
"MIT"
] | null | null | null |
assignments/week02/version_score_88/C2W2_Assignment.ipynb
|
camara94/convolutional-neural-networks-tensorflow
|
7a370fc692f53a0695242d6d8d10acb572a81437
|
[
"MIT"
] | null | null | null | 72.264846 | 13,508 | 0.705179 |
[
[
[
"# Week 2: Tackle Overfitting with Data Augmentation\n\nWelcome to this assignment! As in the previous week, you will be using the famous `cats vs dogs` dataset to train a model that can classify images of dogs from images of cats. For this, you will create your own Convolutional Neural Network in Tensorflow and leverage Keras' image preprocessing utilities, more so this time around since Keras provides excellent support for augmenting image data.\n\nYou will also need to create the helper functions to move the images around the filesystem as you did last week, so if you need to refresh your memory with the `os` module be sure to take a look a the [docs](https://docs.python.org/3/library/os.html).\n\nLet's get started!",
"_____no_output_____"
]
],
[
[
"import warnings\nwarnings.filterwarnings('ignore')\nimport os\nimport zipfile\nimport random\nimport shutil\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom shutil import copyfile\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"Download the dataset from its original source by running the cell below. \n\nNote that the `zip` file that contains the images is unzipped under the `/tmp` directory.",
"_____no_output_____"
]
],
[
[
"# If the URL doesn't work, visit https://www.microsoft.com/en-us/download/confirmation.aspx?id=54765\n# And right click on the 'Download Manually' link to get a new URL to the dataset\n\n# Note: This is a very large dataset and will take some time to download\n\n!wget --no-check-certificate \\\n \"https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip\" \\\n -O \"/tmp/cats-and-dogs.zip\"\n\nlocal_zip = '/tmp/cats-and-dogs.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp')\nzip_ref.close()",
"--2022-03-29 20:08:53-- https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip\nResolving download.microsoft.com (download.microsoft.com)... 23.53.112.109, 2600:1407:f800:49b::e59, 2600:1407:f800:4a5::e59\nConnecting to download.microsoft.com (download.microsoft.com)|23.53.112.109|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 824894548 (787M) [application/octet-stream]\nSaving to: ‘/tmp/cats-and-dogs.zip’\n\n/tmp/cats-and-dogs. 100%[===================>] 786.68M 195MB/s in 4.1s \n\n2022-03-29 20:08:57 (191 MB/s) - ‘/tmp/cats-and-dogs.zip’ saved [824894548/824894548]\n\n"
]
],
[
[
"Now the images are stored within the `/tmp/PetImages` directory. There is a subdirectory for each class, so one for dogs and one for cats.",
"_____no_output_____"
]
],
[
[
"source_path = '/tmp/PetImages'\n\nsource_path_dogs = os.path.join(source_path, 'Dog')\nsource_path_cats = os.path.join(source_path, 'Cat')\n\n\n# os.listdir returns a list containing all files under the given path\nprint(f\"There are {len(os.listdir(source_path_dogs))} images of dogs.\")\nprint(f\"There are {len(os.listdir(source_path_cats))} images of cats.\")",
"There are 12501 images of dogs.\nThere are 12501 images of cats.\n"
]
],
[
[
"**Expected Output:**\n\n```\nThere are 12501 images of dogs.\nThere are 12501 images of cats.\n```",
"_____no_output_____"
],
[
"You will need a directory for cats-v-dogs, and subdirectories for training\nand testing. These in turn will need subdirectories for 'cats' and 'dogs'. To accomplish this, complete the `create_train_test_dirs` below:",
"_____no_output_____"
]
],
[
[
"# Define root directory\nroot_dir = '/tmp/cats-v-dogs'\n\n# Empty directory to prevent FileExistsError is the function is run several times\nif os.path.exists(root_dir):\n shutil.rmtree(root_dir)\n\n# GRADED FUNCTION: create_train_test_dirs\ndef create_train_test_dirs(root_path):\n ### START CODE HERE\n\n # HINT:\n # Use os.makedirs to create your directories with intermediate subdirectories\n # Don't hardcode the paths. Use os.path.join to append the new directories to the root_path parameter\n try:\n os.makedirs(os.path.join(root_dir))\n os.makedirs(os.path.join(root_dir, \"training\"))\n os.makedirs(os.path.join(root_dir, \"training\", \"cats\"))\n os.makedirs(os.path.join(root_dir, \"training\", \"dogs\"))\n\n os.makedirs(os.path.join(root_dir, \"testing\"))\n os.makedirs(os.path.join(root_dir, \"testing\", \"cats\"))\n os.makedirs(os.path.join(root_dir, \"testing\", \"dogs\"))\n except:\n pass\n \n ### END CODE HERE\n\n \ntry:\n create_train_test_dirs(root_path=root_dir)\nexcept FileExistsError:\n print(\"You should not be seeing this since the upper directory is removed beforehand\")",
"_____no_output_____"
],
[
"# Test your create_train_test_dirs function\n\nfor rootdir, dirs, files in os.walk(root_dir):\n for subdir in dirs:\n print(os.path.join(rootdir, subdir))",
"/tmp/cats-v-dogs/training\n/tmp/cats-v-dogs/testing\n/tmp/cats-v-dogs/training/dogs\n/tmp/cats-v-dogs/training/cats\n/tmp/cats-v-dogs/testing/dogs\n/tmp/cats-v-dogs/testing/cats\n"
]
],
[
[
"**Expected Output (directory order might vary):**\n\n``` txt\n/tmp/cats-v-dogs/training\n/tmp/cats-v-dogs/testing\n/tmp/cats-v-dogs/training/cats\n/tmp/cats-v-dogs/training/dogs\n/tmp/cats-v-dogs/testing/cats\n/tmp/cats-v-dogs/testing/dogs\n\n```",
"_____no_output_____"
],
[
"Code the `split_data` function which takes in the following arguments:\n- SOURCE: directory containing the files\n\n- TRAINING: directory that a portion of the files will be copied to (will be used for training)\n- TESTING: directory that a portion of the files will be copied to (will be used for testing)\n- SPLIT SIZE: to determine the portion\n\nThe files should be randomized, so that the training set is a random sample of the files, and the test set is made up of the remaining files.\n\nFor example, if `SOURCE` is `PetImages/Cat`, and `SPLIT` SIZE is .9 then 90% of the images in `PetImages/Cat` will be copied to the `TRAINING` dir\nand 10% of the images will be copied to the `TESTING` dir.\n\nAll images should be checked before the copy, so if they have a zero file length, they will be omitted from the copying process. If this is the case then your function should print out a message such as `\"filename is zero length, so ignoring.\"`. **You should perform this check before the split so that only non-zero images are considered when doing the actual split.**\n\n\nHints:\n\n- `os.listdir(DIRECTORY)` returns a list with the contents of that directory.\n\n- `os.path.getsize(PATH)` returns the size of the file\n\n- `copyfile(source, destination)` copies a file from source to destination\n\n- `random.sample(list, len(list))` shuffles a list",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: split_data\ndef split_data(SOURCE, TRAINING, TESTING, SPLIT_SIZE):\n\n ### START CODE HERE\n all_files = []\n \n for file_name in os.listdir(SOURCE):\n file_path = SOURCE + file_name\n\n if os.path.getsize(file_path):\n all_files.append(file_name)\n else:\n print('{} is zero length, so ignoring'.format(file_name))\n \n n_files = len(all_files)\n split_point = int(n_files * SPLIT_SIZE)\n \n shuffled = random.sample(all_files, n_files)\n \n train_set = shuffled[:split_point]\n test_set = shuffled[split_point:]\n \n for file_name in train_set:\n copyfile(SOURCE + file_name, TRAINING + file_name)\n \n for file_name in test_set:\n copyfile(SOURCE + file_name, TESTING + file_name)\n\n ### END CODE HERE\n",
"_____no_output_____"
],
[
"# Test your split_data function\n\n# Define paths\nCAT_SOURCE_DIR = \"/tmp/PetImages/Cat/\"\nDOG_SOURCE_DIR = \"/tmp/PetImages/Dog/\"\n\nTRAINING_DIR = \"/tmp/cats-v-dogs/training/\"\nTESTING_DIR = \"/tmp/cats-v-dogs/testing/\"\n\nTRAINING_CATS_DIR = os.path.join(TRAINING_DIR, \"cats/\")\nTESTING_CATS_DIR = os.path.join(TESTING_DIR, \"cats/\")\n\nTRAINING_DOGS_DIR = os.path.join(TRAINING_DIR, \"dogs/\")\nTESTING_DOGS_DIR = os.path.join(TESTING_DIR, \"dogs/\")\n\n# Empty directories in case you run this cell multiple times\nif len(os.listdir(TRAINING_CATS_DIR)) > 0:\n for file in os.scandir(TRAINING_CATS_DIR):\n os.remove(file.path)\nif len(os.listdir(TRAINING_DOGS_DIR)) > 0:\n for file in os.scandir(TRAINING_DOGS_DIR):\n os.remove(file.path)\nif len(os.listdir(TESTING_CATS_DIR)) > 0:\n for file in os.scandir(TESTING_CATS_DIR):\n os.remove(file.path)\nif len(os.listdir(TESTING_DOGS_DIR)) > 0:\n for file in os.scandir(TESTING_DOGS_DIR):\n os.remove(file.path)\n\n# Define proportion of images used for training\nsplit_size = .9\n\n# Run the function\n# NOTE: Messages about zero length images should be printed out\nsplit_data(CAT_SOURCE_DIR, TRAINING_CATS_DIR, TESTING_CATS_DIR, split_size)\nsplit_data(DOG_SOURCE_DIR, TRAINING_DOGS_DIR, TESTING_DOGS_DIR, split_size)\n\n# Check that the number of images matches the expected output\nprint(f\"\\n\\nThere are {len(os.listdir(TRAINING_CATS_DIR))} images of cats for training\")\nprint(f\"There are {len(os.listdir(TRAINING_DOGS_DIR))} images of dogs for training\")\nprint(f\"There are {len(os.listdir(TESTING_CATS_DIR))} images of cats for testing\")\nprint(f\"There are {len(os.listdir(TESTING_DOGS_DIR))} images of dogs for testing\")",
"666.jpg is zero length, so ignoring\n11702.jpg is zero length, so ignoring\n\n\nThere are 11250 images of cats for training\nThere are 11250 images of dogs for training\nThere are 1250 images of cats for testing\nThere are 1250 images of dogs for testing\n"
]
],
[
[
"**Expected Output:**\n\n```\n666.jpg is zero length, so ignoring.\n11702.jpg is zero length, so ignoring.\n```\n\n```\nThere are 11250 images of cats for training\nThere are 11250 images of dogs for training\nThere are 1250 images of cats for testing\nThere are 1250 images of dogs for testing\n```",
"_____no_output_____"
],
[
"Now that you have successfully organized the data in a way that can be easily fed to Keras' `ImageDataGenerator`, it is time for you to code the generators that will yield batches of images, both for training and validation. For this, complete the `train_val_generators` function below.\n\nSomething important to note is that the images in this dataset come in a variety of resolutions. Luckily, the `flow_from_directory` method allows you to standarize this by defining a tuple called `target_size` that will be used to convert each image to this target resolution. **For this exercise use a `target_size` of (150, 150)**.\n\n**Note:** So far, you have seen the term `testing` being used a lot for referring to a subset of images within the dataset. In this exercise, all of the `testing` data is actually being used as `validation` data. This is not very important within the context of the task at hand but it is worth mentioning to avoid confusion.",
"_____no_output_____"
]
],
[
[
"TRAINING_DIR = '/tmp/cats-v-dogs/training'\nVALIDATION_DIR = '/tmp/cats-v-dogs/testing'\n# GRADED FUNCTION: train_val_generators\ndef train_val_generators(TRAINING_DIR, VALIDATION_DIR):\n ### START CODE HERE\n # Instantiate the ImageDataGenerator class (don't forget to set the arguments to augment the images)\n train_datagen = ImageDataGenerator(rescale=1.0/255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n\n # Pass in the appropriate arguments to the flow_from_directory method\n train_generator = train_datagen.flow_from_directory(directory=TRAINING_DIR,\n batch_size=64,\n class_mode='binary',\n target_size=(150, 150))\n\n # Instantiate the ImageDataGenerator class (don't forget to set the rescale argument)\n validation_datagen = ImageDataGenerator(rescale=1.0/255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n\n # Pass in the appropriate arguments to the flow_from_directory method\n validation_generator = validation_datagen.flow_from_directory(directory=VALIDATION_DIR,\n batch_size=64,\n class_mode='binary',\n target_size=(150, 150))\n ### END CODE HERE\n return train_generator, validation_generator\n",
"_____no_output_____"
],
[
"# Test your generators\ntrain_generator, validation_generator = train_val_generators(TRAINING_DIR, TESTING_DIR)",
"Found 22498 images belonging to 2 classes.\nFound 2500 images belonging to 2 classes.\n"
]
],
[
[
"**Expected Output:**\n\n```\nFound 22498 images belonging to 2 classes.\nFound 2500 images belonging to 2 classes.\n```\n",
"_____no_output_____"
],
[
"One last step before training is to define the architecture of the model that will be trained.\n\nComplete the `create_model` function below which should return a Keras' `Sequential` model.\n\nAside from defining the architecture of the model, you should also compile it so make sure to use a `loss` function that is compatible with the `class_mode` you defined in the previous exercise, which should also be compatible with the output of your network. You can tell if they aren't compatible if you get an error during training.\n\n**Note that you should use at least 3 convolution layers to achieve the desired performance.**",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.optimizers import RMSprop\n# GRADED FUNCTION: create_model\ndef create_model():\n # DEFINE A KERAS MODEL TO CLASSIFY CATS V DOGS\n # USE AT LEAST 3 CONVOLUTION LAYERS\n\n ### START CODE HERE\n\n model = tf.keras.models.Sequential([\n tf.keras.layers.Conv2D(32, (3,3), input_shape = (150, 150, 3), activation = tf.nn.relu),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Conv2D(64, (3,3), activation = tf.nn.relu),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Conv2D(128, (3, 3), activation = tf.nn.relu),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation = tf.nn.relu),\n tf.keras.layers.Dense(128, activation = tf.nn.relu),\n tf.keras.layers.Dense(1, activation = tf.nn.sigmoid)\n])\n\n \n model.compile( optimizer = RMSprop(lr=0.001),\n loss = 'binary_crossentropy',\n metrics = ['accuracy']) \n \n ### END CODE HERE\n\n return model",
"_____no_output_____"
]
],
[
[
"Now it is time to train your model!\n\nNote: You can ignore the `UserWarning: Possibly corrupt EXIF data.` warnings.",
"_____no_output_____"
]
],
[
[
"# Get the untrained model\nmodel = create_model()\n\n# Train the model\n# Note that this may take some time.\nhistory = model.fit(train_generator,\n epochs=15,\n verbose=1,\n validation_data=validation_generator)",
"Epoch 1/15\n352/352 [==============================] - 216s 608ms/step - loss: 0.7101 - accuracy: 0.5928 - val_loss: 0.6705 - val_accuracy: 0.6028\nEpoch 2/15\n352/352 [==============================] - 210s 596ms/step - loss: 0.6143 - accuracy: 0.6694 - val_loss: 0.6798 - val_accuracy: 0.6700\nEpoch 3/15\n352/352 [==============================] - 217s 615ms/step - loss: 0.5683 - accuracy: 0.7067 - val_loss: 0.5994 - val_accuracy: 0.6540\nEpoch 4/15\n352/352 [==============================] - 209s 594ms/step - loss: 0.5445 - accuracy: 0.7293 - val_loss: 0.5018 - val_accuracy: 0.7628\nEpoch 5/15\n352/352 [==============================] - 213s 605ms/step - loss: 0.5273 - accuracy: 0.7415 - val_loss: 0.4954 - val_accuracy: 0.7584\nEpoch 6/15\n352/352 [==============================] - 214s 607ms/step - loss: 0.5100 - accuracy: 0.7512 - val_loss: 0.4545 - val_accuracy: 0.7888\nEpoch 7/15\n352/352 [==============================] - 209s 595ms/step - loss: 0.4896 - accuracy: 0.7650 - val_loss: 0.5543 - val_accuracy: 0.7200\nEpoch 8/15\n352/352 [==============================] - 211s 598ms/step - loss: 0.4804 - accuracy: 0.7746 - val_loss: 0.5324 - val_accuracy: 0.7336\nEpoch 9/15\n352/352 [==============================] - 207s 589ms/step - loss: 0.4659 - accuracy: 0.7865 - val_loss: 0.4554 - val_accuracy: 0.8044\nEpoch 10/15\n352/352 [==============================] - 207s 588ms/step - loss: 0.4595 - accuracy: 0.7865 - val_loss: 0.4014 - val_accuracy: 0.8140\nEpoch 11/15\n352/352 [==============================] - 201s 570ms/step - loss: 0.4456 - accuracy: 0.7925 - val_loss: 0.5547 - val_accuracy: 0.7196\nEpoch 12/15\n352/352 [==============================] - 199s 566ms/step - loss: 0.4395 - accuracy: 0.8014 - val_loss: 0.4468 - val_accuracy: 0.8196\nEpoch 13/15\n352/352 [==============================] - 198s 563ms/step - loss: 0.4287 - accuracy: 0.8080 - val_loss: 0.4043 - val_accuracy: 0.8280\nEpoch 14/15\n352/352 [==============================] - 197s 559ms/step - loss: 0.4185 - accuracy: 0.8116 - val_loss: 0.3652 - val_accuracy: 0.8424\nEpoch 15/15\n352/352 [==============================] - 197s 559ms/step - loss: 0.4097 - accuracy: 0.8179 - val_loss: 0.3996 - val_accuracy: 0.8076\n"
]
],
[
[
"Once training has finished, you can run the following cell to check the training and validation accuracy achieved at the end of each epoch.\n\n**To pass this assignment, your model should achieve a training and validation accuracy of at least 80% and the final testing accuracy should be either higher than the training one or have a 5% difference at maximum**. If your model didn't achieve these thresholds, try training again with a different model architecture, remember to use at least 3 convolutional layers or try tweaking the image augmentation process.\n\nYou might wonder why the training threshold to pass this assignment is significantly lower compared to last week's assignment. Image augmentation does help with overfitting but usually this comes at the expense of requiring more training time. To keep the training time reasonable, the same number of epochs as in the previous assignment are kept. \n\nHowever, as an optional exercise you are encouraged to try training for more epochs and to achieve really good training and validation accuracies.",
"_____no_output_____"
]
],
[
[
"#-----------------------------------------------------------\n# Retrieve a list of list results on training and test data\n# sets for each training epoch\n#-----------------------------------------------------------\nacc=history.history['accuracy']\nval_acc=history.history['val_accuracy']\nloss=history.history['loss']\nval_loss=history.history['val_loss']\n\nepochs=range(len(acc)) # Get number of epochs\n\n#------------------------------------------------\n# Plot training and validation accuracy per epoch\n#------------------------------------------------\nplt.plot(epochs, acc, 'r', \"Training Accuracy\")\nplt.plot(epochs, val_acc, 'b', \"Validation Accuracy\")\nplt.title('Training and validation accuracy')\nplt.show()\nprint(\"\")\n\n#------------------------------------------------\n# Plot training and validation loss per epoch\n#------------------------------------------------\nplt.plot(epochs, loss, 'r', \"Training Loss\")\nplt.plot(epochs, val_loss, 'b', \"Validation Loss\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"You will probably encounter that the model is overfitting, which means that it is doing a great job at classifying the images in the training set but struggles with new data. This is perfectly fine and you will learn how to mitigate this issue in the upcomming week.\n\nBefore closing the assignment, be sure to also download the `history.pkl` file which contains the information of the training history of your model. You can download this file by running the cell below:",
"_____no_output_____"
]
],
[
[
"def download_history():\n import pickle\n from google.colab import files\n\n with open('history_augmented.pkl', 'wb') as f:\n pickle.dump(history.history, f)\n\n files.download('history_augmented.pkl')\n\ndownload_history()",
"_____no_output_____"
]
],
[
[
"You will also need to submit this notebook for grading. To download it, click on the `File` tab in the upper left corner of the screen then click on `Download` -> `Download .ipynb`. You can name it anything you want as long as it is a valid `.ipynb` (jupyter notebook) file.",
"_____no_output_____"
],
[
"**Congratulations on finishing this week's assignment!**\n\nYou have successfully implemented a convolutional neural network that classifies images of cats and dogs, along with the helper functions needed to pre-process the images!\n\n**Keep it up!**",
"_____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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4aabb7de6488ac17c909a4f6733564a32ce7b48e
| 7,411 |
ipynb
|
Jupyter Notebook
|
tutorial/westeros/westeros_flexible_generation.ipynb
|
amastrucci/message_ix
|
154c58150755f1445ed48de028656daefccde995
|
[
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null |
tutorial/westeros/westeros_flexible_generation.ipynb
|
amastrucci/message_ix
|
154c58150755f1445ed48de028656daefccde995
|
[
"Apache-2.0",
"CC-BY-4.0"
] | 1 |
2019-06-13T20:51:20.000Z
|
2019-06-13T20:51:20.000Z
|
tutorial/westeros/westeros_flexible_generation.ipynb
|
amastrucci/message_ix
|
154c58150755f1445ed48de028656daefccde995
|
[
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | 25.467354 | 138 | 0.545945 |
[
[
[
"import pandas as pd\nimport ixmp as ix\nimport message_ix\n\nfrom message_ix.utils import make_df\n\n%matplotlib inline",
"_____no_output_____"
],
[
"mp = ix.Platform(dbtype='HSQLDB')",
"_____no_output_____"
],
[
"base = message_ix.Scenario(mp, model='Westeros Electrified', scenario='baseline')",
"_____no_output_____"
],
[
"model = 'Westeros Electrified'\nscen = base.clone(model, 'flexibile_generation',\n 'illustration of flexible-generation formulation', keep_sol=False)\nscen.check_out()\n\nyear_df = scen.vintage_and_active_years()\nvintage_years, act_years = year_df['year_vtg'], year_df['year_act']\nmodel_horizon = scen.set('year')\ncountry = 'Westeros'",
"_____no_output_____"
]
],
[
[
"# Add a carbon tax\n\nNote that the example below is not feasible with a strict bound on emissions, hence this tutorial uses a tax.\n\nBelow, we repeat the set-up of the emissions formulation from the \"emissions bounds\" tutorial.",
"_____no_output_____"
]
],
[
[
"# first we introduce the emission specis CO2 and the emission category GHG\nscen.add_set('emission', 'CO2')\nscen.add_cat('emission', 'GHG', 'CO2')\n\n# we now add CO2 emissions to the coal powerplant\nbase_emission_factor = {\n 'node_loc': country,\n 'year_vtg': vintage_years,\n 'year_act': act_years,\n 'mode': 'standard',\n 'unit': 'USD/GWa',\n}\n\nemission_factor = make_df(base_emission_factor, technology= 'coal_ppl', emission= 'CO2', value = 100)\nscen.add_par('emission_factor', emission_factor)",
"_____no_output_____"
],
[
"base_tax_emission = {\n 'node': country,\n 'type_year': [700,710,720],\n 'type_tec': 'all',\n 'unit': 'tCO2',\n 'type_emission': 'GHG',\n 'value': [1., 2., 3.]\n}\n\ntax_emission = make_df(base_tax_emission)\nscen.add_par('tax_emission', tax_emission)",
"_____no_output_____"
]
],
[
[
"## Add Renewable Formulation",
"_____no_output_____"
],
[
"## Describing the Renewable Technologies Flexibility \n### flexibility of demand and supply --> ensuring the activity flexibility reserve \n\nThe wind power plant has a flexibility demand of 5% of its ACT. The coal powerplant can provide 20% of it's activity as flexibility.",
"_____no_output_____"
]
],
[
[
"base_flexibility_factor = pd.DataFrame({\n 'node_loc': country,\n 'commodity': 'electricity',\n 'level' : 'secondary',\n 'mode': 'standard',\n 'unit': '???',\n 'time': 'year',\n 'year_vtg': vintage_years,\n 'year_act': act_years,\n})\n\nbase_rating = pd.DataFrame({\n 'node': country,\n 'commodity': 'electricity',\n 'level' : 'secondary', \n 'unit': '???',\n 'time': 'year',\n 'year_act': model_horizon})",
"_____no_output_____"
],
[
"# add the ratings as a set \nscen.add_set('rating', ['r1', 'r2'])\n\n# For the Load \nflexibility_factor = make_df(base_flexibility_factor, technology= 'grid', rating= 'unrated', value = -0.1)\nscen.add_par('flexibility_factor',flexibility_factor)\n\n# For the Wind PPL\nrating_bin = make_df(base_rating, technology= 'wind_ppl', value = 0.2, rating= 'r1')\nscen.add_par('rating_bin', rating_bin)\n\nflexibility_factor = make_df(base_flexibility_factor, technology= 'wind_ppl', rating= 'r1', value = -0.2)\nscen.add_par('flexibility_factor',flexibility_factor)\n\nrating_bin = make_df(base_rating, technology= 'wind_ppl', value = 0.8, rating= 'r2')\nscen.add_par('rating_bin', rating_bin)\n\nflexibility_factor = make_df(base_flexibility_factor, technology= 'wind_ppl', rating= 'r2', value = -0.7)\nscen.add_par('flexibility_factor',flexibility_factor)\n\n# For the Coal PPL\nflexibility_factor = make_df(base_flexibility_factor, technology= 'coal_ppl', rating= 'unrated', value = 1)\nscen.add_par('flexibility_factor',flexibility_factor)",
"_____no_output_____"
]
],
[
[
"### commit and solve",
"_____no_output_____"
]
],
[
[
"scen.commit(comment='define parameters for flexibile-generation implementation')\nscen.set_as_default()",
"_____no_output_____"
],
[
"scen.solve()",
"_____no_output_____"
],
[
"scen.var('OBJ')['lvl']",
"_____no_output_____"
]
],
[
[
"### plotting",
"_____no_output_____"
]
],
[
[
"from tools import Plots\np = Plots(scen, country, firstyear=700)",
"_____no_output_____"
],
[
"p.plot_activity(baseyear=True, subset=['coal_ppl', 'wind_ppl'])",
"_____no_output_____"
],
[
"p.plot_capacity(baseyear=True, subset=['coal_ppl', 'wind_ppl'])",
"_____no_output_____"
],
[
"p.plot_prices(subset=['light'], baseyear=True)",
"_____no_output_____"
],
[
"mp.close_db()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4aabbd331b0833653ef237199396b44c21b8524b
| 177,388 |
ipynb
|
Jupyter Notebook
|
Ugam_Sentiment_Analysis_MachineHack/Ugam_Sentiment_Analysis_Per-Label-Model-Fine-Tuning-Approach.ipynb
|
PradipKumarDas/Competitions
|
df9487bbf0e489b3bcbe5239b43d74f410459ae8
|
[
"MIT"
] | 1 |
2022-01-16T16:06:59.000Z
|
2022-01-16T16:06:59.000Z
|
Ugam_Sentiment_Analysis_MachineHack/Ugam_Sentiment_Analysis_Per-Label-Model-Fine-Tuning-Approach.ipynb
|
PradipKumarDas/Competitions
|
df9487bbf0e489b3bcbe5239b43d74f410459ae8
|
[
"MIT"
] | null | null | null |
Ugam_Sentiment_Analysis_MachineHack/Ugam_Sentiment_Analysis_Per-Label-Model-Fine-Tuning-Approach.ipynb
|
PradipKumarDas/Competitions
|
df9487bbf0e489b3bcbe5239b43d74f410459ae8
|
[
"MIT"
] | 1 |
2022-01-16T16:07:16.000Z
|
2022-01-16T16:07:16.000Z
| 49.233417 | 48,296 | 0.620792 |
[
[
[
"**Author**: _Pradip Kumar Das_\n\n**License:** https://github.com/PradipKumarDas/Competitions/blob/main/LICENSE\n\n**Profile & Contact:** [LinkedIn](https://www.linkedin.com/in/daspradipkumar/) | [GitHub](https://github.com/PradipKumarDas) | [Kaggle](https://www.kaggle.com/pradipkumardas) | [email protected] (Email)",
"_____no_output_____"
],
[
"# Ugam Sentiment Analysis | MachineHack\n\n**Dec. 22, 2021 - Jan. 10, 2022**\n\nhttps://machinehack.com/hackathon/uhack_sentiments_20_decode_code_words/overview\n\n**Sections:**\n- Dependencies\n- Exploratory Data Analysis (EDA) & Preprocessing\n- Modeling & Evaluation\n- Submission\n\nNOTE: Running this notebook over CPU will be intractable as it uses Transformers, and hence it is recommended to use GPU.",
"_____no_output_____"
],
[
"# Dependencies",
"_____no_output_____"
]
],
[
[
"# The following packages may need to be first installed on cloud hosted Data Science platforms such as Google Colab.\n\n!pip install transformers",
"Collecting transformers\n Downloading transformers-4.15.0-py3-none-any.whl (3.4 MB)\n\u001b[K |████████████████████████████████| 3.4 MB 5.6 MB/s \n\u001b[?25hCollecting pyyaml>=5.1\n Downloading PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (596 kB)\n\u001b[K |████████████████████████████████| 596 kB 27.2 MB/s \n\u001b[?25hRequirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from transformers) (21.3)\nCollecting tokenizers<0.11,>=0.10.1\n Downloading tokenizers-0.10.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (3.3 MB)\n\u001b[K |████████████████████████████████| 3.3 MB 36.2 MB/s \n\u001b[?25hRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from transformers) (4.8.2)\nRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from transformers) (1.19.5)\nCollecting sacremoses\n Downloading sacremoses-0.0.46-py3-none-any.whl (895 kB)\n\u001b[K |████████████████████████████████| 895 kB 45.1 MB/s \n\u001b[?25hRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from transformers) (4.62.3)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from transformers) (2.23.0)\nRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers) (2019.12.20)\nCollecting huggingface-hub<1.0,>=0.1.0\n Downloading huggingface_hub-0.2.1-py3-none-any.whl (61 kB)\n\u001b[K |████████████████████████████████| 61 kB 442 kB/s \n\u001b[?25hRequirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers) (3.4.0)\nRequirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.7/dist-packages (from huggingface-hub<1.0,>=0.1.0->transformers) (3.10.0.2)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging>=20.0->transformers) (3.0.6)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->transformers) (3.6.0)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (2021.10.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->transformers) (1.24.3)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (2.10)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (3.0.4)\nRequirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (1.1.0)\nRequirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (7.1.2)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (1.15.0)\nInstalling collected packages: pyyaml, tokenizers, sacremoses, huggingface-hub, transformers\n Attempting uninstall: pyyaml\n Found existing installation: PyYAML 3.13\n Uninstalling PyYAML-3.13:\n Successfully uninstalled PyYAML-3.13\nSuccessfully installed huggingface-hub-0.2.1 pyyaml-6.0 sacremoses-0.0.46 tokenizers-0.10.3 transformers-4.15.0\n"
],
[
"# Imports required packages\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.model_selection import StratifiedKFold\n\nimport tensorflow as tf\n# from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\n\nimport transformers\nfrom transformers import TFAutoModelForSequenceClassification, AutoTokenizer\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport datetime, gc",
"_____no_output_____"
]
],
[
[
"# Initialization",
"_____no_output_____"
]
],
[
[
"# Connects drive in Google Colab\nfrom google.colab import drive\ndrive.mount('/content/drive/')",
"Mounted at /content/drive/\n"
],
[
" # Changes working directory to the project directory\n cd \"/content/drive/MyDrive/Colab/Ugam_Sentiment_Analysis/\"",
"/content/drive/MyDrive/Colab/Ugam_Sentiment_Analysis\n"
],
[
"# Configures styles for plotting runtime\n\nplt.style.use(\"seaborn-whitegrid\")\nplt.rc(\n \"figure\",\n autolayout=True,\n figsize=(11, 4),\n titlesize=18,\n titleweight='bold',\n)\nplt.rc(\n \"axes\",\n labelweight=\"bold\",\n labelsize=\"large\",\n titleweight=\"bold\",\n titlesize=16,\n titlepad=10,\n)\n%config InlineBackend.figure_format = 'retina'\n\n# Sets Tranformer's level of verbosity to INFO level\ntransformers.logging.set_verbosity_error()",
"_____no_output_____"
]
],
[
[
"# Exploratory Data Analysis (EDA) & Preprocessing",
"_____no_output_____"
]
],
[
[
"# Loads train data set\ntrain = pd.read_csv(\"./data/train.csv\")\n\n# Checks few rows from train data set\ndisplay(train)",
"_____no_output_____"
],
[
"# Sets dataframe's `Id` columns as its index\ntrain.set_index(\"Id\", drop=True, append=False, inplace=True)",
"_____no_output_____"
],
[
"# Loads test data set\ntest = pd.read_csv(\"./data/test.csv\")\n\n# Checks top few rows from test data set\ndisplay(test.head(5))",
"_____no_output_____"
],
[
"# Sets dataframe's `Id` columns as its index\ntest.set_index(\"Id\", drop=True, append=False, inplace=True)",
"_____no_output_____"
],
[
"# Checks the distribution of review length (number of characters in review)\n\nfig, ax = plt.subplots(1, 2, sharey=True)\nfig.suptitle(\"Review Length\")\ntrain.Review.str.len().plot(kind='hist', bins=50, ax=ax[0])\nax[0].set_xlabel(\"Train Data\")\nax[0].set_ylabel(\"No. of Reviews\")\ntest.Review.str.len().plot(kind='hist', bins=50, ax=ax[1])\nax[1].set_xlabel(\"Test Data\")",
"_____no_output_____"
]
],
[
[
"The above plot shows that lengthy reviews containing 1000+ characters are less compares to that of reviews having less than 1000 characters. Hence, first 512 characters from the reviews will be considered for analysis.",
"_____no_output_____"
]
],
[
[
"# Finds the distribution of each label\ndisplay(train.select_dtypes([\"int\"]).apply(pd.Series.value_counts))",
"_____no_output_____"
],
[
"# Let's find stratified cross validation on 'Polarity' label will have same distribution \n\nsk_fold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n\ncv_generator = sk_fold.split(train, train.Polarity)\nfor fold, (idx_train, idx_val) in enumerate(cv_generator):\n display(train.iloc[idx_train].select_dtypes([\"int\"]).apply(pd.Series.value_counts))",
"_____no_output_____"
]
],
[
[
"It shows the same distribution is available in cross validation.",
"_____no_output_____"
],
[
"# Modeling & Evaluation",
"_____no_output_____"
],
[
"The approach is to use pretrained **Transfomer** model and to fine-tune, if required. As fine-tuning over cross-validation is time consuming even on GPUs, let's avoid it, and hence prepare one stratified validation set first to check pretrained model's or fine-tuned model's performance.",
"_____no_output_____"
]
],
[
[
"# Creates data set splitter and gets indexes for train and validation rows\ncv_generator = sk_fold.split(train, train.Polarity)\nidx_train, idx_val = next(cv_generator)",
"_____no_output_____"
],
[
"# Sets parameters for Transformer model fine-tuning\nmodel_config = {\n \"model_name\": \"distilbert-base-uncased-finetuned-sst-2-english\", # selected pretrained model\n \"max_length\": 512, # maximum number of review characters allowed to input to model\n}",
"_____no_output_____"
],
[
"# Creates tokenizer from pre-trained transformer model\ntokenizer = AutoTokenizer.from_pretrained(model_config[\"model_name\"])",
"_____no_output_____"
],
[
"# Tokenize reviews for train, validation and test data set\n\ntrain_encodings = tokenizer(\n train.iloc[idx_train].Review.to_list(),\n max_length=model_config[\"max_length\"],\n truncation=True,\n padding=True,\n return_tensors=\"tf\"\n)\n\nval_encodings = tokenizer(\n train.iloc[idx_val].Review.to_list(),\n max_length=model_config[\"max_length\"],\n truncation=True,\n padding=True,\n return_tensors=\"tf\"\n)\n\ntest_encodings = tokenizer(\n test.Review.to_list(),\n max_length=model_config[\"max_length\"],\n truncation=True,\n padding=True,\n return_tensors=\"tf\"\n)",
"_____no_output_____"
],
[
"# Performs target specific model fine-tuning \n\n\"\"\"\nNOTE:\n\n1) It was observed that increasing number of epochs more than one during model fine-tuning\ndoes not improve model performance, and hence epochs is set to 1.\n\n2) As pretrained model being used is already used for predicting sentiment polarity, that model\nwill not be fine-tuned any further, and will be used directly to predict sentimen polarity\nagainst the test data. Fine-tuning was already experimented and found to be not useful as it \ndecreases performance with higher log loss and lower accuracy on validation data.\n\n\"\"\"\n\ncolumns = train.select_dtypes([\"int\"]).columns.tolist()\ncolumns.remove(\"Polarity\")\n\n# Fine-tunes models except that of Polarity\n\nfor column in columns:\n print(f\"Fine tuning model for {column.upper()}...\")\n print(\"======================================================\\n\")\n \n model = TFAutoModelForSequenceClassification.from_pretrained(model_config[\"model_name\"])\n \n # Prepares tensorflow dataset for both train, validation and test data\n train_encodings_dataset = tf.data.Dataset.from_tensor_slices((\n {\"input_ids\": train_encodings[\"input_ids\"], \"attention_mask\": train_encodings[\"attention_mask\"]},\n train.iloc[idx_train][[column]]\n )).batch(16).prefetch(tf.data.AUTOTUNE)\n\n val_encodings_dataset = tf.data.Dataset.from_tensor_slices((\n {\"input_ids\": val_encodings[\"input_ids\"], \"attention_mask\": val_encodings[\"attention_mask\"]},\n train.iloc[idx_val][[column]]\n )).batch(16).prefetch(tf.data.AUTOTUNE)\n\n test_encodings_dataset = tf.data.Dataset.from_tensor_slices(\n {\"input_ids\": test_encodings[\"input_ids\"], \"attention_mask\": test_encodings[\"attention_mask\"]}\n ).batch(16).prefetch(tf.data.AUTOTUNE)\n \n predictions = tf.nn.softmax(model.predict(val_encodings_dataset).logits)\n print(\"Pretrained model's perfomance on validation data before fine-tuning:\",\n tf.keras.metrics.binary_crossentropy(train.iloc[idx_val][column], predictions[:,1], from_logits=False).numpy(), \"(log loss)\",\n tf.keras.metrics.binary_accuracy(train.iloc[idx_val][column], predictions[:,1]).numpy(), \"(accuracy)\\n\"\n )\n del predictions\n \n print(\"Starting fine tuning...\")\n\n # Freezes model configuration before starting fine-tuning\n model.compile(\n optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5),\n loss=tf.keras.losses.binary_crossentropy,\n metrics=[tf.keras.metrics.binary_crossentropy, tf.keras.metrics.binary_accuracy]\n )\n \n # Sets model file name to organize storing logs and fine-tuned models against\n # model_filename = f\"{column}\" + \"_\" + datetime.datetime.now().strftime(\"%Y.%m.%d-%H:%M:%S\")\n \n # Fine tunes model\n model.fit(\n x=train_encodings_dataset,\n validation_data=val_encodings_dataset, \n batch_size=16, \n epochs=1, \n # callbacks=[\n # EarlyStopping(monitor=\"val_loss\", mode=\"min\", patience=2, restore_best_weights=True, verbose=1),\n # ModelCheckpoint(filepath=f\"./models/{model_filename}\", monitor=\"val_loss\", mode=\"min\", save_best_only=True, save_weights_only=True),\n # TensorBoard(log_dir=f\"./logs/{model_filename}\", histogram_freq=1, update_freq='epoch')\n # ], \n use_multiprocessing=True)\n \n print(\"\\nFine tuning was completed.\\n\")\n \n del train_encodings_dataset, val_encodings_dataset\n \n print(\"Performing prediction on test data...\", end=\"\")\n \n # Performs predictions on test data\n predictions = tf.nn.softmax(model.predict(test_encodings_dataset).logits)\n test[column] = predictions[:, 1]\n del test_encodings_dataset\n print(\"done\\n\")\n \n del predictions, model\n\nprint(\"Skipping fine-tuning model for POLARITY (as it uses pretrained model) and continuing direct prediction on test data...\")\nprint(\"======================================================================================================================\\n\")\n\nprint(\"Performing prediction on test data...\", end=\"\")\n\nmodel = TFAutoModelForSequenceClassification.from_pretrained(model_config[\"model_name\"])\n\n# Prepares tensorflow dataset for test data\ntest_encodings_dataset = tf.data.Dataset.from_tensor_slices(\n {\"input_ids\": test_encodings[\"input_ids\"], \"attention_mask\": test_encodings[\"attention_mask\"]}\n).batch(16).prefetch(tf.data.AUTOTUNE)\n\n# Performs predictions on test data\npredictions = tf.nn.softmax(model.predict(test_encodings_dataset).logits)\ntest[\"Polarity\"] = predictions[:, 1]\ndel test_encodings_dataset\n\ndel predictions, model\n\nprint(\"done\\n\")\nprint(\"Fine-tuning and test predictions were completed.\")\n",
"Fine tuning model for COMPONENTS...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 4.743803 (log loss) 0.30374593 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 498s 2s/step - loss: 1.2578 - binary_crossentropy: 1.2578 - binary_accuracy: 0.9130 - val_loss: 0.5904 - val_binary_crossentropy: 0.5904 - val_binary_accuracy: 0.9617\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for DELIVERY AND CUSTOMER SUPPORT...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 4.680458 (log loss) 0.31514657 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 498s 2s/step - loss: 0.8953 - binary_crossentropy: 0.8953 - binary_accuracy: 0.9365 - val_loss: 0.4648 - val_binary_crossentropy: 0.4648 - val_binary_accuracy: 0.9699\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for DESIGN AND AESTHETICS...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 4.351811 (log loss) 0.35016286 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 499s 2s/step - loss: 2.6059 - binary_crossentropy: 2.6059 - binary_accuracy: 0.8183 - val_loss: 1.5426 - val_binary_crossentropy: 1.5426 - val_binary_accuracy: 0.8986\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for DIMENSIONS...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 4.373391 (log loss) 0.35179153 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 500s 2s/step - loss: 2.4400 - binary_crossentropy: 2.4400 - binary_accuracy: 0.8103 - val_loss: 0.9741 - val_binary_crossentropy: 0.9741 - val_binary_accuracy: 0.9039\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for FEATURES...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 4.5807853 (log loss) 0.3281759 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 499s 2s/step - loss: 1.4978 - binary_crossentropy: 1.4978 - binary_accuracy: 0.8977 - val_loss: 0.7160 - val_binary_crossentropy: 0.7160 - val_binary_accuracy: 0.9536\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for FUNCTIONALITY...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 3.4565454 (log loss) 0.47394136 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 497s 2s/step - loss: 7.6470 - binary_crossentropy: 7.6470 - binary_accuracy: 0.4997 - val_loss: 7.6565 - val_binary_crossentropy: 7.6565 - val_binary_accuracy: 0.5000\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for INSTALLATION...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 4.232262 (log loss) 0.36970684 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 498s 2s/step - loss: 2.8794 - binary_crossentropy: 2.8794 - binary_accuracy: 0.8067 - val_loss: 2.1104 - val_binary_crossentropy: 2.1104 - val_binary_accuracy: 0.8632\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for MATERIAL...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 4.672621 (log loss) 0.31351793 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 498s 2s/step - loss: 1.1027 - binary_crossentropy: 1.1027 - binary_accuracy: 0.9242 - val_loss: 0.4648 - val_binary_crossentropy: 0.4648 - val_binary_accuracy: 0.9699\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for PRICE...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 4.12672 (log loss) 0.3916938 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 499s 2s/step - loss: 2.3488 - binary_crossentropy: 2.3488 - binary_accuracy: 0.8131 - val_loss: 2.1731 - val_binary_crossentropy: 2.1731 - val_binary_accuracy: 0.8591\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for QUALITY...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 3.7491693 (log loss) 0.42996743 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 498s 2s/step - loss: 7.6351 - binary_crossentropy: 7.6351 - binary_accuracy: 0.5007 - val_loss: 7.6185 - val_binary_crossentropy: 7.6185 - val_binary_accuracy: 0.5012\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nFine tuning model for USABILITY...\n======================================================\n\nPretrained model's perfomance on validation data before fine-tuning: 3.821944 (log loss) 0.4267101 (accuracy)\n\nStarting fine tuning...\n307/307 [==============================] - 498s 2s/step - loss: 5.3542 - binary_crossentropy: 5.3542 - binary_accuracy: 0.6452 - val_loss: 3.0649 - val_binary_crossentropy: 3.0649 - val_binary_accuracy: 0.8013\n\nFine tuning was completed.\n\nPerforming prediction on test data...done\n\nSkipping fine-tuning model for POLARITY (as it uses pretrained model) and continuing direct prediction on test data...\n======================================================================================================================\n\nPerforming prediction on test data...done\n\nFine-tuning and test predictions were completed.\n"
]
],
[
[
"# Submission",
"_____no_output_____"
]
],
[
[
"# Saves test predictions\ntest.select_dtypes([\"float\"]).to_csv(\"./submission.csv\", index=False)",
"_____no_output_____"
]
],
[
[
"***Leaderboard score for this submission was 8.8942 as against highest of that was 2.74 on Jan 06, 2022 at 11:50 PM.***",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aabc09ebd367f28196b8f7244b4551be842618b
| 5,089 |
ipynb
|
Jupyter Notebook
|
notebooks/03_categorical_pipeline_ex_02.ipynb
|
flkt-crnpio/scikit-learn-mooc
|
5f40c764e0d9eb60323af7aa2cae9ebda687b425
|
[
"CC-BY-4.0"
] | null | null | null |
notebooks/03_categorical_pipeline_ex_02.ipynb
|
flkt-crnpio/scikit-learn-mooc
|
5f40c764e0d9eb60323af7aa2cae9ebda687b425
|
[
"CC-BY-4.0"
] | null | null | null |
notebooks/03_categorical_pipeline_ex_02.ipynb
|
flkt-crnpio/scikit-learn-mooc
|
5f40c764e0d9eb60323af7aa2cae9ebda687b425
|
[
"CC-BY-4.0"
] | null | null | null | 30.112426 | 88 | 0.61407 |
[
[
[
"# 📝 Exercise M1.05\n\nThe goal of this exercise is to evaluate the impact of feature preprocessing\non a pipeline that uses a decision-tree-based classifier instead of a logistic\nregression.\n\n- The first question is to empirically evaluate whether scaling numerical\n features is helpful or not;\n- The second question is to evaluate whether it is empirically better (both\n from a computational and a statistical perspective) to use integer coded or\n one-hot encoded categories.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\nadult_census = pd.read_csv(\"../datasets/adult-census.csv\")",
"_____no_output_____"
],
[
"target_name = \"class\"\ntarget = adult_census[target_name]\ndata = adult_census.drop(columns=[target_name, \"education-num\"])",
"_____no_output_____"
]
],
[
[
"As in the previous notebooks, we use the utility `make_column_selector`\nto select only columns with a specific data type. Besides, we list in\nadvance all categories for the categorical columns.",
"_____no_output_____"
]
],
[
[
"from sklearn.compose import make_column_selector as selector\n\nnumerical_columns_selector = selector(dtype_exclude=object)\ncategorical_columns_selector = selector(dtype_include=object)\nnumerical_columns = numerical_columns_selector(data)\ncategorical_columns = categorical_columns_selector(data)",
"_____no_output_____"
]
],
[
[
"## Reference pipeline (no numerical scaling and integer-coded categories)\n\nFirst let's time the pipeline we used in the main notebook to serve as a\nreference:",
"_____no_output_____"
]
],
[
[
"import time\n\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import HistGradientBoostingClassifier\n\ncategorical_preprocessor = OrdinalEncoder(handle_unknown=\"use_encoded_value\",\n unknown_value=-1)\npreprocessor = ColumnTransformer([\n ('categorical', categorical_preprocessor, categorical_columns)],\n remainder=\"passthrough\")\n\nmodel = make_pipeline(preprocessor, HistGradientBoostingClassifier())\n\nstart = time.time()\ncv_results = cross_validate(model, data, target)\nelapsed_time = time.time() - start\n\nscores = cv_results[\"test_score\"]\n\nprint(\"The mean cross-validation accuracy is: \"\n f\"{scores.mean():.3f} +/- {scores.std():.3f} \"\n f\"with a fitting time of {elapsed_time:.3f}\")",
"_____no_output_____"
]
],
[
[
"## Scaling numerical features\n\nLet's write a similar pipeline that also scales the numerical features using\n`StandardScaler` (or similar):",
"_____no_output_____"
]
],
[
[
"# Write your code here.",
"_____no_output_____"
]
],
[
[
"## One-hot encoding of categorical variables\n\nWe observed that integer coding of categorical variables can be very\ndetrimental for linear models. However, it does not seem to be the case for\n`HistGradientBoostingClassifier` models, as the cross-validation score\nof the reference pipeline with `OrdinalEncoder` is reasonably good.\n\nLet's see if we can get an even better accuracy with `OneHotEncoder`.\n\nHint: `HistGradientBoostingClassifier` does not yet support sparse input\ndata. You might want to use\n`OneHotEncoder(handle_unknown=\"ignore\", sparse=False)` to force the use of a\ndense representation as a workaround.",
"_____no_output_____"
]
],
[
[
"# Write your code here.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aabd8e5b8a23e87957e2c3710ffdbfcaee7cf1e
| 42,623 |
ipynb
|
Jupyter Notebook
|
mices_2021_workshop_final.ipynb
|
jacopotagliabue/retail-personalization-workshop
|
fc3fbc11fae4191ddb16f7a7a3863cfe55979aaa
|
[
"MIT"
] | 14 |
2021-04-20T17:05:23.000Z
|
2022-03-01T18:58:51.000Z
|
mices_2021_workshop_final.ipynb
|
jacopotagliabue/retail-personalization-workshop
|
fc3fbc11fae4191ddb16f7a7a3863cfe55979aaa
|
[
"MIT"
] | 3 |
2021-11-28T17:57:02.000Z
|
2021-12-01T13:45:23.000Z
|
mices_2021_workshop_final.ipynb
|
jacopotagliabue/retail-personalization-workshop
|
fc3fbc11fae4191ddb16f7a7a3863cfe55979aaa
|
[
"MIT"
] | 3 |
2021-07-01T17:04:58.000Z
|
2021-07-18T20:33:16.000Z
| 36.213254 | 309 | 0.561223 |
[
[
[
"# SESSIONS ARE ALL YOU NEED\n### Workshop on e-commerce personalization\n\nThis notebook showcases with working code the main ideas of our ML-in-retail workshop from June lst, 2021 at MICES (https://mices.co/). Please refer to the README in the repo for a bit of context!\n\nWhile the code below is (well, should be!) fully functioning, please note we aim for functions which are pedagogically useful, more than terse code per se: it should be fairly easy to take these ideas and refactor the code to achieve more speed, better re-usability etc.",
"_____no_output_____"
],
[
"_If you want to use Google Colab, you can uncomment this cell:_",
"_____no_output_____"
]
],
[
[
"# if you need requirements....\n# !pip install -r requirements.txt\n\n# #from google.colab import drive\n#drive.mount('/content/drive',force_remount=True)\n#%cd drive/MyDrive/path_to_directory_containing_train_folder\n#LOCAL_FOLDER = 'train'",
"_____no_output_____"
]
],
[
[
"## Basic import and some global vars to know where data is!\n\nHere we import the libraries we need and set the working folders - make sure your current python interpreter has all the dependencies installed. If you want to use the same real-world data as I'm using, please download the open dataset you find at: https://github.com/coveooss/SIGIR-ecom-data-challenge.",
"_____no_output_____"
]
],
[
[
"import os\nfrom random import choice\nimport time\nimport ast\nimport json\nimport numpy as np\nimport csv\nfrom collections import Counter,defaultdict\n# viz stuff\nfrom sklearn.manifold import TSNE\nfrom matplotlib import pyplot as plt\nfrom IPython.display import Image \n# gensim stuff for prod2vec\nimport gensim # gensim > 4\nfrom gensim.similarities.annoy import AnnoyIndexer\n# keras stuff for auto-encoder\nfrom keras.layers.core import Dropout\nfrom keras.layers.core import Dense\nfrom keras.layers import Concatenate\nfrom keras.models import Sequential\nfrom keras.layers import Input\nfrom keras.optimizers import SGD, Adam\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping\nfrom keras.utils import plot_model\nfrom sklearn.model_selection import train_test_split\nfrom keras import utils\nimport hashlib\nfrom copy import deepcopy",
"_____no_output_____"
],
[
"%matplotlib inline",
"_____no_output_____"
],
[
"LOCAL_FOLDER = '/Users/jacopotagliabue/Documents/data_dump/train' # where is the dataset stored?\nN_ROWS = 5000000 # how many rows we want to take (to avoid waiting too much for tutorial purposes)?",
"_____no_output_____"
]
],
[
[
"## Step 1: build a prod2vec space\n\nFor more information on prod2vec and its use, you can also check our blog post: https://blog.coveo.com/clothes-in-space-real-time-personalization-in-less-than-100-lines-of-code/ or latest NLP paper: https://arxiv.org/abs/2104.02061",
"_____no_output_____"
]
],
[
[
"def read_sessions_from_training_file(training_file: str, K: int = None):\n \"\"\"\n Read the training file containing product interactions, up to K rows.\n \n :return: a list of lists, each list being a session (sequence of product IDs)\n \"\"\"\n user_sessions = []\n current_session_id = None\n current_session = []\n with open(training_file) as csvfile:\n reader = csv.DictReader(csvfile)\n for idx, row in enumerate(reader):\n # if a max number of items is specified, just return at the K with what you have\n if K and idx >= K:\n break\n # just append \"detail\" events in the order we see them\n # row will contain: session_id_hash, product_action, product_sku_hash\n _session_id_hash = row['session_id_hash']\n # when a new session begins, store the old one and start again\n if current_session_id and current_session and _session_id_hash != current_session_id:\n user_sessions.append(current_session)\n # reset session\n current_session = []\n # check for the right type and append\n if row['product_action'] == 'detail':\n current_session.append(row['product_sku_hash'])\n # update the current session id\n current_session_id = _session_id_hash\n\n # print how many sessions we have...\n print(\"# total sessions: {}\".format(len(user_sessions)))\n # print first one to check\n print(\"First session is: {}\".format(user_sessions[0]))\n assert user_sessions[0][0] == 'd5157f8bc52965390fa21ad5842a8502bc3eb8b0930f3f8eafbc503f4012f69c'\n assert user_sessions[0][-1] == '63b567f4cef976d1411aecc4240984e46ebe8e08e327f2be786beb7ee83216d0'\n\n return user_sessions",
"_____no_output_____"
],
[
"def train_product_2_vec_model(sessions: list,\n min_c: int = 3,\n size: int = 48,\n window: int = 5,\n iterations: int = 15,\n ns_exponent: float = 0.75):\n \"\"\"\n Train CBOW to get product embeddings. We start with sensible defaults from the literature - please\n check https://arxiv.org/abs/2007.14906 for practical tips on how to optimize prod2vec.\n\n :param sessions: list of lists, as user sessions are list of interactions\n :param min_c: minimum frequency of an event for it to be calculated for product embeddings\n :param size: output dimension\n :param window: window parameter for gensim word2vec\n :param iterations: number of training iterations\n :param ns_exponent: ns_exponent parameter for gensim word2vec\n :return: trained product embedding model\n \"\"\"\n model = gensim.models.Word2Vec(sentences=sessions,\n min_count=min_c,\n vector_size=size,\n window=window,\n epochs=iterations,\n ns_exponent=ns_exponent)\n\n print(\"# products in the space: {}\".format(len(model.wv.index_to_key)))\n\n return model.wv",
"_____no_output_____"
]
],
[
[
"Get sessions from the training file, and train a prod2vec model with standard hyperparameters",
"_____no_output_____"
]
],
[
[
"# get sessions\nsessions = read_sessions_from_training_file(\n training_file=os.path.join(LOCAL_FOLDER, 'browsing_train.csv'),\n K=N_ROWS)\n# get a counter on all items for later use\nsku_cnt = Counter([item for s in sessions for item in s])\n# print out most common SKUs\nsku_cnt.most_common(3)",
"_____no_output_____"
],
[
"# leave some sessions aside\nidx = int(len(sessions) * 0.8)\ntrain_sessions = sessions[0: idx]\ntest_sessions = sessions[idx:]\nprint(\"Train sessions # {}, test sessions # {}\".format(len(train_sessions), len(test_sessions)))\n# finally, train the p2vec, leaving all the default hyperparameters\nprod2vec_model = train_product_2_vec_model(train_sessions)",
"_____no_output_____"
]
],
[
[
"Show how to get a prediction with knn",
"_____no_output_____"
]
],
[
[
"prod2vec_model.similar_by_word(sku_cnt.most_common(1)[0][0], topn=3)",
"_____no_output_____"
]
],
[
[
"Visualize the prod2vec space, color-coding for categories in the catalog",
"_____no_output_____"
]
],
[
[
"def plot_scatter_by_category_with_lookup(title, \n skus, \n sku_to_target_cat,\n results, \n custom_markers=None):\n groups = {}\n for sku, target_cat in sku_to_target_cat.items():\n if sku not in skus:\n continue\n\n sku_idx = skus.index(sku)\n x = results[sku_idx][0]\n y = results[sku_idx][1]\n if target_cat in groups:\n groups[target_cat]['x'].append(x)\n groups[target_cat]['y'].append(y)\n else:\n groups[target_cat] = {\n 'x': [x], 'y': [y]\n }\n # DEBUG print\n print(\"Total of # groups: {}\".format(len(groups)))\n \n fig, ax = plt.subplots(figsize=(10, 10))\n for group, data in groups.items():\n ax.scatter(data['x'], data['y'], \n alpha=0.3, \n edgecolors='none', \n s=25, \n marker='o' if not custom_markers else custom_markers,\n label=group)\n\n plt.title(title)\n plt.show()\n \n return",
"_____no_output_____"
],
[
"def tsne_analysis(embeddings, perplexity=25, n_iter=1000):\n tsne = TSNE(n_components=2, verbose=1, perplexity=perplexity, n_iter=n_iter)\n return tsne.fit_transform(embeddings)",
"_____no_output_____"
],
[
"def get_sku_to_category_map(catalog_file, depth_index=1):\n \"\"\"\n For each SKU, get category from catalog file (if specified)\n \n :return: dictionary, mapping SKU to a category\n \"\"\"\n sku_to_cats = dict()\n with open(catalog_file) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n _sku = row['product_sku_hash']\n category_hash = row['category_hash']\n if not category_hash:\n continue\n # pick only category at a certain depth in the tree\n # e.g. x/xx/xxx, with depth=1, -> xx\n branches = category_hash.split('/')\n target_branch = branches[depth_index] if depth_index < len(branches) else None\n if not target_branch:\n continue\n # if all good, store the mapping\n sku_to_cats[_sku] = target_branch\n \n return sku_to_cats",
"_____no_output_____"
],
[
"sku_to_category = get_sku_to_category_map(os.path.join(LOCAL_FOLDER, 'sku_to_content.csv'))\nprint(\"Total of # {} categories\".format(len(set(sku_to_category.values()))))\nprint(\"Total of # {} SKU with a category\".format(len(sku_to_category)))\n# debug with a sample SKU\nprint(sku_to_category[sku_cnt.most_common(1)[0][0]])\nskus = prod2vec_model.index_to_key\nprint(\"Total of # {} skus in the model\".format(len(skus)))\nembeddings = [prod2vec_model[s] for s in skus]",
"_____no_output_____"
],
[
"# print out tsne plot with standard params\ntsne_results = tsne_analysis(embeddings)\nassert len(tsne_results) == len(skus)\nplot_scatter_by_category_with_lookup('Prod2vec', skus, sku_to_category, tsne_results)",
"_____no_output_____"
],
[
"# do a version with only top K categories\nTOP_K = 5\ncnt_categories = Counter(list(sku_to_category.values()))\ntop_categories = [c[0] for c in cnt_categories.most_common(TOP_K)]",
"_____no_output_____"
],
[
"# filter out SKUs outside of top categories\ntop_skus = []\ntop_tsne_results = []\nfor _s, _t in zip(skus, tsne_results):\n if sku_to_category.get(_s, None) not in top_categories:\n continue\n top_skus.append(_s)\n top_tsne_results.append(_t)\n# re-plot tsne with filtered SKUs\nprint(\"Top SKUs # {}\".format(len(top_skus)))\nplot_scatter_by_category_with_lookup('Prod2vec (top {})'.format(TOP_K), \n top_skus, sku_to_category, top_tsne_results)",
"_____no_output_____"
]
],
[
[
"### Bonus: faster inference\n\nGensim is awesome and support approximate, faster inference! You need to have installed ANNOY first, e.g. \"pip install annoy\". We re-run here on our prod space the original benchmark for word2vec from gensim!\n\nSee: https://radimrehurek.com/gensim/auto_examples/tutorials/run_annoy.html",
"_____no_output_____"
]
],
[
[
"# Set up the model and vector that we are using in the comparison\nannoy_index = AnnoyIndexer(prod2vec_model, 100)\ntest_sku = sku_cnt.most_common(1)[0][0]\n# test all is good\nprint(prod2vec_model.most_similar([test_sku], topn=2, indexer=annoy_index))\nprint(prod2vec_model.most_similar([test_sku], topn=2))",
"_____no_output_____"
],
[
"def avg_query_time(model, annoy_index=None, queries=5000):\n \"\"\"Average query time of a most_similar method over random queries.\"\"\"\n total_time = 0\n for _ in range(queries):\n _v = model[choice(model.index_to_key)]\n start_time = time.process_time()\n model.most_similar([_v], topn=5, indexer=annoy_index)\n total_time += time.process_time() - start_time\n \n return total_time / queries\n\ngensim_time = avg_query_time(prod2vec_model)\nannoy_time = avg_query_time(prod2vec_model, annoy_index=annoy_index)\nprint(\"Gensim (s/query):\\t{0:.5f}\".format(gensim_time))\nprint(\"Annoy (s/query):\\t{0:.5f}\".format(annoy_time))\nspeed_improvement = gensim_time / annoy_time\nprint (\"\\nAnnoy is {0:.2f} times faster on average on this particular run\".format(speed_improvement))",
"_____no_output_____"
]
],
[
[
"### Bonus: hyper tuning\n\nFor more info on hyper tuning in the context of product embeddings, please see our paper: https://arxiv.org/abs/2007.14906 and our data release: https://github.com/coveooss/fantastic-embeddings-sigir-2020.\n\nWe use the sessions we left out to simulate a small optimization loop...",
"_____no_output_____"
]
],
[
[
"def calculate_HR_on_NEP(model, sessions, k=10, min_length=3):\n _count = 0\n _hits = 0\n for session in sessions:\n # consider only decently-long sessions\n if len(session) < min_length:\n continue\n # update the counter\n _count += 1\n # get the item to predict\n target_item = session[-1]\n # get model prediction using before-last item\n query_item = session[-2]\n # if model cannot make the prediction, it's a failure\n if query_item not in model:\n continue\n predictions = model.similar_by_word(query_item, topn=k)\n # debug\n # print(target_item, query_item, predictions)\n if target_item in [p[0] for p in predictions]:\n _hits += 1\n # debug\n print(\"Total test cases: {}\".format(_count))\n \n return _hits / _count",
"_____no_output_____"
],
[
"# we simulate a test with 3 values for epochs in prod2ve\niterations_values = [1, 10]\n# for each value we train a model, and use Next Event Prediction (NEP) to get a quality assessment\nfor i in iterations_values:\n print(\"\\n ======> Hyper value: {}\".format(i))\n cnt_model = train_product_2_vec_model(train_sessions, iterations=i)\n # use hold-out to have NEP performance\n _hr = calculate_HR_on_NEP(cnt_model, test_sessions)\n print(\"HR: {}\\n\".format(_hr))",
"_____no_output_____"
]
],
[
[
"## Step 2: improving low-count vectors\n\nFor more information about prod2vec in the cold start scenario, please see our paper: https://dl.acm.org/doi/10.1145/3383313.3411477 and video: https://vimeo.com/455641121",
"_____no_output_____"
]
],
[
[
"def build_mapper(pro2vec_dims=48):\n \"\"\"\n Build a Keras model for content-based \"fake\" embeddings.\n \n :return: a Keras model, mapping BERT-like catalog representations to the prod2vec space\n \"\"\"\n # input\n description_input = Input(shape=(50,))\n image_input = Input(shape=(50,))\n # model\n x = Dense(25, activation=\"relu\")(description_input)\n y = Dense(25, activation=\"relu\")(image_input)\n combined = Concatenate()([x, y])\n combined = Dropout(0.3)(combined)\n combined = Dense(25)(combined)\n output = Dense(pro2vec_dims)(combined)\n\n return Model(inputs=[description_input, image_input], outputs=output)",
"_____no_output_____"
],
[
"# get vectors representing text and images in the catalog\ndef get_sku_to_embeddings_map(catalog_file):\n \"\"\"\n For each SKU, get the text and image embeddings, as provided pre-computed by the dataset\n \n :return: dictionary, mapping SKU to a tuple of embeddings\n \"\"\"\n sku_to_embeddings = dict()\n with open(catalog_file) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n _sku = row['product_sku_hash']\n _description = row['description_vector']\n _image = row['image_vector']\n # skip when both vectors are not there\n if not _description or not _image:\n continue\n # if all good, store the mapping\n sku_to_embeddings[_sku] = (json.loads(_description), json.loads(_image))\n \n return sku_to_embeddings",
"_____no_output_____"
],
[
"sku_to_embeddings = get_sku_to_embeddings_map(os.path.join(LOCAL_FOLDER, 'sku_to_content.csv'))\nprint(\"Total of # {} SKUs with embeddings\".format(len(sku_to_embeddings)))\n# print out an example\n_d, _i = sku_to_embeddings['438630a8ba0320de5235ee1bedf3103391d4069646d640602df447e1042a61a3']\nprint(len(_d), len(_i), _d[:5], _i[:5])",
"_____no_output_____"
],
[
"# just make sure we have the SKUs in the model and a counter\nskus = prod2vec_model.index_to_key\nprint(\"Total of # {} skus in the model\".format(len(skus)))\nprint(sku_cnt.most_common(5))",
"_____no_output_____"
],
[
"# above which percentile of frequency we consider SKU popular enough to be our training set?\nFREQUENT_PRODUCTS_PTILE = 80",
"_____no_output_____"
],
[
"_counts = [c[1] for c in sku_cnt.most_common()]\n_counts[:3]",
"_____no_output_____"
],
[
"# make sure we have just SKUS in the prod2vec space for which we have embeddings\npopular_threshold = np.percentile(_counts, FREQUENT_PRODUCTS_PTILE)\npopular_skus = [s for s in skus if s in sku_to_embeddings and sku_cnt.get(s, 0) > popular_threshold]\nproduct_embeddings = [prod2vec_model[s] for s in popular_skus]\ndescription_embeddings = [sku_to_embeddings[s][0] for s in popular_skus]\nimage_embeddings = [sku_to_embeddings[s][1] for s in popular_skus]\n# debug\nprint(popular_threshold, len(skus), len(popular_skus))\n# print(description_embeddings[:1][:3])\n# print(image_embeddings[:1][:3])",
"_____no_output_____"
],
[
"# train the mapper now\ntraining_data_X = [np.array(description_embeddings), np.array(image_embeddings)]\ntraining_data_y = np.array(product_embeddings)",
"_____no_output_____"
],
[
"es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=20, restore_best_weights=True)\n# build and display model\nrare_net = build_mapper()\nplot_model(rare_net, show_shapes=True, show_layer_names=True, to_file='rare_net.png')\nImage('rare_net.png')",
"_____no_output_____"
],
[
"# train!\nrare_net.compile(loss='mse', optimizer='rmsprop')\nrare_net.fit(training_data_X, \n training_data_y, \n batch_size=200, \n epochs=20000, \n validation_split=0.2, \n callbacks=[es])",
"_____no_output_____"
],
[
"# rarest_skus = [_[0] for _ in sku_cnt.most_common()[-500:]]\n# test_skus = [s for s in rarest_skus if s in sku_to_embeddings]\n\n# get to rare vectors\ntest_skus = [s for s in skus if s in sku_to_embeddings and sku_cnt.get(s, 0) < popular_threshold/2]\nprint(len(skus), len(test_skus))\n# prepare embeddings for prediction\nrare_description_embeddings = [sku_to_embeddings[s][0] for s in test_skus]\nrare_image_embeddings = [sku_to_embeddings[s][1] for s in test_skus]",
"_____no_output_____"
],
[
"# prepare embeddings for prediction\ntest_data_X = [np.array(rare_description_embeddings), np.array(rare_image_embeddings)]\npredicted_embeddings = rare_net.predict(test_data_X)\n# debug\n# print(len(predicted_embeddings))\n# print(predicted_embeddings[0][:10])",
"_____no_output_____"
],
[
"def calculate_HR_on_NEP_rare(model, sessions, rare_skus, k=10, min_length=3):\n _count = 0\n _hits = 0\n _rare_hits = 0\n _rare_count = 0\n for session in sessions:\n # consider only decently-long sessions\n if len(session) < min_length:\n continue\n # update the counter\n _count += 1\n # get the item to predict\n target_item = session[-1]\n # get model prediction using before-last item\n query_item = session[-2]\n\n # if model cannot make the prediction, it's a failure\n if query_item not in model:\n continue\n \n # increment counter if rare sku\n if query_item in rare_skus:\n _rare_count+=1\n \n predictions = model.similar_by_word(query_item, topn=k)\n \n # debug\n # print(target_item, query_item, predictions) \n if target_item in [p[0] for p in predictions]:\n _hits += 1\n # track hits if query is rare sku\n if query_item in rare_skus:\n _rare_hits+=1\n # debug\n print(\"Total test cases: {}\".format(_count))\n print(\"Total rare test cases: {}\".format(_rare_count))\n \n return _hits / _count, _rare_hits/_rare_count",
"_____no_output_____"
],
[
"# make copy of original prod2vec model\nprod2vec_rare_model = deepcopy(prod2vec_model)\n# update model with new vectors\nprod2vec_rare_model.add_vectors(test_skus, predicted_embeddings, replace=True)\nprod2vec_rare_model.fill_norms(force=True)\n# check\nassert np.array_equal(predicted_embeddings[0], prod2vec_rare_model[test_skus[0]])\n\n# test new model\ncalculate_HR_on_NEP_rare(prod2vec_rare_model, test_sessions, test_skus)",
"_____no_output_____"
],
[
"# test original model\ncalculate_HR_on_NEP_rare(prod2vec_model, test_sessions, test_skus)",
"_____no_output_____"
]
],
[
[
"## Step 3: query scoping\n\nFor more information about query scoping, please see our paper: https://www.aclweb.org/anthology/2020.ecnlp-1.2/ and repository: https://github.com/jacopotagliabue/session-path",
"_____no_output_____"
]
],
[
[
"# get vectors representing text and images in the catalog\ndef get_query_to_category_dataset(search_file, cat_2_id, sku_to_category):\n \"\"\"\n For each query, get a label representing the category in items clicked after the query.\n It uses as input a mapping \"sku_to_category\" to join the search file with catalog meta-data!\n \n :return: two lists, matching query vectors to a label\n \"\"\"\n query_X = list()\n query_Y = list()\n with open(search_file) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n _click_products = row['clicked_skus_hash']\n if not _click_products: # or _click_product not in sku_to_category:\n continue\n # clean the string and extract SKUs from array\n cleaned_skus = ast.literal_eval(_click_products)\n for s in cleaned_skus: \n if s in sku_to_category:\n query_X.append(json.loads(row['query_vector']))\n target_category_as_int = cat_2_id[sku_to_category[s]]\n query_Y.append(utils.to_categorical(target_category_as_int, num_classes=len(cat_2_id)))\n \n return query_X, query_Y",
"_____no_output_____"
],
[
"sku_to_category = get_sku_to_category_map(os.path.join(LOCAL_FOLDER, 'sku_to_content.csv'))\nprint(\"Total of # {} categories\".format(len(set(sku_to_category.values()))))\ncats = list(set(sku_to_category.values()))\ncat_2_id = {c: idx for idx, c in enumerate(cats)}\nprint(cat_2_id[cats[0]])\nquery_X, query_Y = get_query_to_category_dataset(os.path.join(LOCAL_FOLDER, 'search_train.csv'), \n cat_2_id,\n sku_to_category)\nprint(len(query_X))\nprint(query_Y[0])",
"_____no_output_____"
],
[
"x_train, x_test, y_train, y_test = train_test_split(np.array(query_X), np.array(query_Y), test_size=0.2)",
"_____no_output_____"
],
[
"def build_query_scoping_model(input_d, target_classes):\n print('Shape tensor {}, target classes {}'.format(input_d, target_classes))\n # define model\n model = Sequential()\n model.add(Dense(64, activation='relu', input_dim=input_d))\n model.add(Dropout(0.5))\n model.add(Dense(64, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(target_classes, activation='softmax'))\n \n return model",
"_____no_output_____"
],
[
"query_model = build_query_scoping_model(x_train[0].shape[0], y_train[0].shape[0])",
"_____no_output_____"
],
[
"# compile model\nsgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\nquery_model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n# train first\nquery_model.fit(x_train, y_train, epochs=10, batch_size=32)\n# compute and print eval score\nscore = query_model.evaluate(x_test, y_test, batch_size=32)\nscore",
"_____no_output_____"
],
[
"# get vectors representing text and images in the catalog\ndef get_query_info(search_file):\n \"\"\"\n For each query, extract relevant metadata of query and to match with session data\n\n :return: list of queries with metadata\n \"\"\"\n queries = list()\n with open(search_file) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n _click_products = row['clicked_skus_hash']\n if not _click_products: # or _click_product not in sku_to_category:\n continue\n # clean the string and extract SKUs from array\n cleaned_skus = ast.literal_eval(_click_products)\n queries.append({'session_id_hash' : row['session_id_hash'],\n 'server_timestamp_epoch_ms' : int(row['server_timestamp_epoch_ms']),\n 'clicked_skus' : cleaned_skus,\n 'query_vector' : json.loads(row['query_vector'])})\n print(\"# total queries: {}\".format(len(queries))) \n \n return queries\n\ndef get_session_info_for_queries(training_file: str, query_info: list, K: int = None):\n \"\"\"\n Read the training file containing product interactions for sessions with query, up to K rows.\n \n :return: dict of lists with session_id as key, each list being a session (sequence of product events with metadata) \n \"\"\"\n user_sessions = dict()\n current_session_id = None\n current_session = []\n \n query_session_ids = set([ _['session_id_hash'] for _ in query_info])\n\n with open(training_file) as csvfile:\n reader = csv.DictReader(csvfile)\n for idx, row in enumerate(reader):\n # if a max number of items is specified, just return at the K with what you have\n if K and idx >= K:\n break\n # just append \"detail\" events in the order we see them\n # row will contain: session_id_hash, product_action, product_sku_hash\n _session_id_hash = row['session_id_hash']\n # when a new session begins, store the old one and start again\n if current_session_id and current_session and _session_id_hash != current_session_id:\n user_sessions[current_session_id] = current_session\n # reset session\n current_session = []\n # check for the right type and append event info\n if row['product_action'] == 'detail' and _session_id_hash in query_session_ids :\n current_session.append({'product_sku_hash': row['product_sku_hash'],\n 'server_timestamp_epoch_ms' : int(row['server_timestamp_epoch_ms'])})\n # update the current session id\n current_session_id = _session_id_hash\n\n # print how many sessions we have...\n print(\"# total sessions: {}\".format(len(user_sessions)))\n\n\n return dict(user_sessions)",
"_____no_output_____"
],
[
"query_info = get_query_info(os.path.join(LOCAL_FOLDER, 'search_train.csv'))\nsession_info = get_session_info_for_queries(os.path.join(LOCAL_FOLDER, 'browsing_train.csv'), query_info)",
"_____no_output_____"
],
[
"def get_contextual_query_to_category_dataset(query_info, session_info, prod2vec_model, cat_2_id, sku_to_category):\n \"\"\"\n For each query, get a label representing the category in items clicked after the query.\n It uses as input a mapping \"sku_to_category\" to join the search file with catalog meta-data!\n It also creates a joint embedding for input by concatenating query vector and average session vector up till\n when query was made\n \n :return: two lists, matching query vectors to a label\n \"\"\"\n query_X = list()\n query_Y = list()\n \n for row in query_info:\n query_timestamp = row['server_timestamp_epoch_ms']\n cleaned_skus = row['clicked_skus']\n session_id_hash = row['session_id_hash']\n if session_id_hash not in session_info or not cleaned_skus: # or _click_product not in sku_to_category:\n continue \n \n session_skus = session_info[session_id_hash]\n context_skus = [ e['product_sku_hash'] for e in session_skus if query_timestamp > e['server_timestamp_epoch_ms'] \n and e['product_sku_hash'] in prod2vec_model]\n if not context_skus:\n continue\n context_vector = np.mean([prod2vec_model[sku] for sku in context_skus], axis=0).tolist()\n for s in cleaned_skus: \n if s in sku_to_category:\n query_X.append(row['query_vector'] + context_vector)\n target_category_as_int = cat_2_id[sku_to_category[s]]\n query_Y.append(utils.to_categorical(target_category_as_int, num_classes=len(cat_2_id)))\n \n return query_X, query_Y",
"_____no_output_____"
],
[
"context_query_X, context_query_Y = get_contextual_query_to_category_dataset(query_info, \n session_info, \n prod2vec_model, \n cat_2_id, \n sku_to_category)\nprint(len(context_query_X))\nprint(context_query_Y[0])",
"_____no_output_____"
],
[
"x_train, x_test, y_train, y_test = train_test_split(np.array(context_query_X), np.array(context_query_Y), test_size=0.2)",
"_____no_output_____"
],
[
"contextual_query_model = build_query_scoping_model(x_train[0].shape[0], y_train[0].shape[0])",
"_____no_output_____"
],
[
"# compile model\nsgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\ncontextual_query_model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n# train first\ncontextual_query_model.fit(x_train, y_train, epochs=10, batch_size=32)\n# compute and print eval score\nscore = contextual_query_model.evaluate(x_test, y_test, batch_size=32)\nscore",
"_____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"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"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",
"code",
"code"
]
] |
4aabef392d9292dca96e34888b4c8660e59ed26e
| 92,457 |
ipynb
|
Jupyter Notebook
|
MultipleLinearRegression/crab-age-prediction-v2.ipynb
|
13rianlucero/CrabAgePrediction
|
92bc7fbe1040f49e820473e33cc3902a5a7177c7
|
[
"MIT"
] | null | null | null |
MultipleLinearRegression/crab-age-prediction-v2.ipynb
|
13rianlucero/CrabAgePrediction
|
92bc7fbe1040f49e820473e33cc3902a5a7177c7
|
[
"MIT"
] | null | null | null |
MultipleLinearRegression/crab-age-prediction-v2.ipynb
|
13rianlucero/CrabAgePrediction
|
92bc7fbe1040f49e820473e33cc3902a5a7177c7
|
[
"MIT"
] | null | null | null | 186.405242 | 45,974 | 0.807608 |
[
[
[
"# CrabAgePrediction\n__\n--\n\n<nav class=\"table-of-contents\"><ol><li><a href=\"#crabageprediction\">CrabAgePrediction</a></li><li><a href=\"#overview\">Overview</a><ol><li><a href=\"#1.-abstract\">1. Abstract</a><ol><li><a href=\"#paper-summary-%E2%9C%94%EF%B8%8F\">Paper Summary ✔️</a></li></ol></li><li><a href=\"#2.-introduction\">2. Introduction</a></li><li><a href=\"#3.-background\">3. Background</a><ol><li><a href=\"#process-activities-%E2%9C%94%EF%B8%8F\">Process Activities ✔️</a></li><li><a href=\"#models-%E2%9C%94%EF%B8%8F\">Models ✔️</a></li><li><a href=\"#analysis-%E2%9C%94%EF%B8%8F\">Analysis ✔️</a></li></ol></li><li><a href=\"#4.-methods\">4. Methods</a><ol><li><a href=\"#approach-%E2%9C%94%EF%B8%8F\">Approach ✔️</a></li><li><a href=\"#key-contributions-%E2%9C%94%EF%B8%8F\">Key Contributions ✔️</a></li></ol></li><li><a href=\"#5.-experiments\">5. Experiments</a><ol><li><a href=\"#prediction-system-development-workflow-%E2%9C%94%EF%B8%8F\">Prediction System Development Workflow ✔️</a></li><li><a href=\"#predicition-model-workflow-%E2%9C%94%EF%B8%8F\">Predicition Model Workflow ✔️</a></li><li><a href=\"#code-%E2%9C%94%EF%B8%8F\">Code ✔️</a></li></ol></li><li><a href=\"#6.-conclusion\">6. Conclusion</a><ol><li><a href=\"#summary-of-results-%E2%9C%94%EF%B8%8F\">Summary of Results ✔️</a></li><li><a href=\"#future-work-%E2%9C%94%EF%B8%8F\">Future work ✔️</a></li></ol></li><li><a href=\"#7.-references\">7. References</a><ol><li><a href=\"#links-%E2%9C%94%EF%B8%8F\">Links ✔️</a></li></ol></li><li><a href=\"#code\">Code</a><ol><li><a href=\"#proposal-information\">Proposal Information</a></li></ol></li><li><a href=\"#helpful-resources-for-the-project\">Helpful Resources for the Project</a></li></ol></li><li><a href=\"#crabageprediction-1\">CrabAgePrediction</a></li></ol></nav>\n<h1 id=\"crabageprediction\" id=\"crabageprediction\">CrabAgePrediction</h1>\n\n\n<p>\n <img src=\"https://img.shields.io/badge/Kaggle-035a7d?style=for-the-badge&logo=kaggle&logoColor=white\" alt=\"\"/>\n <img src=\"https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54\" alt=\"\" />\n <img src=\"https://img.shields.io/badge/jupyter-%23FA0F00.svg?style=for-the-badge&logo=jupyter&logoColor=white\" alt=\"\" />\n <img src=\"https://img.shields.io/badge/pycharm-143?style=for-the-badge&logo=pycharm&logoColor=black&color=black&labelColor=green\" alt=\"\" />\n</p>\n\n## Project Information:\n```py\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n```\n\n**CLASS:** `CPSC-483 Machine Learning Section-02`\n\n**LAST UPDATE:** `May 5, 2022`\n\n**PROJECT NAME:** `Crab Age Prediction`\n\n**PROJECT GROUP:**\n\n| Name | Email | Student |\n| ------------ | ------------------------------ | ------------- |\n| Brian Lucero | [email protected] | Undergraduate |\n| Justin Heng | [email protected] | Graduate |\n\n**PROJECT PAPER:** [Here](https://github.com/13rianlucero/CrabAgePrediction/blob/main/FirstDraft/Crab%20Age%20Prediction%20Paper.pdf)\n\n**PROJECT GITHUB REPOSITORY:** [Here](https://github.com/13rianlucero/CrabAgePrediction)\n\n\n\n# Overview\n\n> __\n> \n> \n> ## **1. Abstract**\n>\n> ###### Paper Summary ✔️\n>\n> Machine learning can be used to predict the age of crabs. It can be more accurate than simply weighing a crab to estimate its age. Several different models can be used, though support vector regression was found to be the most accurate in this experiment.\n>\n>> __\n>> \n>> \n>> ## **2. Introduction**\n>>\n>> | The Problem ✔️ | Why it's important? ✔️ | Our Solution Strategy ✔️ |\n>> | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n>> | <br /><br />*It is quite difficult to determine a crab's age due to their molting cycles which happen throughout their whole life. Essentially, the failure to harvest at an ideal age, increases cost and crab lives go to waste.* | <br /><br />*Beyond a certain age, there is negligible growth in crab's physical characteristics and hence, it is important to time the harvesting to reduce cost and increase profit.* | <br /><br />Prepare crab data and use it to train several machine learning models. Thus, given certain physcial chraracteristics and the corresponding values, the ML models will accurately determine the age of the crabs. |\n>>\n>>> __\n>>> ## **3. Background**\n>>>\n>>> ###### **Process Activities ✔️**\n>>>\n>>> - Feature Selection & Representation\n>>> - Evaluation on variety of methods\n>>> - Method Selection\n>>> - Parameter Tuning\n>>> - Classifier Evaluation\n>>> - Train-Test Split\n>>> - Cross Validation\n>>> - Eliminating Data\n>>> - Handle Categorical Data\n>>> - One-hot encoding\n>>> - Data Partitioning\n>>> - Feature Scaling\n>>> - Feature Selection\n>>> - Choose ML Models\n>>>\n>>> ###### Models ✔️\n>>>\n>>> - K-Nearest Neighbours (KNN)\n>>> - Multiple Linear Regression (MLR)\n>>> - Support Vector Machine (SVM)\n>>>\n>>> ###### Analysis ✔️\n>>>\n>>> - Evaluate Results\n>>> - Performance Metrics\n>>> - Compare ML Models using Metrics\n>>>\n>>>> __\n>>>> ## **4. Methods**\n>>>>\n>>>> ###### Approach ✔️\n>>>>\n>>>> - Prediction System using 3 main ML Models\n>>>>\n>>>> ###### Key Contributions ✔️\n>>>>\n>>>> - Justin\n>>>> - `KNN`\n>>>> - `SVM`\n>>>> - Brian\n>>>> - `MLR`\n>>>>\n>>>>> __\n>>>>> ## **5. Experiments**\n>>>>>\n>>>>> ###### Prediction System Development Workflow ✔️\n>>>>>\n>>>>> ```mermaid\n>>>>> graph TD\n>>>>>\n>>>>> A[Problem Domain: Age Prediction of Crabs]\n>>>>> B[Data Representation: Physical Attribute Values]\n>>>>> C[Objective Function: Average Error Rate on Training Crab Data]\n>>>>> D[Evalutation: Average Error Rate on Test Crab Data]\n>>>>> E[Learning Algorithm: KNN, MLR, SVM]\n>>>>>\n>>>>> F[Predictive Model: KNN Model]\n>>>>> G[Predictive Model: MLR Model]\n>>>>> H[Predictive Model: SVM Model]\n>>>>>\n>>>>> I[Prediction System: Aggregate Model Results]\n>>>>> J[Useful Predictions: Low Bias, Low Variance]\n>>>>> K[Domain Insights: Types of Crabs]\n>>>>>\n>>>>> A -- Discrete and Continuous --> B\n>>>>> A -- Training dataset --> C\n>>>>> A -- Test dataset --> D\n>>>>>\n>>>>> B --> E\n>>>>> C --> E \n>>>>> D --> E\n>>>>>\n>>>>> E --> F\n>>>>> E --> G \n>>>>> E --> H\n>>>>>\n>>>>> F --> I\n>>>>> G --> I\n>>>>> H --> I\n>>>>>\n>>>>> I --> J\n>>>>> I --> K\n>>>>>\n>>>>> ```\n>>>>>\n>>>>> ###### Predicition Model Workflow ✔️\n>>>>>\n>>>>> | KNN | MLR | SVM |\n>>>>> | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |\n>>>>> | Import Libraries | Import Libraries | Import Libraries |\n>>>>> | Import Dataset, create dataframe | Import Dataset, create dataframe | Import Dataset, create dataframe |\n>>>>> | Data Preprocessing | Data Preprocessing | Data Preprocessing |\n>>>>> | Check for Missing data, Bad Data, Outliers, Data Types, Choose Classifier, Data Organization, Data Scaling, etc | Check for Missing data, Bad Data, Outliers, Data Types, Choose Classifier, Data Organization, Data Scaling, etc | Check for Missing data, Bad Data, Outliers, Data Types, Choose Classifier, Data Organization, Data Scaling, etc |\n>>>>> | Feature Selection | Feature Selection | Feature Selection |\n>>>>> | Train-Test Split | Train-Test Split | Train-Test Split |\n>>>>> | Build Algorithm | Build Algorithm | Build Algorithm |\n>>>>> | Train Algorithm | Train Algorithm | Train Algorithm |\n>>>>> | Test Algorithm | Test Algorithm | Test Algorithm |\n>>>>> | Produce Performance Metrics from Tests | Produce Performance Metrics from Tests | Produce Performance Metrics from Tests |\n>>>>> | Evaluate Results | Evaluate Results | Evaluate Results |\n>>>>> | Tune Algorithm | Tune Algorithm | Tune Algorithm |\n>>>>> | Retest & Re-Analayze | Retest & Re-Analayze | Retest & Re-Analayze |\n>>>>> | Predicition Model defined from new train-test-analyze cycle | Predicition Model defined from new train-test-analyze cycle | Predicition Model defined from new train-test-analyze cycle |\n>>>>> | Use model to refine the results | Use model to refine the results | Use model to refine the results |\n>>>>> | Draw Conclusions | Draw Conclusions | Draw Conclusions |\n>>>>>\n>>>>> ###### Code ✔️\n>>>>>>\n>>>>>> __\n>>>>>> ## **6. Conclusion**\n>>>>>>\n>>>>>> ###### Summary of Results ✔️\n>>>>>>\n>>>>>> Overall, the models were able to predict the age of crabs reasonably well. On average, the predictions were off by about 1.5 months. Although support vector regression performed slightly better than the other two models, it was still close enough that any of the models could be used with satisfactory results.\n>>>>>>\n>>>>>> Multiple linear regression was found to be slightly better at predicting older crabs while support vector regression was better at predicting younger crabs. K-nearest neighbor was average overall. What is important to note is that the predictions for all three models were more accurate when the age of the crab was less than 12 months. This makes sense because after a crab reaches full maturity around 12 months, its growth comes to a halt and it is harder to predict its age since its features stay roughly the same.\n>>>>>>\n>>>>>> Therefore, predicting the age of a crab becomes less accurate the longer a crab has matured. To circumvent this, the dataset could be further preprocessed so that any crab over the age of 12 months will be set to 12 months.\n>>>>>>\n>>>>>> This would greatly increase the accuracy of the machine learning models though the models would no longer be able to predict any ages over 12 months. Since the purpose is to find which crabs are harvestable, this may be a good compromise.\n>>>>>>\n>>>>>> | Model | Type | Error (months) |\n>>>>>> | --------------------------------- | -------- | -------------- |\n>>>>>> | Linear Regression (Weight vs Age) | Baseline | 1.939 |\n>>>>>> | K-nearest Neighbor | ML | 1.610 |\n>>>>>> | Multiple Linear Regression | ML | 1.560 |\n>>>>>>\n>>>>>> ###### Future work ✔️\n>>>>>>\n>>>>>> Predicting the age of a crab becomes less accurate the longer a crab has matured. To circumvent this, the dataset could be further preprocessed so that any crab over the age of 12 months will be set to 12 months.\n>>>>>>\n>>>>>> This would greatly increase the accuracy of the machine learning models though the models would no longer be able to predict any ages over 12 months. Since the purpose is to find which crabs are harvestable, this may be a good compromise.\n>>>>>>\n>>>>>>> __\n>>>>>>> ## **7. References**\n>>>>>>>\n>>>>>>> <p align=\"center\">\n>>>>>>> <img src=\"https://img.shields.io/badge/Kaggle-035a7d?style=for-the-badge&logo=kaggle&logoColor=white\" alt=\"\"/>\n>>>>>>> <img src=\"https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54\" alt=\"\" />\n>>>>>>> <img src=\"https://img.shields.io/badge/jupyter-%23FA0F00.svg?style=for-the-badge&logo=jupyter&logoColor=white\" alt=\"\" />\n>>>>>>> <img src=\"https://img.shields.io/badge/pycharm-143?style=for-the-badge&logo=pycharm&logoColor=black&color=black&labelColor=green\" alt=\"\" />\n>>>>>>> </p>\n>>>>>>>\n>>>>>>> ###### Links ✔️\n>>>>>>>\n>>>>>>> [1] [https://www.kaggle.com/datasets/sidhus/crab-age-prediction](https://www.kaggle.com/datasets/sidhus/crab-age-prediction)\n>>>>>>>\n>>>>>>> [2] [https://scikit-learn.org/stable/modules/svm.html](https://scikit-learn.org/stable/modules/svm.html)\n>>>>>>>\n>>>>>>> [3] [https://repository.library.noaa.gov/view/noaa/16273/noaa_16273_DS4.pdf](https://repository.library.noaa.gov/view/noaa/16273/noaa_16273_DS4.pdf)\n>>>>>>>\n>>>>>>> [4] [https://faculty.math.illinois.edu/~hildebr/tex/latex-start.html](https://faculty.math.illinois.edu/~hildebr/tex/latex-start.html)\n>>>>>>>\n>>>>>>> [5] [https://github.com/krishnaik06/Multiple-Linear-Regression](https://github.com/krishnaik06/Multiple-Linear-Regression)\n>>>>>>>\n>>>>>>> [6] [https://github.com/13rianlucero/CrabAgePrediction](https://github.com/13rianlucero/CrabAgePrediction)\n>>>>>>>\n>>>>>>> __\n>>>>>>>\n>>>>>>\n>>>>>> __\n>>>>>>\n>>>>>\n>>>>> __\n>>>>>\n>>>>\n>>>> __\n>>>>\n>>>\n>>> __\n>>>\n>>\n>> __\n>>\n>\n> __\n\n---\n ",
"_____no_output_____"
],
[
"## Import the Libraries\n---",
"_____no_output_____"
]
],
[
[
"import pandas\nimport numpy\nfrom scipy import stats\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import svm\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score",
"_____no_output_____"
]
],
[
[
"## Import Dataset into Dataframe variable\n---",
"_____no_output_____"
]
],
[
[
"import pandas\nimport numpy\nfrom scipy import stats\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import svm\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score\n\ndata = pandas.read_csv(r\"CrabAgePrediction.csv\").dropna(axis=0)\nprint(data.columns)\ndata[\"SexValue\"] = 0 #create a new column\n\nfor index, row in data.iterrows():\n #convert male or female to a numerical value Male=1, Female=2, Indeterminate=1.5\n if row[\"Sex\"] == \"M\":\n data.iloc[index, 9] = 1\n elif row[\"Sex\"] == \"F\":\n data.iloc[index, 9] = 2\n else:\n data.iloc[index, 9] = 1.5\n\n#putting all our data together and dropping Sex for SexValue\ndata = data[[\"SexValue\", \"Length\", \"Diameter\", \"Height\", \"Weight\", \"Shucked Weight\", \"Viscera Weight\", \"Shell Weight\", \"Age\"]]\nX = data[[\"Length\", \"Diameter\", \"Height\", \"Weight\", \"Shucked Weight\", \"Viscera Weight\", \"Shell Weight\"]]\ny = data[[\"Age\"]]\n\n#Pearson correlation for every feature\ncol_cor = stats.pearsonr(data[\"SexValue\"], y)\ncol1_cor = stats.pearsonr(data[\"Length\"], y)\ncol2_cor = stats.pearsonr(data[\"Diameter\"], y)\ncol3_cor = stats.pearsonr(data[\"Height\"], y)\ncol4_cor = stats.pearsonr(data[\"Weight\"], y)\ncol5_cor = stats.pearsonr(data[\"Shucked Weight\"], y)\ncol6_cor = stats.pearsonr(data[\"Viscera Weight\"], y)\ncol7_cor = stats.pearsonr(data[\"Shell Weight\"], y)\nprint(col_cor)\nprint(col1_cor)\nprint(col2_cor)\nprint(col3_cor)\nprint(col4_cor)\nprint(col5_cor)\nprint(col6_cor)\nprint(col7_cor)\n\n#split the data into test and train set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=132)\n\n#n_neighbors plot\nerror_rate = []\ny_test2 = numpy.ravel(y_test)\nfor k in range(1, 31):\n neigh = KNeighborsClassifier(n_neighbors=k)\n neigh.fit(X_train, numpy.ravel(y_train))\n knn_predict = neigh.predict(X_test)\n error_knn = 0\n for x in range(0, 1168):\n error_knn += abs(knn_predict[x] - y_test2[x])\n error_rate.append(error_knn/1169)\n\nplt.plot(range(1, 31), error_rate)\nplt.xlabel(\"n_neighbors\")\nplt.ylabel(\"error_rate\")\nplt.title(\"Average error vs n_neighbors\")\nplt.show()\n\n#KNN\nneigh = KNeighborsClassifier(n_neighbors=20)\nneigh.fit(X_train, numpy.ravel(y_train))\nknn_predict = neigh.predict(X_test)\n\n#Multiple Linear Regression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\ny_pred = regressor.predict(X_test)\nscore = r2_score(y_test,y_pred)\n\n\n#SVR\nregr = svm.SVR()\nregr.fit(X_train, numpy.ravel(y_train))\nregr_predict = regr.predict(X_test)\n\n# #plot the predicted age against the actual age for the test set\nplt.plot(range(1, 1169), knn_predict)\nplt.plot(range(1, 1169), y_pred)\nplt.plot(range(1, 1169), regr_predict)\nplt.plot(range(1, 1169), numpy.ravel(y_test))\nplt.xlim([0, 50])\n\n#plt.xlim([60, 90])\nplt.legend([\"KNN Predicted Age\", \"LR Predicted Age\", \"SVR Predicted Age\", \"Actual Age\"])\nplt.ylabel(\"Age in months\")\nplt.title(\"Predicted vs Actual Crab Age\")\nplt.show()\n\nerror_knn = 0\nerror_mlr = 0\nerror_svr = 0\ny_test2 = numpy.ravel(y_test)\nfor x in range(0, 1168):\n error_knn += abs(knn_predict[x] - y_test2[x])\n error_mlr += abs(y_pred[x] - y_test2[x])\n error_svr += abs(regr_predict[x] - y_test2[x])\n\nprint (error_knn/1169)\nprint (error_mlr/1169)\nprint (error_svr/1169)",
"Index(['Sex', 'Length', 'Diameter', 'Height', 'Weight', 'Shucked Weight',\n 'Viscera Weight', 'Shell Weight', 'Age'],\n dtype='object')\n(array([0.033699509736789965], dtype=object), 0.03550371594306473)\n(array([0.5549732839723299], dtype=object), 1.9699194608e-313)\n(array([0.5738443164409989], dtype=object), 0.0)\n(array([0.5519563592563644], dtype=object), 2.31460580813873e-309)\n(array([0.5388194354367395], dtype=object), 4.071814981169477e-292)\n(array([0.41875977260190494], dtype=object), 3.776041286385598e-165)\n(array([0.5013277738041874], dtype=object), 6.902144598512297e-247)\n(array([0.625194993696918], dtype=object), 0.0)\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aabef892c5fbd3c3bbf321b910f0bff397f495a
| 92,803 |
ipynb
|
Jupyter Notebook
|
_oldnotebooks/Introduction_to_Pandas-4.ipynb
|
eneskemalergin/OldBlog
|
3fc3c516b40c1cba7dec18eb461e4dd90f8cb5bb
|
[
"MIT"
] | null | null | null |
_oldnotebooks/Introduction_to_Pandas-4.ipynb
|
eneskemalergin/OldBlog
|
3fc3c516b40c1cba7dec18eb461e4dd90f8cb5bb
|
[
"MIT"
] | null | null | null |
_oldnotebooks/Introduction_to_Pandas-4.ipynb
|
eneskemalergin/OldBlog
|
3fc3c516b40c1cba7dec18eb461e4dd90f8cb5bb
|
[
"MIT"
] | null | null | null | 55.371718 | 28,288 | 0.696465 |
[
[
[
" ---\n layout: post\n title: Introduction to Pandas 4\n excerpt:\n categories: blog\n tags: [\"Python\", \"Data Science\", \"Pandas\"]\n published: true\n comments: true\n share: true\n ---\n\n",
"_____no_output_____"
],
[
"Let;s get our hands dirty with another important topic in Pandas. We need to able to handle missing data and we will see some methods to handle them. After making our data more suitable for analysis, or prediction we will learn how to plot it with ```matplotlib``` library. \n\n> I am going to use matplotlib library for this post and other pandas tutorials but I normally prefer using bokeh interactive plotting library. \n\nIf you like to follow this small tutorial in notebook format you can check out [here](https://github.com/eneskemalergin/Blog-Notebooks/blob/master/Introduction_to_Pandas-4.ipynb)\n\n## Handling Missing Data\n\nMissing data is usually shows up as ```NULL``` or ```N/A``` or **```NaN```** (Pandas represents this way.)\nOther than appearing natively in the source dataset, missing values can be added to a dataset by an operation such as reindexing, or changing frequencies in the case of a time series:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"date_stngs = ['2014-05-01','2014-05-02','2014-05-05','2014-05-06','2014-05-07']\ntradeDates = pd.to_datetime(pd.Series(date_stngs))\nclosingPrices=[531.35,527.93,527.81,515.14,509.96]\ngoogClosingPrices=pd.DataFrame(data=closingPrices, columns=['closingPrice'], index=tradeDates)\ngoogClosingPrices",
"_____no_output_____"
]
],
[
[
"Pandas is also provides a very easy and fast API to read stock data from various finance data providers. ",
"_____no_output_____"
]
],
[
[
"from pandas_datareader import data, wb # pandas data READ API\nimport datetime",
"_____no_output_____"
],
[
"googPrices = data.get_data_yahoo(\"GOOG\", start=datetime.datetime(2014, 5, 1), \n end=datetime.datetime(2014, 5, 7))",
"_____no_output_____"
],
[
"googFinalPrices=pd.DataFrame(googPrices['Close'], index=tradeDates)\ngoogFinalPrices",
"_____no_output_____"
]
],
[
[
"We now have a time series that depicts the closing price of Google's stock from May 1, 2014 to May 7, 2014 with gaps in the date range since the trading only occur on business days. If we want to change the date range so that it shows calendar days (that is, along with the weekend), we can change the frequency of the time series index from business days to calendar days as follow:",
"_____no_output_____"
]
],
[
[
"googClosingPricesCDays = googClosingPrices.asfreq('D')\ngoogClosingPricesCDays",
"_____no_output_____"
]
],
[
[
"Note that we have now introduced NaN values for the closingPrice for the weekend dates of May 3, 2014 and May 4, 2014. \n\nWe can check which values are missing by using the ```isnull()``` and ```notnull()``` functions as follows:",
"_____no_output_____"
]
],
[
[
"googClosingPricesCDays.isnull()",
"_____no_output_____"
],
[
"googClosingPricesCDays.notnull()",
"_____no_output_____"
]
],
[
[
"A Boolean DataFrame is returned in each case. In datetime and pandas Timestamps, missing values are represented by the NaT value. This is the equivalent of NaN in pandas for time-based types",
"_____no_output_____"
]
],
[
[
"tDates=tradeDates.copy()\ntDates[1]=np.NaN\ntDates[4]=np.NaN\ntDates",
"_____no_output_____"
],
[
"FBVolume=[82.34,54.11,45.99,55.86,78.5]\nTWTRVolume=[15.74,12.71,10.39,134.62,68.84]\nsocialTradingVolume=pd.concat([pd.Series(FBVolume), pd.Series(TWTRVolume),\n tradeDates], axis=1,keys=['FB','TWTR','TradeDate'])\nsocialTradingVolume",
"_____no_output_____"
],
[
"socialTradingVolTS=socialTradingVolume.set_index('TradeDate')\nsocialTradingVolTS",
"_____no_output_____"
],
[
"socialTradingVolTSCal=socialTradingVolTS.asfreq('D')\nsocialTradingVolTSCal",
"_____no_output_____"
]
],
[
[
"We can perform arithmetic operations on data containing missing values. For example, we can calculate the total trading volume (in millions of shares) across the two stocks for Facebook and Twitter as follows:",
"_____no_output_____"
]
],
[
[
"socialTradingVolTSCal['FB']+socialTradingVolTSCal['TWTR']",
"_____no_output_____"
]
],
[
[
"By default, any operation performed on an object that contains missing values will return a missing value at that position as shown in the following command:",
"_____no_output_____"
]
],
[
[
"pd.Series([1.0,np.NaN,5.9,6])+pd.Series([3,5,2,5.6])",
"_____no_output_____"
],
[
"pd.Series([1.0,25.0,5.5,6])/pd.Series([3,np.NaN,2,5.6])",
"_____no_output_____"
]
],
[
[
"There is a difference, however, in the way NumPy treats aggregate calculations versus what pandas does.\n\nIn pandas, the default is to treat the missing value as 0 and do the aggregate calculation, whereas for NumPy, NaN is returned if any of the values are missing. Here is an illustration:",
"_____no_output_____"
]
],
[
[
"np.mean([1.0,np.NaN,5.9,6])",
"_____no_output_____"
],
[
"np.sum([1.0,np.NaN,5.9,6])",
"_____no_output_____"
]
],
[
[
"However, if this data is in a pandas Series, we will get the following output:",
"_____no_output_____"
]
],
[
[
"pd.Series([1.0,np.NaN,5.9,6]).sum()",
"_____no_output_____"
],
[
"pd.Series([1.0,np.NaN,5.9,6]).mean()",
"_____no_output_____"
]
],
[
[
"It is important to be aware of this difference in behavior between pandas and NumPy. However, if we wish to get NumPy to behave the same way as pandas, we can use the np.nanmean and np.nansum functions, which are illustrated as follows:",
"_____no_output_____"
]
],
[
[
"np.nanmean([1.0,np.NaN,5.9,6])",
"_____no_output_____"
],
[
"np.nansum([1.0,np.NaN,5.9,6])",
"_____no_output_____"
]
],
[
[
"## Handling Missing Values\nThere are various ways to handle missing values, which are as follows:\n\n__ 1. By using the ```fillna()``` function to fill in the NA values:__",
"_____no_output_____"
]
],
[
[
"socialTradingVolTSCal",
"_____no_output_____"
],
[
"socialTradingVolTSCal.fillna(100)",
"_____no_output_____"
]
],
[
[
"We can also fill forward or backward values using the ```ffill()``` or ```bfill()``` arguments:",
"_____no_output_____"
]
],
[
[
"socialTradingVolTSCal.fillna(method='ffill')",
"_____no_output_____"
],
[
"socialTradingVolTSCal.fillna(method='bfill')",
"_____no_output_____"
]
],
[
[
"__2. By using the ```dropna()``` function to drop/delete rows and columns with missing values.__",
"_____no_output_____"
]
],
[
[
"socialTradingVolTSCal.dropna()",
"_____no_output_____"
]
],
[
[
"__3. We can also interpolate and fill in the missing values by using the ```interpolate()``` function__",
"_____no_output_____"
]
],
[
[
"pd.set_option('display.precision',4)\nsocialTradingVolTSCal.interpolate()",
"_____no_output_____"
]
],
[
[
"The ```interpolate()``` function also takes an argument—method that denotes the method. These methods include linear, quadratic, cubic spline, and so on.",
"_____no_output_____"
],
[
"## Plotting using matplotlib\nThe matplotlib api is imported using the standard convention, as shown in the following command: ```import matplotlib.pyplot as plt```\n\nSeries and DataFrame have a plot method, which is simply a wrapper around ```plt.plot``` . Here, we will examine how we can do a simple plot of a sine and cosine function. Suppose we wished to plot the following functions over the interval pi to pi:\n\n$$\nf(x) = \\cos(x) + \\sin(x) \\\\\ng(x) = \\cos(x) - \\sin(x)\n$$",
"_____no_output_____"
]
],
[
[
"X = np.linspace(-np.pi, np.pi, 256, endpoint=True)\nf,g = np.cos(X)+np.sin(X), np.sin(X)-np.cos(X)\nf_ser=pd.Series(f)\ng_ser=pd.Series(g)",
"_____no_output_____"
],
[
"plotDF=pd.concat([f_ser,g_ser],axis=1)\nplotDF.index=X\nplotDF.columns=['sin(x)+cos(x)','sin(x)-cos(x)']\nplotDF.head()",
"_____no_output_____"
],
[
"plotDF.columns=['f(x)','g(x)']\nplotDF.plot(title='Plot of f(x)=sin(x)+cos(x), \\n g(x)=sinx(x)-cos(x)')\nplt.show()",
"_____no_output_____"
],
[
"plotDF.plot(subplots=True, figsize=(6,6))\nplt.show()",
"_____no_output_____"
]
],
[
[
"There is a lot more to using the plotting functionality of matplotlib within pandas. For more information, take a look at the [documentation](http://pandas.pydata.org/pandas-docs/dev/visualization.html)\n\n### Summary \nTo summarize, we have discussed how to handle missing data values and manipulate dates in pandas. We also took a brief detour to investigate the plotting functionality in pandas using matplotlib .",
"_____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"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4aabf2bcfec5d069e94d1346755f81cefe8ff730
| 100,468 |
ipynb
|
Jupyter Notebook
|
pytorch_ipynb/basic-ml/perceptron.ipynb
|
Theigrams/deeplearning-models
|
260519f71bde3a34fb7f0b7bd96b02e8a6b3cd45
|
[
"MIT"
] | null | null | null |
pytorch_ipynb/basic-ml/perceptron.ipynb
|
Theigrams/deeplearning-models
|
260519f71bde3a34fb7f0b7bd96b02e8a6b3cd45
|
[
"MIT"
] | null | null | null |
pytorch_ipynb/basic-ml/perceptron.ipynb
|
Theigrams/deeplearning-models
|
260519f71bde3a34fb7f0b7bd96b02e8a6b3cd45
|
[
"MIT"
] | null | null | null | 320.984026 | 33,403 | 0.690349 |
[
[
[
"# Model Zoo -- Rosenblatt Perceptron",
"_____no_output_____"
],
[
"Implementation of the classic Perceptron by Frank Rosenblatt for binary classification (here: 0/1 class labels).",
"_____no_output_____"
],
[
"## Imports",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport torch\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## Preparing a toy dataset",
"_____no_output_____"
]
],
[
[
"##########################\n### DATASET\n##########################\n\ndata = np.genfromtxt('../data/perceptron_toydata.txt', delimiter='\\t')\nX, y = data[:, :2], data[:, 2]\ny = y.astype(np.int)\n\nprint('Class label counts:', np.bincount(y))\nprint('X.shape:', X.shape)\nprint('y.shape:', y.shape)\n\n# Shuffling & train/test split\nshuffle_idx = np.arange(y.shape[0])\nshuffle_rng = np.random.RandomState(123)\nshuffle_rng.shuffle(shuffle_idx)\nX, y = X[shuffle_idx], y[shuffle_idx]\n\nX_train, X_test = X[shuffle_idx[:70]], X[shuffle_idx[70:]]\ny_train, y_test = y[shuffle_idx[:70]], y[shuffle_idx[70:]]\n\n# Normalize (mean zero, unit variance)\nmu, sigma = X_train.mean(axis=0), X_train.std(axis=0)\nX_train = (X_train - mu) / sigma\nX_test = (X_test - mu) / sigma",
"Class label counts: [50 50]\nX.shape: (100, 2)\ny.shape: (100,)\n"
],
[
"plt.scatter(X_train[y_train==0, 0], X_train[y_train==0, 1], label='class 0', marker='o')\nplt.scatter(X_train[y_train==1, 0], X_train[y_train==1, 1], label='class 1', marker='s')\nplt.xlabel('feature 1')\nplt.ylabel('feature 2')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Defining the Perceptron model",
"_____no_output_____"
]
],
[
[
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef custom_where(cond, x_1, x_2):\n # cond = torch.tensor(cond,dtype=torch.float32)\n cond=cond.float()\n return (cond * x_1) + ((1-cond) * x_2)\n\n\nclass Perceptron():\n def __init__(self, num_features):\n self.num_features = num_features\n self.weights = torch.zeros(num_features, 1, \n dtype=torch.float32, device=device)\n self.bias = torch.zeros(1, dtype=torch.float32, device=device)\n\n def forward(self, x):\n linear = torch.add(torch.mm(x, self.weights), self.bias)\n predictions = custom_where(linear > 0., 1, 0)\n return predictions\n \n def backward(self, x, y): \n predictions = self.forward(x)\n errors = y - predictions\n return errors\n \n def train(self, x, y, epochs):\n for e in range(epochs):\n \n for i in range(y.size()[0]):\n # use view because backward expects a matrix (i.e., 2D tensor)\n errors = self.backward(x[i].view(1, self.num_features), y[i]).view(-1)\n self.weights += (errors * x[i]).view(self.num_features, 1)\n self.bias += errors\n \n def evaluate(self, x, y):\n predictions = self.forward(x).view(-1)\n accuracy = torch.sum(predictions == y).float() / y.size()[0]\n return accuracy",
"_____no_output_____"
]
],
[
[
"## Training the Perceptron",
"_____no_output_____"
]
],
[
[
"ppn = Perceptron(num_features=2)\n\nX_train_tensor = torch.tensor(X_train, dtype=torch.float32, device=device)\ny_train_tensor = torch.tensor(y_train, dtype=torch.float32, device=device)\n\nppn.train(X_train_tensor, y_train_tensor, epochs=5)\n\nprint('Model parameters:')\nprint(' Weights: %s' % ppn.weights)\nprint(' Bias: %s' % ppn.bias)",
"Model parameters:\n Weights: tensor([[1.2734],\n [1.3464]], device='cuda:0')\n Bias: tensor([-1.], device='cuda:0')\n"
]
],
[
[
"## Evaluating the model",
"_____no_output_____"
]
],
[
[
"X_test_tensor = torch.tensor(X_test, dtype=torch.float32, device=device)\ny_test_tensor = torch.tensor(y_test, dtype=torch.float32, device=device)\n\ntest_acc = ppn.evaluate(X_test_tensor, y_test_tensor)\nprint('Test set accuracy: %.2f%%' % (test_acc*100))",
"Test set accuracy: 93.33%\n"
],
[
"##########################\n### 2D Decision Boundary\n##########################\n\nw, b = ppn.weights, ppn.bias\n\nx_min = -2\ny_min = ( (-(w[0] * x_min) - b[0]) \n / w[1] )\n\nx_max = 2\ny_max = ( (-(w[0] * x_max) - b[0]) \n / w[1] )\n\n\nfig, ax = plt.subplots(1, 2, sharex=True, figsize=(7, 3))\n\nax[0].plot([x_min, x_max], [y_min, y_max])\nax[1].plot([x_min, x_max], [y_min, y_max])\n\nax[0].scatter(X_train[y_train==0, 0], X_train[y_train==0, 1], label='class 0', marker='o')\nax[0].scatter(X_train[y_train==1, 0], X_train[y_train==1, 1], label='class 1', marker='s')\n\nax[1].scatter(X_test[y_test==0, 0], X_test[y_test==0, 1], label='class 0', marker='o')\nax[1].scatter(X_test[y_test==1, 0], X_test[y_test==1, 1], label='class 1', marker='s')\n\nax[1].legend(loc='upper left')\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aabf7e5f29aa43b6b7df9cd777d2c9333267d97
| 8,259 |
ipynb
|
Jupyter Notebook
|
ipynb/08/where_and_argmin.ipynb
|
matthew-brett/cfd-uob
|
cc9233a26457f5e688ed6297ebbf410786cfd806
|
[
"CC-BY-4.0"
] | 1 |
2019-09-30T13:31:41.000Z
|
2019-09-30T13:31:41.000Z
|
ipynb/08/where_and_argmin.ipynb
|
matthew-brett/cfd-uob
|
cc9233a26457f5e688ed6297ebbf410786cfd806
|
[
"CC-BY-4.0"
] | 1 |
2020-08-14T11:16:11.000Z
|
2020-08-14T11:16:11.000Z
|
ipynb/08/where_and_argmin.ipynb
|
matthew-brett/cfd-uob
|
cc9233a26457f5e688ed6297ebbf410786cfd806
|
[
"CC-BY-4.0"
] | 5 |
2019-12-03T00:54:39.000Z
|
2020-09-21T14:30:43.000Z
| 20.908861 | 191 | 0.538322 |
[
[
[
"We sometimes want to know where a value is in an array.",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
]
],
[
[
"By \"where\" we mean, which element contains a particular value.\n\nHere is an array.",
"_____no_output_____"
]
],
[
[
"arr = np.array([2, 99, -1, 4, 99])\narr",
"_____no_output_____"
]
],
[
[
"As you know, we can get element using their *index* in the array. In\nPython, array indices start at zero.\n\nHere's the value at index (position) 0:",
"_____no_output_____"
]
],
[
[
"arr[0]",
"_____no_output_____"
]
],
[
[
"We might also be interested to find which positions hold particular values.\n\nIn our array above, by reading, and counting positions, we can see\nthat the values of 99 are in positions 1 and 4. We can ask for these\nelements by passing a list or an array between the square brackets, to\nindex the array:",
"_____no_output_____"
]
],
[
[
"positions_with_99 = np.array([1, 4])\narr[positions_with_99]",
"_____no_output_____"
]
],
[
[
"Of course, we are already used to finding and then selecting elements according to various conditions, using *Boolean vectors*.\n\nHere we identify the elements that contain 99. There is a `True` at the position where the array contains 99, and `False` otherwise.",
"_____no_output_____"
]
],
[
[
"contains_99 = arr == 99\ncontains_99",
"_____no_output_____"
]
],
[
[
"We can then get the 99 values with:",
"_____no_output_____"
]
],
[
[
"arr[contains_99]",
"_____no_output_____"
]
],
[
[
"## Enter \"where\"\n\nSometimes we really do need to know the index of the values that meet a certain condition.\n\nIn that case, you can use the Numpy [where\nfunction](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html).\n`where` finds the index positions of the `True` values in Boolean\nvectors.",
"_____no_output_____"
]
],
[
[
"indices = np.where(arr == 99)\nindices",
"_____no_output_____"
]
],
[
[
"We can use the returned `indices` to index into the array, using square brackets.",
"_____no_output_____"
]
],
[
[
"arr[indices]",
"_____no_output_____"
]
],
[
[
"This also works in two or more dimensions. Here is a two-dimensional array, with some values of 99.",
"_____no_output_____"
]
],
[
[
"arr2d = np.array([[4, 99, 3], [8, 8, 99]])\narr2d",
"_____no_output_____"
]
],
[
[
"`where` now returns two index arrays, one for the rows, and one for the columns.",
"_____no_output_____"
]
],
[
[
"indices2d = np.where(arr2d == 99)\nindices2d",
"_____no_output_____"
]
],
[
[
"Just as for the one-dimensional case, we can use the returned indices to index into the array, and get the elements.",
"_____no_output_____"
]
],
[
[
"arr2d[indices2d]",
"_____no_output_____"
]
],
[
[
"## Where summary\n\nNumpy `where` returns the indices of `True` values in a Boolean array/\n\nYou can use these indices to index into an array, and get the matching elements.\n\n## Argmin\n\nNumpy has various *argmin* functions that are a shortcut for using `where`, for particular cases.\n\nA typical case is where you want to know the index (position) of the minimum value in an array.\n\nHere is our array:",
"_____no_output_____"
]
],
[
[
"arr",
"_____no_output_____"
]
],
[
[
"We can get the minimum value with Numpy `min`:",
"_____no_output_____"
]
],
[
[
"np.min(arr)",
"_____no_output_____"
]
],
[
[
"Sometimes we want to know the *index position* of the minimum value. Numpy `argmin` returns the index of the minimum value:",
"_____no_output_____"
]
],
[
[
"min_pos = np.argmin(arr)\nmin_pos",
"_____no_output_____"
]
],
[
[
"Therefore, we can get the minimum value again with:",
"_____no_output_____"
]
],
[
[
"arr[min_pos]",
"_____no_output_____"
]
],
[
[
"There is a matching `argmax` function that returns the position of the maximum value:",
"_____no_output_____"
]
],
[
[
"np.max(arr)",
"_____no_output_____"
],
[
"max_pos = np.argmax(arr)\nmax_pos",
"_____no_output_____"
],
[
"arr[max_pos]",
"_____no_output_____"
]
],
[
[
"We could also have found the position of the minimum value above, using `np.min` and `where`:",
"_____no_output_____"
]
],
[
[
"min_value = np.min(arr)\nmin_indices = np.where(arr == min_value)\narr[min_indices]",
"_____no_output_____"
]
],
[
[
"The `argmin` and `argmax` functions are not quite the same, in that they only return the *first* position of the minimum or maximum, if there are multiple values with the same value.\n\nCompare:",
"_____no_output_____"
]
],
[
[
"np.argmax(arr)",
"_____no_output_____"
]
],
[
[
"to",
"_____no_output_____"
]
],
[
[
"max_value = np.max(arr)\nnp.where(arr == max_value)",
"_____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",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aabfcf0bc135a88a9a97b9442bc0432328f7617
| 55,451 |
ipynb
|
Jupyter Notebook
|
elmo-chinese.ipynb
|
RundongChou/elmo-chinese-oversimplified
|
0064171885db2dda069964988cd5c95a9d6cc9b4
|
[
"Apache-2.0"
] | 7 |
2019-07-27T16:49:37.000Z
|
2021-05-14T12:42:42.000Z
|
elmo-chinese.ipynb
|
RundongChou/elmo-chinese-oversimplified
|
0064171885db2dda069964988cd5c95a9d6cc9b4
|
[
"Apache-2.0"
] | null | null | null |
elmo-chinese.ipynb
|
RundongChou/elmo-chinese-oversimplified
|
0064171885db2dda069964988cd5c95a9d6cc9b4
|
[
"Apache-2.0"
] | 4 |
2019-07-31T08:21:34.000Z
|
2022-02-14T08:15:59.000Z
| 39.438834 | 293 | 0.477394 |
[
[
[
"# from utils import *\nimport tensorflow as tf\nimport os\nimport sklearn.datasets\nimport numpy as np\nimport re\nimport collections\nimport random\nfrom sklearn import metrics\nimport jieba",
"_____no_output_____"
],
[
"# 写入停用词\nwith open(r'stopwords.txt','r',encoding='utf-8') as f:\n english_stopwords = f.read().split('\\n')",
"_____no_output_____"
],
[
"def separate_dataset(trainset, ratio = 0.5):\n datastring = []\n datatarget = []\n for i in range(len(trainset.data)):\n # 提取每一条文本数据,并过滤None值行文本;\n data_ = trainset.data[i].split('\\n')\n data_ = list(filter(None, data_))\n # 抽取len(data_) * ratio个样本,并打乱某类样本顺序;\n data_ = random.sample(data_, int(len(data_) * ratio))\n # 去除停用词\n for n in range(len(data_)):\n data_[n] = clearstring(data_[n])\n # 提取所有的词\n datastring += data_\n # 为每一个样本补上标签\n for n in range(len(data_)):\n datatarget.append(trainset.target[i])\n return datastring, datatarget\n\ndef clearstring(string):\n # 清洗样本,并去停用词\n # 去除非中文字符\n string = re.sub(r'^[\\u4e00-\\u9fa5a-zA-Z0-9]', '', string)\n string = list(jieba.cut(string, cut_all=False))\n string = filter(None, string)\n string = [y.strip() for y in string if y.strip() not in english_stopwords]\n string = ' '.join(string)\n return string.lower()\n\n\ndef str_idx(corpus, dic, maxlen, UNK = 3):\n # 词典索引\n X = np.zeros((len(corpus), maxlen))\n for i in range(len(corpus)):\n for no, k in enumerate(corpus[i].split()[:maxlen][::-1]):\n X[i, -1 - no] = dic.get(k, UNK)\n return X\n",
"_____no_output_____"
],
[
"trainset = sklearn.datasets.load_files(container_path = 'dataset', encoding = 'UTF-8')\ntrainset.data, trainset.target = separate_dataset(trainset,1.0)\nprint(trainset.target_names)\nprint(len(trainset.data))\nprint(len(trainset.target))",
"['.ipynb_checkpoints', 'Chinese']\n14342\n14342\n"
],
[
"import collections\n\ndef build_dataset(words, n_words, atleast=1):\n # 四种填充词\n count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n counter = collections.Counter(words).most_common(n_words)\n # 过滤那些只有一个字的字符\n counter = [i for i in counter if i[1] >= atleast]\n count.extend(counter)\n dictionary = dict()\n # 构建词的索引\n for word, _ in count:\n dictionary[word] = len(dictionary)\n data = list()\n for word in words:\n # 如果字典中没有出现的词,用unk表示\n index = dictionary.get(word, 3)\n data.append(index)\n # 翻转字典\n reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n return data, dictionary, reversed_dictionary",
"_____no_output_____"
],
[
"split = (' '.join(trainset.data)).split()\n# 去重后的所有单词集合,组成词典\nvocabulary_size = len(list(set(split)))\n# data为所有词的词索引,词典,反向词典\ndata, dictionary, rev_dictionary = build_dataset(split, vocabulary_size)",
"_____no_output_____"
],
[
"len(dictionary)",
"_____no_output_____"
],
[
"def build_char_dataset(words):\n # 四种填充词\n count = []\n dictionary = dict()\n # 构建词的索引\n for word in words:\n dictionary[word] = len(dictionary)\n data = list()\n for word in words:\n # 如果字典中没有出现的词,用unk表示\n index = dictionary.get(word, 3)\n data.append(index)\n # 翻转字典\n reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n return data, dictionary, reversed_dictionary",
"_____no_output_____"
],
[
"# 构建所有中文汉字的字典,3912个汉字\nchar_split = list(set(list(''.join(trainset.data))))\nlength = len(char_split)\nchar_data, char_dictionary, char_rev_dictionary = build_char_dataset(char_split)",
"_____no_output_____"
],
[
"# 给中文字符编码\nclass Vocabulary:\n def __init__(self, dictionary, rev_dictionary):\n self._dictionary = dictionary\n self._rev_dictionary = rev_dictionary\n \n # 起始符\n @property\n def start_string(self):\n return self._dictionary['GO']\n \n # 结束符\n @property\n def end_string(self):\n return self._dictionary['EOS']\n \n # 未知单词\n @property\n def unk(self):\n return self._dictionary['UNK']\n\n @property\n def size(self):\n return len(self._dictionary)\n \n # 查询词语的数值索引\n def word_to_id(self, word):\n return self._dictionary.get(word, self.unk)\n \n # 通过索引反查词语\n def id_to_word(self, cur_id):\n return self._rev_dictionary.get(cur_id, self._rev_dictionary[3])\n \n # 将数字索引解码成字符串并拼接起来\n def decode(self, cur_ids):\n return ' '.join([self.id_to_word(cur_id) for cur_id in cur_ids])\n \n # 将字符串编码成数字索引\n def encode(self, sentence, reverse = False, split = True):\n\n if split:\n sentence = sentence.split()\n # 将文本转化为数字索引\n word_ids = [self.word_to_id(cur_word) for cur_word in sentence]\n \n # 为所有的文本加上起始符和结束符,双向编码都支持\n if reverse:\n return np.array(\n [self.end_string] + word_ids + [self.start_string],\n dtype = np.int32,\n )\n else:\n return np.array(\n [self.start_string] + word_ids + [self.end_string],\n dtype = np.int32,\n )\n",
"_____no_output_____"
],
[
"# 英文,数字,字符用自制转码,中文字符,从0开始进行编码,考虑到中文短语的长度一般不超过8,故可取max_length=10\nclass UnicodeCharsVocabulary(Vocabulary):\n def __init__(self, dictionary, rev_dictionary,char_dictionary, char_rev_dictionary, max_word_length, **kwargs):\n super(UnicodeCharsVocabulary, self).__init__(\n dictionary, rev_dictionary, **kwargs\n )\n # 最大单词长度\n self._max_word_length = max_word_length\n self._char_dictionary = char_dictionary\n self._char_rev_dictionary = char_rev_dictionary\n self.bos_char = 3912\n self.eos_char = 3913\n self.bow_char = 3914\n self.eow_char = 3915\n self.pad_char = 3916\n self.unk_char = 3917\n # 单词的数量\n num_words = self.size\n \n # 构建字符级别的词典表,[num_words,max_word_length]\n self._word_char_ids = np.zeros(\n [num_words, max_word_length], dtype = np.int32\n )\n \n # 构建bos和eos的mask,初始化一个_max_word_length的张量,全部用3916填充,第一个字符位用3914,第三个字符位用3915,\n # 第二个字符作为输入进行传入\n def _make_bos_eos(c):\n r = np.zeros([self._max_word_length], dtype = np.int32)\n r[:] = self.pad_char\n r[0] = self.bow_char\n r[1] = c\n r[2] = self.eow_char\n return r\n \n # 张量化\n self.bos_chars = _make_bos_eos(self.bos_char)\n self.eos_chars = _make_bos_eos(self.eos_char)\n \n # 遍历字典中的每个单词,并将每个单词都进行字符级别的编码\n for i, word in enumerate(self._dictionary.keys()):\n self._word_char_ids[i] = self._convert_word_to_char_ids(word)\n # 对于起始符GO和结束符EOS进行编码\n self._word_char_ids[self.start_string] = self.bos_chars\n self._word_char_ids[self.end_string] = self.eos_chars\n\n @property\n def word_char_ids(self):\n return self._word_char_ids\n\n @property\n def max_word_length(self):\n return self._max_word_length\n \n # 将单词转化为字符级别的索引\n def _convert_word_to_char_ids(self, word):\n # 对输入的单词进行张量化\n code = np.zeros([self.max_word_length], dtype = np.int32)\n code[:] = self.pad_char\n # 截取maxlen-2个字符,并将所有字符转化为unicode字符集\n\n word_encoded = [self._char_dictionary.get(item,self.unk_char) for item in list(word)][:(self.max_word_length - 2)]\n # 第一个字符位为3914\n code[0] = self.bow_char\n # 遍历单词的每一个字符,k从1开始\n for k, chr_id in enumerate(word_encoded, start = 1):\n code[k] = chr_id\n # 在单词的末尾补充一个单词末尾结束符3915\n code[len(word_encoded) + 1] = self.eow_char\n return code\n \n # 将单词转化为自定义字符编码\n def word_to_char_ids(self, word):\n if word in self._dictionary:\n return self._word_char_ids[self._dictionary[word]]\n else:\n return self._convert_word_to_char_ids(word)\n # 将句子转化为自定义字符编码矩阵\n def encode_chars(self, sentence, reverse = False, split = True):\n if split:\n sentence = sentence.split()\n chars_ids = [self.word_to_char_ids(cur_word) for cur_word in sentence]\n\n if reverse:\n return np.vstack([self.eos_chars] + chars_ids + [self.bos_chars])\n else:\n return np.vstack([self.bos_chars] + chars_ids + [self.eos_chars])\n\n\ndef _get_batch(generator, batch_size, num_steps, max_word_length):\n # generator: 生成器\n # batch_size: 每个批次的字符串的数量\n # num_steps: 窗口大小\n # max_word_length: 最大单词长度,一般设置为50\n # 初始化batch_size个字符串\n cur_stream = [None] * batch_size\n\n no_more_data = False\n while True:\n # 初始化单词矩阵输入0值化[batch_size,num_steps]\n inputs = np.zeros([batch_size, num_steps], np.int32)\n # 初始化字符级矩阵,输入0值化\n if max_word_length is not None:\n char_inputs = np.zeros(\n [batch_size, num_steps, max_word_length], np.int32\n )\n else:\n char_inputs = None\n # 初始化单词矩阵输出0值化[batch_size,num_steps]\n targets = np.zeros([batch_size, num_steps], np.int32)\n for i in range(batch_size):\n cur_pos = 0\n while cur_pos < num_steps:\n if cur_stream[i] is None or len(cur_stream[i][0]) <= 1:\n try:\n # 每一步都获取词索引,字符集编码器\n cur_stream[i] = list(next(generator))\n except StopIteration:\n no_more_data = True\n break\n # how_many 取当前总num_steps与文本词向量数量的较小值,累加\n how_many = min(len(cur_stream[i][0]) - 1, num_steps - cur_pos)\n next_pos = cur_pos + how_many\n \n # 赋值输入对应的词索引范围和字符级别索引范围\n inputs[i, cur_pos:next_pos] = cur_stream[i][0][:how_many]\n if max_word_length is not None:\n char_inputs[i, cur_pos:next_pos] = cur_stream[i][1][\n :how_many\n ]\n # targets 我们的目标是预测下一个词来优化emlo,所以我们以向右滑动的1个词作为target,作为预测对象\n targets[i, cur_pos:next_pos] = cur_stream[i][0][\n 1 : how_many + 1\n ]\n\n cur_pos = next_pos\n \n # 处理完之前那段,重新处理下一段,每段的长度取决于howmany,这里既是window的宽度。\n cur_stream[i][0] = cur_stream[i][0][how_many:]\n if max_word_length is not None:\n cur_stream[i][1] = cur_stream[i][1][how_many:]\n\n if no_more_data:\n break\n\n X = {\n 'token_ids': inputs,\n 'tokens_characters': char_inputs,\n 'next_token_id': targets,\n }\n\n yield X\n\n\nclass LMDataset:\n def __init__(self, string, vocab, reverse = False):\n self._vocab = vocab\n self._string = string\n self._reverse = reverse\n self._use_char_inputs = hasattr(vocab, 'encode_chars')\n self._i = 0\n # 总文本的数量\n self._nids = len(self._string)\n\n def _load_string(self, string):\n if self._reverse:\n string = string.split()\n string.reverse()\n string = ' '.join(string)\n \n # 将一段文本解析成词索引,会在起始和末尾增加一个标志位\n ids = self._vocab.encode(string, self._reverse)\n \n # 将一段文本解析成字符级编码\n if self._use_char_inputs:\n chars_ids = self._vocab.encode_chars(string, self._reverse)\n else:\n chars_ids = None\n # 返回由词索引和字符集编码的元组\n return list(zip([ids], [chars_ids]))[0]\n \n # 生成器,循环生成每个样本的词索引和字符编码\n def get_sentence(self):\n while True:\n if self._i == self._nids:\n self._i = 0\n ret = self._load_string(self._string[self._i])\n self._i += 1\n yield ret\n\n @property\n def max_word_length(self):\n if self._use_char_inputs:\n return self._vocab.max_word_length\n else:\n return None\n # batch生成器,每次只拿batch_size个数据,要多少数据就即时处理多少数据\n def iter_batches(self, batch_size, num_steps):\n for X in _get_batch(\n self.get_sentence(), batch_size, num_steps, self.max_word_length\n ):\n yield X\n\n @property\n def vocab(self):\n return self._vocab\n\n# 双向编码\nclass BidirectionalLMDataset:\n def __init__(self, string, vocab):\n # 正向编码和反向编码\n self._data_forward = LMDataset(string, vocab, reverse = False)\n self._data_reverse = LMDataset(string, vocab, reverse = True)\n\n def iter_batches(self, batch_size, num_steps):\n max_word_length = self._data_forward.max_word_length\n\n for X, Xr in zip(\n _get_batch(\n self._data_forward.get_sentence(),\n batch_size,\n num_steps,\n max_word_length,\n ),\n _get_batch(\n self._data_reverse.get_sentence(),\n batch_size,\n num_steps,\n max_word_length,\n ),\n ):\n # 拼接成一个6个item的字典,前三个为正向,后三个为反向\n for k, v in Xr.items():\n X[k + '_reverse'] = v\n\n yield X",
"_____no_output_____"
],
[
"# maxlens=10,很明显没有超过8的词语,其中两个用来做填充符\nuni = UnicodeCharsVocabulary(dictionary, rev_dictionary,char_dictionary,char_rev_dictionary, 10)",
"_____no_output_____"
],
[
"bi = BidirectionalLMDataset(trainset.data, uni)",
"_____no_output_____"
],
[
"# 每次只输入16个样本数据\nbatch_size = 16\n# 训练用的词典大小\nn_train_tokens = len(dictionary)\n# 语言模型参数配置项\noptions = {\n # 开启双向编码机制\n 'bidirectional': True,\n # 字符级别的CNN,字符级别词嵌入128维,一共配置7种类型的滤波器,每个词最大长度为50,编码的有效数量为3918个,设置两条高速通道\n 'char_cnn': {\n 'activation': 'relu',\n 'embedding': {'dim': 128},\n 'filters': [\n [1, 32],\n [2, 32],\n [3, 64],\n [4, 128],\n [5, 256],\n [6, 512],\n [7, 1024],\n ],\n 'max_characters_per_token': 10,\n 'n_characters': 3918,\n 'n_highway': 2,\n },\n # 随机失活率设置为0.1\n 'dropout': 0.1,\n # lstm单元,设置三层,嵌入维度为512维\n 'lstm': {\n # 截断值\n 'cell_clip': 3,\n 'dim': 512,\n 'n_layers': 2,\n 'projection_dim': 256,\n # 裁剪到[-3,3]之间\n 'proj_clip': 3,\n 'use_skip_connections': True,\n },\n # 一共迭代100轮\n 'n_epochs': 100,\n # 训练词典的大小\n 'n_train_tokens': n_train_tokens,\n # 每个batch的大小\n 'batch_size': batch_size,\n # 所有词的数量\n 'n_tokens_vocab': uni.size,\n # 推断区间为20\n 'unroll_steps': 20,\n 'n_negative_samples_batch': 0.001,\n 'sample_softmax': True,\n 'share_embedding_softmax': False,\n}",
"_____no_output_____"
],
[
"# 构建ELMO语言模型\nclass LanguageModel:\n def __init__(self, options, is_training):\n self.options = options\n self.is_training = is_training\n self.bidirectional = options.get('bidirectional', False)\n\n self.char_inputs = 'char_cnn' in self.options\n\n self.share_embedding_softmax = options.get(\n 'share_embedding_softmax', False\n )\n if self.char_inputs and self.share_embedding_softmax:\n raise ValueError(\n 'Sharing softmax and embedding weights requires ' 'word input'\n )\n\n self.sample_softmax = options.get('sample_softmax', False)\n # 建立模型\n self._build()\n # 配置学习率\n lr = options.get('learning_rate', 0.2)\n # 配置优化器\n self.optimizer = tf.train.AdagradOptimizer(\n learning_rate = lr, initial_accumulator_value = 1.0\n ).minimize(self.total_loss)\n\n def _build_word_embeddings(self):\n # 建立词嵌入\n # 加载所有的词\n n_tokens_vocab = self.options['n_tokens_vocab']\n batch_size = self.options['batch_size']\n # 上下文推断的窗口大小,这里关联20个单词\n unroll_steps = self.options['unroll_steps']\n # 词嵌入维度128\n projection_dim = self.options['lstm']['projection_dim']\n # 词索引\n self.token_ids = tf.placeholder(\n tf.int32, shape = (None, unroll_steps), name = 'token_ids'\n )\n self.batch_size = tf.shape(self.token_ids)[0]\n with tf.device('/cpu:0'):\n \n # 对单词进行256维的单词编码,初始化数据服从(-1,1)的正态分布\n self.embedding_weights = tf.get_variable(\n 'embedding',\n [n_tokens_vocab, projection_dim],\n dtype = tf.float32,\n initializer = tf.random_uniform_initializer(-1.0, 1.0),\n )\n # 20个词对应的词嵌入\n self.embedding = tf.nn.embedding_lookup(\n self.embedding_weights, self.token_ids\n )\n \n # 启用双向编码机制\n if self.bidirectional:\n self.token_ids_reverse = tf.placeholder(\n tf.int32,\n shape = (None, unroll_steps),\n name = 'token_ids_reverse',\n )\n with tf.device('/cpu:0'):\n self.embedding_reverse = tf.nn.embedding_lookup(\n self.embedding_weights, self.token_ids_reverse\n )\n\n def _build_word_char_embeddings(self):\n\n batch_size = self.options['batch_size']\n unroll_steps = self.options['unroll_steps']\n projection_dim = self.options['lstm']['projection_dim']\n\n cnn_options = self.options['char_cnn']\n filters = cnn_options['filters']\n # 求和所有的滤波器数量\n n_filters = sum(f[1] for f in filters)\n # 最大单词字符长度\n max_chars = cnn_options['max_characters_per_token']\n # 字符级别嵌入维度,128\n char_embed_dim = cnn_options['embedding']['dim']\n # 所有字符的类型,一共261种\n n_chars = cnn_options['n_characters']\n \n # 配置激活函数\n if cnn_options['activation'] == 'tanh':\n activation = tf.nn.tanh\n elif cnn_options['activation'] == 'relu':\n activation = tf.nn.relu\n \n # [batch_size,unroll_steps,max_chars]\n self.tokens_characters = tf.placeholder(\n tf.int32,\n shape = (None, unroll_steps, max_chars),\n name = 'tokens_characters',\n )\n self.batch_size = tf.shape(self.tokens_characters)[0]\n with tf.device('/cpu:0'):\n # 字符级别词嵌入,嵌入维度128维\n self.embedding_weights = tf.get_variable(\n 'char_embed',\n [n_chars, char_embed_dim],\n dtype = tf.float32,\n initializer = tf.random_uniform_initializer(-1.0, 1.0),\n )\n self.char_embedding = tf.nn.embedding_lookup(\n self.embedding_weights, self.tokens_characters\n )\n\n if self.bidirectional:\n self.tokens_characters_reverse = tf.placeholder(\n tf.int32,\n shape = (None, unroll_steps, max_chars),\n name = 'tokens_characters_reverse',\n )\n self.char_embedding_reverse = tf.nn.embedding_lookup(\n self.embedding_weights, self.tokens_characters_reverse\n )\n \n # 构建卷积层网络,用于字符级别的CNN卷积\n def make_convolutions(inp, reuse):\n with tf.variable_scope('CNN', reuse = reuse) as scope:\n convolutions = []\n # 这里构建7层卷积网络\n for i, (width, num) in enumerate(filters):\n if cnn_options['activation'] == 'relu':\n w_init = tf.random_uniform_initializer(\n minval = -0.05, maxval = 0.05\n )\n elif cnn_options['activation'] == 'tanh':\n w_init = tf.random_normal_initializer(\n mean = 0.0,\n stddev = np.sqrt(1.0 / (width * char_embed_dim)),\n )\n w = tf.get_variable(\n 'W_cnn_%s' % i,\n [1, width, char_embed_dim, num],\n initializer = w_init,\n dtype = tf.float32,\n )\n b = tf.get_variable(\n 'b_cnn_%s' % i,\n [num],\n dtype = tf.float32,\n initializer = tf.constant_initializer(0.0),\n )\n # 卷积,uroll_nums,characters_nums采用1*1,1*2,...,1*7的卷积核,采用valid卷积策略;\n # width上,(uroll_nums-1/1)+1=uroll_nums\n # height上,(characters_nums-7/1)+1,捕捉词与词之间的相关性\n conv = (\n tf.nn.conv2d(\n inp, w, strides = [1, 1, 1, 1], padding = 'VALID'\n )\n + b\n )\n # 最大池化,每个词的字符编码\n conv = tf.nn.max_pool(\n conv,\n [1, 1, max_chars - width + 1, 1],\n [1, 1, 1, 1],\n 'VALID',\n )\n conv = activation(conv)\n # 删除第三维,输入为[batch_size,uroll_nums,1,nums]\n # 输出为[batch_size,uroll_nums,nums]\n conv = tf.squeeze(conv, squeeze_dims = [2])\n \n # 收集每个卷积层,并进行拼接\n convolutions.append(conv)\n\n return tf.concat(convolutions, 2)\n\n reuse = tf.get_variable_scope().reuse\n # inp [batch_size,uroll_nums,characters_nums,embedding_size]\n embedding = make_convolutions(self.char_embedding, reuse)\n # [batch_size,20,2048] #经过验证无误\n # 增加一维[1,batch_size,uroll_nums,nums++]\n self.token_embedding_layers = [embedding]\n if self.bidirectional:\n embedding_reverse = make_convolutions(\n self.char_embedding_reverse, True\n )\n # 高速网络的数量\n n_highway = cnn_options.get('n_highway')\n use_highway = n_highway is not None and n_highway > 0\n # use_proj 为True\n use_proj = n_filters != projection_dim\n \n # 本来已经第三维是2048维了,这么做的原因是?\n if use_highway or use_proj:\n embedding = tf.reshape(embedding, [-1, n_filters])\n if self.bidirectional:\n embedding_reverse = tf.reshape(\n embedding_reverse, [-1, n_filters]\n )\n\n if use_proj:\n # 使用投影,将滤波器再投影到一个projection_dim维的向量空间内\n assert n_filters > projection_dim\n with tf.variable_scope('CNN_proj') as scope:\n W_proj_cnn = tf.get_variable(\n 'W_proj',\n [n_filters, projection_dim],\n initializer = tf.random_normal_initializer(\n mean = 0.0, stddev = np.sqrt(1.0 / n_filters)\n ),\n dtype = tf.float32,\n )\n b_proj_cnn = tf.get_variable(\n 'b_proj',\n [projection_dim],\n initializer = tf.constant_initializer(0.0),\n dtype = tf.float32,\n )\n\n def high(x, ww_carry, bb_carry, ww_tr, bb_tr):\n carry_gate = tf.nn.sigmoid(tf.matmul(x, ww_carry) + bb_carry)\n transform_gate = tf.nn.relu(tf.matmul(x, ww_tr) + bb_tr)\n return carry_gate * transform_gate + (1.0 - carry_gate) * x\n\n if use_highway:\n # 高速网络的维度为2048维\n highway_dim = n_filters\n\n for i in range(n_highway):\n with tf.variable_scope('CNN_high_%s' % i) as scope:\n W_carry = tf.get_variable(\n 'W_carry',\n [highway_dim, highway_dim],\n initializer = tf.random_normal_initializer(\n mean = 0.0, stddev = np.sqrt(1.0 / highway_dim)\n ),\n dtype = tf.float32,\n )\n b_carry = tf.get_variable(\n 'b_carry',\n [highway_dim],\n initializer = tf.constant_initializer(-2.0),\n dtype = tf.float32,\n )\n W_transform = tf.get_variable(\n 'W_transform',\n [highway_dim, highway_dim],\n initializer = tf.random_normal_initializer(\n mean = 0.0, stddev = np.sqrt(1.0 / highway_dim)\n ),\n dtype = tf.float32,\n )\n b_transform = tf.get_variable(\n 'b_transform',\n [highway_dim],\n initializer = tf.constant_initializer(0.0),\n dtype = tf.float32,\n )\n\n embedding = high(\n embedding, W_carry, b_carry, W_transform, b_transform\n )\n if self.bidirectional:\n embedding_reverse = high(\n embedding_reverse,\n W_carry,\n b_carry,\n W_transform,\n b_transform,\n )\n # 扩展一层和两层经过高速网络的参数\n self.token_embedding_layers.append(\n tf.reshape(\n embedding, [self.batch_size, unroll_steps, highway_dim]\n )\n )\n \n # 经过一层线性变换[bacth_size,unroll_nums,projection_dim]\n if use_proj:\n embedding = tf.matmul(embedding, W_proj_cnn) + b_proj_cnn\n if self.bidirectional:\n embedding_reverse = (\n tf.matmul(embedding_reverse, W_proj_cnn) + b_proj_cnn\n )\n # 只经过线性变换的网络参数\n self.token_embedding_layers.append(\n tf.reshape(\n embedding, [self.batch_size, unroll_steps, projection_dim]\n )\n )\n \n # 确保矩阵尺寸相同\n if use_highway or use_proj:\n shp = [self.batch_size, unroll_steps, projection_dim]\n embedding = tf.reshape(embedding, shp)\n if self.bidirectional:\n embedding_reverse = tf.reshape(embedding_reverse, shp)\n \n # 经过线性变化的embdedding [bacth_size,unroll_nums,projection_dim]\n # self.token_embedding_layers 由四个嵌入层参数组成\n # [bacth_size,unroll_nums,nums++] 原始词嵌入\n # [bacth_size,unroll_nums,highway_dim] 经过第一层高速网络的词嵌入\n # [bacth_size,unroll_nums,highway_dim] 经过第二层高速网络的词嵌入\n # [bacth_size,unroll_nums,projection_dim] 经过低微线性投影的词嵌入\n # print(embedding)\n # print(self.token_embedding_layers)\n self.embedding = embedding\n if self.bidirectional:\n self.embedding_reverse = embedding_reverse\n \n # 构建模型\n def _build(self):\n # 所有词的数量\n n_tokens_vocab = self.options['n_tokens_vocab']\n batch_size = self.options['batch_size']\n # window长度\n unroll_steps = self.options['unroll_steps']\n \n # lstm编码长度\n lstm_dim = self.options['lstm']['dim']\n projection_dim = self.options['lstm']['projection_dim']\n # lstm的层数\n n_lstm_layers = self.options['lstm'].get('n_layers', 1)\n dropout = self.options['dropout']\n # 保有率\n keep_prob = 1.0 - dropout\n \n # 如果是字符级别的输入,则建立词,字符嵌入,否则建立词嵌入,实际上使用前者\n if self.char_inputs:\n self._build_word_char_embeddings()\n else:\n self._build_word_embeddings()\n \n # 存储lstm的状态\n self.init_lstm_state = []\n self.final_lstm_state = []\n \n # 双向\n # lstm_inputs单元为[batch_size,uroll_nums,projection_dim]双向单元\n if self.bidirectional:\n lstm_inputs = [self.embedding, self.embedding_reverse]\n else:\n lstm_inputs = [self.embedding]\n\n cell_clip = self.options['lstm'].get('cell_clip')\n proj_clip = self.options['lstm'].get('proj_clip')\n\n \n use_skip_connections = self.options['lstm'].get('use_skip_connections')\n print(lstm_inputs)\n lstm_outputs = []\n for lstm_num, lstm_input in enumerate(lstm_inputs):\n lstm_cells = []\n for i in range(n_lstm_layers):\n # 在进行LSTM编码后再接入一个num_proj的全连接层,[batch_size,projection_dim]\n # [batch_size,num_proj]\n lstm_cell = tf.nn.rnn_cell.LSTMCell(\n # 隐含层的单元数\n lstm_dim,\n num_proj = lstm_dim // 2,\n cell_clip = cell_clip,\n proj_clip = proj_clip,\n )\n\n if use_skip_connections:\n if i == 0:\n pass\n else:\n # 将上一个单元的输出,和当前输入映射到下一个单元\n lstm_cell = tf.nn.rnn_cell.ResidualWrapper(lstm_cell)\n \n # 添加随机失活层\n if self.is_training:\n lstm_cell = tf.nn.rnn_cell.DropoutWrapper(\n lstm_cell, input_keep_prob = keep_prob\n )\n\n lstm_cells.append(lstm_cell)\n \n # 构建多层LSTM\n if n_lstm_layers > 1:\n lstm_cell = tf.nn.rnn_cell.MultiRNNCell(lstm_cells)\n else:\n lstm_cell = lstm_cells[0]\n\n with tf.control_dependencies([lstm_input]):\n # 初始化状态\n self.init_lstm_state.append(\n lstm_cell.zero_state(self.batch_size, tf.float32)\n )\n if self.bidirectional:\n with tf.variable_scope('RNN_%s' % lstm_num):\n # 从最后一步开始,获取最后一步的输出,和最终的隐含状态,确保正反向LSTM单元可以拼接起来\n _lstm_output_unpacked, final_state = tf.nn.static_rnn(\n lstm_cell,\n # 将每个词对应的张量进行分离并作为LSTM的输入\n tf.unstack(lstm_input, axis = 1),\n initial_state = self.init_lstm_state[-1],\n )\n else:\n _lstm_output_unpacked, final_state = tf.nn.static_rnn(\n lstm_cell,\n tf.unstack(lstm_input, axis = 1),\n initial_state = self.init_lstm_state[-1],\n )\n self.final_lstm_state.append(final_state)\n # [batch_size,num_proj]\n# print(final_state)\n # 将一个隐含层的输出拼接起来 [batch_size,20,256]\n lstm_output_flat = tf.reshape(\n tf.stack(_lstm_output_unpacked, axis = 1), [-1, projection_dim]\n )\n print(lstm_output_flat)\n tf.add_to_collection(\n 'lstm_output_embeddings', _lstm_output_unpacked\n )\n\n lstm_outputs.append(lstm_output_flat)\n self._build_loss(lstm_outputs)\n \n # 构建损失函数\n def _build_loss(self, lstm_outputs):\n batch_size = self.options['batch_size']\n unroll_steps = self.options['unroll_steps']\n \n # 所有词的数量\n n_tokens_vocab = self.options['n_tokens_vocab']\n\n def _get_next_token_placeholders(suffix):\n name = 'next_token_id' + suffix\n id_placeholder = tf.placeholder(\n tf.int32, shape = (None, unroll_steps), name = name\n )\n return id_placeholder\n\n self.next_token_id = _get_next_token_placeholders('')\n # 每次抽取[batch_size,unroll_nums]个词\n print(self.next_token_id)\n if self.bidirectional:\n self.next_token_id_reverse = _get_next_token_placeholders(\n '_reverse'\n )\n # softmax的维度为projection_dim(256)\n softmax_dim = self.options['lstm']['projection_dim']\n # 与词嵌入的权重共享\n if self.share_embedding_softmax:\n self.softmax_W = self.embedding_weights\n\n # 初始化softmax的参数\n with tf.variable_scope('softmax'), tf.device('/cpu:0'):\n softmax_init = tf.random_normal_initializer(\n 0.0, 1.0 / np.sqrt(softmax_dim)\n )\n # softmax分布到每一个词中\n if not self.share_embedding_softmax:\n self.softmax_W = tf.get_variable(\n 'W',\n [n_tokens_vocab, softmax_dim],\n dtype = tf.float32,\n initializer = softmax_init,\n )\n self.softmax_b = tf.get_variable(\n 'b',\n [n_tokens_vocab],\n dtype = tf.float32,\n initializer = tf.constant_initializer(0.0),\n )\n\n self.individual_losses = []\n\n if self.bidirectional:\n next_ids = [self.next_token_id, self.next_token_id_reverse]\n else:\n next_ids = [self.next_token_id]\n \n print(lstm_outputs)\n self.output_scores = tf.identity(lstm_outputs, name = 'softmax_score')\n print(self.output_scores)\n \n for id_placeholder, lstm_output_flat in zip(next_ids, lstm_outputs):\n next_token_id_flat = tf.reshape(id_placeholder, [-1, 1])\n with tf.control_dependencies([lstm_output_flat]):\n if self.is_training and self.sample_softmax:\n losses = tf.nn.sampled_softmax_loss(\n self.softmax_W,\n self.softmax_b,\n next_token_id_flat,\n lstm_output_flat,\n int(\n self.options['n_negative_samples_batch']\n * self.options['n_tokens_vocab']\n ),\n self.options['n_tokens_vocab'],\n num_true = 1,\n )\n\n else:\n output_scores = (\n tf.matmul(\n lstm_output_flat, tf.transpose(self.softmax_W)\n )\n + self.softmax_b\n )\n\n losses = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits = self.output_scores,\n labels = tf.squeeze(\n next_token_id_flat, squeeze_dims = [1]\n ),\n )\n\n self.individual_losses.append(tf.reduce_mean(losses))\n\n if self.bidirectional:\n self.total_loss = 0.5 * (\n self.individual_losses[0] + self.individual_losses[1]\n )\n else:\n self.total_loss = self.individual_losses[0]",
"_____no_output_____"
],
[
"tf.reset_default_graph()\nsess = tf.InteractiveSession()\nmodel = LanguageModel(options, True)\nsess.run(tf.global_variables_initializer())",
"W0725 20:41:37.074845 42196 deprecation.py:506] From E:\\Anaconda\\envs\\git_test\\lib\\site-packages\\tensorflow\\python\\util\\dispatch.py:180: calling squeeze (from tensorflow.python.ops.array_ops) with squeeze_dims is deprecated and will be removed in a future version.\nInstructions for updating:\nUse the `axis` argument instead\nW0725 20:41:37.241371 42196 deprecation.py:323] From <ipython-input-29-70f0070b2d45>:358: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\nW0725 20:41:37.247355 42196 deprecation.py:323] From <ipython-input-29-70f0070b2d45>:378: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\nW0725 20:41:37.269296 42196 deprecation.py:323] From <ipython-input-29-70f0070b2d45>:394: static_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `keras.layers.RNN(cell, unroll=True)`, which is equivalent to this API\n"
],
[
"from tqdm import tqdm\n\ndef _get_feed_dict_from_X(X, model, char_inputs, bidirectional):\n feed_dict = {}\n if not char_inputs:\n token_ids = X['token_ids']\n feed_dict[model.token_ids] = token_ids\n else:\n char_ids = X['tokens_characters']\n feed_dict[model.tokens_characters] = char_ids\n if bidirectional:\n if not char_inputs:\n feed_dict[model.token_ids_reverse] = X['token_ids_reverse']\n else:\n feed_dict[model.tokens_characters_reverse] = X['tokens_characters_reverse']\n next_id_placeholders = [[model.next_token_id, '']]\n if bidirectional:\n next_id_placeholders.append([model.next_token_id_reverse, '_reverse'])\n\n for id_placeholder, suffix in next_id_placeholders:\n name = 'next_token_id' + suffix\n feed_dict[id_placeholder] = X[name]\n\n return feed_dict",
"_____no_output_____"
],
[
"bidirectional = options.get('bidirectional', False)\nbatch_size = options['batch_size']\nunroll_steps = options['unroll_steps']\nn_train_tokens = options.get('n_train_tokens')\nn_tokens_per_batch = batch_size * unroll_steps\nn_batches_per_epoch = int(n_train_tokens / n_tokens_per_batch)\nn_batches_total = options['n_epochs'] * n_batches_per_epoch\n\ninit_state_tensors = model.init_lstm_state\nfinal_state_tensors = model.final_lstm_state\n\nchar_inputs = 'char_cnn' in options\nif char_inputs:\n max_chars = options['char_cnn']['max_characters_per_token']\n feed_dict = {\n model.tokens_characters: np.zeros(\n [batch_size, unroll_steps, max_chars], dtype = np.int32\n )\n }\n\nelse:\n feed_dict = {model.token_ids: np.zeros([batch_size, unroll_steps])}\n\nif bidirectional:\n if char_inputs:\n feed_dict.update(\n {\n model.tokens_characters_reverse: np.zeros(\n [batch_size, unroll_steps, max_chars], dtype = np.int32\n )\n }\n )\n else:\n feed_dict.update(\n {\n model.token_ids_reverse: np.zeros(\n [batch_size, unroll_steps], dtype = np.int32\n )\n }\n )\n\ninit_state_values = sess.run(init_state_tensors, feed_dict = feed_dict)",
"_____no_output_____"
],
[
"data_gen = bi.iter_batches(batch_size, unroll_steps)\npbar = tqdm(range(n_batches_total), desc = 'train minibatch loop')\nfor p in pbar:\n batch = next(data_gen)\n feed_dict = {t: v for t, v in zip(init_state_tensors, init_state_values)}\n feed_dict.update(_get_feed_dict_from_X(batch, model, char_inputs, bidirectional))\n score, loss, _, init_state_values = sess.run([model.output_scores,\n model.total_loss, model.optimizer, final_state_tensors],\n feed_dict = feed_dict)\n pbar.set_postfix(cost = loss)",
"train minibatch loop: 100%|█████████████████████████████████████████| 14200/14200 [2:50:17<00:00, 1.40it/s, cost=3.54]\n"
],
[
"word_embed = model.softmax_W.eval()",
"_____no_output_____"
],
[
"from scipy.spatial.distance import cdist\nfrom sklearn.neighbors import NearestNeighbors",
"_____no_output_____"
],
[
"word = '金轮'\nnn = NearestNeighbors(10, metric = 'cosine').fit(word_embed)\ndistances, idx = nn.kneighbors(word_embed[dictionary[word]].reshape((1, -1)))\nword_list = []\nfor i in range(1, idx.shape[1]):\n word_list.append([rev_dictionary[idx[0, i]], 1 - distances[0, i]])\nword_list",
"_____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"
]
] |
4aac07fe6545597f0d09d1f59f8bd6092421c532
| 77,133 |
ipynb
|
Jupyter Notebook
|
artigos/bd_for_beginners.ipynb
|
basedosdados/analises
|
48d16ffc39dff8d1bfc48c149090a36dbde1d4ee
|
[
"MIT"
] | 54 |
2021-02-10T19:50:13.000Z
|
2022-03-14T12:21:14.000Z
|
artigos/bd_for_beginners.ipynb
|
basedosdados/analises
|
48d16ffc39dff8d1bfc48c149090a36dbde1d4ee
|
[
"MIT"
] | 19 |
2021-02-10T16:16:27.000Z
|
2022-03-08T01:58:07.000Z
|
artigos/bd_for_beginners.ipynb
|
basedosdados/analises
|
48d16ffc39dff8d1bfc48c149090a36dbde1d4ee
|
[
"MIT"
] | 15 |
2021-02-10T14:55:49.000Z
|
2022-02-22T14:02:44.000Z
| 56.757174 | 12,992 | 0.679722 |
[
[
[
"# Base dos dados",
"_____no_output_____"
],
[
"Base dos Dados is a Brazilian project of consolidation of datasets in a common repository with easy to follow codes. \n\nDownload *clean, integrated and updated* datasets in an easy way through SQL, Python, R or CLI (Stata in development). With Base dos Dados you have freedom to:\n- download whole tables\n- download tables partially\n- cross datasets and download final product\n\nThis Jupyter Notebook aims to help Python coders in main funcionalities of the platform. If you just heard about Base Dos Dados this is the place to come and start your journey. \n\nThis manual is divided into three sections:\n- Installation and starting commands\n- Using Base dos Dados with Pandas package\n- Examples\n\nIt is recommended to have know about the package Pandas before using *basedosdados* since data will be stored as dataframes. \nIf you have any feedback about this material please send me an email and I will gladly help: [email protected]",
"_____no_output_____"
],
[
"### 1. Installation and starting commands",
"_____no_output_____"
],
[
"Base dos Dados are located in pip and to install it you have to run the following code:",
"_____no_output_____"
]
],
[
[
"#!pip install basedosdados==1.3.0a3",
"_____no_output_____"
]
],
[
[
"Using an exclamation mark before the command will pass the command to the shell (not to the Python interpreter). If you prefer you can type *pip install basedosdados* directly in your Command Prompt.<br>\n\nBefore using *basedosdados* you have to import it: ",
"_____no_output_____"
]
],
[
[
"import basedosdados as bd",
"_____no_output_____"
]
],
[
[
"Now that you have installed and imported the package it is time to see what data is available. The following command will list all current datasets.<br>\n<br>\nNote: the first time you execute a command in *basedosdados* it will prompt you to login with your Google Cloud. This is because results are delivered through BigQuery (which belongs to Google). BigQuery provides a reliable and quick service for managing data. It is free unless you require more than 1TB per month. If this happens to you just follow the on-screen instructions.",
"_____no_output_____"
]
],
[
[
"bd.list_datasets()",
"\n\ndataset_id: br_abrinq_oca\n\n\ndataset_id: br_ana_atlas_esgotos\n\n\ndataset_id: br_bd_diretorios_brasil\n\n\ndataset_id: br_camara_atividade_legislativa\n\n\ndataset_id: br_camara_dados_abertos\n\n\ndataset_id: br_cgu_servidores_executivo_federal\n\n\ndataset_id: br_geobr_mapas\n\n\ndataset_id: br_ibge_amc\n\n\ndataset_id: br_ibge_censo2010\n\n\ndataset_id: br_ibge_nomes_brasil\n\n\ndataset_id: br_ibge_pib\n\n\ndataset_id: br_ibge_pnad_covid\n\n\ndataset_id: br_ibge_populacao\n\n\ndataset_id: br_imprensa_nacional_dou\n\n\ndataset_id: br_inep_ideb\n\n\ndataset_id: br_inep_indicadores_educacionais\n\n\ndataset_id: br_inep_sinopse_estatistica_educacao_basica\n\n\ndataset_id: br_inpe_prodes\n\n\ndataset_id: br_mapbiomas_estatisticas\n\n\ndataset_id: br_mc_auxilio_emergencial\n\n\ndataset_id: br_mc_indicadores\n\n\ndataset_id: br_me_caged\n\n\ndataset_id: br_me_rais\n\n\ndataset_id: br_me_socios\n\n\ndataset_id: br_mobilidados_indicadores\n\n\ndataset_id: br_ms_sim\n\n\ndataset_id: br_observatorio_crianca_indicadores\n\n\ndataset_id: br_ponte_indicadores\n\n\ndataset_id: br_sp_alesp\n\n\ndataset_id: br_sp_gov_orcamento\n\n\ndataset_id: br_sp_gov_ssp\n\n\ndataset_id: br_tesouro_finbra\n\n\ndataset_id: br_tse_eleicoes\n\n\ndataset_id: br_tse_filiacao_partidaria\n\n\ndataset_id: mundo_onu_adh\n"
]
],
[
[
"Note: the first time you execute a command in *basedosdados* it will prompt you to login with your Google Cloud. This is because results are delivered through BigQuery (which belongs to Google). BigQuery provides a reliable and quick service for managing data. It is free unless you require more than 1TB per month. If the login screen appears to you just follow the on-screen instructions.",
"_____no_output_____"
],
[
"You can check the data you want with the *get_dataset_description*. We will use *br_ibge_pib* as example:",
"_____no_output_____"
]
],
[
[
"bd.get_dataset_description('br_ibge_pib')",
"Dados sobre Produto Interno Bruto do IBGE.\n\n\nPara saber mais acesse:\nWebsite: https://basedosdados.org/dataset/br-ibge-pib\nGithub: https://github.com/basedosdados/mais/\n\nAjude a manter o projeto :)\nApoia-se: https://apoia.se/basedosdados\n\nInstituição (Quem mantém os dados oficiais?)\n-----------\nNome: instituto-brasileiro-de-geografia-e-estatistica\n\nOnde encontrar os dados\n-----------------------\n- https://www.ibge.gov.br/explica/pib.php\n\nGrupos\n------\n- economia\n\nIdiomas\n------\n- portugues\n\nLicença\n-------\nNome: MIT\n\n"
]
],
[
[
"Each of the *datasets* has tables inside and to see what are the available tables you can use the following command:",
"_____no_output_____"
]
],
[
[
"bd.list_dataset_tables('br_ibge_pib')",
"\n\ntable_id: municipios\n"
]
],
[
[
"To analyze which information is in that table you can run the following command.",
"_____no_output_____"
]
],
[
[
"bd.get_table_description('br_ibge_pib', 'municipios')",
"Produto Interno Bruto (PIB) municipal a preços correntes.\n\n\nPara saber mais acesse:\nWebsite: \nGithub: https://github.com/basedosdados/mais/\n\nAjude a manter o projeto :)\nApoia-se: https://apoia.se/basedosdados\n\nNível da Observação (Colunas que identificam cada linha unicamente)\n-------------------\n- municipio\n- ano\n\nCobertura Temporal\n------------------\n- 2002\n- 2003\n- 2004\n- 2005\n- 2006\n- 2007\n- 2008\n- 2009\n- 2010\n- 2011\n- 2012\n- 2013\n- 2014\n- 2015\n- 2016\n- 2017\n- 2018\n\nCobertura Espacial\n------------------\n- brasil\n\nFrequencia de Atualização\n-------------------------\n1 ano\n\nTratado por\n-----------\nNome: Ricardo Dahis\nCódigo: https://github.com/basedosdados/mais/tree/master/bases/br_ibge_pib/code\nEmail: [email protected]\n\nPublicado por\n-------------\nNome: Ricardo Dahis\nCódigo: https://github.com/basedosdados/mais/tree/master/bases/br_ibge_pib/code\nWebsite: www.ricardodahis.com\nEmail: [email protected]\n"
]
],
[
[
"With these three commands you are set and know what data is available. You are now able to create your dataframe and start your analysis! In this example we will generate a dataframe called *df* with information regarding Brazilian municipalities' GDP. The data is stored as a dataframe object and it will interact with the same commands used in Pandas.",
"_____no_output_____"
]
],
[
[
"df = bd.read_table('br_ibge_pib', 'municipios')\n# Note: depending on how you configured your Google Cloud setup, it might be necessary to add project ID in the request.\n# Like `bd.read_table('br_ibge_pib', 'municipios', billing_project_id=<YOUR_PROJECT_ID>)",
"Downloading: 100%|██████████████████████████████████████████████████████████| 94616/94616 [00:08<00:00, 10636.02rows/s]\n"
]
],
[
[
"### Example",
"_____no_output_____"
],
[
"In this section we will do quick exploratory example on the dataset we have been using. <br>\nFirst by let's define again the table and take a look at it:",
"_____no_output_____"
]
],
[
[
"df.head()",
"_____no_output_____"
]
],
[
[
"#### Example 1: São Paulo",
"_____no_output_____"
],
[
"The cities are being indexed by their ID You can see the correspondence in the following website: https://www.ibge.gov.br/explica/codigos-dos-municipios.php <br>\n<br>\nWe will take a look at São Paulo city with the following ID: 3550308<br>\nCreating a dataframe with São Paulo information:",
"_____no_output_____"
]
],
[
[
"sao_paulo = df[df.id_municipio == 3550308]",
"_____no_output_____"
]
],
[
[
"Looking at the table created we can check that everything is working as expected. ",
"_____no_output_____"
]
],
[
[
"sao_paulo",
"_____no_output_____"
]
],
[
[
"Pandas has some graph functions built in and we can use them to further visualize data:",
"_____no_output_____"
]
],
[
[
"sao_paulo.plot(x='ano', y='PIB')",
"_____no_output_____"
]
],
[
[
"Since the tables are in nominal prices it might be interesting to see results in logarithmic form. For that we can use the following code:",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n#Adding new columns:\ndf['log_pib'] = df.PIB.apply(np.log10)\n\n#Separating Sao Paulo again, now it will come with the new columns:\nsao_paulo = df[df.id_municipio == 3550308]",
"_____no_output_____"
]
],
[
[
"Analyzing data the way we did before:",
"_____no_output_____"
]
],
[
[
"sao_paulo",
"_____no_output_____"
],
[
"sao_paulo.plot(x='ano',y='log_pib')",
"_____no_output_____"
]
],
[
[
"#### Example 2: 2015",
"_____no_output_____"
],
[
"If you want to check all value added to GDP by the services sector in the year 2015 you could use the following code:",
"_____no_output_____"
]
],
[
[
"# First separating 2015 data only:\nmunicipios2015 = df[df.ano == 2015]\n\n#Adding logarithmic column:\nmunicipios2015['log_VA_servicos'] = municipios2015.VA_servicos.apply(np.log10)\n\n#Visualizing dataframe as histogram:\nmunicipios2015[municipios2015['log_VA_servicos'] > 0].hist('log_VA_servicos')",
"_____no_output_____"
]
],
[
[
"For the last piece of code we are using conditional statement '> 0' because it might be the case of a city with value of zero in the *VA_servicos* and when we calculate log it is equal to -inf.",
"_____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"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aac0974ddca8eea494f0d0510ad605faed854c6
| 96,650 |
ipynb
|
Jupyter Notebook
|
3. Landmark Detection and Tracking.ipynb
|
msardonini/P3_Implement_SLAM
|
0bae93a93f9cfcce4d9e3110dfb1c50a938a145a
|
[
"MIT"
] | null | null | null |
3. Landmark Detection and Tracking.ipynb
|
msardonini/P3_Implement_SLAM
|
0bae93a93f9cfcce4d9e3110dfb1c50a938a145a
|
[
"MIT"
] | null | null | null |
3. Landmark Detection and Tracking.ipynb
|
msardonini/P3_Implement_SLAM
|
0bae93a93f9cfcce4d9e3110dfb1c50a938a145a
|
[
"MIT"
] | null | null | null | 102.928647 | 31,716 | 0.785639 |
[
[
[
"# Project 3: Implement SLAM \n\n---\n\n## Project Overview\n\nIn this project, you'll implement SLAM for robot that moves and senses in a 2 dimensional, grid world!\n\nSLAM gives us a way to both localize a robot and build up a map of its environment as a robot moves and senses in real-time. This is an active area of research in the fields of robotics and autonomous systems. Since this localization and map-building relies on the visual sensing of landmarks, this is a computer vision problem. \n\nUsing what you've learned about robot motion, representations of uncertainty in motion and sensing, and localization techniques, you will be tasked with defining a function, `slam`, which takes in six parameters as input and returns the vector `mu`. \n> `mu` contains the (x,y) coordinate locations of the robot as it moves, and the positions of landmarks that it senses in the world\n\nYou can implement helper functions as you see fit, but your function must return `mu`. The vector, `mu`, should have (x, y) coordinates interlaced, for example, if there were 2 poses and 2 landmarks, `mu` will look like the following, where `P` is the robot position and `L` the landmark position:\n```\nmu = matrix([[Px0],\n [Py0],\n [Px1],\n [Py1],\n [Lx0],\n [Ly0],\n [Lx1],\n [Ly1]])\n```\n\nYou can see that `mu` holds the poses first `(x0, y0), (x1, y1), ...,` then the landmark locations at the end of the matrix; we consider a `nx1` matrix to be a vector.\n\n## Generating an environment\n\nIn a real SLAM problem, you may be given a map that contains information about landmark locations, and in this example, we will make our own data using the `make_data` function, which generates a world grid with landmarks in it and then generates data by placing a robot in that world and moving and sensing over some numer of time steps. The `make_data` function relies on a correct implementation of robot move/sense functions, which, at this point, should be complete and in the `robot_class.py` file. The data is collected as an instantiated robot moves and senses in a world. Your SLAM function will take in this data as input. So, let's first create this data and explore how it represents the movement and sensor measurements that our robot takes.\n\n---",
"_____no_output_____"
],
[
"## Create the world\n\nUse the code below to generate a world of a specified size with randomly generated landmark locations. You can change these parameters and see how your implementation of SLAM responds! \n\n`data` holds the sensors measurements and motion of your robot over time. It stores the measurements as `data[i][0]` and the motion as `data[i][1]`.\n\n#### Helper functions\n\nYou will be working with the `robot` class that may look familiar from the first notebook, \n\nIn fact, in the `helpers.py` file, you can read the details of how data is made with the `make_data` function. It should look very similar to the robot move/sense cycle you've seen in the first notebook.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom helpers import make_data\n\n# your implementation of slam should work with the following inputs\n# feel free to change these input values and see how it responds!\n\n# world parameters\nnum_landmarks = 5 # number of landmarks\nN = 20 # time steps\nworld_size = 100.0 # size of world (square)\n\n# robot parameters\nmeasurement_range = 50.0 # range at which we can sense landmarks\nmotion_noise = 2.0 # noise in robot motion\nmeasurement_noise = 2.0 # noise in the measurements\ndistance = 20.0 # distance by which robot (intends to) move each iteratation \n\n# world parameters\n# num_landmarks = 1 # number of landmarks\n# N = 2 # time steps\n# world_size = 10.0 # size of world (square)\n\n# # robot parameters\n# measurement_range = 5.0 # range at which we can sense landmarks\n# motion_noise = 0.0 # noise in robot motion\n# measurement_noise = 0.0 # noise in the measurements\n# distance = 2.0 # distance by which robot (intends to) move each iteratation \n\n\n\n\n\n# make_data instantiates a robot, AND generates random landmarks for a given world size and number of landmarks\ndata = make_data(N, num_landmarks, world_size, measurement_range, motion_noise, measurement_noise, distance)",
" \nLandmarks: [[92, 70], [65, 32], [65, 50], [48, 50], [49, 12]]\nRobot: [x=53.66166 y=45.68890]\n"
]
],
[
[
"### A note on `make_data`\n\nThe function above, `make_data`, takes in so many world and robot motion/sensor parameters because it is responsible for:\n1. Instantiating a robot (using the robot class)\n2. Creating a grid world with landmarks in it\n\n**This function also prints out the true location of landmarks and the *final* robot location, which you should refer back to when you test your implementation of SLAM.**\n\nThe `data` this returns is an array that holds information about **robot sensor measurements** and **robot motion** `(dx, dy)` that is collected over a number of time steps, `N`. You will have to use *only* these readings about motion and measurements to track a robot over time and find the determine the location of the landmarks using SLAM. We only print out the true landmark locations for comparison, later.\n\n\nIn `data` the measurement and motion data can be accessed from the first and second index in the columns of the data array. See the following code for an example, where `i` is the time step:\n```\nmeasurement = data[i][0]\nmotion = data[i][1]\n```\n",
"_____no_output_____"
]
],
[
[
"# print out some stats about the data\ntime_step = 0\n\nprint('Example measurements: \\n', data[time_step][0])\nprint('\\n')\nprint('Example motion: \\n', data[time_step][1])\nprint('size of data: \\n', len(data[time_step][1]))",
"Example measurements: \n [[0, 41.92105595483544, 19.921055954835442], [1, 13.120179121701325, -19.879820878298677], [2, 14.365265085617818, -0.6347349143821832], [3, -2.6301030786758095, -0.6301030786758095], [4, 0.7364016952095795, -36.26359830479042]]\n\n\nExample motion: \n [-8.372730419153866, 18.163077529102154]\nsize of data: \n 2\n"
]
],
[
[
"Try changing the value of `time_step`, you should see that the list of measurements varies based on what in the world the robot sees after it moves. As you know from the first notebook, the robot can only sense so far and with a certain amount of accuracy in the measure of distance between its location and the location of landmarks. The motion of the robot always is a vector with two values: one for x and one for y displacement. This structure will be useful to keep in mind as you traverse this data in your implementation of slam.",
"_____no_output_____"
],
[
"## Initialize Constraints\n\nOne of the most challenging tasks here will be to create and modify the constraint matrix and vector: omega and xi. In the second notebook, you saw an example of how omega and xi could hold all the values the define the relationships between robot poses `xi` and landmark positions `Li` in a 1D world, as seen below, where omega is the blue matrix and xi is the pink vector.\n\n<img src='images/motion_constraint.png' width=50% height=50% />\n\n\nIn *this* project, you are tasked with implementing constraints for a 2D world. We are referring to robot poses as `Px, Py` and landmark positions as `Lx, Ly`, and one way to approach this challenge is to add *both* x and y locations in the constraint matrices.\n\n<img src='images/constraints2D.png' width=50% height=50% />\n\nYou may also choose to create two of each omega and xi (one for x and one for y positions).",
"_____no_output_____"
],
[
"### TODO: Write a function that initializes omega and xi\n\nComplete the function `initialize_constraints` so that it returns `omega` and `xi` constraints for the starting position of the robot. Any values that we do not yet know should be initialized with the value `0`. You may assume that our robot starts out in exactly the middle of the world with 100% confidence (no motion or measurement noise at this point). The inputs `N` time steps, `num_landmarks`, and `world_size` should give you all the information you need to construct intial constraints of the correct size and starting values.\n\n*Depending on your approach you may choose to return one omega and one xi that hold all (x,y) positions *or* two of each (one for x values and one for y); choose whichever makes most sense to you!*",
"_____no_output_____"
]
],
[
[
"def initialize_constraints(N, num_landmarks, world_size):\n ''' This function takes in a number of time steps N, number of landmarks, and a world_size,\n and returns initialized constraint matrices, omega and xi.'''\n \n ## Recommended: Define and store the size (rows/cols) of the constraint matrix in a variable\n matSize = N + num_landmarks\n \n ## TODO: Define the constraint matrix, Omega, with two initial \"strength\" values\n ## for the initial x, y location of our robot\n omegaX = [[0 for i in range(matSize)] for j in range(matSize)]\n omegaY = [[0 for i in range(matSize)] for j in range(matSize)]\n \n omegaX[0][0] = 1\n omegaY[0][0] = 1\n \n ## TODO: Define the constraint *vector*, xi\n ## you can assume that the robot starts out in the middle of the world with 100% confidence\n xiX = [0 for i in range(matSize)]\n xiY = [0 for i in range(matSize)]\n \n xiX[0] = world_size / 2\n xiY[0] = world_size / 2\n \n return omegaX, omegaY, xiX, xiY\n ",
"_____no_output_____"
]
],
[
[
"### Test as you go\n\nIt's good practice to test out your code, as you go. Since `slam` relies on creating and updating constraint matrices, `omega` and `xi` to account for robot sensor measurements and motion, let's check that they initialize as expected for any given parameters.\n\nBelow, you'll find some test code that allows you to visualize the results of your function `initialize_constraints`. We are using the [seaborn](https://seaborn.pydata.org/) library for visualization.\n\n**Please change the test values of N, landmarks, and world_size and see the results**. Be careful not to use these values as input into your final smal function.\n\nThis code assumes that you have created one of each constraint: `omega` and `xi`, but you can change and add to this code, accordingly. The constraints should vary in size with the number of time steps and landmarks as these values affect the number of poses a robot will take `(Px0,Py0,...Pxn,Pyn)` and landmark locations `(Lx0,Ly0,...Lxn,Lyn)` whose relationships should be tracked in the constraint matrices. Recall that `omega` holds the weights of each variable and `xi` holds the value of the sum of these variables, as seen in Notebook 2. You'll need the `world_size` to determine the starting pose of the robot in the world and fill in the initial values for `xi`.",
"_____no_output_____"
]
],
[
[
"# import data viz resources\nimport matplotlib.pyplot as plt\nfrom pandas import DataFrame\nimport seaborn as sns\n%matplotlib inline",
"_____no_output_____"
],
[
"# define a small N and world_size (small for ease of visualization)\nN_test = 5\nnum_landmarks_test = 2\nsmall_world = 10\n\n# initialize the constraints\ninitial_omegaX, initial_omegaY, initial_xiX, initial_xiY = initialize_constraints(N_test, num_landmarks_test, small_world)",
"_____no_output_____"
],
[
"# define figure size\nplt.rcParams[\"figure.figsize\"] = (10,7)\n\n# display omega\nsns.heatmap(DataFrame(initial_omegaX), cmap='Blues', annot=True, linewidths=.5)",
"_____no_output_____"
],
[
"# define figure size\nplt.rcParams[\"figure.figsize\"] = (1,7)\n\n# display xi\nsns.heatmap(DataFrame(initial_xiX), cmap='Oranges', annot=True, linewidths=.5)",
"_____no_output_____"
]
],
[
[
"---\n## SLAM inputs \n\nIn addition to `data`, your slam function will also take in:\n* N - The number of time steps that a robot will be moving and sensing\n* num_landmarks - The number of landmarks in the world\n* world_size - The size (w/h) of your world\n* motion_noise - The noise associated with motion; the update confidence for motion should be `1.0/motion_noise`\n* measurement_noise - The noise associated with measurement/sensing; the update weight for measurement should be `1.0/measurement_noise`\n\n#### A note on noise\n\nRecall that `omega` holds the relative \"strengths\" or weights for each position variable, and you can update these weights by accessing the correct index in omega `omega[row][col]` and *adding/subtracting* `1.0/noise` where `noise` is measurement or motion noise. `Xi` holds actual position values, and so to update `xi` you'll do a similar addition process only using the actual value of a motion or measurement. So for a vector index `xi[row][0]` you will end up adding/subtracting one measurement or motion divided by their respective `noise`.\n\n### TODO: Implement Graph SLAM\n\nFollow the TODO's below to help you complete this slam implementation (these TODO's are in the recommended order), then test out your implementation! \n\n#### Updating with motion and measurements\n\nWith a 2D omega and xi structure as shown above (in earlier cells), you'll have to be mindful about how you update the values in these constraint matrices to account for motion and measurement constraints in the x and y directions. Recall that the solution to these matrices (which holds all values for robot poses `P` and landmark locations `L`) is the vector, `mu`, which can be computed at the end of the construction of omega and xi as the inverse of omega times xi: $\\mu = \\Omega^{-1}\\xi$\n\n**You may also choose to return the values of `omega` and `xi` if you want to visualize their final state!**",
"_____no_output_____"
]
],
[
[
"## TODO: Complete the code to implement SLAM\n\n## slam takes in 6 arguments and returns mu, \n## mu is the entire path traversed by a robot (all x,y poses) *and* all landmarks locations\ndef slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise):\n \n ## TODO: Use your initilization to create constraint matrices, omega and xi\n omegaX, omegaY, xiX, xiY = initialize_constraints(N, num_landmarks, world_size)\n \n ## TODO: Iterate through each time step in the data\n ## get all the motion and measurement data as you iterate\n motion = []\n measurements = []\n \n for i in range(len(data)):\n measurements.append(data[i][0])\n motion.append(data[i][1])\n \n ## TODO: update the constraint matrix/vector to account for all *measurements*\n ## this should be a series of additions that take into account the measurement noise\n for i in range(len(data)):\n for j in range(len(measurements[i])):\n ind = i\n omegaX[ind][ind] += 1 / measurement_noise\n omegaX[ind][N + measurements[i][j][0]] -= 1 / measurement_noise\n omegaX[N + measurements[i][j][0]][N + measurements[i][j][0]] += 1 / measurement_noise\n omegaX[N + measurements[i][j][0]][ind] -= 1 / measurement_noise\n \n xiX[ind] -= measurements[i][j][1] / measurement_noise\n xiX[N + measurements[i][j][0]] += measurements[i][j][1] / measurement_noise\n \n omegaY[ind][ind] += 1 / measurement_noise\n omegaY[ind][N + measurements[i][j][0]] -= 1 / measurement_noise\n omegaY[N + measurements[i][j][0]][N + measurements[i][j][0]] += 1 / measurement_noise\n omegaY[N + measurements[i][j][0]][ind] -= 1 / measurement_noise\n \n xiY[ind] -= measurements[i][j][2] / measurement_noise\n xiY[N + measurements[i][j][0]] += measurements[i][j][2] / measurement_noise\n \n ## TODO: update the constraint matrix/vector to account for all *motion* and motion noise\n for i in range(len(data)):\n ind = i+1\n \n omegaX[ind][ind] += 1 / motion_noise\n omegaX[ind][ind-1] -= 1 / motion_noise\n omegaX[ind-1][ind-1] += 1 / motion_noise\n omegaX[ind-1][ind] -= 1 / motion_noise\n xiX[ind] += motion[i][0] / motion_noise\n xiX[ind-1] -= motion[i][0] / motion_noise\n \n omegaY[ind][ind] += 1 / motion_noise\n omegaY[ind][ind-1] -= 1 / motion_noise\n omegaY[ind-1][ind-1] += 1 / motion_noise\n omegaY[ind-1][ind] -= 1 / motion_noise\n \n xiY[ind] += motion[i][1] / motion_noise\n xiY[ind-1] -= motion[i][1] / motion_noise\n \n ## TODO: After iterating through all the data\n ## Compute the best estimate of poses and landmark positions\n ## using the formula, omega_inverse * Xi\n# print(\"\\n\\n\\n\") \n\n# print(omegaX)\n# print(\"\\n\\n\\n\")\n# print(xiX)\n# print(\"\\n\\n\\n\")\n \n# print(omegaY)\n# print(\"\\n\\n\\n\")\n# print(xiY)\n# print(\"\\n\\n\\n\")\n \n# sns.heatmap(DataFrame(omegaX), cmap='Blues', annot=True, linewidths=.5)\n \n muX = np.linalg.inv(np.matrix(omegaX)) * np.transpose(np.matrix(xiX))\n muY = np.linalg.inv(np.matrix(omegaY)) * np.transpose(np.matrix(xiY))\n \n return muX, muY # return `mu`\n",
"_____no_output_____"
]
],
[
[
"## Helper functions\n\nTo check that your implementation of SLAM works for various inputs, we have provided two helper functions that will help display the estimated pose and landmark locations that your function has produced. First, given a result `mu` and number of time steps, `N`, we define a function that extracts the poses and landmarks locations and returns those as their own, separate lists. \n\nThen, we define a function that nicely print out these lists; both of these we will call, in the next step.\n",
"_____no_output_____"
]
],
[
[
"# a helper function that creates a list of poses and of landmarks for ease of printing\n# this only works for the suggested constraint architecture of interlaced x,y poses\ndef get_poses_landmarks(muX, muY, N):\n # create a list of poses\n poses = []\n for i in range(N):\n poses.append((muX[i].item(), muY[i].item()))\n\n # create a list of landmarks\n landmarks = []\n for i in range(num_landmarks):\n landmarks.append((muX[(N+i)].item(), muY[(N+i)].item()))\n\n # return completed lists\n return poses, landmarks\n",
"_____no_output_____"
],
[
"def print_all(poses, landmarks):\n print('\\n')\n print('Estimated Poses:')\n for i in range(len(poses)):\n print('['+', '.join('%.3f'%p for p in poses[i])+']')\n print('\\n')\n print('Estimated Landmarks:')\n for i in range(len(landmarks)):\n print('['+', '.join('%.3f'%l for l in landmarks[i])+']')\n",
"_____no_output_____"
]
],
[
[
"## Run SLAM\n\nOnce you've completed your implementation of `slam`, see what `mu` it returns for different world sizes and different landmarks!\n\n### What to Expect\n\nThe `data` that is generated is random, but you did specify the number, `N`, or time steps that the robot was expected to move and the `num_landmarks` in the world (which your implementation of `slam` should see and estimate a position for. Your robot should also start with an estimated pose in the very center of your square world, whose size is defined by `world_size`.\n\nWith these values in mind, you should expect to see a result that displays two lists:\n1. **Estimated poses**, a list of (x, y) pairs that is exactly `N` in length since this is how many motions your robot has taken. The very first pose should be the center of your world, i.e. `[50.000, 50.000]` for a world that is 100.0 in square size.\n2. **Estimated landmarks**, a list of landmark positions (x, y) that is exactly `num_landmarks` in length. \n\n#### Landmark Locations\n\nIf you refer back to the printout of *exact* landmark locations when this data was created, you should see values that are very similar to those coordinates, but not quite (since `slam` must account for noise in motion and measurement).",
"_____no_output_____"
]
],
[
[
"# call your implementation of slam, passing in the necessary parameters\nmuX, muY = slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise)\n\nprint(muX)\nprint(muY)\n\nprint(\"\\n\\n\\n\", data, \"\\n\\n\\n\")\n\n# print out the resulting landmarks and poses\nif(muX is not None):\n # get the lists of poses and landmarks\n # and print them out\n poses, landmarks = get_poses_landmarks(muX, muY, N)\n print_all(poses, landmarks)",
"[[ 50. ]\n [ 42.89778274]\n [ 32.45063509]\n [ 38.27517174]\n [ 44.29771035]\n [ 49.37941174]\n [ 56.38931955]\n [ 35.22736036]\n [ 13.96850158]\n [ 29.0105715 ]\n [ 44.36693369]\n [ 59.69934219]\n [ 75.23602068]\n [ 90.35011821]\n [ 71.94878996]\n [ 54.86718974]\n [ 36.17668524]\n [ 17.51581142]\n [ 34.14017028]\n [ 53.01144101]\n [ 91.61102953]\n [ 63.80224374]\n [ 64.30206455]\n [ 47.47013777]\n [ 49.05681003]]\n[[ 50. ]\n [ 69.35850479]\n [ 87.07783721]\n [ 68.89646325]\n [ 50.7472664 ]\n [ 31.44974362]\n [ 11.70730595]\n [ 6.94904504]\n [ 1.83463784]\n [ 13.24464334]\n [ 24.30700135]\n [ 37.17932865]\n [ 48.08687851]\n [ 61.10873496]\n [ 53.9535888 ]\n [ 47.58272097]\n [ 37.78325155]\n [ 30.76113227]\n [ 37.55722387]\n [ 44.18105515]\n [ 69.62377018]\n [ 30.8166081 ]\n [ 49.31642891]\n [ 49.48694604]\n [ 12.07361829]]\n\n\n\n [[[[0, 41.92105595483544, 19.921055954835442], [1, 13.120179121701325, -19.879820878298677], [2, 14.365265085617818, -0.6347349143821832], [3, -2.6301030786758095, -0.6301030786758095], [4, 0.7364016952095795, -36.26359830479042]], [-8.372730419153866, 18.163077529102154]], [[[0, 47.344202674575335, -0.7603506010778571], [1, 20.091335532654274, -39.01321774299892], [2, 21.78714797808451, -19.317405297568687], [3, 4.275919792866682, -19.828633482786515], [4, 4.909835575031103, -58.19471770062209]], [-8.372730419153866, 18.163077529102154]], [[[1, 30.238497322194085, -57.41408115184142], [2, 32.328548113477595, -37.32403036055791], [3, 16.484924122389156, -36.16765435164635], [4, 17.0862828784664, -74.5662955955691]], [6.5894171917572955, -18.883314885712558]], [[[1, 25.498453580551594, -38.148707826424236], [2, 26.182943919619238, -19.464217487356596], [3, 10.357555918608485, -18.28960548836735], [4, 9.689617651731744, -57.95754375524409]], [6.5894171917572955, -18.883314885712558]], [[[0, 46.91557291769347, 18.439536304552192], [1, 19.30907444562172, -20.166962167519554], [2, 18.778991588872767, -2.697045024268507], [3, 3.051503064422816, -1.4245335487184594], [4, 5.757754636389684, -37.71828197675159]], [6.5894171917572955, -18.883314885712558]], [[[0, 44.148030536577245, 39.61809156893098], [1, 13.504766551727624, -2.025172415918643], [2, 14.426886577311077, 16.89694760966481], [3, -1.9356555476512312, 17.534405484702503], [4, 1.1294052320346242, -18.400533735611642]], [6.5894171917572955, -18.883314885712558]], [[[0, 36.02106493373732, 59.00874331941575], [1, 7.556249917644067, 19.543928303322495], [2, 6.5163368489862235, 36.50401523466465], [3, -9.762559787797906, 37.225118597880524], [4, -7.920667961522908, 0.06701042415552028]], [-19.69718591432021, -3.467112207112061]], [[[1, 29.517430291999517, 24.746520257890765], [2, 29.495355524472217, 42.724445490363465], [3, 11.554468673227293, 41.78355863911854], [4, 13.057660549557244, 4.286750515448494]], [-19.69718591432021, -3.467112207112061]], [[[3, 34.39065604508607, 48.585318288637886], [4, 34.96092275123213, 10.155584994783954]], [15.84210864935275, 12.207685838933715]], [[[1, 34.0185011952975, 16.63453072203008], [2, 36.48420896371205, 37.100238490444625], [3, 17.105218211812797, 34.72124773854538], [4, 21.295334002720388, -0.08863647054702994]], [15.84210864935275, 12.207685838933715]], [[[0, 46.30045253860562, 44.74218664774781], [1, 20.468801950410374, 7.910536059552566], [2, 19.294162913819193, 24.735897022961385], [3, 4.146762654789447, 26.58849676393164], [4, 4.17348344669079, -12.384782444167017]], [15.84210864935275, 12.207685838933715]], [[[0, 31.757914249863884, 31.859135492707072], [1, 5.007484000470546, -5.891294756686266], [2, 5.7634007711583966, 12.864622014001585], [3, -13.3697643571832, 10.731456885659988], [4, -11.209190029660178, -26.10796878681699]], [15.84210864935275, 12.207685838933715]], [[[0, 16.36753338316317, 22.03907023972331], [1, -11.548735407839967, -16.87719855127983], [2, -10.212232522473666, 2.4593043340864726], [3, -29.632989250993813, 0.03854760556632453], [4, -25.333974933185807, -34.66243807662567]], [15.84210864935275, 12.207685838933715]], [[[0, 1.1478290254627677, 8.309204419782004], [1, -27.58645429937223, -31.425078905052995], [2, -25.382970248461213, -11.221594854141978], [3, -43.02783563749852, -11.866460243179283], [4, -40.04807102247929, -47.886695628160055]], [-18.284120400525175, -8.104994829060603]], [[[0, 20.462004691530044, 16.365133085394074], [1, -5.376801973376769, -20.473673579512738], [2, -8.9528784609996, -6.049750067135569], [3, -25.50108536720878, -5.597956973344751], [4, -22.813175024051343, -41.91004663018731]], [-18.284120400525175, -8.104994829060603]], [[[0, 35.90304501993084, 20.838591504770907], [1, 7.973745153028212, -18.09070836213173], [2, 9.130671899746435, 1.066218384586496], [3, -5.8028528825935215, 3.132693602246539], [4, -6.907176537573559, -36.971630052733495]], [-18.284120400525175, -8.104994829060603]], [[[1, 27.97257301953823, -5.931477102467667], [2, 29.016641710053765, 13.112591588047865], [3, 12.138103040377297, 13.234052918371399], [4, 10.826828024408226, -27.077222097597673]], [-18.284120400525175, -8.104994829060603]], [[[1, 46.85997589680546, 0.8701271559164634], [2, 45.896428639603904, 17.906579898714902], [3, 29.077952515239403, 18.088103774350405], [4, 30.863494937987003, -19.126353802901995]], [18.871270734936786, 6.623831281721962]], [[[1, 29.586286579032006, -7.419973746779554], [2, 30.289228109251436, 11.282967783439876], [3, 14.814873511654437, 12.808613185842876], [4, 15.627098663558339, -25.37916166225322]], [18.871270734936786, 6.623831281721962]]] \n\n\n\n\n\nEstimated Poses:\n[50.000, 50.000]\n[42.898, 69.359]\n[32.451, 87.078]\n[38.275, 68.896]\n[44.298, 50.747]\n[49.379, 31.450]\n[56.389, 11.707]\n[35.227, 6.949]\n[13.969, 1.835]\n[29.011, 13.245]\n[44.367, 24.307]\n[59.699, 37.179]\n[75.236, 48.087]\n[90.350, 61.109]\n[71.949, 53.954]\n[54.867, 47.583]\n[36.177, 37.783]\n[17.516, 30.761]\n[34.140, 37.557]\n[53.011, 44.181]\n\n\nEstimated Landmarks:\n[91.611, 69.624]\n[63.802, 30.817]\n[64.302, 49.316]\n[47.470, 49.487]\n[49.057, 12.074]\n"
]
],
[
[
"## Visualize the constructed world\n\nFinally, using the `display_world` code from the `helpers.py` file (which was also used in the first notebook), we can actually visualize what you have coded with `slam`: the final position of the robot and the positon of landmarks, created from only motion and measurement data!\n\n**Note that these should be very similar to the printed *true* landmark locations and final pose from our call to `make_data` early in this notebook.**",
"_____no_output_____"
]
],
[
[
"# import the helper function\nfrom helpers import display_world\n\n# Display the final world!\n\n# define figure size\nplt.rcParams[\"figure.figsize\"] = (20,20)\n\n# check if poses has been created\nif 'poses' in locals():\n # print out the last pose\n print('Last pose: ', poses[-1])\n # display the last position of the robot *and* the landmark positions\n display_world(int(world_size), poses[-1], landmarks)",
"Last pose: (53.01144101174819, 44.181055147701045)\n"
]
],
[
[
"### Question: How far away is your final pose (as estimated by `slam`) compared to the *true* final pose? Why do you think these poses are different?\n\nYou can find the true value of the final pose in one of the first cells where `make_data` was called. You may also want to look at the true landmark locations and compare them to those that were estimated by `slam`. Ask yourself: what do you think would happen if we moved and sensed more (increased N)? Or if we had lower/higher noise parameters.",
"_____no_output_____"
],
[
"My final pose was within 1.5 units of the real answer. The difference is caused by the introduction of noise in our measurements. If we were to increase N, the slam algorithm would have more data to use and the final positions of the landmarks would eventually converge to the true value. Of course, if the noise parameters were higher it would take much longer to converge and vice versa with lower noise parameters ",
"_____no_output_____"
],
[
"## Testing\n\nTo confirm that your slam code works before submitting your project, it is suggested that you run it on some test data and cases. A few such cases have been provided for you, in the cells below. When you are ready, uncomment the test cases in the next cells (there are two test cases, total); your output should be **close-to or exactly** identical to the given results. If there are minor discrepancies it could be a matter of floating point accuracy or in the calculation of the inverse matrix.\n\n### Submit your project\n\nIf you pass these tests, it is a good indication that your project will pass all the specifications in the project rubric. Follow the submission instructions to officially submit!",
"_____no_output_____"
]
],
[
[
"# Here is the data and estimated outputs for test case 1\n\ntest_data1 = [[[[1, 19.457599255548065, 23.8387362100849], [2, -13.195807561967236, 11.708840328458608], [3, -30.0954905279171, 15.387879242505843]], [-12.2607279422326, -15.801093326936487]], [[[2, -0.4659930049620491, 28.088559771215664], [4, -17.866382374890936, -16.384904503932]], [-12.2607279422326, -15.801093326936487]], [[[4, -6.202512900833806, -1.823403210274639]], [-12.2607279422326, -15.801093326936487]], [[[4, 7.412136480918645, 15.388585962142429]], [14.008259661173426, 14.274756084260822]], [[[4, -7.526138813444998, -0.4563942429717849]], [14.008259661173426, 14.274756084260822]], [[[2, -6.299793150150058, 29.047830407717623], [4, -21.93551130411791, -13.21956810989039]], [14.008259661173426, 14.274756084260822]], [[[1, 15.796300959032276, 30.65769689694247], [2, -18.64370821983482, 17.380022987031367]], [14.008259661173426, 14.274756084260822]], [[[1, 0.40311325410337906, 14.169429532679855], [2, -35.069349468466235, 2.4945558982439957]], [14.008259661173426, 14.274756084260822]], [[[1, -16.71340983241936, -2.777000269543834]], [-11.006096015782283, 16.699276945166858]], [[[1, -3.611096830835776, -17.954019226763958]], [-19.693482634035977, 3.488085684573048]], [[[1, 18.398273354362416, -22.705102332550947]], [-19.693482634035977, 3.488085684573048]], [[[2, 2.789312482883833, -39.73720193121324]], [12.849049222879723, -15.326510824972983]], [[[1, 21.26897046581808, -10.121029799040915], [2, -11.917698965880655, -23.17711662602097], [3, -31.81167947898398, -16.7985673023331]], [12.849049222879723, -15.326510824972983]], [[[1, 10.48157743234859, 5.692957082575485], [2, -22.31488473554935, -5.389184118551409], [3, -40.81803984305378, -2.4703329790238118]], [12.849049222879723, -15.326510824972983]], [[[0, 10.591050242096598, -39.2051798967113], [1, -3.5675572049297553, 22.849456408289125], [2, -38.39251065320351, 7.288990306029511]], [12.849049222879723, -15.326510824972983]], [[[0, -3.6225556479370766, -25.58006865235512]], [-7.8874682868419965, -18.379005523261092]], [[[0, 1.9784503557879374, -6.5025974151499]], [-7.8874682868419965, -18.379005523261092]], [[[0, 10.050665232782423, 11.026385307998742]], [-17.82919359778298, 9.062000642947142]], [[[0, 26.526838150174818, -0.22563393232425621], [4, -33.70303936886652, 2.880339841013677]], [-17.82919359778298, 9.062000642947142]]]\n\n## Test Case 1\n##\n# Estimated Pose(s):\n# [50.000, 50.000]\n# [37.858, 33.921]\n# [25.905, 18.268]\n# [13.524, 2.224]\n# [27.912, 16.886]\n# [42.250, 30.994]\n# [55.992, 44.886]\n# [70.749, 59.867]\n# [85.371, 75.230]\n# [73.831, 92.354]\n# [53.406, 96.465]\n# [34.370, 100.134]\n# [48.346, 83.952]\n# [60.494, 68.338]\n# [73.648, 53.082]\n# [86.733, 38.197]\n# [79.983, 20.324]\n# [72.515, 2.837]\n# [54.993, 13.221]\n# [37.164, 22.283]\n\n\n# Estimated Landmarks:\n# [82.679, 13.435]\n# [70.417, 74.203]\n# [36.688, 61.431]\n# [18.705, 66.136]\n# [20.437, 16.983]\n\n\n### Uncomment the following three lines for test case 1 and compare the output to the values above ###\n\nmuX_1, muY_1 = slam(test_data1, 20, 5, 100.0, 2.0, 2.0)\nposes, landmarks = get_poses_landmarks(muX_1, muY_1, 20)\nprint_all(poses, landmarks)",
"\n\nEstimated Poses:\n[50.000, 50.000]\n[37.973, 33.652]\n[26.185, 18.155]\n[13.745, 2.116]\n[28.097, 16.783]\n[42.384, 30.902]\n[55.831, 44.497]\n[70.857, 59.699]\n[85.697, 75.543]\n[74.011, 92.434]\n[53.544, 96.454]\n[34.525, 100.080]\n[48.623, 83.953]\n[60.197, 68.107]\n[73.778, 52.935]\n[87.132, 38.538]\n[80.303, 20.508]\n[72.798, 2.945]\n[55.245, 13.255]\n[37.416, 22.317]\n\n\nEstimated Landmarks:\n[82.956, 13.539]\n[70.495, 74.141]\n[36.740, 61.281]\n[18.698, 66.060]\n[20.635, 16.875]\n"
],
[
"# Here is the data and estimated outputs for test case 2\n\ntest_data2 = [[[[0, 26.543274387283322, -6.262538160312672], [3, 9.937396825799755, -9.128540360867689]], [18.92765331253674, -6.460955043986683]], [[[0, 7.706544739722961, -3.758467215445748], [1, 17.03954411948937, 31.705489938553438], [3, -11.61731288777497, -6.64964096716416]], [18.92765331253674, -6.460955043986683]], [[[0, -12.35130507136378, 2.585119104239249], [1, -2.563534536165313, 38.22159657838369], [3, -26.961236804740935, -0.4802312626141525]], [-11.167066095509824, 16.592065417497455]], [[[0, 1.4138633151721272, -13.912454837810632], [1, 8.087721200818589, 20.51845934354381], [3, -17.091723454402302, -16.521500551709707], [4, -7.414211721400232, 38.09191602674439]], [-11.167066095509824, 16.592065417497455]], [[[0, 12.886743222179561, -28.703968411636318], [1, 21.660953298391387, 3.4912891084614914], [3, -6.401401414569506, -32.321583037341625], [4, 5.034079343639034, 23.102207946092893]], [-11.167066095509824, 16.592065417497455]], [[[1, 31.126317672358578, -10.036784369535214], [2, -38.70878528420893, 7.4987265861424595], [4, 17.977218575473767, 6.150889254289742]], [-6.595520680493778, -18.88118393939265]], [[[1, 41.82460922922086, 7.847527392202475], [3, 15.711709540417502, -30.34633659912818]], [-6.595520680493778, -18.88118393939265]], [[[0, 40.18454208294434, -6.710999804403755], [3, 23.019508919299156, -10.12110867290604]], [-6.595520680493778, -18.88118393939265]], [[[3, 27.18579315312821, 8.067219022708391]], [-6.595520680493778, -18.88118393939265]], [[], [11.492663265706092, 16.36822198838621]], [[[3, 24.57154567653098, 13.461499960708197]], [11.492663265706092, 16.36822198838621]], [[[0, 31.61945290413707, 0.4272295085799329], [3, 16.97392299158991, -5.274596836133088]], [11.492663265706092, 16.36822198838621]], [[[0, 22.407381798735177, -18.03500068379259], [1, 29.642444125196995, 17.3794951934614], [3, 4.7969752441371645, -21.07505361639969], [4, 14.726069092569372, 32.75999422300078]], [11.492663265706092, 16.36822198838621]], [[[0, 10.705527984670137, -34.589764174299596], [1, 18.58772336795603, -0.20109708164787765], [3, -4.839806195049413, -39.92208742305105], [4, 4.18824810165454, 14.146847823548889]], [11.492663265706092, 16.36822198838621]], [[[1, 5.878492140223764, -19.955352450942357], [4, -7.059505455306587, -0.9740849280550585]], [19.628527845173146, 3.83678180657467]], [[[1, -11.150789592446378, -22.736641053247872], [4, -28.832815721158255, -3.9462962046291388]], [-19.841703647091965, 2.5113335861604362]], [[[1, 8.64427397916182, -20.286336970889053], [4, -5.036917727942285, -6.311739993868336]], [-5.946642674882207, -19.09548221169787]], [[[0, 7.151866679283043, -39.56103232616369], [1, 16.01535401373368, -3.780995345194027], [4, -3.04801331832137, 13.697362774960865]], [-5.946642674882207, -19.09548221169787]], [[[0, 12.872879480504395, -19.707592098123207], [1, 22.236710716903136, 16.331770792606406], [3, -4.841206109583004, -21.24604435851242], [4, 4.27111163223552, 32.25309748614184]], [-5.946642674882207, -19.09548221169787]]] \n\n\n## Test Case 2\n##\n# Estimated Pose(s):\n# [50.000, 50.000]\n# [69.035, 45.061]\n# [87.655, 38.971]\n# [76.084, 55.541]\n# [64.283, 71.684]\n# [52.396, 87.887]\n# [44.674, 68.948]\n# [37.532, 49.680]\n# [31.392, 30.893]\n# [24.796, 12.012]\n# [33.641, 26.440]\n# [43.858, 43.560]\n# [54.735, 60.659]\n# [65.884, 77.791]\n# [77.413, 94.554]\n# [96.740, 98.020]\n# [76.149, 99.586]\n# [70.211, 80.580]\n# [64.130, 61.270]\n# [58.183, 42.175]\n\n\n# Estimated Landmarks:\n# [76.777, 42.415]\n# [85.109, 76.850]\n# [13.687, 95.386]\n# [59.488, 39.149]\n# [69.283, 93.654]\n\n\n### Uncomment the following three lines for test case 2 and compare to the values above ###\n\nmux_2, muy_2 = slam(test_data2, 20, 5, 100.0, 2.0, 2.0)\nposes, landmarks = get_poses_landmarks(mux_2, muy_2, 20)\nprint_all(poses, landmarks)\n",
"\n\nEstimated Poses:\n[50.000, 50.000]\n[69.181, 45.665]\n[87.743, 39.703]\n[76.270, 56.311]\n[64.317, 72.176]\n[52.257, 88.154]\n[44.059, 69.401]\n[37.002, 49.918]\n[30.924, 30.955]\n[23.508, 11.419]\n[34.180, 27.133]\n[44.155, 43.846]\n[54.806, 60.920]\n[65.698, 78.546]\n[77.468, 95.626]\n[96.802, 98.821]\n[75.957, 99.971]\n[70.200, 81.181]\n[64.054, 61.723]\n[58.107, 42.628]\n\n\nEstimated Landmarks:\n[76.779, 42.887]\n[85.065, 77.438]\n[13.548, 95.652]\n[59.449, 39.595]\n[69.263, 94.240]\n"
]
]
] |
[
"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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
4aac3f0c7e7df4d133eae91e33d3dd71fcb62270
| 125,562 |
ipynb
|
Jupyter Notebook
|
02-Camera-Calibration/2-Calibrating-Camera.ipynb
|
vyasparthm/AutonomousDriving
|
4a767442a7e661dd71f4e160f3c071dc02614ab6
|
[
"MIT"
] | null | null | null |
02-Camera-Calibration/2-Calibrating-Camera.ipynb
|
vyasparthm/AutonomousDriving
|
4a767442a7e661dd71f4e160f3c071dc02614ab6
|
[
"MIT"
] | null | null | null |
02-Camera-Calibration/2-Calibrating-Camera.ipynb
|
vyasparthm/AutonomousDriving
|
4a767442a7e661dd71f4e160f3c071dc02614ab6
|
[
"MIT"
] | null | null | null | 865.944828 | 121,764 | 0.956707 |
[
[
[
"## Calibrating a Camera\n\nIn this notebook we'll learn about calibrating a camera.",
"_____no_output_____"
]
],
[
[
"# Importing required libraries\n\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n%matplotlib inline\n# lets just read one image and display\nimg = mpimg.imread('./camera_cal/calibration9.jpg')\nplt.imshow(img)",
"_____no_output_____"
]
],
[
[
"In order to understand the image better, I will map the coordinates of the corners(Image Points) in this 2 Dimensional image to 3 Dimensional coordinates(object points) or lets say Real undistorted chessboard corners. \n<br/>\n\nWe will setup two arrays to store these points, at the same time we'll be using a few more `numpy` functions as well.",
"_____no_output_____"
]
],
[
[
"objpoints = [] # 3D points / Object points\nimgpoints = [] # 2D points / Image points",
"_____no_output_____"
]
],
[
[
"To get a better understanding, these points can be represented as below diagram:\n\nZ will remain 0 since the image is on a 2D plane/flat surface\n<img src=\"./img/imgvsobj_plane.jpg\"/>",
"_____no_output_____"
]
],
[
[
"import glob\nimport os\n\n# Prepare np(numpy) array for points like (0,0,0), (1,0,0),(1,1,0),....(7,5,0)\nobjp = np.zeros((6*9,3), np.float32)\n\n# Lets use np's mgrig to initialize the array\n\nobjp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2) # T is for Transpose\n\nimg_files = os.listdir('camera_cal')\n\n\nfor fname in img_files:\n if fname.startswith('calibration'):\n img = mpimg.imread('camera_cal/'+fname)\n \n # Lets use findChessboardCorners on input\n gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)\n \n # Lets find chessboardCorners\n ret, corners = cv2.findChessboardCorners(gray,(9,6),None)\n \n if ret == True:\n imgpoints.append(corners)\n objpoints.append(objp)\n # Draw and display Chessboard\n img = cv2.drawChessboardCorners(img , (9,6) , corners, ret)\n \n plt.imsave('./output_images/ChessboardCorners/'+fname,img)\n \n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aac430ae9f9661dd8e80f911b3e5c4288f04956
| 10,603 |
ipynb
|
Jupyter Notebook
|
week04_finetuning/other_frameworks/seminar_tf.ipynb
|
GrafikXxxxxxxYyyyyyyyyyy/Practical_DL
|
77aab4c03b686a2e515c1d0d1e629b7cac5fe816
|
[
"MIT"
] | null | null | null |
week04_finetuning/other_frameworks/seminar_tf.ipynb
|
GrafikXxxxxxxYyyyyyyyyyy/Practical_DL
|
77aab4c03b686a2e515c1d0d1e629b7cac5fe816
|
[
"MIT"
] | null | null | null |
week04_finetuning/other_frameworks/seminar_tf.ipynb
|
GrafikXxxxxxxYyyyyyyyyyy/Practical_DL
|
77aab4c03b686a2e515c1d0d1e629b7cac5fe816
|
[
"MIT"
] | 1 |
2019-05-17T16:57:18.000Z
|
2019-05-17T16:57:18.000Z
| 27.756545 | 190 | 0.573423 |
[
[
[
"### Imagenet\n\nLargest image classification dataset at this point of time.\n\nUrl: http://image-net.org/\n\nOur setup: classify from a set of 1000 classes.",
"_____no_output_____"
]
],
[
[
"#classes' names are stored here\nimport pickle\nclasses = pickle.load(open('classes.pkl','rb'))\nprint (classes[::100])",
"_____no_output_____"
]
],
[
[
"### Using pre-trained model: inception\nKeras has a number of models for which you can use pre-trained weights. The interface is super-straightforward:",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\ngpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.1)\ns = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=gpu_options))",
"_____no_output_____"
],
[
"import keras\nimport keras.applications as zoo\n\nmodel = zoo.InceptionV3(include_top=True, weights='imagenet')",
"_____no_output_____"
],
[
"model.summary()",
"_____no_output_____"
]
],
[
[
"### Predict class probabilities",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nfrom scipy.misc import imresize\n%matplotlib inline\n\nimg = imresize(plt.imread('sample_images/albatross.jpg'), (299,299))\nplt.imshow(img)\nplt.show()\n\nimg_preprocessed = zoo.inception_v3.preprocess_input(img[None].astype('float32'))\n\nprobs = model.predict(img_preprocessed)\n\nlabels = probs.ravel().argsort()[-1:-10:-1]\nprint ('top-10 classes are:')\nfor l in labels:\n print ('%.4f\\t%s' % (probs.ravel()[l], classes[l].split(',')[0]))\n\n",
"_____no_output_____"
]
],
[
[
"### Having fun with pre-trained nets",
"_____no_output_____"
]
],
[
[
"!wget http://cdn.com.do/wp-content/uploads/2017/02/Donal-Trum-Derogar.jpeg -O img.jpg",
"_____no_output_____"
],
[
"img = imresize(plt.imread('img.jpg'), (299,299))\nplt.imshow(img)\nplt.show()\n\nimg_preprocessed = zoo.inception_v3.preprocess_input(img[None].astype('float32'))\n\nprobs = model.predict(img_preprocessed)\n\nlabels = probs.ravel().argsort()[-1:-10:-1]\nprint ('top-10 classes are:')\nfor l in labels:\n print ('%.4f\\t%s' % (probs.ravel()[l], classes[l].split(',')[0]))\n\n",
"_____no_output_____"
]
],
[
[
"### How do you reuse layers\n\nSince model is just a sequence of layers, one can apply it as any other Keras model. Then you can build more layers on top of it, train them and maybe fine-tune \"body\" weights a bit.",
"_____no_output_____"
]
],
[
[
"img = keras.backend.Input('float32',[None,299,299,3])\n\nneck = zoo.InceptionV3(include_top=False, weights='imagenet')(img)\n\nhid = keras.layers.GlobalMaxPool2D()(neck)\n\nhid = keras.layers.Dense(512,activation='relu')(hid)\n\nout = keras.layers.Dense(10,activation='softmax')(hid)\n\n#<...> loss, training, etc.",
"_____no_output_____"
]
],
[
[
"# Grand-quest: Dogs Vs Cats\n* original competition\n* https://www.kaggle.com/c/dogs-vs-cats\n* 25k JPEG images of various size, 2 classes (guess what)\n\n### Your main objective\n* In this seminar your goal is to fine-tune a pre-trained model to distinguish between the two rivaling animals\n* The first step is to just reuse some network layer as features",
"_____no_output_____"
]
],
[
[
"!wget https://www.dropbox.com/s/ae1lq6dsfanse76/dogs_vs_cats.train.zip?dl=1 -O data.zip\n!unzip data.zip",
"_____no_output_____"
]
],
[
[
"# for starters\n* Train sklearn model, evaluate validation accuracy (should be >80%",
"_____no_output_____"
]
],
[
[
"#extract features from images\nfrom tqdm import tqdm\nfrom scipy.misc import imresize\nimport os\nX = []\nY = []\n\n#this may be a tedious process. If so, store the results in some pickle and re-use them.\nfor fname in tqdm(os.listdir('train/')):\n y = fname.startswith(\"cat\")\n img = imread(\"train/\"+fname)\n img = imresize(img,(IMAGE_W,IMAGE_W))\n img = zoo.inception_v3.preprocess_input(img[None].astype('float32'))\n \n features = <use network to process the image into features>\n Y.append(y)\n X.append(features)",
"_____no_output_____"
],
[
"\nX = np.concatenate(X) #stack all [1xfeatures] matrices into one. \nassert X.ndim==2\n#WARNING! the concatenate works for [1xN] matrices. If you have other format, stack them yourself.\n\n#crop if we ended prematurely\nY = Y[:len(X)]",
"_____no_output_____"
],
[
"<split data either here or use cross-validation>",
"_____no_output_____"
]
],
[
[
"__load our dakka__\n",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestClassifier,ExtraTreesClassifier,GradientBoostingClassifier,AdaBoostClassifier\nfrom sklearn.linear_model import LogisticRegression, RidgeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier",
"_____no_output_____"
]
],
[
[
"# Main quest\n\n* Get the score improved!\n* You have to reach __at least 95%__ on the test set. More = better.\n\nNo methods are illegal: ensembling, data augmentation, NN hacks. \nJust don't let test data slip into training.\n\n\n### Split the raw image data\n * please do train/validation/test instead of just train/test\n * reasonable but not optimal split is 20k/2.5k/2.5k or 15k/5k/5k\n\n### Choose which vgg layers are you going to use\n * Anything but for prob is okay\n * Do not forget that vgg16 uses dropout\n\n### Build a few layers on top of chosen \"neck\" layers.\n * a good idea is to just stack more layers inside the same network\n * alternative: stack on top of get_output\n\n### Train the newly added layers for some iterations\n * you can selectively train some weights by setting var_list in the optimizer\n * `opt = tf.train.AdamOptimizer(learning_rate=...)`\n * `updates = opt.minimize(loss,var_list=variables_you_wanna_train)`\n * it's cruicial to monitor the network performance at this and following steps\n\n### Fine-tune the network body\n * probably a good idea to SAVE your new network weights now 'cuz it's easy to mess things up.\n * Moreover, saving weights periodically is a no-nonsense idea\n * even more cruicial to monitor validation performance\n * main network body may need a separate, much lower learning rate\n * you can create two update operations\n * `opt1 = tf.train.AdamOptimizer(learning_rate=lr1)`\n * `updates1 = opt1.minimize(loss,var_list=head_weights)`\n * `opt2 = tf.train.AdamOptimizer(learning_rate=lr2)`\n * `updates2 = opt2.minimize(loss,var_list=body_weights)`\n * `s.run([updates1,updates2],{...})\n \n### Grading\n* 95% accuracy on test yields 10 points\n* -1 point per 5% less accuracy\n\n### Some ways to get bonus points\n* explore other networks from the model zoo\n* play with architecture\n* 96%/97%/98%/99%/99.5% test score (screen pls).\n* data augmentation, prediction-time data augmentation\n* use any more advanced fine-tuning technique you know/read anywhere\n* ml hacks that benefit the final score\n",
"_____no_output_____"
]
],
[
[
"#<A whole lot of your code>",
"_____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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aac4f12c31e8e641fb1bc3c2c6fd697b97a75c4
| 562,939 |
ipynb
|
Jupyter Notebook
|
C1 - Intro to Deep Learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6c.ipynb
|
sharad5/Deep-Learning-Specialization-Coursera-
|
882be118b3484a758a41bd511e3a7c9356379a51
|
[
"MIT"
] | null | null | null |
C1 - Intro to Deep Learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6c.ipynb
|
sharad5/Deep-Learning-Specialization-Coursera-
|
882be118b3484a758a41bd511e3a7c9356379a51
|
[
"MIT"
] | null | null | null |
C1 - Intro to Deep Learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6c.ipynb
|
sharad5/Deep-Learning-Specialization-Coursera-
|
882be118b3484a758a41bd511e3a7c9356379a51
|
[
"MIT"
] | null | null | null | 351.836875 | 331,088 | 0.914268 |
[
[
[
"\n### <font color = \"darkblue\">Updates to Assignment</font>\n\n#### If you were working on the older version:\n* Please click on the \"Coursera\" icon in the top right to open up the folder directory. \n* Navigate to the folder: Week 3/ Planar data classification with one hidden layer. You can see your prior work in version 6b: \"Planar data classification with one hidden layer v6b.ipynb\"\n\n#### List of bug fixes and enhancements\n* Clarifies that the classifier will learn to classify regions as either red or blue.\n* compute_cost function fixes np.squeeze by casting it as a float.\n* compute_cost instructions clarify the purpose of np.squeeze.\n* compute_cost clarifies that \"parameters\" parameter is not needed, but is kept in the function definition until the auto-grader is also updated.\n* nn_model removes extraction of parameter values, as the entire parameter dictionary is passed to the invoked functions.",
"_____no_output_____"
],
[
"# Planar data classification with one hidden layer\n\nWelcome to your week 3 programming assignment. It's time to build your first neural network, which will have a hidden layer. You will see a big difference between this model and the one you implemented using logistic regression. \n\n**You will learn how to:**\n- Implement a 2-class classification neural network with a single hidden layer\n- Use units with a non-linear activation function, such as tanh \n- Compute the cross entropy loss \n- Implement forward and backward propagation\n",
"_____no_output_____"
],
[
"## 1 - Packages ##\n\nLet's first import all the packages that you will need during this assignment.\n- [numpy](https://www.numpy.org/) is the fundamental package for scientific computing with Python.\n- [sklearn](http://scikit-learn.org/stable/) provides simple and efficient tools for data mining and data analysis. \n- [matplotlib](http://matplotlib.org) is a library for plotting graphs in Python.\n- testCases provides some test examples to assess the correctness of your functions\n- planar_utils provide various useful functions used in this assignment",
"_____no_output_____"
]
],
[
[
"# Package imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom testCases_v2 import *\nimport sklearn\nimport sklearn.datasets\nimport sklearn.linear_model\nfrom planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets\n\n%matplotlib inline\n\nnp.random.seed(1) # set a seed so that the results are consistent",
"_____no_output_____"
]
],
[
[
"## 2 - Dataset ##\n\nFirst, let's get the dataset you will work on. The following code will load a \"flower\" 2-class dataset into variables `X` and `Y`.",
"_____no_output_____"
]
],
[
[
"X, Y = load_planar_dataset()",
"_____no_output_____"
]
],
[
[
"Visualize the dataset using matplotlib. The data looks like a \"flower\" with some red (label y=0) and some blue (y=1) points. Your goal is to build a model to fit this data. In other words, we want the classifier to define regions as either red or blue.",
"_____no_output_____"
]
],
[
[
"# Visualize the data:\nplt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);",
"_____no_output_____"
]
],
[
[
"You have:\n - a numpy-array (matrix) X that contains your features (x1, x2)\n - a numpy-array (vector) Y that contains your labels (red:0, blue:1).\n\nLets first get a better sense of what our data is like. \n\n**Exercise**: How many training examples do you have? In addition, what is the `shape` of the variables `X` and `Y`? \n\n**Hint**: How do you get the shape of a numpy array? [(help)](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html)",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (≈ 3 lines of code)\nshape_X = X.shape\nshape_Y = Y.shape\nm = shape_X[1] # training set size\n### END CODE HERE ###\n\nprint ('The shape of X is: ' + str(shape_X))\nprint ('The shape of Y is: ' + str(shape_Y))\nprint ('I have m = %d training examples!' % (m))",
"The shape of X is: (2, 400)\nThe shape of Y is: (1, 400)\nI have m = 400 training examples!\n"
]
],
[
[
"**Expected Output**:\n \n<table style=\"width:20%\">\n \n <tr>\n <td>**shape of X**</td>\n <td> (2, 400) </td> \n </tr>\n \n <tr>\n <td>**shape of Y**</td>\n <td>(1, 400) </td> \n </tr>\n \n <tr>\n <td>**m**</td>\n <td> 400 </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"## 3 - Simple Logistic Regression\n\nBefore building a full neural network, lets first see how logistic regression performs on this problem. You can use sklearn's built-in functions to do that. Run the code below to train a logistic regression classifier on the dataset.",
"_____no_output_____"
]
],
[
[
"# Train the logistic regression classifier\nclf = sklearn.linear_model.LogisticRegressionCV();\nclf.fit(X.T, Y.T);",
"_____no_output_____"
]
],
[
[
"You can now plot the decision boundary of these models. Run the code below.",
"_____no_output_____"
]
],
[
[
"# Plot the decision boundary for logistic regression\nplot_decision_boundary(lambda x: clf.predict(x), X, Y)\nplt.title(\"Logistic Regression\")\n\n# Print accuracy\nLR_predictions = clf.predict(X.T)\nprint ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +\n '% ' + \"(percentage of correctly labelled datapoints)\")",
"Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:20%\">\n <tr>\n <td>**Accuracy**</td>\n <td> 47% </td> \n </tr>\n \n</table>\n",
"_____no_output_____"
],
[
"**Interpretation**: The dataset is not linearly separable, so logistic regression doesn't perform well. Hopefully a neural network will do better. Let's try this now! ",
"_____no_output_____"
],
[
"## 4 - Neural Network model\n\nLogistic regression did not work well on the \"flower dataset\". You are going to train a Neural Network with a single hidden layer.\n\n**Here is our model**:\n<img src=\"images/classification_kiank.png\" style=\"width:600px;height:300px;\">\n\n**Mathematically**:\n\nFor one example $x^{(i)}$:\n$$z^{[1] (i)} = W^{[1]} x^{(i)} + b^{[1]}\\tag{1}$$ \n$$a^{[1] (i)} = \\tanh(z^{[1] (i)})\\tag{2}$$\n$$z^{[2] (i)} = W^{[2]} a^{[1] (i)} + b^{[2]}\\tag{3}$$\n$$\\hat{y}^{(i)} = a^{[2] (i)} = \\sigma(z^{ [2] (i)})\\tag{4}$$\n$$y^{(i)}_{prediction} = \\begin{cases} 1 & \\mbox{if } a^{[2](i)} > 0.5 \\\\ 0 & \\mbox{otherwise } \\end{cases}\\tag{5}$$\n\nGiven the predictions on all the examples, you can also compute the cost $J$ as follows: \n$$J = - \\frac{1}{m} \\sum\\limits_{i = 0}^{m} \\large\\left(\\small y^{(i)}\\log\\left(a^{[2] (i)}\\right) + (1-y^{(i)})\\log\\left(1- a^{[2] (i)}\\right) \\large \\right) \\small \\tag{6}$$\n\n**Reminder**: The general methodology to build a Neural Network is to:\n 1. Define the neural network structure ( # of input units, # of hidden units, etc). \n 2. Initialize the model's parameters\n 3. Loop:\n - Implement forward propagation\n - Compute loss\n - Implement backward propagation to get the gradients\n - Update parameters (gradient descent)\n\nYou often build helper functions to compute steps 1-3 and then merge them into one function we call `nn_model()`. Once you've built `nn_model()` and learnt the right parameters, you can make predictions on new data.",
"_____no_output_____"
],
[
"### 4.1 - Defining the neural network structure ####\n\n**Exercise**: Define three variables:\n - n_x: the size of the input layer\n - n_h: the size of the hidden layer (set this to 4) \n - n_y: the size of the output layer\n\n**Hint**: Use shapes of X and Y to find n_x and n_y. Also, hard code the hidden layer size to be 4.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: layer_sizes\n\ndef layer_sizes(X, Y):\n \"\"\"\n Arguments:\n X -- input dataset of shape (input size, number of examples)\n Y -- labels of shape (output size, number of examples)\n \n Returns:\n n_x -- the size of the input layer\n n_h -- the size of the hidden layer\n n_y -- the size of the output layer\n \"\"\"\n ### START CODE HERE ### (≈ 3 lines of code)\n n_x = X.shape[0] # size of input layer\n n_h = 4\n n_y = Y.shape[0] # size of output layer\n ### END CODE HERE ###\n return (n_x, n_h, n_y)",
"_____no_output_____"
],
[
"X_assess, Y_assess = layer_sizes_test_case()\n(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)\nprint(\"The size of the input layer is: n_x = \" + str(n_x))\nprint(\"The size of the hidden layer is: n_h = \" + str(n_h))\nprint(\"The size of the output layer is: n_y = \" + str(n_y))",
"The size of the input layer is: n_x = 5\nThe size of the hidden layer is: n_h = 4\nThe size of the output layer is: n_y = 2\n"
]
],
[
[
"**Expected Output** (these are not the sizes you will use for your network, they are just used to assess the function you've just coded).\n\n<table style=\"width:20%\">\n <tr>\n <td>**n_x**</td>\n <td> 5 </td> \n </tr>\n \n <tr>\n <td>**n_h**</td>\n <td> 4 </td> \n </tr>\n \n <tr>\n <td>**n_y**</td>\n <td> 2 </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"### 4.2 - Initialize the model's parameters ####\n\n**Exercise**: Implement the function `initialize_parameters()`.\n\n**Instructions**:\n- Make sure your parameters' sizes are right. Refer to the neural network figure above if needed.\n- You will initialize the weights matrices with random values. \n - Use: `np.random.randn(a,b) * 0.01` to randomly initialize a matrix of shape (a,b).\n- You will initialize the bias vectors as zeros. \n - Use: `np.zeros((a,b))` to initialize a matrix of shape (a,b) with zeros.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters\n\ndef initialize_parameters(n_x, n_h, n_y):\n \"\"\"\n Argument:\n n_x -- size of the input layer\n n_h -- size of the hidden layer\n n_y -- size of the output layer\n \n Returns:\n params -- python dictionary containing your parameters:\n W1 -- weight matrix of shape (n_h, n_x)\n b1 -- bias vector of shape (n_h, 1)\n W2 -- weight matrix of shape (n_y, n_h)\n b2 -- bias vector of shape (n_y, 1)\n \"\"\"\n \n np.random.seed(2) # we set up a seed so that your output matches ours although the initialization is random.\n \n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = np.random.randn(n_h,n_x) * 0.01\n b1 = np.zeros((n_h, 1))\n W2 = np.random.randn(n_y,n_h) * 0.01\n b2 = np.zeros((n_y, 1))\n ### END CODE HERE ###\n \n assert (W1.shape == (n_h, n_x))\n assert (b1.shape == (n_h, 1))\n assert (W2.shape == (n_y, n_h))\n assert (b2.shape == (n_y, 1))\n \n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n \n return parameters",
"_____no_output_____"
],
[
"n_x, n_h, n_y = initialize_parameters_test_case()\n\nparameters = initialize_parameters(n_x, n_h, n_y)\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"W1 = [[-0.00416758 -0.00056267]\n [-0.02136196 0.01640271]\n [-0.01793436 -0.00841747]\n [ 0.00502881 -0.01245288]]\nb1 = [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]]\nW2 = [[-0.01057952 -0.00909008 0.00551454 0.02292208]]\nb2 = [[ 0.]]\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:90%\">\n <tr>\n <td>**W1**</td>\n <td> [[-0.00416758 -0.00056267]\n [-0.02136196 0.01640271]\n [-0.01793436 -0.00841747]\n [ 0.00502881 -0.01245288]] </td> \n </tr>\n \n <tr>\n <td>**b1**</td>\n <td> [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]] </td> \n </tr>\n \n <tr>\n <td>**W2**</td>\n <td> [[-0.01057952 -0.00909008 0.00551454 0.02292208]]</td> \n </tr>\n \n\n <tr>\n <td>**b2**</td>\n <td> [[ 0.]] </td> \n </tr>\n \n</table>\n\n",
"_____no_output_____"
],
[
"### 4.3 - The Loop ####\n\n**Question**: Implement `forward_propagation()`.\n\n**Instructions**:\n- Look above at the mathematical representation of your classifier.\n- You can use the function `sigmoid()`. It is built-in (imported) in the notebook.\n- You can use the function `np.tanh()`. It is part of the numpy library.\n- The steps you have to implement are:\n 1. Retrieve each parameter from the dictionary \"parameters\" (which is the output of `initialize_parameters()`) by using `parameters[\"..\"]`.\n 2. Implement Forward Propagation. Compute $Z^{[1]}, A^{[1]}, Z^{[2]}$ and $A^{[2]}$ (the vector of all your predictions on all the examples in the training set).\n- Values needed in the backpropagation are stored in \"`cache`\". The `cache` will be given as an input to the backpropagation function.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: forward_propagation\n\ndef forward_propagation(X, parameters):\n \"\"\"\n Argument:\n X -- input data of size (n_x, m)\n parameters -- python dictionary containing your parameters (output of initialization function)\n \n Returns:\n A2 -- The sigmoid output of the second activation\n cache -- a dictionary containing \"Z1\", \"A1\", \"Z2\" and \"A2\"\n \"\"\"\n # Retrieve each parameter from the dictionary \"parameters\"\n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n ### END CODE HERE ###\n \n # Implement Forward Propagation to calculate A2 (probabilities)\n ### START CODE HERE ### (≈ 4 lines of code)\n Z1 = np.dot(W1, X) + b1\n A1 = np.tanh(Z1)\n Z2 = np.dot(W2, A1) + b2\n A2 = sigmoid(Z2)\n ### END CODE HERE ###\n \n assert(A2.shape == (1, X.shape[1]))\n \n cache = {\"Z1\": Z1,\n \"A1\": A1,\n \"Z2\": Z2,\n \"A2\": A2}\n \n return A2, cache",
"_____no_output_____"
],
[
"X_assess, parameters = forward_propagation_test_case()\nA2, cache = forward_propagation(X_assess, parameters)\n\n# Note: we use the mean here just to make sure that your output matches ours. \nprint(np.mean(cache['Z1']) ,np.mean(cache['A1']),np.mean(cache['Z2']),np.mean(cache['A2']))",
"0.262818640198 0.091999045227 -1.30766601287 0.212877681719\n"
]
],
[
[
"**Expected Output**:\n<table style=\"width:50%\">\n <tr>\n <td> 0.262818640198 0.091999045227 -1.30766601287 0.212877681719 </td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"Now that you have computed $A^{[2]}$ (in the Python variable \"`A2`\"), which contains $a^{[2](i)}$ for every example, you can compute the cost function as follows:\n\n$$J = - \\frac{1}{m} \\sum\\limits_{i = 1}^{m} \\large{(} \\small y^{(i)}\\log\\left(a^{[2] (i)}\\right) + (1-y^{(i)})\\log\\left(1- a^{[2] (i)}\\right) \\large{)} \\small\\tag{13}$$\n\n**Exercise**: Implement `compute_cost()` to compute the value of the cost $J$.\n\n**Instructions**:\n- There are many ways to implement the cross-entropy loss. To help you, we give you how we would have implemented\n$- \\sum\\limits_{i=0}^{m} y^{(i)}\\log(a^{[2](i)})$:\n```python\nlogprobs = np.multiply(np.log(A2),Y)\ncost = - np.sum(logprobs) # no need to use a for loop!\n```\n\n(you can use either `np.multiply()` and then `np.sum()` or directly `np.dot()`). \nNote that if you use `np.multiply` followed by `np.sum` the end result will be a type `float`, whereas if you use `np.dot`, the result will be a 2D numpy array. We can use `np.squeeze()` to remove redundant dimensions (in the case of single float, this will be reduced to a zero-dimension array). We can cast the array as a type `float` using `float()`.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: compute_cost\n\ndef compute_cost(A2, Y, parameters):\n \"\"\"\n Computes the cross-entropy cost given in equation (13)\n \n Arguments:\n A2 -- The sigmoid output of the second activation, of shape (1, number of examples)\n Y -- \"true\" labels vector of shape (1, number of examples)\n parameters -- python dictionary containing your parameters W1, b1, W2 and b2\n [Note that the parameters argument is not used in this function, \n but the auto-grader currently expects this parameter.\n Future version of this notebook will fix both the notebook \n and the auto-grader so that `parameters` is not needed.\n For now, please include `parameters` in the function signature,\n and also when invoking this function.]\n \n Returns:\n cost -- cross-entropy cost given equation (13)\n \n \"\"\"\n \n m = Y.shape[1] # number of example\n\n # Compute the cross-entropy cost\n ### START CODE HERE ### (≈ 2 lines of code)\n logprobs = (Y)*(np.log(A2)) + (1-Y)*np.log(1-A2)\n cost = (-1/m)*np.sum(logprobs)\n ### END CODE HERE ###\n \n cost = float(np.squeeze(cost)) # makes sure cost is the dimension we expect. \n # E.g., turns [[17]] into 17 \n assert(isinstance(cost, float))\n \n return cost",
"_____no_output_____"
],
[
"A2, Y_assess, parameters = compute_cost_test_case()\n\nprint(\"cost = \" + str(compute_cost(A2, Y_assess, parameters)))",
"cost = 0.6930587610394646\n"
]
],
[
[
"**Expected Output**:\n<table style=\"width:20%\">\n <tr>\n <td>**cost**</td>\n <td> 0.693058761... </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"Using the cache computed during forward propagation, you can now implement backward propagation.\n\n**Question**: Implement the function `backward_propagation()`.\n\n**Instructions**:\nBackpropagation is usually the hardest (most mathematical) part in deep learning. To help you, here again is the slide from the lecture on backpropagation. You'll want to use the six equations on the right of this slide, since you are building a vectorized implementation. \n\n<img src=\"images/grad_summary.png\" style=\"width:600px;height:300px;\">\n\n<!--\n$\\frac{\\partial \\mathcal{J} }{ \\partial z_{2}^{(i)} } = \\frac{1}{m} (a^{[2](i)} - y^{(i)})$\n\n$\\frac{\\partial \\mathcal{J} }{ \\partial W_2 } = \\frac{\\partial \\mathcal{J} }{ \\partial z_{2}^{(i)} } a^{[1] (i) T} $\n\n$\\frac{\\partial \\mathcal{J} }{ \\partial b_2 } = \\sum_i{\\frac{\\partial \\mathcal{J} }{ \\partial z_{2}^{(i)}}}$\n\n$\\frac{\\partial \\mathcal{J} }{ \\partial z_{1}^{(i)} } = W_2^T \\frac{\\partial \\mathcal{J} }{ \\partial z_{2}^{(i)} } * ( 1 - a^{[1] (i) 2}) $\n\n$\\frac{\\partial \\mathcal{J} }{ \\partial W_1 } = \\frac{\\partial \\mathcal{J} }{ \\partial z_{1}^{(i)} } X^T $\n\n$\\frac{\\partial \\mathcal{J} _i }{ \\partial b_1 } = \\sum_i{\\frac{\\partial \\mathcal{J} }{ \\partial z_{1}^{(i)}}}$\n\n- Note that $*$ denotes elementwise multiplication.\n- The notation you will use is common in deep learning coding:\n - dW1 = $\\frac{\\partial \\mathcal{J} }{ \\partial W_1 }$\n - db1 = $\\frac{\\partial \\mathcal{J} }{ \\partial b_1 }$\n - dW2 = $\\frac{\\partial \\mathcal{J} }{ \\partial W_2 }$\n - db2 = $\\frac{\\partial \\mathcal{J} }{ \\partial b_2 }$\n \n!-->\n\n- Tips:\n - To compute dZ1 you'll need to compute $g^{[1]'}(Z^{[1]})$. Since $g^{[1]}(.)$ is the tanh activation function, if $a = g^{[1]}(z)$ then $g^{[1]'}(z) = 1-a^2$. So you can compute \n $g^{[1]'}(Z^{[1]})$ using `(1 - np.power(A1, 2))`.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: backward_propagation\n\ndef backward_propagation(parameters, cache, X, Y):\n \"\"\"\n Implement the backward propagation using the instructions above.\n \n Arguments:\n parameters -- python dictionary containing our parameters \n cache -- a dictionary containing \"Z1\", \"A1\", \"Z2\" and \"A2\".\n X -- input data of shape (2, number of examples)\n Y -- \"true\" labels vector of shape (1, number of examples)\n \n Returns:\n grads -- python dictionary containing your gradients with respect to different parameters\n \"\"\"\n m = X.shape[1]\n \n # First, retrieve W1 and W2 from the dictionary \"parameters\".\n ### START CODE HERE ### (≈ 2 lines of code)\n W1 = parameters[\"W1\"]\n W2 = parameters[\"W2\"]\n ### END CODE HERE ###\n \n # Retrieve also A1 and A2 from dictionary \"cache\".\n ### START CODE HERE ### (≈ 2 lines of code)\n A1 = cache[\"A1\"]\n A2 = cache[\"A2\"]\n ### END CODE HERE ###\n \n # Backward propagation: calculate dW1, db1, dW2, db2. \n ### START CODE HERE ### (≈ 6 lines of code, corresponding to 6 equations on slide above)\n dZ2 = A2 - Y\n dW2 = (1/m)*(np.dot(dZ2, A1.T))\n db2 = (1/m)*(np.sum(dZ2, axis=1, keepdims=True))\n dZ1 = np.dot(W2.T, dZ2) * (1-np.power(A1, 2))\n dW1 = (1/m)*(np.dot(dZ1, X.T))\n db1 = (1/m)*(np.sum(dZ1, axis=1, keepdims=True))\n ### END CODE HERE ###\n \n grads = {\"dW1\": dW1,\n \"db1\": db1,\n \"dW2\": dW2,\n \"db2\": db2}\n \n return grads",
"_____no_output_____"
],
[
"parameters, cache, X_assess, Y_assess = backward_propagation_test_case()\n\ngrads = backward_propagation(parameters, cache, X_assess, Y_assess)\nprint (\"dW1 = \"+ str(grads[\"dW1\"]))\nprint (\"db1 = \"+ str(grads[\"db1\"]))\nprint (\"dW2 = \"+ str(grads[\"dW2\"]))\nprint (\"db2 = \"+ str(grads[\"db2\"]))",
"dW1 = [[ 0.00301023 -0.00747267]\n [ 0.00257968 -0.00641288]\n [-0.00156892 0.003893 ]\n [-0.00652037 0.01618243]]\ndb1 = [[ 0.00176201]\n [ 0.00150995]\n [-0.00091736]\n [-0.00381422]]\ndW2 = [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]]\ndb2 = [[-0.16655712]]\n"
]
],
[
[
"**Expected output**:\n\n\n\n<table style=\"width:80%\">\n <tr>\n <td>**dW1**</td>\n <td> [[ 0.00301023 -0.00747267]\n [ 0.00257968 -0.00641288]\n [-0.00156892 0.003893 ]\n [-0.00652037 0.01618243]] </td> \n </tr>\n \n <tr>\n <td>**db1**</td>\n <td> [[ 0.00176201]\n [ 0.00150995]\n [-0.00091736]\n [-0.00381422]] </td> \n </tr>\n \n <tr>\n <td>**dW2**</td>\n <td> [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]] </td> \n </tr>\n \n\n <tr>\n <td>**db2**</td>\n <td> [[-0.16655712]] </td> \n </tr>\n \n</table> ",
"_____no_output_____"
],
[
"**Question**: Implement the update rule. Use gradient descent. You have to use (dW1, db1, dW2, db2) in order to update (W1, b1, W2, b2).\n\n**General gradient descent rule**: $ \\theta = \\theta - \\alpha \\frac{\\partial J }{ \\partial \\theta }$ where $\\alpha$ is the learning rate and $\\theta$ represents a parameter.\n\n**Illustration**: The gradient descent algorithm with a good learning rate (converging) and a bad learning rate (diverging). Images courtesy of Adam Harley.\n\n<img src=\"images/sgd.gif\" style=\"width:400;height:400;\"> <img src=\"images/sgd_bad.gif\" style=\"width:400;height:400;\">\n\n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: update_parameters\n\ndef update_parameters(parameters, grads, learning_rate = 1.2):\n \"\"\"\n Updates parameters using the gradient descent update rule given above\n \n Arguments:\n parameters -- python dictionary containing your parameters \n grads -- python dictionary containing your gradients \n \n Returns:\n parameters -- python dictionary containing your updated parameters \n \"\"\"\n # Retrieve each parameter from the dictionary \"parameters\"\n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n ### END CODE HERE ###\n \n # Retrieve each gradient from the dictionary \"grads\"\n ### START CODE HERE ### (≈ 4 lines of code)\n dW1 = grads[\"dW1\"]\n db1 = grads[\"db1\"]\n dW2 = grads[\"dW2\"]\n db2 = grads[\"db2\"]\n ## END CODE HERE ###\n \n # Update rule for each parameter\n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = W1 - (learning_rate * dW1)\n b1 = b1 - (learning_rate * db1)\n W2 = W2 - (learning_rate * dW2)\n b2 = b2 - (learning_rate * db2)\n ### END CODE HERE ###\n \n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n \n return parameters",
"_____no_output_____"
],
[
"parameters, grads = update_parameters_test_case()\nparameters = update_parameters(parameters, grads)\n\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"W1 = [[-0.00643025 0.01936718]\n [-0.02410458 0.03978052]\n [-0.01653973 -0.02096177]\n [ 0.01046864 -0.05990141]]\nb1 = [[ -1.02420756e-06]\n [ 1.27373948e-05]\n [ 8.32996807e-07]\n [ -3.20136836e-06]]\nW2 = [[-0.01041081 -0.04463285 0.01758031 0.04747113]]\nb2 = [[ 0.00010457]]\n"
]
],
[
[
"**Expected Output**:\n\n\n<table style=\"width:80%\">\n <tr>\n <td>**W1**</td>\n <td> [[-0.00643025 0.01936718]\n [-0.02410458 0.03978052]\n [-0.01653973 -0.02096177]\n [ 0.01046864 -0.05990141]]</td> \n </tr>\n \n <tr>\n <td>**b1**</td>\n <td> [[ -1.02420756e-06]\n [ 1.27373948e-05]\n [ 8.32996807e-07]\n [ -3.20136836e-06]]</td> \n </tr>\n \n <tr>\n <td>**W2**</td>\n <td> [[-0.01041081 -0.04463285 0.01758031 0.04747113]] </td> \n </tr>\n \n\n <tr>\n <td>**b2**</td>\n <td> [[ 0.00010457]] </td> \n </tr>\n \n</table> ",
"_____no_output_____"
],
[
"### 4.4 - Integrate parts 4.1, 4.2 and 4.3 in nn_model() ####\n\n**Question**: Build your neural network model in `nn_model()`.\n\n**Instructions**: The neural network model has to use the previous functions in the right order.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: nn_model\n\ndef nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):\n \"\"\"\n Arguments:\n X -- dataset of shape (2, number of examples)\n Y -- labels of shape (1, number of examples)\n n_h -- size of the hidden layer\n num_iterations -- Number of iterations in gradient descent loop\n print_cost -- if True, print the cost every 1000 iterations\n \n Returns:\n parameters -- parameters learnt by the model. They can then be used to predict.\n \"\"\"\n \n np.random.seed(3)\n n_x = layer_sizes(X, Y)[0]\n n_y = layer_sizes(X, Y)[2]\n \n # Initialize parameters\n ### START CODE HERE ### (≈ 1 line of code)\n parameters = initialize_parameters(n_h=n_h, n_x=n_x, n_y=n_y)\n ### END CODE HERE ###\n \n # Loop (gradient descent)\n\n for i in range(0, num_iterations):\n \n ### START CODE HERE ### (≈ 4 lines of code)\n # Forward propagation. Inputs: \"X, parameters\". Outputs: \"A2, cache\".\n A2, cache = forward_propagation(parameters=parameters, X=X)\n \n # Cost function. Inputs: \"A2, Y, parameters\". Outputs: \"cost\".\n cost = compute_cost(A2=A2, parameters=parameters, Y=Y)\n \n # Backpropagation. Inputs: \"parameters, cache, X, Y\". Outputs: \"grads\".\n grads = backward_propagation(cache=cache, parameters=parameters, X=X, Y=Y)\n \n # Gradient descent parameter update. Inputs: \"parameters, grads\". Outputs: \"parameters\".\n parameters = update_parameters(grads=grads, parameters=parameters)\n \n ### END CODE HERE ###\n \n # Print the cost every 1000 iterations\n if print_cost and i % 1000 == 0:\n print (\"Cost after iteration %i: %f\" %(i, cost))\n\n return parameters",
"_____no_output_____"
],
[
"X_assess, Y_assess = nn_model_test_case()\nparameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=True)\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"Cost after iteration 0: 0.692739\nCost after iteration 1000: 0.000218\nCost after iteration 2000: 0.000107\nCost after iteration 3000: 0.000071\nCost after iteration 4000: 0.000053\nCost after iteration 5000: 0.000042\nCost after iteration 6000: 0.000035\nCost after iteration 7000: 0.000030\nCost after iteration 8000: 0.000026\nCost after iteration 9000: 0.000023\nW1 = [[-0.65848169 1.21866811]\n [-0.76204273 1.39377573]\n [ 0.5792005 -1.10397703]\n [ 0.76773391 -1.41477129]]\nb1 = [[ 0.287592 ]\n [ 0.3511264 ]\n [-0.2431246 ]\n [-0.35772805]]\nW2 = [[-2.45566237 -3.27042274 2.00784958 3.36773273]]\nb2 = [[ 0.20459656]]\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:90%\">\n\n<tr> \n <td> \n **cost after iteration 0**\n </td>\n <td> \n 0.692739\n </td>\n</tr>\n\n<tr> \n <td> \n <center> $\\vdots$ </center>\n </td>\n <td> \n <center> $\\vdots$ </center>\n </td>\n</tr>\n\n <tr>\n <td>**W1**</td>\n <td> [[-0.65848169 1.21866811]\n [-0.76204273 1.39377573]\n [ 0.5792005 -1.10397703]\n [ 0.76773391 -1.41477129]]</td> \n </tr>\n \n <tr>\n <td>**b1**</td>\n <td> [[ 0.287592 ]\n [ 0.3511264 ]\n [-0.2431246 ]\n [-0.35772805]] </td> \n </tr>\n \n <tr>\n <td>**W2**</td>\n <td> [[-2.45566237 -3.27042274 2.00784958 3.36773273]] </td> \n </tr>\n \n\n <tr>\n <td>**b2**</td>\n <td> [[ 0.20459656]] </td> \n </tr>\n \n</table> ",
"_____no_output_____"
],
[
"### 4.5 Predictions\n\n**Question**: Use your model to predict by building predict().\nUse forward propagation to predict results.\n\n**Reminder**: predictions = $y_{prediction} = \\mathbb 1 \\text{{activation > 0.5}} = \\begin{cases}\n 1 & \\text{if}\\ activation > 0.5 \\\\\n 0 & \\text{otherwise}\n \\end{cases}$ \n \nAs an example, if you would like to set the entries of a matrix X to 0 and 1 based on a threshold you would do: ```X_new = (X > threshold)```",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: predict\n\ndef predict(parameters, X):\n \"\"\"\n Using the learned parameters, predicts a class for each example in X\n \n Arguments:\n parameters -- python dictionary containing your parameters \n X -- input data of size (n_x, m)\n \n Returns\n predictions -- vector of predictions of our model (red: 0 / blue: 1)\n \"\"\"\n \n # Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold.\n ### START CODE HERE ### (≈ 2 lines of code)\n A2, cache = forward_propagation(parameters=parameters, X=X)\n predictor = np.vectorize(lambda x: int(x>0.5))\n predictions = predictor(A2)\n ### END CODE HERE ###\n \n return predictions",
"_____no_output_____"
],
[
"parameters, X_assess = predict_test_case()\n\npredictions = predict(parameters, X_assess)\nprint(\"predictions mean = \" + str(np.mean(predictions)))",
"predictions mean = 0.666666666667\n"
]
],
[
[
"**Expected Output**: \n\n\n<table style=\"width:40%\">\n <tr>\n <td>**predictions mean**</td>\n <td> 0.666666666667 </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"It is time to run the model and see how it performs on a planar dataset. Run the following code to test your model with a single hidden layer of $n_h$ hidden units.",
"_____no_output_____"
]
],
[
[
"# Build a model with a n_h-dimensional hidden layer\nparameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)\n\n# Plot the decision boundary\nplot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)\nplt.title(\"Decision Boundary for hidden layer size \" + str(4))",
"Cost after iteration 0: 0.693048\nCost after iteration 1000: 0.288083\nCost after iteration 2000: 0.254385\nCost after iteration 3000: 0.233864\nCost after iteration 4000: 0.226792\nCost after iteration 5000: 0.222644\nCost after iteration 6000: 0.219731\nCost after iteration 7000: 0.217504\nCost after iteration 8000: 0.219471\nCost after iteration 9000: 0.218612\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:40%\">\n <tr>\n <td>**Cost after iteration 9000**</td>\n <td> 0.218607 </td> \n </tr>\n \n</table>\n",
"_____no_output_____"
]
],
[
[
"# Print accuracy\npredictions = predict(parameters, X)\nprint ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')",
"Accuracy: 90%\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:15%\">\n <tr>\n <td>**Accuracy**</td>\n <td> 90% </td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"Accuracy is really high compared to Logistic Regression. The model has learnt the leaf patterns of the flower! Neural networks are able to learn even highly non-linear decision boundaries, unlike logistic regression. \n\nNow, let's try out several hidden layer sizes.",
"_____no_output_____"
],
[
"### 4.6 - Tuning hidden layer size (optional/ungraded exercise) ###\n\nRun the following code. It may take 1-2 minutes. You will observe different behaviors of the model for various hidden layer sizes.",
"_____no_output_____"
]
],
[
[
"# This may take about 2 minutes to run\n\nplt.figure(figsize=(16, 32))\nhidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]\nfor i, n_h in enumerate(hidden_layer_sizes):\n plt.subplot(5, 2, i+1)\n plt.title('Hidden Layer of size %d' % n_h)\n parameters = nn_model(X, Y, n_h, num_iterations = 5000)\n plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)\n predictions = predict(parameters, X)\n accuracy = float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100)\n print (\"Accuracy for {} hidden units: {} %\".format(n_h, accuracy))",
"Accuracy for 1 hidden units: 67.5 %\nAccuracy for 2 hidden units: 67.25 %\nAccuracy for 3 hidden units: 90.75 %\nAccuracy for 4 hidden units: 90.5 %\nAccuracy for 5 hidden units: 91.25 %\nAccuracy for 20 hidden units: 90.0 %\nAccuracy for 50 hidden units: 90.25 %\n"
]
],
[
[
"**Interpretation**:\n- The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models overfit the data. \n- The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits the data well without also incurring noticeable overfitting.\n- You will also learn later about regularization, which lets you use very large models (such as n_h = 50) without much overfitting. ",
"_____no_output_____"
],
[
"**Optional questions**:\n\n**Note**: Remember to submit the assignment by clicking the blue \"Submit Assignment\" button at the upper-right. \n\nSome optional/ungraded questions that you can explore if you wish: \n- What happens when you change the tanh activation for a sigmoid activation or a ReLU activation?\n- Play with the learning_rate. What happens?\n- What if we change the dataset? (See part 5 below!)",
"_____no_output_____"
],
[
"<font color='blue'>\n**You've learnt to:**\n- Build a complete neural network with a hidden layer\n- Make a good use of a non-linear unit\n- Implemented forward propagation and backpropagation, and trained a neural network\n- See the impact of varying the hidden layer size, including overfitting.",
"_____no_output_____"
],
[
"Nice work! ",
"_____no_output_____"
],
[
"## 5) Performance on other datasets",
"_____no_output_____"
],
[
"If you want, you can rerun the whole notebook (minus the dataset part) for each of the following datasets.",
"_____no_output_____"
]
],
[
[
"# Datasets\nnoisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()\n\ndatasets = {\"noisy_circles\": noisy_circles,\n \"noisy_moons\": noisy_moons,\n \"blobs\": blobs,\n \"gaussian_quantiles\": gaussian_quantiles}\n\n### START CODE HERE ### (choose your dataset)\ndataset = \"noisy_moons\"\n### END CODE HERE ###\n\nX, Y = datasets[dataset]\nX, Y = X.T, Y.reshape(1, Y.shape[0])\n\n# make blobs binary\nif dataset == \"blobs\":\n Y = Y%2\n\n# Visualize the data\nplt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);",
"_____no_output_____"
]
],
[
[
"Congrats on finishing this Programming Assignment!\n\nReference:\n- http://scs.ryerson.ca/~aharley/neural-networks/\n- http://cs231n.github.io/neural-networks-case-study/",
"_____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"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aac78e571f3db9c01c4dbcdc8666513db5b276f
| 5,081 |
ipynb
|
Jupyter Notebook
|
ipynb/Germany-Saarland-LK-Saarlouis.ipynb
|
oscovida/oscovida.github.io
|
c74d6da79feda1b5ccce107ad3acd48cf0e74c1c
|
[
"CC-BY-4.0"
] | 2 |
2020-06-19T09:16:14.000Z
|
2021-01-24T17:47:56.000Z
|
ipynb/Germany-Saarland-LK-Saarlouis.ipynb
|
oscovida/oscovida.github.io
|
c74d6da79feda1b5ccce107ad3acd48cf0e74c1c
|
[
"CC-BY-4.0"
] | 8 |
2020-04-20T16:49:49.000Z
|
2021-12-25T16:54:19.000Z
|
ipynb/Germany-Saarland-LK-Saarlouis.ipynb
|
oscovida/oscovida.github.io
|
c74d6da79feda1b5ccce107ad3acd48cf0e74c1c
|
[
"CC-BY-4.0"
] | 4 |
2020-04-20T13:24:45.000Z
|
2021-01-29T11:12:12.000Z
| 30.42515 | 183 | 0.523716 |
[
[
[
"# Germany: LK Saarlouis (Saarland)\n\n* Homepage of project: https://oscovida.github.io\n* Plots are explained at http://oscovida.github.io/plots.html\n* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Saarland-LK-Saarlouis.ipynb)",
"_____no_output_____"
]
],
[
[
"import datetime\nimport time\n\nstart = datetime.datetime.now()\nprint(f\"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}\")",
"_____no_output_____"
],
[
"%config InlineBackend.figure_formats = ['svg']\nfrom oscovida import *",
"_____no_output_____"
],
[
"overview(country=\"Germany\", subregion=\"LK Saarlouis\", weeks=5);",
"_____no_output_____"
],
[
"overview(country=\"Germany\", subregion=\"LK Saarlouis\");",
"_____no_output_____"
],
[
"compare_plot(country=\"Germany\", subregion=\"LK Saarlouis\", dates=\"2020-03-15:\");\n",
"_____no_output_____"
],
[
"# load the data\ncases, deaths = germany_get_region(landkreis=\"LK Saarlouis\")\n\n# get population of the region for future normalisation:\ninhabitants = population(country=\"Germany\", subregion=\"LK Saarlouis\")\nprint(f'Population of country=\"Germany\", subregion=\"LK Saarlouis\": {inhabitants} people')\n\n# compose into one table\ntable = compose_dataframe_summary(cases, deaths)\n\n# show tables with up to 1000 rows\npd.set_option(\"max_rows\", 1000)\n\n# display the table\ntable",
"_____no_output_____"
]
],
[
[
"# Explore the data in your web browser\n\n- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Saarland-LK-Saarlouis.ipynb)\n- and wait (~1 to 2 minutes)\n- Then press SHIFT+RETURN to advance code cell to code cell\n- See http://jupyter.org for more details on how to use Jupyter Notebook",
"_____no_output_____"
],
[
"# Acknowledgements:\n\n- Johns Hopkins University provides data for countries\n- Robert Koch Institute provides data for within Germany\n- Atlo Team for gathering and providing data from Hungary (https://atlo.team/koronamonitor/)\n- Open source and scientific computing community for the data tools\n- Github for hosting repository and html files\n- Project Jupyter for the Notebook and binder service\n- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))\n\n--------------------",
"_____no_output_____"
]
],
[
[
"print(f\"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and \"\n f\"deaths at {fetch_deaths_last_execution()}.\")",
"_____no_output_____"
],
[
"# to force a fresh download of data, run \"clear_cache()\"",
"_____no_output_____"
],
[
"print(f\"Notebook execution took: {datetime.datetime.now()-start}\")\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
4aac90c082285adef4ef8b90600e7251253baf41
| 23,576 |
ipynb
|
Jupyter Notebook
|
notebooks/Multiple comparison corrections.ipynb
|
gbrookshire/simulated_rhythmic_sampling
|
5c9ed507847a75dbe38d10d78b54441ae83f5831
|
[
"MIT"
] | null | null | null |
notebooks/Multiple comparison corrections.ipynb
|
gbrookshire/simulated_rhythmic_sampling
|
5c9ed507847a75dbe38d10d78b54441ae83f5831
|
[
"MIT"
] | null | null | null |
notebooks/Multiple comparison corrections.ipynb
|
gbrookshire/simulated_rhythmic_sampling
|
5c9ed507847a75dbe38d10d78b54441ae83f5831
|
[
"MIT"
] | null | null | null | 62.869333 | 10,420 | 0.706566 |
[
[
[
"# Correcting for multiple comparisons\n\nGeoffrey Brookshire\n\nHere we test how the AR surrogate and robust est. analyses behave when correcting for multiple comparisons using cluster-based permutation tests, Bonferroni corrections, and correcting with the False Discovery Rate (FDR).",
"_____no_output_____"
]
],
[
[
"# Import libraries and set up analyses\n%matplotlib inline\n\nimport os\nos.chdir('..')",
"_____no_output_____"
],
[
"import yaml\nimport copy\nimport itertools\nimport numpy as np\nfrom scipy import signal, stats\nimport matplotlib.pyplot as plt\nimport analysis\nimport simulate_behavior as behav\nimport simulate_experiments as sim_exp\nfrom analysis_methods import shuff_time, alternatives, utils\nfrom generate_plots import remove_topright_axes\nfrom stat_report_helpers import chi_square_report\n\n# Suppress maximum likelihood estimation convergence warnings\nimport warnings\nfrom statsmodels.tools.sm_exceptions import ConvergenceWarning\nwarnings.simplefilter('ignore', ConvergenceWarning)\n\nUSE_CACHE = True # Whether to use previously-saved simulations\n\nbehav_details = yaml.safe_load(open('behav_details.yaml'))\n\nplt.ion()\n\nplot_dir = 'plots/'\nn_exp = 1000\nbehav_kwargs = {'noise_method': 'powerlaw',\n 'exponent': 2}\nosc_parameters = {'Rand walk': {'f_osc': 0, 'osc_amp': 0},\n 'Rand walk + osc': {'f_osc': 6, 'osc_amp': 0.4}}\nmethod_names = {'Robust est': 'mann_lees',\n 'AR surr': 'ar'}\n\ncolors = {'Rand walk': 'red',\n 'Rand walk + osc': 'dodgerblue'}",
"_____no_output_____"
],
[
"osc_parameters = {'Rand walk': {'f_osc': 0, 'osc_amp': 0},\n 'Rand walk + osc': {'f_osc': 6, 'osc_amp': 0.4}}\ncorrection_methods = ('Cluster', 'Bonferroni', 'FDR')\nexp_functions = {'Robust est': sim_exp.robust_est_experiment,\n 'AR surr': sim_exp.ar_experiment}\nprop_signif = {}\n\nfor osc_label, osc_params in osc_parameters.items():\n prop_signif[osc_label] = {}\n \n for analysis_meth, exp_fnc in exp_functions.items():\n prop_signif[osc_label][analysis_meth] = {}\n\n for correction in correction_methods:\n \n # Can't run a cluster test on robust est.\n if analysis_meth == 'Robust est' and correction == 'Cluster':\n continue\n\n if correction == 'Cluster': # Re-use main data for cluster\n desc = ''\n else:\n desc = f'-{correction}'\n\n def analysis_fnc(**behav_kwargs):\n \"\"\" Helper function\n \"\"\"\n res = exp_fnc(correction=correction.lower(),\n **behav_kwargs)\n return res\n\n if USE_CACHE or correction == 'Cluster':\n lit = analysis.load_simulation(method_names[analysis_meth],\n desc=desc,\n **behav_kwargs,\n **osc_params)\n\n else:\n\n lit = analysis.simulate_lit(analysis_fnc, n_exp,\n desc=desc,\n **behav_kwargs,\n **osc_params)\n analysis.save_simulation(lit,\n method_names[analysis_meth],\n desc=desc,\n **behav_kwargs,\n **osc_params)\n\n p = analysis.prop_sig(lit)\n prop_signif[osc_label][analysis_meth][correction] = p",
"loading: results/mann_lees_exp_2.00_f_0.00_amp_0.00-Bonferroni.npy\nloading: results/mann_lees_exp_2.00_f_0.00_amp_0.00-FDR.npy\nloading: results/ar_exp_2.00_f_0.00_amp_0.00.npy\nloading: results/ar_exp_2.00_f_0.00_amp_0.00-Bonferroni.npy\nloading: results/ar_exp_2.00_f_0.00_amp_0.00-FDR.npy\nloading: results/mann_lees_exp_2.00_f_6.00_amp_0.40-Bonferroni.npy\nloading: results/mann_lees_exp_2.00_f_6.00_amp_0.40-FDR.npy\nloading: results/ar_exp_2.00_f_6.00_amp_0.40.npy\nloading: results/ar_exp_2.00_f_6.00_amp_0.40-Bonferroni.npy\nloading: results/ar_exp_2.00_f_6.00_amp_0.40-FDR.npy\n"
],
[
"def prop_ci(p, n):\n \"\"\" 95% CI of a proportion\n \"\"\"\n return 1.96 * np.sqrt((p * (1 - p)) / n)\n\nfig, axes = plt.subplots(1, 2,\n gridspec_kw={'width_ratios': [1, 1]},\n figsize=(4, 3))\n\nfor i_plot, analysis_meth in enumerate(exp_functions.keys()):\n plt.subplot(axes[i_plot])\n plt.title(analysis_meth)\n plt.axhline(y=0.05, color='k', linestyle='--')\n for osc_label in osc_parameters.keys():\n psig = prop_signif[osc_label][analysis_meth]\n labels = psig.keys()\n x_pos = np.arange(float(len(psig)))\n psig = np.array(list(psig.values()))\n plt.errorbar(x_pos, psig,\n yerr=prop_ci(psig, n_exp),\n fmt='o',\n color=colors[osc_label],\n label=osc_label)\n plt.xticks(x_pos, labels, rotation=45)\n plt.xlim([-0.5, len(psig) - 0.5])\n plt.ylim(0, 1.05)\n plt.ylabel('Prop. signif.')\n remove_topright_axes()\nplt.tight_layout()\nplt.savefig(f\"{plot_dir}mult_comp_corrections.eps\")",
"_____no_output_____"
]
],
[
[
"These plots show the proportion of significant oscillations identified for each method of multiple comparisons correction. The false positive rate for each method is reflected in the proportion of significant results when the data were simulated as a random walk (in blue). The true positive rate (analogous to experimental power, assuming certain characteristics of the signal) is reflected in the proportion of significant results when the data were simulated as a random walk plus an oscillation (in orange).",
"_____no_output_____"
],
[
"## Statistical tests\n\n### Differences between methods for multiple comparisons correction\n\nWe can test for differences in performance between the different methods of adjusting for multiple comparisons.",
"_____no_output_____"
],
[
"First, test whether the choice of multiple comparison influences the rate of positive results for the AR surrogate analysis.",
"_____no_output_____"
]
],
[
[
"analysis_meth = 'AR surr'\nfor osc_label in osc_parameters.keys():\n print('-', osc_label)\n psig = prop_signif[osc_label][analysis_meth]\n labels = psig.keys()\n tbl = []\n for mult_comp_meth, p in psig.items():\n row = [int(p * n_exp), int((1 - p) * n_exp)]\n tbl.append(row)\n tbl = np.array(tbl)\n msg = chi_square_report(tbl)\n print(' ' + msg)",
"- Rand walk\n $\\chi^2(2) = 14.0$, $p = 0.0009$, $\\phi_C = 0.07$ [0.04, 0.10]\n- Rand walk + osc\n $\\chi^2(2) = 55.0$, $p = 1 \\times 10^{-12}$, $\\phi_C = 0.14$ [0.10, 0.17]\n"
]
],
[
[
"Next, test for pairwise differences between multiple comparisons methods within each analysis method and signal type.",
"_____no_output_____"
]
],
[
[
"for analysis_meth in exp_functions.keys():\n print(analysis_meth)\n for osc_label in osc_parameters.keys():\n print('-', osc_label)\n psig = prop_signif[osc_label][analysis_meth]\n labels = psig.keys()\n for comp in itertools.combinations(labels, 2):\n # Make a contingency table\n p0 = psig[comp[0]]\n p1 = psig[comp[1]]\n tbl = [[p0 * n_exp, p1 * n_exp],\n [(1 - p0) * n_exp, (1 - p1) * n_exp]]\n tbl = np.array(tbl)\n msg = f' - {comp[0][:3]} vs {comp[1][:3]}: '\n msg += chi_square_report(tbl)\n print(msg)",
"Robust est\n- Rand walk\n - Bon vs FDR: $\\chi^2(1) = 0.2$, $p = 0.7$, $\\phi_C = 0.01$ [0.00, 0.06]\n- Rand walk + osc\n - Bon vs FDR: $\\chi^2(1) = 0.5$, $p = 0.5$, $\\phi_C = 0.02$ [0.00, 0.06]\nAR surr\n- Rand walk\n - Clu vs Bon: $\\chi^2(1) = 10.5$, $p = 0.001$, $\\phi_C = 0.07$ [0.03, 0.12]\n - Clu vs FDR: $\\chi^2(1) = 11.1$, $p = 0.0009$, $\\phi_C = 0.08$ [0.03, 0.12]\n - Bon vs FDR: $\\chi^2(1) = 0.0$, $p = 1$, $\\phi_C = 0.00$ [0.00, 0.05]\n- Rand walk + osc\n - Clu vs Bon: $\\chi^2(1) = 34.0$, $p = 6 \\times 10^{-09}$, $\\phi_C = 0.13$ [0.10, 0.16]\n - Clu vs FDR: $\\chi^2(1) = 26.1$, $p = 3 \\times 10^{-07}$, $\\phi_C = 0.12$ [0.08, 0.15]\n - Bon vs FDR: $\\chi^2(1) = 0.6$, $p = 0.5$, $\\phi_C = 0.02$ [0.00, 0.07]\n"
]
],
[
[
"### Comparing false positives against alpha = 0.05\n\nDoes each method have a rate of false positives higher than 0.05? If so, that method does not adequately control the rate of false positives.",
"_____no_output_____"
]
],
[
[
"for analysis_meth in exp_functions.keys():\n print(analysis_meth)\n psig = prop_signif['Rand walk'][analysis_meth]\n labels = psig.keys()\n for mc_meth, prop in psig.items():\n pval = stats.binom_test(prop * n_exp,\n n_exp,\n 0.05,\n alternative = 'greater')\n msg = f'- {mc_meth[:3]}: {prop:.2f}, '\n msg += f'p = {pval:.0e}'\n if prop > 0.05 and pval < 0.05:\n msg += ' *'\n print(msg)",
"Robust est\n- Bon: 0.03, p = 1e+00\n- FDR: 0.02, p = 1e+00\nAR surr\n- Clu: 0.04, p = 8e-01\n- Bon: 0.08, p = 3e-05 *\n- FDR: 0.08, p = 2e-05 *\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aac929746366a071bd17aa0fbcc2f0e285ccc18
| 2,174 |
ipynb
|
Jupyter Notebook
|
notebooks/week2_challenge.ipynb
|
kmendler/202110-data-science-python
|
f290ce2cca701243d6e75d9c8bde953d1092664d
|
[
"Apache-2.0"
] | 1 |
2022-02-24T20:20:01.000Z
|
2022-02-24T20:20:01.000Z
|
notebooks/week2_challenge.ipynb
|
kmendler/202110-data-science-python
|
f290ce2cca701243d6e75d9c8bde953d1092664d
|
[
"Apache-2.0"
] | 1 |
2022-03-09T10:48:13.000Z
|
2022-03-09T10:48:13.000Z
|
notebooks/week2_challenge.ipynb
|
kmendler/202110-data-science-python
|
f290ce2cca701243d6e75d9c8bde953d1092664d
|
[
"Apache-2.0"
] | 3 |
2022-02-27T16:16:16.000Z
|
2022-03-09T10:43:43.000Z
| 43.48 | 325 | 0.676173 |
[
[
[
"# Week 2 - Course challenge\n\nThe aim of this optional activity is to apply the learnings from the course to a dataset of research interest to the participant or alternatively one of the datasets provided below\n\nDuring the rest of the course, individual partipants or participants working as part of small teams will analyse, visualise and apply modelling concepts to the selected dataset. Partipants are invited to apply the concepts learned throughout the course and developed them through further using the selected dataset. \n\nTowards the end of the course (week 7), partipants will be asked to share a short summary of their work with the tutors and those interested will be invited to present their work to the rest of the class\n\nThe two example datasets were provided by Guillaume Desachy from AZ who took them from the study [Ternès et al. 2016](https://onlinelibrary.wiley.com/doi/10.1002/bimj.201500234), which aims at studying gene expression from 614 breast cancer patients treated with adjuvant chemotherapy. The datasets are:\n\n- `clinical.csv`: this is survival data from a breast cancer control trial where the variables are:\n - Treatment: coded as 0 (Standard of care) and 1 (Standard of care + Chemotherapy)\n - Status: coded as 0 (censoring) and 1 (event)\n - Time: time of event or censoring\n \n- `omics.csv`: this is RNA microarray data, centered and scaled, for 1691 gene probes\n\nAlternatively, participants can also use the METABRIC dataset presented during the course",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown"
]
] |
4aac978d5490d0d5a3d929f88e83742a252dbeb3
| 1,054 |
ipynb
|
Jupyter Notebook
|
python_modules/dagstermill/dagstermill/examples/notebooks/hello_world_explicit_yield.ipynb
|
bambielli-flex/dagster
|
30b75ba7c62fc536bc827f177c1dc6ba20f5ae20
|
[
"Apache-2.0"
] | null | null | null |
python_modules/dagstermill/dagstermill/examples/notebooks/hello_world_explicit_yield.ipynb
|
bambielli-flex/dagster
|
30b75ba7c62fc536bc827f177c1dc6ba20f5ae20
|
[
"Apache-2.0"
] | null | null | null |
python_modules/dagstermill/dagstermill/examples/notebooks/hello_world_explicit_yield.ipynb
|
bambielli-flex/dagster
|
30b75ba7c62fc536bc827f177c1dc6ba20f5ae20
|
[
"Apache-2.0"
] | null | null | null | 17 | 47 | 0.514231 |
[
[
[
"import dagstermill as dm",
"_____no_output_____"
],
[
"dm.yield_result('A result')",
"_____no_output_____"
],
[
"# dm.yield_expectation()",
"_____no_output_____"
],
[
"dm.yield_materialization('/path/to/file')",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4aac9af54801b964342c9420d9931266bff77db6
| 271,810 |
ipynb
|
Jupyter Notebook
|
dump/notebooks/single_atom_training_Co_pretrained.ipynb
|
abekipnis/Atom_manipulation_with_RL_new
|
d7f74f5b40e28677f100aa687adb76dea496f269
|
[
"MIT"
] | null | null | null |
dump/notebooks/single_atom_training_Co_pretrained.ipynb
|
abekipnis/Atom_manipulation_with_RL_new
|
d7f74f5b40e28677f100aa687adb76dea496f269
|
[
"MIT"
] | null | null | null |
dump/notebooks/single_atom_training_Co_pretrained.ipynb
|
abekipnis/Atom_manipulation_with_RL_new
|
d7f74f5b40e28677f100aa687adb76dea496f269
|
[
"MIT"
] | 2 |
2022-02-16T08:37:08.000Z
|
2022-02-16T09:25:48.000Z
| 481.079646 | 27,008 | 0.934042 |
[
[
[
"import importlib\nfrom matplotlib import pyplot as plt\nplt.plot([1,2,3])\nfrom IPython.display import clear_output\nimport matplotlib\nimport numpy as np\nimport pandas as pd\nimport pdb\nimport time\nfrom collections import deque\nimport torch\nimport cv2\nfrom Environment.Env import RealExpEnv\nfrom RL.sac import sac_agent, ReplayMemory\nfrom Environment.data_visualization import plot_graph, show_reset, show_done, show_step\nfrom Environment.episode_memory import Episode_Memory\nfrom Environment.get_atom_coordinate import atom_detection, blob_detection, get_atom_coordinate_nm\nfrom skimage import morphology, measure\nfrom Environment.createc_control import Createc_Controller\nimport glob\nfrom collections import deque\nmatplotlib.rcParams['image.cmap'] = 'gray'\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nprint(device)",
"cpu\n"
],
[
"##Define anchor template\ncreatec_controller = Createc_Controller(None, None, None, None)\nimg_forward = np.array(createc_controller.stm.scandata(1,4))\nprint(img_forward.shape)\ntop_left, w, h = (4,4), 14, 14\ntemplate = img_forward[top_left[1]:top_left[1]+h, top_left[0]:top_left[0]+w]\nplt.imshow(template)\n",
"succeed to connect\n(128, 128)\n"
],
[
"step_nm = 0.4\nmax_mvolt = 15 #min_mvolt = 0.5*max_mvolt\nmax_pcurrent_to_mvolt_ratio = 6E3 # min = 0.5*max\ngoal_nm = 2\ncurrent_jump = 4\nim_size_nm = 10.027\nDactoA = float(createc_controller.stm.getparam('Dacto[A]xy'))\nGain = float(createc_controller.stm.getparam(\"GainX\"))\nprint('gain:', Gain)\noffset_x = -float(createc_controller.stm.getparam('OffsetX'))*DactoA*Gain/10\noffset_y = -float(createc_controller.stm.getparam('OffsetY'))*DactoA*Gain/10\nprint(offset_x, offset_y)\nprint(float(createc_controller.stm.getparam('PlanDx')), float(createc_controller.stm.getparam('PlanDy')))\noffset_x -= float(createc_controller.stm.getparam('PlanDx'))\noffset_y -= float(createc_controller.stm.getparam('PlanDy'))\n\nprint(offset_x, offset_y)\noffset_nm = np.array([190.386,-13.5])\npixel = 128\nmanip_limit_nm = np.array([189, 195, -11, -5]) #[left, right, up, down]\ntemplate_max_y = 25\ntemplate_min_x = None\nscan_mV = 1000\nmax_len = 5\nenv = RealExpEnv(step_nm, max_mvolt, max_pcurrent_to_mvolt_ratio, goal_nm, \n template, current_jump, im_size_nm, offset_nm, manip_limit_nm, pixel, \n template_max_y, template_min_x, scan_mV, max_len)\n",
"gain: 10.0\n191.53506700000003 -13.581448\n-0.09 -0.138\n191.62506700000003 -13.443448\nsucceed to connect\n"
],
[
"batch_size= 64\nLEARNING_RATE = 0.0003\nreplay_size=1000000\n#initialize sac_agent\nagent = sac_agent(num_inputs = 4, num_actions = 6, action_space = None, device=device, hidden_size=256, lr=LEARNING_RATE,\n gamma=0.9, tau=0.005, alpha=0.0973)\n#load pretrained parameters\nagent.critic.load_state_dict(torch.load('training_4/reward_2_critic_{}.pth'.format(3000)))\nagent.policy.load_state_dict(torch.load('training_4/reward_2_policy_{}.pth'.format(3000)))\nagent.alpha = torch.load('training_4/reward_2_alpha_{}.pth'.format(3000))\nmemory = ReplayMemory(replay_size)\n#, map_location=torch.device('cpu')",
"_____no_output_____"
],
[
"episode_memory = Episode_Memory()",
"_____no_output_____"
],
[
"scores_array = []\navg_scores_array = []\n\nalpha = []\ntemp_nm = []\nc_k_min = 2500\neta_0 = 0.996\neta_T = 1.0\nn_interactions = 500\nmax_ep_len = 5\ndef sac_train(max_steps, num_episodes = 50, episode_start = 0):\n global added_episode\n for i_episode in range(episode_start,episode_start+num_episodes):\n print('Episode:', i_episode)\n eta_t = np.minimum(eta_0 + (eta_T - eta_0)*(i_episode/n_interactions), eta_T)\n episode_reward = 0\n episode_steps = 0\n done = False\n state, info = env.reset()\n show_reset(env.img_info['img_forward'], env.img_info['offset_nm'], env.img_info['len_nm'], \n env.atom_start_absolute_nm, env.destination_absolute_nm, env.template_nm, env.template_wh)\n print('old value:',env.old_value)\n #print(env.atom_absolute_nm)\n episode_memory.update_memory_reset(env.img_info, i_episode, info)\n temp_nm.append(env.template_nm)\n for step in range(max_steps):\n print('step:', step)\n action = agent.select_action(state)\n atom_absolute_nm = env.atom_absolute_nm\n next_state, reward, done, info = env.step(action)\n print(reward)\n #print(action, done, reward)\n episode_steps+=1\n episode_reward+=reward\n mask = float(not done)\n memory.push(state,action,reward,next_state,mask)\n episode_memory.update_memory_step(state, action, next_state, reward, done, info)\n state=next_state\n show_step(env.img_info['img_forward'], env.img_info['offset_nm'], env.img_info['len_nm'], \n info['start_nm']+atom_absolute_nm, info['end_nm']+atom_absolute_nm,\n env.atom_absolute_nm, env.atom_start_absolute_nm, env.destination_absolute_nm, \n env.template_nm, env.template_wh, action[4]*env.max_mvolt, \n action[5]*env.max_pcurrent_to_mvolt_ratio*action[4]*env.max_mvolt)\n print('template_nm',env.template_nm)\n temp_nm.append(env.template_nm)\n if done:\n episode_memory.update_memory_done(env.img_info, env.atom_absolute_nm, env.atom_relative_nm)\n episode_memory.save_memory('training_4')\n new_destination_absolute_nm = None\n atom_to_start = env.atom_relative_nm - env.atom_start_relative_nm\n print('atom moved by:', np.linalg.norm(atom_to_start))\n print('Episode reward:', episode_reward)\n show_done(env.img_info['img_forward'], env.img_info['offset_nm'], env.img_info['len_nm'], env.atom_absolute_nm, env.atom_start_absolute_nm, env.destination_absolute_nm, env.template_nm, env.template_wh, reward, new_destination_absolute_nm)\n \n break\n \n if (len(memory)>batch_size):\n if i_episode>100:\n train_pi = True\n else:\n train_pi = True\n episode_K = int(episode_steps)\n for k in range(episode_K):\n c_k = max(int(memory.__len__()*eta_t**(k*(max_ep_len/episode_K))), c_k_min)\n #c_k = memory.__len__()\n print('TRAINING!')\n agent.update_parameters(memory, batch_size, c_k, train_pi)\n \n scores_array.append(episode_reward)\n if len(scores_array)>100:\n avg_scores_array.append(np.mean(scores_array[-100:]))\n else:\n avg_scores_array.append(np.mean(scores_array))\n print(agent.alpha)\n alpha.append(agent.alpha)\n \n if (i_episode+1)%2==0:\n plot_graph(scores_array,avg_scores_array)\n if (i_episode)%20 == 0:\n torch.save(agent.critic.state_dict(), 'training_4/reward_2_critic_{}.pth'.format(i_episode))\n torch.save(agent.policy.state_dict(), 'training_4/reward_2_policy_{}.pth'.format(i_episode))\n torch.save(agent.alpha, 'training_4/reward_2_alpha_{}.pth'.format(i_episode))\n",
"_____no_output_____"
],
[
"env.atom_absolute_nm = None",
"_____no_output_____"
],
[
"sac_train(max_steps=max_len, episode_start = 0,num_episodes = 1000)",
"_____no_output_____"
]
],
[
[
"@1700 change max_ep_len from 50 to 5\n@1826 change cut off distance from 0.28 nm to 0.14 nm\n@1850 pause for taking bench mark and change cutoff distance to 0.1 nm\n@2092 change upper cutoff from self.goal_nm to 1.5*self.goal_nm\n@2106 change to 128 pixel\n@2138 chnge to check_similarity with absolute coordinates\n@2216 system crash, restart computer and tip",
"_____no_output_____"
]
],
[
[
"def save_buffer(buffer):\n state, action, reward, next_state, done = map(np.stack,zip(*memory.buffer))\n np.save('state.npy',state)\n np.save('action.npy',action)\n np.save('reward.npy',reward)\n np.save('next_state.npy', next_state)\n np.save('done.npy', done)\nsave_buffer(memory.buffer)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aacadb37fa99fa131c112de16ded92e90d32eb2
| 14,247 |
ipynb
|
Jupyter Notebook
|
tutorial/source/jit.ipynb
|
fehiepsi/pyro
|
c2a88c3c3c2ff58802026377c08be7f7c8e59785
|
[
"MIT"
] | null | null | null |
tutorial/source/jit.ipynb
|
fehiepsi/pyro
|
c2a88c3c3c2ff58802026377c08be7f7c8e59785
|
[
"MIT"
] | 1 |
2017-12-15T14:01:01.000Z
|
2017-12-17T03:09:06.000Z
|
tutorial/source/jit.ipynb
|
fehiepsi/pyro
|
c2a88c3c3c2ff58802026377c08be7f7c8e59785
|
[
"MIT"
] | null | null | null | 35.440299 | 882 | 0.593248 |
[
[
[
"# Using the PyTorch JIT Compiler with Pyro\n\nThis tutorial shows how to use the PyTorch [jit compiler](https://pytorch.org/docs/master/jit.html) in Pyro models.\n\n#### Summary:\n- You can use compiled functions in Pyro models.\n- You cannot use pyro primitives inside compiled functions.\n- If your model has static structure, you can use a `Jit*` version of an `ELBO` algorithm, e.g.\n ```diff\n - Trace_ELBO()\n + JitTrace_ELBO()\n ```\n- The [HMC](http://docs.pyro.ai/en/dev/mcmc.html#pyro.infer.mcmc.HMC) and [NUTS](http://docs.pyro.ai/en/dev/mcmc.html#pyro.infer.mcmc.NUTS) classes accept `jit_compile=True` kwarg.\n- Models should input all tensors as `*args` and all non-tensors as `**kwargs`.\n- Each different value of `**kwargs` triggers a separate compilation.\n- Use `**kwargs` to specify all variation in structure (e.g. time series length).\n- To ignore jit warnings in safe code blocks, use `with pyro.util.ignore_jit_warnings():`.\n- To ignore all jit warnings in `HMC` or `NUTS`, pass `ignore_jit_warnings=True`.\n\n#### Table of contents\n- [Introduction](#Introduction)\n- [A simple model](#A-simple-model)\n- [Varying structure](#Varying-structure)",
"_____no_output_____"
]
],
[
[
"import os\nimport torch\nimport pyro\nimport pyro.distributions as dist\nfrom torch.distributions import constraints\nfrom pyro import poutine\nfrom pyro.distributions.util import broadcast_shape\nfrom pyro.infer import Trace_ELBO, JitTrace_ELBO, TraceEnum_ELBO, JitTraceEnum_ELBO, SVI\nfrom pyro.infer.mcmc import MCMC, NUTS\nfrom pyro.contrib.autoguide import AutoDiagonalNormal\nfrom pyro.optim import Adam\n\nsmoke_test = ('CI' in os.environ)\nassert pyro.__version__.startswith('0.3.0')\npyro.enable_validation(True) # <---- This is always a good idea!",
"_____no_output_____"
]
],
[
[
"\n## Introduction\n\nPyTorch 1.0 includes a [jit compiler](https://pytorch.org/docs/master/jit.html) to speed up models. You can think of compilation as a \"static mode\", whereas PyTorch usually operates in \"eager mode\".\n\nPyro supports the jit compiler in two ways. First you can use compiled functions inside Pyro models (but those functions cannot contain Pyro primitives). Second, you can use Pyro's jit inference algorithms to compile entire inference steps; in static models this can reduce the Python overhead of Pyro models and speed up inference.\n\nThe rest of this tutorial focuses on Pyro's jitted inference algorithms: [JitTrace_ELBO](http://docs.pyro.ai/en/dev/inference_algos.html#pyro.infer.trace_elbo.JitTrace_ELBO), [JitTraceGraph_ELBO](http://docs.pyro.ai/en/dev/inference_algos.html#pyro.infer.tracegraph_elbo.JitTraceGraph_ELBO), [JitTraceEnum_ELBO](http://docs.pyro.ai/en/dev/inference_algos.html#pyro.infer.traceenum_elbo.JitTraceEnum_ELBO), [JitMeanField_ELBO](http://docs.pyro.ai/en/dev/inference_algos.html#pyro.infer.trace_mean_field_elbo.JitTraceMeanField_ELBO), [HMC(jit_compile=True)](http://docs.pyro.ai/en/dev/mcmc.html#pyro.infer.mcmc.HMC), and [NUTS(jit_compile=True)](http://docs.pyro.ai/en/dev/mcmc.html#pyro.infer.mcmc.NUTS). For further reading, see the [examples/](https://github.com/uber/pyro/tree/dev/examples) directory, where most examples include a `--jit` option to run in compiled mode.\n\n## A simple model\n\nLet's start with a simple Gaussian model and an [autoguide](http://docs.pyro.ai/en/dev/contrib.autoguide.html).",
"_____no_output_____"
]
],
[
[
"def model(data):\n loc = pyro.sample(\"loc\", dist.Normal(0., 10.))\n scale = pyro.sample(\"scale\", dist.LogNormal(0., 3.))\n with pyro.plate(\"data\", data.size(0)):\n pyro.sample(\"obs\", dist.Normal(loc, scale), obs=data)\n\nguide = AutoDiagonalNormal(model)\n\ndata = dist.Normal(0.5, 2.).sample((100,))",
"_____no_output_____"
]
],
[
[
"First let's run as usual with an SVI object and `Trace_ELBO`.",
"_____no_output_____"
]
],
[
[
"%%time\npyro.clear_param_store()\nelbo = Trace_ELBO()\nsvi = SVI(model, guide, Adam({'lr': 0.01}), elbo)\nfor i in range(2 if smoke_test else 1000):\n svi.step(data)",
"CPU times: user 2.71 s, sys: 31.4 ms, total: 2.74 s\nWall time: 2.76 s\n"
]
],
[
[
"Next to run with a jit compiled inference, we simply replace\n```diff\n- elbo = Trace_ELBO()\n+ elbo = JitTrace_ELBO()\n```\nAlso note that the `AutoDiagonalNormal` guide behaves a little differently on its first invocation (it runs the model to produce a prototype trace), and we don't want to record this warmup behavior when compiling. Thus we call the `guide(data)` once to initialize, then run the compiled SVI,",
"_____no_output_____"
]
],
[
[
"%%time\npyro.clear_param_store()\n\nguide(data) # Do any lazy initialization before compiling.\n\nelbo = JitTrace_ELBO()\nsvi = SVI(model, guide, Adam({'lr': 0.01}), elbo)\nfor i in range(2 if smoke_test else 1000):\n svi.step(data)",
"CPU times: user 1.1 s, sys: 30.4 ms, total: 1.13 s\nWall time: 1.16 s\n"
]
],
[
[
"Notice that we have a more than 2x speedup for this small model.\n\nLet us now use the same model, but we will instead use MCMC to generate samples from the model's posterior. We will use the No-U-Turn(NUTS) sampler.",
"_____no_output_____"
]
],
[
[
"%%time\nnuts_kernel = NUTS(model)\npyro.set_rng_seed(1)\nmcmc_run = MCMC(nuts_kernel, num_samples=100).run(data)",
"_____no_output_____"
]
],
[
[
"We can compile the potential energy computation in NUTS using the `jit_compile=True` argument to the NUTS kernel. We also silence JIT warnings due to the presence of tensor constants in the model by using `ignore_jit_warnings=True`.",
"_____no_output_____"
]
],
[
[
"%%time\nnuts_kernel = NUTS(model, jit_compile=True, ignore_jit_warnings=True)\npyro.set_rng_seed(1)\nmcmc_run = MCMC(nuts_kernel, num_samples=100).run(data)",
"_____no_output_____"
]
],
[
[
"We notice a significant increase in sampling throughput when JIT compilation is enabled.",
"_____no_output_____"
],
[
"## Varying structure\n\nTime series models often run on datasets of multiple time series with different lengths. To accomodate varying structure like this, Pyro requires models to separate all model inputs into tensors and non-tensors.$^\\dagger$\n\n- Non-tensor inputs should be passed as `**kwargs` to the model and guide. These can determine model structure, so that a model is compiled for each value of the passed `**kwargs`.\n- Tensor inputs should be passed as `*args`. These must not determine model structure. However `len(args)` may determine model structure (as is used e.g. in semisupervised models).\n\nTo illustrate this with a time series model, we will pass in a sequence of observations as a tensor `arg` and the sequence length as a non-tensor `kwarg`:",
"_____no_output_____"
]
],
[
[
"def model(sequence, num_sequences, length, state_dim=16):\n # This is a Gaussian HMM model.\n with pyro.plate(\"states\", state_dim):\n trans = pyro.sample(\"trans\", dist.Dirichlet(0.5 * torch.ones(state_dim)))\n emit_loc = pyro.sample(\"emit_loc\", dist.Normal(0., 10.))\n emit_scale = pyro.sample(\"emit_scale\", dist.LogNormal(0., 3.))\n\n # We're doing manual data subsampling, so we need to scale to actual data size.\n with poutine.scale(scale=num_sequences):\n # We'll use enumeration inference over the hidden x.\n x = 0\n for t in pyro.markov(range(length)):\n x = pyro.sample(\"x_{}\".format(t), dist.Categorical(trans[x]),\n infer={\"enumerate\": \"parallel\"})\n pyro.sample(\"y_{}\".format(t), dist.Normal(emit_loc[x], emit_scale),\n obs=sequence[t])\n\nguide = AutoDiagonalNormal(poutine.block(model, expose=[\"trans\", \"emit_scale\", \"emit_loc\"]))\n\n# This is fake data of different lengths.\nlengths = [24] * 50 + [48] * 20 + [72] * 5\nsequences = [torch.randn(length) for length in lengths]",
"_____no_output_____"
]
],
[
[
"Now lets' run SVI as usual.",
"_____no_output_____"
]
],
[
[
"%%time\npyro.clear_param_store()\nelbo = TraceEnum_ELBO(max_plate_nesting=1)\nsvi = SVI(model, guide, Adam({'lr': 0.01}), elbo)\nfor i in range(1 if smoke_test else 10):\n for sequence in sequences:\n svi.step(sequence, # tensor args\n num_sequences=len(sequences), length=len(sequence)) # non-tensor args",
"CPU times: user 52.4 s, sys: 270 ms, total: 52.7 s\nWall time: 52.8 s\n"
]
],
[
[
"Again we'll simply swap in a `Jit*` implementation\n```diff\n- elbo = TraceEnum_ELBO(max_plate_nesting=1)\n+ elbo = JitTraceEnum_ELBO(max_plate_nesting=1)\n```\nNote that we are manually specifying the `max_plate_nesting` arg. Usually Pyro can figure this out automatically by running the model once on the first invocation; however to avoid this extra work when we run the compiler on the first step, we pass this in manually.",
"_____no_output_____"
]
],
[
[
"%%time\npyro.clear_param_store()\n\n# Do any lazy initialization before compiling.\nguide(sequences[0], num_sequences=len(sequences), length=len(sequences[0]))\n\nelbo = JitTraceEnum_ELBO(max_plate_nesting=1)\nsvi = SVI(model, guide, Adam({'lr': 0.01}), elbo)\nfor i in range(1 if smoke_test else 10):\n for sequence in sequences:\n svi.step(sequence, # tensor args\n num_sequences=len(sequences), length=len(sequence)) # non-tensor args",
"CPU times: user 21.9 s, sys: 201 ms, total: 22.1 s\nWall time: 22.2 s\n"
]
],
[
[
"Again we see more than 2x speedup. Note that since there were three different sequence lengths, compilation was triggered three times.\n\n$^\\dagger$ Note this section is only valid for SVI, and HMC/NUTS assume fixed model arguments.",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aacb49d1f1b59bfda3d6086a13a41d78824fd72
| 3,131 |
ipynb
|
Jupyter Notebook
|
notebooks/Geometry.ipynb
|
jtpio/xleaflet
|
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
|
[
"BSD-3-Clause"
] | null | null | null |
notebooks/Geometry.ipynb
|
jtpio/xleaflet
|
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
|
[
"BSD-3-Clause"
] | null | null | null |
notebooks/Geometry.ipynb
|
jtpio/xleaflet
|
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
|
[
"BSD-3-Clause"
] | null | null | null | 20.873333 | 95 | 0.493772 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4aacb6ed3fd705bd554203e876cda8db7a753fdf
| 21,286 |
ipynb
|
Jupyter Notebook
|
Guia Practica Nro 2/174440_Guia_2_Taxonomia_de_Flynn.ipynb
|
ParalelaUnsaac/2020-2
|
797487516b27a80b4d68f2039b8ef77a404202ec
|
[
"Apache-2.0"
] | null | null | null |
Guia Practica Nro 2/174440_Guia_2_Taxonomia_de_Flynn.ipynb
|
ParalelaUnsaac/2020-2
|
797487516b27a80b4d68f2039b8ef77a404202ec
|
[
"Apache-2.0"
] | null | null | null |
Guia Practica Nro 2/174440_Guia_2_Taxonomia_de_Flynn.ipynb
|
ParalelaUnsaac/2020-2
|
797487516b27a80b4d68f2039b8ef77a404202ec
|
[
"Apache-2.0"
] | null | null | null | 37.541446 | 1,146 | 0.50949 |
[
[
[
"<a href=\"https://colab.research.google.com/github/ParalelaUnsaac/2020-2/blob/main/GACO_Guia_2_Taxonomia_de_Flynn.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"El siguiente código va a permitir que todo código ejecutado en el colab pueda ser medido",
"_____no_output_____"
]
],
[
[
"!pip install ipython-autotime\r\n\r\n%load_ext autotime",
"Requirement already satisfied: ipython-autotime in /usr/local/lib/python3.6/dist-packages (0.2.0)\nRequirement already satisfied: ipython in /usr/local/lib/python3.6/dist-packages (from ipython-autotime) (5.5.0)\nRequirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from ipython->ipython-autotime) (4.4.2)\nRequirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.6/dist-packages (from ipython->ipython-autotime) (0.8.1)\nRequirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.6/dist-packages (from ipython->ipython-autotime) (50.3.2)\nRequirement already satisfied: pexpect; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from ipython->ipython-autotime) (4.8.0)\nRequirement already satisfied: pygments in /usr/local/lib/python3.6/dist-packages (from ipython->ipython-autotime) (2.6.1)\nRequirement already satisfied: pickleshare in /usr/local/lib/python3.6/dist-packages (from ipython->ipython-autotime) (0.7.5)\nRequirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.6/dist-packages (from ipython->ipython-autotime) (4.3.3)\nRequirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.6/dist-packages (from ipython->ipython-autotime) (1.0.18)\nRequirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.6/dist-packages (from pexpect; sys_platform != \"win32\"->ipython->ipython-autotime) (0.6.0)\nRequirement already satisfied: ipython-genutils in /usr/local/lib/python3.6/dist-packages (from traitlets>=4.2->ipython->ipython-autotime) (0.2.0)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from traitlets>=4.2->ipython->ipython-autotime) (1.15.0)\nRequirement already satisfied: wcwidth in /usr/local/lib/python3.6/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython->ipython-autotime) (0.2.5)\nThe autotime extension is already loaded. To reload it, use:\n %reload_ext autotime\ntime: 2.54 s\n"
],
[
"print(sum(range(10)))",
"45\ntime: 1.01 ms\n"
]
],
[
[
"Pregunta #1: Que porción de 1 segundo es el valor impreso?\r\nEs mili segundo representado por 1*10^(-3)\r\n\r\n",
"_____no_output_____"
],
[
"\r\n---\r\n\r\n",
"_____no_output_____"
],
[
"A seguir, tenemos una librería de Python llamado **numba** que realiza paralelización automatica. Asi, se puede verificar que al usar prange() se tiene mejor tiempo de ejecución que al usar range()",
"_____no_output_____"
]
],
[
[
"from numba import njit, prange\r\nimport numpy as np\r\n\r\nA = np.arange(5, 1600000)\r\n@njit(parallel=True)\r\ndef prange_test(A):\r\n s = 0\r\n # Without \"parallel=True\" in the jit-decorator\r\n # the prange statement is equivalent to range\r\n for i in prange(A.shape[0]):\r\n s += A[i]\r\n return s\r\n\r\nprint(prange_test(A))",
"1279999199990\ntime: 391 ms\n"
],
[
"from numba import njit, prange\r\nimport numpy as np\r\n\r\nA = np.arange(5, 1600000)\r\n#@njit(parallel=True)\r\ndef prange_test(A):\r\n s = 0\r\n # Without \"parallel=True\" in the jit-decorator\r\n # the prange statement is equivalent to range\r\n for i in range(A.shape[0]):\r\n s += A[i]\r\n return s\r\n\r\nprint(prange_test(A))\r\n\r\n",
"1279999199990\ntime: 412 ms\n"
]
],
[
[
"Pregunta #2: identifique otros valores en A, de manera que, serializando, tengamos mejor resultado que paralelizando\r\n\r\nComo se puede observar cuando tenemos un parámetro mas pequeño el mejor resultado vendria a ser serializando pero cuando se va icrementando los parámetros el mejor resultado sería paralelizando",
"_____no_output_____"
],
[
"\r\n\r\n---\r\n\r\n",
"_____no_output_____"
],
[
"La Taxonomia de Flynn define 4 tipos de arquitecturas para computación paralela: SISD, SIMD, MISD, y MIMD. \r\n\r\n\r\n---\r\n\r\n\r\nPregunta #3 : El ultimo código ejecutado es de tipo?\r\n\r\nSISD ya que es serial secuencial",
"_____no_output_____"
],
[
"\r\n\r\n---\r\n\r\n",
"_____no_output_____"
],
[
"Pregunta #4: ¿Segun la Tax. de Flynn, De que tipo es el siguiente código paralelo? Comentar el código para justificar su respuesta\r\n\r\n\r\nSIMD por que solo se tiene una sola instruccion que viene a ser print_time(name,n) y se tiene multiples datos como t1 y t2 y cada hilo funciona independientemente ",
"_____no_output_____"
]
],
[
[
"import threading\r\nimport time\r\n\r\ndef print_time(name, n):\r\n count = 0 \r\n print(\"Para el Hilo: %s, en el momento: %s, su valor de count es: %s\" % ( name, time.ctime(), count))\r\n while count < 5:\r\n time.sleep(n)\r\n count+=1\r\n print(\"%s: %s. count %s\" % ( name, time.ctime(), count))\r\n\r\n \r\nt1 = threading.Thread(target=print_time, args=(\"Thread-1\", 0, ) )\r\nt2 = threading.Thread(target=print_time, args=(\"Thread-2\", 0, ) )\r\n\r\nt1.start()\r\nt2.start()",
"Para el Hilo: Thread-1, en el momento: Wed Dec 9 15:26:34 2020, su valor de count es: 0Para el Hilo: Thread-2, en el momento: Wed Dec 9 15:26:34 2020, su valor de count es: 0\nThread-1: Wed Dec 9 15:26:34 2020. count 1\nThread-1: Wed Dec 9 15:26:34 2020. count 2\nThread-1: Wed Dec 9 15:26:34 2020. count 3\nThread-1: Wed Dec 9 15:26:34 2020. count 4\nThread-1: Wed Dec 9 15:26:34 2020. count 5\ntime: 6.49 ms\n\nThread-2: Wed Dec 9 15:26:34 2020. count 1\nThread-2: Wed Dec 9 15:26:34 2020. count 2\nThread-2: Wed Dec 9 15:26:34 2020. count 3\nThread-2: Wed Dec 9 15:26:34 2020. count 4\nThread-2: Wed Dec 9 15:26:34 2020. count 5\n"
]
],
[
[
"\r\n\r\n---\r\n\r\n",
"_____no_output_____"
],
[
"Una computadora paralela tipo MIMD es utilizado más en la computación distribuida, ejm. Clusters. El siguiente código en python desktop muestra tal funcionamiento",
"_____no_output_____"
]
],
[
[
"#greeting-server.py\r\nimport Pyro4\r\n\r\[email protected]\r\nclass GreetingMaker(object):\r\n def get_fortune(self, name):\r\n return \"Hello, {0}. Here is your fortune message:\\n\" \\\r\n \"Behold the warranty -- the bold print giveth and the fine print taketh away.\".format(name)\r\n\r\ndaemon = Pyro4.Daemon() # make a Pyro daemon\r\nuri = daemon.register(GreetingMaker) # register the greeting maker as a Pyro object\r\n\r\nprint(\"Ready. Object uri =\", uri) # print the uri so we can use it in the client later\r\ndaemon.requestLoop() # start the event loop of the server to wait for calls",
"_____no_output_____"
],
[
"#greeting-client.py\r\nimport Pyro4\r\n\r\nuri = input(\"What is the Pyro uri of the greeting object? \").strip()\r\nname = input(\"What is your name? \").strip()\r\n\r\ngreeting_maker = Pyro4.Proxy(uri) # get a Pyro proxy to the greeting object\r\nprint(greeting_maker.get_fortune(name)) # call method normally",
"_____no_output_____"
]
],
[
[
"Pregunta #5: Explique que hace este código de tipo MIMD\r\n\r\npresenta un sistema con un flujo de múltiples instrucciones que operan sobre múltiples datos usando un servidor se ve que se recibe un nombre de usuario registrado despues se pide que un usuario se loguee con el codigo que se recupera del server luego de loguearse te pide un nombre para asi con la ayuda de este poder entregar un mensaje aleatorio al usuario con una frase.",
"_____no_output_____"
],
[
"\r\n\r\n---\r\n\r\n",
"_____no_output_____"
],
[
"Ejercicio Propuesto: Crear un ejemplo que muestre una computación paralela de tipo MISD",
"_____no_output_____"
]
],
[
[
"from numba import njit, prange\r\nimport numpy as np\r\nA = np.arange(5, 1000)\r\n#@njit(parallel=True)\r\ndef prange_test(A):\r\n s = 0\r\n # Without \"parallel=True\" in the jit-decorator\r\n # the prange statement is equivalent to range\r\n for i in range(A.shape[0]):\r\n s += A[i]\r\n return s\r\ndef ValPremio(A):\r\n s = int(input(\"Ingrese un numero de la suerte: \"))\r\n #Verifica\r\n if prange_test(A) <= s or prange_test(A)%s==0:\r\n return \"Ganaste\"\r\n else:\r\n return \"Perdiste\"\r\n\r\n\r\nprint(prange_test(A))\r\nValPremio(A)\r\n\r\n",
"499490\nIngrese un numero de la suerte: 4\n"
]
],
[
[
"en MISD Hay N secuencias de instrucciones y utilizando el mismo dato \r\ntenemos A quien esta siendo utilizado por dos instrucciones en este caso \r\nprange_test y ValPremio",
"_____no_output_____"
],
[
"**Referencias**\r\n\r\nhttps://wiki.python.org/moin/ParallelProcessing\r\n\r\nhttps://numba.readthedocs.io/en/stable/user/parallel.html\r\n\r\nhttps://ao.gl/how-to-measure-execution-time-in-google-colab/\r\n\r\nhttp://noisymime.org/blogimages/SIMD.pdf",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4aaccedaac20ecf336b5c422ecbca00f89f2ef38
| 15,841 |
ipynb
|
Jupyter Notebook
|
presentation.ipynb
|
AntoineStevan/EA-elective-NEAT
|
e45ae8fc84af9d99afb58434ec0747ebedef91b1
|
[
"Apache-2.0"
] | null | null | null |
presentation.ipynb
|
AntoineStevan/EA-elective-NEAT
|
e45ae8fc84af9d99afb58434ec0747ebedef91b1
|
[
"Apache-2.0"
] | null | null | null |
presentation.ipynb
|
AntoineStevan/EA-elective-NEAT
|
e45ae8fc84af9d99afb58434ec0747ebedef91b1
|
[
"Apache-2.0"
] | 3 |
2021-05-28T10:12:33.000Z
|
2021-05-28T10:17:16.000Z
| 20.843421 | 173 | 0.473139 |
[
[
[
"# Minatar integration",
"_____no_output_____"
],
[
"## The minatar wrapper.",
"_____no_output_____"
],
[
"In **standardized *Reinforcement Learning* (RL) environments and benchmarks**, one usually has:",
"_____no_output_____"
],
[
"- a `reset` method with signature `None -> Tensor` (resets and give 1st observation)",
"_____no_output_____"
],
[
"- a `step` method with signature `int -> (Tensor, float, bool, dict)` (takes an action steps into the environment and gives an (observation, reward, done, info) tuple)",
"_____no_output_____"
],
[
"- a `render` method with signature `None -> None or Tensor` (renders current env state by giving, or not, an image)",
"_____no_output_____"
],
[
"However, **MinAtar does not use this standardized approach**! Rather one has access to:",
"_____no_output_____"
],
[
"- a `reset` method with signature `None -> None` (resets only)",
"_____no_output_____"
],
[
"- an `act` method with signature `int -> (float, bool)` (steps and gives (reward, done) tuple)",
"_____no_output_____"
],
[
"- a `state` method with signature `None -> Tensor` (gives an observation)",
"_____no_output_____"
],
[
"- a `display_state` method with signature `None -> int(optional)` (renders only)",
"_____no_output_____"
],
[
"In order to adapt the minatar benchmark to standard RL environments,",
"_____no_output_____"
],
[
"and to do as little changes to the original code as possible,",
"_____no_output_____"
],
[
"we implemented a Wrapper class that looks like",
"_____no_output_____"
]
],
[
[
"class MinatarWrapper(Environment):\n def reset(self):\n \"\"\"\n Resets the environment.\n\n Return:\n (observation) the first observation.\n \"\"\"\n\n def step(self, actions):\n \"\"\"\n Steps in the environment.\n\n Args:\n actions (): the action to take.\n\n Return:\n (tensor, float, bool, dict) new observation, reward, done signal and complementary informations.\n \"\"\"",
"_____no_output_____"
],
[
" def render(self, time=0, done=False):\n \"\"\"\n Resets the environment.\n\n Args:\n time (int): the number of milliseconds for each frame. if 0, there will be no live animation.\n done (bool): tells if the episode is done.\n\n Return:\n (Image) the current image of the game.\n \"\"\"\n\n def _state(self):\n \"\"\"\n Reduces the dimensions of the raw observation and normalize it.\n \"\"\"",
"_____no_output_____"
]
],
[
[
"in `_state`, **reduction** and **normalization** tricks are applied.",
"_____no_output_____"
]
],
[
[
"# sums the object channels to have a single image.\nstate = np.sum([state[i] * (i+1) for i in range(state.shape[0])], axis=0)\n\n# normalize the image\nm, M = np.min(state), np.max(state)\nstate = 2 * (state - m) / (M - m) - 1",
"_____no_output_____"
]
],
[
[
"## Environment hyper-definition",
"_____no_output_____"
],
[
"### Breakout",
"_____no_output_____"
]
],
[
[
"breakout = Game(env_name=\"minatar:breakout\",\n actionSelect=\"softmax\",\n input_size=100,\n output_size=6,\n time_factor=0,\n layers=[5, 5],\n i_act=np.full(5, 1),\n h_act=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n o_act=np.full(1, 1),\n weightCap=2.0,\n noise_bias=0.0,\n output_noise=[False, False, False],\n max_episode_length=1000,\n in_out_labels=['x', 'x_dot', 'cos(theta)', 'sin(theta)', 'theta_dot',\n 'force']\n )\ngames[\"minatar:breakout\"] = breakout",
"_____no_output_____"
]
],
[
[
"## Environment hyper-definition\n### Freeway",
"_____no_output_____"
]
],
[
[
"freeway = Game(env_name=\"minatar:freeway\",\n actionSelect=\"softmax\",\n input_size=100,\n output_size=6,\n time_factor=0,\n layers=[5, 5],\n i_act=np.full(5, 1),\n h_act=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n o_act=np.full(1, 1),\n weightCap=2.0,\n noise_bias=0.0,\n output_noise=[False, False, False],\n max_episode_length=1000,\n in_out_labels=['x', 'x_dot', 'cos(theta)', 'sin(theta)', 'theta_dot',\n 'force']\n )\ngames[\"minatar:freeway\"] = freeway",
"_____no_output_____"
]
],
[
[
"## Hyperparameters automatic search.",
"_____no_output_____"
]
],
[
[
"parameters = OrderedDict(\n popSize=[64, 200],\n\n prob_addConn=[.025, .1],\n prob_addNode=[.015, .06],\n prob_crossover=[.7, .9],\n prob_enable=[.005, .02],\n prob_mutConn=[.7, .9],\n prob_initEnable=[.8, 1.],\n)",
"_____no_output_____"
],
[
"class RunBuilder:\n @staticmethod\n def get_runs(parameters):\n runs = []\n for v in product(*parameters.values()):\n runs.append(dict(zip(parameters.keys(), v)))\n\n return runs",
"_____no_output_____"
],
[
"b_fit, b_run = 0, -1\nfor run in RunBuilder.get_runs(parameters):\n fitness = run_one_hyp(hyp, run)\n if fitness > b_fit:\n b_fit = fitness\n b_run = run",
"_____no_output_____"
]
],
[
[
"- the runs where ran on **Breakout** because it is a lot faster to evaluate.",
"_____no_output_____"
],
[
"- **fitnesses** where **recorded** for further investigations.",
"_____no_output_____"
],
[
"however...",
"_____no_output_____"
],
[
"results were *not good* at all!",
"_____no_output_____"
],
[
"the best set of hyperparameters was:",
"_____no_output_____"
],
[
"| popSize | prob_addConn | prob_addNode | prob_crossover | prob_enable | prob_mutAct | prob_mutConn | prob_initEnable | budget |\n| ------- | ------------ | ---- | ---- | ---- | ---- | ---- | ---- | ----- |\n| 32 | .025 | .015 | .7 | .02 | .0 | .9 | 1. | 50000 |",
"_____no_output_____"
],
[
"and the fitness seen during search was 6.0",
"_____no_output_____"
],
[
"So, for final training, we have used the above set of parameters.",
"_____no_output_____"
],
[
"## The experiment.",
"_____no_output_____"
],
[
"- run 50000 learning processes 3 times to show statistical results.",
"_____no_output_____"
],
[
"- use the parameters of the above search result.",
"_____no_output_____"
],
[
"## The results.",
"_____no_output_____"
],
[
"- time spent for Breakout: **~ 2 hours**\n- final fitness on Breakout: **max of ~ 2.80**",
"_____no_output_____"
],
[
"- time spent for Freeway: **~ 21h** (Cumulated)\n- final fitness on Freeway: **14**",
"_____no_output_____"
],
[
"A random breakout agent...",
"_____no_output_____"
],
[
"<img src=\"./log/breakout/gifs/3484933263.gif\" width=\"600\" align=\"center\">",
"_____no_output_____"
],
[
"performing around 0.50",
"_____no_output_____"
],
[
"The final best breakout agent given by ***NEAT***:",
"_____no_output_____"
],
[
"<img src=\"./log/breakout/gifs/3292025515.gif\" width=\"600\" align=\"center\">",
"_____no_output_____"
],
[
"performing around 2.80 and it takes significantly more time to evaluate such an agent!",
"_____no_output_____"
],
[
"A random freeway agent...",
"_____no_output_____"
],
[
"<img src=\"./357277723.gif\" width=\"600\" align=\"center\">",
"_____no_output_____"
],
[
"almost never reaches the top",
"_____no_output_____"
],
[
"The final best freeway agent given by ***NEAT***:",
"_____no_output_____"
],
[
"<img src=\"./357277723.gif\" width=\"600\" align=\"center\">",
"_____no_output_____"
],
[
"performing around 14 but clearly not very efficient... ",
"_____no_output_____"
],
[
"Same issue for both problems...",
"_____no_output_____"
],
[
"<img src=\"./Graph.png\" width=\"600\" align=\"center\">",
"_____no_output_____"
],
[
"local minimum prevent innovation and diversity, species mechanism isn't efficient enough with our hyperparameters set.",
"_____no_output_____"
]
]
] |
[
"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"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4aacd0291afd787b99478825cda03af3906de7ad
| 42,390 |
ipynb
|
Jupyter Notebook
|
notebooks/DS_Session3_Aufgabe_Ecoli.ipynb
|
ChristianCKKoch/Repo_1
|
372a6a2fe7ce5b7c4ec8a238769f9807d4f0dc35
|
[
"FTL"
] | null | null | null |
notebooks/DS_Session3_Aufgabe_Ecoli.ipynb
|
ChristianCKKoch/Repo_1
|
372a6a2fe7ce5b7c4ec8a238769f9807d4f0dc35
|
[
"FTL"
] | null | null | null |
notebooks/DS_Session3_Aufgabe_Ecoli.ipynb
|
ChristianCKKoch/Repo_1
|
372a6a2fe7ce5b7c4ec8a238769f9807d4f0dc35
|
[
"FTL"
] | null | null | null | 107.316456 | 28,092 | 0.79816 |
[
[
[
"Daten importieren aus Excel\n------",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\ndata_input = pd.read_excel('../data/raw/U bung kNN Klassifizierung Ecoli.xlsx', sheet_name=0)\ndata_output = pd.read_excel('../data/raw/U bung kNN Klassifizierung Ecoli.xlsx', sheet_name=1)",
"_____no_output_____"
],
[
"data_output",
"_____no_output_____"
]
],
[
[
"Train und Test Datensätze erstellen, normalisieren und kNN-Classifier trainieren\n---------",
"_____no_output_____"
]
],
[
[
"X = data_input.loc[:,data_input.columns != \"Target\"]\ny = data_input[\"Target\"]\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20) #, random_state=0)",
"_____no_output_____"
],
[
"data_input",
"_____no_output_____"
],
[
"#Normalisieren der Daten\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nscaler.fit(X_train)\n\nX_train_norm = scaler.transform(X_train)\nX_test_norm = scaler.transform(X_test)",
"_____no_output_____"
],
[
"from sklearn.neighbors import KNeighborsClassifier\nknnclf = KNeighborsClassifier(n_neighbors=7)\nknnclf.fit(X_train_norm, y_train)",
"_____no_output_____"
]
],
[
[
"Test Datensätze erstellen und kNN-Classifier verwenden\n---------",
"_____no_output_____"
]
],
[
[
"X_output = data_output",
"_____no_output_____"
],
[
"y_pred = knnclf.predict(X_output)",
"_____no_output_____"
],
[
"#Normalisieren der Daten\nX_output_norm = scaler.transform(X_output)\ny_pred_norm = knnclf.predict(X_output_norm)",
"_____no_output_____"
],
[
"print(X_output)\nprint(y_pred)\nprint(X_output_norm)\nprint(y_pred_norm)",
" mcg gvh lip chg aac alm1 alm2\n0 0.79 0.36 0.48 0.5 0.46 0.82 0.70\n1 0.36 0.54 0.48 0.5 0.41 0.38 0.46\n2 0.60 0.61 0.48 0.5 0.54 0.67 0.71\n3 0.71 0.71 0.48 0.5 0.68 0.43 0.36\n['imU' 'cp' 'im' 'pp']\n[[0.88764045 0.15789474 0. 0. 0.53488372 0.86813187\n 0.74468085]\n [0.40449438 0.39473684 0. 0. 0.47674419 0.38461538\n 0.4893617 ]\n [0.6741573 0.48684211 0. 0. 0.62790698 0.7032967\n 0.75531915]\n [0.79775281 0.61842105 0. 0. 0.79069767 0.43956044\n 0.38297872]]\n['imU' 'cp' 'im' 'om']\n"
]
],
[
[
"Akkuranz bestimmen\n----------------",
"_____no_output_____"
]
],
[
[
"score = knnclf.score(X_test,y_test)\nprint('knn-Classifier scores with {}% accuracy'.format(score*100))",
"knn-Classifier scores with 85.07462686567165% accuracy\n"
]
],
[
[
"Optimalen k-wert bestimmen\n---------------",
"_____no_output_____"
],
[
"y_pred = knnclf.predict(X_test)\n\nfrom sklearn.metrics import classification_report, confusion_matrix\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport numpy as np\nerror = []\n\n# Calculating error for K values between 1 and 40\nfor i in range(1, 40):\n knn = KNeighborsClassifier(n_neighbors=i)\n knn.fit(X_train_norm, y_train)\n pred_i = knn.predict(X_test_norm)\n error.append(np.mean(pred_i != y_test))",
"_____no_output_____"
],
[
"plt.figure(figsize=(12, 6))\nplt.plot(range(1, 40), error, color='red', linestyle='dashed', marker='o',\n markerfacecolor='blue', markersize=10)\nplt.title('Error Rate K Value')\nplt.xlabel('K Value')\nplt.ylabel('Mean Error')",
"_____no_output_____"
]
],
[
[
"Decision Tree\n----------",
"_____no_output_____"
]
],
[
[
"from sklearn.tree import DecisionTreeClassifier\n\ndt = DecisionTreeClassifier(max_depth=3, criterion=\"entropy\", min_samples_split=2)\ndt.fit(X_train,y_train)\nfrom sklearn.tree import DecisionTreeClassifier\n\nscore = dt.score(X_test,y_test)\nprint('Decision Tree scores with {}% accuracy'.format(score*100))",
"Decision Tree scores with 71.64179104477611% accuracy\n"
],
[
"from sklearn.model_selection import GridSearchCV\n\n#tree parameters which shall be tested\ntree_para = {'criterion':['gini','entropy'],'max_depth':[i for i in range(1,20)], 'min_samples_split':[i for i in range (2,20)]}\n\n#GridSearchCV object\ngrd_clf = GridSearchCV(dt, tree_para, cv=5)\n\n#creates differnt trees with all the differnet parameters out of our data\ngrd_clf.fit(X_train, y_train)\n\n#best paramters that were found\nbest_parameters = grd_clf.best_params_ \nprint(best_parameters) ",
"C:\\Users\\Chris\\anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_split.py:670: UserWarning: The least populated class in y has only 1 members, which is less than n_splits=5.\n warnings.warn((\"The least populated class in y has only %d\"\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aace1ee261c6a9a7e63a534f8cbfa439a9e3cdf
| 19,975 |
ipynb
|
Jupyter Notebook
|
site/en/r2/tutorials/text/text_classification_rnn.ipynb
|
crypdra/docs
|
41ab06fd14b3a3dff933bb80b19ce46c7c5781cf
|
[
"Apache-2.0"
] | 2 |
2019-10-25T18:51:16.000Z
|
2019-10-25T18:51:18.000Z
|
site/en/r2/tutorials/text/text_classification_rnn.ipynb
|
crypdra/docs
|
41ab06fd14b3a3dff933bb80b19ce46c7c5781cf
|
[
"Apache-2.0"
] | null | null | null |
site/en/r2/tutorials/text/text_classification_rnn.ipynb
|
crypdra/docs
|
41ab06fd14b3a3dff933bb80b19ce46c7c5781cf
|
[
"Apache-2.0"
] | null | null | null | 30.082831 | 328 | 0.51234 |
[
[
[
"##### Copyright 2018 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Text classification with an RNN",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/beta/tutorials/text/text_classification_rnn\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/tutorials/text/text_classification_rnn.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/text/text_classification_rnn.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/r2/tutorials/text/text_classification_rnn.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"This text classification tutorial trains a [recurrent neural network](https://developers.google.com/machine-learning/glossary/#recurrent_neural_network) on the [IMDB large movie review dataset](http://ai.stanford.edu/~amaas/data/sentiment/) for sentiment analysis.",
"_____no_output_____"
]
],
[
[
"from __future__ import absolute_import, division, print_function, unicode_literals\n\ntry:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass\nimport tensorflow_datasets as tfds\nimport tensorflow as tf",
"_____no_output_____"
]
],
[
[
"Import `matplotlib` and create a helper function to plot graphs:",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n\n\ndef plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.plot(history.history['val_'+string])\n plt.xlabel(\"Epochs\")\n plt.ylabel(string)\n plt.legend([string, 'val_'+string])\n plt.show()",
"_____no_output_____"
]
],
[
[
"## Setup input pipeline\n\n\nThe IMDB large movie review dataset is a *binary classification* dataset—all the reviews have either a *positive* or *negative* sentiment.\n\nDownload the dataset using [TFDS](https://www.tensorflow.org/datasets). The dataset comes with an inbuilt subword tokenizer.\n",
"_____no_output_____"
]
],
[
[
"dataset, info = tfds.load('imdb_reviews/subwords8k', with_info=True,\n as_supervised=True)\ntrain_dataset, test_dataset = dataset['train'], dataset['test']",
"_____no_output_____"
]
],
[
[
"As this is a subwords tokenizer, it can be passed any string and the tokenizer will tokenize it.",
"_____no_output_____"
]
],
[
[
"tokenizer = info.features['text'].encoder",
"_____no_output_____"
],
[
"print ('Vocabulary size: {}'.format(tokenizer.vocab_size))",
"_____no_output_____"
],
[
"sample_string = 'TensorFlow is cool.'\n\ntokenized_string = tokenizer.encode(sample_string)\nprint ('Tokenized string is {}'.format(tokenized_string))\n\noriginal_string = tokenizer.decode(tokenized_string)\nprint ('The original string: {}'.format(original_string))\n\nassert original_string == sample_string",
"_____no_output_____"
]
],
[
[
"The tokenizer encodes the string by breaking it into subwords if the word is not in its dictionary.",
"_____no_output_____"
]
],
[
[
"for ts in tokenized_string:\n print ('{} ----> {}'.format(ts, tokenizer.decode([ts])))",
"_____no_output_____"
],
[
"BUFFER_SIZE = 10000\nBATCH_SIZE = 64",
"_____no_output_____"
],
[
"train_dataset = train_dataset.shuffle(BUFFER_SIZE)\ntrain_dataset = train_dataset.padded_batch(BATCH_SIZE, train_dataset.output_shapes)\n\ntest_dataset = test_dataset.padded_batch(BATCH_SIZE, test_dataset.output_shapes)",
"_____no_output_____"
]
],
[
[
"## Create the model",
"_____no_output_____"
],
[
"Build a `tf.keras.Sequential` model and start with an embedding layer. An embedding layer stores one vector per word. When called, it converts the sequences of word indices to sequences of vectors. These vectors are trainable. After training (on enough data), words with similar meanings often have similar vectors.\n\nThis index-lookup is much more efficient than the equivalent operation of passing a one-hot encoded vector through a `tf.keras.layers.Dense` layer.\n\nA recurrent neural network (RNN) processes sequence input by iterating through the elements. RNNs pass the outputs from one timestep to their input—and then to the next.\n\nThe `tf.keras.layers.Bidirectional` wrapper can also be used with an RNN layer. This propagates the input forward and backwards through the RNN layer and then concatenates the output. This helps the RNN to learn long range dependencies.",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential([\n tf.keras.layers.Embedding(tokenizer.vocab_size, 64),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),\n tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dense(1, activation='sigmoid')\n])",
"_____no_output_____"
]
],
[
[
"Compile the Keras model to configure the training process:",
"_____no_output_____"
]
],
[
[
"model.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"## Train the model",
"_____no_output_____"
]
],
[
[
"history = model.fit(train_dataset, epochs=10,\n validation_data=test_dataset)",
"_____no_output_____"
],
[
"test_loss, test_acc = model.evaluate(test_dataset)\n\nprint('Test Loss: {}'.format(test_loss))\nprint('Test Accuracy: {}'.format(test_acc))",
"_____no_output_____"
]
],
[
[
"The above model does not mask the padding applied to the sequences. This can lead to skewness if we train on padded sequences and test on un-padded sequences. Ideally the model would learn to ignore the padding, but as you can see below it does have a small effect on the output.\n\nIf the prediction is >= 0.5, it is positive else it is negative.",
"_____no_output_____"
]
],
[
[
"def pad_to_size(vec, size):\n zeros = [0] * (size - len(vec))\n vec.extend(zeros)\n return vec",
"_____no_output_____"
],
[
"def sample_predict(sentence, pad):\n tokenized_sample_pred_text = tokenizer.encode(sample_pred_text)\n\n if pad:\n tokenized_sample_pred_text = pad_to_size(tokenized_sample_pred_text, 64)\n\n predictions = model.predict(tf.expand_dims(tokenized_sample_pred_text, 0))\n\n return (predictions)",
"_____no_output_____"
],
[
"# predict on a sample text without padding.\n\nsample_pred_text = ('The movie was cool. The animation and the graphics '\n 'were out of this world. I would recommend this movie.')\npredictions = sample_predict(sample_pred_text, pad=False)\nprint (predictions)",
"_____no_output_____"
],
[
"# predict on a sample text with padding\n\nsample_pred_text = ('The movie was cool. The animation and the graphics '\n 'were out of this world. I would recommend this movie.')\npredictions = sample_predict(sample_pred_text, pad=True)\nprint (predictions)",
"_____no_output_____"
],
[
"plot_graphs(history, 'accuracy')",
"_____no_output_____"
],
[
"plot_graphs(history, 'loss')",
"_____no_output_____"
]
],
[
[
"## Stack two or more LSTM layers\n\nKeras recurrent layers have two available modes that are controlled by the `return_sequences` constructor argument:\n\n* Return either the full sequences of successive outputs for each timestep (a 3D tensor of shape `(batch_size, timesteps, output_features)`).\n* Return only the last output for each input sequence (a 2D tensor of shape (batch_size, output_features)).",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential([\n tf.keras.layers.Embedding(tokenizer.vocab_size, 64),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(\n 64, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dense(1, activation='sigmoid')\n])",
"_____no_output_____"
],
[
"model.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"history = model.fit(train_dataset, epochs=10,\n validation_data=test_dataset)",
"_____no_output_____"
],
[
"test_loss, test_acc = model.evaluate(test_dataset)\n\nprint('Test Loss: {}'.format(test_loss))\nprint('Test Accuracy: {}'.format(test_acc))",
"_____no_output_____"
],
[
"# predict on a sample text without padding.\n\nsample_pred_text = ('The movie was not good. The animation and the graphics '\n 'were terrible. I would not recommend this movie.')\npredictions = sample_predict(sample_pred_text, pad=False)\nprint (predictions)",
"_____no_output_____"
],
[
"# predict on a sample text with padding\n\nsample_pred_text = ('The movie was not good. The animation and the graphics '\n 'were terrible. I would not recommend this movie.')\npredictions = sample_predict(sample_pred_text, pad=True)\nprint (predictions)",
"_____no_output_____"
],
[
"plot_graphs(history, 'accuracy')",
"_____no_output_____"
],
[
"plot_graphs(history, 'loss')",
"_____no_output_____"
]
],
[
[
"Check out other existing recurrent layers such as [GRU layers](https://www.tensorflow.org/api_docs/python/tf/keras/layers/GRU).",
"_____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",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4aacf540ce8a0ee20e953dabc1a4a50a75837795
| 13,824 |
ipynb
|
Jupyter Notebook
|
notebooks/inference.ipynb
|
neuro-inc/ml-recipe-midi-generator
|
4ed59a083b6de5148cc676cc7e41ca5ecaff50dc
|
[
"Apache-2.0"
] | 6 |
2020-02-18T20:20:46.000Z
|
2020-03-14T07:03:20.000Z
|
notebooks/inference.ipynb
|
neuro-inc/ml-recipe-midi-generator
|
4ed59a083b6de5148cc676cc7e41ca5ecaff50dc
|
[
"Apache-2.0"
] | 6 |
2020-03-11T16:58:37.000Z
|
2020-04-08T20:51:09.000Z
|
notebooks/inference.ipynb
|
neuromation/ml-recipe-midi-generator
|
4ed59a083b6de5148cc676cc7e41ca5ecaff50dc
|
[
"Apache-2.0"
] | null | null | null | 25.55268 | 269 | 0.581814 |
[
[
[
"## MIDI Generator",
"_____no_output_____"
]
],
[
[
"## Uncomment command below to kill current job:\n#!neuro kill $(hostname)",
"_____no_output_____"
],
[
"import random\nimport sys\nimport subprocess\nimport torch\nsys.path.append('../midi-generator')\n\n%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"import IPython.display as ipd\n\nfrom model.dataset import MidiDataset\n\nfrom utils.load_model import load_model\nfrom utils.generate_midi import generate_midi\nfrom utils.seed import set_seed\nfrom utils.write_notes import write_notes",
"_____no_output_____"
]
],
[
[
"Each `*.mid` file can be thought of as a sequence where notes and chords follow each other with specified time offsets between them. So, following this model a next note can be predicted with a `seq2seq` model. In this work, a simple `GRU`-based model is used.\n\nNote that the number of available notes and chord in vocabulary is not specified and depends on a dataset which a model was trained on.",
"_____no_output_____"
],
[
"To listen to MIDI files from Jupyter notebook, let's define help function which transforms `*.mid` file to `*.wav` file. ",
"_____no_output_____"
]
],
[
[
"def mid2wav(mid_path, wav_path):\n subprocess.check_output(['timidity', mid_path, '-OwS', '-o', wav_path])",
"_____no_output_____"
]
],
[
[
"The next step is loading the model from the checkpoint. To make experiments reproducible let's also specify random seed.\n\nYou can also try to use the model, which was trained with label smoothing (see `../results/smoothing.ch`).",
"_____no_output_____"
]
],
[
[
"seed = 1234\nset_seed(seed)\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\nprint(device)\nmodel, vocab = load_model(checkpoint_path='../results/test.ch', device=device)",
"_____no_output_____"
]
],
[
[
"Let's also specify additional help function to avoid code duplication.",
"_____no_output_____"
]
],
[
[
"def dump_result(file_preffix, vocab, note_seq, offset_seq=None):\n note_seq = vocab.decode(note_seq)\n notes = MidiDataset.decode_notes(note_seq, offset_seq=offset_seq)\n\n mid_path = file_preffix + '.mid'\n wav_path = file_preffix + '.wav'\n\n write_notes(mid_path, notes)\n mid2wav(mid_path, wav_path)\n \n return wav_path",
"_____no_output_____"
]
],
[
[
"# MIDI file generation\n\nLet's generate a new file. Note that the parameter `seq_len` specifies the length of the output sequence of notes. \n\nFunction `generate_midi` return sequence of generated notes and offsets between them.\n\n## Nucleus (`top-p`) Sampling\n\nSample from the most probable tokens, which sum of probabilities gives `top-p`. If `top-p == 0` the most probable token is sampled.\n\n## Temperature\n\nAs `temperature` → 0 this approaches greedy decoding, while `temperature` → ∞ asymptotically approaches uniform sampling from the vocabulary.",
"_____no_output_____"
]
],
[
[
"note_seq, offset_seq = generate_midi(model, vocab, seq_len=128, top_p=0, temperature=1, device=device)",
"_____no_output_____"
]
],
[
[
"Let's listen to result midi.",
"_____no_output_____"
]
],
[
[
"# midi with constant offsets\nipd.Audio(dump_result('../results/output_without_offsets', vocab, note_seq, offset_seq=None))",
"_____no_output_____"
],
[
"# midi with generated offsets\nipd.Audio(dump_result('../results/output_with_offsets.mid', vocab, note_seq, offset_seq))",
"_____no_output_____"
]
],
[
[
"The result with constant offsets sounds better, doesn't it? :)\n\nBe free to try different generation parameters (`top-p` and `temperature`) to understand their impact on the resulting sound.",
"_____no_output_____"
],
[
"You can also train your own model with different specs (e.g. different hidden size) or use label smoothing during training.",
"_____no_output_____"
],
[
"# Continue existing file",
"_____no_output_____"
],
[
"## Continue sampled notes\nFor beginning, let's continue sound that consists of sampled from `vocab` notes. ",
"_____no_output_____"
]
],
[
[
"seed = 4321\nset_seed(seed)\n\nhistory_notes = random.choices(range(len(vocab)), k=20)\nhistory_offsets = len(history_notes) * [0.5]",
"_____no_output_____"
],
[
"ipd.Audio(dump_result('../results/random_history', vocab, history_notes, history_offsets))",
"_____no_output_____"
]
],
[
[
"It sounds a little bit chaotic. Let's try to continue this with our model.",
"_____no_output_____"
]
],
[
[
"history = [*zip(history_notes, history_offsets)]\nnote_seq, offset_seq = generate_midi(model, vocab, seq_len=128, top_p=0, temperature=1, device=device, \n history=history)",
"_____no_output_____"
],
[
"# midi with constant offsets\nipd.Audio(dump_result('../results/random_without_offsets', vocab, note_seq, offset_seq=None))",
"_____no_output_____"
]
],
[
[
"After the sampled part ends, the generated melody starts to sound better.",
"_____no_output_____"
],
[
"## Continue existed melody",
"_____no_output_____"
]
],
[
[
"raw_notest = MidiDataset.load_raw_notes('../data/mining.mid')",
"_____no_output_____"
],
[
"org_note_seq, org_offset_seq = MidiDataset.encode_notes(raw_notest)\norg_note_seq = vocab.encode(org_note_seq)",
"_____no_output_____"
]
],
[
[
"Let's listen to it",
"_____no_output_____"
]
],
[
[
"ipd.Audio(dump_result('../results/original_sound', vocab, org_note_seq, org_offset_seq))",
"_____no_output_____"
]
],
[
[
"and take 20 first elements from the sequence as out history sequence.",
"_____no_output_____"
]
],
[
[
"history_notes = org_note_seq[:20]\nhistory_offsets = org_offset_seq[:20]",
"_____no_output_____"
],
[
"history = [*zip(history_notes, history_offsets)]\nnote_seq, offset_seq = generate_midi(model, vocab, seq_len=128, top_p=0, temperature=1, device=device, \n history=history)",
"_____no_output_____"
],
[
"# result melody without generated offsets\nipd.Audio(dump_result('../results/continue_rand_without_offsets', vocab, note_seq, offset_seq=None))",
"_____no_output_____"
],
[
"# result melody with generated offsets\nipd.Audio(dump_result('../results/continue_rand_with_offsets', vocab, note_seq, offset_seq))",
"_____no_output_____"
]
],
[
[
"You can try to overfit your model on one melody to get better results. Otherwise, you can use already pretrained model (`../results/onemelody.ch`)",
"_____no_output_____"
],
[
"# Model overfitted on one melody",
"_____no_output_____"
],
[
"Let's try the same thing which we did before. Let's continue melody, but this time do it with the model, \nwhich was overfitted with this melody.",
"_____no_output_____"
]
],
[
[
"seed = 1234\nset_seed(seed)\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\nmodel, vocab = load_model(checkpoint_path='../results/onemelody.ch', device=device)",
"_____no_output_____"
],
[
"raw_notest = MidiDataset.load_raw_notes('../data/Final_Fantasy_Matouyas_Cave_Piano.mid')\norg_note_seq, org_offset_seq = MidiDataset.encode_notes(raw_notest)\norg_note_seq = vocab.encode(org_note_seq)",
"_____no_output_____"
]
],
[
[
"Let's listen to it.",
"_____no_output_____"
]
],
[
[
"ipd.Audio(dump_result('../results/onemelody_original_sound', vocab, org_note_seq, org_offset_seq))",
"_____no_output_____"
],
[
"end = 60\nhistory_notes = org_note_seq[:end]\nhistory_offsets = org_offset_seq[:end]",
"_____no_output_____"
]
],
[
[
"Listen to history part of loaded melody.",
"_____no_output_____"
]
],
[
[
"ipd.Audio(dump_result('../results/onemelody_history', vocab, history_notes, history_offsets))",
"_____no_output_____"
]
],
[
[
"Now we can try to continue the original melody with our model. But firstly, you can listen to the original tail part of the melody do refresh it in the memory and have reference to compare with.",
"_____no_output_____"
]
],
[
[
"tail_notes = org_note_seq[end:]\ntail_offsets = org_offset_seq[end:]\nipd.Audio(dump_result('../results/onemelody_tail', vocab, tail_notes, tail_offsets))",
"_____no_output_____"
],
[
"history = [*zip(history_notes, history_offsets)]\nnote_seq, offset_seq = generate_midi(model, vocab, seq_len=128, top_p=0, temperature=1, device=device, \n history=history)\n\n# delete history part\nnote_seq = note_seq[end:]\noffset_seq = offset_seq[end:]",
"_____no_output_____"
],
[
"# result melody without generated offsets\nipd.Audio(dump_result('../results/continue_onemelody_without_offsets', vocab, note_seq, offset_seq=None))",
"_____no_output_____"
],
[
"# result melody with generated offsets\nipd.Audio(dump_result('../results/continue_onemelody_with_offsets', vocab, note_seq, offset_seq))",
"_____no_output_____"
]
],
[
[
"As you can hear, this time, the model generated better offsets and the result melody does not sound so chaostic.",
"_____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"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4aacf708ff0ec230d61d3bfe1992650498ab8ecd
| 11,918 |
ipynb
|
Jupyter Notebook
|
examples/sandbox.ipynb
|
3d-pli/fastpli
|
fe90ac53a7e78d122696bebb4816f4cb953cdb72
|
[
"MIT"
] | 13 |
2020-03-21T10:40:36.000Z
|
2022-03-20T17:27:56.000Z
|
examples/sandbox.ipynb
|
3d-pli/fastpli
|
fe90ac53a7e78d122696bebb4816f4cb953cdb72
|
[
"MIT"
] | 11 |
2021-01-30T07:21:52.000Z
|
2021-03-16T15:24:41.000Z
|
examples/sandbox.ipynb
|
3d-pli/fastpli
|
fe90ac53a7e78d122696bebb4816f4cb953cdb72
|
[
"MIT"
] | 6 |
2020-08-27T07:19:30.000Z
|
2021-07-20T08:49:11.000Z
| 37.834921 | 200 | 0.550344 |
[
[
[
"# Sandbox - Tutorial\n\n## Building a fiber bundle\n\nA [fiber bundle](https://github.com/3d-pli/fastpli/wiki/FiberModel) consit out of multiple individual nerve fibers.\nA fiber bundle is a list of fibers, where fibers are represented as `(n,4)-np.array`.\n\nThis makes desining individually fiber of any shape possible.\nHowever since nerve fibers are often in nerve fiber bundles, this toolbox allows to fill fiber_bundles from a pattern of fibers.\n\nAdditionally this toolbox also allows to build parallell cubic shapes as well as different kinds of cylindric shapes to allow a faster building experience.",
"_____no_output_____"
],
[
"## General imports\n\nFirst, we prepair all necesarry modules and defining a function to euqalice all three axis of an 3d plot.\n\nYou can change the `magic ipython` line from `inline` to `qt`.\nThis generate seperate windows allowing us also to rotate the resulting plots and therfore to investigate the 3d models from different views.\nMake sure you have `PyQt5` installed if you use it.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n# %matplotlib qt\n\nimport fastpli.model.sandbox as sandbox\n\ndef set_3d_axes_equal(ax):\n x_limits = ax.get_xlim3d()\n y_limits = ax.get_ylim3d()\n z_limits = ax.get_zlim3d()\n\n x_range = abs(x_limits[1] - x_limits[0])\n x_middle = np.mean(x_limits)\n y_range = abs(y_limits[1] - y_limits[0])\n y_middle = np.mean(y_limits)\n z_range = abs(z_limits[1] - z_limits[0])\n z_middle = np.mean(z_limits)\n\n plot_radius = 0.5 * max([x_range, y_range, z_range])\n\n ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])\n ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])\n ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])",
"_____no_output_____"
]
],
[
[
"## Designing a fiber bundle\n\nThe idea is to build design first a macroscopic struces, i. e. nerve fiber bundles, which can then at a later step be filled with individual nerve fibers.\n\n",
"_____no_output_____"
],
[
"We start by defining a fiber bundle as a trajectory of points (similar to fibers).\nAs an example we start with use a helical form.",
"_____no_output_____"
]
],
[
[
"t = np.linspace(0, 4 * np.pi, 50, True)\ntraj = np.array((42 * np.cos(t), 42 * np.sin(t), 10 * t)).T\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection='3d')\nax.plot(\n traj[:, 0],\n traj[:, 1],\n traj[:, 2],\n)\nplt.title(\"fb trajectory\")\nset_3d_axes_equal(ax)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### seed points\n\nseed points are used to initialize the populating process of individual fibers inside the fiber bundle.\n\nSeed points are a list of 3d points.\nThis toolbox provides two methods to build seed points pattern.\n\nThe first one is a 2d triangular grid.\nIt is defined by a `width`, `height` and an inside `spacing` between the seed point.\nAdditionally one can actiavte the `center` option so that the seed points are centered around a seed point at `(0,0,0)`.\n\nThe second method provides a circular shape instead of a rectangular.\nHowever it can also be achievd by using an additional function `crop_circle` which returns only seed points along the first two dimensions with the defined `radius` around the center.",
"_____no_output_____"
]
],
[
[
"seeds = sandbox.seeds.triangular_grid(width=42,\n height=42,\n spacing=6,\n center=True)\nradius = 21\ncirc_seeds = sandbox.seeds.crop_circle(radius=radius, seeds=seeds)\nfig, ax = plt.subplots(1, 1)\nplt.title(\"seed points\")\nplt.scatter(seeds[:, 0], seeds[:, 1])\nplt.scatter(circ_seeds[:, 0], circ_seeds[:, 1])\nax.set_aspect('equal', 'box')\n\n# plot circle margin\nt = np.linspace(0, 2 * np.pi, 42)\nx = radius * np.cos(t)\ny = radius * np.sin(t)\nplt.plot(x, y)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Generating a fiber bundle from seed points\n\nThe next step is to build a fiber bundle from the desined trajectory and seed points.\n\nHowever one additional step is necesarry.\nSince nerve fibers are not a line, but a 3d object, they need also a volume for the later `solving` and `simulation` steps of this toolbox.\nThis toolbox describes nerve fibers as tubes, which are defined by a list of points and radii, i. e. (n,4)-np.array).\nThe radii `[:,3]` can change along the fiber trajectories `[:,0:3]` allowiing for a change of thickness.\n\nNow we have everything we need to build a fiber bundle from the desined trajectory and seed points.\nThe function `bundle` provides this funcionallity.\nAdditionally to the `traj` and `seeds` parameter the `radii` can be a single number if all fibers should have the same radii, or a list of numbers, if each fiber shell have a different radii.\nAn additional `scale` parameter allows to scale the seed points along the trajectory e. g. allowing for a fanning. \n",
"_____no_output_____"
]
],
[
[
"# populating fiber bundle\nfiber_bundle = sandbox.build.bundle(\n traj=traj,\n seeds=circ_seeds,\n radii=np.random.uniform(0.5, 0.8, circ_seeds.shape[0]),\n scale=0.25 + 0.5 * np.linspace(0, 1, traj.shape[0]))\n\n# plotting\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection='3d')\nfor fiber in fiber_bundle:\n ax.plot(fiber[:, 0], fiber[:, 1], fiber[:, 2])\nplt.title(\"helical thinning out fiber bundle\")\nset_3d_axes_equal(ax)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Additional macroscopic structures\n\nIn the development and using of this toolbox, it was found that it is usefull to have other patterns than filled fiber bundles to build macroscopic structures.\nDepending on a brain sections, where the nerve fiber orientation is measured with the 3D-PLI technique, nerve fibers can be visibale as type of patterns.",
"_____no_output_____"
],
[
"### Cylindrical shapes\n\nRadial shaped patterns can be quickly build with the following `cylinder` method.\nA hollow cylinder is defined by a inner and outer radii `r_in` and `r_out`, along two points `p` and `q`.\nAdditionally the cylinder can be also only partial along its radius by defining two angles `alpha` and `beta`.\nAgain as for the `bundle` method, one needs seed points to defining a pattern.\nFilling this cylindrig shape can be performed by three differet `mode`s: \n- radial\n- circular\n- parallel",
"_____no_output_____"
]
],
[
[
"# plotting\nseeds = sandbox.seeds.triangular_grid(width=200,\n height=200,\n spacing=5,\n center=True)\n\nfig, axs = plt.subplots(1, 3, figsize=(15,5), subplot_kw={'projection':'3d'}, constrained_layout=True)\nfor i, mode in enumerate(['radial', 'circular', 'parallel']):\n # ax = fig.add_subplot(1, 1, 1, projection='3d')\n fiber_bundle = sandbox.build.cylinder(p=(0, 80, 50),\n q=(40, 80, 100),\n r_in=20,\n r_out=40,\n seeds=seeds,\n radii=1,\n alpha=np.deg2rad(20),\n beta=np.deg2rad(160),\n mode=mode)\n for fiber in fiber_bundle:\n axs[i].plot(fiber[:, 0], fiber[:, 1], fiber[:, 2])\n set_3d_axes_equal(axs[i])\n axs[i].set_title(f'{mode}')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Cubic shapes\n\nThe next method allows placing fibers inside a cube with a use definde direction.\nThe cube is definded by two 3d points `p` and `q`.\nThe direction of the fibers inside the cube is defined by spherical angels `phi` and `theta`.\nSeed points again describe the pattern of fibers inside the cube. \nThe seed points (rotated its xy-plane according to `phi` and `theta`) are places at point `q` and `q`.\nFrom the corresponding seed points are the starting and end point for each fiber.",
"_____no_output_____"
]
],
[
[
"# define cub corner points\np = np.array([0, 80, 50])\nq = np.array([40, 180, 100])\n\n# create seed points which will fill the cube\nd = np.max(np.abs(p - q)) * np.sqrt(3)\nseeds = sandbox.seeds.triangular_grid(width=d,\n height=d,\n spacing=10,\n center=True)\n\n# fill a cube with (theta, phi) directed fibers\nfiber_bundle = sandbox.build.cuboid(p=p,\n q=q,\n phi=np.deg2rad(45),\n theta=np.deg2rad(90),\n seeds=seeds,\n radii=1)\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection='3d')\nfor fiber in fiber_bundle:\n ax.plot(fiber[:, 0], fiber[:, 1], fiber[:, 2])\nplt.title('cubic shape')\nset_3d_axes_equal(ax)\nplt.show() ",
"_____no_output_____"
]
],
[
[
"## next\n\nfrom here further anatomical more interesting examples are presented in the solver tutorial and `examples/crossing.py` example.",
"_____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"
],
[
"code"
],
[
"markdown"
]
] |
4aacf83e2b04faabbe0d256f2567eafa502ab69d
| 267,586 |
ipynb
|
Jupyter Notebook
|
Communicate_Data_Findings/Part_II_slide_deck_ames.ipynb
|
lustraka/Data_Analysis_Workouts
|
1bce2c1f50706b48c203ad603109aefbe69e2831
|
[
"CC0-1.0"
] | 1 |
2022-01-17T09:05:47.000Z
|
2022-01-17T09:05:47.000Z
|
Communicate_Data_Findings/Part_II_slide_deck_ames.ipynb
|
lustraka/Data_Analysis_Workouts
|
1bce2c1f50706b48c203ad603109aefbe69e2831
|
[
"CC0-1.0"
] | null | null | null |
Communicate_Data_Findings/Part_II_slide_deck_ames.ipynb
|
lustraka/Data_Analysis_Workouts
|
1bce2c1f50706b48c203ad603109aefbe69e2831
|
[
"CC0-1.0"
] | null | null | null | 430.202572 | 77,160 | 0.934825 |
[
[
[
"# Effect of House Characteristics on Their Prices \n## by Lubomir Straka",
"_____no_output_____"
],
[
"## Investigation Overview\n\nIn this investigation, I wanted to look at the key characteristics of houses that could be used to predict their prices. The main focus was on three aspects: above grade living area representing space characteristics, overall quality of house's material and finish representing physical characteristics, and neighborhood cluster representing location characteristics.\n\n## Dataset Overview\n\nThe data consists of information regarding 1460 houses in Ames, Iowa, including their sale price, physical characteristics, space properties and location within the city as provided by [Kaggle](https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data). The data set contains 1460 observations and a large number of explanatory variables (23 nominal, 23 ordinal, 14 discrete, and 20 continuous) involved in assessing home values. These 79 explanatory variables plus one response variable (sale price) describe almost every aspect of residential homes in Ames, Iowa.\n\nIn addition to some basic data type encoding, missing value imputing and cleaning, four outliers were removed from the analysis due to unusual sale conditions.",
"_____no_output_____"
]
],
[
[
"# Import all packages and set plots to be embedded inline\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n%matplotlib inline\n\n# Suppress warnings from final output\nimport warnings\nwarnings.simplefilter(\"ignore\")",
"_____no_output_____"
],
[
"# Load the Ames Housing dataset\npath = 'https://raw.githubusercontent.com/lustraka/Data_Analysis_Workouts/main/Communicate_Data_Findings/ames_train_data.csv'\names = pd.read_csv(path, index_col='Id')\n################\n# Wrangle data #\n################\n# The numeric features are already encoded correctly (`float` for\n# continuous, `int` for discrete), but the categoricals we'll need to\n# do ourselves. Note in particular, that the `MSSubClass` feature is\n# read as an `int` type, but is actually a (nominative) categorical.\n\n# The categorical features nominative (unordered)\ncatn = [\"MSSubClass\", \"MSZoning\", \"Street\", \"Alley\", \"LandContour\", \"LotConfig\",\n \"Neighborhood\", \"Condition1\", \"Condition2\", \"BldgType\", \"HouseStyle\", \n \"RoofStyle\", \"RoofMatl\", \"Exterior1st\", \"Exterior2nd\", \"MasVnrType\", \n \"Foundation\", \"Heating\", \"CentralAir\", \"GarageType\", \"MiscFeature\", \n \"SaleType\", \"SaleCondition\"]\n\n\n# The categorical features ordinal (ordered) \n\n# Pandas calls the categories \"levels\"\nfive_levels = [\"Po\", \"Fa\", \"TA\", \"Gd\", \"Ex\"]\nten_levels = list(range(10))\n\ncato = {\n \"OverallQual\": ten_levels,\n \"OverallCond\": ten_levels,\n \"ExterQual\": five_levels,\n \"ExterCond\": five_levels,\n \"BsmtQual\": five_levels,\n \"BsmtCond\": five_levels,\n \"HeatingQC\": five_levels,\n \"KitchenQual\": five_levels,\n \"FireplaceQu\": five_levels,\n \"GarageQual\": five_levels,\n \"GarageCond\": five_levels,\n \"PoolQC\": five_levels,\n \"LotShape\": [\"Reg\", \"IR1\", \"IR2\", \"IR3\"],\n \"LandSlope\": [\"Sev\", \"Mod\", \"Gtl\"],\n \"BsmtExposure\": [\"No\", \"Mn\", \"Av\", \"Gd\"],\n \"BsmtFinType1\": [\"Unf\", \"LwQ\", \"Rec\", \"BLQ\", \"ALQ\", \"GLQ\"],\n \"BsmtFinType2\": [\"Unf\", \"LwQ\", \"Rec\", \"BLQ\", \"ALQ\", \"GLQ\"],\n \"Functional\": [\"Sal\", \"Sev\", \"Maj1\", \"Maj2\", \"Mod\", \"Min2\", \"Min1\", \"Typ\"],\n \"GarageFinish\": [\"Unf\", \"RFn\", \"Fin\"],\n \"PavedDrive\": [\"N\", \"P\", \"Y\"],\n \"Utilities\": [\"NoSeWa\", \"NoSewr\", \"AllPub\"],\n \"CentralAir\": [\"N\", \"Y\"],\n \"Electrical\": [\"Mix\", \"FuseP\", \"FuseF\", \"FuseA\", \"SBrkr\"],\n \"Fence\": [\"MnWw\", \"GdWo\", \"MnPrv\", \"GdPrv\"],\n}\n\n# Add a None level for missing values\ncato = {key: [\"None\"] + value for key, value in\n cato.items()}\n\n\ndef encode_dtypes(df):\n \"\"\"Encode nominal and ordinal categorical variables.\"\"\"\n\n global catn, cato\n\n # Nominal categories\n for name in catn:\n df[name] = df[name].astype(\"category\")\n # Add a None category for missing values\n if \"None\" not in df[name].cat.categories:\n df[name].cat.add_categories(\"None\", inplace=True)\n # Ordinal categories\n for name, levels in cato.items():\n df[name] = df[name].astype(pd.CategoricalDtype(levels,\n ordered=True))\n return df\n\ndef impute_missing(df):\n \"\"\"Impute zeros to numerical and None to categorical variables.\"\"\"\n\n for name in df.select_dtypes(\"number\"):\n df[name] = df[name].fillna(0)\n for name in df.select_dtypes(\"category\"):\n df[name] = df[name].fillna(\"None\")\n return df\n\ndef clean_data(df):\n \"\"\"Remedy typos and mistakes based on EDA.\"\"\"\n\n global cato\n # YearRemodAdd: Remodel date (same as construction date if no remodeling or additions)\n df.YearRemodAdd = np.where(df.YearRemodAdd < df.YearBuilt, df.YearBuilt, df.YearRemodAdd)\n assert len(df.loc[df.YearRemodAdd < df.YearBuilt]) == 0, 'Check YearRemodAdd - should be greater or equal then YearBuilt'\n \n # Check range of years\n yr_max = 2022\n # Some values of GarageYrBlt are corrupt. Fix them by replacing them with the YearBuilt\n df.GarageYrBlt = np.where(df.GarageYrBlt > yr_max, df.YearBuilt, df.GarageYrBlt)\n assert df.YearBuilt.max() < yr_max and df.YearBuilt.min() > 1800, 'Check YearBuilt min() and max()'\n assert df.YearRemodAdd.max() < yr_max and df.YearRemodAdd.min() > 1900, 'Check YearRemodAdd min() and max()'\n assert df.YrSold.max() < yr_max and df.YrSold.min() > 2000, 'Check YrSold min() and max()'\n assert df.GarageYrBlt.max() < yr_max and df.GarageYrBlt.min() >= 0, 'Check GarageYrBlt min() and max()'\n \n # Check values of ordinal catagorical variables\n for k in cato.keys():\n assert set(df[k].unique()).difference(df[k].cat.categories) == set(), f'Check values of {k}'\n \n # Check typos in nominal categorical variables\n df['Exterior2nd'] = df['Exterior2nd'].replace({'Brk Cmn':'BrkComm', 'CmentBd':'CemntBd', 'Wd Shng':'WdShing'})\n # Renew a data type after replacement\n df['Exterior2nd'] = df['Exterior2nd'].astype(\"category\")\n if \"None\" not in df['Exterior2nd'].cat.categories:\n df['Exterior2nd'].cat.add_categories(\"None\", inplace=True)\n\n return df\n\ndef label_encode(df):\n \"\"\"Encode categorical variables using their dtype setting.\"\"\"\n\n X = df.copy()\n for colname in X.select_dtypes([\"category\"]):\n X[colname] = X[colname].cat.codes\n return X\n\n# Pre-process data\names = encode_dtypes(ames)\names = impute_missing(ames)\names = clean_data(ames)\n\n# Add log transformed SalePrice to the dataset\names['logSalePrice'] = ames.SalePrice.apply(np.log10)",
"_____no_output_____"
]
],
[
[
"## Distribution of House Prices\n**Graph on left**\n\nThe values of the response variable *SalePrice* are distributed between \\$34.900 and \\$755.000 with one mode at \\$140.000, which is lower than the median at \\$163.000, which is lower than the average price of \\$180.921. The distribution of *SalePrice* is asymmetric with relatively few large values and tails off to the right. It is also relatively peaked. \n\n**Graph on right**\n\nFor analysis of the relationships with other variables would be more suitable a log transformation of *SalePrice*. The distribution of *logSalePrice* is almost symmetric with skewness close to zero although the distribution is still a bit peaked.\n",
"_____no_output_____"
]
],
[
[
"def log_trans(x, inverse=False):\n \"\"\"Get log or tenth power of the argument.\"\"\"\n if not inverse:\n return np.log10(x)\n else:\n return 10**x\n\n# Plot SalePrice with a standard and log scale\nfig, axs = plt.subplots(1, 2, figsize=[16,5])\n# LEFT plot\nsns.histplot(data=ames, x='SalePrice', ax=axs[0])\naxs[0].set_title('Distribution of Sale Price')\nxticks = np.arange(100000, 800000, 100000)\naxs[0].set_xticks(xticks)\naxs[0].set_xticklabels([f'{int(xtick/1000)}K' for xtick in xticks])\naxs[0].set_xlabel('Price ($)')\n# RIGHT plot\nsns.histplot(data=ames, x='logSalePrice', ax=axs[1])\naxs[1].set_title('Distribution of Sale Price After Log Transformation')\nlticks = [50000, 100000, 200000, 500000]\naxs[1].set_xticks(log_trans(lticks))\naxs[1].set_xticklabels([f'{int(xtick/1000)}K' for xtick in lticks])\naxs[1].set_xlabel('Price ($)')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Distribution of Living Area\n\nThe distribution of above grade living area (*GrLivArea*) is asymmetrical with skewness to the right and some peakness. There was two partial sales (houses not completed), one abnormal sale (trade, foreclosure, or short sale), and one normal, just simply unusual sale (very large house priced relatively appropriately). These outliers (any houses with *GrLivArea* greater then 4000 square feet) had been removed. This is a distribution of the cleaned dataset.",
"_____no_output_____"
]
],
[
[
"# Remove outliers\names = ames.query('GrLivArea < 4000').copy()\n\n# Plot a distribution of GrLivArea\nsns.histplot(data=ames, x='GrLivArea')\nplt.title('Distribution of Above Grade Living Area')\nplt.xlabel('GrLivArea (sq ft)')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Sale Price vs Overall Quality\nOverall Quality (*OverallQual*) represents physical aspects of the building and rates the overall material and finish of the house. The moset frequent value of this categorical variable is average rate (5). The violin plot of sale price versus overall quality illuminates positive correlation between these variables. The higher the quality, the higher the price.\n\nInterestingly, it looks like the missing values occur exclusively in observations with the best overall quality.\n",
"_____no_output_____"
]
],
[
[
"# Set the base color\nbase_color = sns.color_palette()[0]\n\n# Show violin plot\nplt.figure(figsize=(10,4))\nsns.violinplot(data=ames, x='OverallQual', y='logSalePrice', color=base_color, inner='quartile')\nplt.ylabel('Price ($)')\nplt.yticks(log_trans(lticks), [f'{int(xtick/1000)}K' for xtick in lticks])\nplt.xlabel('Overall Quality')\nplt.title('Sale Price vs Overall Quality')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Sale Price vs Neighborhood\nNeighborhood represent the place where the house is located. The most frequent in the dataset are houses from North Ames (15 %) followed by houses from College Creek (10 %) and Old Town (8 %). To get insight into the effect of the nominal variable *Neighborhood* I had to cluster neighborhoods according to unit price per square feet. The violin plot of sale price versus three neighborhood clusters shows a positive correlation between these variables.",
"_____no_output_____"
]
],
[
[
"# Add a variable with total surface area\names['TotalSF'] = ames['TotalBsmtSF'] + ames['1stFlrSF'] + ames['2ndFlrSF'] + ames['GarageArea']\n# Calculate price per square feet\names['SalePricePerSF'] = ames.SalePrice / ames.TotalSF\n\n# Cluster neighborhoods into three clusters\nngb_mean_df = ames.groupby('Neighborhood')['SalePricePerSF'].mean().dropna()\nbins = np.linspace(ngb_mean_df.min(), ngb_mean_df.max(), 4)\nclusters = ['LowUnitPriceCluster', 'AvgUnitPriceCluster', 'HighUnitPriceCluster']\n# Create a dict 'Neighborhood' : 'Cluster'\nngb_clusters = pd.cut(ngb_mean_df, bins=bins, labels=clusters, include_lowest=True).to_dict()\n\n# Add new feature to the dataset\names['NgbCluster'] = ames.Neighborhood.apply(lambda c: ngb_clusters.get(c, \"\")).astype(pd.CategoricalDtype(clusters, ordered=True))\n\n# Plot the new feature\nsns.violinplot(data=ames, x='NgbCluster', y='logSalePrice', color=base_color, inner='quartile')\nplt.xlabel('Neighborhood Cluster')\nplt.ylabel('Price ($)')\nplt.yticks(log_trans(lticks), [f'{int(xtick/1000)}K' for xtick in lticks])\nplt.title('Sale Price vs Neighborhood Cluster')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Sale Price vs Living Area and Location\nTwo previous figures showed a positive correlation between building and location variables and sale price. Now, let's look at the relation between a space variable *GrLivArea* and price. The scatter plot of sale price versus living area with colored neighborhood clusters justifies the approximately linear relationship between price on one side and living area and location on the other side.",
"_____no_output_____"
]
],
[
[
"# Combine space and location variables\nax = sns.scatterplot(data=ames, x='GrLivArea', y='logSalePrice', hue='NgbCluster')\nplt.title('Sale Price vs Living Area with Neighborhood Clusters')\nplt.xlabel('Living Area (sq ft)')\nplt.ylabel('Price ($)')\nplt.yticks(log_trans(lticks), [f'{int(xtick/1000)}K' for xtick in lticks])\nhandles, _ = ax.get_legend_handles_labels()\nax.legend(handles[::-1], ['High Unit Price', 'Average Unit Price', 'Low Unit Price'], title='Neighborhood Clusters')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Sale Price vs Overall Quality by Location\n\nFinally, let's look at combination of overall quality and neighborhood clusters. These violin plots of sale price versus overall quality show differences between neighborhood clusters. The most diverse cluster in regards to overall quality of houses is the one with lower unit price per square feet. As expected, houses in the cluster with high unit prices per square feet have better overall quality as wall as higer prices.",
"_____no_output_____"
]
],
[
[
"# Combine building and location variables\ng = sns.FacetGrid(data=ames, row='NgbCluster', aspect=3)\ng.map(sns.violinplot, 'OverallQual', 'logSalePrice', inner='quartile')\ng.set_titles('{row_name}')\ng.set(yticks=log_trans(lticks), yticklabels=[f'{int(xtick/1000)}K' for xtick in lticks])\ng.set_ylabels('Price ($)')\ng.fig.suptitle('Sale Price vs OverallQual For Neighborhood Clusters', y=1.01)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Conclusion\n\nThe investigation justified that the three selected explanatory variables of house can be used to predict the house sale price (a response variable). These variable are namely: \n- *above grade living area* representing space characteristics, \n- *overall quality* of house's material and finish representing physical characteristics, and \n- *neighborhood cluster* representing location characteristics; this variable was engineered by clustering neighborhoods according to unit price per square feet. \n\nAll these variables have a positive relationship with sale price of the house.\n\n## Thanks For Your Attention\nFinished 2021-11-18",
"_____no_output_____"
]
],
[
[
"# !jupyter nbconvert Part_II_slide_deck_ames.ipynb --to slides --post serve --no-input --no-prompt",
"_____no_output_____"
]
]
] |
[
"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"
]
] |
4aad0a43ab83f43bc75cf75523464c68ce08bcda
| 939,346 |
ipynb
|
Jupyter Notebook
|
4_DTM/.ipynb_checkpoints/load1234-checkpoint.ipynb
|
jlmjkfd/CS760_2021S2_PA4
|
796fa0bb1721462a109f454dc22015c63942bbe9
|
[
"MIT"
] | 2 |
2021-08-14T12:57:31.000Z
|
2021-08-15T03:17:46.000Z
|
4_DTM/.ipynb_checkpoints/load1234-checkpoint.ipynb
|
jlmjkfd/CS760_2021S2_PA4
|
796fa0bb1721462a109f454dc22015c63942bbe9
|
[
"MIT"
] | null | null | null |
4_DTM/.ipynb_checkpoints/load1234-checkpoint.ipynb
|
jlmjkfd/CS760_2021S2_PA4
|
796fa0bb1721462a109f454dc22015c63942bbe9
|
[
"MIT"
] | 1 |
2021-08-15T03:18:12.000Z
|
2021-08-15T03:18:12.000Z
| 1,134.475845 | 246,396 | 0.949903 |
[
[
[
"import pickle",
"_____no_output_____"
],
[
"with open('ldaseq1234.pickle', 'rb') as f:\n ldaseq = pickle.load(f)\n print(ldaseq.print_topic_times(topic=0))",
"C:\\Users\\irabe\\.conda\\envs\\venv\\lib\\site-packages\\gensim\\similarities\\__init__.py:15: UserWarning: The gensim.similarities.levenshtein submodule is disabled, because the optional Levenshtein package <https://pypi.org/project/python-Levenshtein/> is unavailable. Install Levenhstein (e.g. `pip install python-Levenshtein`) to suppress this warning.\n warnings.warn(msg)\n"
],
[
"topicdis = [[0.04461942257217848,\n 0.08583100499534332,\n 0.0327237321141309,\n 0.0378249089831513,\n 0.08521717043434086,\n 0.03543307086614173,\n 0.054356108712217424,\n 0.04057658115316231,\n 0.0499745999491999,\n 0.04468292269917873,\n 0.028257556515113032,\n 0.026013885361104057,\n 0.0668021336042672,\n 0.07567098467530269,\n 0.08409533485733638,\n 0.026966387266107866,\n 0.04533909067818136,\n 0.028172889679112693,\n 0.04121158242316485,\n 0.06623063246126493],\n [0.04375013958058825,\n 0.07278290193626193,\n 0.025437166402394087,\n 0.03566563190923912,\n 0.0600978180762445,\n 0.03541997007392188,\n 0.07258190588918417,\n 0.0305960649440561,\n 0.06355941666480559,\n 0.0459164303102039,\n 0.0295464189204279,\n 0.02733546240257275,\n 0.03622395426223284,\n 0.12723049780020992,\n 0.07838845836031891,\n 0.03517430823860464,\n 0.0370726042387833,\n 0.030216405744020368,\n 0.04841771445161579,\n 0.06458672979431404],\n [0.047832813411448426,\n 0.07557888863526846,\n 0.01995992797179741,\n 0.03816987496512719,\n 0.13469781125567476,\n 0.03291993202972431,\n 0.07570569885109944,\n 0.030586624058434146,\n 0.049760328692079435,\n 0.04080752745441173,\n 0.02835476425980877,\n 0.02495625047553831,\n 0.044434299627177966,\n 0.08879251312485734,\n 0.07190139237616983,\n 0.028405488346141164,\n 0.034416292576529964,\n 0.028608384691470746,\n 0.04149230261989906,\n 0.06261888457734155],\n [0.042617561579875174,\n 0.07770737052741912,\n 0.03601886702558483,\n 0.04750107199009005,\n 0.06608223355090762,\n 0.07060841393110677,\n 0.0826861689456382,\n 0.0338272428414884,\n 0.042951069607889844,\n 0.04888274810615084,\n 0.04173614750583639,\n 0.03728143313164038,\n 0.04371337367192339,\n 0.04190290151984373,\n 0.06603458954690553,\n 0.03363666682548001,\n 0.045190337795988376,\n 0.035590070989565965,\n 0.03327933679546429,\n 0.0727523941112011],\n [0.05211050194283281,\n 0.022701868313195296,\n 0.04215681056049396,\n 0.03776547612710917,\n 0.06246340554638846,\n 0.05240325757172513,\n 0.03425240858040134,\n 0.060094746367168786,\n 0.04189066907968276,\n 0.03837760153297493,\n 0.031431308883802626,\n 0.08609676904242296,\n 0.04383350188960451,\n 0.11209879171767712,\n 0.06754670782988237,\n 0.03071272688561239,\n 0.0415446851546282,\n 0.02789162718901368,\n 0.0347314632458615,\n 0.07989567253952201],\n [0.052505147563486614,\n 0.03777739647677877,\n 0.03743422557767102,\n 0.03311599176389842,\n 0.11201670098375657,\n 0.06963509494394875,\n 0.02916952642415923,\n 0.043239533287577216,\n 0.03854953099977122,\n 0.03260123541523679,\n 0.03546099290780142,\n 0.07958705101807367,\n 0.03165751544269046,\n 0.1153054221002059,\n 0.06637497140242507,\n 0.02304964539007092,\n 0.03955044612216884,\n 0.030942576069549303,\n 0.031457332418210936,\n 0.06056966369251887],\n [0.03823109185601696,\n 0.0364105636723971,\n 0.03279255196570954,\n 0.033691293727243395,\n 0.15926164907590912,\n 0.061321841729271326,\n 0.036203161727427755,\n 0.03440567820436005,\n 0.03157118495644559,\n 0.0335069364428262,\n 0.03426741024104715,\n 0.07637000506982532,\n 0.03892243167258146,\n 0.11098308521915472,\n 0.05643637369221551,\n 0.026086555745033876,\n 0.036525786975157855,\n 0.04528275798497488,\n 0.033046043231783194,\n 0.04468359681061898],\n [0.02800869900733102,\n 0.048055000175383215,\n 0.02597425374443158,\n 0.0358483285979866,\n 0.1538987688098495,\n 0.06082289803220036,\n 0.04098705671893087,\n 0.035585253779508226,\n 0.03213020449682556,\n 0.03448033954189905,\n 0.03277912238240556,\n 0.06162966080886738,\n 0.07131081412887158,\n 0.11022834894243923,\n 0.029727454488056405,\n 0.02874530849907047,\n 0.04032060051211898,\n 0.06248903854923007,\n 0.029253919814795328,\n 0.03772492896979901],\n [0.04004854368932039,\n 0.019997889404812157,\n 0.015882228788518363,\n 0.04353102574926129,\n 0.10579358379062896,\n 0.01978682988602786,\n 0.030656395103419165,\n 0.02532714225411566,\n 0.055878007598142675,\n 0.033241874208526805,\n 0.02643520472773322,\n 0.05730265934993668,\n 0.05566694807935838,\n 0.20409455466441537,\n 0.05925495989869143,\n 0.02543267201350781,\n 0.0408400168847615,\n 0.03197551709582102,\n 0.033030814689742505,\n 0.07582313212325877],\n [0.035613691698095196,\n 0.026543180407695613,\n 0.03375184990690791,\n 0.020337041103738004,\n 0.10770038669021817,\n 0.02291497589153578,\n 0.02597030601040722,\n 0.11419296319281998,\n 0.04516159831956843,\n 0.02897789659617129,\n 0.023344631689502078,\n 0.05060390509380818,\n 0.04430228672363584,\n 0.21196352699670598,\n 0.03948059387979186,\n 0.028643719864419725,\n 0.0347543801021626,\n 0.025779347877977754,\n 0.031078436052895404,\n 0.048885281901943]]",
"_____no_output_____"
]
],
[
[
"## Fig.1.a.topic proportion over time (bar chart)",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nfrom pandas.core.frame import DataFrame\nimport numpy as np\n\nfig, ax = plt.subplots(1, figsize=(32,16))\nyear = ['19Q1','19Q2','19Q3','19Q4','20Q1','20Q2','20Q3','20Q4','21Q1','21Q2']\ncol = ['#63b2ee','#76da91','#f8cb7f','#f89588','#7cd6cf','#9192ab','#7898e1','#efa666','#eddd86','#9987ce',\n '#95a2ff','#fa8080','#ffc076','#fae768','#87e885','#3cb9fc','#73abf5','#cb9bff','#90ed7d','#f7a35c']\ntopicdis1 = DataFrame(topicdis)\ntopic2 = topicdis1.T\ntopic2 = np.array(topic2)\nfor i in range(20):\n data = topic2[i]\n if i == 0:\n plt.bar(year,data)\n else:\n bot = sum(topic2[k] for k in range(i)) \n plt.bar(year,data,color=col[i],bottom = bot)\n\n# size for xticks and yticks\nplt.xticks(fontsize=20)\nplt.yticks(fontsize=20)\n# x and y limits\n# plt.xlim(-0.6, 2.5)\n# plt.ylim(-0.0, 1)\n# remove spines\nax.spines['right'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.spines['top'].set_visible(False)\n# ax.spines['bottom'].set_visible(False)\n#grid\nax.set_axisbelow(True)\nax.yaxis.grid(color='gray', linestyle='dashed', alpha=0.7)\n# title and legend\nlegend_label = ['Topic1', 'Topic2', 'Topic3', 'Topic4','Topic5','Topic6','Topic7','Topic8','Topic9','Topic10','Topic11'\n ,'Topic12','Topic13','Topic14','Topic15','Topic16','Topic17','Topic18','Topic19','Topic20']\nplt.legend(legend_label, ncol = 1, bbox_to_anchor=([1.1, 0.65, 0, 0]), loc = 'right', borderaxespad = 0., frameon = True, fontsize = 18)\nplt.rcParams['axes.titley'] = 1.05 # y is in axes-relative coordinates.\nplt.title('Topic proportions over 2019 - 2021\\n', loc='center', fontsize = 40)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Fig.1.b.topic proportion over time (line graph) - for the best topics",
"_____no_output_____"
]
],
[
[
"# best topics in seed1234\nntop = [0,7,8,14,19]",
"_____no_output_____"
],
[
"year = ['19Q1','19Q2','19Q3','19Q4','20Q1','20Q2','20Q3','20Q4','21Q1','21Q2']\ncol = ['#63b2ee','#76da91','#f8cb7f','#f89588','#7cd6cf','#9192ab','#7898e1','#efa666','#eddd86','#9987ce',\n '#95a2ff','#fa8080','#ffc076','#fae768','#87e885','#3cb9fc','#73abf5','#cb9bff','#90ed7d','#fa8080']\nfig, ax = plt.subplots(1, figsize=(32,16))\n\n# plot proportions of each topic over years\nfor i in ntop:\n ys = [item[i] for item in topicdis]\n ax.plot(year, ys, label='Topic ' + str(i+1),color = col[i],linewidth=3)\n\n# size for xticks and yticks\nplt.xticks(fontsize=25)\nplt.yticks(fontsize=25)\n# remove spines\nax.spines['right'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.spines['top'].set_visible(False)\n# x and y limits\n# plt.xlim(-0.2, 2.2)\nplt.ylim(-0.0, 0.125)\n# remove spines\nax.spines['right'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.spines['top'].set_visible(False)\n#grid\nax.set_axisbelow(True)\nax.yaxis.grid(color='gray', linestyle='dashed', alpha=0.7)\n# title and legend\nlegend_label = ['Topic1: Lipstick', 'Topic8: Tom Ford', 'Topic9: Beauty & Face products', 'Topic15: Eye Products','Topic20: Makeup','Topic6','Topic7','Topic8','Topic9','Topic10','Topic11'\n ,'Topic12','Topic13','Topic14','Topic15','Topic16','Topic17','Topic18','Topic19','Topic20']\nplt.rcParams['axes.titley'] = 1.1 # y is in axes-relative coordinates.\nplt.legend(legend_label, ncol = 1, bbox_to_anchor=([0.28, 0.975, 0, 0]), frameon = True, fontsize = 25)\nplt.title('Topic proportions over 2019 - 2021 (5 topics) \\n', loc='center', fontsize = 40)\nplt.show()",
"_____no_output_____"
]
],
[
[
"* Drop in 2020 Q4 because of delay reveal of purchase patterns. Purchased in Q4 but discuss online in Q121.",
"_____no_output_____"
],
[
"## Fig.2. topic key words over time",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"# best topics are [0,7,8,14,19]\nt = 14\ntopicEvolution0 = ldaseq.print_topic_times(topic=t)",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(2,5, figsize=(30, 15), sharex=True)\naxes = axes.flatten()\nyear = ['19Q1','19Q2','19Q3','19Q4','20Q1','20Q2','20Q3','20Q4','21Q1','21Q2']\ntitle = ['Topic1:Lipstick', 'Topic2', 'Topic3', 'Topic4','Topic5','Topic6','Topic7','Topic8: Tom Ford','Topic9: Beauty & Face Products','Topic10','Topic11'\n ,'Topic12','Topic13','Topic14','Topic15: Eye Products','Topic16','Topic17','Topic18','Topic19','Topic20: Makeup']\nfor i in range(len(topicEvolution0)):\n value = [item[1] for item in topicEvolution0[i]]\n index = [item[0] for item in topicEvolution0[i]]\n \n ax = axes[i]\n ax.barh(index,value,height = 0.7)\n plt.rcParams['axes.titley'] = 1.25 # y is in axes-relative coordinates.\n ax.set_title(year[i],\n fontdict={'fontsize': 30})\n ax.invert_yaxis()\n ax.tick_params(axis='both', which='major', labelsize=20)\n for k in 'top right left'.split():\n ax.spines[k].set_visible(False)\n fig.suptitle(title[t], fontsize=40)\n\nplt.subplots_adjust(top=0.90, bottom=0.05, wspace=0.90, hspace=0.3)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Fig.3. Trend of key words under 1 topic over time",
"_____no_output_____"
]
],
[
[
"from ekphrasis.classes.segmenter import Segmenter\nseg = Segmenter(corpus=\"twitter\")",
"Reading twitter - 1grams ...\nReading twitter - 2grams ...\n"
],
[
"ss_keywords = []\nfor i in range(len(keywords)):\n s_keywords = [] # legends are keywords with first letter capitalised\n for j in range(len(keywords[i])):\n s_keyword = seg.segment(keywords[i][j])\n s_keyword = s_keyword.capitalize()\n s_keywords.append(s_keyword)\n ss_keywords.append(s_keywords)\nss_keywords ",
"_____no_output_____"
],
[
"# CHANGE k!\nkeyTopics = [0,7,8,14,19]\nk = 3 # keyTopics index\ntopicEvolution_k = ldaseq.print_topic_times(topic=key_topics[k])\n\n# transfrom topicEvolutiont to dictionary\nfor i in range(len(topicEvolution_k)):\n topicEvolution_k[i] = dict(topicEvolution_k[i])\n \n# our most interested keywords under each topic, pick manually\nkeywords = [['nars', 'revlon', 'wetnwild', 'dior'], # keywords for topic 0\n ['tomford', 'tomfordbeauty', 'body', 'japan', 'yuta'], # keywords for topic 7\n ['ysl', 'yvessaintlaurent', 'nyx', 'charlottetilbury','ctilburymakeup','diormakeup'], # keywords for topic 8\n ['maybelline', 'makeupforever', 'mua', 'anastasiabeverlyhills', \n 'morphe', 'morphebrushes', 'hudabeauty', 'fentybeauty', 'jeffreestar'], # keywords for topic 14\n ['colourpop', 'colorpopcosmetics', 'wetnwildbeauty', 'nyx',\n 'nyxcosmetics', 'bhcosmetics', 'tarte','tartecosmetics', \n 'elfcosmetics','benefit', 'makeuprevolution', 'loreal', \n 'katvond', 'jeffreestarcosmetics', 'urbandecaycosmetics']] # keywords for topic 19",
"_____no_output_____"
],
[
"year = ['19Q1','19Q2','19Q3','19Q4','20Q1','20Q2','20Q3','20Q4','21Q1','21Q2']\ncol = ['#63b2ee','#76da91','#f8cb7f','#f89588','#7cd6cf','#9192ab','#7898e1','#efa666','#eddd86','#9987ce',\n '#95a2ff','#fa8080','#ffc076','#fae768','#87e885','#3cb9fc','#73abf5','#cb9bff','#90ed7d','#fa8080']\nfig, ax = plt.subplots(1, figsize=(32,16))\n\n# plot the value of keywords\nyss = []\nfor word in keywords[k]: # for each word in keywords\n ys = [\"0\"] * 10\n for j in range(len(topicEvolution_k)): # for each top-20-keywords dict (one dict for one time period)\n if word in topicEvolution_k[j]: # if keyword is in top 20 keywords dict\n ys[j] = topicEvolution_k[j].get(word) # assign the keyword value to jth position\n else:\n ys[j] = 0 # else assign 0 to jth position\n if k == 0 or k == 1 :\n ax.plot(year, ys, linewidth=3) # plot keyword values against year\n else:\n yss.append(ys)\n\n# k = 2\n# ['ysl', 'yvessaintlaurent', 'nyx', 'charlottetilbury','ctilburymakeup','diormakeup']\nif k == 2:\n yss = [[a + b for a, b in zip(yss[0], yss[1])],\n yss[2],\n [a + b for a, b in zip(yss[3], yss[4])],\n yss[5]]\n for i in range(len(yss)):\n ax.plot(year, yss[i], linewidth = 3)\n# k = 3\n# ['maybelline', 'makeupforever', 'mua', 'anatasiabeverlyhills', \n# 'morphe', 'morphe brushes', 'hudabeauty', 'fentybeauty', 'jeffreestar']\nif k == 3:\n for i in range(len(keywords[3])):\n if i == 4:\n ax.plot(year, [a + b for a, b in zip(yss[4], yss[5])])\n elif i == 5:\n continue\n else:\n ax.plot(year, yss[i], linewidth = 3)\n\n# k = 4: \n# ['colourpop', 'colorpopcosmetics', 'wetnwildbeauty', 'nyx',\n# 'nyxcosmetics', 'bhcosmetics', 'tarte','tartecosmetics', \n# 'elfcosmetics','benefit', 'makeuprevolution', 'loreal', \n# 'katvond', 'jeffreestarcosmetics', 'urbandecaycosmetics']\nif k == 4:\n for i in range(len(keywords[4])):\n if i == 0:\n ax.plot(year, [a + b for a, b in zip(yss[0], yss[1])])\n elif i == 1:\n continue\n elif i == 3:\n ax.plot(year, [a + b for a, b in zip(yss[3], yss[4])])\n elif i == 4:\n continue\n else:\n ax.plot(year, yss[i], linewidth = 3)\n\n# size for xticks and yticks\nplt.xticks(fontsize=25)\nplt.yticks(fontsize=25)\n# remove spines\nax.spines['right'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.spines['top'].set_visible(False)\n# grid\nax.set_axisbelow(True)\nax.yaxis.grid(color='gray', linestyle='dashed', alpha=0.7)\n# legend\nlegends = [['Nars', 'Revlon', 'wet n wild', 'Dior'],\n ['Tom Ford', 'Tom Ford Beauty', 'Body', 'Japan', 'Yuta'],\n ['YSL','NYX', 'Charlotte Tilbury','Dior'],\n ['Maybelline', 'Make Up For Ever','Mua','Anastasia Beverlyhills',\n 'Morphe','Huda Beauty','Fenty Beauty','Jeffree Star'],\n ['Colourpop','wet n wild', 'NYX','BH Cosmetics','Tarte',\n 'e.l.f','Benefit','Makeup revolution','Loreal',\n 'Kat Von D','Jeffree Star','Urban Decay']]\nplt.legend(legends[k], ncol = 1, bbox_to_anchor=([1, 1.05, 0, 0]), frameon = True, fontsize = 25)\n# title\ntitles = ['Brand occupation over topic \"Lipstick\" from 2019 - 2021',\n 'Effect of celebrity collaboration on brand',\n 'Brand occupation over topic \"Beauty & Face Products\" from 2019 - 2021',\n 'Brand occupation over topic \"Eye Products\" from 2019 - 2021',\n 'Brand occupation over topic \"Makeup\" from 2019 - 2021']\nplt.title(titles[k], loc='left', fontsize = 40)\nplt.show()",
"_____no_output_____"
],
[
"year = ['19Q1','19Q2','19Q3','19Q4','20Q1','20Q2','20Q3','20Q4','21Q1','21Q2']\ncol = ['#63b2ee','#76da91','#f8cb7f','#f89588','#7cd6cf','#9192ab','#7898e1','#efa666','#eddd86','#9987ce',\n '#95a2ff','#fa8080','#ffc076','#fae768','#87e885','#3cb9fc','#73abf5','#cb9bff','#90ed7d','#fa8080']\nfig, ax = plt.subplots(1, figsize=(32,16))\n\n# plot the value of keywords\n\nfor word in keywords[k]: # for each word in keywords\n ys = [\"0\"] * 10\n for j in range(len(topicEvolution_k)): # for each top-20-keywords dict (one dict for one time period)\n if word in topicEvolution_k[j]: # if keyword is in top 20 keywords dict\n ys[j] = topicEvolution_k[j].get(word) # assign the keyword value to jth position\n else:\n ys[j] = 0 # else assign 0 to jth position:\n ax.plot(year, ys, linewidth=3) # plot keyword values against year\n\n\n# size for xticks and yticks\nplt.xticks(fontsize=25)\nplt.yticks(fontsize=25)\n# remove spines\nax.spines['right'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.spines['top'].set_visible(False)\n# grid\nax.set_axisbelow(True)\nax.yaxis.grid(color='gray', linestyle='dashed', alpha=0.7)\n# legend\nplt.legend(keywords[k], ncol = 1, bbox_to_anchor=([1, 1.05, 0, 0]), frameon = True, fontsize = 25)\n# title\ntitles = ['Brand occupation over topic \"Lipstick\" from 2019 - 2021',\n 'Effect of celebrity collaboration on brand',\n 'Brand occupation over topic \"Beauty & Face Products\" from 2019 - 2021',\n 'Brand occupation over topic \"Eye Products\" from 2019 - 2021',\n 'Brand occupation over topic \"Makeup\" from 2019 - 2021']\nplt.title(titles[k], loc='left', fontsize = 40)\nplt.show()",
"_____no_output_____"
],
[
"# ver 1\n# for z in keywords[k]:\n# print(z)\n# ys = [item[z] for item in topicEvolution_k]\n# print(ys)\n# ax.plot(year, ys, linewidth=3)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aad0d79da4eb6202aa1f2dc6b36572555344272
| 198,203 |
ipynb
|
Jupyter Notebook
|
A Getting Started Guide For Azure Sentinel ML Notebooks.ipynb
|
Love-A/Azure-Sentinel-Notebooks
|
fa26715add90f21e3a80c70a8e664d4dfb530287
|
[
"MIT"
] | null | null | null |
A Getting Started Guide For Azure Sentinel ML Notebooks.ipynb
|
Love-A/Azure-Sentinel-Notebooks
|
fa26715add90f21e3a80c70a8e664d4dfb530287
|
[
"MIT"
] | null | null | null |
A Getting Started Guide For Azure Sentinel ML Notebooks.ipynb
|
Love-A/Azure-Sentinel-Notebooks
|
fa26715add90f21e3a80c70a8e664d4dfb530287
|
[
"MIT"
] | null | null | null | 66.067667 | 71,008 | 0.570102 |
[
[
[
"# Getting Started with Azure ML Notebooks and Microsoft Sentinel\n\n---\n\n# Contents\n\n1. Introduction<br><br>\n2. What is a Jupyter notebook?<br>\n 2.1 Using Azure ML notebooks<br>\n 2.2 Running code in notebooks<br><br>\n\n3. Initializing the notebook and MSTICPy<br><br>\n4. Notebook/MSTICPy configuration<br><br>\n 4.1 Configure Microsoft Sentinel settings<br>\n 4.2 Configure external data providers (VirusTotal and Maxmind GeoLite2)<br>\n 4.3 Configure your Azure Cloud<br>\n 4.4 Validate your settings<br>\n 4.5 Loading and reloading your settings<br><br>\n5. Query data from Microsoft Sentinel<br>\n 5.1 Load a QueryProvider<br>\n 5.2 Authenticate to your Microsoft Sentinel Workspace<br>\n 5.3 Authenticate with Azure CLI to cache your credentials<br>\n 5.4 Viewing the Microsoft Sentinel Schema<br>\n 5.5 Using built-in Microsoft Sentinel queries<br>\n 5.6 Customizable and custom queries<br><br>\n6. Testing external data providers<br>\n 6.1 Threat intelligence lookup using VirusTotal<br>\n 6.2 IP geo-location lookup with Maxmind GeoLite2<br><br>\n7. Conclusion<br><br>\n8. Further Resources<br><br>\n9. FAQs - Frequently Asked Questions\n\n---\n\n# 1. Introduction\n\nThis notebook takes you through the basics needed to get started with Azure Machine Learning (ML) Notebooks and Microsoft Sentinel.\n\nIt focuses on getting things set up and basic steps to query data.\n\nAfter you've finished running this notebook you can go on to look at the following notebooks:\n\n- **A Tour of Cybersec notebook features** - this takes you through some of the basic\n features for CyberSec investigation/hunting available to you in notebooks.\n- **Configuring your environment** - this covers all of the configuration options for \n accessing external cybersec resources\n\n\nEach topic includes 'learn more' sections to provide you with the resource to deep\ndive into each of these topics. We encourage you to work through the notebook from start\nto finish.\n\n<div style=\"color: Black; background-color: Khaki; padding: 5px; font-size: 20px\">\n<p>Please run the the code cells in sequence. Skipping cells will result in errors.</p>\n<div style=\"font-size: 14px\">\n<p>If you encounter any unexpected errors or warnings please see the FAQ at the end of this notebook.</p>\n</div>\n</div>\n\n<hr>",
"_____no_output_____"
],
[
"---\n\n# 2. What is a Jupyter notebook?\n\n<div style=\"color: Black; background-color: Gray; padding: 5px; font-size: 15px\">\nIf you're familiar with notebooks, skip this section and go to \"3. Initializing\nthe notebook and MSTICPy\" section.\n</div>\n<br>\n\nYou are currently reading a Jupyter notebook. [Jupyter](http://jupyter.org/) is an interactive\ndevelopment and data manipulation environment presented in a browser.\n\nA Jupyter notebook is a document\nmade up of cells that contain interactive code, alongside that code's output,\nand other items such as text and images (what you are looking at now is a cell of *Markdown* text).\n\nThe name, Jupyter, comes from the core supported programming languages that it supports: **Ju**lia, **Pyt**hon, and **R**.\nWhile you can use any of these languages (and others such as Powershell) we are going to use Python in this notebook.\n\nThe majority of the notebooks on the [Microsoft Sentinel GitHub repo](https://github.com/Azure/Azure-Sentinel-Notebooks)\nare written in Python. Whilst there are pros, and cons to each language, Python is a well-established\nlanguage that has a large number of materials and libraries well suited for\ndata analysis and security investigation, making it ideal for our needs.\n\nTo use a Jupyter notebook you need a Jupyter server that will render the notebook and execute the code within it.\nThis can take the form of a local [Jupyter installation](https://pypi.org/project/jupyter/),\nor a remotely hosted version such as \n[Azure Machine Learning Notebooks](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-run-jupyter-notebooks). \n\n<details>\n <summary>Learn more...</summary>\n <ul>\n <li><a href=https://infosecjupyterbook.com/introduction.html>The Infosec Jupyter Book</a>\n has more details on the technical working of Jupyter.\n </li>\n <li><a href=https://jupyter.org/documentation>The Jupyter Project documentation</a></li>\n </ul>\n</details>\n\n<br>\n\n",
"_____no_output_____"
],
[
"---\n\n## 2.1 Using Azure Machine Learning (ML) Notebooks\n\nIf you launched this notebook from Microsoft Sentinel, you will be running it in an Azure ML workspace.\nBy default, the notebook is running in the built-in notebook editor. You can also open\nand run the notebook in Jupyterlab or Jupyter classic, if these environments are more familiar\nto you.\n\n<details>\n <summary>Learn more...</summary>\n<p>Although you can view a notebook as a static document (GitHub, for example has a built-in\nstatic notebook renderer), if you want to run the code in a notebook, the notebook\nmust be attached to a backend process, know as a Jupyter kernel. The kernel\nis really where your code is being run and where all of variables and objects\ncreated in the code are held. The browser is just the viewer for this data.\n</p>\n<p>In Azure ML, the kernel runs on a virtual machine known as an Azure ML Compute.\nThe Compute instance can support the running of many notebooks simultaneously.</p>\n<p>\nUsually, the creation/attaching of a kernel for your notebook happens\nseamlessly - you don't need to do anything manually. One thing that you\nmay need to check (especially if you are getting errors or the notebook\ndoesn't seem to be executing) is the version and state of the kernel.</p>\n <ul>\n <li><a href=https://realpython.com/jupyter-notebook-introduction/>\n Installing and running a local Jupyter server\n </a>\n </li>\n </ul>\n</details>\n\nFor this notebook we are going to be using Python 3.8 (you can also choose the Python 3.6 kernel).\n\nYou can check the kernel name and version is selected by looking at\nthe drop down in the top left corner of the Workspace window as shown in\nthe image below.\n\n\n\n<img src=\"https://github.com/Azure/Azure-Sentinel-Notebooks/raw/master/images/AML_kernel.png\" height=\"200px\">\n\nThis image also shows the active compute instance (to the right).\n\n<img src=\"https://github.com/Azure/Azure-Sentinel-Notebooks/raw/master/images/AML_compute_kernel.png\" height=\"200px\">\n\n\nIf the selected kernel does not show `Azure ML Python 3.8` you can select the correct kernel by clicking on the Kernel drop-down.\n\n<p style=\"border: solid; padding: 5pt\"><b>Note</b>: the notebook works with Python 3.6 or later.\nIf you are using this notebook in another\nJupyter environment you can choose any kernel that supports Python 3.6 or later\n</p>\n\n<p style=\"border: solid; padding: 5pt; color: white; background-color: DarkOliveGreen\"><b>Tip:</b>\nSometimes, your notebook may \"hang\" or you want to just start over.\nTo do this you can restart the kernel. Use the \"recycle\" button in the toolbar\nin the upper right of the screen above the notebook.\n<br>\nYou will need to re-run any initialization and authentication cells after doing\nthis since restarting the kernel wipes all variables and other state.\n</p>\n\n<img src=\"https://github.com/Azure/Azure-Sentinel-Notebooks/raw/master/images/AML_restart_kernel.png\" height=\"200px\">\n\n<br>\n<details>\n <summary>Troubleshooting...</summary>\n <p>\nIf you are having trouble getting the notebook running you should review\n<a href=https://docs.microsoft.com/en-us/azure/machine-learning/how-to-run-jupyter-notebooks>How to run Juptyer notebooks</a>.\n</p>\n</details>\n",
"_____no_output_____"
],
[
"---\n\n## 2.2 Running code in notebooks\n\nThe **cell** below is a code cell (note that it looks different from the\ncell you are reading). The current cell is known as a *Markdown* cell\nand lets you write text (including HTML) and include static images.\n\nSelect the code cell (using mouse or cursor keys) below.\nOnce selected, you can execute the code in it by clicking the \"Play\" button in the cell, or by pressing Shift+Enter.\n\n<p style=\"border: solid; padding: 5pt; color: white; background-color: DarkOliveGreen\">\n<b>Tip</b>: You can identify which cells are code cells by selecting them.<br>\nIn Azure ML notebooks and VSCode, code cells have a larger border\non the left side with a \"Play\" button to execute the cell.<br>\nIn other notebook environments code and markdown cells will have\ndifferent styles but it's usually easy to distinguish them.\n</p>\n",
"_____no_output_____"
]
],
[
[
"# This is our first code cell, it contains basic Python code.\n# You can run a code cell by selecting it and clicking\n# the Run button (to the left of the cell), or by pressing Shift + Enter.\n# Any output from the code will be displayed directly below it.\nprint(\"Congratulations you just ran this code cell\")\ny = 2 + 2\nprint(\"2 + 2 =\", y)",
"Congratulations you just ran this code cell\n2 + 2 = 4\n"
]
],
[
[
"Variables set within a code cell persist between cells meaning you can chain cells together.\nIn this example we're using the value of y from the previous cell.",
"_____no_output_____"
]
],
[
[
"# Note that output from the last line of a cell is automatically\n# sent to the output cell, without needing the print() function.\ny + 2",
"_____no_output_____"
]
],
[
[
"Now that you understand the basics we can move onto more complex code.\n\n\n<details>\n <summary>Learn more about notebooks...</summary>\n <ul>\n <li><a href=https://infosecjupyterbook.com/>The Infosec Jupyter Book</a>\n provides an infosec-specific intro to Python.\n </li>\n <li><a href=https://realpython.com/>Real Python</a>\n is a comprehensive set of Python learnings and tutorials.</li>\n <ul>\n\n</details>\n",
"_____no_output_____"
],
[
"---\n\n# 3. Initializing the notebook and MSTICPy\n\nTo avoid having to type (or paste) a lot of complex and repetitive code into\nnotebook cells, most notebooks rely on third party libraries (known in the Python\nworld as \"packages\").\n\nBefore you can use a package in your notebook, you need to do two things:\n\n- install the package (although the Azure ML Compute has most common packages pre-installed)\n- import the package (or some part of the package - usually a module/file, a function or a class)\n\n## MSTICPy\n\nWe've created a Python package built for Microsoft Sentinel notebooks - named MSTICPy (pronounced miss-tick-pie).\nIt is a collection of CyberSecurity tools for data retrieval, analysis, enrichment and visualization.\n\n## Intializing notebooks\n\nAt the start of most Microsoft Sentinel notebooks you will see an initialization cell like the one below.\nThis cell is specific to the MSTICPy initialization:\n\n- it defines the minimum versions for Python and MSTICPy needed for this notebook\n- it then imports and runs the `init_notebook` function.\n\n<details>\n <summary>More about <i>init_notebook</i>...</summary>\n <p>\n`init_notebook` does some of the tedious work of importing other packages, \nchecking configuration (we'll get to configuration in a moment) and, optionally,\ninstalling other required packages.</p>\n</details>\n<br>\n\n<div style=\"border: solid; padding: 5pt\">\n<b>Note: </b>don't be alarmed if you see configuration warnings (such as \"Missing msticpyconfig.yaml\").<br>\nWe haven't configured anything yet, so this is expected.<br>\nYou may also see some warnings about package version conflicts. It is usually safe\nto ignore these.\n</div>\n\nThe first line ensures that the latest version of msticpy is installed.",
"_____no_output_____"
]
],
[
[
"# import some modules needed in this cell\nfrom IPython.display import display, HTML\n\nREQ_PYTHON_VER=\"3.6\"\nREQ_MSTICPY_VER=\"1.4.3\"\n\ndisplay(HTML(\"Checking upgrade to latest msticpy version\"))\n# %pip install --upgrade --quiet msticpy[azuresentinel]\n\n# initialize msticpy\nfrom msticpy.nbtools import nbinit\nnbinit.init_notebook(\n namespace=globals(),\n extra_imports=[\"urllib.request, urlretrieve\"]\n)\npd.set_option(\"display.html.table_schema\", False)",
"_____no_output_____"
]
],
[
[
"---\n\n# 4. Notebook/MSTICPy Configuration\n\nOnce we've done this basic initialization step,\nwe need to make sure we have some configuration in place.\n\nSome of the notebook components need addtional configuration to connect our Microsoft Sentinel workspace\nas well as to external services (e.g. API keys to retrieve Threat Intelligence data). \n\nThe easiest way to manage the configuration data for these services is to store it in a \nconfiguration file (`msticpyconfig.yaml`).<br>\nThe alternative to this is having to type\nconfiguration details and keys in each time you use a notebook - which is\nguaranteed to put you off notebooks forever!\n\n<details>\n <summary>Learn more...</summary>\n <p>\n Although you don't need to know these details now, you can find more information here:\n </p>\n <ul>\n <li><a href=https://msticpy.readthedocs.io/en/latest/getting_started/msticpyconfig.html >MSTICPy Package Configuration</a></li>\n <li><a href=https://msticpy.readthedocs.io/en/latest/getting_started/SettingsEditor.html >MSTICPy Settings Editor</a></li>\n </ul>\n <p>If you need a more complete walk-through of configuration, we have a separate notebook to help you:</p>\n <ul>\n <li><a href=https://github.com/Azure/Azure-Sentinel-Notebooks/blob/master/ConfiguringNotebookEnvironment.ipynb >Configuring Notebook Environment</a></li>\n <li>And for the ultimate walk-through of how to configure all your `msticpyconfig.yaml` settings\n see the <a href=https://github.com/microsoft/msticpy/blob/master/docs/notebooks/MPSettingsEditor.ipynb >MPSettingsEditor notebook</a></li>\n <li>The Azure-Sentinel-Notebooks GitHub repo also contains an template `msticpyconfig.yaml`, with commented-out sections\n that may also be helpful in finding your way around the settings if you want to dig into things\n by hand.</li>\n </ul>\n</details>\n<br>\n\n---",
"_____no_output_____"
],
[
"## 4.1 Configuring Microsoft Sentinel settings\n\nWhen you launched this notebook from Microsoft Sentinel it copied a basic configuration file - `config.json` -\nto your workspace folder.<br>\nYou should be able to see this file in the file browser to the left.<br>\nThis file contains details about your Microsoft Sentinel workspace but has\nno configuration settings for other external services that we need.\n\nIf you didn't have a `msticpyconfig.yaml` file in your workspace folder (which is likely\nif this is your first use of notebooks), the `init_notebook` function should have created\none for you and populated it\nwith the Microsoft Sentinel workspace data taken from your config.json.\n\n<p style=\"border: solid; padding: 5pt; color: white; background-color: DarkOliveGreen\"><b>Tip:</b>\nIf you do not see a \"msticpyconfig.yaml\" file in your user folder, click the refresh button<br>\nat the top of the file browser.\n</p>\n\nWe can check this now by opening the settings editor and view the settings.\n\n<div style=\"color: Black; background-color: Khaki; border: solid; padding: 5pt;\"><b>\nYou should not have to change anything here unless you need to add\none or more additional workspaces.</b></div>\n<p/>\n<p style=\"border: solid; padding: 5pt\"><b>Note:</b>\nIn the Azure ML environment, the settings editor may take 10-20 seconds to appear.<br>\nThis is a known bug that we are working to fix.\n</p>\n\nWhen you have verified that this looks OK. Click **Save Settings**\n\n\n<details>\n <summary>Multiple Microsoft Sentinel workspaces...</summary>\n <p>If you have multiple Microsoft Sentinel workspaces, you can add\n them in the following configuration cell.</p>\n <p>You can choose to keep one as the default or just delete this entry\n if you always want to name your workspaces explicitly when you \n connect.\n </p>\n</details>",
"_____no_output_____"
]
],
[
[
"from msticpy.config import MpConfigEdit\nimport os\n\nmp_conf = \"msticpyconfig.yaml\"\n\n# check if MSTICPYCONFIG is already an env variable\nmp_env = os.environ.get(\"MSTICPYCONFIG\")\nmp_conf = mp_env if mp_env and Path(mp_env).is_file() else mp_conf\n\nif not Path(mp_conf).is_file():\n print(\n \"No msticpyconfig.yaml was found!\",\n \"Please check that there is a config.json file in your workspace folder.\",\n \"If this is not there, go back to the Microsoft Sentinel portal and launch\",\n \"this notebook from there.\",\n sep=\"\\n\"\n )\nelse:\n mpedit = MpConfigEdit(mp_conf)\n mpedit.set_tab(\"AzureSentinel\")\n display(mpedit)",
"_____no_output_____"
]
],
[
[
"At this stage you should only see two entries in the Microsoft Sentinel tab:\n\n- An entry with the name of your Microsoft Sentinel workspace\n- An entry named \"Default\" with the same settings.\n\nMSTICPy lets you store configurations for multiple Microsoft Sentinel workspaces\nand switch between them. The \"Default\" entry lets you authenticate\nto a specific workspace without having to name it explicitly.\n\nLet's add some additional configuration.",
"_____no_output_____"
],
[
"## 4.2 Configure external data providers (VirusTotal and Maxmind GeoLite2)\n\nWe are going to use [VirusTotal](https://www.virustotal.com) (VT) as an example of a popular threat intelligence source.\nTo use VirusTotal threat intel lookups you will need a VirusTotal account and API key.\n\nYou can sign up for a free account at the\n[VirusTotal getting started page](https://developers.virustotal.com/v3.0/reference#getting-started) website.\n\nIf you are already a VirusTotal user, you can, of course, use your existing key.\n\n<p style=\"border: solid; padding: 5pt; color: black; background-color: Khaki\">\n<b>Warning</b> If you are using a VT enterprise key we do not recommend storing this\nin the msticpyconfig.yaml file.<br>\nMSTICPy supports storage of secrets in\nAzure Key Vault. You can read more about this\n<a href=https://msticpy.readthedocs.io/en/latest/getting_started/msticpyconfig.html#specifying-secrets-as-key-vault-secrets >in the MSTICPY docs</a><br>\nFor the moment, you can sign up for a free acount, until you can take the time to\nset up Key Vault storage.\n</p>\n\n\nAs well as VirusTotal, we also support a range\nof other threat intelligence providers: https://msticpy.readthedocs.io/en/latest/data_acquisition/TIProviders.html\n<br><br>\n\nTo add the VirusTotal details, run the following cell.\n\n1. Select \"VirusTotal\" from the **Add prov** drop down\n2. Click the **Add** button\n3. In the left-side Details panel select **Text** as the Storage option.\n4. Paste the API key in the **Value** text box.\n5. Click the **Update** button to confirm your changes.\n\nYour changes are not yet saved to your configuration file. To\ndo this, click on the **Save Settings** button at the bottom of the dialog.\n\nIf you are unclear about what anything in the configuration editor means, use the **Help** drop-down. This\nhas instructions and links to more detailed documentation.\n",
"_____no_output_____"
]
],
[
[
"display(mpedit)\nmpedit.set_tab(\"TI Providers\")\n",
"_____no_output_____"
]
],
[
[
"Our notebooks commonly use IP geo-location information. \nIn order to enable this we are going to set up [MaxMind GeoLite2](https://www.maxmind.com)\nto provide geolocation lookup services for IP addresses.\n\nGeoLite2 uses a downloaded database which requires an account key to download.\nYou can sign up for a free account and a license key at \n[The Maxmind signup page - https://www.maxmind.com/en/geolite2/signup](https://www.maxmind.com/en/geolite2/signup).\n<br>\n\n<details>\n <summary>Using IPStack as an alernative to GeoLite2...</summary>\n <p>\n For more details see the\n <a href=https://msticpy.readthedocs.io/en/latest/data_acquisition/GeoIPLookups.html >\n MSTICPy GeoIP Providers documentation</a>\n </p>\n</details>\n<br>\n\nOnce, you have an account, run the following cell to add the Maxmind GeopIP Lite details to your configuration.\n\nThe procedure is similar to the one we used for VirusTotal:\n\n1. Select the \"GeoIPLite\" provider from the **Add prov** drop-down\n2. Click **Add**\n3. Select **Text** Storage and paste the license (API/Auth) key into the text box\n4. Click **Update**\n5. Click **Save Settings** to write your settings to your configuration.\n",
"_____no_output_____"
]
],
[
[
"display(mpedit)\nmpedit.set_tab(\"GeoIP Providers\")\n",
"_____no_output_____"
]
],
[
[
"## 4.3 Configure your Azure Cloud\n\nIf you are running in a sovereign or government cloud (i.e. not the Azure global cloud)\nyou must set up Azure functions to use the correct authentication and\nresource management authorities.\n\n<p style=\"border: solid; padding: 5pt\"><b>Note:</b>\nThis is not required if using the Azure Global cloud (most common).<br>\nIf the domain of your Microsoft Sentinel or Azure Machine learning does\nnot end with '.azure.com' you should set the appropriate cloud\nfor your organization\n</p>",
"_____no_output_____"
]
],
[
[
"display(mpedit)\nmpedit.set_tab(\"Azure\")\n",
"_____no_output_____"
]
],
[
[
"## 4.4 Validate your settings\n\n- click on the **Validate settings** button.\n\nYou may see some warnings about missing sections but not about the Microsoft Sentinel, TIProviders or GeoIP Providers settings.\n\nClick on the **Close** button to hide the validation output.\n\nIf you need to make any changes as a result of the Validation,\nremember to save your changes by clicking the **Save File** button.",
"_____no_output_____"
],
[
"## 4.5 Loading and re-loading your saved settings\n\n<h3 stylecolor: Black; background-color: Khaki;i; padding: 5px\">\nAlthough your settings are saved they are not yet loaded into MSTICPy. Please run the next cell.</h3>\n<hr>\n\nYou have saved your settings to a \"msticpyconfig.yaml\" file on disk. This file<br>\nis a YAML file so is easy to read with a text editor.<br>\nHowever, MSTICPy does not automatically reload these settings.\n\nRun the following cell to force it to reload from the new configuration file.\n",
"_____no_output_____"
]
],
[
[
"import msticpy\nmsticpy.settings.refresh_config()",
"_____no_output_____"
]
],
[
[
"\n<details>\n <summary>Optional - set a MSTICPYCONFIG environment variable...</summary>\n\nSetting a `MSTICPYCONFIG` environment variable to point to the location of your\nyour `msticpyconfig.yaml` configuration file lets MSTICPy find this file. By\ndefault, it looks in the current directory only.\n\nHaving a MSTICPYCONFIG variable set is especially convenient if you are\nusing notebooks locally or have a deep or complex folder structure\n\n<b>You may not need this on Azure ML</b> - the\n`nb_check` script (in the initialization cell) will automatically set the MSTICPYCONFIG\nenvironment variable if it is not already set. The script will try to find a\n`msticpyconfig.yaml` in the current directory or in the root of your AML user folder.\n\nFor more detailed instructions on this, please see the *Setting the path to your msticpyconfig.yaml* section\nin the <a href=https://github.com/Azure/Azure-Sentinel-Notebooks/blob/master/ConfiguringNotebookEnvironment.ipynb >Configuring Notebook Environment</a>.\n\n<p style=\"border: solid; padding: 5pt; color: black; background-color: #AA4000\">\n<b>Warning</b>: If you are storing secrets such as API keys in the file you should<br>\nprobably opt to store either store this file on the compute instance or use<br.>\nAzure Key Vault to store the secrets.<br>\nRead more about using KeyVault\n<a href=https://msticpy.readthedocs.io/en/latest/getting_started/msticpyconfig.html#specifying-secrets-as-key-vault-secrets >in the MSTICPY docs</a>\n</p>\n\n</details>\n",
"_____no_output_____"
],
[
"---\n\n# 5. Querying Data from Microsoft Sentinel\n\nNow that we have configured the details for your Microsoft Sentinel workspace, \nwe can go ahead and test it. We will do this with `QueryProvider` class from MSTICPy.\n\nThe QueryProvider class has one main function:\n\n- querying data from a data source to make it available to view and analyze in the notebook.\n\nQuery results are always returned as *pandas* DataFrames. If you are new\nto using *pandas* look at the **Introduction to Pandas** section at in\nthe **A Tour of Cybersec notebook features** notebook.\n\n<details>\n <summary>Other data sources...</summary>\n <p>\n The query provider supports several different data sources - the one we'll use\nhere is \"AzureSentinel\".</p>\n<p>\nOther data sources supported by the `QueryProvider` class include Microsoft Defender for Endpoint,\nSplunk, Microsoft Graph API, Azure Resource Graph but these are not covered here.\n </p>\n</details>\n<br>\n\nMost query providers come with a range of built-in queries\nfor common data operations. You can also a query provider to run custom queries against\nMicrosoft Sentinel data.\n\nOnce you've loaded a QueryProvider you'll normally need to authenticate\nto the data source (in this case Microsoft Sentinel).\n\n<details>\n <summary><b>Learn more...</b></summary>\n <p>\n More details on configuring and using QueryProviders:\n </p>\n <ul>\n <li>\n <a href=https://msticpy.readthedocs.io/en/latest/data_acquisition/DataProviders.html#instantiating-a-query-provider >MSTICPy Documentation</a>.</li>\n </ul>\n</details>\n<br>\n",
"_____no_output_____"
],
[
"## 5.1 Load a QueryProvider\nTo start, we are going to load up a QueryProvider\nfor Microsoft Sentinel, pass it the \ndetails for our workspace that we just stored in the msticpyconfig file, and connect.\n\n<div style=\"border: solid; padding: 5pt\"><b>Note:</b>\nIf you see a warning \"Runtime dependency of PyGObject is missing\" when loading the<br>\nMicrosoft Sentinel driver, please see the FAQ section at the end of this notebook.<br>\nThe warning does not impact any functionality of the notebooks.\n</div>",
"_____no_output_____"
]
],
[
[
"# Initalize a QueryProvider for Microsoft Sentinel\nqry_prov = QueryProvider(\"AzureSentinel\")",
"Please wait. Loading Kqlmagic extension...done\n"
]
],
[
[
"## 5.2 Authenticate to the Microsoft Sentinel workspace\n\nNext we need to authenticate The code cell immediately following this section\nwill start the authentication process. e.When you run the cell it will trigger an Azure authentication sequence.\n\n\nThe connection process will ask us to authenticate to our Microsoft Sentinel workspace using \n[device authorization](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code)\nwith our Azure credentials.\n\nDevice authorization adds an additional factor to the authentication by generating a\none-time device code that you supply as part of the authentication process.\n\nThe process is as follows:\n\n1. generate and display an device code\n\n<img src=\"https://github.com/Azure/Azure-Sentinel-Notebooks/raw/master/images/device_auth_code.png\" height=\"300px\">\n\nIn some Jupyter notebook interfaces, step 1 has a clickable button that will copy the code to the clipboard\nand then open a browser window to the devicelogin URI.<br>The default AML notebook interface does not\ndo this. You need to manually select and copy the code to the clipboard, then click on the devicelogin link\nwhere you can paste the code in to start the authentication process.\n\n2. go to http://microsoft.com/devicelogin and paste in the code\n3. authenticate with your Azure credentials\n\n<p style=\"border: sols:id; <br>\n1. Tdding: 5pt\"><b>Note:</b> the devicelogin URL may be different for government <br>\n2. You must use an account that has permissions to the Microsoft Sentinel workspace.<br>\n(<b>Microsoft Sentinel Reader</b> or <b>Log Analytics Reader</b>)\nor national Azure clouds.</p>\n\n<br>\n\n<img src=\"https://github.com/Azure/Azure-Sentinel-Notebooks/raw/master/images/device_authn.png\" height=\"300px\">\n\n4. Once the last box in the previous image is shown you can close that tab and return to the notebook. \n You should see an image like the one shown below.\n\n<img src=\"https://github.com/Azure/Azure-Sentinel-Notebooks/raw/master/images/device_auth_complete.png\" height=\"300px\">\n\n<br>\n",
"_____no_output_____"
]
],
[
[
"# Get the Microsoft Sentinel workspace details from msticpyconfig\n# Loading WorkspaceConfig with no parameters will use the details\n# of your \"Default\" workspace (see the Configuring Microsoft Sentinel settings section earlier)\n# If you want to connect to a specific workspace use this syntax:\n# ws_config = WorkspaceConfig(workspace=\"WorkspaceName\")\n# ('WorkspaceName' should be one of the workspaces defined in msticpyconfig.yaml)\nws_config = WorkspaceConfig()\n \n# Connect to Microsoft Sentinel with our QueryProvider and config details\nqry_prov.connect(ws_config)",
"Connecting... "
]
],
[
[
"## 5.3 Authenticating with Azure CLI to cache your logon credentials\n\nNormally, you may need to re-authenticate if you restart the kernel in the current notebook.\nYou also have to authenticate again if you open another notebook.\n\nYou can avoid this by using Azure CLI to create a cached logon on the AML compute (this is described\nin the FAQ section at the end of the notebook).<br>\n\n<div style=\"border: solid; padding: 5pt; color: white; background-color: DarkOliveGreen\"><b>Tip:</b>\nThis also works with other types of Jupyter hub: for example, if you are running the\nJupyter server on your local computer or using another remote Jupyter server.<br>\n</div>\n<p>\nThe Azure CLI\nlogon has to be performed on the system where your Jupyter server is running. If\nyou are using a remote Jupyter server, you can do this by opening a terminal\nand running <pre>az login</pre> on the remote machine.</p>\nMore, simply you can create an empty cell in a notebook and run\n<pre>!az login</pre><br>\nAzure CLI must be installed on the system where your Jupyter server is running.\n\nThis information is also available in a \n[Wiki article](https://github.com/Azure/Azure-Sentinel-Notebooks/wiki/Caching-credentials-with-Azure-CLI)\n\nThe Azure CLI logon will cache the token even if you restart kernel.<AML br>\nThis <i>refresh token</i> is cached on the compute (Jupyter server)\nand can be re-used until it times out.<br>\nYou will need to re-authenticate if you restart your compute instance/\nJupyter server or switch to a different compute/server.\n\nYou can try this by uncommenting the line in the cell below and running it.",
"_____no_output_____"
]
],
[
[
"#!az login\n",
"_____no_output_____"
]
],
[
[
"## 5.4 Viewing the Microsoft Sentinel workspace data schema\n\nYou can use the schema to help understand what data is available to query.<br>\n\nThis also works as a quick test to ensure that you've authenticated successfully\nto your Microsoft Sentinel workspace.\n\nThe AzureSentinel QueryProvider has a `schema_tables` property that lets us get a list of tables.\nIt also has the `schema` property which returns a dictionary of \\<table_name, column_schema\\>.\nFor each table the column names and data types are shown.\n\n<p style=\"border: solid; padding: 5pt\"><b>Note:</b>\nIf you see an error here, make sure that you ran the previous cells in this\nsection and that your authentication succeeded.\n</p>",
"_____no_output_____"
]
],
[
[
"# Get list of tables in our Workspace with the 'schema_tables' property\nprint(\"Sample of first 10 tables in the schema\")\nqry_prov.schema_tables[:10] # We are outputting only a sample of tables for brevity\n # remove the \"[:10]\" to see the whole list\n",
"Sample of first 10 tables in the schema\n"
]
],
[
[
"## 5.5 Using built-in Microsoft Sentinel queries in MSTICPy\n\nMSTICPy includes a number of built-in queries that you can run.\n\nEach query is a function (or method) that's a member of the\n`QueryProvider` object that you loaded earlier. Notice, in\nthe list of queries below, each query has a two-part name, separated\nby a dot. The first part is a container name that helps to group\nthe queries in related sets. The second part (after the dot) is the\nname of the query function itself.\n\nYou run a\nquery by specifying the name of the `QueryProvider` instance,\nfollowed by the fully-qualified name (i.e. container_name + \".\" + query_name),\nfollowed by a set of parentheses. For example:\n\n```Python\nqry_prov.Azure.get_vmcomputer_for_host(host_name=\"my-computer\")\n```\n\nInside the parentheses is where you specify parameters to the query\n(nearly all queries require one or more parameters).\n\nList available queries with the QueryProvider `.list_queries()` function<br>\nand get specific details about a query, and its required and optional\nparameters by running the query function with \"?\" as the only parameter.",
"_____no_output_____"
]
],
[
[
"# Get a sample of available queries\nprint(\"Sample of queries\")\nprint(\"=================\")\nprint(qry_prov.list_queries()[::5]) # showing a sample - remove \"[::5]\" for whole list\n\n# Get help about a query by passing \"?\" as a parameter\nprint(\"\\nHelp for 'list_all_signins_geo' query\")\nprint(\"=====================================\")\nqry_prov.Azure.list_all_signins_geo(\"?\")",
"Sample of queries\n=================\n['Azure.get_vmcomputer_for_host', 'Azure.list_azure_activity_for_account', 'AzureNetwork.az_net_analytics', 'AzureNetwork.get_heartbeat_for_ip', 'AzureSentinel.get_bookmark_by_id', 'Heartbeat.get_heartbeat_for_host', 'LinuxSyslog.all_syslog', 'LinuxSyslog.list_logon_failures', 'LinuxSyslog.sudo_activity', 'MultiDataSource.get_timeseries_decompose', 'Network.get_host_for_ip', 'Office365.list_activity_for_ip', 'SecurityAlert.list_alerts_for_ip', 'ThreatIntelligence.list_indicators_by_filepath', 'WindowsSecurity.get_parent_process', 'WindowsSecurity.list_host_events', 'WindowsSecurity.list_hosts_matching_commandline', 'WindowsSecurity.list_other_events']\n\nHelp for 'list_all_signins_geo' query\n=====================================\nQuery: list_all_signins_geo\nData source: AzureSentinel\nGets Signin data used by morph charts\n\nParameters\n----------\nadd_query_items: str (optional)\n Additional query clauses\nend: datetime (optional)\n Query end time\nstart: datetime (optional)\n Query start time\n (default value is: -5)\ntable: str (optional)\n Table name\n (default value is: SigninLogs)\nQuery:\n {table} | where TimeGenerated >= datetime({start}) | where TimeGenerated <= datetime({end}) | extend Result = iif(ResultType==0, \"Sucess\", \"Failed\") | extend Latitude = tostring(parse_json(tostring(LocationDetails.geoCoordinates)).latitude) | extend Longitude = tostring(parse_json(tostring(LocationDetails.geoCoordinates)).longitude)\n"
]
],
[
[
"### MSTICPy Query browser\n\nThe query browser combines both of the previous functions in a scrollable<br>\nand filterable list. For the selected query, it shows the required and<br>\noptional parameters, together with the full text of the query.<br>\n\nYou cannot execute queries from the browser but you can copy and paste\nthe example shown below the help for each query.\n",
"_____no_output_____"
]
],
[
[
"qry_prov.browse_queries()",
"_____no_output_____"
]
],
[
[
"### Run some queries\n\n### Most queries require time parameters!\n\nDatetime strings are **painful** to type in and keep track of. \nWe can use MSTICPy's `nbwidgets.QueryTime` class to define \"start\" and \"end\" for queries.\n\nEach query provider has its own `QueryTime` instance built-in. If the query\nneeds \"start\" and \"end\" parameters and you do not supply them, the query\nwill take the time from this built-in timerange control.",
"_____no_output_____"
]
],
[
[
"# Open the query time control for our query provider\nqry_prov.query_time",
"_____no_output_____"
]
],
[
[
"### Run a query using this time range.\n\nQuery results are returned as a [Pandas DataFrame](https://pandas.pydata.org/).\nA dataframe is a tabular data structure much like a spreadsheet or\ndatabase table.\n\n<details>\n <summary>Learn more about DataFrames...</summary>\n <p>\n <ul>\n <li>\n The <a href=https://pandas.pydata.org/ >Pandas website</a> has an extensive user guide.</li>\n <li>The <i>A Tour of Cybersec notebook features</i> has a brief introduction to common pandas operations.</li>\n </ul>\n </p>\n</details>\n",
"_____no_output_____"
]
],
[
[
"# The time parameters are taken from the qry_prov time settings\n# but you can override this by supplying explict \"start\" and \"end\" datetimes\nsignins_df = qry_prov.Azure.list_all_signins_geo()\n\nif signins_df.empty:\n md(\"The query returned no rows for this time range. You might want to increase the time range\")\n\n# display first 5 rows of any results\nsignins_df.head() # If you have no data you will just see the column headings displayed",
"_____no_output_____"
]
],
[
[
"## 5.6 Customizable and custom queries\n\n### Customizing built-in queries\n\nMost built-in queries support the \"add_query_items\" parameter.\nYou can use this to append additional filters or other operations to the built-in queries.\n\nMicrosoft Sentinel queries use the Kusto Query Language (KQL).\n\n<div style=border: solid; padding: 5pt\"><b>Note:</b>\nIf the query in following cell returns too many or too few results you can change the \"28\"\nin the query below to a smaller or larger number of days.\n</div>\n<br>\n\n<details>\n <summary>Learn more about KQL query syntax...</summary>\n <p>\n <a href=https://aka.ms/kql >Kusto Query Language reference</a><br>\n </p>\n</details>\n<br>\n",
"_____no_output_____"
]
],
[
[
"from datetime import datetime, timedelta\n\nqry_prov.SecurityAlert.list_alerts(\n start=datetime.utcnow() - timedelta(28),\n end=datetime.utcnow(),\n add_query_items=\"| summarize NumAlerts=count() by AlertName\"\n)",
"_____no_output_____"
]
],
[
[
"### Custom queries\n\nAnother way to run queries is to pass a full KQL query string to the query provider.\n\nThis will run the query against the workspace connected to above, and will return the data \nas DataFrame.\n",
"_____no_output_____"
]
],
[
[
"# Define our query\ntest_query = \"\"\"\nOfficeActivity\n| where TimeGenerated > ago(1d)\n| take 10\n\"\"\"\n\n# Pass that query to our QueryProvider\noffice_events_df = qry_prov.exec_query(test_query)\ndisplay(office_events_df.head())\n",
"_____no_output_____"
]
],
[
[
"<details>\n <summary>Learn more about MSTICPy pre-defined queries...</summary>\n <ul>\n <li>\n <a href=https://msticpy.readthedocs.io/en/latest/data_acquisition/DataProviders.html#running-an-pre-defined-query >Running MSTICPy pre-defined queries</a>\n </li>\n <li>\n <a href=https://msticpy.readthedocs.io/en/latest/data_acquisition/DataQueries.html>MSTICPy query reference</a>\n </li>\n </ul>\n</details>\n<br>\n",
"_____no_output_____"
],
[
"---\n\n# 6. Testing external data providers\n\nThreat intelligence and IP location are two common enrichments that you might apply to queried data.\n\nLet's test the VirusTotal provider with a known bad IP Address.\n\n<details>\n <summary>Learn more...</summary>\n <p>\n </p>\n <ul>\n <li>More details are shown in the <i>A Tour of Cybersec notebook features</i> notebook</li>\n <li><a href=https://msticpy.readthedocs.io/en/latest/data_acquisition/TIProviders.html >Threat Intel Lookups in MSTICPy</a></li>\n </ul>\n</details>\n<br>\n\n\n## 6.1 Threat intelligence lookup using VirusTotal\n",
"_____no_output_____"
]
],
[
[
"# Create our TI provider\nti = TILookup()\n\n# Lookup an IP Address\nti_resp = ti.lookup_ioc(\"85.214.149.236\", providers=[\"VirusTotal\"])\n\nti_df = ti.result_to_df(ti_resp)\nti.browse_results(ti_df, severities=\"all\")",
"Using Open PageRank. See https://www.domcop.com/openpagerank/what-is-openpagerank\n"
]
],
[
[
"## 6.2 IP geolocation lookup with Maxmind GeoLite2\n\n<div style=\"border: solid; padding: 5pt\"><b>Note:</b>\nYou may see the GeoLite driver downloading its database the first time you run this.\n</div>\n<br>\n<details>\n <summary>Learn more about MSTICPy GeoIP providers...</summary>\n <p>\n <a href=https://msticpy.readthedocs.io/en/latest/data_acquisition/GeoIPLookups.html >MSTICPy GeoIP Providers</a>\n </p>\n</details>\n<br>\n",
"_____no_output_____"
]
],
[
[
"geo_ip = GeoLiteLookup()\nraw_res, ip_entity = geo_ip.lookup_ip(\"85.214.149.236\")\ndisplay(ip_entity[0])",
"_____no_output_____"
]
],
[
[
"---\n\n# 7. Conclusion\n\nIn this notebook, we've gone through the basics of installing MSTICPy and setting up configuration.\nWe also briefly introduced:\n\n- QueryProviders and querying data from Microsoft Sentinel\n- Threat Intelligence lookups using VirusTotal\n- Geo-location lookups using MaxMind GeoLite2\n\nWe encourage you to run through the **A Tour of Cybersec notebook features** notebook\nto get a better feel for some more of the capabilities of notebooks and MSTICPy.</br>\n\nThis notebook includes:\n\n- more examples of queries\n- visualizing your data\n- brief introduction to using panda to manipulate your data.\n\nAlso try out any of the notebooks in the [Microsoft Sentinel Notebooks GitHub repo](https://github.com/Azure/Azure-Sentinel-Notebooks)\n",
"_____no_output_____"
],
[
"---\n\n# 8. Futher resources\n\n - [Jupyter Notebooks: An Introduction](https://realpython.com/jupyter-notebook-introduction/)\n - [Threat Hunting in the cloud with Azure Notebooks](https://medium.com/@maarten.goet/threat-hunting-in-the-cloud-with-azure-notebooks-supercharge-your-hunting-skills-using-jupyter-8d69218e7ca0)\n - [MSTICPy documentation](https://msticpy.readthedocs.io/)\n - [Microsoft Sentinel Notebooks documentation](https://docs.microsoft.com/en-us/azure/sentinel/notebooks)\n - [The Infosec Jupyterbook](https://infosecjupyterbook.com/introduction.html)\n - [Linux Host Explorer Notebook walkthrough](https://techcommunity.microsoft.com/t5/azure-sentinel/explorer-notebook-series-the-linux-host-explorer/ba-p/1138273)\n - [Why use Jupyter for Security Investigations](https://techcommunity.microsoft.com/t5/azure-sentinel/why-use-jupyter-for-security-investigations/ba-p/475729)\n - [Security Investigtions with Microsoft Sentinel & Notebooks](https://techcommunity.microsoft.com/t5/azure-sentinel/security-investigation-with-azure-sentinel-and-jupyter-notebooks/ba-p/432921)\n - [Pandas Documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/index.html)\n - [Bokeh Documentation](https://docs.bokeh.org/en/latest/)",
"_____no_output_____"
],
[
"---\n\n# 9. FAQs\n\nThe following links take you to short articles in the Azure-Sentinel-Notebooks Wiki\nthat answer common questions.\n\n## [How can I download all Azure-Sentinel-Notebooks notebooks to my Azure ML workspace?](https://github.com/Azure/Azure-Sentinel-Notebooks/wiki/How-can-I-download-all-Azure-Sentinel-Notebooks-notebooks-to-my-Azure-ML-workspace%3F)\n\n## [Can I install MSTICPy by default on a new AML compute?](https://github.com/Azure/Azure-Sentinel-Notebooks/wiki/Can-I-install-MSTICPy-by-default-on-a-new-AML-compute%3F)\n\n## [I see error \"Runtime dependency of PyGObject is missing\" when I load a query provider](https://github.com/Azure/Azure-Sentinel-Notebooks/wiki/%22Runtime-dependency-of-PyGObject-is-missing%22-error)\n\n## [MSTICPy and other packages do not install properly when switching between the Python 3.6 or 3.8 Kernels](https://github.com/Azure/Azure-Sentinel-Notebooks/wiki/MSTICPy-and-other-packages-do-not-install-properly-when-switching-between-the-Python-3.6-or-3.8-Kernels)\n\n## [My user account/credentials do not get cached between notebook runs - using Azure CLI](https://github.com/Azure/Azure-Sentinel-Notebooks/wiki/Caching-credentials-with-Azure-CLI)\n\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"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"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",
"markdown"
]
] |
4aad120bd51ab08e04e865bb746282e6656840cf
| 16,868 |
ipynb
|
Jupyter Notebook
|
Tweet_Sentiment_Extraction.ipynb
|
smsubham/Tweet-Sentiment-Extraction
|
ab33df59e0dce1243972482ab15ddbab96df4614
|
[
"Apache-2.0"
] | null | null | null |
Tweet_Sentiment_Extraction.ipynb
|
smsubham/Tweet-Sentiment-Extraction
|
ab33df59e0dce1243972482ab15ddbab96df4614
|
[
"Apache-2.0"
] | null | null | null |
Tweet_Sentiment_Extraction.ipynb
|
smsubham/Tweet-Sentiment-Extraction
|
ab33df59e0dce1243972482ab15ddbab96df4614
|
[
"Apache-2.0"
] | null | null | null | 35.436975 | 554 | 0.427852 |
[
[
[
"import time\nstart = time.perf_counter()\nimport tensorflow as tf\nprint(tf.__version__)\nend = time.perf_counter()\nprint('Elapsed time: ' + str(end - start))",
"2.4.1\nElapsed time: 1.5711914119999904\n"
]
],
[
[
"## Tweet Sentiment Extraction\n\"My ridiculous dog is amazing.\" [sentiment: positive]\n\nWith all of the tweets circulating every second it is hard to tell whether the sentiment behind a specific tweet will impact a company, or a person's, brand for being viral (positive), or devastate profit because it strikes a negative tone. Capturing sentiment in language is important in these times where decisions and reactions are created and updated in seconds. But, which words actually lead to the sentiment description? In this competition you will need to pick out the part of the tweet (word or phrase) that reflects the sentiment.\n\nHelp build your skills in this important area with this broad dataset of tweets. Work on your technique to grab a top spot in this competition. What words in tweets support a positive, negative, or neutral sentiment? How can you help make that determination using machine learning tools?\n\nIn this competition we've extracted support phrases from Figure Eight's Data for Everyone platform. The dataset is titled Sentiment Analysis: Emotion in Text tweets with existing sentiment labels, used here under creative commons attribution 4.0. international licence. Your objective in this competition is to construct a model that can do the same - look at the labeled sentiment for a given tweet and figure out what word or phrase best supports it.\n\nDisclaimer: The dataset for this competition contains text that may be considered profane, vulgar, or offensive.\nLink: https://www.kaggle.com/c/tweet-sentiment-extraction/overview",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/gdrive')",
"Mounted at /content/gdrive\n"
]
],
[
[
"# EDA",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\nstart = time.perf_counter()\n\"\"\"\n#loading data if using local system\ntrain_data = pd.read_csv(\"data/jigsaw-toxic-comment-train.csv\")\nvalidation_data = pd.read_csv(\"data/validation.csv\")\ntest_data = pd.read_csv(\"data/test.csv\")\n\"\"\"\n\n#loading data if using colab\n\npath = \"/content/gdrive/MyDrive/Dataset/Tweet Sentiment Extraction/Data/\"\ntrain_data = pd.read_csv(path+ \"train.csv\")\ntest_data = pd.read_csv(path+\"/test.csv\")\nend = time.perf_counter()\nprint('Elapsed time: ' + str(end - start))",
"Elapsed time: 0.10131069999999909\n"
],
[
"train_data.head()",
"_____no_output_____"
],
[
"train_data.describe",
"_____no_output_____"
],
[
"test_data.head()",
"_____no_output_____"
],
[
"test_data.describe",
"_____no_output_____"
],
[
"pip install wordcloud",
"Requirement already satisfied: wordcloud in /usr/local/lib/python3.7/dist-packages (1.5.0)\nRequirement already satisfied: numpy>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from wordcloud) (1.19.5)\nRequirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from wordcloud) (7.1.2)\n"
],
[
"pip install plotly",
"Requirement already satisfied: plotly in /usr/local/lib/python3.7/dist-packages (4.4.1)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from plotly) (1.15.0)\nRequirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.7/dist-packages (from plotly) (1.3.3)\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aad124e575fd43ef30b733ad2bcace75d003dd1
| 31,000 |
ipynb
|
Jupyter Notebook
|
titanic-native-predictions.ipynb
|
TheodorMariusWienert/misy467-assignments
|
b0b84c8c13d3a0cfbf39f4838e1e8aa6d1cde1d3
|
[
"MIT"
] | null | null | null |
titanic-native-predictions.ipynb
|
TheodorMariusWienert/misy467-assignments
|
b0b84c8c13d3a0cfbf39f4838e1e8aa6d1cde1d3
|
[
"MIT"
] | null | null | null |
titanic-native-predictions.ipynb
|
TheodorMariusWienert/misy467-assignments
|
b0b84c8c13d3a0cfbf39f4838e1e8aa6d1cde1d3
|
[
"MIT"
] | null | null | null | 32.460733 | 92 | 0.331323 |
[
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"df_train=pd.read_csv('Titanic_Data/titanic-train.csv')",
"_____no_output_____"
],
[
"s_norm=df_train['Survived'].value_counts(normalize=True)\ns_norm",
"_____no_output_____"
],
[
"df_test=pd.read_csv('Titanic_Data/test.csv')\ndf_test.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 418 entries, 0 to 417\nData columns (total 11 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 PassengerId 418 non-null int64 \n 1 Pclass 418 non-null int64 \n 2 Name 418 non-null object \n 3 Sex 418 non-null object \n 4 Age 332 non-null float64\n 5 SibSp 418 non-null int64 \n 6 Parch 418 non-null int64 \n 7 Ticket 418 non-null object \n 8 Fare 417 non-null float64\n 9 Cabin 91 non-null object \n 10 Embarked 418 non-null object \ndtypes: float64(2), int64(4), object(5)\nmemory usage: 36.0+ KB\n"
],
[
"df_test['Survived']=0\ndf_test.head()",
"_____no_output_____"
],
[
"df_submit_allzero=df_test[['PassengerId','Survived']]\ndf_submit_allzero.to_csv('Titanic_Data/titanic_submit_allzero.csv',index=False)",
"_____no_output_____"
],
[
"sex_s_norm=df_train.groupby('Sex')['Survived'].value_counts(normalize=True)\nsex_s_norm",
"_____no_output_____"
],
[
"df_test2=pd.read_csv('Titanic_Data/test.csv')\n",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 418 entries, 0 to 417\nData columns (total 12 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 PassengerId 418 non-null int64 \n 1 Pclass 418 non-null int64 \n 2 Name 418 non-null object \n 3 Sex 418 non-null object \n 4 Age 332 non-null float64\n 5 SibSp 418 non-null int64 \n 6 Parch 418 non-null int64 \n 7 Ticket 418 non-null object \n 8 Fare 417 non-null float64\n 9 Cabin 91 non-null object \n 10 Embarked 418 non-null object \n 11 Survived 418 non-null int64 \ndtypes: float64(2), int64(5), object(5)\nmemory usage: 39.3+ KB\n"
],
[
"df_test2['Survived']=df_test2['Sex'].apply(lambda x: 0 if x=='male' else 1)\ndf_test2.head()",
"_____no_output_____"
],
[
"df_submit_gender=df_test2[['PassengerId','Survived']]\ndf_submit_gender.to_csv('Titanic_Data/titanic_submit_gender.csv',index=False)",
"_____no_output_____"
],
[
"pclass_s_norm=df_train.groupby('Pclass')['Survived'].value_counts(normalize=True)\npclass_s_norm",
"_____no_output_____"
],
[
"df_test3=pd.read_csv('Titanic_Data/test.csv')\n",
"_____no_output_____"
],
[
"df_test3['Survived']=df_test2['Pclass'].apply(lambda x: 1 if x==1 else 0)\ndf_test3.head(20)",
"_____no_output_____"
],
[
"df_submit_Pclass=df_test3[['PassengerId','Survived']]\ndf_submit_Pclass.to_csv('Titanic_Data/titanic_submit_Pclass.csv',index=False)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aad19067335e13507653af1b8a1f079b6e7874f
| 4,480 |
ipynb
|
Jupyter Notebook
|
examples/GeoData.ipynb
|
trungleduc/ipyleaflet
|
d72ce50171e9766313ea7869c249160818efe3da
|
[
"MIT"
] | 903 |
2018-04-12T01:39:33.000Z
|
2022-03-22T22:11:55.000Z
|
examples/GeoData.ipynb
|
trungleduc/ipyleaflet
|
d72ce50171e9766313ea7869c249160818efe3da
|
[
"MIT"
] | 620 |
2018-04-09T08:51:40.000Z
|
2022-03-30T09:33:05.000Z
|
examples/GeoData.ipynb
|
trungleduc/ipyleaflet
|
d72ce50171e9766313ea7869c249160818efe3da
|
[
"MIT"
] | 253 |
2018-04-13T13:05:14.000Z
|
2022-03-22T09:30:27.000Z
| 22.068966 | 137 | 0.481027 |
[
[
[
"# GeoData",
"_____no_output_____"
]
],
[
[
"import ipyleaflet as ipy\nimport geopandas\nimport json",
"_____no_output_____"
],
[
"m = ipy.Map(center=(52.3, 8.0), zoom=3, basemap=ipy.basemaps.Esri.WorldTopoMap)",
"_____no_output_____"
],
[
"countries = geopandas.read_file(geopandas.datasets.get_path(\"naturalearth_lowres\"))\ncities = geopandas.read_file(geopandas.datasets.get_path(\"naturalearth_cities\"))\nrivers = geopandas.read_file(\n \"https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/10m/physical/ne_10m_rivers_lake_centerlines.zip\"\n)",
"_____no_output_____"
]
],
[
[
"## GeoDataFrame",
"_____no_output_____"
]
],
[
[
"countries.head()",
"_____no_output_____"
],
[
"geo_data = ipy.GeoData(\n geo_dataframe=countries,\n style={\n \"color\": \"black\",\n \"fillColor\": \"#3366cc\",\n \"opacity\": 0.05,\n \"weight\": 1.9,\n \"dashArray\": \"2\",\n \"fillOpacity\": 0.6,\n },\n hover_style={\"fillColor\": \"red\", \"fillOpacity\": 0.2},\n name=\"Countries\",\n)\nm.add_layer(geo_data)\nm.add_control(ipy.LayersControl())\nm",
"_____no_output_____"
],
[
"rivers_data = ipy.GeoData(\n geo_dataframe=rivers,\n style={\n \"color\": \"purple\",\n \"opacity\": 3,\n \"weight\": 1.9,\n \"dashArray\": \"2\",\n \"fillOpacity\": 0.6,\n },\n hover_style={\"fillColor\": \"red\", \"fillOpacity\": 0.2},\n name=\"Rivers\",\n)\nm.add_layer(rivers_data)",
"_____no_output_____"
],
[
"# geo_data.geo_dataframe = cities",
"_____no_output_____"
],
[
"# m.remove_layer(geo_data)",
"_____no_output_____"
]
],
[
[
"## Continent",
"_____no_output_____"
]
],
[
[
"africa_countries = countries[countries[\"continent\"] == \"Africa\"]\nafrica_countries.head()",
"_____no_output_____"
],
[
"africa_data = ipy.GeoData(\n geo_dataframe=africa_countries,\n style={\n \"color\": \"black\",\n \"fillColor\": \"red\",\n \"opacity\": 7,\n \"weight\": 1.9,\n \"dashArray\": \"7\",\n \"fillOpacity\": 0.2,\n },\n hover_style={\"fillColor\": \"grey\", \"fillOpacity\": 0.6},\n name=\"Africa\",\n)\nm.add_layer(africa_data)\nm",
"_____no_output_____"
],
[
"# m.remove_layer(africa_data)",
"_____no_output_____"
],
[
"m.add_control(ipy.FullScreenControl())",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4aad2537387180fe0a0f2428891356f4d68e4184
| 73,520 |
ipynb
|
Jupyter Notebook
|
fiona_nanopore/pipeline/notebook_processed/AT1G02500_m6a_gene_tracks.py.ipynb
|
bartongroup/Simpson_Davies_Barton_U6_methylation
|
85b0936fd95e579a3ea6391e76253e96353f94c6
|
[
"MIT"
] | null | null | null |
fiona_nanopore/pipeline/notebook_processed/AT1G02500_m6a_gene_tracks.py.ipynb
|
bartongroup/Simpson_Davies_Barton_U6_methylation
|
85b0936fd95e579a3ea6391e76253e96353f94c6
|
[
"MIT"
] | null | null | null |
fiona_nanopore/pipeline/notebook_processed/AT1G02500_m6a_gene_tracks.py.ipynb
|
bartongroup/Simpson_Davies_Barton_U6_methylation
|
85b0936fd95e579a3ea6391e76253e96353f94c6
|
[
"MIT"
] | null | null | null | 393.15508 | 60,096 | 0.915615 |
[
[
[
"\n######## snakemake preamble start (automatically inserted, do not edit) ########\nimport sys; sys.path.extend(['/cluster/ggs_lab/mtparker/.conda/envs/snakemake6/lib/python3.10/site-packages', '/cluster/ggs_lab/mtparker/papers/fiona/fiona_nanopore/rules/notebook_templates']); import pickle; snakemake = pickle.loads(b'\\x80\\x04\\x95t\\x0f\\x00\\x00\\x00\\x00\\x00\\x00\\x8c\\x10snakemake.script\\x94\\x8c\\tSnakemake\\x94\\x93\\x94)\\x81\\x94}\\x94(\\x8c\\x05input\\x94\\x8c\\x0csnakemake.io\\x94\\x8c\\nInputFiles\\x94\\x93\\x94)\\x81\\x94(\\x8c\"yanocomp/fip37_vs_fio1_vs_col0.bed\\x94\\x8c\"yanocomp/fip37_vs_fio1.posthoc.bed\\x94\\x8c\"yanocomp/fip37_vs_col0.posthoc.bed\\x94\\x8c!yanocomp/fio1_vs_col0.posthoc.bed\\x94\\x8c6yanocomp/fip37_vs_fio1__and__fip37_vs_col0.posthoc.bed\\x94\\x8c5yanocomp/fip37_vs_fio1__and__fio1_vs_col0.posthoc.bed\\x94\\x8c6yanocomp/fip37_vs_col0__and__fip37_vs_fio1.posthoc.bed\\x94\\x8c5yanocomp/fip37_vs_col0__and__fio1_vs_col0.posthoc.bed\\x94\\x8c5yanocomp/fio1_vs_col0__and__fip37_vs_fio1.posthoc.bed\\x94\\x8c5yanocomp/fio1_vs_col0__and__fip37_vs_col0.posthoc.bed\\x94\\x8c6yanocomp/fip37_vs_fio1__not__fip37_vs_col0.posthoc.bed\\x94\\x8c5yanocomp/fip37_vs_fio1__not__fio1_vs_col0.posthoc.bed\\x94\\x8c6yanocomp/fip37_vs_col0__not__fip37_vs_fio1.posthoc.bed\\x94\\x8c5yanocomp/fip37_vs_col0__not__fio1_vs_col0.posthoc.bed\\x94\\x8c5yanocomp/fio1_vs_col0__not__fip37_vs_fio1.posthoc.bed\\x94\\x8c5yanocomp/fio1_vs_col0__not__fip37_vs_col0.posthoc.bed\\x94\\x8c>yanocomp/fip37_vs_fio1__not__fip37_vs_col0__miclip.posthoc.bed\\x94\\x8c=yanocomp/fip37_vs_fio1__not__fio1_vs_col0__miclip.posthoc.bed\\x94\\x8c>yanocomp/fip37_vs_col0__not__fip37_vs_fio1__miclip.posthoc.bed\\x94\\x8c=yanocomp/fip37_vs_col0__not__fio1_vs_col0__miclip.posthoc.bed\\x94\\x8c=yanocomp/fio1_vs_col0__not__fip37_vs_fio1__miclip.posthoc.bed\\x94\\x8c=yanocomp/fio1_vs_col0__not__fip37_vs_col0__miclip.posthoc.bed\\x94\\x8c ../annotations/miclip_cov.fwd.bw\\x94\\x8c ../annotations/miclip_cov.rev.bw\\x94\\x8c\"../annotations/miclip_peaks.bed.gz\\x94\\x8c,../annotations/vir1_vs_VIRc_der_sites.bed.gz\\x94\\x8cA../annotations/Araport11_GFF3_genes_transposons.201606.no_chr.gtf\\x94e}\\x94(\\x8c\\x06_names\\x94}\\x94(\\x8c\\x08yanocomp\\x94K\\x00K\\x01\\x86\\x94\\x8c\\x10yanocomp_posthoc\\x94K\\x01K\\x16\\x86\\x94\\x8c\\nmiclip_cov\\x94K\\x16K\\x18\\x86\\x94\\x8c\\x0cmiclip_peaks\\x94K\\x18N\\x86\\x94\\x8c\\tder_sites\\x94K\\x19N\\x86\\x94\\x8c\\x03gtf\\x94K\\x1aN\\x86\\x94u\\x8c\\x12_allowed_overrides\\x94]\\x94(\\x8c\\x05index\\x94\\x8c\\x04sort\\x94eh6\\x8c\\tfunctools\\x94\\x8c\\x07partial\\x94\\x93\\x94h\\x06\\x8c\\x19Namedlist._used_attribute\\x94\\x93\\x94\\x85\\x94R\\x94(h<)}\\x94\\x8c\\x05_name\\x94h6sNt\\x94bh7h:h<\\x85\\x94R\\x94(h<)}\\x94h@h7sNt\\x94bh(h\\x06\\x8c\\tNamedlist\\x94\\x93\\x94)\\x81\\x94h\\na}\\x94(h&}\\x94h4]\\x94(h6h7eh6h:h<\\x85\\x94R\\x94(h<)}\\x94h@h6sNt\\x94bh7h:h<\\x85\\x94R\\x94(h<)}\\x94h@h7sNt\\x94bubh*hG)\\x81\\x94(h\\x0bh\\x0ch\\rh\\x0eh\\x0fh\\x10h\\x11h\\x12h\\x13h\\x14h\\x15h\\x16h\\x17h\\x18h\\x19h\\x1ah\\x1bh\\x1ch\\x1dh\\x1eh\\x1fe}\\x94(h&}\\x94h4]\\x94(h6h7eh6h:h<\\x85\\x94R\\x94(h<)}\\x94h@h6sNt\\x94bh7h:h<\\x85\\x94R\\x94(h<)}\\x94h@h7sNt\\x94bubh,hG)\\x81\\x94(h h!e}\\x94(h&}\\x94h4]\\x94(h6h7eh6h:h<\\x85\\x94R\\x94(h<)}\\x94h@h6sNt\\x94bh7h:h<\\x85\\x94R\\x94(h<)}\\x94h@h7sNt\\x94bubh.h\"h0h#h2h$ub\\x8c\\x06output\\x94h\\x06\\x8c\\x0bOutputFiles\\x94\\x93\\x94)\\x81\\x94\\x8c9figures/yanocomp/gene_tracks/AT1G02500_m6a_gene_track.svg\\x94a}\\x94(h&}\\x94\\x8c\\ngene_track\\x94K\\x00N\\x86\\x94sh4]\\x94(h6h7eh6h:h<\\x85\\x94R\\x94(h<)}\\x94h@h6sNt\\x94bh7h:h<\\x85\\x94R\\x94(h<)}\\x94h@h7sNt\\x94bhshpub\\x8c\\x06params\\x94h\\x06\\x8c\\x06Params\\x94\\x93\\x94)\\x81\\x94}\\x94(h&}\\x94h4]\\x94(h6h7eh6h:h<\\x85\\x94R\\x94(h<)}\\x94h@h6sNt\\x94bh7h:h<\\x85\\x94R\\x94(h<)}\\x94h@h7sNt\\x94bub\\x8c\\twildcards\\x94h\\x06\\x8c\\tWildcards\\x94\\x93\\x94)\\x81\\x94\\x8c\\tAT1G02500\\x94a}\\x94(h&}\\x94\\x8c\\x07gene_id\\x94K\\x00N\\x86\\x94sh4]\\x94(h6h7eh6h:h<\\x85\\x94R\\x94(h<)}\\x94h@h6sNt\\x94bh7h:h<\\x85\\x94R\\x94(h<)}\\x94h@h7sNt\\x94bh\\x94h\\x91ub\\x8c\\x07threads\\x94K\\x01\\x8c\\tresources\\x94h\\x06\\x8c\\tResources\\x94\\x93\\x94)\\x81\\x94(K\\x01K\\x01M\\xe8\\x03M\\xe8\\x03\\x8c\\x13/tmp/370838.1.all.q\\x94\\x8c\\x03c6*\\x94e}\\x94(h&}\\x94(\\x8c\\x06_cores\\x94K\\x00N\\x86\\x94\\x8c\\x06_nodes\\x94K\\x01N\\x86\\x94\\x8c\\x06mem_mb\\x94K\\x02N\\x86\\x94\\x8c\\x07disk_mb\\x94K\\x03N\\x86\\x94\\x8c\\x06tmpdir\\x94K\\x04N\\x86\\x94\\x8c\\x08hostname\\x94K\\x05N\\x86\\x94uh4]\\x94(h6h7eh6h:h<\\x85\\x94R\\x94(h<)}\\x94h@h6sNt\\x94bh7h:h<\\x85\\x94R\\x94(h<)}\\x94h@h7sNt\\x94bh\\xa8K\\x01h\\xaaK\\x01h\\xacM\\xe8\\x03h\\xaeM\\xe8\\x03h\\xb0h\\xa4\\x8c\\x08hostname\\x94h\\xa5ub\\x8c\\x03log\\x94h\\x06\\x8c\\x03Log\\x94\\x93\\x94)\\x81\\x94\\x8c5notebook_processed/AT1G02500_m6a_gene_tracks.py.ipynb\\x94a}\\x94(h&}\\x94\\x8c\\x08notebook\\x94K\\x00N\\x86\\x94sh4]\\x94(h6h7eh6h:h<\\x85\\x94R\\x94(h<)}\\x94h@h6sNt\\x94bh7h:h<\\x85\\x94R\\x94(h<)}\\x94h@h7sNt\\x94bh\\xc5h\\xc2ub\\x8c\\x06config\\x94}\\x94(\\x8c\\x16transcriptome_fasta_fn\\x94\\x8c0../annotations/Araport11_genes.201606.cdna.fasta\\x94\\x8c\\x0fgenome_fasta_fn\\x94\\x8c:../annotations/Arabidopsis_thaliana.TAIR10.dna.toplevel.fa\\x94\\x8c\\x06gtf_fn\\x94\\x8cA../annotations/Araport11_GFF3_genes_transposons.201606.no_chr.gtf\\x94\\x8c\\x08flowcell\\x94\\x8c\\nFLO-MIN106\\x94\\x8c\\x03kit\\x94\\x8c\\nSQK-RNA002\\x94\\x8c\\x13minimap2_parameters\\x94}\\x94\\x8c\\x0fmax_intron_size\\x94M Ns\\x8c\\x12d3pendr_parameters\\x94}\\x94(\\x8c\\x10min_read_overlap\\x94G?\\xc9\\x99\\x99\\x99\\x99\\x99\\x9a\\x8c\\x06nboots\\x94M\\xe7\\x03\\x8c\\x0fuse_gamma_model\\x94\\x88\\x8c\\x10test_homogeneity\\x94\\x89u\\x8c\\x0eexpected_motif\\x94\\x8c\\x05NNANN\\x94\\x8c\\x0bcomparisons\\x94]\\x94(\\x8c\\rfip37_vs_col0\\x94\\x8c\\x0cfio1_vs_col0\\x94e\\x8c\\tmulticomp\\x94]\\x94\\x8c\\x15fip37_vs_fio1_vs_col0\\x94a\\x8c\\x0fmiclip_coverage\\x94]\\x94(\\x8c ../annotations/miclip_cov.fwd.bw\\x94\\x8c ../annotations/miclip_cov.rev.bw\\x94e\\x8c\\x0cmiclip_peaks\\x94\\x8c\"../annotations/miclip_peaks.bed.gz\\x94\\x8c\\tder_sites\\x94\\x8c,../annotations/vir1_vs_VIRc_der_sites.bed.gz\\x94\\x8c\\x0fm6a_gene_tracks\\x94]\\x94(\\x8c\\tAT2G22540\\x94\\x8c\\tAT2G45660\\x94\\x8c\\tAT2G43010\\x94\\x8c\\tAT1G02500\\x94\\x8c\\tAT4G01850\\x94\\x8c\\tAT2G36880\\x94\\x8c\\tAT3G17390\\x94eu\\x8c\\x04rule\\x94\\x8c\\x18generate_m6a_gene_tracks\\x94\\x8c\\x0fbench_iteration\\x94N\\x8c\\tscriptdir\\x94\\x8cN/cluster/ggs_lab/mtparker/papers/fiona/fiona_nanopore/rules/notebook_templates\\x94ub.'); from snakemake.logging import logger; logger.printshellcmds = True; import os; os.chdir(r'/cluster/ggs_lab/mtparker/papers/fiona/fiona_nanopore/pipeline');\n######## snakemake preamble end #########\n",
"_____no_output_____"
],
[
"import os\nimport re\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom matplotlib import patches, gridspec\nimport seaborn as sns\nfrom IPython.display import display_markdown, Markdown\n\n\nfrom gene_track_utils import plot_yanocomp_miclip\n\n%matplotlib inline\nsns.set(font='Arial')\nplt.rcParams['svg.fonttype'] = 'none'\nstyle = sns.axes_style('white')\nstyle.update(sns.axes_style('ticks'))\nstyle['xtick.major.size'] = 1\nstyle['ytick.major.size'] = 1\nsns.set(font_scale=1.2, style=style)\npal = sns.color_palette(['#0072b2', '#d55e00', '#009e73', '#f0e442', '#cc79a7', '#56b4e9', '#e69f00'])\ncmap = ListedColormap(pal.as_hex())\nsns.set_palette(pal)\nsns.palplot(pal)\nplt.show()",
"_____no_output_____"
],
[
"display_markdown(Markdown(f'# {snakemake.wildcards.gene_id} m6A gene track'))",
"_____no_output_____"
],
[
"plot_yanocomp_miclip(\n snakemake.wildcards.gene_id,\n snakemake.input.miclip_cov,\n snakemake.input.miclip_peaks,\n snakemake.input.der_sites,\n {'FIP37-dependent only Yanocomp sites': 'yanocomp/fip37_vs_col0__not__fio1_vs_col0.posthoc.bed',\n 'FIP37/FIO1-dependent Yanocomp sites': 'yanocomp/fio1_vs_col0__and__fip37_vs_col0.posthoc.bed',\n 'FIO1-dependent only Yanocomp sites': 'yanocomp/fio1_vs_col0__not__fip37_vs_col0.posthoc.bed'},\n snakemake.input.gtf\n)\nplt.savefig(snakemake.output.gene_track)\nplt.show()",
"/cluster/ggs_lab/mtparker/papers/fiona/fiona_nanopore/rules/notebook_templates/gene_track_utils/__init__.py:262: MatplotlibDeprecationWarning: The 's' parameter of annotate() has been renamed 'text' since Matplotlib 3.3; support for the old name will be dropped two minor releases later.\n ax.annotate(s=label, xy=(0.99, 0.05), ha='right', va='bottom', xycoords='axes fraction')\n/cluster/ggs_lab/mtparker/papers/fiona/fiona_nanopore/rules/notebook_templates/gene_track_utils/__init__.py:225: MatplotlibDeprecationWarning: The 's' parameter of annotate() has been renamed 'text' since Matplotlib 3.3; support for the old name will be dropped two minor releases later.\n ax.annotate(s='Araport11 annotation', xy=(0.99, 0.05), ha='right', va='bottom', xycoords='axes fraction')\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4aad3160151db20b009c75ca1bad12042254c855
| 155,074 |
ipynb
|
Jupyter Notebook
|
1_ANN/3 Torch NN.ipynb
|
leriomaggio/deep-learning-for-data-science
|
1dff9a8a8d09c56f0f1785ed38368c5ea412041c
|
[
"Apache-2.0"
] | 2 |
2021-04-02T08:23:00.000Z
|
2021-04-02T10:51:36.000Z
|
1_ANN/3 Torch NN.ipynb
|
leriomaggio/deep-learning-for-data-science
|
1dff9a8a8d09c56f0f1785ed38368c5ea412041c
|
[
"Apache-2.0"
] | null | null | null |
1_ANN/3 Torch NN.ipynb
|
leriomaggio/deep-learning-for-data-science
|
1dff9a8a8d09c56f0f1785ed38368c5ea412041c
|
[
"Apache-2.0"
] | 1 |
2021-07-09T18:39:03.000Z
|
2021-07-09T18:39:03.000Z
| 37.602813 | 701 | 0.499129 |
[
[
[
"%load_ext notexbook\n%texify",
"_____no_output_____"
]
],
[
[
"# PyTorch `nn` package",
"_____no_output_____"
],
[
"### `torch.nn`\n\nComputational graphs and autograd are a very powerful paradigm for defining complex operators and automatically taking derivatives; however for large neural networks raw autograd can be a bit too low-level.\n\nWhen building neural networks we frequently think of arranging the computation into layers, some of which \nhave learnable parameters which will be optimized during learning.\n\nIn TensorFlow, packages like **Keras**, (old **TensorFlow-Slim**, and **TFLearn**) provide higher-level abstractions over raw computational graphs that are useful for building neural networks.\n\nIn PyTorch, the `nn` package serves this same purpose. \n\nThe `nn` package defines a set of `Module`s, which are roughly equivalent to neural network layers. \n\nA `Module` receives input `Tensor`s and computes output `Tensor`s, but may also hold internal state such as `Tensor`s containing learnable parameters. \n\nThe `nn` package also defines a set of useful `loss` functions that are commonly used when \ntraining neural networks.",
"_____no_output_____"
],
[
"In this example we use the `nn` package to implement our two-layer network:",
"_____no_output_____"
]
],
[
[
"import torch",
"_____no_output_____"
],
[
"# N is batch size; D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# Create random Tensors to hold inputs and outputs\nx = torch.randn(N, D_in)\ny = torch.randn(N, D_out)\n\n# Use the nn package to define our model as a sequence of layers. nn.Sequential\n# is a Module which contains other Modules, and applies them in sequence to\n# produce its output. Each Linear Module computes output from input using a\n# linear function, and holds internal Tensors for its weight and bias.\nmodel = torch.nn.Sequential(\n torch.nn.Linear(D_in, H), # xW+b\n torch.nn.ReLU(),\n torch.nn.Linear(H, D_out),\n)",
"_____no_output_____"
],
[
"[p.shape for p in model.parameters()]",
"_____no_output_____"
],
[
"# The nn package also contains definitions of popular loss functions; in this\n# case we will use Mean Squared Error (MSE) as our loss function.\nmseloss = torch.nn.MSELoss(reduction='sum')\n\nlearning_rate = 1e-4",
"_____no_output_____"
],
[
"for t in range(500):\n # Forward pass: compute predicted y by passing x to the model. Module objects\n # override the __call__ operator so you can call them like functions. When\n # doing so you pass a Tensor of input data to the Module and it produces\n # a Tensor of output data.\n y_pred = model(x)\n\n # Compute and print loss. We pass Tensors containing the predicted and true\n # values of y, and the loss function returns a Tensor containing the\n # loss.\n loss = mseloss(y_pred, y)\n if t % 50 == 0:\n print(t, loss.item())\n\n # Zero the gradients before running the backward pass.\n model.zero_grad()\n\n # Backward pass: compute gradient of the loss with respect to all the learnable\n # parameters of the model. Internally, the parameters of each Module are stored\n # in Tensors with requires_grad=True, so this call will compute gradients for\n # all learnable parameters in the model.\n loss.backward()\n\n # Update the weights using gradient descent. Each parameter is a Tensor, so\n # we can access its gradients like we did before.\n with torch.no_grad():\n for param in model.parameters():\n param -= learning_rate * param.grad",
"0 680.2872924804688\n50 34.80508804321289\n100 2.535295248031616\n150 0.2940663993358612\n200 0.04337170347571373\n250 0.007349258754402399\n300 0.001383807510137558\n350 0.0002830548328347504\n400 6.166603998281062e-05\n450 1.4081156223255675e-05\n"
]
],
[
[
"---",
"_____no_output_____"
],
[
"### `torch.optim`\n\nUp to this point we have updated the weights of our models by manually mutating the Tensors holding learnable parameters (**using `torch.no_grad()` or `.data` to avoid tracking history in autograd**). \n\nThis is not a huge burden for simple optimization algorithms like stochastic gradient descent, but in practice we often train neural networks using more sophisticated optimizers like `AdaGrad`, `RMSProp`, \n`Adam`.\n\nThe optim package in PyTorch abstracts the idea of an optimization algorithm and provides implementations of commonly used optimization algorithms.\n\nLet's finally modify the previous example in order to use `torch.optim` and the `Adam` algorithm:",
"_____no_output_____"
]
],
[
[
"# N is batch size; D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# Create random Tensors to hold inputs and outputs\nx = torch.randn(N, D_in)\ny = torch.randn(N, D_out)\n\n# Use the nn package to define our model and loss function.\nmodel = torch.nn.Sequential(\n torch.nn.Linear(D_in, H),\n torch.nn.ReLU(),\n torch.nn.Linear(H, D_out),\n)\nloss_fn = torch.nn.MSELoss(reduction='sum')",
"_____no_output_____"
]
],
[
[
"##### Model and Optimiser (w/ Parameters) at a glance\n\n\n\n<span class=\"fn\"><i>Source:</i> [1] - _Deep Learning with PyTorch_",
"_____no_output_____"
]
],
[
[
"# Use the optim package to define an Optimizer that will update the weights of\n# the model for us. Here we will use Adam; the optim package contains many other\n# optimization algoriths. The first argument to the Adam constructor tells the\n# optimizer which Tensors it should update.\nlearning_rate = 1e-4\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)",
"_____no_output_____"
],
[
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")",
"_____no_output_____"
],
[
"device",
"_____no_output_____"
],
[
"for t in range(500):\n # Forward pass: compute predicted y by passing x to the model.\n y_pred = model(x)\n loss = loss_fn(y_pred, y)\n if t % 50 == 0:\n print(t, loss.item())\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()",
"0 668.644287109375\n50 214.5611114501953\n100 60.03946304321289\n150 11.170021057128906\n200 1.4548708200454712\n250 0.15160593390464783\n300 0.01368227880448103\n350 0.001026861951686442\n400 5.9516169130802155e-05\n450 2.4962496354419272e-06\n"
]
],
[
[
"### Can we do better ?",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"##### The Learning Process\n\n\n\n<span class=\"fn\"><i>Source:</i> [1] - _Deep Learning with PyTorch_ </span>",
"_____no_output_____"
],
[
"Possible scenarios:\n\n- Specify models that are more complex than a sequence of existing (pre-defined) modules;\n- Customise the learning procedure (e.g. _weight sharing_ ?)\n- ?\n\nFor these cases, **PyTorch** allows to define our own custom modules by subclassing `nn.Module` and defining a `forward` method which receives the input data (i.e. `Tensor`) and returns the output (i.e. `Tensor`).\n\nIt is in the `forward` method that **all** the _magic_ of Dynamic Graph and `autograd` operations happen!",
"_____no_output_____"
],
[
"### PyTorch: Custom Modules",
"_____no_output_____"
],
[
" Let's implement our **two-layers** model as a custom `nn.Module` subclass",
"_____no_output_____"
]
],
[
[
"class TwoLayerNet(torch.nn.Module):\n def __init__(self, D_in, H, D_out):\n \"\"\"\n In the constructor we instantiate two nn.Linear modules and assign them as\n member variables.\n \"\"\"\n super(TwoLayerNet, self).__init__()\n self.linear1 = torch.nn.Linear(D_in, H)\n self.hidden_activation = torch.nn.ReLU()\n self.linear2 = torch.nn.Linear(H, D_out)\n\n def forward(self, x):\n \"\"\"\n In the forward function we accept a Tensor of input data and we must return\n a Tensor of output data. We can use Modules defined in the constructor as\n well as arbitrary operators on Tensors.\n \"\"\"\n l1 = self.linear1(x)\n h_relu = self.hidden_activation(l1)\n y_pred = self.linear2(h_relu)\n return y_pred",
"_____no_output_____"
],
[
"# N is batch size; D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# Create random Tensors to hold inputs and outputs\nx = torch.randn(N, D_in)\ny = torch.randn(N, D_out)",
"_____no_output_____"
],
[
"# Construct our model by instantiating the class defined above\nmodel = TwoLayerNet(D_in, H, D_out)",
"_____no_output_____"
],
[
"# Construct our loss function and an Optimizer. The call to model.parameters()\n# in the SGD constructor will contain the learnable parameters of the two\n# nn.Linear modules which are members of the model.\ncriterion = torch.nn.MSELoss(reduction='sum')\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4)",
"_____no_output_____"
],
[
"for t in range(500):\n # Forward pass: Compute predicted y by passing x to the model\n y_pred = model(x)\n\n # Compute and print loss\n loss = criterion(y_pred, y)\n if t % 50 == 0:\n print(t, loss.item())\n\n # Zero gradients, perform a backward pass, and update the weights.\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()",
"0 628.4317626953125\n50 30.246702194213867\n100 1.9293240308761597\n150 0.20857909321784973\n200 0.029761089012026787\n250 0.004920090548694134\n300 0.0008848008001223207\n350 0.0001684843737166375\n400 3.3450385672040284e-05\n450 6.8520644163072575e-06\n"
]
],
[
[
"#### What happened really? Let's have a closer look",
"_____no_output_____"
],
[
"```python\n>>> model = TwoLayerNet(D_in, H, D_out)\n```\n\nThis calls `TwoLayerNet.__init__` **constructor** method (_implementation reported below_ ):\n\n```python\ndef __init__(self, D_in, H, D_out):\n \"\"\"\n In the constructor we instantiate two nn.Linear modules and assign them as\n member variables.\n \"\"\"\n super(TwoLayerNet, self).__init__()\n self.linear1 = torch.nn.Linear(D_in, H)\n self.hidden_activation = torch.nn.ReLU()\n self.linear2 = torch.nn.Linear(H, D_out)\n```\n\n1. First thing, we call the `nn.Module` constructor which sets up the housekeeping\n - If you forget to do that, you will get and error message reminding that you should call it before using any `nn.Module` capabilities\n2. We create a class attribute for each layer (`OP/Tensor/`) that we intend to include in our model\n - These can be also `Sequential` as in _Submodules_ or *Block of Layers*\n - **Note**: We are **not** defining the Graph yet, just the layer!",
"_____no_output_____"
],
[
"```python\n>>> y_pred = model(x)\n```\n\n1. First thing to notice: the `model` object is **callable**\n - It means `nn.Module` is implementing a `__call__` method\n - We **don't** need to re-implement that!\n \n2. (in fact) The `nn.Module` class will call `self.forward` - in a [Template Method Pattern](https://en.wikipedia.org/wiki/Template_method_pattern) fashion\n - for this reason, we have to define the `forward` method\n - (needless to say) the `forward` method implements the **forward** pass of our model",
"_____no_output_____"
],
[
"`from torch.nn.modules.module.py`",
"_____no_output_____"
],
[
"```python \nclass Module(object):\n # [...] omissis\n def __call__(self, *input, **kwargs):\n for hook in self._forward_pre_hooks.values():\n result = hook(self, input)\n if result is not None:\n if not isinstance(result, tuple):\n result = (result,)\n input = result\n if torch._C._get_tracing_state():\n result = self._slow_forward(*input, **kwargs)\n else:\n result = self.forward(*input, **kwargs)\n for hook in self._forward_hooks.values():\n hook_result = hook(self, input, result)\n if hook_result is not None:\n result = hook_result\n if len(self._backward_hooks) > 0:\n var = result\n while not isinstance(var, torch.Tensor):\n if isinstance(var, dict):\n var = next((v for v in var.values() if isinstance(v, torch.Tensor)))\n else:\n var = var[0]\n grad_fn = var.grad_fn\n if grad_fn is not None:\n for hook in self._backward_hooks.values():\n wrapper = functools.partial(hook, self)\n functools.update_wrapper(wrapper, hook)\n grad_fn.register_hook(wrapper)\n return result\n \n # [...] omissis\n def forward(self, *input):\n r\"\"\"Defines the computation performed at every call.\n\n Should be overridden by all subclasses.\n\n .. note::\n Although the recipe for forward pass needs to be defined within\n this function, one should call the :class:`Module` instance afterwards\n instead of this since the former takes care of running the\n registered hooks while the latter silently ignores them.\n \"\"\"\n raise NotImplementedError\n```",
"_____no_output_____"
],
[
"**Take away messages** :\n1. We don't need to implement the `__call__` method at all in our custom model subclass\n2. We don't need to call the `forward` method directly. \n - We could, but we would miss the flexibility of _forward_ and _backwar_ hooks ",
"_____no_output_____"
],
[
"##### Last but not least\n\n```python\n>>> optimizer = torch.optim.SGD(model.parameters(), lr=1e-4)\n```\n\nBeing `model` a subclass of `nn.Module`, `model.parameters()` will automatically capture all the `Layers/OP/Tensors/Parameters` that require gradient computation, so to feed to the `autograd` engine during the *backward* (optimisation) step.",
"_____no_output_____"
],
[
"###### `model.named_parameters`",
"_____no_output_____"
]
],
[
[
"for name_str, param in model.named_parameters():\n print(\"{:21} {:19} {}\".format(name_str, str(param.shape), param.numel()))",
"linear1.weight torch.Size([100, 1000]) 100000\nlinear1.bias torch.Size([100]) 100\nlinear2.weight torch.Size([10, 100]) 1000\nlinear2.bias torch.Size([10]) 10\n"
]
],
[
[
"**WAIT**: What happened to `hidden_activation` ?",
"_____no_output_____"
],
[
"```python\nself.hidden_activation = torch.nn.ReLU()\n```\n\nSo, it looks that we are registering in the constructor a submodule (`torch.nn.ReLU`) that has no parameters.\n\nGeneralising, if we would've had **more** (hidden) layers, it would have required the definition of one of these submodules for each pair of layers (at least).",
"_____no_output_____"
],
[
"Looking back at the implementation of the `TwoLayerNet` class as a whole, it looks like a bit of a waste.\n\n**Can we do any better here?** 🤔",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"Well, in this particular case, we could implement the `ReLU` activation _manually_, it is not that difficult, isn't it?\n\n$\\rightarrow$ As we already did before, we could use the [`torch.clamp`](https://pytorch.org/docs/stable/torch.html?highlight=clamp#torch.clamp) function\n\n> `torch.clamp`: Clamp all elements in input into the range [ min, max ] and return a resulting tensor\n\n`t.clamp(min=0)` is **exactly** the ReLU that we want.",
"_____no_output_____"
]
],
[
[
"class TwoLayerNet(torch.nn.Module):\n def __init__(self, D_in, H, D_out):\n \"\"\"\n In the constructor we instantiate two nn.Linear modules and assign them as\n member variables.\n \"\"\"\n super(TwoLayerNet, self).__init__()\n self.linear1 = torch.nn.Linear(D_in, H)\n self.linear2 = torch.nn.Linear(H, D_out)\n\n def forward(self, x):\n \"\"\"\n In the forward function we accept a Tensor of input data and we must return\n a Tensor of output data. We can use Modules defined in the constructor as\n well as arbitrary operators on Tensors.\n \"\"\"\n h_relu = self.linear1(x).clamp(min=0)\n y_pred = self.linear2(h_relu)\n return y_pred",
"_____no_output_____"
]
],
[
[
"###### Sorted!\n\nThat was easy, wasn't it? **However**, what if we wanted *other* activation functions (e.g. `tanh`, \n`sigmoid`, `LeakyReLU`)?",
"_____no_output_____"
],
[
"### Introducing the Functional API\n\nPyTorch has functional counterparts of every `nn` module. \n\nBy _functional_ here we mean \"having no internal state\", or, in other words, \"whose output value is solely and fully determined by the value input arguments\". \n\nIndeed, `torch.nn.functional` provides the many of the same modules we find in `nn`, but with all eventual parameters moved as an argument to the function call. \n\nFor instance, the functional counterpart of `nn.Linear` is `nn.functional.linear`, which is a function that has signature `linear(input, weight, bias=None)`. \n\nThe `weight` and `bias` parameters are **arguments** to the function.",
"_____no_output_____"
],
[
"Back to our `TwoLayerNet` model, it makes sense to keep using nn modules for `nn.Linear`, so that our model will be able to manage all of its `Parameter` instances during training. \n\nHowever, we can safely switch to the functional counterparts of `nn.ReLU`, since it has no parameters.",
"_____no_output_____"
]
],
[
[
"class TwoLayerNet(torch.nn.Module):\n def __init__(self, D_in, H, D_out):\n \"\"\"\n In the constructor we instantiate two nn.Linear modules and assign them as\n member variables.\n \"\"\"\n super(TwoLayerNet, self).__init__()\n self.linear1 = torch.nn.Linear(D_in, H)\n self.linear2 = torch.nn.Linear(H, D_out)\n\n def forward(self, x):\n \"\"\"\n In the forward function we accept a Tensor of input data and we must return\n a Tensor of output data. We can use Modules defined in the constructor as\n well as arbitrary operators on Tensors.\n \"\"\"\n h_relu = torch.nn.functional.relu(self.linear1(x)) # torch.relu would do as well\n y_pred = self.linear2(h_relu)\n return y_pred",
"_____no_output_____"
],
[
"model = TwoLayerNet(D_in, H, D_out)\ncriterion = torch.nn.MSELoss(reduction='sum')\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4)\nfor t in range(500):\n y_pred = model(x)\n loss = criterion(y_pred, y)\n if t % 50 == 0:\n print(t, loss.item())\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()",
"0 644.9325561523438\n50 34.45087432861328\n100 2.602616548538208\n150 0.3441075086593628\n200 0.061480022966861725\n250 0.013185965828597546\n300 0.0031574771273881197\n350 0.000819869339466095\n400 0.00022226624423637986\n450 6.197119364514947e-05\n"
]
],
[
[
"$\\rightarrow$ For the curious minds: [The difference and connection between torch.nn and torch.nn.function from relu's various implementations](https://programmer.group/5d5a404b257d7.html)",
"_____no_output_____"
],
[
"#### Clever advice and Rule of thumb\n\n> With **quantization**, stateless bits like activations suddenly become stateful because information on the quantization needs to be captured. This means that if we aim to quantize our model, it might be worthwile to stick with the modular API if we go for non-JITed quantization. There is one style matter that will help you avoid surprises with (originally unforseen) uses: if you need several applications of stateless modules (like `nn.HardTanh` or `nn.ReLU`), it is likely a good idea to have a separate instance for each. Re-using the same module appears to be clever and will give correct results with our standard Python usage here, but tools analysing your model might trip over it.\n\n<span class=\"fn\"><i>Source:</i> [1] - _Deep Learning with PyTorch_ </span>",
"_____no_output_____"
],
[
"### Custom Graph flow: Example of Weight Sharing",
"_____no_output_____"
],
[
"As we already discussed, the definition of custom `nn.Module` in PyTorch requires the definition of layers (i.e. Parameters) in the constructor (`__init__`), and the implementation of the `forward` method in which the dynamic graph will be traversed defined by the call to each of those layers/parameters.",
"_____no_output_____"
],
[
"As an example of **dynamic graphs** we are going to implement a scenario in which we require parameters (i.e. _weights_) sharing between layers.\n\nIn order to do so, we will implement a very odd model: a fully-connected ReLU network that on each `forward` call chooses a `random` number (between 1 and 4) and uses that many hidden layers, reusing the same weights multiple times to compute the innermost hidden layers.",
"_____no_output_____"
],
[
"In order to do so, we will implement _weight sharing_ among the innermost layers by simply reusing the same `Module` multiple times when defining the forward pass.",
"_____no_output_____"
]
],
[
[
"import torch",
"_____no_output_____"
],
[
"import random\n\nclass DynamicNet(torch.nn.Module):\n def __init__(self, D_in, H, D_out):\n \"\"\"\n In the constructor we construct three nn.Linear instances that we will use\n in the forward pass.\n \"\"\"\n super(DynamicNet, self).__init__()\n self.input_linear = torch.nn.Linear(D_in, H)\n self.middle_linear = torch.nn.Linear(H, H)\n self.output_linear = torch.nn.Linear(H, D_out)\n\n def forward(self, x):\n \"\"\"\n For the forward pass of the model, we randomly choose either 0, 1, 2, or 3\n and reuse the middle_linear Module that many times to compute hidden layer\n representations.\n\n Since each forward pass builds a dynamic computation graph, we can use normal\n Python control-flow operators like loops or conditional statements when\n defining the forward pass of the model.\n\n Here we also see that it is perfectly safe to reuse the same Module many\n times when defining a computational graph. This is a big improvement from Lua\n Torch, where each Module could be used only once.\n \"\"\"\n h_relu = torch.relu(self.input_linear(x))\n hidden_layers = random.randint(0, 3)\n for _ in range(hidden_layers):\n h_relu = torch.relu(self.middle_linear(h_relu))\n y_pred = self.output_linear(h_relu)\n return y_pred",
"_____no_output_____"
],
[
"# N is batch size; D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# Create random Tensors to hold inputs and outputs\nx = torch.randn(N, D_in)\ny = torch.randn(N, D_out)\n\n# Construct our model by instantiating the class defined above\nmodel = DynamicNet(D_in, H, D_out)\n\n# Construct our loss function and an Optimizer. Training this strange model with\n# vanilla stochastic gradient descent is tough, so we use momentum\ncriterion = torch.nn.MSELoss(reduction='sum')\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)",
"_____no_output_____"
],
[
"for t in range(500):\n for i in range(2):\n start, end = int((N/2)*i), int((N/2)*(i+1))\n x = x[start:end, ...]\n y = y[start:end, ...]\n # Forward pass: Compute predicted y by passing x to the model\n y_pred = model(x)\n\n # Compute and print loss\n loss = criterion(y_pred, y)\n if t % 50 == 0:\n print(t, loss.item())\n\n # Zero gradients, perform a backward pass, and update the weights.\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()",
"0 323.1838684082031\n0 0.0\n50 0.0\n50 0.0\n100 0.0\n100 0.0\n150 0.0\n150 0.0\n200 0.0\n200 0.0\n250 0.0\n250 0.0\n300 0.0\n300 0.0\n350 0.0\n350 0.0\n400 0.0\n400 0.0\n450 0.0\n450 0.0\n"
]
],
[
[
"### Latest from the `torch` ecosystem",
"_____no_output_____"
],
[
"* $\\rightarrow$: [Migration from Chainer to PyTorch](https://medium.com/pytorch/migration-from-chainer-to-pytorch-8ed92c12c8)\n\n* $\\rightarrow$: [PyTorch Lightning](https://pytorch-lightning.readthedocs.io/en/latest/introduction_guide.html)\n - [fast.ai](https://docs.fast.ai/)",
"_____no_output_____"
],
[
"---\n### References and Futher Reading:\n\n1. [Deep Learning with PyTorch, Luca Antiga et. al.](https://www.manning.com/books/deep-learning-with-pytorch)\n2. [(**Terrific**) PyTorch Examples Repo](https://github.com/jcjohnson/pytorch-examples) (*where most of the examples in this notebook have been adapted from*)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
4aad323fe9eaca3124e077d689363311409196bd
| 4,893 |
ipynb
|
Jupyter Notebook
|
ipython_nb/annot_gff_with_interprot.ipynb
|
maubarsom/biotico-tools
|
3e34e1fdde083e49da10f5afdae6a951246b8a94
|
[
"Apache-2.0"
] | null | null | null |
ipython_nb/annot_gff_with_interprot.ipynb
|
maubarsom/biotico-tools
|
3e34e1fdde083e49da10f5afdae6a951246b8a94
|
[
"Apache-2.0"
] | null | null | null |
ipython_nb/annot_gff_with_interprot.ipynb
|
maubarsom/biotico-tools
|
3e34e1fdde083e49da10f5afdae6a951246b8a94
|
[
"Apache-2.0"
] | null | null | null | 33.513699 | 130 | 0.486818 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4aad50f36b4f3e0f7796578a1f95664fe5c9da12
| 144,867 |
ipynb
|
Jupyter Notebook
|
ch13/ch13-momentum.ipynb
|
systemquant/book-pandas-for-finance
|
90b7eb9be1de20a12ae72b9bb5d51424a979b174
|
[
"MIT"
] | 10 |
2021-02-04T12:49:56.000Z
|
2022-03-26T11:28:11.000Z
|
ch13/ch13-momentum.ipynb
|
systemquant/book-pandas-for-finance
|
90b7eb9be1de20a12ae72b9bb5d51424a979b174
|
[
"MIT"
] | 1 |
2022-03-24T03:47:14.000Z
|
2022-03-24T03:54:52.000Z
|
ch13/ch13-momentum.ipynb
|
systemquant/book-pandas-for-finance
|
90b7eb9be1de20a12ae72b9bb5d51424a979b174
|
[
"MIT"
] | 4 |
2021-07-17T16:50:15.000Z
|
2022-03-22T05:55:34.000Z
| 31.776047 | 98 | 0.351674 |
[
[
[
"## 13.2 유가증권시장 12개월 모멘텀",
"_____no_output_____"
],
[
"최근 투자 기간 기준으로 12개월 모멘텀 계산 날짜 구하기",
"_____no_output_____"
]
],
[
[
"from pykrx import stock\nimport FinanceDataReader as fdr",
"_____no_output_____"
],
[
"df = fdr.DataReader(symbol='KS11', start=\"2019-11\")\nstart = df.loc[\"2019-11\"]\nend = df.loc[\"2020-09\"]",
"_____no_output_____"
],
[
"df.loc[\"2020-11\"].head()",
"_____no_output_____"
],
[
"start",
"_____no_output_____"
],
[
"start_date = start.index[0]\nend_date = end.index[-1]\nprint(start_date, end_date)",
"2019-11-01 00:00:00 2020-09-29 00:00:00\n"
]
],
[
[
"가격 모멘텀 계산 시작일 기준으로 등락률을 계산합니다. ",
"_____no_output_____"
]
],
[
[
"df1 = stock.get_market_ohlcv_by_ticker(\"20191101\")\ndf2 = stock.get_market_ohlcv_by_ticker(\"20200929\")\nkospi = df1.join(df2, lsuffix=\"_l\", rsuffix=\"_r\")\nkospi",
"_____no_output_____"
]
],
[
[
"12개월 등락률(가격 모멘텀, 최근 1개월 제외)을 기준으로 상위 20종목의 종목 코드를 가져와봅시다. ",
"_____no_output_____"
]
],
[
[
"kospi['모멘텀'] = 100 * (kospi['종가_r'] - kospi['종가_l']) / kospi['종가_l']\nkospi = kospi[['종가_l', '종가_r', '모멘텀']]\nkospi.sort_values(by='모멘텀', ascending=False)[:20]",
"_____no_output_____"
],
[
"kospi_momentum20 = kospi.sort_values(by='모멘텀', ascending=False)[:20]\nkospi_momentum20.rename(columns={\"종가_l\": \"매수가\", \"종가_r\": \"매도가\"}, inplace=True)\nkospi_momentum20",
"_____no_output_____"
],
[
"df3 = stock.get_market_ohlcv_by_ticker(\"20201102\")\ndf4 = stock.get_market_ohlcv_by_ticker(\"20210430\")\npct_df = df3.join(df4, lsuffix=\"_l\", rsuffix=\"_r\")\npct_df",
"_____no_output_____"
],
[
"pct_df = pct_df[['종가_l', '종가_r']]\nkospi_momentum20_result = kospi_momentum20.join(pct_df)\nkospi_momentum20_result",
"_____no_output_____"
],
[
"kospi_momentum20_result['수익률'] = (kospi_momentum20_result['종가_r'] / \n kospi_momentum20_result['종가_l'])\nkospi_momentum20_result",
"_____no_output_____"
],
[
"수익률평균 = kospi_momentum20_result['수익률'].fillna(0).mean()\n수익률평균",
"_____no_output_____"
],
[
"mom20_cagr = 수익률평균 ** (1/0.5) - 1 # 6개월\nmom20_cagr * 100",
"_____no_output_____"
],
[
"df_ref = fdr.DataReader(\n symbol='KS11', \n start=\"2020-11-02\", # 첫번째 거래일\n end=\"2021-04-30\"\n)\ndf_ref",
"_____no_output_____"
],
[
"CAGR = ((df_ref['Close'].iloc[-1] / df_ref['Close'].iloc[0]) ** (1/0.5)) -1\nCAGR * 100",
"_____no_output_____"
]
],
[
[
"## 13.3 대형주 12개월 모멘텀",
"_____no_output_____"
],
[
"대형주(시가총액 200위) 기준으로 상대 모멘텀이 큰 종목을 20개 선정하는 전략",
"_____no_output_____"
]
],
[
[
"df1 = stock.get_market_ohlcv_by_ticker(\"20191101\", market=\"ALL\")\ndf2 = stock.get_market_ohlcv_by_ticker(\"20200929\", market=\"ALL\")\nall = df1.join(df2, lsuffix=\"_l\", rsuffix=\"_r\")\nall",
"_____no_output_____"
],
[
"# 기본 필터링\n# 우선주 제외 \nall2 = all.filter(regex=\"0$\", axis=0).copy()\nall2",
"_____no_output_____"
],
[
"all2['모멘텀'] = 100 * (all2['종가_r'] - all2['종가_l']) / all2['종가_l']\nall2 = all2[['모멘텀']]\nall2",
"_____no_output_____"
],
[
"cap = stock.get_market_cap_by_ticker(date=\"20200929\", market=\"ALL\") \ncap = cap[['시가총액']]\ncap",
"_____no_output_____"
],
[
"all3 = all2.join(other=cap)\nall3",
"_____no_output_____"
],
[
"# 대형주 필터링\nbig = all3.sort_values(by='시가총액', ascending=False)[:200]\nbig",
"_____no_output_____"
],
[
"big.sort_values(by='모멘텀', ascending=False)",
"_____no_output_____"
],
[
"big_pct20 = big.sort_values(by='모멘텀', ascending=False)[:20]\nbig_pct20",
"_____no_output_____"
],
[
"df3 = stock.get_market_ohlcv_by_ticker(\"20201102\", market=\"ALL\")\ndf4 = stock.get_market_ohlcv_by_ticker(\"20211015\", market=\"ALL\")\npct_df = df3.join(df4, lsuffix=\"_l\", rsuffix=\"_r\")\npct_df['수익률'] = pct_df['종가_r'] / pct_df['종가_l']\npct_df = pct_df[['종가_l', '종가_r', '수익률']]\npct_df",
"_____no_output_____"
],
[
"big_mom_result = big_pct20.join(pct_df)\nbig_mom_result",
"_____no_output_____"
],
[
"평균수익률 = big_mom_result['수익률'].mean()\nbig_mom_cagr = (평균수익률 ** 1/1) -1\nbig_mom_cagr * 100",
"_____no_output_____"
]
],
[
[
"## 13.4 장기 백테스팅",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport datetime\nfrom dateutil.relativedelta import relativedelta\n\nyear = 2010\nmonth = 11\nperiod = 6\n\ninv_start = f\"{year}-{month}-01\"\ninv_start = datetime.datetime.strptime(inv_start, \"%Y-%m-%d\")\ninv_end = inv_start + relativedelta(months=period-1)\n\nmom_start = inv_start - relativedelta(months=12)\nmom_end = inv_start - relativedelta(months=2)\nprint(mom_start.strftime(\"%Y-%m\"), mom_end.strftime(\"%Y-%m\"), \"=>\", \n inv_start.strftime(\"%Y-%m\"), inv_end.strftime(\"%Y-%m\"))",
"2009-11 2010-09 => 2010-11 2011-04\n"
],
[
"df = fdr.DataReader(symbol='KS11')\ndf",
"_____no_output_____"
],
[
"def get_business_day(df, year, month, index=0):\n str_month = f\"{year}-{month}\"\n return df.loc[str_month].index[index]",
"_____no_output_____"
],
[
"df = fdr.DataReader(symbol='KS11')\nget_business_day(df, 2010, 1, 0)",
"_____no_output_____"
],
[
"def momentum(df, year=2010, month=11, period=12):\n # 투자 시작일, 종료일\n str_day = f\"{year}-{month}-01\"\n start = datetime.datetime.strptime(str_day, \"%Y-%m-%d\")\n end = start + relativedelta(months=period-1)\n inv_start = get_business_day(df, start.year, start.month, 0) # 첫 번째 거래일의 종가\n inv_end = get_business_day(df, end.year, end.month, -1)\n inv_start = inv_start.strftime(\"%Y%m%d\")\n inv_end = inv_end.strftime(\"%Y%m%d\")\n #print(inv_start, inv_end)\n \n # 모멘텀 계산 시작일, 종료일\n end = start - relativedelta(months=2) # 역추세 1개월 제외\n start = start - relativedelta(months=period)\n mom_start = get_business_day(df, start.year, start.month, 0) # 첫 번째 거래일의 종가\n mom_end = get_business_day(df, end.year, end.month, -1)\n mom_start = mom_start.strftime(\"%Y%m%d\")\n mom_end = mom_end.strftime(\"%Y%m%d\")\n print(mom_start, mom_end, \" | \", inv_start, inv_end)\n \n # momentum 계산\n df1 = stock.get_market_ohlcv_by_ticker(mom_start)\n df2 = stock.get_market_ohlcv_by_ticker(mom_end)\n mon_df = df1.join(df2, lsuffix=\"l\", rsuffix=\"r\")\n mon_df['등락률'] = (mon_df['종가r'] - mon_df['종가l'])/mon_df['종가l']*100\n \n # 우선주 제외\n mon_df = mon_df.filter(regex=\"0$\", axis=0)\n mon20 = mon_df.sort_values(by=\"등락률\", ascending=False)[:20]\n mon20 = mon20[['등락률']]\n #print(mon20)\n \n # 투자 기간 수익률\n df3 = stock.get_market_ohlcv_by_ticker(inv_start)\n df4 = stock.get_market_ohlcv_by_ticker(inv_end)\n inv_df = df3.join(df4, lsuffix=\"l\", rsuffix=\"r\")\n inv_df['수익률'] = inv_df['종가r'] / inv_df['종가l'] # 수익률 = 매도가 / 매수가\n inv_df = inv_df[['수익률']]\n \n # join\n result_df = mon20.join(inv_df)\n result = result_df['수익률'].fillna(0).mean()\n return year, result",
"_____no_output_____"
],
[
"import time \n\ndata = []\nfor year in range(2010, 2021):\n ret = momentum(df, year, month=11, period=6)\n data.append(ret)\n time.sleep(1)",
"20100503 20100930 | 20101101 20110429\n20110502 20110930 | 20111101 20120430\n20120502 20120928 | 20121101 20130430\n20130502 20130930 | 20131101 20140430\n20140502 20140930 | 20141103 20150430\n20150504 20150930 | 20151102 20160429\n20160502 20160930 | 20161101 20170428\n20170502 20170929 | 20171101 20180430\n20180502 20180928 | 20181101 20190430\n20190502 20190930 | 20191101 20200429\n20200504 20200929 | 20201102 20210430\n"
],
[
"import pandas as pd \n\nret_df = pd.DataFrame(data=data, columns=['year', 'yield'])\nret_df.set_index('year', inplace=True)\nret_df",
"_____no_output_____"
],
[
"cum_yield = ret_df['yield'].cumprod()\ncum_yield",
"_____no_output_____"
],
[
"CAGR = cum_yield.iloc[-1] ** (1/11) - 1\nCAGR * 100",
"_____no_output_____"
],
[
"buy_price = df.loc[\"2010-11\"].iloc[0, 0]\nsell_price = df.loc[\"2021-04\"].iloc[-1, 0]\nkospi_yield = sell_price / buy_price\nkospi_cagr = kospi_yield ** (1/11)-1\nkospi_cagr * 100",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aad56225e068477d5b3a0dfd308bae053ae647c
| 185,217 |
ipynb
|
Jupyter Notebook
|
AWS_DapSeq_Maize_Data_And_Model_Generation_Pipeline.ipynb
|
arjunkhakhar/Maize-DapSeq-Machine-Learning
|
6c46019b93c7b5fd63719679c3c483b0e3f7a9b0
|
[
"MIT"
] | 1 |
2021-07-16T05:34:43.000Z
|
2021-07-16T05:34:43.000Z
|
AWS_DapSeq_Maize_Data_And_Model_Generation_Pipeline.ipynb
|
arjunkhakhar/Maize-DapSeq-Machine-Learning
|
6c46019b93c7b5fd63719679c3c483b0e3f7a9b0
|
[
"MIT"
] | null | null | null |
AWS_DapSeq_Maize_Data_And_Model_Generation_Pipeline.ipynb
|
arjunkhakhar/Maize-DapSeq-Machine-Learning
|
6c46019b93c7b5fd63719679c3c483b0e3f7a9b0
|
[
"MIT"
] | null | null | null | 47.85969 | 799 | 0.4466 |
[
[
[
"import numpy\nimport pandas as pd\nimport sqlite3\nimport os\nfrom pandas.io import sql\nfrom tables import *\nimport re\nimport pysam\nimport matplotlib\nimport matplotlib.image as mpimg\nimport seaborn\nimport matplotlib.pyplot\n%matplotlib inline",
"_____no_output_____"
],
[
"def vectorizeSequence(seq):\n # the order of the letters is not arbitrary.\n # Flip the matrix up-down and left-right for reverse compliment\n ltrdict = {'a':[1,0,0,0],'c':[0,1,0,0],'g':[0,0,1,0],'t':[0,0,0,1], 'n':[0,0,0,0]}\n return numpy.array([ltrdict[x] for x in seq])\n\ndef Generate_training_and_test_datasets(Gem_events_file_path,ARF_label):\n \n #Make Maize genome\n from Bio import SeqIO\n for record in SeqIO.parse(open('/mnt/Data_DapSeq_Maize/MaizeGenome.fa'),'fasta'):\n if record.id =='1':\n chr1 = record.seq.tostring()\n if record.id =='2':\n chr2 = record.seq.tostring()\n if record.id =='3':\n chr3 = record.seq.tostring()\n if record.id =='4':\n chr4 = record.seq.tostring()\n if record.id =='5':\n chr5 = record.seq.tostring()\n if record.id =='6':\n chr6 = record.seq.tostring()\n if record.id =='7':\n chr7 = record.seq.tostring()\n if record.id =='8':\n chr8 = record.seq.tostring()\n if record.id =='9':\n chr9 = record.seq.tostring()\n if record.id =='10':\n chr10 = record.seq.tostring()\n\n wholegenome = {'chr1':chr1,'chr2':chr2,'chr3':chr3,'chr4':chr4,'chr5':chr5,'chr6':chr6,'chr7':chr7,'chr8':chr8,'chr9':chr9,'chr10':chr10}\n \n \n rawdata = open(Gem_events_file_path) \n GEM_events=rawdata.read()\n GEM_events=re.split(',|\\t|\\n',GEM_events)\n GEM_events=GEM_events[0:(len(GEM_events)-1)] # this is to make sure the reshape step works\n GEM_events= numpy.reshape(GEM_events,(-1,10))\n \n #Build Negative dataset\n import random\n \n Bound_Sequences = []\n for i in range(0,len(GEM_events)):\n Bound_Sequences.append(wholegenome[GEM_events[i][0]][int(GEM_events[i][1]):int(GEM_events[i][2])])\n \n Un_Bound_Sequences = []\n count=0\n while count<len(Bound_Sequences):\n chro = numpy.random.choice(['chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10'])\n index = random.randint(1,len(wholegenome[chro]))\n absent=True\n for i in range(len(GEM_events)):\n if chro == GEM_events[i][0]:\n if index>int(GEM_events[i][1]) and index<int(GEM_events[i][2]):\n absent = False\n if absent:\n if wholegenome[chro][index:(index+201)].upper().count('R') == 0 and wholegenome[chro][index:(index+201)].upper().count('W') == 0 and wholegenome[chro][index:(index+201)].upper().count('M') == 0 and wholegenome[chro][index:(index+201)].upper().count('S') == 0 and wholegenome[chro][index:(index+201)].upper().count('K') == 0 and wholegenome[chro][index:(index+201)].upper().count('Y') == 0and wholegenome[chro][index:(index+201)].upper().count('B') == 0 and wholegenome[chro][index:(index+201)].upper().count('D') == 0and wholegenome[chro][index:(index+201)].upper().count('H') == 0 and wholegenome[chro][index:(index+201)].upper().count('V') == 0 and wholegenome[chro][index:(index+201)].upper().count('Z') == 0 and wholegenome[chro][index:(index+201)].upper().count('N') == 0 :\n Un_Bound_Sequences.append(wholegenome[chro][index:(index+201)])\n count=count+1\n response = [0]*(len(Un_Bound_Sequences))\n temp3 = numpy.array(Un_Bound_Sequences)\n temp2 = numpy.array(response)\n neg = pd.DataFrame({'sequence':temp3,'response':temp2})\n \n #Build Positive dataset labeled with signal value\n Bound_Sequences = []\n Responses=[]\n for i in range(0,len(GEM_events)):\n Bound_Sequences.append(wholegenome[GEM_events[i][0]][int(GEM_events[i][1]):int(GEM_events[i][2])])\n Responses.append(float(GEM_events[i][6]))\n \n d = {'sequence' : pd.Series(Bound_Sequences, index=range(len(Bound_Sequences))),\n 'response' : pd.Series(Responses, index=range(len(Bound_Sequences)))}\n pos = pd.DataFrame(d)\n \n #Put positive and negative datasets together\n \n LearningData = neg.append(pos)\n LearningData = LearningData.reindex()\n \n #one hot encode sequence data\n counter2=0\n LearningData_seq_OneHotEncoded =numpy.empty([len(LearningData),201,4])\n\n for counter1 in LearningData['sequence']:\n LearningData_seq_OneHotEncoded[counter2]=vectorizeSequence(counter1.lower())\n counter2=counter2+1\n \n #Create training and test datasets\n from sklearn.cross_validation import train_test_split\n sequence_train, sequence_test, response_train, response_test = train_test_split(LearningData_seq_OneHotEncoded, LearningData['response'], test_size=0.2, random_state=42)\n \n #Saving datasets\n \n numpy.save('/mnt/Data_DapSeq_Maize/'+ARF_label+'_seq_train.npy',sequence_train)\n numpy.save('/mnt/Data_DapSeq_Maize/'+ARF_label+'_res_train.npy',response_train)\n numpy.save('/mnt/Data_DapSeq_Maize/'+ARF_label+'_seq_test.npy',sequence_test)\n numpy.save('/mnt/Data_DapSeq_Maize/'+ARF_label+'_res_test.npy',response_test)\n \ndef Generate_training_and_test_datasets_no_negative(Gem_events_file_path,ARF_label):\n \n #Make Maize genome\n from Bio import SeqIO\n for record in SeqIO.parse(open('/mnt/Data_DapSeq_Maize/MaizeGenome.fa'),'fasta'):\n if record.id =='1':\n chr1 = record.seq.tostring()\n if record.id =='2':\n chr2 = record.seq.tostring()\n if record.id =='3':\n chr3 = record.seq.tostring()\n if record.id =='4':\n chr4 = record.seq.tostring()\n if record.id =='5':\n chr5 = record.seq.tostring()\n if record.id =='6':\n chr6 = record.seq.tostring()\n if record.id =='7':\n chr7 = record.seq.tostring()\n if record.id =='8':\n chr8 = record.seq.tostring()\n if record.id =='9':\n chr9 = record.seq.tostring()\n if record.id =='10':\n chr10 = record.seq.tostring()\n\n wholegenome = {'chr1':chr1,'chr2':chr2,'chr3':chr3,'chr4':chr4,'chr5':chr5,'chr6':chr6,'chr7':chr7,'chr8':chr8,'chr9':chr9,'chr10':chr10}\n \n \n rawdata = open(Gem_events_file_path) \n GEM_events=rawdata.read()\n GEM_events=re.split(',|\\t|\\n',GEM_events)\n GEM_events=GEM_events[0:(len(GEM_events)-1)] # this is to make sure the reshape step works\n GEM_events= numpy.reshape(GEM_events,(-1,10))\n \n #Build Positive dataset labeled with signal value\n Bound_Sequences = []\n Responses=[]\n for i in range(0,len(GEM_events)):\n Bound_Sequences.append(wholegenome[GEM_events[i][0]][int(GEM_events[i][1]):int(GEM_events[i][2])])\n Responses.append(float(GEM_events[i][6]))\n \n d = {'sequence' : pd.Series(Bound_Sequences, index=range(len(Bound_Sequences))),\n 'response' : pd.Series(Responses, index=range(len(Bound_Sequences)))}\n pos = pd.DataFrame(d)\n \n LearningData = pos\n \n #one hot encode sequence data\n counter2=0\n LearningData_seq_OneHotEncoded =numpy.empty([len(LearningData),201,4])\n\n for counter1 in LearningData['sequence']:\n LearningData_seq_OneHotEncoded[counter2]=vectorizeSequence(counter1.lower())\n counter2=counter2+1\n \n #Create training and test datasets\n from sklearn.cross_validation import train_test_split\n sequence_train, sequence_test, response_train, response_test = train_test_split(LearningData_seq_OneHotEncoded, LearningData['response'], test_size=0.2, random_state=42)\n \n #Saving datasets\n \n numpy.save('/mnt/Data_DapSeq_Maize/'+ARF_label+'no_negative_seq_train.npy',sequence_train)\n numpy.save('/mnt/Data_DapSeq_Maize/'+ARF_label+'no_negative_res_train.npy',response_train)\n numpy.save('/mnt/Data_DapSeq_Maize/'+ARF_label+'no_negative_seq_test.npy',sequence_test)\n numpy.save('/mnt/Data_DapSeq_Maize/'+ARF_label+'no_negative_res_test.npy',response_test) \n ",
"_____no_output_____"
],
[
"def Train_and_save_DanQ_model(ARF_label,number_backpropagation_cycles):\n \n #Loading the data\n sequence_train=numpy.load('/mnt/Data_DapSeq_Maize/'+ARF_label+'_seq_train.npy')\n response_train=numpy.load('/mnt/Data_DapSeq_Maize/'+ARF_label+'_res_train.npy')\n sequence_test=numpy.load('/mnt/Data_DapSeq_Maize/'+ARF_label+'_seq_test.npy')\n response_test=numpy.load('/mnt/Data_DapSeq_Maize/'+ARF_label+'_res_test.npy')\n \n #Setting up the model\n import keras\n import numpy as np\n from keras import backend\n backend._BACKEND=\"theano\"\n \n #DanQ model\n\n from keras.preprocessing import sequence\n from keras.optimizers import RMSprop\n from keras.models import Sequential\n from keras.layers.core import Dense\n from keras.layers.core import Merge\n from keras.layers.core import Dropout\n from keras.layers.core import Activation\n from keras.layers.core import Flatten\n from keras.layers.convolutional import Convolution1D, MaxPooling1D\n from keras.regularizers import l2, activity_l1\n from keras.constraints import maxnorm\n from keras.layers.recurrent import LSTM, GRU\n from keras.callbacks import ModelCheckpoint, EarlyStopping\n from keras.layers import Bidirectional\n\n model = Sequential()\n model.add(Convolution1D(nb_filter=20,filter_length=26,input_dim=4,input_length=201,border_mode=\"valid\")) \n model.add(Activation('relu'))\n\n\n model.add(MaxPooling1D(pool_length=6, stride=6))\n\n model.add(Dropout(0.2))\n\n model.add(Bidirectional(LSTM(5))) \n model.add(Dropout(0.5))\n\n\n model.add(Dense(10))\n model.add(Activation('relu'))\n\n model.add(Dense(1))\n\n #compile the model\n model.compile(loss='mean_squared_error', optimizer='rmsprop')\n \n model.fit(sequence_train, response_train, validation_split=0.2,batch_size=100, nb_epoch=number_backpropagation_cycles, verbose=1)\n \n #evaulting correlation between model and test data\n import scipy\n\n correlation = scipy.stats.pearsonr(response_test,model.predict(sequence_test).flatten())\n correlation_2 = (correlation[0]**2)*100\n\n print('Percent of variability explained by model: '+str(correlation_2))\n \n # saving the model\n model.save('/mnt/Data_DapSeq_Maize/TrainedModel_DanQ_' +ARF_label+'.h5')",
"_____no_output_____"
],
[
"def Train_and_save_DanQ_model_no_negative(ARF_label,number_backpropagation_cycles,train_size):\n \n #Loading the data\n sequence_train=numpy.load('/mnt/Data_DapSeq_Maize/'+ARF_label+'no_negative_seq_train.npy')\n response_train=numpy.load('/mnt/Data_DapSeq_Maize/'+ARF_label+'no_negative_res_train.npy')\n sequence_train=sequence_train[0:train_size]\n response_train=response_train[0:train_size]\n \n sequence_test=numpy.load('/mnt/Data_DapSeq_Maize/'+ARF_label+'no_negative_seq_test.npy')\n response_test=numpy.load('/mnt/Data_DapSeq_Maize/'+ARF_label+'no_negative_res_test.npy')\n \n #Setting up the model\n import keras\n import numpy as np\n from keras import backend\n backend._BACKEND=\"theano\"\n \n #DanQ model\n\n from keras.preprocessing import sequence\n from keras.optimizers import RMSprop\n from keras.models import Sequential\n from keras.layers.core import Dense\n from keras.layers.core import Merge\n from keras.layers.core import Dropout\n from keras.layers.core import Activation\n from keras.layers.core import Flatten\n from keras.layers.convolutional import Convolution1D, MaxPooling1D\n from keras.regularizers import l2, activity_l1\n from keras.constraints import maxnorm\n from keras.layers.recurrent import LSTM, GRU\n from keras.callbacks import ModelCheckpoint, EarlyStopping\n from keras.layers import Bidirectional\n\n model = Sequential()\n model.add(Convolution1D(nb_filter=20,filter_length=26,input_dim=4,input_length=201,border_mode=\"valid\")) \n model.add(Activation('relu'))\n\n\n model.add(MaxPooling1D(pool_length=6, stride=6))\n\n model.add(Dropout(0.2))\n\n model.add(Bidirectional(LSTM(5))) \n model.add(Dropout(0.5))\n\n\n model.add(Dense(10))\n model.add(Activation('relu'))\n\n model.add(Dense(1))\n\n #compile the model\n model.compile(loss='mean_squared_error', optimizer='rmsprop')\n \n model.fit(sequence_train, response_train, validation_split=0.2,batch_size=100, nb_epoch=number_backpropagation_cycles, verbose=1)\n \n #evaulting correlation between model and test data\n import scipy\n\n correlation = scipy.stats.pearsonr(response_test,model.predict(sequence_test).flatten())\n correlation_2 = (correlation[0]**2)*100\n\n print('Percent of variability explained by model: '+str(correlation_2))\n \n # saving the model\n model.save('/mnt/Data_DapSeq_Maize/TrainedModel_DanQ_no_negative_' +ARF_label+'.h5')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF27_smaller_GEM_events.txt','ARF27_smaller')",
"/usr/local/lib/python2.7/dist-packages/Bio/Seq.py:341: BiopythonDeprecationWarning: This method is obsolete; please use str(my_seq) instead of my_seq.tostring().\n BiopythonDeprecationWarning)\n"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF34_smaller_GEM_events.txt','ARF34_smaller')",
"_____no_output_____"
],
[
"Train_and_save_DanQ_model('ARF27_smaller',35)",
"Using TensorFlow backend.\n"
],
[
"Train_and_save_DanQ_model('ARF34_smaller',35)",
"Train on 95597 samples, validate on 23900 samples\nEpoch 1/35\n95597/95597 [==============================] - 191s - loss: 4887.8733 - val_loss: 4327.9871\nEpoch 2/35\n95597/95597 [==============================] - 190s - loss: 4531.3844 - val_loss: 4251.6972\nEpoch 3/35\n95597/95597 [==============================] - 190s - loss: 4456.6051 - val_loss: 4202.6710\nEpoch 4/35\n95597/95597 [==============================] - 187s - loss: 4241.0890 - val_loss: 3892.3050\nEpoch 5/35\n95597/95597 [==============================] - 186s - loss: 4007.0111 - val_loss: 3519.4219\nEpoch 6/35\n95597/95597 [==============================] - 187s - loss: 3848.9529 - val_loss: 3682.6917\nEpoch 7/35\n95597/95597 [==============================] - 186s - loss: 3752.3041 - val_loss: 3343.3430\nEpoch 8/35\n95597/95597 [==============================] - 187s - loss: 3653.3723 - val_loss: 3197.1191\nEpoch 9/35\n95597/95597 [==============================] - 187s - loss: 3575.5975 - val_loss: 3151.9682\nEpoch 10/35\n95597/95597 [==============================] - 186s - loss: 3510.2862 - val_loss: 3048.9712\nEpoch 11/35\n95597/95597 [==============================] - 187s - loss: 3428.6527 - val_loss: 3085.6631\nEpoch 12/35\n95597/95597 [==============================] - 186s - loss: 3327.8164 - val_loss: 2896.9163\nEpoch 13/35\n95597/95597 [==============================] - 189s - loss: 3276.2440 - val_loss: 2824.8755\nEpoch 14/35\n95597/95597 [==============================] - 195s - loss: 3229.8879 - val_loss: 2941.8023\nEpoch 15/35\n95597/95597 [==============================] - 193s - loss: 3187.2784 - val_loss: 2811.2938\nEpoch 16/35\n95597/95597 [==============================] - 193s - loss: 3176.0136 - val_loss: 2748.7770\nEpoch 17/35\n95597/95597 [==============================] - 194s - loss: 3133.8044 - val_loss: 2899.3654\nEpoch 18/35\n95597/95597 [==============================] - 194s - loss: 3113.5332 - val_loss: 2694.3913\nEpoch 19/35\n95597/95597 [==============================] - 195s - loss: 3105.4206 - val_loss: 2769.7157\nEpoch 20/35\n95597/95597 [==============================] - 196s - loss: 3060.3629 - val_loss: 2691.1610\nEpoch 21/35\n95597/95597 [==============================] - 194s - loss: 3052.6832 - val_loss: 2742.2659\nEpoch 22/35\n95597/95597 [==============================] - 194s - loss: 3030.7377 - val_loss: 2775.6038\nEpoch 23/35\n95597/95597 [==============================] - 195s - loss: 3022.7071 - val_loss: 2813.7917\nEpoch 24/35\n95597/95597 [==============================] - 194s - loss: 3019.5164 - val_loss: 2646.4062\nEpoch 25/35\n95597/95597 [==============================] - 190s - loss: 3012.5687 - val_loss: 2646.8621\nEpoch 26/35\n95597/95597 [==============================] - 185s - loss: 2996.6075 - val_loss: 2636.6273\nEpoch 27/35\n95597/95597 [==============================] - 194s - loss: 2996.8960 - val_loss: 2693.1497\nEpoch 28/35\n95597/95597 [==============================] - 190s - loss: 2988.2616 - val_loss: 2636.2069\nEpoch 29/35\n95597/95597 [==============================] - 186s - loss: 2978.7858 - val_loss: 2723.5984\nEpoch 30/35\n95597/95597 [==============================] - 185s - loss: 2979.4342 - val_loss: 2679.8599\nEpoch 31/35\n95597/95597 [==============================] - 190s - loss: 2975.5008 - val_loss: 2696.6434\nEpoch 32/35\n95597/95597 [==============================] - 195s - loss: 2944.4941 - val_loss: 2642.6848\nEpoch 33/35\n95597/95597 [==============================] - 195s - loss: 2965.7662 - val_loss: 2626.8915\nEpoch 34/35\n95597/95597 [==============================] - 195s - loss: 2954.4101 - val_loss: 2654.3864\nEpoch 35/35\n95597/95597 [==============================] - 196s - loss: 2939.8508 - val_loss: 2596.2920\nPercent of variability explained by model: 39.7201759078\n"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF16_GEM_events.txt','ARF16')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF4_GEM_events.txt','ARF4')",
"/usr/local/lib/python2.7/dist-packages/Bio/Seq.py:341: BiopythonDeprecationWarning: This method is obsolete; please use str(my_seq) instead of my_seq.tostring().\n BiopythonDeprecationWarning)\n"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF4_rep2_GEM_events.txt','ARF4_rep2')",
"/usr/local/lib/python2.7/dist-packages/Bio/Seq.py:341: BiopythonDeprecationWarning: This method is obsolete; please use str(my_seq) instead of my_seq.tostring().\n BiopythonDeprecationWarning)\n"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF4_rep3_GEM_events.txt','ARF4_rep3')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF10_GEM_events.txt','ARF10')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF13_GEM_events.txt','ARF13')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF18_GEM_events.txt','ARF18')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF27_GEM_events.txt','ARF27')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF29_GEM_events.txt','ARF29')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF34_GEM_events.txt','ARF34')",
"/usr/local/lib/python2.7/dist-packages/Bio/Seq.py:341: BiopythonDeprecationWarning: This method is obsolete; please use str(my_seq) instead of my_seq.tostring().\n BiopythonDeprecationWarning)\n"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF35_GEM_events.txt','ARF35')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF39_GEM_events.txt','ARF39')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF10_rep1_ear_GEM_events.txt','ARF10_rep1_ear')",
"/usr/local/lib/python2.7/dist-packages/Bio/Seq.py:341: BiopythonDeprecationWarning: This method is obsolete; please use str(my_seq) instead of my_seq.tostring().\n BiopythonDeprecationWarning)\n"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF10_rep2_ear_GEM_events.txt','ARF10_rep2_ear')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF10_rep1_tassel_GEM_events.txt','ARF10_rep1_tassel')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF10_rep2_tassel_GEM_events.txt','ARF10_rep2_tassel')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF7_GEM_events.txt','ARF7')",
"/usr/local/lib/python2.7/dist-packages/Bio/Seq.py:341: BiopythonDeprecationWarning: This method is obsolete; please use str(my_seq) instead of my_seq.tostring().\n BiopythonDeprecationWarning)\n"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF14_GEM_events.txt','ARF14')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF24_GEM_events.txt','ARF24')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF25_GEM_events.txt','ARF25')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets('/mnt/Data_DapSeq_Maize/ARF36_GEM_events.txt','ARF36')",
"_____no_output_____"
],
[
"Train_and_save_DanQ_model('ARF7',35)",
"Using TensorFlow backend.\n"
],
[
"Train_and_save_DanQ_model('ARF14',35)",
"Train on 35964 samples, validate on 8992 samples\nEpoch 1/35\n35964/35964 [==============================] - 74s - loss: 11727.8352 - val_loss: 10908.0097\nEpoch 2/35\n35964/35964 [==============================] - 74s - loss: 10596.9515 - val_loss: 9942.7811\nEpoch 3/35\n35964/35964 [==============================] - 73s - loss: 10001.3984 - val_loss: 9175.8203\nEpoch 4/35\n35964/35964 [==============================] - 73s - loss: 9506.0265 - val_loss: 8702.6930\nEpoch 5/35\n35964/35964 [==============================] - 73s - loss: 9059.9357 - val_loss: 8096.7627\nEpoch 6/35\n35964/35964 [==============================] - 73s - loss: 8630.9983 - val_loss: 7631.9033\nEpoch 7/35\n35964/35964 [==============================] - 72s - loss: 8143.9787 - val_loss: 7030.0634\nEpoch 8/35\n35964/35964 [==============================] - 72s - loss: 7883.4281 - val_loss: 7317.5209\nEpoch 9/35\n35964/35964 [==============================] - 72s - loss: 7467.0412 - val_loss: 6484.9748\nEpoch 10/35\n35964/35964 [==============================] - 72s - loss: 7209.5031 - val_loss: 5997.7775\nEpoch 11/35\n35964/35964 [==============================] - 72s - loss: 6927.5920 - val_loss: 5788.0981\nEpoch 12/35\n35964/35964 [==============================] - 72s - loss: 6715.3237 - val_loss: 5478.6077\nEpoch 13/35\n35964/35964 [==============================] - 72s - loss: 6533.4871 - val_loss: 5379.8309\nEpoch 14/35\n35964/35964 [==============================] - 72s - loss: 6399.8846 - val_loss: 5217.7689\nEpoch 15/35\n35964/35964 [==============================] - 72s - loss: 6250.6924 - val_loss: 5029.8046\nEpoch 16/35\n35964/35964 [==============================] - 72s - loss: 5975.3661 - val_loss: 5159.6967\nEpoch 17/35\n35964/35964 [==============================] - 72s - loss: 5975.6800 - val_loss: 4699.4047\nEpoch 18/35\n35964/35964 [==============================] - 72s - loss: 5835.0874 - val_loss: 4610.2140\nEpoch 19/35\n35964/35964 [==============================] - 72s - loss: 5735.6967 - val_loss: 4534.0169\nEpoch 20/35\n35964/35964 [==============================] - 72s - loss: 5720.0174 - val_loss: 5235.4754\nEpoch 21/35\n35964/35964 [==============================] - 72s - loss: 5552.5980 - val_loss: 4426.9628\nEpoch 22/35\n35964/35964 [==============================] - 72s - loss: 5475.6967 - val_loss: 4795.1638\nEpoch 23/35\n35964/35964 [==============================] - 73s - loss: 5432.1412 - val_loss: 4303.8051\nEpoch 24/35\n35964/35964 [==============================] - 73s - loss: 5307.4175 - val_loss: 4795.9356\nEpoch 25/35\n35964/35964 [==============================] - 72s - loss: 5139.6907 - val_loss: 4397.4290\nEpoch 26/35\n35964/35964 [==============================] - 73s - loss: 5145.8064 - val_loss: 4000.1930\nEpoch 27/35\n35964/35964 [==============================] - 72s - loss: 5211.1155 - val_loss: 4097.8988\nEpoch 28/35\n35964/35964 [==============================] - 72s - loss: 5160.3637 - val_loss: 3984.9019\nEpoch 29/35\n35964/35964 [==============================] - 72s - loss: 5035.2585 - val_loss: 4935.7730\nEpoch 30/35\n35964/35964 [==============================] - 73s - loss: 4914.4231 - val_loss: 4161.9653\nEpoch 31/35\n35964/35964 [==============================] - 73s - loss: 4946.0091 - val_loss: 4002.8170\nEpoch 32/35\n35964/35964 [==============================] - 72s - loss: 4824.1349 - val_loss: 4342.5013\nEpoch 33/35\n35964/35964 [==============================] - 73s - loss: 4855.1827 - val_loss: 3785.8531\nEpoch 34/35\n35964/35964 [==============================] - 73s - loss: 4894.3338 - val_loss: 4307.0775\nEpoch 35/35\n35964/35964 [==============================] - 73s - loss: 4780.3014 - val_loss: 3909.9706\nPercent of variability explained by model: 57.1741803243\n"
],
[
"Train_and_save_DanQ_model('ARF24',35)",
"Train on 6246 samples, validate on 1562 samples\nEpoch 1/35\n6246/6246 [==============================] - 13s - loss: 1845.6847 - val_loss: 1268.6567\nEpoch 2/35\n6246/6246 [==============================] - 13s - loss: 1752.4039 - val_loss: 1191.2670\nEpoch 3/35\n6246/6246 [==============================] - 13s - loss: 1664.3215 - val_loss: 1105.1476\nEpoch 4/35\n6246/6246 [==============================] - 13s - loss: 1575.9163 - val_loss: 1012.8874\nEpoch 5/35\n6246/6246 [==============================] - 13s - loss: 1481.7557 - val_loss: 927.2195\nEpoch 6/35\n6246/6246 [==============================] - 13s - loss: 1399.2385 - val_loss: 860.5576\nEpoch 7/35\n6246/6246 [==============================] - 13s - loss: 1359.1820 - val_loss: 819.0821\nEpoch 8/35\n6246/6246 [==============================] - 12s - loss: 1329.2209 - val_loss: 803.4981\nEpoch 9/35\n6246/6246 [==============================] - 13s - loss: 1322.7034 - val_loss: 799.4066\nEpoch 10/35\n6246/6246 [==============================] - 13s - loss: 1316.4996 - val_loss: 798.5440\nEpoch 11/35\n6246/6246 [==============================] - 13s - loss: 1313.0510 - val_loss: 786.2240\nEpoch 12/35\n6246/6246 [==============================] - 13s - loss: 1283.1800 - val_loss: 765.1199\nEpoch 13/35\n6246/6246 [==============================] - 13s - loss: 1266.8248 - val_loss: 756.6198\nEpoch 14/35\n6246/6246 [==============================] - 12s - loss: 1256.1989 - val_loss: 707.6280\nEpoch 15/35\n6246/6246 [==============================] - 13s - loss: 1230.8148 - val_loss: 726.1959\nEpoch 16/35\n6246/6246 [==============================] - 13s - loss: 1215.7759 - val_loss: 677.1362\nEpoch 17/35\n6246/6246 [==============================] - 13s - loss: 1221.3784 - val_loss: 663.0693\nEpoch 18/35\n6246/6246 [==============================] - 13s - loss: 1201.1836 - val_loss: 663.7076\nEpoch 19/35\n6246/6246 [==============================] - 13s - loss: 1202.6870 - val_loss: 667.0089\nEpoch 20/35\n6246/6246 [==============================] - 13s - loss: 1186.6280 - val_loss: 749.2782\nEpoch 21/35\n6246/6246 [==============================] - 13s - loss: 1172.2532 - val_loss: 596.5781\nEpoch 22/35\n6246/6246 [==============================] - 13s - loss: 1155.1508 - val_loss: 659.9744\nEpoch 23/35\n6246/6246 [==============================] - 13s - loss: 1141.3941 - val_loss: 551.5812\nEpoch 24/35\n6246/6246 [==============================] - 13s - loss: 1124.9158 - val_loss: 732.5192\nEpoch 25/35\n6246/6246 [==============================] - 12s - loss: 1122.6277 - val_loss: 612.5024\nEpoch 26/35\n6246/6246 [==============================] - 13s - loss: 1085.2072 - val_loss: 662.0493\nEpoch 27/35\n6246/6246 [==============================] - 13s - loss: 1088.8146 - val_loss: 596.4913\nEpoch 28/35\n6246/6246 [==============================] - 13s - loss: 1081.4676 - val_loss: 644.7216\nEpoch 29/35\n6246/6246 [==============================] - 12s - loss: 1068.0843 - val_loss: 577.8746\nEpoch 30/35\n6246/6246 [==============================] - 13s - loss: 1064.6992 - val_loss: 507.9213\nEpoch 31/35\n6246/6246 [==============================] - 12s - loss: 1042.6208 - val_loss: 558.5735\nEpoch 32/35\n6246/6246 [==============================] - 12s - loss: 1038.6201 - val_loss: 462.0628\nEpoch 33/35\n6246/6246 [==============================] - 12s - loss: 1021.2140 - val_loss: 551.6287\nEpoch 34/35\n6246/6246 [==============================] - 12s - loss: 1033.1250 - val_loss: 720.6261\nEpoch 35/35\n6246/6246 [==============================] - 12s - loss: 1021.9171 - val_loss: 574.5370\nPercent of variability explained by model: 26.8260213126\n"
],
[
"Train_and_save_DanQ_model('ARF25',35)",
"Train on 49043 samples, validate on 12261 samples\nEpoch 1/35\n49043/49043 [==============================] - 100s - loss: 4231.9249 - val_loss: 3410.6344\nEpoch 2/35\n49043/49043 [==============================] - 99s - loss: 3469.8376 - val_loss: 2913.4720\nEpoch 3/35\n49043/49043 [==============================] - 99s - loss: 2966.6209 - val_loss: 2344.9716\nEpoch 4/35\n49043/49043 [==============================] - 99s - loss: 2545.7802 - val_loss: 2041.7218\nEpoch 5/35\n49043/49043 [==============================] - 99s - loss: 2342.5778 - val_loss: 1881.4029\nEpoch 6/35\n49043/49043 [==============================] - 99s - loss: 2248.5204 - val_loss: 1823.6334\nEpoch 7/35\n49043/49043 [==============================] - 100s - loss: 2156.5479 - val_loss: 1767.9331\nEpoch 8/35\n49043/49043 [==============================] - 99s - loss: 2086.5730 - val_loss: 1767.0500\nEpoch 9/35\n49043/49043 [==============================] - 98s - loss: 2031.4524 - val_loss: 1708.2211\nEpoch 10/35\n49043/49043 [==============================] - 99s - loss: 2004.6410 - val_loss: 1719.0536\nEpoch 11/35\n49043/49043 [==============================] - 99s - loss: 1973.2102 - val_loss: 1636.6358\nEpoch 12/35\n49043/49043 [==============================] - 99s - loss: 1905.9724 - val_loss: 1592.5196\nEpoch 13/35\n49043/49043 [==============================] - 99s - loss: 1880.8204 - val_loss: 1581.3771\nEpoch 14/35\n49043/49043 [==============================] - 99s - loss: 1830.4650 - val_loss: 1497.1677\nEpoch 15/35\n49043/49043 [==============================] - 99s - loss: 1772.0954 - val_loss: 1643.0501\nEpoch 16/35\n49043/49043 [==============================] - 99s - loss: 1744.7997 - val_loss: 1477.3018\nEpoch 17/35\n49043/49043 [==============================] - 99s - loss: 1704.1094 - val_loss: 1537.0124\nEpoch 18/35\n49043/49043 [==============================] - 99s - loss: 1700.3115 - val_loss: 1378.1721\nEpoch 19/35\n49043/49043 [==============================] - 99s - loss: 1657.9233 - val_loss: 1330.4318\nEpoch 20/35\n49043/49043 [==============================] - 99s - loss: 1645.3381 - val_loss: 1332.2371\nEpoch 21/35\n49043/49043 [==============================] - 99s - loss: 1638.3268 - val_loss: 1262.7675\nEpoch 22/35\n49043/49043 [==============================] - 99s - loss: 1611.4036 - val_loss: 1268.2791\nEpoch 23/35\n49043/49043 [==============================] - 99s - loss: 1604.3058 - val_loss: 1657.9262\nEpoch 24/35\n49043/49043 [==============================] - 99s - loss: 1575.7680 - val_loss: 1271.7683\nEpoch 25/35\n49043/49043 [==============================] - 99s - loss: 1573.3003 - val_loss: 1349.9233\nEpoch 26/35\n49043/49043 [==============================] - 99s - loss: 1558.2760 - val_loss: 1800.3849\nEpoch 27/35\n49043/49043 [==============================] - 99s - loss: 1552.2584 - val_loss: 1258.8138\nEpoch 28/35\n49043/49043 [==============================] - 99s - loss: 1552.2192 - val_loss: 1246.9384\nEpoch 29/35\n49043/49043 [==============================] - 99s - loss: 1550.2047 - val_loss: 1262.9190\nEpoch 30/35\n49043/49043 [==============================] - 99s - loss: 1522.2117 - val_loss: 1233.3699\nEpoch 31/35\n49043/49043 [==============================] - 99s - loss: 1540.4941 - val_loss: 1257.5926\nEpoch 32/35\n49043/49043 [==============================] - 99s - loss: 1495.7793 - val_loss: 1220.7274\nEpoch 33/35\n49043/49043 [==============================] - 99s - loss: 1493.1641 - val_loss: 1446.7592\nEpoch 34/35\n49043/49043 [==============================] - 99s - loss: 1496.3455 - val_loss: 1301.2476\nEpoch 35/35\n49043/49043 [==============================] - 99s - loss: 1474.7239 - val_loss: 1228.7005\nPercent of variability explained by model: 68.9232006375\n"
],
[
"Train_and_save_DanQ_model('ARF36',35)",
"Train on 27740 samples, validate on 6936 samples\nEpoch 1/35\n27740/27740 [==============================] - 57s - loss: 2706.4706 - val_loss: 2243.1777\nEpoch 2/35\n27740/27740 [==============================] - 56s - loss: 2298.0900 - val_loss: 1827.3086\nEpoch 3/35\n27740/27740 [==============================] - 56s - loss: 1968.8071 - val_loss: 1543.3805\nEpoch 4/35\n27740/27740 [==============================] - 56s - loss: 1780.6917 - val_loss: 1374.7958\nEpoch 5/35\n27740/27740 [==============================] - 56s - loss: 1633.8010 - val_loss: 1190.2560\nEpoch 6/35\n27740/27740 [==============================] - 56s - loss: 1469.4236 - val_loss: 1080.1638\nEpoch 7/35\n27740/27740 [==============================] - 56s - loss: 1360.2485 - val_loss: 938.3718\nEpoch 8/35\n27740/27740 [==============================] - 57s - loss: 1276.4778 - val_loss: 1320.8241\nEpoch 9/35\n27740/27740 [==============================] - 56s - loss: 1222.6943 - val_loss: 962.0015\nEpoch 10/35\n27740/27740 [==============================] - 57s - loss: 1169.1075 - val_loss: 777.1483\nEpoch 11/35\n27740/27740 [==============================] - 56s - loss: 1119.6554 - val_loss: 755.8332\nEpoch 12/35\n27740/27740 [==============================] - 56s - loss: 1096.4447 - val_loss: 724.9508\nEpoch 13/35\n27740/27740 [==============================] - 56s - loss: 1061.7248 - val_loss: 697.2680\nEpoch 14/35\n27740/27740 [==============================] - 55s - loss: 1048.8343 - val_loss: 681.8855\nEpoch 15/35\n27740/27740 [==============================] - 55s - loss: 1005.5454 - val_loss: 671.5647\nEpoch 16/35\n27740/27740 [==============================] - 56s - loss: 982.8432 - val_loss: 689.3844\nEpoch 17/35\n27740/27740 [==============================] - 55s - loss: 966.7395 - val_loss: 667.2142\nEpoch 18/35\n27740/27740 [==============================] - 55s - loss: 956.8186 - val_loss: 637.4529\nEpoch 19/35\n27740/27740 [==============================] - 55s - loss: 920.2142 - val_loss: 684.8309\nEpoch 20/35\n27740/27740 [==============================] - 55s - loss: 910.9738 - val_loss: 625.5196\nEpoch 21/35\n27740/27740 [==============================] - 55s - loss: 892.5888 - val_loss: 558.9853\nEpoch 22/35\n27740/27740 [==============================] - 56s - loss: 880.0646 - val_loss: 546.9863\nEpoch 23/35\n27740/27740 [==============================] - 55s - loss: 871.3335 - val_loss: 549.5048\nEpoch 24/35\n27740/27740 [==============================] - 55s - loss: 843.2825 - val_loss: 682.5569\nEpoch 25/35\n27740/27740 [==============================] - 56s - loss: 845.7665 - val_loss: 578.4210\nEpoch 26/35\n27740/27740 [==============================] - 55s - loss: 839.3233 - val_loss: 523.9775\nEpoch 27/35\n27740/27740 [==============================] - 56s - loss: 844.6519 - val_loss: 549.6877\nEpoch 28/35\n27740/27740 [==============================] - 55s - loss: 824.7393 - val_loss: 581.6711\nEpoch 29/35\n27740/27740 [==============================] - 56s - loss: 816.1288 - val_loss: 610.2768\nEpoch 30/35\n27740/27740 [==============================] - 56s - loss: 822.5226 - val_loss: 501.3240\nEpoch 31/35\n27740/27740 [==============================] - 55s - loss: 806.5089 - val_loss: 524.9157\nEpoch 32/35\n27740/27740 [==============================] - 56s - loss: 803.0831 - val_loss: 766.9125\nEpoch 33/35\n27740/27740 [==============================] - 56s - loss: 777.0254 - val_loss: 494.8405\nEpoch 34/35\n27740/27740 [==============================] - 56s - loss: 794.8929 - val_loss: 509.8121\nEpoch 35/35\n27740/27740 [==============================] - 56s - loss: 769.7662 - val_loss: 509.3959\nPercent of variability explained by model: 53.5808931124\n"
],
[
"Train_and_save_DanQ_model('ARF10_rep1_ear',35)",
"Using TensorFlow backend.\n"
],
[
"Train_and_save_DanQ_model('ARF10_rep2_ear',35)",
"Train on 53817 samples, validate on 13455 samples\nEpoch 1/35\n53817/53817 [==============================] - 105s - loss: 2735.9892 - val_loss: 2196.0429\nEpoch 2/35\n53817/53817 [==============================] - 104s - loss: 2074.7095 - val_loss: 1679.8025\nEpoch 3/35\n53817/53817 [==============================] - 105s - loss: 1823.5133 - val_loss: 1452.7318\nEpoch 4/35\n53817/53817 [==============================] - 106s - loss: 1548.3769 - val_loss: 1139.5833\nEpoch 5/35\n53817/53817 [==============================] - 107s - loss: 1368.5312 - val_loss: 1367.0449\nEpoch 6/35\n53817/53817 [==============================] - 106s - loss: 1270.4029 - val_loss: 956.2281\nEpoch 7/35\n53817/53817 [==============================] - 107s - loss: 1224.3185 - val_loss: 918.1251\nEpoch 8/35\n53817/53817 [==============================] - 107s - loss: 1185.7815 - val_loss: 918.5137\nEpoch 9/35\n53817/53817 [==============================] - 106s - loss: 1151.5525 - val_loss: 851.4569\nEpoch 10/35\n53817/53817 [==============================] - 108s - loss: 1127.1724 - val_loss: 974.0705\nEpoch 11/35\n53817/53817 [==============================] - 107s - loss: 1096.5490 - val_loss: 1210.4117\nEpoch 12/35\n53817/53817 [==============================] - 106s - loss: 1084.2597 - val_loss: 888.9740\nEpoch 13/35\n53817/53817 [==============================] - 105s - loss: 1060.1046 - val_loss: 800.3079\nEpoch 14/35\n53817/53817 [==============================] - 105s - loss: 1031.4883 - val_loss: 768.4859\nEpoch 15/35\n53817/53817 [==============================] - 107s - loss: 1017.6233 - val_loss: 833.3002\nEpoch 16/35\n53817/53817 [==============================] - 105s - loss: 999.5198 - val_loss: 959.5333\nEpoch 17/35\n53817/53817 [==============================] - 107s - loss: 994.9775 - val_loss: 768.8517\nEpoch 18/35\n53817/53817 [==============================] - 108s - loss: 966.5902 - val_loss: 747.7137\nEpoch 19/35\n53817/53817 [==============================] - 107s - loss: 958.5745 - val_loss: 1126.3153\nEpoch 20/35\n53817/53817 [==============================] - 108s - loss: 953.5367 - val_loss: 762.3031\nEpoch 21/35\n53817/53817 [==============================] - 106s - loss: 935.4873 - val_loss: 999.5213\nEpoch 22/35\n53817/53817 [==============================] - 105s - loss: 920.0312 - val_loss: 721.3861\nEpoch 23/35\n53817/53817 [==============================] - 104s - loss: 918.6266 - val_loss: 763.5100\nEpoch 24/35\n53817/53817 [==============================] - 105s - loss: 908.5171 - val_loss: 713.9174\nEpoch 25/35\n53817/53817 [==============================] - 104s - loss: 900.0862 - val_loss: 837.5072\nEpoch 26/35\n53817/53817 [==============================] - 104s - loss: 889.1065 - val_loss: 688.1433\nEpoch 27/35\n53817/53817 [==============================] - 105s - loss: 892.6824 - val_loss: 770.2082\nEpoch 28/35\n53817/53817 [==============================] - 105s - loss: 882.1656 - val_loss: 726.8864\nEpoch 29/35\n53817/53817 [==============================] - 104s - loss: 880.4216 - val_loss: 680.0496\nEpoch 30/35\n53817/53817 [==============================] - 106s - loss: 873.0544 - val_loss: 717.0640\nEpoch 31/35\n53817/53817 [==============================] - 104s - loss: 865.6911 - val_loss: 689.4541\nEpoch 32/35\n53817/53817 [==============================] - 105s - loss: 871.8002 - val_loss: 675.5850\nEpoch 33/35\n53817/53817 [==============================] - 106s - loss: 864.2799 - val_loss: 684.6305\nEpoch 34/35\n53817/53817 [==============================] - 106s - loss: 847.1374 - val_loss: 651.5566\nEpoch 35/35\n53817/53817 [==============================] - 107s - loss: 849.8304 - val_loss: 718.3556\nPercent of variability explained by model: 67.8468598329\n"
],
[
"Train_and_save_DanQ_model('ARF10_rep1_tassel',35)",
"Train on 31403 samples, validate on 7851 samples\nEpoch 1/35\n31403/31403 [==============================] - 63s - loss: 1571.1728 - val_loss: 1351.4851\nEpoch 2/35\n31403/31403 [==============================] - 63s - loss: 1196.3053 - val_loss: 1037.7606\nEpoch 3/35\n31403/31403 [==============================] - 63s - loss: 1016.0788 - val_loss: 942.9680\nEpoch 4/35\n31403/31403 [==============================] - 63s - loss: 960.3343 - val_loss: 886.9431\nEpoch 5/35\n31403/31403 [==============================] - 62s - loss: 910.0408 - val_loss: 816.6931\nEpoch 6/35\n31403/31403 [==============================] - 62s - loss: 824.9694 - val_loss: 733.0281\nEpoch 7/35\n31403/31403 [==============================] - 62s - loss: 772.4587 - val_loss: 670.1912\nEpoch 8/35\n31403/31403 [==============================] - 62s - loss: 722.3292 - val_loss: 1066.9985\nEpoch 9/35\n31403/31403 [==============================] - 62s - loss: 696.5746 - val_loss: 757.6237\nEpoch 10/35\n31403/31403 [==============================] - 62s - loss: 663.6295 - val_loss: 615.5785\nEpoch 11/35\n31403/31403 [==============================] - 62s - loss: 647.9178 - val_loss: 761.9931\nEpoch 12/35\n31403/31403 [==============================] - 62s - loss: 625.0294 - val_loss: 736.0144\nEpoch 13/35\n31403/31403 [==============================] - 62s - loss: 607.5215 - val_loss: 653.8895\nEpoch 14/35\n31403/31403 [==============================] - 62s - loss: 584.9469 - val_loss: 654.1202\nEpoch 15/35\n31403/31403 [==============================] - 62s - loss: 562.0689 - val_loss: 537.7629\nEpoch 16/35\n31403/31403 [==============================] - 61s - loss: 553.4536 - val_loss: 566.3934\nEpoch 17/35\n31403/31403 [==============================] - 61s - loss: 535.9065 - val_loss: 531.9602\nEpoch 18/35\n31403/31403 [==============================] - 61s - loss: 534.4462 - val_loss: 544.7651\nEpoch 19/35\n31403/31403 [==============================] - 61s - loss: 520.9113 - val_loss: 572.7887\nEpoch 20/35\n31403/31403 [==============================] - 62s - loss: 512.0969 - val_loss: 493.9874\nEpoch 21/35\n31403/31403 [==============================] - 61s - loss: 499.3621 - val_loss: 463.6151\nEpoch 22/35\n31403/31403 [==============================] - 61s - loss: 500.6590 - val_loss: 476.1600\nEpoch 23/35\n31403/31403 [==============================] - 61s - loss: 490.8636 - val_loss: 456.1391\nEpoch 24/35\n31403/31403 [==============================] - 61s - loss: 482.2543 - val_loss: 522.2680\nEpoch 25/35\n31403/31403 [==============================] - 62s - loss: 478.4660 - val_loss: 534.0453\nEpoch 26/35\n31403/31403 [==============================] - 62s - loss: 471.5043 - val_loss: 455.2348\nEpoch 27/35\n31403/31403 [==============================] - 62s - loss: 472.7790 - val_loss: 548.4255\nEpoch 28/35\n31403/31403 [==============================] - 62s - loss: 464.2687 - val_loss: 444.4443\nEpoch 29/35\n31403/31403 [==============================] - 61s - loss: 464.8370 - val_loss: 490.7210\nEpoch 30/35\n31403/31403 [==============================] - 61s - loss: 461.7160 - val_loss: 435.3085\nEpoch 31/35\n31403/31403 [==============================] - 62s - loss: 459.0585 - val_loss: 433.1171\nEpoch 32/35\n31403/31403 [==============================] - 62s - loss: 458.5646 - val_loss: 479.2010\nEpoch 33/35\n31403/31403 [==============================] - 62s - loss: 444.8748 - val_loss: 450.6478\nEpoch 34/35\n31403/31403 [==============================] - 63s - loss: 442.6540 - val_loss: 453.4857\nEpoch 35/35\n31403/31403 [==============================] - 62s - loss: 448.3169 - val_loss: 435.4559\nPercent of variability explained by model: 68.895173477\n"
],
[
"Train_and_save_DanQ_model('ARF10_rep2_tassel',35)",
"Train on 48745 samples, validate on 12187 samples\nEpoch 1/35\n48745/48745 [==============================] - 99s - loss: 2912.2922 - val_loss: 2496.6601\nEpoch 2/35\n48745/48745 [==============================] - 97s - loss: 2320.6934 - val_loss: 2059.1017\nEpoch 3/35\n48745/48745 [==============================] - 97s - loss: 2077.2247 - val_loss: 1963.1966\nEpoch 4/35\n48745/48745 [==============================] - 99s - loss: 1984.6060 - val_loss: 1876.5615\nEpoch 5/35\n48745/48745 [==============================] - 97s - loss: 1842.2177 - val_loss: 1759.1762\nEpoch 6/35\n48745/48745 [==============================] - 94s - loss: 1674.5266 - val_loss: 1510.3170\nEpoch 7/35\n48745/48745 [==============================] - 94s - loss: 1564.8009 - val_loss: 1660.5494\nEpoch 8/35\n48745/48745 [==============================] - 94s - loss: 1506.3860 - val_loss: 1413.6896\nEpoch 9/35\n48745/48745 [==============================] - 93s - loss: 1442.3534 - val_loss: 1337.6433\nEpoch 10/35\n48745/48745 [==============================] - 93s - loss: 1404.6619 - val_loss: 1291.9787\nEpoch 11/35\n48745/48745 [==============================] - 94s - loss: 1349.7194 - val_loss: 1416.7899\nEpoch 12/35\n48745/48745 [==============================] - 94s - loss: 1341.2044 - val_loss: 1226.6917\nEpoch 13/35\n48745/48745 [==============================] - 94s - loss: 1283.1535 - val_loss: 1164.9581\nEpoch 14/35\n48745/48745 [==============================] - 94s - loss: 1237.7734 - val_loss: 1209.1388\nEpoch 15/35\n48745/48745 [==============================] - 94s - loss: 1220.3711 - val_loss: 1250.4805\nEpoch 16/35\n48745/48745 [==============================] - 94s - loss: 1188.2384 - val_loss: 1114.6012\nEpoch 17/35\n48745/48745 [==============================] - 94s - loss: 1175.3719 - val_loss: 1066.0846\nEpoch 18/35\n48745/48745 [==============================] - 94s - loss: 1148.1204 - val_loss: 1072.0996\nEpoch 19/35\n48745/48745 [==============================] - 94s - loss: 1116.8075 - val_loss: 1030.3942\nEpoch 20/35\n48745/48745 [==============================] - 96s - loss: 1119.6857 - val_loss: 1066.2099\nEpoch 21/35\n48745/48745 [==============================] - 96s - loss: 1115.2190 - val_loss: 1087.2071\nEpoch 22/35\n48745/48745 [==============================] - 96s - loss: 1087.2154 - val_loss: 1009.0873\nEpoch 23/35\n48745/48745 [==============================] - 97s - loss: 1093.3352 - val_loss: 1132.4259\nEpoch 24/35\n48745/48745 [==============================] - 96s - loss: 1083.4726 - val_loss: 1097.8092\nEpoch 25/35\n48745/48745 [==============================] - 97s - loss: 1075.3678 - val_loss: 1064.3904\nEpoch 26/35\n48745/48745 [==============================] - 97s - loss: 1052.8227 - val_loss: 1074.2313\nEpoch 27/35\n48745/48745 [==============================] - 93s - loss: 1058.0004 - val_loss: 1000.6560\nEpoch 28/35\n48745/48745 [==============================] - 95s - loss: 1030.5848 - val_loss: 977.2433\nEpoch 29/35\n48745/48745 [==============================] - 97s - loss: 1030.7933 - val_loss: 981.8221\nEpoch 30/35\n48745/48745 [==============================] - 97s - loss: 1026.8462 - val_loss: 987.1618\nEpoch 31/35\n48745/48745 [==============================] - 96s - loss: 1009.8915 - val_loss: 957.4260\nEpoch 32/35\n48745/48745 [==============================] - 97s - loss: 996.6200 - val_loss: 988.3522\nEpoch 33/35\n48745/48745 [==============================] - 94s - loss: 1007.0529 - val_loss: 1091.2293\nEpoch 34/35\n48745/48745 [==============================] - 96s - loss: 993.3373 - val_loss: 1024.1513\nEpoch 35/35\n48745/48745 [==============================] - 97s - loss: 997.0950 - val_loss: 952.6439\nPercent of variability explained by model: 63.8616784321\n"
],
[
"Train_and_save_DanQ_model('ARF4',35)",
"Using TensorFlow backend.\n"
],
[
"Train_and_save_DanQ_model('ARF4_rep2',35)",
"Train on 19473 samples, validate on 4869 samples\nEpoch 1/35\n19473/19473 [==============================] - 37s - loss: 1679.4559 - val_loss: 1132.3133\nEpoch 2/35\n19473/19473 [==============================] - 36s - loss: 1383.0800 - val_loss: 931.4516\nEpoch 3/35\n19473/19473 [==============================] - 36s - loss: 1301.4132 - val_loss: 913.7392\nEpoch 4/35\n19473/19473 [==============================] - 36s - loss: 1290.4728 - val_loss: 912.5556\nEpoch 5/35\n19473/19473 [==============================] - 36s - loss: 1277.8503 - val_loss: 865.1717\nEpoch 6/35\n19473/19473 [==============================] - 36s - loss: 1282.8576 - val_loss: 891.8963\nEpoch 7/35\n19473/19473 [==============================] - 36s - loss: 1272.3135 - val_loss: 871.9457\nEpoch 8/35\n19473/19473 [==============================] - 36s - loss: 1244.8601 - val_loss: 861.7561\nEpoch 9/35\n19473/19473 [==============================] - 36s - loss: 1216.9461 - val_loss: 803.5947\nEpoch 10/35\n19473/19473 [==============================] - 36s - loss: 1181.0971 - val_loss: 766.5046\nEpoch 11/35\n19473/19473 [==============================] - 36s - loss: 1120.1579 - val_loss: 873.6869\nEpoch 12/35\n19473/19473 [==============================] - 36s - loss: 1088.7480 - val_loss: 651.1982\nEpoch 13/35\n19473/19473 [==============================] - 36s - loss: 1043.4052 - val_loss: 752.4677\nEpoch 14/35\n19473/19473 [==============================] - 36s - loss: 1029.7515 - val_loss: 593.4123\nEpoch 15/35\n19473/19473 [==============================] - 36s - loss: 1006.2415 - val_loss: 537.1680\nEpoch 16/35\n19473/19473 [==============================] - 36s - loss: 989.9344 - val_loss: 774.3669\nEpoch 17/35\n19473/19473 [==============================] - 36s - loss: 984.4070 - val_loss: 597.0228\nEpoch 18/35\n19473/19473 [==============================] - 36s - loss: 952.9973 - val_loss: 522.0613\nEpoch 19/35\n19473/19473 [==============================] - 36s - loss: 944.6987 - val_loss: 522.8866\nEpoch 20/35\n19473/19473 [==============================] - 36s - loss: 922.0551 - val_loss: 548.2800\nEpoch 21/35\n19473/19473 [==============================] - 36s - loss: 916.5126 - val_loss: 522.4950\nEpoch 22/35\n19473/19473 [==============================] - 36s - loss: 903.4039 - val_loss: 620.2227\nEpoch 23/35\n19473/19473 [==============================] - 36s - loss: 895.7719 - val_loss: 550.5333\nEpoch 24/35\n19473/19473 [==============================] - 36s - loss: 896.0578 - val_loss: 530.9172\nEpoch 25/35\n19473/19473 [==============================] - 36s - loss: 880.7782 - val_loss: 461.1192\nEpoch 26/35\n19473/19473 [==============================] - 36s - loss: 874.0875 - val_loss: 469.8853\nEpoch 27/35\n19473/19473 [==============================] - 36s - loss: 860.5315 - val_loss: 468.0470\nEpoch 28/35\n19473/19473 [==============================] - 36s - loss: 846.8996 - val_loss: 442.2312\nEpoch 29/35\n19473/19473 [==============================] - 36s - loss: 845.1063 - val_loss: 494.2035\nEpoch 30/35\n19473/19473 [==============================] - 36s - loss: 833.3395 - val_loss: 472.8117\nEpoch 31/35\n19473/19473 [==============================] - 36s - loss: 827.7247 - val_loss: 437.4095\nEpoch 32/35\n19473/19473 [==============================] - 36s - loss: 813.2496 - val_loss: 418.6183\nEpoch 33/35\n19473/19473 [==============================] - 36s - loss: 807.6633 - val_loss: 504.5649\nEpoch 34/35\n19473/19473 [==============================] - 36s - loss: 802.3556 - val_loss: 416.9182\nEpoch 35/35\n19473/19473 [==============================] - 36s - loss: 795.5772 - val_loss: 411.3676\nPercent of variability explained by model: 52.8280910487\n"
],
[
"Train_and_save_DanQ_model('ARF4_rep3',35)",
"Train on 36190 samples, validate on 9048 samples\nEpoch 1/35\n36190/36190 [==============================] - 72s - loss: 3367.6591 - val_loss: 3307.8301\nEpoch 2/35\n36190/36190 [==============================] - 71s - loss: 2849.5019 - val_loss: 3014.9194\nEpoch 3/35\n36190/36190 [==============================] - 71s - loss: 2779.7190 - val_loss: 3007.9033\nEpoch 4/35\n36190/36190 [==============================] - 69s - loss: 2758.3360 - val_loss: 3007.5720\nEpoch 5/35\n36190/36190 [==============================] - 67s - loss: 2726.9250 - val_loss: 2967.4282\nEpoch 6/35\n36190/36190 [==============================] - 67s - loss: 2714.6290 - val_loss: 2896.4135\nEpoch 7/35\n36190/36190 [==============================] - 67s - loss: 2638.8910 - val_loss: 2822.2334\nEpoch 8/35\n36190/36190 [==============================] - 67s - loss: 2562.6571 - val_loss: 2736.8975\nEpoch 9/35\n36190/36190 [==============================] - 67s - loss: 2480.9359 - val_loss: 2673.9643\nEpoch 10/35\n36190/36190 [==============================] - 69s - loss: 2416.7002 - val_loss: 2586.1669\nEpoch 11/35\n36190/36190 [==============================] - 69s - loss: 2353.3997 - val_loss: 2438.5993\nEpoch 12/35\n36190/36190 [==============================] - 67s - loss: 2291.7351 - val_loss: 2813.4242\nEpoch 13/35\n36190/36190 [==============================] - 68s - loss: 2243.8905 - val_loss: 2330.0041\nEpoch 14/35\n36190/36190 [==============================] - 68s - loss: 2184.4594 - val_loss: 2391.5287\nEpoch 15/35\n36190/36190 [==============================] - 68s - loss: 2167.9827 - val_loss: 2257.3522\nEpoch 16/35\n36190/36190 [==============================] - 68s - loss: 2120.6718 - val_loss: 2229.8465\nEpoch 17/35\n36190/36190 [==============================] - 67s - loss: 2099.1641 - val_loss: 2245.2091\nEpoch 18/35\n36190/36190 [==============================] - 68s - loss: 2065.4634 - val_loss: 2204.9971\nEpoch 19/35\n36190/36190 [==============================] - 68s - loss: 2042.2773 - val_loss: 2175.3797\nEpoch 20/35\n36190/36190 [==============================] - 69s - loss: 2014.7688 - val_loss: 2234.6879\nEpoch 21/35\n36190/36190 [==============================] - 70s - loss: 1998.4618 - val_loss: 2118.2103\nEpoch 22/35\n36190/36190 [==============================] - 72s - loss: 1962.6600 - val_loss: 2274.4610\nEpoch 23/35\n36190/36190 [==============================] - 71s - loss: 1934.9538 - val_loss: 2088.0149\nEpoch 24/35\n36190/36190 [==============================] - 71s - loss: 1925.7744 - val_loss: 2150.9025\nEpoch 25/35\n36190/36190 [==============================] - 71s - loss: 1889.1768 - val_loss: 2088.1324\nEpoch 26/35\n36190/36190 [==============================] - 71s - loss: 1881.2483 - val_loss: 2028.0651\nEpoch 27/35\n36190/36190 [==============================] - 72s - loss: 1864.5443 - val_loss: 2026.0519\nEpoch 28/35\n36190/36190 [==============================] - 72s - loss: 1841.3566 - val_loss: 2015.3970\nEpoch 29/35\n36190/36190 [==============================] - 72s - loss: 1846.9823 - val_loss: 2001.9727\nEpoch 30/35\n36190/36190 [==============================] - 72s - loss: 1838.7619 - val_loss: 1986.5135\nEpoch 31/35\n36190/36190 [==============================] - 71s - loss: 1817.7643 - val_loss: 2006.2423\nEpoch 32/35\n36190/36190 [==============================] - 71s - loss: 1819.5251 - val_loss: 2011.5963\nEpoch 33/35\n36190/36190 [==============================] - 72s - loss: 1797.4400 - val_loss: 1981.8943\nEpoch 34/35\n36190/36190 [==============================] - 71s - loss: 1801.6066 - val_loss: 2029.0007\nEpoch 35/35\n36190/36190 [==============================] - 71s - loss: 1784.2935 - val_loss: 2329.1623\nPercent of variability explained by model: 30.5283859963\n"
],
[
"Train_and_save_DanQ_model('ARF10',35)",
"Train on 42963 samples, validate on 10741 samples\nEpoch 1/35\n42963/42963 [==============================] - 82s - loss: 2364.4806 - val_loss: 2013.0646\nEpoch 2/35\n42963/42963 [==============================] - 81s - loss: 1734.5396 - val_loss: 1463.8579\nEpoch 3/35\n42963/42963 [==============================] - 81s - loss: 1371.7000 - val_loss: 1130.8974\nEpoch 4/35\n42963/42963 [==============================] - 82s - loss: 1180.5277 - val_loss: 1069.9976\nEpoch 5/35\n42963/42963 [==============================] - 81s - loss: 1087.6656 - val_loss: 932.7324\nEpoch 6/35\n42963/42963 [==============================] - 80s - loss: 1046.5845 - val_loss: 866.3762\nEpoch 7/35\n42963/42963 [==============================] - 80s - loss: 1008.9000 - val_loss: 827.6527\nEpoch 8/35\n42963/42963 [==============================] - 79s - loss: 970.7698 - val_loss: 844.0327\nEpoch 9/35\n42963/42963 [==============================] - 79s - loss: 946.1754 - val_loss: 806.4745\nEpoch 10/35\n42963/42963 [==============================] - 80s - loss: 905.3566 - val_loss: 700.8230\nEpoch 11/35\n42963/42963 [==============================] - 81s - loss: 888.4429 - val_loss: 792.8951\nEpoch 12/35\n42963/42963 [==============================] - 82s - loss: 855.2450 - val_loss: 650.2038\nEpoch 13/35\n42963/42963 [==============================] - 82s - loss: 844.4491 - val_loss: 651.8952\nEpoch 14/35\n42963/42963 [==============================] - 82s - loss: 821.2733 - val_loss: 611.5214\nEpoch 15/35\n42963/42963 [==============================] - 82s - loss: 814.4304 - val_loss: 597.7862\nEpoch 16/35\n42963/42963 [==============================] - 82s - loss: 809.0766 - val_loss: 635.1612\nEpoch 17/35\n42963/42963 [==============================] - 82s - loss: 794.8655 - val_loss: 584.2861\nEpoch 18/35\n42963/42963 [==============================] - 82s - loss: 778.2633 - val_loss: 589.0683\nEpoch 19/35\n42963/42963 [==============================] - 82s - loss: 780.9996 - val_loss: 571.9919\nEpoch 20/35\n42963/42963 [==============================] - 82s - loss: 743.9281 - val_loss: 577.8172\nEpoch 21/35\n42963/42963 [==============================] - 82s - loss: 745.0407 - val_loss: 615.2937\nEpoch 22/35\n42963/42963 [==============================] - 82s - loss: 733.4389 - val_loss: 574.7604\nEpoch 23/35\n42963/42963 [==============================] - 82s - loss: 737.5555 - val_loss: 571.2478\nEpoch 24/35\n42963/42963 [==============================] - 82s - loss: 729.0695 - val_loss: 563.6074\nEpoch 25/35\n42963/42963 [==============================] - 82s - loss: 724.6396 - val_loss: 560.4709\nEpoch 26/35\n42963/42963 [==============================] - 82s - loss: 732.8482 - val_loss: 554.8340\nEpoch 27/35\n42963/42963 [==============================] - 82s - loss: 712.6953 - val_loss: 546.8854\nEpoch 28/35\n42963/42963 [==============================] - 82s - loss: 714.6152 - val_loss: 540.0943\nEpoch 29/35\n42963/42963 [==============================] - 82s - loss: 706.9493 - val_loss: 557.3089\nEpoch 30/35\n42963/42963 [==============================] - 82s - loss: 696.9899 - val_loss: 545.6832\nEpoch 31/35\n42963/42963 [==============================] - 82s - loss: 706.4488 - val_loss: 587.4052\nEpoch 32/35\n42963/42963 [==============================] - 82s - loss: 693.2072 - val_loss: 542.8237\nEpoch 33/35\n42963/42963 [==============================] - 82s - loss: 685.5955 - val_loss: 537.8628\nEpoch 34/35\n42963/42963 [==============================] - 81s - loss: 688.4545 - val_loss: 561.4629\nEpoch 35/35\n42963/42963 [==============================] - 81s - loss: 696.0120 - val_loss: 542.0661\nPercent of variability explained by model: 74.8382009504\n"
],
[
"Train_and_save_DanQ_model('ARF13',35)",
"Train on 23500 samples, validate on 5876 samples\nEpoch 1/35\n23500/23500 [==============================] - 45s - loss: 3260.6062 - val_loss: 2878.4745\nEpoch 2/35\n23500/23500 [==============================] - 45s - loss: 2730.0433 - val_loss: 2466.1536\nEpoch 3/35\n23500/23500 [==============================] - 45s - loss: 2282.1756 - val_loss: 1842.5053\nEpoch 4/35\n23500/23500 [==============================] - 45s - loss: 1844.0153 - val_loss: 1406.7536\nEpoch 5/35\n23500/23500 [==============================] - 45s - loss: 1541.0483 - val_loss: 1129.5317\nEpoch 6/35\n23500/23500 [==============================] - 45s - loss: 1379.6999 - val_loss: 1061.9651\nEpoch 7/35\n23500/23500 [==============================] - 45s - loss: 1297.5732 - val_loss: 1030.1212\nEpoch 8/35\n23500/23500 [==============================] - 45s - loss: 1242.7591 - val_loss: 913.2825\nEpoch 9/35\n23500/23500 [==============================] - 44s - loss: 1189.4518 - val_loss: 908.1424\nEpoch 10/35\n23500/23500 [==============================] - 44s - loss: 1164.2450 - val_loss: 919.6730\nEpoch 11/35\n23500/23500 [==============================] - 44s - loss: 1124.0101 - val_loss: 843.7477\nEpoch 12/35\n23500/23500 [==============================] - 44s - loss: 1096.5662 - val_loss: 810.6230\nEpoch 13/35\n23500/23500 [==============================] - 44s - loss: 1077.7338 - val_loss: 918.9437\nEpoch 14/35\n23500/23500 [==============================] - 44s - loss: 1050.4621 - val_loss: 809.8206\nEpoch 15/35\n23500/23500 [==============================] - 44s - loss: 1025.0704 - val_loss: 791.6479\nEpoch 16/35\n23500/23500 [==============================] - 44s - loss: 1006.1381 - val_loss: 742.1155\nEpoch 17/35\n23500/23500 [==============================] - 44s - loss: 991.7388 - val_loss: 722.9475\nEpoch 18/35\n23500/23500 [==============================] - 44s - loss: 967.7184 - val_loss: 702.3437\nEpoch 19/35\n23500/23500 [==============================] - 44s - loss: 955.5380 - val_loss: 690.7325\nEpoch 20/35\n23500/23500 [==============================] - 44s - loss: 928.0433 - val_loss: 689.0414\nEpoch 21/35\n23500/23500 [==============================] - 44s - loss: 914.2803 - val_loss: 653.0092\nEpoch 22/35\n23500/23500 [==============================] - 44s - loss: 893.9404 - val_loss: 640.3976\nEpoch 23/35\n23500/23500 [==============================] - 44s - loss: 885.3753 - val_loss: 670.1932\nEpoch 24/35\n23500/23500 [==============================] - 44s - loss: 874.1493 - val_loss: 692.9627\nEpoch 25/35\n23500/23500 [==============================] - 44s - loss: 873.2505 - val_loss: 718.7199\nEpoch 26/35\n23500/23500 [==============================] - 44s - loss: 847.1545 - val_loss: 596.9739\nEpoch 27/35\n23500/23500 [==============================] - 44s - loss: 842.9350 - val_loss: 588.9807\nEpoch 28/35\n23500/23500 [==============================] - 44s - loss: 822.8153 - val_loss: 573.3144\nEpoch 29/35\n23500/23500 [==============================] - 44s - loss: 815.3163 - val_loss: 598.0026\nEpoch 30/35\n23500/23500 [==============================] - 44s - loss: 801.5074 - val_loss: 715.1495\nEpoch 31/35\n23500/23500 [==============================] - 44s - loss: 781.1472 - val_loss: 570.6527\nEpoch 32/35\n23500/23500 [==============================] - 44s - loss: 789.7735 - val_loss: 657.8060\nEpoch 33/35\n23500/23500 [==============================] - 44s - loss: 776.8453 - val_loss: 554.1165\nEpoch 34/35\n23500/23500 [==============================] - 44s - loss: 767.8657 - val_loss: 585.7433\nEpoch 35/35\n23500/23500 [==============================] - 44s - loss: 785.0858 - val_loss: 547.1795\nPercent of variability explained by model: 73.9722611215\n"
],
[
"Train_and_save_DanQ_model('ARF16',35)",
"Train on 53941 samples, validate on 13486 samples\nEpoch 1/35\n53941/53941 [==============================] - 104s - loss: 9463.3411 - val_loss: 11466.4891\nEpoch 2/35\n53941/53941 [==============================] - 103s - loss: 8558.3027 - val_loss: 11119.7556\nEpoch 3/35\n53941/53941 [==============================] - 103s - loss: 8424.2766 - val_loss: 10964.1154\nEpoch 4/35\n53941/53941 [==============================] - 103s - loss: 8299.6816 - val_loss: 10780.1169\nEpoch 5/35\n53941/53941 [==============================] - 103s - loss: 8038.9400 - val_loss: 10451.6659\nEpoch 6/35\n53941/53941 [==============================] - 103s - loss: 7760.9728 - val_loss: 10418.1807\nEpoch 7/35\n53941/53941 [==============================] - 102s - loss: 7485.4884 - val_loss: 10147.1557\nEpoch 8/35\n53941/53941 [==============================] - 102s - loss: 7339.0710 - val_loss: 10459.5790\nEpoch 9/35\n53941/53941 [==============================] - 103s - loss: 7212.2982 - val_loss: 9553.9941\nEpoch 10/35\n53941/53941 [==============================] - 102s - loss: 7093.0289 - val_loss: 9460.1840\nEpoch 11/35\n53941/53941 [==============================] - 102s - loss: 7017.3432 - val_loss: 9558.7582\nEpoch 12/35\n53941/53941 [==============================] - 102s - loss: 6941.5186 - val_loss: 9613.7603\nEpoch 13/35\n53941/53941 [==============================] - 102s - loss: 6837.4931 - val_loss: 9279.6793\nEpoch 14/35\n53941/53941 [==============================] - 102s - loss: 6738.4136 - val_loss: 9950.7435\nEpoch 15/35\n53941/53941 [==============================] - 103s - loss: 6691.7959 - val_loss: 9318.6941\nEpoch 16/35\n53941/53941 [==============================] - 102s - loss: 6608.1653 - val_loss: 9014.6074\nEpoch 17/35\n53941/53941 [==============================] - 102s - loss: 6522.9413 - val_loss: 9111.3076\nEpoch 18/35\n53941/53941 [==============================] - 102s - loss: 6492.4264 - val_loss: 8981.8711\nEpoch 19/35\n53941/53941 [==============================] - 102s - loss: 6419.5070 - val_loss: 9084.3887\nEpoch 20/35\n53941/53941 [==============================] - 102s - loss: 6355.4390 - val_loss: 9008.5528\nEpoch 21/35\n53941/53941 [==============================] - 103s - loss: 6334.8788 - val_loss: 8860.3204\nEpoch 22/35\n53941/53941 [==============================] - 102s - loss: 6258.1236 - val_loss: 8819.6715\nEpoch 23/35\n53941/53941 [==============================] - 102s - loss: 6213.1623 - val_loss: 9149.9568\nEpoch 24/35\n53941/53941 [==============================] - 102s - loss: 6177.2981 - val_loss: 8809.9202\nEpoch 25/35\n53941/53941 [==============================] - 102s - loss: 6123.7487 - val_loss: 8924.4985\nEpoch 26/35\n53941/53941 [==============================] - 102s - loss: 6130.9793 - val_loss: 8933.6373\nEpoch 27/35\n53941/53941 [==============================] - 102s - loss: 6065.7940 - val_loss: 8732.7928\nEpoch 28/35\n53941/53941 [==============================] - 102s - loss: 6060.7093 - val_loss: 8961.4107\nEpoch 29/35\n53941/53941 [==============================] - 102s - loss: 6043.2317 - val_loss: 8627.6769\nEpoch 30/35\n53941/53941 [==============================] - 102s - loss: 6008.1131 - val_loss: 8586.5488\nEpoch 31/35\n53941/53941 [==============================] - 102s - loss: 6001.5337 - val_loss: 8759.5860\nEpoch 32/35\n53941/53941 [==============================] - 102s - loss: 5986.1187 - val_loss: 8682.4249\nEpoch 33/35\n53941/53941 [==============================] - 102s - loss: 5933.0512 - val_loss: 8978.9609\nEpoch 34/35\n53941/53941 [==============================] - 102s - loss: 5903.0483 - val_loss: 8812.1026\nEpoch 35/35\n53941/53941 [==============================] - 102s - loss: 5942.3226 - val_loss: 8768.1463\nPercent of variability explained by model: 34.3051068112\n"
],
[
"Train_and_save_DanQ_model('ARF18',35)",
"Train on 9536 samples, validate on 2384 samples\nEpoch 1/35\n9536/9536 [==============================] - 19s - loss: 4551.3087 - val_loss: 3765.3687\nEpoch 2/35\n9536/9536 [==============================] - 18s - loss: 4264.2203 - val_loss: 3494.2492\nEpoch 3/35\n9536/9536 [==============================] - 18s - loss: 3976.0749 - val_loss: 3214.3347\nEpoch 4/35\n9536/9536 [==============================] - 18s - loss: 3750.8471 - val_loss: 3001.1992\nEpoch 5/35\n9536/9536 [==============================] - 18s - loss: 3623.5280 - val_loss: 2897.0141\nEpoch 6/35\n9536/9536 [==============================] - 18s - loss: 3576.6640 - val_loss: 2878.4662\nEpoch 7/35\n9536/9536 [==============================] - 18s - loss: 3555.4869 - val_loss: 2872.2026\nEpoch 8/35\n9536/9536 [==============================] - 18s - loss: 3559.6610 - val_loss: 2871.8774\nEpoch 9/35\n9536/9536 [==============================] - 18s - loss: 3544.3018 - val_loss: 2865.2712\nEpoch 10/35\n9536/9536 [==============================] - 18s - loss: 3540.9527 - val_loss: 2835.2304\nEpoch 11/35\n9536/9536 [==============================] - 18s - loss: 3522.4646 - val_loss: 2826.2941\nEpoch 12/35\n9536/9536 [==============================] - 18s - loss: 3537.5548 - val_loss: 2805.6569\nEpoch 13/35\n9536/9536 [==============================] - 18s - loss: 3467.2021 - val_loss: 2789.0331\nEpoch 14/35\n9536/9536 [==============================] - 18s - loss: 3482.4845 - val_loss: 2775.8624\nEpoch 15/35\n9536/9536 [==============================] - 18s - loss: 3466.3659 - val_loss: 2760.7009\nEpoch 16/35\n9536/9536 [==============================] - 18s - loss: 3441.9068 - val_loss: 2742.0459\nEpoch 17/35\n9536/9536 [==============================] - 18s - loss: 3427.8328 - val_loss: 2734.1413\nEpoch 18/35\n9536/9536 [==============================] - 18s - loss: 3417.9450 - val_loss: 2712.7061\nEpoch 19/35\n9536/9536 [==============================] - 18s - loss: 3387.6997 - val_loss: 2689.6157\nEpoch 20/35\n9536/9536 [==============================] - 18s - loss: 3350.0506 - val_loss: 2608.8226\nEpoch 21/35\n9536/9536 [==============================] - 18s - loss: 3296.8725 - val_loss: 2578.7761\nEpoch 22/35\n9536/9536 [==============================] - 18s - loss: 3225.0268 - val_loss: 2776.9235\nEpoch 23/35\n9536/9536 [==============================] - 18s - loss: 3200.8930 - val_loss: 2569.2358\nEpoch 24/35\n9536/9536 [==============================] - 18s - loss: 3165.5454 - val_loss: 2366.1596\nEpoch 25/35\n9536/9536 [==============================] - 18s - loss: 3126.6468 - val_loss: 2395.1955\nEpoch 26/35\n9536/9536 [==============================] - 18s - loss: 3084.9360 - val_loss: 2281.6529\nEpoch 27/35\n9536/9536 [==============================] - 18s - loss: 3039.4327 - val_loss: 2307.9124\nEpoch 28/35\n9536/9536 [==============================] - 18s - loss: 3042.0998 - val_loss: 2357.1558\nEpoch 29/35\n9536/9536 [==============================] - 18s - loss: 3016.1919 - val_loss: 2280.4380\nEpoch 30/35\n9536/9536 [==============================] - 18s - loss: 2995.7759 - val_loss: 2166.7773\nEpoch 31/35\n9536/9536 [==============================] - 18s - loss: 2940.8803 - val_loss: 2155.1909\nEpoch 32/35\n9536/9536 [==============================] - 18s - loss: 2927.0390 - val_loss: 2126.2424\nEpoch 33/35\n9536/9536 [==============================] - 18s - loss: 2906.0545 - val_loss: 2352.7121\nEpoch 34/35\n9536/9536 [==============================] - 18s - loss: 2858.5164 - val_loss: 2060.4132\nEpoch 35/35\n9536/9536 [==============================] - 18s - loss: 2836.1459 - val_loss: 2121.8501\nPercent of variability explained by model: 26.0710017312\n"
],
[
"Train_and_save_DanQ_model('ARF27',35)",
"Train on 76796 samples, validate on 19200 samples\nEpoch 1/35\n76796/76796 [==============================] - 147s - loss: 11567.5999 - val_loss: 7797.8566\nEpoch 2/35\n76796/76796 [==============================] - 146s - loss: 10485.7554 - val_loss: 7440.0080\nEpoch 3/35\n76796/76796 [==============================] - 147s - loss: 10331.7848 - val_loss: 7394.0962\nEpoch 4/35\n76796/76796 [==============================] - 146s - loss: 10100.9652 - val_loss: 7577.4496\nEpoch 5/35\n76796/76796 [==============================] - 146s - loss: 9793.3170 - val_loss: 6915.0043\nEpoch 6/35\n76796/76796 [==============================] - 146s - loss: 9502.8091 - val_loss: 6240.1487\nEpoch 7/35\n76796/76796 [==============================] - 146s - loss: 9284.4717 - val_loss: 6883.5863\nEpoch 8/35\n76796/76796 [==============================] - 146s - loss: 9105.8293 - val_loss: 6142.5660\nEpoch 9/35\n76796/76796 [==============================] - 146s - loss: 8907.7040 - val_loss: 5788.8614\nEpoch 10/35\n76796/76796 [==============================] - 146s - loss: 8807.2780 - val_loss: 5718.9640\nEpoch 11/35\n76796/76796 [==============================] - 145s - loss: 8646.1518 - val_loss: 5524.2761\nEpoch 12/35\n76796/76796 [==============================] - 145s - loss: 8468.0482 - val_loss: 5456.4008\nEpoch 13/35\n76796/76796 [==============================] - 145s - loss: 8328.9032 - val_loss: 5274.8272\nEpoch 14/35\n76796/76796 [==============================] - 145s - loss: 8175.5070 - val_loss: 5127.8153\nEpoch 15/35\n76796/76796 [==============================] - 145s - loss: 8094.2276 - val_loss: 5248.7073\nEpoch 16/35\n76796/76796 [==============================] - 145s - loss: 7961.3261 - val_loss: 5127.5275\nEpoch 17/35\n76796/76796 [==============================] - 145s - loss: 7910.6706 - val_loss: 4933.0410\nEpoch 18/35\n76796/76796 [==============================] - 145s - loss: 7854.9603 - val_loss: 4915.1154\nEpoch 19/35\n76796/76796 [==============================] - 145s - loss: 7836.7134 - val_loss: 4859.1486\nEpoch 20/35\n76796/76796 [==============================] - 145s - loss: 7821.8868 - val_loss: 4880.9116\nEpoch 21/35\n76796/76796 [==============================] - 145s - loss: 7759.5270 - val_loss: 4937.9341\nEpoch 22/35\n76796/76796 [==============================] - 145s - loss: 7706.4979 - val_loss: 4866.2938\nEpoch 23/35\n76796/76796 [==============================] - 145s - loss: 7661.3977 - val_loss: 4760.7040\nEpoch 24/35\n76796/76796 [==============================] - 145s - loss: 7655.8762 - val_loss: 4761.6139\nEpoch 25/35\n76796/76796 [==============================] - 145s - loss: 7632.6630 - val_loss: 4817.1028\nEpoch 26/35\n76796/76796 [==============================] - 145s - loss: 7575.6240 - val_loss: 4764.1703\nEpoch 27/35\n76796/76796 [==============================] - 145s - loss: 7569.1694 - val_loss: 4850.8236\nEpoch 28/35\n76796/76796 [==============================] - 145s - loss: 7564.3062 - val_loss: 4765.7377\nEpoch 29/35\n76796/76796 [==============================] - 146s - loss: 7572.5786 - val_loss: 4926.5521\nEpoch 30/35\n76796/76796 [==============================] - 146s - loss: 7468.1937 - val_loss: 4725.3528\nEpoch 31/35\n76796/76796 [==============================] - 146s - loss: 7463.2669 - val_loss: 4951.1801\nEpoch 32/35\n76796/76796 [==============================] - 147s - loss: 7497.6844 - val_loss: 4743.0922\nEpoch 33/35\n76796/76796 [==============================] - 146s - loss: 7399.3070 - val_loss: 4702.1234\nEpoch 34/35\n76796/76796 [==============================] - 146s - loss: 7412.2034 - val_loss: 4652.1605\nEpoch 35/35\n76796/76796 [==============================] - 146s - loss: 7415.8879 - val_loss: 4833.3607\nPercent of variability explained by model: 39.1430997174\n"
],
[
"Train_and_save_DanQ_model('ARF29',35)",
"Train on 18176 samples, validate on 4545 samples\nEpoch 1/35\n18176/18176 [==============================] - 36s - loss: 4012.5159 - val_loss: 7084.5936\nEpoch 2/35\n18176/18176 [==============================] - 34s - loss: 3566.8719 - val_loss: 6579.0753\nEpoch 3/35\n18176/18176 [==============================] - 34s - loss: 3286.6815 - val_loss: 6295.5785\nEpoch 4/35\n18176/18176 [==============================] - 34s - loss: 3247.5279 - val_loss: 6296.0166\nEpoch 5/35\n18176/18176 [==============================] - 34s - loss: 3208.5870 - val_loss: 6249.1865\nEpoch 6/35\n18176/18176 [==============================] - 34s - loss: 3190.5696 - val_loss: 6212.4715\nEpoch 7/35\n18176/18176 [==============================] - 34s - loss: 3186.3926 - val_loss: 6198.6038\nEpoch 8/35\n18176/18176 [==============================] - 35s - loss: 3160.3990 - val_loss: 6161.8641\nEpoch 9/35\n18176/18176 [==============================] - 34s - loss: 3126.4145 - val_loss: 6011.4645\nEpoch 10/35\n18176/18176 [==============================] - 34s - loss: 3067.4938 - val_loss: 6045.6275\nEpoch 11/35\n18176/18176 [==============================] - 34s - loss: 3007.7921 - val_loss: 6069.6114\nEpoch 12/35\n18176/18176 [==============================] - 34s - loss: 2922.9409 - val_loss: 5861.1404\nEpoch 13/35\n18176/18176 [==============================] - 34s - loss: 2859.7227 - val_loss: 5642.7361\nEpoch 14/35\n18176/18176 [==============================] - 34s - loss: 2825.4111 - val_loss: 5586.3013\nEpoch 15/35\n18176/18176 [==============================] - 34s - loss: 2772.2867 - val_loss: 5546.1216\nEpoch 16/35\n18176/18176 [==============================] - 34s - loss: 2731.9619 - val_loss: 5508.5621\nEpoch 17/35\n18176/18176 [==============================] - 34s - loss: 2683.8070 - val_loss: 5549.8098\nEpoch 18/35\n18176/18176 [==============================] - 34s - loss: 2658.1472 - val_loss: 5618.1533\nEpoch 19/35\n18176/18176 [==============================] - 34s - loss: 2604.2639 - val_loss: 5572.4899\nEpoch 20/35\n18176/18176 [==============================] - 34s - loss: 2589.8870 - val_loss: 5391.9571\nEpoch 21/35\n18176/18176 [==============================] - 34s - loss: 2550.2193 - val_loss: 5328.2595\nEpoch 22/35\n18176/18176 [==============================] - 35s - loss: 2525.8761 - val_loss: 5395.4145\nEpoch 23/35\n18176/18176 [==============================] - 34s - loss: 2507.5790 - val_loss: 5364.2836\nEpoch 24/35\n18176/18176 [==============================] - 34s - loss: 2470.4161 - val_loss: 5881.2107\nEpoch 25/35\n18176/18176 [==============================] - 34s - loss: 2485.9862 - val_loss: 5308.3448\nEpoch 26/35\n18176/18176 [==============================] - 34s - loss: 2448.1507 - val_loss: 5222.3359\nEpoch 27/35\n18176/18176 [==============================] - 34s - loss: 2431.3644 - val_loss: 5220.8918\nEpoch 28/35\n18176/18176 [==============================] - 34s - loss: 2407.7872 - val_loss: 5316.2696\nEpoch 29/35\n18176/18176 [==============================] - 34s - loss: 2402.7066 - val_loss: 5425.3541\nEpoch 30/35\n18176/18176 [==============================] - 34s - loss: 2374.2633 - val_loss: 5628.7410\nEpoch 31/35\n18176/18176 [==============================] - 34s - loss: 2362.0490 - val_loss: 5157.7844\nEpoch 32/35\n18176/18176 [==============================] - 34s - loss: 2350.6472 - val_loss: 5112.2845\nEpoch 33/35\n18176/18176 [==============================] - 34s - loss: 2320.0966 - val_loss: 5099.1438\nEpoch 34/35\n18176/18176 [==============================] - 34s - loss: 2320.7829 - val_loss: 5319.6228\nEpoch 35/35\n18176/18176 [==============================] - 34s - loss: 2307.0901 - val_loss: 5076.8829\nPercent of variability explained by model: 27.0574528136\n"
],
[
"Train_and_save_DanQ_model('ARF34',35)",
"Using TensorFlow backend.\n"
],
[
"Train_and_save_DanQ_model('ARF35',35)",
"Train on 11855 samples, validate on 2964 samples\nEpoch 1/35\n11855/11855 [==============================] - 24s - loss: 6097.4915 - val_loss: 5784.4525\nEpoch 2/35\n11855/11855 [==============================] - 23s - loss: 5772.8231 - val_loss: 5463.0940\nEpoch 3/35\n11855/11855 [==============================] - 23s - loss: 5440.4093 - val_loss: 5099.5840\nEpoch 4/35\n11855/11855 [==============================] - 23s - loss: 5102.9008 - val_loss: 4760.2303\nEpoch 5/35\n11855/11855 [==============================] - 23s - loss: 4855.0404 - val_loss: 4536.7182\nEpoch 6/35\n11855/11855 [==============================] - 23s - loss: 4734.2198 - val_loss: 4467.9315\nEpoch 7/35\n11855/11855 [==============================] - 23s - loss: 4741.3306 - val_loss: 4454.6128\nEpoch 8/35\n11855/11855 [==============================] - 23s - loss: 4697.8945 - val_loss: 4430.3923\nEpoch 9/35\n11855/11855 [==============================] - 23s - loss: 4688.1672 - val_loss: 4399.4323\nEpoch 10/35\n11855/11855 [==============================] - 23s - loss: 4661.9672 - val_loss: 4423.1073\nEpoch 11/35\n11855/11855 [==============================] - 23s - loss: 4643.8215 - val_loss: 4335.0464\nEpoch 12/35\n11855/11855 [==============================] - 23s - loss: 4646.6278 - val_loss: 4333.4177\nEpoch 13/35\n11855/11855 [==============================] - 23s - loss: 4625.0273 - val_loss: 4321.1520\nEpoch 14/35\n11855/11855 [==============================] - 23s - loss: 4583.0405 - val_loss: 4285.6209\nEpoch 15/35\n11855/11855 [==============================] - 23s - loss: 4605.0021 - val_loss: 4297.5199\nEpoch 16/35\n11855/11855 [==============================] - 23s - loss: 4566.4320 - val_loss: 4237.5957\nEpoch 17/35\n11855/11855 [==============================] - 23s - loss: 4543.7511 - val_loss: 4273.7716\nEpoch 18/35\n11855/11855 [==============================] - 23s - loss: 4544.9670 - val_loss: 4163.1217\nEpoch 19/35\n11855/11855 [==============================] - 23s - loss: 4509.9262 - val_loss: 4199.9296\nEpoch 20/35\n11855/11855 [==============================] - 23s - loss: 4483.4442 - val_loss: 4067.7207\nEpoch 21/35\n11855/11855 [==============================] - 23s - loss: 4448.4036 - val_loss: 4045.7609\nEpoch 22/35\n11855/11855 [==============================] - 23s - loss: 4409.2989 - val_loss: 3975.7726\nEpoch 23/35\n11855/11855 [==============================] - 23s - loss: 4329.2529 - val_loss: 4013.4743\nEpoch 24/35\n11855/11855 [==============================] - 23s - loss: 4335.6587 - val_loss: 3878.5343\nEpoch 25/35\n11855/11855 [==============================] - 23s - loss: 4279.5517 - val_loss: 3804.0455\nEpoch 26/35\n11855/11855 [==============================] - 23s - loss: 4232.8491 - val_loss: 3914.8966\nEpoch 27/35\n11855/11855 [==============================] - 23s - loss: 4159.4006 - val_loss: 3857.0168\nEpoch 28/35\n11855/11855 [==============================] - 23s - loss: 4125.4522 - val_loss: 3911.7196\nEpoch 29/35\n11855/11855 [==============================] - 23s - loss: 4082.1091 - val_loss: 3632.5541\nEpoch 30/35\n11855/11855 [==============================] - 23s - loss: 4106.7159 - val_loss: 3781.8576\nEpoch 31/35\n11855/11855 [==============================] - 23s - loss: 4043.0479 - val_loss: 3584.0946\nEpoch 32/35\n11855/11855 [==============================] - 23s - loss: 4046.0540 - val_loss: 4309.6445\nEpoch 33/35\n11855/11855 [==============================] - 23s - loss: 3999.6126 - val_loss: 3581.3163\nEpoch 34/35\n11855/11855 [==============================] - 23s - loss: 3946.7305 - val_loss: 3549.4471\nEpoch 35/35\n11855/11855 [==============================] - 23s - loss: 3944.2907 - val_loss: 3476.7079\nPercent of variability explained by model: 25.1822268533\n"
],
[
"Train_and_save_DanQ_model('ARF39',35)",
"Train on 13050 samples, validate on 3263 samples\nEpoch 1/35\n13050/13050 [==============================] - 26s - loss: 7428.7201 - val_loss: 7121.2714\nEpoch 2/35\n13050/13050 [==============================] - 25s - loss: 6905.6091 - val_loss: 6518.6309\nEpoch 3/35\n13050/13050 [==============================] - 25s - loss: 6401.2708 - val_loss: 6051.2632\nEpoch 4/35\n13050/13050 [==============================] - 25s - loss: 6067.2285 - val_loss: 5770.6936\nEpoch 5/35\n13050/13050 [==============================] - 25s - loss: 5732.0044 - val_loss: 5313.6510\nEpoch 6/35\n13050/13050 [==============================] - 25s - loss: 5421.6541 - val_loss: 4916.7067\nEpoch 7/35\n13050/13050 [==============================] - 26s - loss: 5175.1188 - val_loss: 4663.0209\nEpoch 8/35\n13050/13050 [==============================] - 25s - loss: 4952.7396 - val_loss: 4365.2324\nEpoch 9/35\n13050/13050 [==============================] - 25s - loss: 4755.1789 - val_loss: 4247.4092\nEpoch 10/35\n13050/13050 [==============================] - 25s - loss: 4596.4414 - val_loss: 4046.7987\nEpoch 11/35\n13050/13050 [==============================] - 26s - loss: 4411.2367 - val_loss: 4019.5627\nEpoch 12/35\n13050/13050 [==============================] - 26s - loss: 4339.9014 - val_loss: 3774.2913\nEpoch 13/35\n13050/13050 [==============================] - 26s - loss: 4167.6949 - val_loss: 3708.8584\nEpoch 14/35\n13050/13050 [==============================] - 25s - loss: 4008.3335 - val_loss: 3444.2087\nEpoch 15/35\n13050/13050 [==============================] - 25s - loss: 3858.9158 - val_loss: 3276.1083\nEpoch 16/35\n13050/13050 [==============================] - 25s - loss: 3762.9474 - val_loss: 3232.8461\nEpoch 17/35\n13050/13050 [==============================] - 25s - loss: 3689.1088 - val_loss: 3418.8968\nEpoch 18/35\n13050/13050 [==============================] - 25s - loss: 3656.7790 - val_loss: 3084.6887\nEpoch 19/35\n13050/13050 [==============================] - 25s - loss: 3494.1276 - val_loss: 3005.5934\nEpoch 20/35\n13050/13050 [==============================] - 25s - loss: 3515.4422 - val_loss: 3321.5681\nEpoch 21/35\n13050/13050 [==============================] - 24s - loss: 3500.3236 - val_loss: 2941.3580\nEpoch 22/35\n13050/13050 [==============================] - 24s - loss: 3438.3702 - val_loss: 2966.1284\nEpoch 23/35\n13050/13050 [==============================] - 24s - loss: 3421.8837 - val_loss: 2891.6533\nEpoch 24/35\n13050/13050 [==============================] - 24s - loss: 3355.9554 - val_loss: 3008.0930\nEpoch 25/35\n13050/13050 [==============================] - 24s - loss: 3318.6918 - val_loss: 2890.2977\nEpoch 26/35\n13050/13050 [==============================] - 24s - loss: 3292.5316 - val_loss: 2829.5120\nEpoch 27/35\n13050/13050 [==============================] - 24s - loss: 3330.8081 - val_loss: 2779.3205\nEpoch 28/35\n13050/13050 [==============================] - 24s - loss: 3240.6894 - val_loss: 2909.2865\nEpoch 29/35\n13050/13050 [==============================] - 24s - loss: 3274.1068 - val_loss: 2819.2848\nEpoch 30/35\n13050/13050 [==============================] - 24s - loss: 3231.6703 - val_loss: 2715.2253\nEpoch 31/35\n13050/13050 [==============================] - 25s - loss: 3188.5408 - val_loss: 2798.0564\nEpoch 32/35\n13050/13050 [==============================] - 24s - loss: 3151.7353 - val_loss: 2663.8983\nEpoch 33/35\n13050/13050 [==============================] - 25s - loss: 3148.6593 - val_loss: 2674.2856\nEpoch 34/35\n13050/13050 [==============================] - 24s - loss: 3167.8683 - val_loss: 2657.1494\nEpoch 35/35\n13050/13050 [==============================] - 24s - loss: 3064.3372 - val_loss: 2570.6496\nPercent of variability explained by model: 55.419082283\n"
]
],
[
[
"# Creating dataset without a negative set",
"_____no_output_____"
]
],
[
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF4_GEM_events.txt','ARF4')",
"/usr/local/lib/python2.7/dist-packages/Bio/Seq.py:341: BiopythonDeprecationWarning: This method is obsolete; please use str(my_seq) instead of my_seq.tostring().\n BiopythonDeprecationWarning)\n"
],
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF39_GEM_events.txt','ARF39')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF35_GEM_events.txt','ARF35')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF34_GEM_events.txt','ARF34')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF10_GEM_events.txt','ARF10')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF13_GEM_events.txt','ARF13')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF16_GEM_events.txt','ARF16')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF18_GEM_events.txt','ARF18')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF27_GEM_events.txt','ARF27')",
"_____no_output_____"
],
[
"Generate_training_and_test_datasets_no_negative('/mnt/Data_DapSeq_Maize/ARF29_GEM_events.txt','ARF29')",
"_____no_output_____"
],
[
"#finding the min length of the test set\nList_of_ARFs =['ARF4','ARF10','ARF13','ARF16','ARF18','ARF27','ARF29','ARF34','ARF35','ARF39']\nseq_test_sets = [None]*len(List_of_ARFs)\n\ncounter1=0\nfor ARF_label in List_of_ARFs:\n seq_test_sets[counter1]=numpy.load('/mnt/Data_DapSeq_Maize/'+ARF_label+'no_negative_seq_test.npy')\n print(len(seq_test_sets[counter1]))\n counter1=counter1+1\n\n#based on this the test set will only be: 5960 in size\n",
"5747\n6713\n3672\n8429\n1490\n12000\n2841\n22497\n1853\n2040\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF4',35,5960)",
"Using TensorFlow backend.\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF39',35,5960)",
"Train on 4768 samples, validate on 1192 samples\nEpoch 1/35\n4768/4768 [==============================] - 9s - loss: 14577.9416 - val_loss: 12933.7465\nEpoch 2/35\n4768/4768 [==============================] - 9s - loss: 14073.1560 - val_loss: 12504.9977\nEpoch 3/35\n4768/4768 [==============================] - 9s - loss: 13627.9211 - val_loss: 12106.2705\nEpoch 4/35\n4768/4768 [==============================] - 9s - loss: 13168.9152 - val_loss: 11632.3015\nEpoch 5/35\n4768/4768 [==============================] - 9s - loss: 12722.4319 - val_loss: 11137.6340\nEpoch 6/35\n4768/4768 [==============================] - 9s - loss: 12167.5643 - val_loss: 10612.4973\nEpoch 7/35\n4768/4768 [==============================] - 9s - loss: 11630.5282 - val_loss: 10079.3457\nEpoch 8/35\n4768/4768 [==============================] - 9s - loss: 11041.3092 - val_loss: 9539.3172\nEpoch 9/35\n4768/4768 [==============================] - 9s - loss: 10532.2490 - val_loss: 9018.0391\nEpoch 10/35\n4768/4768 [==============================] - 9s - loss: 9952.3070 - val_loss: 8501.5769\nEpoch 11/35\n4768/4768 [==============================] - 9s - loss: 9422.7393 - val_loss: 8023.5584\nEpoch 12/35\n4768/4768 [==============================] - 9s - loss: 8998.2327 - val_loss: 7595.9637\nEpoch 13/35\n4768/4768 [==============================] - 9s - loss: 8575.4874 - val_loss: 7229.7785\nEpoch 14/35\n4768/4768 [==============================] - 9s - loss: 8399.7434 - val_loss: 6945.9726\nEpoch 15/35\n4768/4768 [==============================] - 9s - loss: 8145.4583 - val_loss: 6750.0343\nEpoch 16/35\n4768/4768 [==============================] - 9s - loss: 7946.3254 - val_loss: 6634.4909\nEpoch 17/35\n4768/4768 [==============================] - 9s - loss: 7875.7046 - val_loss: 6585.3010\nEpoch 18/35\n4768/4768 [==============================] - 9s - loss: 7867.9213 - val_loss: 6560.7160\nEpoch 19/35\n4768/4768 [==============================] - 9s - loss: 7687.4446 - val_loss: 6336.8109\nEpoch 20/35\n4768/4768 [==============================] - 9s - loss: 7533.5556 - val_loss: 6030.5207\nEpoch 21/35\n4768/4768 [==============================] - 9s - loss: 7259.3354 - val_loss: 5880.5821\nEpoch 22/35\n4768/4768 [==============================] - 9s - loss: 7227.7054 - val_loss: 5729.5056\nEpoch 23/35\n4768/4768 [==============================] - 9s - loss: 7139.2910 - val_loss: 5626.4758\nEpoch 24/35\n4768/4768 [==============================] - 9s - loss: 6972.7025 - val_loss: 5523.7227\nEpoch 25/35\n4768/4768 [==============================] - 9s - loss: 6826.7708 - val_loss: 5404.3682\nEpoch 26/35\n4768/4768 [==============================] - 9s - loss: 6734.6967 - val_loss: 5301.3958\nEpoch 27/35\n4768/4768 [==============================] - 9s - loss: 6646.6681 - val_loss: 5180.1779\nEpoch 28/35\n4768/4768 [==============================] - 9s - loss: 6548.8659 - val_loss: 5105.7130\nEpoch 29/35\n4768/4768 [==============================] - 9s - loss: 6489.3590 - val_loss: 5014.1606\nEpoch 30/35\n4768/4768 [==============================] - 9s - loss: 6177.1732 - val_loss: 4878.6666\nEpoch 31/35\n4768/4768 [==============================] - 9s - loss: 6114.8994 - val_loss: 4786.8649\nEpoch 32/35\n4768/4768 [==============================] - 9s - loss: 6014.9641 - val_loss: 4847.1161\nEpoch 33/35\n4768/4768 [==============================] - 9s - loss: 5702.4390 - val_loss: 4607.3779\nEpoch 34/35\n4768/4768 [==============================] - 9s - loss: 5764.0252 - val_loss: 4522.6867\nEpoch 35/35\n4768/4768 [==============================] - 9s - loss: 5857.0698 - val_loss: 4632.0016\nPercent of variability explained by model: 29.5327329983\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF35',35,5960)",
"Train on 4768 samples, validate on 1192 samples\nEpoch 1/35\n4768/4768 [==============================] - 9s - loss: 10946.4969 - val_loss: 11185.2873\nEpoch 2/35\n4768/4768 [==============================] - 9s - loss: 10533.5791 - val_loss: 10834.7799\nEpoch 3/35\n4768/4768 [==============================] - 9s - loss: 10172.1700 - val_loss: 10463.8320\nEpoch 4/35\n4768/4768 [==============================] - 9s - loss: 9768.0352 - val_loss: 10055.2487\nEpoch 5/35\n4768/4768 [==============================] - 9s - loss: 9382.1408 - val_loss: 9659.6886\nEpoch 6/35\n4768/4768 [==============================] - 9s - loss: 8987.8170 - val_loss: 9230.7290\nEpoch 7/35\n4768/4768 [==============================] - 9s - loss: 8547.3093 - val_loss: 8785.8348\nEpoch 8/35\n4768/4768 [==============================] - 9s - loss: 8088.5609 - val_loss: 8313.3311\nEpoch 9/35\n4768/4768 [==============================] - 9s - loss: 7666.6547 - val_loss: 7840.2453\nEpoch 10/35\n4768/4768 [==============================] - 9s - loss: 7177.4912 - val_loss: 7360.9617\nEpoch 11/35\n4768/4768 [==============================] - 9s - loss: 6750.3059 - val_loss: 6913.5058\nEpoch 12/35\n4768/4768 [==============================] - 9s - loss: 6412.9564 - val_loss: 6489.9776\nEpoch 13/35\n4768/4768 [==============================] - 8s - loss: 5985.2282 - val_loss: 6098.3254\nEpoch 14/35\n4768/4768 [==============================] - 8s - loss: 5702.4702 - val_loss: 5778.1726\nEpoch 15/35\n4768/4768 [==============================] - 9s - loss: 5466.2012 - val_loss: 5513.1851\nEpoch 16/35\n4768/4768 [==============================] - 8s - loss: 5194.3979 - val_loss: 5334.8031\nEpoch 17/35\n4768/4768 [==============================] - 8s - loss: 5223.3418 - val_loss: 5231.1662\nEpoch 18/35\n4768/4768 [==============================] - 8s - loss: 5209.4964 - val_loss: 5190.8448\nEpoch 19/35\n4768/4768 [==============================] - 8s - loss: 5214.6889 - val_loss: 5174.3212\nEpoch 20/35\n4768/4768 [==============================] - 8s - loss: 5162.2242 - val_loss: 5167.8655\nEpoch 21/35\n4768/4768 [==============================] - 8s - loss: 5167.8035 - val_loss: 5163.2450\nEpoch 22/35\n4768/4768 [==============================] - 8s - loss: 5150.0007 - val_loss: 5165.4142\nEpoch 23/35\n4768/4768 [==============================] - 8s - loss: 5127.5728 - val_loss: 5165.7103\nEpoch 24/35\n4768/4768 [==============================] - 8s - loss: 5161.7497 - val_loss: 5152.7857\nEpoch 25/35\n4768/4768 [==============================] - 9s - loss: 5093.5866 - val_loss: 5156.1450\nEpoch 26/35\n4768/4768 [==============================] - 8s - loss: 5144.9233 - val_loss: 5149.2959\nEpoch 27/35\n4768/4768 [==============================] - 9s - loss: 5120.0145 - val_loss: 5146.1774\nEpoch 28/35\n4768/4768 [==============================] - 8s - loss: 5100.5471 - val_loss: 5127.4838\nEpoch 29/35\n4768/4768 [==============================] - 8s - loss: 5218.7795 - val_loss: 5133.8482\nEpoch 30/35\n4768/4768 [==============================] - 8s - loss: 5057.8604 - val_loss: 5109.0342\nEpoch 31/35\n4768/4768 [==============================] - 8s - loss: 5174.0485 - val_loss: 5055.1585\nEpoch 32/35\n4768/4768 [==============================] - 9s - loss: 5060.4608 - val_loss: 5053.0450\nEpoch 33/35\n4768/4768 [==============================] - 9s - loss: 5055.0064 - val_loss: 5079.4916\nEpoch 34/35\n4768/4768 [==============================] - 8s - loss: 5064.3328 - val_loss: 5132.8067\nEpoch 35/35\n4768/4768 [==============================] - 8s - loss: 5078.3729 - val_loss: 5052.6419\nPercent of variability explained by model: 1.64739355478\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF34',35,5960)",
"Train on 4768 samples, validate on 1192 samples\nEpoch 1/35\n4768/4768 [==============================] - 9s - loss: 17719.5891 - val_loss: 15691.4057\nEpoch 2/35\n4768/4768 [==============================] - 9s - loss: 17452.0443 - val_loss: 15405.6035\nEpoch 3/35\n4768/4768 [==============================] - 9s - loss: 17168.2036 - val_loss: 15148.4330\nEpoch 4/35\n4768/4768 [==============================] - 8s - loss: 16901.5397 - val_loss: 14895.5741\nEpoch 5/35\n4768/4768 [==============================] - 8s - loss: 16628.1404 - val_loss: 14619.2694\nEpoch 6/35\n4768/4768 [==============================] - 8s - loss: 16361.8708 - val_loss: 14326.8482\nEpoch 7/35\n4768/4768 [==============================] - 8s - loss: 16051.8572 - val_loss: 14009.0199\nEpoch 8/35\n4768/4768 [==============================] - 9s - loss: 15706.0098 - val_loss: 13676.6697\nEpoch 9/35\n4768/4768 [==============================] - 9s - loss: 15397.3244 - val_loss: 13333.9494\nEpoch 10/35\n4768/4768 [==============================] - 9s - loss: 15009.6023 - val_loss: 12979.2436\nEpoch 11/35\n4768/4768 [==============================] - 9s - loss: 14674.8238 - val_loss: 12600.9859\nEpoch 12/35\n4768/4768 [==============================] - 8s - loss: 14267.0471 - val_loss: 12206.1986\nEpoch 13/35\n4768/4768 [==============================] - 8s - loss: 13848.2059 - val_loss: 11788.0071\nEpoch 14/35\n4768/4768 [==============================] - 9s - loss: 13471.5364 - val_loss: 11370.2029\nEpoch 15/35\n4768/4768 [==============================] - 9s - loss: 13076.1669 - val_loss: 10950.5317\nEpoch 16/35\n4768/4768 [==============================] - 9s - loss: 12676.4646 - val_loss: 10537.8259\nEpoch 17/35\n4768/4768 [==============================] - 9s - loss: 12326.4688 - val_loss: 10144.1147\nEpoch 18/35\n4768/4768 [==============================] - 9s - loss: 11923.4663 - val_loss: 9786.9047\nEpoch 19/35\n4768/4768 [==============================] - 9s - loss: 11610.7356 - val_loss: 9465.7874\nEpoch 20/35\n4768/4768 [==============================] - 9s - loss: 11454.2503 - val_loss: 9196.2210\nEpoch 21/35\n4768/4768 [==============================] - 9s - loss: 11246.4061 - val_loss: 9008.6464\nEpoch 22/35\n4768/4768 [==============================] - 9s - loss: 11091.3923 - val_loss: 8859.4581\nEpoch 23/35\n4768/4768 [==============================] - 9s - loss: 11032.3310 - val_loss: 8764.4206\nEpoch 24/35\n4768/4768 [==============================] - 9s - loss: 10998.9423 - val_loss: 8719.2872\nEpoch 25/35\n4768/4768 [==============================] - 8s - loss: 10795.6257 - val_loss: 8693.3548\nEpoch 26/35\n4768/4768 [==============================] - 9s - loss: 10882.1229 - val_loss: 8686.4291\nEpoch 27/35\n4768/4768 [==============================] - 9s - loss: 10984.9797 - val_loss: 8672.6397\nEpoch 28/35\n4768/4768 [==============================] - 9s - loss: 10812.2505 - val_loss: 8653.8552\nEpoch 29/35\n4768/4768 [==============================] - 9s - loss: 10933.0021 - val_loss: 8626.3384\nEpoch 30/35\n4768/4768 [==============================] - 9s - loss: 10920.2750 - val_loss: 8619.0407\nEpoch 31/35\n4768/4768 [==============================] - 9s - loss: 10941.7363 - val_loss: 8649.7234\nEpoch 32/35\n4768/4768 [==============================] - 9s - loss: 10941.4361 - val_loss: 8625.5589\nEpoch 33/35\n4768/4768 [==============================] - 9s - loss: 10804.4650 - val_loss: 8610.9649\nEpoch 34/35\n4768/4768 [==============================] - 9s - loss: 10757.0189 - val_loss: 8592.7522\nEpoch 35/35\n4768/4768 [==============================] - 9s - loss: 10730.3960 - val_loss: 8608.0205\nPercent of variability explained by model: 1.52459054695\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF10',35,5960)",
"Using TensorFlow backend.\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF13',35,5960)",
"Train on 4768 samples, validate on 1192 samples\nEpoch 1/35\n4768/4768 [==============================] - 9s - loss: 7162.8012 - val_loss: 7485.3040\nEpoch 2/35\n4768/4768 [==============================] - 9s - loss: 6905.1397 - val_loss: 7258.5765\nEpoch 3/35\n4768/4768 [==============================] - 9s - loss: 6696.2349 - val_loss: 7051.5224\nEpoch 4/35\n4768/4768 [==============================] - 9s - loss: 6462.5410 - val_loss: 6790.3744\nEpoch 5/35\n4768/4768 [==============================] - 9s - loss: 6218.5152 - val_loss: 6525.9009\nEpoch 6/35\n4768/4768 [==============================] - 9s - loss: 5944.5448 - val_loss: 6231.9420\nEpoch 7/35\n4768/4768 [==============================] - 9s - loss: 5665.5727 - val_loss: 5918.8718\nEpoch 8/35\n4768/4768 [==============================] - 9s - loss: 5383.3247 - val_loss: 5582.5464\nEpoch 9/35\n4768/4768 [==============================] - 9s - loss: 5059.8562 - val_loss: 5234.5013\nEpoch 10/35\n4768/4768 [==============================] - 9s - loss: 4765.1292 - val_loss: 4879.9716\nEpoch 11/35\n4768/4768 [==============================] - 9s - loss: 4403.7091 - val_loss: 4524.2552\nEpoch 12/35\n4768/4768 [==============================] - 9s - loss: 4133.4844 - val_loss: 4173.1508\nEpoch 13/35\n4768/4768 [==============================] - 9s - loss: 3805.9474 - val_loss: 3835.1713\nEpoch 14/35\n4768/4768 [==============================] - 9s - loss: 3531.3655 - val_loss: 3523.2739\nEpoch 15/35\n4768/4768 [==============================] - 9s - loss: 3312.8969 - val_loss: 3247.8757\nEpoch 16/35\n4768/4768 [==============================] - 9s - loss: 3100.3144 - val_loss: 3001.7607\nEpoch 17/35\n4768/4768 [==============================] - 9s - loss: 2919.4300 - val_loss: 2809.6163\nEpoch 18/35\n4768/4768 [==============================] - 9s - loss: 2863.8568 - val_loss: 2591.3716\nEpoch 19/35\n4768/4768 [==============================] - 9s - loss: 2701.4685 - val_loss: 2455.6865\nEpoch 20/35\n4768/4768 [==============================] - 9s - loss: 2682.5971 - val_loss: 2385.1186\nEpoch 21/35\n4768/4768 [==============================] - 9s - loss: 2550.9321 - val_loss: 2284.0103\nEpoch 22/35\n4768/4768 [==============================] - 9s - loss: 2494.7227 - val_loss: 2136.7737\nEpoch 23/35\n4768/4768 [==============================] - 9s - loss: 2444.3440 - val_loss: 2023.9215\nEpoch 24/35\n4768/4768 [==============================] - 9s - loss: 2393.5707 - val_loss: 1976.5227\nEpoch 25/35\n4768/4768 [==============================] - 9s - loss: 2353.7849 - val_loss: 1905.7492\nEpoch 26/35\n4768/4768 [==============================] - 9s - loss: 2347.7937 - val_loss: 1895.6703\nEpoch 27/35\n4768/4768 [==============================] - 9s - loss: 2313.1156 - val_loss: 1909.8415\nEpoch 28/35\n4768/4768 [==============================] - 9s - loss: 2268.2340 - val_loss: 1843.8834\nEpoch 29/35\n4768/4768 [==============================] - 9s - loss: 2258.2211 - val_loss: 1847.6030\nEpoch 30/35\n4768/4768 [==============================] - 9s - loss: 2259.9826 - val_loss: 1826.7762\nEpoch 31/35\n4768/4768 [==============================] - 9s - loss: 2222.8086 - val_loss: 1789.6405\nEpoch 32/35\n4768/4768 [==============================] - 9s - loss: 2185.0375 - val_loss: 1777.4582\nEpoch 33/35\n4768/4768 [==============================] - 9s - loss: 2217.3778 - val_loss: 1773.5324\nEpoch 34/35\n4768/4768 [==============================] - 9s - loss: 2193.6455 - val_loss: 1745.4401\nEpoch 35/35\n4768/4768 [==============================] - 9s - loss: 2146.9611 - val_loss: 1718.1591\nPercent of variability explained by model: 33.7417860049\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF16',35,5960)",
"Train on 4768 samples, validate on 1192 samples\nEpoch 1/35\n4768/4768 [==============================] - 9s - loss: 19244.4914 - val_loss: 24385.7134\nEpoch 2/35\n4768/4768 [==============================] - 9s - loss: 18528.0734 - val_loss: 23616.8646\nEpoch 3/35\n4768/4768 [==============================] - 9s - loss: 17900.6331 - val_loss: 23054.1207\nEpoch 4/35\n4768/4768 [==============================] - 9s - loss: 17397.3471 - val_loss: 22536.2846\nEpoch 5/35\n4768/4768 [==============================] - 9s - loss: 16954.8024 - val_loss: 21986.4600\nEpoch 6/35\n4768/4768 [==============================] - 9s - loss: 16358.7515 - val_loss: 21410.0441\nEpoch 7/35\n4768/4768 [==============================] - 9s - loss: 15858.3919 - val_loss: 20821.5654\nEpoch 8/35\n4768/4768 [==============================] - 9s - loss: 15400.5026 - val_loss: 20228.1970\nEpoch 9/35\n4768/4768 [==============================] - 9s - loss: 14880.9121 - val_loss: 19647.1964\nEpoch 10/35\n4768/4768 [==============================] - 9s - loss: 14325.1711 - val_loss: 19093.4150\nEpoch 11/35\n4768/4768 [==============================] - 9s - loss: 13781.4194 - val_loss: 18552.1781\nEpoch 12/35\n4768/4768 [==============================] - 9s - loss: 13409.9945 - val_loss: 18077.7874\nEpoch 13/35\n4768/4768 [==============================] - 9s - loss: 13096.8066 - val_loss: 17643.4105\nEpoch 14/35\n4768/4768 [==============================] - 9s - loss: 12821.4105 - val_loss: 17279.7092\nEpoch 15/35\n4768/4768 [==============================] - 9s - loss: 12589.8869 - val_loss: 16990.8248\nEpoch 16/35\n4768/4768 [==============================] - 9s - loss: 12370.1985 - val_loss: 16774.7517\nEpoch 17/35\n4768/4768 [==============================] - 9s - loss: 12473.5209 - val_loss: 16664.1146\nEpoch 18/35\n4768/4768 [==============================] - 9s - loss: 12148.5408 - val_loss: 16627.3970\nEpoch 19/35\n4768/4768 [==============================] - 9s - loss: 13136.7808 - val_loss: 17018.8270\nEpoch 20/35\n4768/4768 [==============================] - 9s - loss: 12281.1203 - val_loss: 16429.5476\nEpoch 21/35\n4768/4768 [==============================] - 9s - loss: 12374.0057 - val_loss: 16452.0995\nEpoch 22/35\n4768/4768 [==============================] - 9s - loss: 12418.8376 - val_loss: 16509.9579\nEpoch 23/35\n4768/4768 [==============================] - 9s - loss: 12208.7118 - val_loss: 16509.8445\nEpoch 24/35\n4768/4768 [==============================] - 9s - loss: 12421.2617 - val_loss: 16568.2082\nEpoch 25/35\n4768/4768 [==============================] - 9s - loss: 12307.4629 - val_loss: 16488.2786\nEpoch 26/35\n4768/4768 [==============================] - 9s - loss: 12321.5856 - val_loss: 16469.5076\nEpoch 27/35\n4768/4768 [==============================] - 9s - loss: 12337.3969 - val_loss: 16462.5404\nEpoch 28/35\n4768/4768 [==============================] - 9s - loss: 12169.4150 - val_loss: 16444.9535\nEpoch 29/35\n4768/4768 [==============================] - 9s - loss: 12219.2012 - val_loss: 16488.7667\nEpoch 30/35\n4768/4768 [==============================] - 9s - loss: 12161.6512 - val_loss: 16358.9330\nEpoch 31/35\n4768/4768 [==============================] - 9s - loss: 12145.7816 - val_loss: 16399.7615\nEpoch 32/35\n4768/4768 [==============================] - 9s - loss: 12129.2868 - val_loss: 16412.4780\nEpoch 33/35\n4768/4768 [==============================] - 9s - loss: 12153.1283 - val_loss: 16354.2944\nEpoch 34/35\n4768/4768 [==============================] - 9s - loss: 12067.0772 - val_loss: 16388.0742\nEpoch 35/35\n4768/4768 [==============================] - 9s - loss: 12306.4900 - val_loss: 16252.7368\nPercent of variability explained by model: 1.59533134158\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF18',35,5960)",
"Train on 4768 samples, validate on 1192 samples\nEpoch 1/35\n4768/4768 [==============================] - 9s - loss: 8748.9681 - val_loss: 8777.8464\nEpoch 2/35\n4768/4768 [==============================] - 9s - loss: 8583.0339 - val_loss: 8566.4760\nEpoch 3/35\n4768/4768 [==============================] - 9s - loss: 8386.2066 - val_loss: 8387.5742\nEpoch 4/35\n4768/4768 [==============================] - 9s - loss: 8198.7488 - val_loss: 8203.5701\nEpoch 5/35\n4768/4768 [==============================] - 9s - loss: 7990.8369 - val_loss: 7997.7229\nEpoch 6/35\n4768/4768 [==============================] - 9s - loss: 7784.3298 - val_loss: 7772.3799\nEpoch 7/35\n4768/4768 [==============================] - 9s - loss: 7540.8908 - val_loss: 7531.1038\nEpoch 8/35\n4768/4768 [==============================] - 9s - loss: 7290.9073 - val_loss: 7271.7973\nEpoch 9/35\n4768/4768 [==============================] - 9s - loss: 7025.3031 - val_loss: 7002.6395\nEpoch 10/35\n4768/4768 [==============================] - 9s - loss: 6727.2333 - val_loss: 6721.8100\nEpoch 11/35\n4768/4768 [==============================] - 9s - loss: 6422.1877 - val_loss: 6437.5237\nEpoch 12/35\n4768/4768 [==============================] - 9s - loss: 6160.3896 - val_loss: 6152.1863\nEpoch 13/35\n4768/4768 [==============================] - 9s - loss: 5862.7063 - val_loss: 5840.1146\nEpoch 14/35\n4768/4768 [==============================] - 9s - loss: 5571.1472 - val_loss: 5537.3236\nEpoch 15/35\n4768/4768 [==============================] - 9s - loss: 5255.9096 - val_loss: 5244.6692\nEpoch 16/35\n4768/4768 [==============================] - 9s - loss: 4968.9115 - val_loss: 4969.2486\nEpoch 17/35\n4768/4768 [==============================] - 9s - loss: 4731.7806 - val_loss: 4711.6057\nEpoch 18/35\n4768/4768 [==============================] - 9s - loss: 4502.8601 - val_loss: 4483.1978\nEpoch 19/35\n4768/4768 [==============================] - 9s - loss: 4349.1414 - val_loss: 4294.9318\nEpoch 20/35\n4768/4768 [==============================] - 9s - loss: 4153.2301 - val_loss: 4147.4267\nEpoch 21/35\n4768/4768 [==============================] - 9s - loss: 4078.0397 - val_loss: 4043.9683\nEpoch 22/35\n4768/4768 [==============================] - 9s - loss: 3958.7682 - val_loss: 3978.9997\nEpoch 23/35\n4768/4768 [==============================] - 9s - loss: 3972.9115 - val_loss: 3955.5714\nEpoch 24/35\n4768/4768 [==============================] - 9s - loss: 3959.0446 - val_loss: 3940.5484\nEpoch 25/35\n4768/4768 [==============================] - 9s - loss: 3954.1515 - val_loss: 3936.3855\nEpoch 26/35\n4768/4768 [==============================] - 9s - loss: 3977.3786 - val_loss: 3932.0859\nEpoch 27/35\n4768/4768 [==============================] - 9s - loss: 3906.9426 - val_loss: 3930.3919\nEpoch 28/35\n4768/4768 [==============================] - 9s - loss: 3975.7385 - val_loss: 3932.1672\nEpoch 29/35\n4768/4768 [==============================] - 9s - loss: 4003.0744 - val_loss: 3933.1659\nEpoch 30/35\n4768/4768 [==============================] - 9s - loss: 3952.7253 - val_loss: 3932.8414\nEpoch 31/35\n4768/4768 [==============================] - 9s - loss: 3972.3676 - val_loss: 3934.2554\nEpoch 32/35\n4768/4768 [==============================] - 9s - loss: 3952.0213 - val_loss: 3931.1075\nEpoch 33/35\n4768/4768 [==============================] - 9s - loss: 3983.0196 - val_loss: 3929.8413\nEpoch 34/35\n4768/4768 [==============================] - 9s - loss: 3963.8794 - val_loss: 3929.2836\nEpoch 35/35\n4768/4768 [==============================] - 9s - loss: 3899.4556 - val_loss: 3928.4144\nPercent of variability explained by model: 1.35322173052\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF27',35,5960)",
"Train on 4768 samples, validate on 1192 samples\nEpoch 1/35\n4768/4768 [==============================] - 9s - loss: 18744.2722 - val_loss: 19074.3203\nEpoch 2/35\n4768/4768 [==============================] - 9s - loss: 18279.2641 - val_loss: 18718.4480\nEpoch 3/35\n4768/4768 [==============================] - 9s - loss: 17938.3101 - val_loss: 18393.8900\nEpoch 4/35\n4768/4768 [==============================] - 9s - loss: 17556.0541 - val_loss: 18022.5358\nEpoch 5/35\n4768/4768 [==============================] - 9s - loss: 17171.9077 - val_loss: 17615.0990\nEpoch 6/35\n4768/4768 [==============================] - 9s - loss: 16740.2670 - val_loss: 17142.5259\nEpoch 7/35\n4768/4768 [==============================] - 9s - loss: 16288.3951 - val_loss: 16642.7629\nEpoch 8/35\n4768/4768 [==============================] - 9s - loss: 15763.2628 - val_loss: 16102.7216\nEpoch 9/35\n4768/4768 [==============================] - 9s - loss: 15222.8111 - val_loss: 15543.7195\nEpoch 10/35\n4768/4768 [==============================] - 9s - loss: 14667.7533 - val_loss: 14980.4200\nEpoch 11/35\n4768/4768 [==============================] - 9s - loss: 14172.3603 - val_loss: 14410.8022\nEpoch 12/35\n4768/4768 [==============================] - 9s - loss: 13577.6773 - val_loss: 13831.7882\nEpoch 13/35\n4768/4768 [==============================] - 9s - loss: 13110.6039 - val_loss: 13269.9711\nEpoch 14/35\n4768/4768 [==============================] - 9s - loss: 12590.6777 - val_loss: 12750.5111\nEpoch 15/35\n4768/4768 [==============================] - 9s - loss: 12191.1372 - val_loss: 12268.3314\nEpoch 16/35\n4768/4768 [==============================] - 9s - loss: 11702.7405 - val_loss: 11840.9488\nEpoch 17/35\n4768/4768 [==============================] - 9s - loss: 11330.9077 - val_loss: 11491.8811\nEpoch 18/35\n4768/4768 [==============================] - 9s - loss: 11144.5220 - val_loss: 11219.3217\nEpoch 19/35\n4768/4768 [==============================] - 9s - loss: 10999.1644 - val_loss: 11053.5681\nEpoch 20/35\n4768/4768 [==============================] - 9s - loss: 10863.2864 - val_loss: 10950.5029\nEpoch 21/35\n4768/4768 [==============================] - 9s - loss: 10824.9442 - val_loss: 10897.1107\nEpoch 22/35\n4768/4768 [==============================] - 9s - loss: 10805.7023 - val_loss: 10877.2154\nEpoch 23/35\n4768/4768 [==============================] - 9s - loss: 10784.7654 - val_loss: 10866.7357\nEpoch 24/35\n4768/4768 [==============================] - 9s - loss: 10848.6033 - val_loss: 10866.2338\nEpoch 25/35\n4768/4768 [==============================] - 9s - loss: 10803.9171 - val_loss: 10862.9972\nEpoch 26/35\n4768/4768 [==============================] - 9s - loss: 10767.1857 - val_loss: 10860.8342\nEpoch 27/35\n4768/4768 [==============================] - 9s - loss: 10842.3422 - val_loss: 10821.0203\nEpoch 28/35\n4768/4768 [==============================] - 9s - loss: 10777.1996 - val_loss: 10787.2853\nEpoch 29/35\n4768/4768 [==============================] - 9s - loss: 10977.6337 - val_loss: 10769.0943\nEpoch 30/35\n4768/4768 [==============================] - 9s - loss: 10652.9033 - val_loss: 10740.3247\nEpoch 31/35\n4768/4768 [==============================] - 9s - loss: 10696.7205 - val_loss: 10640.2055\nEpoch 32/35\n4768/4768 [==============================] - 9s - loss: 10713.1484 - val_loss: 10606.6910\nEpoch 33/35\n4768/4768 [==============================] - 9s - loss: 10908.9671 - val_loss: 10616.5042\nEpoch 34/35\n4768/4768 [==============================] - 9s - loss: 10757.9798 - val_loss: 10526.5241\nEpoch 35/35\n4768/4768 [==============================] - 9s - loss: 10861.3602 - val_loss: 10504.4291\nPercent of variability explained by model: 2.06880731388\n"
],
[
"Train_and_save_DanQ_model_no_negative('ARF29',35,5960)",
"Train on 4768 samples, validate on 1192 samples\nEpoch 1/35\n4768/4768 [==============================] - 9s - loss: 10420.5704 - val_loss: 8756.7509\nEpoch 2/35\n4768/4768 [==============================] - 9s - loss: 10109.8713 - val_loss: 8375.7107\nEpoch 3/35\n4768/4768 [==============================] - 9s - loss: 9781.5750 - val_loss: 8090.5768\nEpoch 4/35\n4768/4768 [==============================] - 9s - loss: 9485.4790 - val_loss: 7809.4614\nEpoch 5/35\n4768/4768 [==============================] - 9s - loss: 9189.2579 - val_loss: 7515.7224\nEpoch 6/35\n4768/4768 [==============================] - 9s - loss: 8905.5076 - val_loss: 7205.1788\nEpoch 7/35\n4768/4768 [==============================] - 9s - loss: 8594.0850 - val_loss: 6881.0137\nEpoch 8/35\n4768/4768 [==============================] - 9s - loss: 8260.0268 - val_loss: 6493.9966\nEpoch 9/35\n4768/4768 [==============================] - 9s - loss: 7872.9390 - val_loss: 6102.5359\nEpoch 10/35\n4768/4768 [==============================] - 9s - loss: 7479.7144 - val_loss: 5731.1808\nEpoch 11/35\n4768/4768 [==============================] - 9s - loss: 7172.7298 - val_loss: 5399.8816\nEpoch 12/35\n4768/4768 [==============================] - 9s - loss: 6867.3108 - val_loss: 5107.6534\nEpoch 13/35\n4768/4768 [==============================] - 9s - loss: 6623.8801 - val_loss: 4859.7648\nEpoch 14/35\n4768/4768 [==============================] - 9s - loss: 6466.8666 - val_loss: 4663.6207\nEpoch 15/35\n4768/4768 [==============================] - 9s - loss: 6288.2106 - val_loss: 4522.0391\nEpoch 16/35\n4768/4768 [==============================] - 9s - loss: 6199.7686 - val_loss: 4437.9086\nEpoch 17/35\n4768/4768 [==============================] - 9s - loss: 6198.6030 - val_loss: 4396.7168\nEpoch 18/35\n4768/4768 [==============================] - 9s - loss: 6090.3164 - val_loss: 4373.9370\nEpoch 19/35\n4768/4768 [==============================] - 9s - loss: 6087.1651 - val_loss: 4363.8964\nEpoch 20/35\n4768/4768 [==============================] - 9s - loss: 6171.0217 - val_loss: 4367.5215\nEpoch 21/35\n4768/4768 [==============================] - 9s - loss: 6166.1833 - val_loss: 4363.5162\nEpoch 22/35\n4768/4768 [==============================] - 9s - loss: 6088.2428 - val_loss: 4359.9851\nEpoch 23/35\n4768/4768 [==============================] - 9s - loss: 6156.3785 - val_loss: 4361.3981\nEpoch 24/35\n4768/4768 [==============================] - 9s - loss: 6202.8644 - val_loss: 4363.3255\nEpoch 25/35\n4768/4768 [==============================] - 9s - loss: 6131.8864 - val_loss: 4356.7086\nEpoch 26/35\n4768/4768 [==============================] - 9s - loss: 6129.0710 - val_loss: 4354.1063\nEpoch 27/35\n4768/4768 [==============================] - 9s - loss: 6090.2526 - val_loss: 4348.2977\nEpoch 28/35\n4768/4768 [==============================] - 9s - loss: 6166.1622 - val_loss: 4342.8343\nEpoch 29/35\n4768/4768 [==============================] - 9s - loss: 6101.2057 - val_loss: 4339.2586\nEpoch 30/35\n4768/4768 [==============================] - 9s - loss: 6085.7709 - val_loss: 4343.8753\nEpoch 31/35\n4768/4768 [==============================] - 9s - loss: 6099.9631 - val_loss: 4331.3811\nEpoch 32/35\n4768/4768 [==============================] - 9s - loss: 6092.3739 - val_loss: 4333.0799\nEpoch 33/35\n4768/4768 [==============================] - 9s - loss: 6095.4406 - val_loss: 4327.4171\nEpoch 34/35\n4768/4768 [==============================] - 9s - loss: 6056.4980 - val_loss: 4330.3611\nEpoch 35/35\n4768/4768 [==============================] - 9s - loss: 6050.3559 - val_loss: 4319.3550\nPercent of variability explained by model: 1.16073776296\n"
]
]
] |
[
"code",
"markdown",
"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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aad6237b0b71beaebb276e6c776acc1299ffcbc
| 263,936 |
ipynb
|
Jupyter Notebook
|
Chp08/Notebooks/PyPlot.ipynb
|
PetrKryslUCSD/Mastering-Julia-1.0
|
375342d933a48142b5b605b9c39cb5922e010691
|
[
"MIT"
] | null | null | null |
Chp08/Notebooks/PyPlot.ipynb
|
PetrKryslUCSD/Mastering-Julia-1.0
|
375342d933a48142b5b605b9c39cb5922e010691
|
[
"MIT"
] | null | null | null |
Chp08/Notebooks/PyPlot.ipynb
|
PetrKryslUCSD/Mastering-Julia-1.0
|
375342d933a48142b5b605b9c39cb5922e010691
|
[
"MIT"
] | 1 |
2020-09-15T19:05:40.000Z
|
2020-09-15T19:05:40.000Z
| 1,898.820144 | 132,618 | 0.963321 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4aad66782d2ebf613c757970a6e3b1cb29dcb1db
| 4,663 |
ipynb
|
Jupyter Notebook
|
Day 2/08 cliffwalk.ipynb
|
jpmaldonado/packt-rl
|
2edeb903ab47fe4f364da5950c08dc85b4ba3e92
|
[
"MIT"
] | 3 |
2018-08-23T19:20:49.000Z
|
2019-07-14T09:11:21.000Z
|
Day 2/.ipynb_checkpoints/08 cliffwalk-checkpoint.ipynb
|
jpmaldonado/packt-rl
|
2edeb903ab47fe4f364da5950c08dc85b4ba3e92
|
[
"MIT"
] | null | null | null |
Day 2/.ipynb_checkpoints/08 cliffwalk-checkpoint.ipynb
|
jpmaldonado/packt-rl
|
2edeb903ab47fe4f364da5950c08dc85b4ba3e92
|
[
"MIT"
] | 4 |
2018-08-23T13:55:39.000Z
|
2020-12-08T12:05:11.000Z
| 25.205405 | 275 | 0.521982 |
[
[
[
"# Tutorial: Policy optimization algorithms",
"_____no_output_____"
],
[
"## Montecarlo Policy Gradient",
"_____no_output_____"
],
[
"This is an example implementation of REINFORCE, as explained in the lecture.",
"_____no_output_____"
]
],
[
[
"import gym\nimport numpy as np",
"_____no_output_____"
],
[
"env = gym.make('CartPole-v0')",
"\u001b[33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.\u001b[0m\n"
],
[
"def featurize(s,a):\n return (2*a-1)*np.tanh(s)\n\ndef softmax_policy(theta, actions):\n def policy_fn(state):\n exp = np.exp([np.dot(featurize(state,a),theta) for a in actions])\n probs = exp/np.sum(exp)\n return probs\n return policy_fn\n\ndef run_episode(env, random_policy): \n done = False\n total_reward = 0\n state = env.reset()\n episode = []\n actions = range(env.action_space.n)\n while not done:\n probs = random_policy(state)\n action = np.random.choice(actions, p=probs)\n new_state, reward, done, _ = env.step(action)\n episode.append((state,action,reward))\n state = new_state\n total_reward += reward\n return episode, total_reward\n",
"_____no_output_____"
],
[
"theta = 2*np.random.rand(4)-1\nn_episodes = 10000\nactions = range(env.action_space.n)\ngamma = 1.\nalpha = 1e-3",
"_____no_output_____"
],
[
"for ep in range(n_episodes):\n G = 0\n policy = softmax_policy(theta,actions)\n episode, ep_reward = run_episode(env,policy)\n \n if ep_reward == 200:\n print(\"Won! this happened in episode \", ep)\n break\n \n if (ep+1) % 1000 == 0:\n print(\"Reward in episode {}: {}\".format(ep+1,ep_reward))\n \n \n for i, _ in enumerate(episode):\n s, a, r = _\n G = sum(x[2]*(gamma**j) for j, x in enumerate(episode[i:]))\n s = np.array(s)\n theta = theta + alpha*(featurize(s,a)-np.sum([policy(s)[a]*featurize(s,a) for a in actions]))*G\n",
"Reward in episode 1000: 99.0\nWon! this happened in episode 1244\n"
]
],
[
[
"## Your turn:\n\n- Implement REINFORCE and REINFORCE with baseline for `CliffWalking`.",
"_____no_output_____"
],
[
"## Additional material\n\nIf you feel ready for a more interesting challenge, you can try `Pong`, which is one of the simples Atari environments. You should do some preprocessing of the video frames, to speed up the computation (resize, downsample, and remove background or color altogether).\n\n\n\n",
"_____no_output_____"
],
[
"Try to solve this yourself first! If you get stuck or want some inspiration, look at Andrej Karpathy's post:\n\n- http://karpathy.github.io/2016/05/31/rl/\n- https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
4aad6736ae880743069b5cda0420ab4c56a2b289
| 10,057 |
ipynb
|
Jupyter Notebook
|
docs/source/user_guide/clean/clean_lat_long.ipynb
|
NoirTree/dataprep
|
4744134886017ce7381fa7ae7c201772e9bafc12
|
[
"MIT"
] | 1,229 |
2019-12-21T02:58:59.000Z
|
2022-03-30T08:12:33.000Z
|
docs/source/user_guide/clean/clean_lat_long.ipynb
|
NoirTree/dataprep
|
4744134886017ce7381fa7ae7c201772e9bafc12
|
[
"MIT"
] | 680 |
2019-12-19T06:09:23.000Z
|
2022-03-31T04:15:25.000Z
|
docs/source/user_guide/clean/clean_lat_long.ipynb
|
NoirTree/dataprep
|
4744134886017ce7381fa7ae7c201772e9bafc12
|
[
"MIT"
] | 170 |
2020-01-08T03:27:26.000Z
|
2022-03-20T20:42:55.000Z
| 27.107817 | 398 | 0.530576 |
[
[
[
".. _clean_lat_long_user_guide:\n\nGeographic Coordinates\n======================",
"_____no_output_____"
],
[
"Introduction\n------------\n\nThe function :func:`clean_lat_long() <dataprep.clean.clean_lat_long.clean_lat_long>` cleans and standardizes a DataFrame column containing latitude and/or longitude coordinates. The function :func:`validate_lat_long() <dataprep.clean.clean_lat_long.validate_lat_long>` validates either a single coordinate or a column of coordinates, returning True if the value is valid, and False otherwise.",
"_____no_output_____"
]
],
[
[
"The following latitude and longitude formats are supported by the `output_format` parameter:\n\n* Decimal degrees (dd): 41.5\n* Decimal degrees hemisphere (ddh): \"41.5° N\"\n* Degrees minutes (dm): \"41° 30′ N\"\n* Degrees minutes seconds (dms): \"41° 30′ 0″ N\"\n\nYou can split a column of geographic coordinates into one column for latitude and another for longitude by setting the parameter ``split`` to True.\n\nInvalid parsing is handled with the `errors` parameter:\n\n* \"coerce\" (default): invalid parsing will be set to NaN\n* \"ignore\": invalid parsing will return the input\n* \"raise\": invalid parsing will raise an exception\n\nAfter cleaning, a **report** is printed that provides the following information:\n\n* How many values were cleaned (the value must have been transformed).\n* How many values could not be parsed.\n* A summary of the cleaned data: how many values are in the correct format, and how many values are NaN.\n \nThe following sections demonstrate the functionality of `clean_lat_long()` and `validate_lat_long()`. ",
"_____no_output_____"
],
[
"### An example dataset with geographic coordinates",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\ndf = pd.DataFrame({\n \"lat_long\":\n [(41.5, -81.0), \"41.5;-81.0\", \"41.5,-81.0\", \"41.5 -81.0\",\n \"41.5° N, 81.0° W\", \"41.5 S;81.0 E\", \"-41.5 S;81.0 E\",\n \"23 26m 22s N 23 27m 30s E\", \"23 26' 22\\\" N 23 27' 30\\\" E\",\n \"UT: N 39°20' 0'' / W 74°35' 0''\", \"hello\", np.nan, \"NULL\"]\n})\ndf",
"_____no_output_____"
]
],
[
[
"## 1. Default `clean_lat_long()`",
"_____no_output_____"
],
[
"By default, the `output_format` parameter is set to \"dd\" (decimal degrees) and the `errors` parameter is set to \"coerce\" (set to NaN when parsing is invalid).",
"_____no_output_____"
]
],
[
[
"from dataprep.clean import clean_lat_long\nclean_lat_long(df, \"lat_long\")",
"_____no_output_____"
]
],
[
[
"Note (41.5, -81.0) is considered not cleaned in the report since it's resulting format is the same as the input. Also, \"-41.5 S;81.0 E\" is invalid because if a coordinate has a hemisphere it cannot contain a negative decimal value.",
"_____no_output_____"
],
[
"## 2. Output formats\n\nThis section demonstrates the supported latitudinal and longitudinal formats.\n\n### decimal degrees hemisphere (ddh)",
"_____no_output_____"
]
],
[
[
"clean_lat_long(df, \"lat_long\", output_format=\"ddh\")",
"_____no_output_____"
]
],
[
[
"### degrees minutes (dm)",
"_____no_output_____"
]
],
[
[
"clean_lat_long(df, \"lat_long\", output_format=\"dm\")",
"_____no_output_____"
]
],
[
[
"### degrees minutes seconds (dms)",
"_____no_output_____"
]
],
[
[
"clean_lat_long(df, \"lat_long\", output_format=\"dms\")",
"_____no_output_____"
]
],
[
[
"## 3. `split` parameter\n\nThe split parameter adds individual columns containing the cleaned latitude and longitude values to the given DataFrame.",
"_____no_output_____"
]
],
[
[
"clean_lat_long(df, \"lat_long\", split=True)",
"_____no_output_____"
]
],
[
[
"Split can be used along with different output formats.",
"_____no_output_____"
]
],
[
[
"clean_lat_long(df, \"lat_long\", split=True, output_format=\"dm\")",
"_____no_output_____"
]
],
[
[
"## 4. `inplace` parameter\nThis just deletes the given column from the returned dataframe. \nA new column containing cleaned coordinates is added with a title in the format `\"{original title}_clean\"`.",
"_____no_output_____"
]
],
[
[
"clean_lat_long(df, \"lat_long\", inplace=True)",
"_____no_output_____"
]
],
[
[
"### `inplace` and `split`",
"_____no_output_____"
]
],
[
[
"clean_lat_long(df, \"lat_long\", split=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"## 5. Latitude and longitude coordinates in separate columns\n\n### Clean latitude or longitude coordinates individually",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({\"lat\": [\" 30′ 0″ E\", \"41° 30′ N\", \"41 S\", \"80\", \"hello\", \"NA\"]})\nclean_lat_long(df, lat_col=\"lat\")",
"_____no_output_____"
]
],
[
[
"### Combine and clean separate columns\n\nLatitude and longitude values are counted separately in the report.",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({\"lat\": [\"30° E\", \"41° 30′ N\", \"41 S\", \"80\", \"hello\", \"NA\"],\n \"long\": [\"30° E\", \"41° 30′ N\", \"41 W\", \"80\", \"hello\", \"NA\"]})\nclean_lat_long(df, lat_col=\"lat\", long_col=\"long\")",
"_____no_output_____"
]
],
[
[
"### Clean separate columns and split the output",
"_____no_output_____"
]
],
[
[
"clean_lat_long(df, lat_col=\"lat\", long_col=\"long\", split=True)",
"_____no_output_____"
]
],
[
[
"## 6. `validate_lat_long()` \n\n`validate_lat_long()` returns True when the input is a valid latitude or longitude value otherwise it returns False.\nValid types are the same as `clean_lat_long()`. ",
"_____no_output_____"
]
],
[
[
"from dataprep.clean import validate_lat_long\nprint(validate_lat_long(\"41° 30′ 0″ N\"))\nprint(validate_lat_long(\"41.5 S;81.0 E\"))\nprint(validate_lat_long(\"-41.5 S;81.0 E\"))\nprint(validate_lat_long((41.5, 81)))\nprint(validate_lat_long(41.5, lat_long=False, lat=True))",
"_____no_output_____"
],
[
"df = pd.DataFrame({\"lat_long\": \n [(41.5, -81.0), \"41.5;-81.0\", \"41.5,-81.0\", \"41.5 -81.0\", \n \"41.5° N, 81.0° W\", \"-41.5 S;81.0 E\", \n \"23 26m 22s N 23 27m 30s E\", \"23 26' 22\\\" N 23 27' 30\\\" E\", \n \"UT: N 39°20' 0'' / W 74°35' 0''\", \"hello\", np.nan, \"NULL\"]\n })\nvalidate_lat_long(df[\"lat_long\"])",
"_____no_output_____"
]
],
[
[
"### Validate only one coordinate",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({\"lat\": \n [41.5, \"41.5\", \"41.5 \", \n \"41.5° N\", \"-41.5 S\", \n \"23 26m 22s N\", \"23 26' 22\\\" N\", \n \"UT: N 39°20' 0''\", \"hello\", np.nan, \"NULL\"]\n })\nvalidate_lat_long(df[\"lat\"], lat_long=False, lat=True)",
"_____no_output_____"
]
]
] |
[
"raw",
"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"
] |
[
[
"raw",
"raw"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"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"
]
] |
4aad68e4d3ad8c86f4c9903c45ac1f79e2edc65d
| 18,128 |
ipynb
|
Jupyter Notebook
|
examples/3C279_spectrum.ipynb
|
cdcihub/oda_api_benchmark
|
247f171dec749ed779b5c50eb2c6a8768e8cb054
|
[
"MIT"
] | null | null | null |
examples/3C279_spectrum.ipynb
|
cdcihub/oda_api_benchmark
|
247f171dec749ed779b5c50eb2c6a8768e8cb054
|
[
"MIT"
] | 1 |
2020-04-27T14:46:58.000Z
|
2020-04-27T14:46:58.000Z
|
examples/3C279_spectrum.ipynb
|
oda-hub/oda_api_benchmark
|
247f171dec749ed779b5c50eb2c6a8768e8cb054
|
[
"MIT"
] | 1 |
2020-02-25T16:00:20.000Z
|
2020-02-25T16:00:20.000Z
| 28.729002 | 116 | 0.517818 |
[
[
[
"from oda_api.api import DispatcherAPI\nfrom oda_api.plot_tools import OdaImage,OdaLightCurve\nfrom oda_api.data_products import BinaryData\nimport os\nfrom astropy.io import fits\nimport numpy as np\nfrom numpy import sqrt\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"source_name='3C 279'\nra=194.046527\ndec=-5.789314\nradius=10.\nTstart='2003-03-15T00:00:00'\nTstop='2018-03-15T00:00:00'\nE1_keV=30.\nE2_keV=100.\nhost='www.astro.unige.ch/cdci/astrooda/dispatch-data'\nrebin=10 # minimal significance in energy bin, for spectral plotting",
"_____no_output_____"
],
[
"#try: input = raw_input\n#except NameError: pass\n#token=input() # token for restricted access server\n#cookies=dict(_oauth2_proxy=token)\n#disp=DispatcherAPI(host=host)",
"_____no_output_____"
],
[
"disp=DispatcherAPI(host=host)",
"_____no_output_____"
],
[
"import requests\nurl=\"https://www.astro.unige.ch/cdci/astrooda/dispatch-data/gw/timesystem/api/v1.0/scwlist/cons/\"\ndef queryxtime(**args):\n params=Tstart+'/'+Tstop+'?&ra='+str(ra)+'&dec='+str(dec)+'&radius='+str(radius)+'&min_good_isgri=1000'\n print(url+params)\n return requests.get(url+params).json()",
"_____no_output_____"
],
[
"scwlist=queryxtime()\nm=len(scwlist)\npointings_osa10=[]\npointings_osa11=[]\nfor i in range(m):\n if scwlist[i][-2:]=='10':\n if(int(scwlist[i][:4])<1626):\n pointings_osa10.append(scwlist[i]+'.001')\n else:\n pointings_osa11.append(scwlist[i]+'.001')\n#else:\n# pointings=np.genfromtxt('scws_3C279_isgri_10deg.txt', dtype='str')\nm_osa10=len(pointings_osa10)\nm_osa11=len(pointings_osa11)",
"_____no_output_____"
],
[
"def chunk_swc_list(lst, size):\n _l = [lst[x:x+size] for x in range(0, len (lst), size)]\n for ID,_ in enumerate(_l):\n _l[ID]=','.join(_)\n \n return _l",
"_____no_output_____"
],
[
"scw_lists_osa10=chunk_swc_list(pointings_osa10, 50)\nscw_lists_osa11=chunk_swc_list(pointings_osa11, 50)\n",
"_____no_output_____"
],
[
"data=disp.get_product(instrument='isgri',\n product='isgri_image',\n scw_list=scw_lists_osa10[0],\n E1_keV=E1_keV,\n E2_keV=E2_keV,\n osa_version='OSA10.2',\n RA=ra,\n DEC=dec,\n detection_threshold=3.5,\n product_type='Real')",
"_____no_output_____"
],
[
"data.dispatcher_catalog_1.table",
"_____no_output_____"
],
[
"FLAG=0\ntorm=[]\nfor ID,n in enumerate(data.dispatcher_catalog_1.table['src_names']):\n if(n[0:3]=='NEW'):\n torm.append(ID)\n if(n==source_name):\n FLAG=1\ndata.dispatcher_catalog_1.table.remove_rows(torm)\nnrows=len(data.dispatcher_catalog_1.table['src_names'])",
"_____no_output_____"
],
[
"if FLAG==0:\n data.dispatcher_catalog_1.table.add_row((0,'3C 279',0,ra,dec,0,2,0,0))\n",
"_____no_output_____"
],
[
"api_cat=data.dispatcher_catalog_1.get_api_dictionary()",
"_____no_output_____"
],
[
"spectrum_results=[]\nfor i in range(len(scw_lists_osa10)):\n print(i)\n data=disp.get_product(instrument='isgri',\n product='isgri_spectrum',\n scw_list=scw_lists_osa10[i],\n query_type='Real',\n osa_version='OSA10.2',\n RA=ra,\n DEC=dec,\n product_type='Real',\n selected_catalog=api_cat)\n spectrum_results.append(data)",
"_____no_output_____"
],
[
"d=spectrum_results[0]\nfor ID,s in enumerate(d._p_list):\n if (s.meta_data['src_name']==source_name):\n if(s.meta_data['product']=='isgri_spectrum'):\n ID_spec=ID\n if(s.meta_data['product']=='isgri_arf'):\n ID_arf=ID\n if(s.meta_data['product']=='isgri_rmf'):\n ID_rmf=ID\n\nprint(ID_spec, ID_arf, ID_rmf)\n ",
"_____no_output_____"
],
[
"d=spectrum_results[0]\nspec=d._p_list[ID_spec].data_unit[1].data\narf=d._p_list[ID_arf].data_unit[1].data\nrmf=d._p_list[ID_rmf].data_unit[2].data\nch=spec['CHANNEL']\nrate=spec['RATE']*0.\nerr=spec['STAT_ERR']*0.\nsyst=spec['SYS_ERR']*0.\nrate.fill(0)\nerr.fill(0)\nsyst.fill(0)\nqual=spec['QUALITY']\nmatrix=rmf['MATRIX']*0.\nspecresp=arf['SPECRESP']*0.\ntot_expos=0.\ncorr_expos=np.zeros(len(rate))\nprint(len(rate))\nfor k in range(len(scw_lists_osa10)):\n d=spectrum_results[k]\n spec=d._p_list[ID_spec].data_unit[1].data\n arf=d._p_list[ID_arf].data_unit[1].data\n rmf=d._p_list[ID_rmf].data_unit[2].data\n expos=d._p_list[0].data_unit[1].header['EXPOSURE']\n tot_expos=tot_expos+expos\n print(k,expos)\n for j in range(len(rate)):\n if(spec['QUALITY'][j]==0): \n rate[j]=rate[j]+spec['RATE'][j]/(spec['STAT_ERR'][j])**2\n err[j]=err[j]+1./(spec['STAT_ERR'][j])**2\n syst[j]=syst[j]+(spec['SYS_ERR'][j])**2*expos\n corr_expos[j]=corr_expos[j]+expos\n matrix=matrix+rmf['MATRIX']*expos\n specresp=specresp+arf['SPECRESP']*expos\n\nfor i in range(len(rate)):\n if err[i]>0.:\n rate[i]=rate[i]/err[i]\n err[i]=1./sqrt(err[i])\nmatrix=matrix/tot_expos\nspecresp=specresp/tot_expos\nsyst=sqrt(syst/(corr_expos+1.))\nprint('Total exposure:',tot_expos)",
"_____no_output_____"
],
[
"print(rate)\nprint(err)",
"_____no_output_____"
],
[
"d._p_list[ID_spec].data_unit[1].data['RATE']=rate\nd._p_list[ID_spec].data_unit[1].data['STAT_ERR']=err\nd._p_list[ID_rmf].data_unit[2].data['MATRIX']=matrix\nd._p_list[ID_arf].data_unit[1].data['SPECRESP']=specresp",
"_____no_output_____"
],
[
"name=source_name.replace(\" \", \"\")\nspecname=name+'_spectrum_osa10.fits'\narfname=name+'_arf_osa10.fits.gz'\nrmfname=name+'_rmf_osa10.fits.gz'\ndata._p_list[ID_spec].write_fits_file(specname)\ndata._p_list[ID_arf].write_fits_file(arfname)\ndata._p_list[ID_rmf].write_fits_file(rmfname)",
"_____no_output_____"
],
[
"hdul = fits.open(specname, mode='update')\nhdr=hdul[1].header\nhdr.set('EXPOSURE', tot_expos)\nhdul.close()",
"_____no_output_____"
],
[
"!./spectrum_fit_osa10.sh $name $rebin",
"_____no_output_____"
],
[
"spectrum_results1=[]\nfor i in range(len(scw_lists_osa11)):\n print(i)\n data=disp.get_product(instrument='isgri',\n product='isgri_spectrum',\n scw_list=scw_lists_osa11[i],\n query_type='Real',\n osa_version='OSA11.0',\n RA=ra,\n DEC=dec,\n product_type='Real',\n selected_catalog=api_cat)\n spectrum_results1.append(data)",
"_____no_output_____"
],
[
"d=spectrum_results1[0]\nfor ID,s in enumerate(d._p_list):\n if (s.meta_data['src_name']==source_name):\n if(s.meta_data['product']=='isgri_spectrum'):\n ID_spec=ID\n if(s.meta_data['product']=='isgri_arf'):\n ID_arf=ID\n if(s.meta_data['product']=='isgri_rmf'):\n ID_rmf=ID\n\nprint(ID_spec, ID_arf, ID_rmf)\n\n",
"_____no_output_____"
],
[
"d=spectrum_results1[0]\nspec=d._p_list[ID_spec].data_unit[1].data\narf=d._p_list[ID_arf].data_unit[1].data\nrmf=d._p_list[ID_rmf].data_unit[2].data\nch=spec['CHANNEL']\nrate=spec['RATE']*0.\nerr=spec['STAT_ERR']*0.\nsyst=spec['SYS_ERR']*0.\nrate.fill(0)\nerr.fill(0)\nsyst.fill(0)\nqual=spec['QUALITY']\nmatrix=rmf['MATRIX']*0.\nspecresp=arf['SPECRESP']*0.\ntot_expos=0.\ncorr_expos=np.zeros(len(rate))\nprint(len(rate))\nfor k in range(len(scw_lists_osa11)):\n d=spectrum_results1[k]\n spec=d._p_list[ID_spec].data_unit[1].data\n arf=d._p_list[ID_arf].data_unit[1].data\n rmf=d._p_list[ID_rmf].data_unit[2].data\n expos=d._p_list[0].data_unit[1].header['EXPOSURE']\n tot_expos=tot_expos+expos\n print(k,expos)\n for j in range(len(rate)):\n if(spec['QUALITY'][j]==0): \n rate[j]=rate[j]+spec['RATE'][j]/(spec['STAT_ERR'][j])**2\n err[j]=err[j]+1./(spec['STAT_ERR'][j])**2\n syst[j]=syst[j]+(spec['SYS_ERR'][j])**2*expos\n corr_expos[j]=corr_expos[j]+expos\n matrix=matrix+rmf['MATRIX']*expos\n specresp=specresp+arf['SPECRESP']*expos\n\nfor i in range(len(rate)):\n if err[i]>0.:\n rate[i]=rate[i]/err[i]\n err[i]=1./sqrt(err[i])\nmatrix=matrix/tot_expos\nspecresp=specresp/tot_expos\nsyst=sqrt(syst/(corr_expos+1.))\nprint('Total exposure:',tot_expos)",
"_____no_output_____"
],
[
"d._p_list[ID_spec].data_unit[1].data['RATE']=rate\nd._p_list[ID_spec].data_unit[1].data['STAT_ERR']=err\nd._p_list[ID_rmf].data_unit[2].data['MATRIX']=matrix\nd._p_list[ID_arf].data_unit[1].data['SPECRESP']=specresp",
"_____no_output_____"
],
[
"name=source_name.replace(\" \", \"\")\nspecname=name+'_spectrum_osa11.fits'\narfname=name+'_arf_osa11.fits.gz'\nrmfname=name+'_rmf_osa11.fits.gz'\ndata._p_list[ID_spec].write_fits_file(specname)\ndata._p_list[ID_arf].write_fits_file(arfname)\ndata._p_list[ID_rmf].write_fits_file(rmfname)",
"_____no_output_____"
],
[
"hdul = fits.open(specname, mode='update')\nhdr=hdul[1].header\nhdr.set('EXPOSURE', tot_expos)\nhdul.close()",
"_____no_output_____"
],
[
"!./spectrum_fit_osa11.sh $name $rebin",
"_____no_output_____"
],
[
"data=disp.get_product(instrument='isgri',\n product='isgri_spectrum',\n T1='2015-06-15T15:56:45',\n T2='2015-06-16T06:13:10',\n query_type='Real',\n osa_version='OSA10.2',\n RA=ra,\n DEC=dec,\n #detection_threshold=5.0,\n radius=15.,\n product_type='Real',\n selected_catalog=api_cat)",
"_____no_output_____"
],
[
"data._p_list[0].write_fits_file(name+'_flare_spectrum_osa10.fits')\ndata._p_list[1].write_fits_file(name+'_flare_arf_osa10.fits.gz')\ndata._p_list[2].write_fits_file(name+'_flare_rmf_osa10.fits.gz')",
"_____no_output_____"
],
[
"name1=name+'_flare'\n!./spectrum_fit_osa10.sh $name1 5",
"_____no_output_____"
],
[
"golden_ratio=0.5*(1.+np.sqrt(5))\nwidth=4.\nplt.figure(figsize=(golden_ratio*width,width))\nalpha=1\nlinewidth=4\nfontsize=11\n\nspectrum=np.genfromtxt(name+'_spectrum_osa10.txt',skip_header=3)\nen=spectrum[:,0]\nen_err=spectrum[:,1]\nfl=spectrum[:,2]\nfl_err=spectrum[:,3]\nmo=spectrum[:,4]\nplt.errorbar(en,fl,xerr=en_err,yerr=fl_err,linestyle='none',linewidth=linewidth,color='black',alpha=alpha, \n label='Average')\nplt.plot(en,mo,color='black',linewidth=linewidth/2)\n\n\nspectrum=np.genfromtxt(name+'_flare_spectrum_osa10.txt',skip_header=3)\nen=spectrum[:,0]\nen_err=spectrum[:,1]\nfl=spectrum[:,2]\nfl_err=spectrum[:,3]\nmo=spectrum[:,4]\nuplims=fl<0\n\nfl[uplims]=3*fl_err[uplims]\nfl_err[uplims] = fl[uplims]/3.\n\nplt.errorbar(en,fl,xerr=en_err,yerr=fl_err,linestyle='none',linewidth=linewidth,color='blue',alpha=alpha, \n label='Flare', uplims=uplims)\nplt.plot(en,mo,color='blue',linewidth=linewidth/2,alpha=alpha)\n\n\nplt.tick_params(axis='both', which='major', labelsize=fontsize)\nplt.tick_params(axis='both', which='minor', labelsize=fontsize)\nplt.tick_params(axis='x', which='minor', length=4)\nplt.xscale('log')\nplt.yscale('log')\nplt.ylim(2.e-3,0.2)\nplt.xlim(18,110)\nplt.xlabel('$E$ [keV]',fontsize=fontsize)\nplt.ylabel('$E^2F_E$ [keV$\\,$cm$^{-2}\\,\\mathrm{s}^{-1}$]',fontsize=fontsize)\nplt.title('3c 273')\nplt.legend()\n\nfrom matplotlib.ticker import ScalarFormatter\n\nmy_formatter=ScalarFormatter()\nmy_formatter.set_scientific(False)\n\n\nax=plt.gca()\n\nax.get_xaxis().set_major_formatter(my_formatter)\nax.get_xaxis().set_minor_formatter(my_formatter)\n\n\nplt.savefig(name+'_spectra.pdf',format='pdf',dpi=100)\n\n\n",
"_____no_output_____"
],
[
"dir(default_formatter)",
"_____no_output_____"
],
[
"spectrum_3C279=name+'_spectra.pdf'",
"_____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"
]
] |
4aad718bcbdf37d040a575478dcbdb63d4515d83
| 363,594 |
ipynb
|
Jupyter Notebook
|
notebooks/MTBLS315/exploratory/Old_notebooks/MTBLS315_uhplc_pos_classifer-25ppm.ipynb
|
irockafe/metabolomics_processing
|
89e9f46300e8edf81989bf73958bb508a1552211
|
[
"MIT"
] | 1 |
2018-04-26T22:12:32.000Z
|
2018-04-26T22:12:32.000Z
|
notebooks/MTBLS315/exploratory/Old_notebooks/MTBLS315_uhplc_pos_classifer-25ppm.ipynb
|
irockafe/revo_healthcare
|
89e9f46300e8edf81989bf73958bb508a1552211
|
[
"MIT"
] | null | null | null |
notebooks/MTBLS315/exploratory/Old_notebooks/MTBLS315_uhplc_pos_classifer-25ppm.ipynb
|
irockafe/revo_healthcare
|
89e9f46300e8edf81989bf73958bb508a1552211
|
[
"MIT"
] | 1 |
2019-08-24T10:52:38.000Z
|
2019-08-24T10:52:38.000Z
| 229.541667 | 28,604 | 0.886588 |
[
[
[
"<h2> 25ppm - somehow more features detected than at 4ppm... I guess because more likely to pass over the #scans needed to define a feature </h2>\nEnough retcor groups, loads of peak insertion problem (1000's). Does that mean data isn't centroided...?",
"_____no_output_____"
]
],
[
[
"import time\n\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn import preprocessing\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.cross_validation import StratifiedShuffleSplit\nfrom sklearn.cross_validation import cross_val_score\n#from sklearn.model_selection import StratifiedShuffleSplit\n#from sklearn.model_selection import cross_val_score\n\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.utils import shuffle\n\nfrom scipy import interp\n\n%matplotlib inline",
"_____no_output_____"
],
[
"def remove_zero_columns(X, threshold=1e-20):\n # convert zeros to nan, drop all nan columns, the replace leftover nan with zeros\n X_non_zero_colum = X.replace(0, np.nan).dropna(how='all', axis=1).replace(np.nan, 0)\n #.dropna(how='all', axis=0).replace(np.nan,0)\n return X_non_zero_colum\n\ndef zero_fill_half_min(X, threshold=1e-20):\n # Fill zeros with 1/2 the minimum value of that column\n # input dataframe. Add only to zero values\n \n # Get a vector of 1/2 minimum values\n half_min = X[X > threshold].min(axis=0)*0.5\n \n # Add the half_min values to a dataframe where everything that isn't zero is NaN.\n # then convert NaN's to 0\n fill_vals = (X[X < threshold] + half_min).fillna(value=0)\n \n # Add the original dataframe to the dataframe of zeros and fill-values\n X_zeros_filled = X + fill_vals\n return X_zeros_filled\n\n\n\ntoy = pd.DataFrame([[1,2,3,0],\n [0,0,0,0],\n [0.5,1,0,0]], dtype=float)\n\ntoy_no_zeros = remove_zero_columns(toy)\ntoy_filled_zeros = zero_fill_half_min(toy_no_zeros)\nprint toy\nprint toy_no_zeros\nprint toy_filled_zeros",
" 0 1 2 3\n0 1.0 2 3 0\n1 0.0 0 0 0\n2 0.5 1 0 0\n 0 1 2\n0 1.0 2 3\n1 0.0 0 0\n2 0.5 1 0\n 0 1 2\n0 1.00 2.0 3.0\n1 0.25 0.5 1.5\n2 0.50 1.0 1.5\n"
]
],
[
[
"<h2> Import the dataframe and remove any features that are all zero </h2>",
"_____no_output_____"
]
],
[
[
"### Subdivide the data into a feature table\ndata_path = '/home/irockafe/Dropbox (MIT)/Alm_Lab/projects/revo_healthcare/data/processed/MTBLS315/'\\\n'uhplc_pos/xcms_result_25.csv'\n## Import the data and remove extraneous columns\ndf = pd.read_csv(data_path, index_col=0)\ndf.shape\ndf.head()\n# Make a new index of mz:rt\nmz = df.loc[:,\"mz\"].astype('str')\nrt = df.loc[:,\"rt\"].astype('str')\nidx = mz+':'+rt\ndf.index = idx\ndf\n# separate samples from xcms/camera things to make feature table\nnot_samples = ['mz', 'mzmin', 'mzmax', 'rt', 'rtmin', 'rtmax', \n 'npeaks', 'uhplc_pos', \n ]\nsamples_list = df.columns.difference(not_samples)\nmz_rt_df = df[not_samples]\n\n# convert to samples x features\nX_df_raw = df[samples_list].T\n# Remove zero-full columns and fill zeroes with 1/2 minimum values\nX_df = remove_zero_columns(X_df_raw)\nX_df_zero_filled = zero_fill_half_min(X_df)\n\nprint \"original shape: %s \\n# zeros: %f\\n\" % (X_df_raw.shape, (X_df_raw < 1e-20).sum().sum())\nprint \"zero-columns repalced? shape: %s \\n# zeros: %f\\n\" % (X_df.shape, \n (X_df < 1e-20).sum().sum())\nprint \"zeros filled shape: %s \\n#zeros: %f\\n\" % (X_df_zero_filled.shape, \n (X_df_zero_filled < 1e-20).sum().sum())\n\n\n# Convert to numpy matrix to play nicely with sklearn\nX = X_df.as_matrix()\nprint X.shape\n",
"original shape: (61, 8251) \n# zeros: 3776.000000\n\nzero-columns repalced? shape: (61, 8251) \n# zeros: 3776.000000\n\nzeros filled shape: (61, 8251) \n#zeros: 0.000000\n\n(61, 8251)\n"
]
],
[
[
"<h2> Get mappings between sample names, file names, and sample classes </h2>",
"_____no_output_____"
]
],
[
[
"# Get mapping between sample name and assay names\npath_sample_name_map = '/home/irockafe/Dropbox (MIT)/Alm_Lab/projects/revo_healthcare/data/raw/'\\\n 'MTBLS315/metadata/a_UPLC_POS_nmfi_and_bsi_diagnosis.txt'\n# Index is the sample name\nsample_df = pd.read_csv(path_sample_name_map, \n sep='\\t', index_col=0)\nsample_df = sample_df['MS Assay Name']\nsample_df.shape\nprint sample_df.head(10)\n\n# get mapping between sample name and sample class\npath_sample_class_map = '/home/irockafe/Dropbox (MIT)/Alm_Lab/projects/revo_healthcare/data/raw/'\\\n 'MTBLS315/metadata/s_NMFI and BSI diagnosis.txt'\nclass_df = pd.read_csv(path_sample_class_map,\n sep='\\t')\n# Set index as sample name\nclass_df.set_index('Sample Name', inplace=True)\nclass_df = class_df['Factor Value[patient group]']\nprint class_df.head(10)\n\n# convert all non-malarial classes into a single classes \n# (collapse non-malarial febril illness and bacteremia together)\nclass_map_df = pd.concat([sample_df, class_df], axis=1)\nclass_map_df.rename(columns={'Factor Value[patient group]': 'class'}, inplace=True)\nclass_map_df\n\nbinary_class_map = class_map_df.replace(to_replace=['non-malarial febrile illness', 'bacterial bloodstream infection' ], \n value='non-malarial fever')\n\nbinary_class_map\n",
"Sample Name\nMCMA429 1001_P\nMCMA430 1002_P\nMCMA431 1003_P\nMCMA433 1004_P\nMCMA434 1005_P\nMCMA435 1006_P\nMCMA436 1007_P\nMCMA442 1009_P\nMCMA443 1010_P\nMCMA444 1011_P\nName: MS Assay Name, dtype: object\nSample Name\nMCMA429 malaria\nMCMA430 malaria\nMCMA431 malaria\nMCMA433 malaria\nMCMA434 non-malarial febrile illness\nMCMA435 malaria\nMCMA436 bacterial bloodstream infection\nMCMA442 malaria\nMCMA443 non-malarial febrile illness\nMCMA444 bacterial bloodstream infection\nName: Factor Value[patient group], dtype: object\n"
],
[
"# convert classes to numbers\nle = preprocessing.LabelEncoder()\nle.fit(binary_class_map['class'])\ny = le.transform(binary_class_map['class'])",
"_____no_output_____"
]
],
[
[
"<h2> Plot the distribution of classification accuracy across multiple cross-validation splits - Kinda Dumb</h2>\nTurns out doing this is kind of dumb, because you're not taking into account the prediction score your classifier assigned. Use AUC's instead. You want to give your classifier a lower score if it is really confident and wrong, than vice-versa",
"_____no_output_____"
]
],
[
[
"def rf_violinplot(X, y, n_iter=25, test_size=0.3, random_state=1,\n n_estimators=1000):\n cross_val_skf = StratifiedShuffleSplit(y, n_iter=n_iter, test_size=test_size, \n random_state=random_state)\n clf = RandomForestClassifier(n_estimators=n_estimators, random_state=random_state)\n\n scores = cross_val_score(clf, X, y, cv=cross_val_skf)\n\n sns.violinplot(scores,inner='stick')\n\nrf_violinplot(X,y)\n\n\n# TODO - Switch to using caret for this bs..?",
"_____no_output_____"
],
[
"# Do multi-fold cross validation for adaboost classifier\ndef adaboost_violinplot(X, y, n_iter=25, test_size=0.3, random_state=1,\n n_estimators=200):\n cross_val_skf = StratifiedShuffleSplit(y, n_iter=n_iter, test_size=test_size, random_state=random_state)\n clf = AdaBoostClassifier(n_estimators=n_estimators, random_state=random_state)\n\n scores = cross_val_score(clf, X, y, cv=cross_val_skf)\n\n sns.violinplot(scores,inner='stick')\n\nadaboost_violinplot(X,y)",
"_____no_output_____"
],
[
"# TODO PQN normalization, and log-transformation, \n# and some feature selection (above certain threshold of intensity, use principal components), et\n\ndef pqn_normalize(X, integral_first=False, plot=False):\n '''\n Take a feature table and run PQN normalization on it\n '''\n # normalize by sum of intensities in each sample first. Not necessary\n if integral_first: \n sample_sums = np.sum(X, axis=1)\n X = (X / sample_sums[:,np.newaxis])\n \n # Get the median value of each feature across all samples\n mean_intensities = np.median(X, axis=0)\n \n # Divde each feature by the median value of each feature - \n # these are the quotients for each feature\n X_quotients = (X / mean_intensities[np.newaxis,:])\n \n if plot: # plot the distribution of quotients from one sample\n for i in range(1,len(X_quotients[:,1])):\n print 'allquotients reshaped!\\n\\n', \n #all_quotients = X_quotients.reshape(np.prod(X_quotients.shape))\n all_quotients = X_quotients[i,:]\n print all_quotients.shape\n x = np.random.normal(loc=0, scale=1, size=len(all_quotients))\n sns.violinplot(all_quotients)\n plt.title(\"median val: %f\\nMax val=%f\" % (np.median(all_quotients), np.max(all_quotients)))\n plt.plot( title=\"median val: \")#%f\" % np.median(all_quotients))\n plt.xlim([-0.5, 5])\n plt.show()\n\n # Define a quotient for each sample as the median of the feature-specific quotients\n # in that sample\n sample_quotients = np.median(X_quotients, axis=1)\n \n # Quotient normalize each samples\n X_pqn = X / sample_quotients[:,np.newaxis]\n return X_pqn\n\n# Make a fake sample, with 2 samples at 1x and 2x dilutions\nX_toy = np.array([[1,1,1,],\n [2,2,2],\n [3,6,9],\n [6,12,18]], dtype=float)\nprint X_toy\nprint X_toy.reshape(1, np.prod(X_toy.shape))\nX_toy_pqn_int = pqn_normalize(X_toy, integral_first=True, plot=True)\nprint X_toy_pqn_int\n\nprint '\\n\\n\\n'\nX_toy_pqn = pqn_normalize(X_toy)\nprint X_toy_pqn",
"[[ 1. 1. 1.]\n [ 2. 2. 2.]\n [ 3. 6. 9.]\n [ 6. 12. 18.]]\n[[ 1. 1. 1. 2. 2. 2. 3. 6. 9. 6. 12. 18.]]\nallquotients reshaped!\n\n(3,)\n"
]
],
[
[
"<h2> pqn normalize your features </h2>",
"_____no_output_____"
]
],
[
[
"X_pqn = pqn_normalize(X)\nprint X_pqn",
"[[ 1.90714948e+06 4.50971700e+05 1.77251670e+06 ..., 7.01523080e+04\n 1.59665775e+04 2.60539246e+04]\n [ 2.90510843e+06 2.35933456e+06 1.39599535e+06 ..., 4.52878467e+04\n 0.00000000e+00 2.25724268e+04]\n [ 1.72777105e+06 2.34533034e+06 1.55577636e+06 ..., 6.60170423e+05\n 1.60019559e+05 6.26021971e+03]\n ..., \n [ 2.18709477e+06 8.02039860e+06 6.12752972e+06 ..., 9.99091402e+05\n 1.93928066e+05 3.68432997e+04]\n [ 1.45538324e+06 4.00769617e+06 1.73976995e+06 ..., 7.09299774e+05\n 1.44120237e+05 2.41003576e+04]\n [ 1.79091715e+06 1.93288632e+06 3.20415148e+06 ..., 2.14220107e+06\n 4.34123656e+05 3.85410930e+04]]\n"
]
],
[
[
"<h2>Random Forest & adaBoost with PQN-normalized data</h2>",
"_____no_output_____"
]
],
[
[
"rf_violinplot(X_pqn, y)",
"_____no_output_____"
],
[
"# Do multi-fold cross validation for adaboost classifier\nadaboost_violinplot(X_pqn, y)",
"_____no_output_____"
]
],
[
[
"<h2> RF & adaBoost with PQN-normalized, log-transformed data </h2>\nTurns out a monotonic transformation doesn't really affect any of these things. \nI guess they're already close to unit varinace...?",
"_____no_output_____"
]
],
[
[
"X_pqn_nlog = np.log(X_pqn)\nrf_violinplot(X_pqn_nlog, y)",
"_____no_output_____"
],
[
"adaboost_violinplot(X_pqn_nlog, y)",
"_____no_output_____"
],
[
"def roc_curve_cv(X, y, clf, cross_val,\n path='/home/irockafe/Desktop/roc.pdf',\n save=False, plot=True): \n t1 = time.time()\n # collect vals for the ROC curves\n tpr_list = []\n mean_fpr = np.linspace(0,1,100)\n auc_list = []\n \n # Get the false-positive and true-positive rate\n for i, (train, test) in enumerate(cross_val):\n clf.fit(X[train], y[train])\n y_pred = clf.predict_proba(X[test])[:,1]\n \n # get fpr, tpr\n fpr, tpr, thresholds = roc_curve(y[test], y_pred)\n roc_auc = auc(fpr, tpr)\n #print 'AUC', roc_auc\n #sns.plt.plot(fpr, tpr, lw=10, alpha=0.6, label='ROC - AUC = %0.2f' % roc_auc,)\n #sns.plt.show()\n tpr_list.append(interp(mean_fpr, fpr, tpr))\n tpr_list[-1][0] = 0.0\n auc_list.append(roc_auc)\n \n if (i % 10 == 0):\n print '{perc}% done! {time}s elapsed'.format(perc=100*float(i)/cross_val.n_iter, time=(time.time() - t1))\n \n \n \n \n # get mean tpr and fpr\n mean_tpr = np.mean(tpr_list, axis=0)\n # make sure it ends up at 1.0\n mean_tpr[-1] = 1.0\n mean_auc = auc(mean_fpr, mean_tpr)\n std_auc = np.std(auc_list)\n \n if plot:\n # plot mean auc\n plt.plot(mean_fpr, mean_tpr, label='Mean ROC - AUC = %0.2f $\\pm$ %0.2f' % (mean_auc, \n std_auc),\n lw=5, color='b')\n\n # plot luck-line\n plt.plot([0,1], [0,1], linestyle = '--', lw=2, color='r',\n label='Luck', alpha=0.5) \n\n # plot 1-std\n std_tpr = np.std(tpr_list, axis=0)\n tprs_upper = np.minimum(mean_tpr + std_tpr, 1)\n tprs_lower = np.maximum(mean_tpr - std_tpr, 0)\n plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=0.2,\n label=r'$\\pm$ 1 stdev')\n\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve, {iters} iterations of {cv} cross validation'.format(\n iters=cross_val.n_iter, cv='{train}:{test}'.format(test=cross_val.test_size, train=(1-cross_val.test_size)))\n )\n plt.legend(loc=\"lower right\")\n\n if save:\n plt.savefig(path, format='pdf')\n\n\n plt.show()\n return tpr_list, auc_list, mean_fpr",
"_____no_output_____"
],
[
"\n\nrf_estimators = 1000\nn_iter = 3\ntest_size = 0.3\nrandom_state = 1\ncross_val_rf = StratifiedShuffleSplit(y, n_iter=n_iter, test_size=test_size, random_state=random_state)\nclf_rf = RandomForestClassifier(n_estimators=rf_estimators, random_state=random_state)\nrf_graph_path = '''/home/irockafe/Dropbox (MIT)/Alm_Lab/projects/revolutionizing_healthcare/data/MTBLS315/\\\nisaac_feature_tables/uhplc_pos/rf_roc_{trees}trees_{cv}cviter.pdf'''.format(trees=rf_estimators, cv=n_iter)\n\nprint cross_val_rf.n_iter\nprint cross_val_rf.test_size\n\ntpr_vals, auc_vals, mean_fpr = roc_curve_cv(X_pqn, y, clf_rf, cross_val_rf,\n path=rf_graph_path, save=False)",
"3\n0.3\n0.0% done! 2.13228392601s elapsed\n"
],
[
"# For adaboosted\nn_iter = 3\ntest_size = 0.3\nrandom_state = 1\nadaboost_estimators = 200\nadaboost_path = '''/home/irockafe/Dropbox (MIT)/Alm_Lab/projects/revolutionizing_healthcare/data/MTBLS315/\\\nisaac_feature_tables/uhplc_pos/adaboost_roc_{trees}trees_{cv}cviter.pdf'''.format(trees=adaboost_estimators, \n cv=n_iter)\n\n\ncross_val_adaboost = StratifiedShuffleSplit(y, n_iter=n_iter, test_size=test_size, random_state=random_state)\nclf = AdaBoostClassifier(n_estimators=adaboost_estimators, random_state=random_state)\nadaboost_tpr, adaboost_auc, adaboost_fpr = roc_curve_cv(X_pqn, y, clf, cross_val_adaboost,\n path=adaboost_path)",
"0.0% done! 5.44429588318s elapsed\n"
]
],
[
[
"<h2> Great, you can classify things. But make null models and do a sanity check to make \nsure you arent just classifying garbage </h2>",
"_____no_output_____"
]
],
[
[
"# Make a null model AUC curve\n\ndef make_null_model(X, y, clf, cross_val, random_state=1, num_shuffles=5, plot=True):\n '''\n Runs the true model, then sanity-checks by:\n \n Shuffles class labels and then builds cross-validated ROC curves from them.\n Compares true AUC vs. shuffled auc by t-test (assumes normality of AUC curve)\n '''\n null_aucs = []\n print y.shape\n print X.shape\n tpr_true, auc_true, fpr_true = roc_curve_cv(X, y, clf, cross_val)\n # shuffle y lots of times\n for i in range(0, num_shuffles):\n #Iterate through the shuffled y vals and repeat with appropriate params\n # Retain the auc vals for final plotting of distribution\n y_shuffle = shuffle(y)\n cross_val.y = y_shuffle\n cross_val.y_indices = y_shuffle\n print 'Number of differences b/t original and shuffle: %s' % (y == cross_val.y).sum()\n # Get auc values for number of iterations\n tpr, auc, fpr = roc_curve_cv(X, y_shuffle, clf, cross_val, plot=False)\n \n null_aucs.append(auc)\n \n \n #plot the outcome\n if plot:\n flattened_aucs = [j for i in null_aucs for j in i]\n my_dict = {'true_auc': auc_true, 'null_auc': flattened_aucs}\n df_poop = pd.DataFrame.from_dict(my_dict, orient='index').T\n df_tidy = pd.melt(df_poop, value_vars=['true_auc', 'null_auc'],\n value_name='auc', var_name='AUC_type')\n #print flattened_aucs\n sns.violinplot(x='AUC_type', y='auc',\n inner='points', data=df_tidy)\n # Plot distribution of AUC vals \n plt.title(\"Distribution of aucs\")\n #sns.plt.ylabel('count')\n plt.xlabel('AUC')\n #sns.plt.plot(auc_true, 0, color='red', markersize=10)\n plt.show()\n # Do a quick t-test to see if odds of randomly getting an AUC that good\n return auc_true, null_aucs\n",
"_____no_output_____"
],
[
"# Make a null model AUC curve & compare it to null-model\n\n# Random forest magic!\nrf_estimators = 1000\nn_iter = 50\ntest_size = 0.3\nrandom_state = 1\ncross_val_rf = StratifiedShuffleSplit(y, n_iter=n_iter, test_size=test_size, random_state=random_state)\nclf_rf = RandomForestClassifier(n_estimators=rf_estimators, random_state=random_state)\n\ntrue_auc, all_aucs = make_null_model(X_pqn, y, clf_rf, cross_val_rf, num_shuffles=5)",
"(61,)\n(61, 8251)\n0.0% done! 2.26181292534s elapsed\n20.0% done! 28.7397949696s elapsed\n40.0% done! 51.4000668526s elapsed\n60.0% done! 72.5403568745s elapsed\n80.0% done! 93.4041440487s elapsed\n"
],
[
"# make dataframe from true and false aucs\nflattened_aucs = [j for i in all_aucs for j in i]\nmy_dict = {'true_auc': true_auc, 'null_auc': flattened_aucs}\ndf_poop = pd.DataFrame.from_dict(my_dict, orient='index').T\ndf_tidy = pd.melt(df_poop, value_vars=['true_auc', 'null_auc'],\n value_name='auc', var_name='AUC_type')\nprint df_tidy.head()\n#print flattened_aucs\nsns.violinplot(x='AUC_type', y='auc',\n inner='points', data=df_tidy, bw=0.7)\nplt.show()\n\n",
" AUC_type auc\n0 true_auc 0.886364\n1 true_auc 0.965909\n2 true_auc 0.704545\n3 true_auc 0.772727\n4 true_auc 0.909091\n"
]
],
[
[
"<h2> Let's check out some PCA plots </h2>",
"_____no_output_____"
]
],
[
[
"from sklearn.decomposition import PCA\n\n# Check PCA of things\ndef PCA_plot(X, y, n_components, plot_color, class_nums, class_names, title='PCA'):\n pca = PCA(n_components=n_components)\n X_pca = pca.fit(X).transform(X)\n\n print zip(plot_color, class_nums, class_names)\n for color, i, target_name in zip(plot_color, class_nums, class_names):\n \n # plot one class at a time, first plot all classes y == 0\n #print color\n #print y == i\n xvals = X_pca[y == i, 0]\n print xvals.shape\n yvals = X_pca[y == i, 1]\n plt.scatter(xvals, yvals, color=color, alpha=0.8, label=target_name)\n\n plt.legend(bbox_to_anchor=(1.01,1), loc='upper left', shadow=False)#, scatterpoints=1)\n plt.title('PCA of Malaria data')\n plt.show()\n\n\nPCA_plot(X_pqn, y, 2, ['red', 'blue'], [0,1], ['malaria', 'non-malaria fever'])\nPCA_plot(X, y, 2, ['red', 'blue'], [0,1], ['malaria', 'non-malaria fever'])",
"[('red', 0, 'malaria'), ('blue', 1, 'non-malaria fever')]\n(34,)\n(27,)\n"
]
],
[
[
"<h2> What about with all thre classes? </h2>",
"_____no_output_____"
]
],
[
[
"# convert classes to numbers\nle = preprocessing.LabelEncoder()\nle.fit(class_map_df['class'])\ny_three_class = le.transform(class_map_df['class'])\nprint class_map_df.head(10)\nprint y_three_class\nprint X.shape\nprint y_three_class.shape\n\ny_labels = np.sort(class_map_df['class'].unique())\nprint y_labels\ncolors = ['green', 'red', 'blue']\n\nprint np.unique(y_three_class)\nPCA_plot(X_pqn, y_three_class, 2, colors, np.unique(y_three_class), y_labels)\nPCA_plot(X, y_three_class, 2, colors, np.unique(y_three_class), y_labels)\n",
" MS Assay Name class\nSample Name \nMCMA429 1001_P malaria\nMCMA430 1002_P malaria\nMCMA431 1003_P malaria\nMCMA433 1004_P malaria\nMCMA434 1005_P non-malarial febrile illness\nMCMA435 1006_P malaria\nMCMA436 1007_P bacterial bloodstream infection\nMCMA442 1009_P malaria\nMCMA443 1010_P non-malarial febrile illness\nMCMA444 1011_P bacterial bloodstream infection\n[1 1 1 1 2 1 0 1 2 0 0 1 1 1 1 1 0 2 2 2 2 0 1 1 1 1 2 0 2 1 2 1 1 1 1 1 1\n 2 1 0 1 1 0 0 1 2 0 2 2 1 0 1 1 2 0 2 1 1 1 1 1]\n(61, 8251)\n(61,)\n['bacterial bloodstream infection' 'malaria' 'non-malarial febrile illness']\n[0 1 2]\n[('green', 0, 'bacterial bloodstream infection'), ('red', 1, 'malaria'), ('blue', 2, 'non-malarial febrile illness')]\n(12,)\n(34,)\n(15,)\n"
]
]
] |
[
"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"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aad73ca45bf192bdaa7289addf8da1ac4199745
| 277,324 |
ipynb
|
Jupyter Notebook
|
m03_v01_store_sales_prediction.ipynb
|
tamsmchado/DataScience_Em_Producao
|
a84e2fd04834b4eba039a266f9e21faca8b9db7a
|
[
"MIT"
] | null | null | null |
m03_v01_store_sales_prediction.ipynb
|
tamsmchado/DataScience_Em_Producao
|
a84e2fd04834b4eba039a266f9e21faca8b9db7a
|
[
"MIT"
] | null | null | null |
m03_v01_store_sales_prediction.ipynb
|
tamsmchado/DataScience_Em_Producao
|
a84e2fd04834b4eba039a266f9e21faca8b9db7a
|
[
"MIT"
] | null | null | null | 196.127298 | 206,020 | 0.870891 |
[
[
[
"# 0.0. IMPORTS",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport inflection\nimport math\nimport numpy as np \nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport datetime\n\n\n\nfrom IPython.display import Image\n\n",
"_____no_output_____"
]
],
[
[
"## 0.1. Helper Functions",
"_____no_output_____"
],
[
"## 0.2. Loading Data",
"_____no_output_____"
]
],
[
[
"df_sales_raw = pd.read_csv('data/train.csv', low_memory=False)\ndf_store_raw = pd.read_csv('data/store.csv', low_memory=False)\n\n# merge\ndf_raw = pd.merge(df_sales_raw, df_store_raw, how='left', on='Store')",
"_____no_output_____"
]
],
[
[
"# 1.0. DESCRIÇÃO DOS DADOS",
"_____no_output_____"
]
],
[
[
"df1 = df_raw.copy()",
"_____no_output_____"
]
],
[
[
"## 1.1. Rename Columns",
"_____no_output_____"
]
],
[
[
"cols_old = ['Store', 'DayOfWeek', 'Date', 'Sales', 'Customers', 'Open', 'Promo',\n 'StateHoliday', 'SchoolHoliday', 'StoreType', 'Assortment',\n 'CompetitionDistance', 'CompetitionOpenSinceMonth',\n 'CompetitionOpenSinceYear', 'Promo2', 'Promo2SinceWeek',\n 'Promo2SinceYear', 'PromoInterval']\n\nsnakecase = lambda x: inflection.underscore(x)\n\ncols_new = list(map(snakecase, cols_old))\n\n#Rename\ndf1.columns = cols_new",
"_____no_output_____"
]
],
[
[
"## 1.2. Data Dimensions",
"_____no_output_____"
]
],
[
[
"print('Numbers of rows: {}'.format(df1.shape[0]))\nprint('Numbers of columns: {}'.format(df1.shape[1]))",
"Numbers of rows: 1017209\nNumbers of columns: 18\n"
]
],
[
[
"## 1.3. Data Types",
"_____no_output_____"
]
],
[
[
"df1['date'] = pd.to_datetime(df1['date'])\ndf1.dtypes",
"_____no_output_____"
]
],
[
[
"## 1.4. Check NA",
"_____no_output_____"
]
],
[
[
"df1.isna().sum()",
"_____no_output_____"
]
],
[
[
"## 1.5. Fillout NA",
"_____no_output_____"
]
],
[
[
"# competition_distance\n## df1['competition_distance'].max() # Checking the maximun distance / ==75860.0\ndf1['competition_distance'] = df1['competition_distance'].apply(lambda x: 200000.0 if math.isnan( x ) else x)\n\n# competition_open_since_month\n## Using the month of the date column as reference if there isn't any value in competition_open_since_month column\ndf1['competition_open_since_month'] = df1.apply(lambda x: x['date'].month if math.isnan(x['competition_open_since_month']) else x['competition_open_since_month'], axis=1)\n\n# competition_open_since_year\n## Using the year inside date column as reference if there isn't any value in competition_open_since_year column\ndf1['competition_open_since_year'] = df1.apply(lambda x: x['date'].year if math.isnan(x['competition_open_since_year']) else x['competition_open_since_year'], axis=1)\n \n# promo2_since_week\n## Using the week inside date column as reference if there isn't any value in promo2_since_week column\ndf1['promo2_since_week'] = df1.apply(lambda x: x['date'].week if math.isnan(x['promo2_since_week']) else x['promo2_since_week'], axis=1)\n \n# promo2_since_year \n## Using the year inside date column as reference if there isn't any value in promo2_since_year column\ndf1['promo2_since_year'] = df1.apply(lambda x: x['date'].year if math.isnan(x['promo2_since_year']) else x['promo2_since_year'], axis=1)\n\n# promo_interval\nmonth_map = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}\n\ndf1['promo_interval'].fillna(0, inplace=True)\n\ndf1['month_map'] = df1['date'].dt.month.map(month_map)\n\ndf1['is_promo'] = df1[['promo_interval', 'month_map']].apply(lambda x: 0 if x['promo_interval'] == 0 else 1 if x['month_map'] in x['promo_interval'].split(',') else 0, axis=1)",
"_____no_output_____"
]
],
[
[
"## 1.6. Change Types",
"_____no_output_____"
]
],
[
[
"df1['competition_open_since_month'] = df1['competition_open_since_month'].astype(np.int64)\ndf1['competition_open_since_year'] = df1['competition_open_since_year'].astype(np.int64)\ndf1['promo2_since_week'] = df1['promo2_since_week'].astype(np.int64)\ndf1['promo2_since_year'] = df1['promo2_since_year'].astype(np.int64)",
"_____no_output_____"
]
],
[
[
"## 1.7. Descriptive Statistical ",
"_____no_output_____"
],
[
"### 1.7.1 Numerical Attributes",
"_____no_output_____"
]
],
[
[
"# Spliting the dataframe between numeric and categorical\nnum_attributes = df1.select_dtypes(include = ['int64', 'float64'])\ncat_attributes = df1.select_dtypes(exclude = ['int64', 'float64', 'datetime64[ns]'])",
"_____no_output_____"
],
[
"# Central Tendency - mean, median\nct1 = pd.DataFrame(num_attributes.apply(np.mean)).T\nct2 = pd.DataFrame(num_attributes.apply(np.median)).T\n\n# Dispersion - std, min, max, range, skew, kurtosis\nd1 = pd.DataFrame(num_attributes.apply(np.std)).T\nd2 = pd.DataFrame(num_attributes.apply(min)).T\nd3 = pd.DataFrame(num_attributes.apply(max)).T\nd4 = pd.DataFrame(num_attributes.apply(lambda x: x.max() - x.min())).T\nd5 = pd.DataFrame(num_attributes.apply(lambda x: x.skew())).T\nd6 = pd.DataFrame(num_attributes.apply(lambda x: x.kurtosis())).T\n\nm = pd.concat([d2, d3, d4, ct1, ct2, d1, d5, d6]).T.reset_index()\nm.columns = ['attributes', 'min', 'max', 'range', 'mean', 'median', 'std', 'skew', 'kurtosis']\nm",
"_____no_output_____"
]
],
[
[
"### 1.7.2 Categorical Attributes",
"_____no_output_____"
]
],
[
[
"cat_attributes.apply(lambda x: x.unique().shape[0])",
"_____no_output_____"
],
[
"aux1 = df1[(df1['state_holiday'] != '0') & (df1['sales'] > 0)]\n\nplt.figure(figsize=(15, 6))\n\nplt.subplot(1, 3, 1)\nsns.boxplot(x='state_holiday', y='sales', data=aux1)\n\nplt.subplot(1, 3, 2)\nsns.boxplot(x='store_type', y='sales', data=aux1)\n\nplt.subplot(1, 3, 3)\nsns.boxplot(x='assortment', y='sales', data=aux1)\n\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"# 2.0. Feature Engineering",
"_____no_output_____"
]
],
[
[
"df2 = df1.copy()",
"_____no_output_____"
]
],
[
[
"## 2.1. Mind Map Hypothesis",
"_____no_output_____"
]
],
[
[
"Image('img/MindMapHypothesis.png')",
"_____no_output_____"
]
],
[
[
"## 2.2.Criação das Hipóteses",
"_____no_output_____"
],
[
"### 2.2.1. Hipóteses Loja",
"_____no_output_____"
],
[
"**1.** Lojas com maior quadro de funcionários deveriam vender mais.\n\n**2.** Lojas com maior capacidade de estoque deveriam vender mais.\n\n**3.** Lojas com maior porte deveriam vender mais.\n\n**4.** Lojas com maior sortimento deveriam vender mais.\n\n**5.** Lojas com competidores mais próximos deveriam vender menos.\n\n**6.** Lojas com competidores à mais tempo deveriam vender mais.",
"_____no_output_____"
],
[
"### 2.2.2. Hipóteses Produto",
"_____no_output_____"
],
[
"**1.** Lojas que investem mais em marketing deveriam vender mais.\n\n**2.** Lojas que expoem mais os produtos na vitrine deveriam vender mais.\n\n**3.** Lojas com produtos que tem preços menores deveriam vender mais.\n\n**4.** Lojas promoções mais agressivas (descontos maiores) deveriam vender mais.\n\n**5.** Lojas com promoções ativas por mais tempo deveriam vender mais.\n\n**6.** Lojas com mais dias de promoção deveriam vender mais.\n\n**7.** Lojas com mais promoções consecutivas deveriam vender mais.",
"_____no_output_____"
],
[
"### 2.2.3. Hipóteses Tempo",
"_____no_output_____"
],
[
"**1.** Lojas abertas durante o feriado de Natal deveriam vender mais.\n\n**2.** Lojas deveriam vender mais ao longo dos anos.\n\n**3.** Lojas deveriam vender mais no segundo semestre.\n\n**4.** Lojas deveriam vender mais depois do dia 10 de cada mês.\n\n**5.** Lojas deveriam vender menos aos finais de semana.\n\n**6.** Lojas deveriam vender menos durante os feriados escolares.",
"_____no_output_____"
],
[
"## 2.3. Lista Final de Hipóteses",
"_____no_output_____"
],
[
"**1.** Lojas com maior sortimento deveriam vender mais.\n\n**2.** Lojas com competidores mais próximos deveriam vender menos.\n\n**3.** Lojas com competidores à mais tempo deveriam vender mais.\n\n**4** Lojas com promoções ativas por mais tempo deveriam vender mais.\n\n**5** Lojas com mais dias de promoção deveriam vender mais.\n\n**6.** Lojas com mais promoções consecutivas deveriam vender mais.\n\n**7.** Lojas abertas durante o feriado de Natal deveriam vender mais.\n\n**8.** Lojas deveriam vender mais ao longo dos anos.\n\n**9.** Lojas deveriam vender mais no segundo semestre.\n\n**10.** Lojas deveriam vender mais depois do dia 10 de cada mês.\n\n**11.** Lojas deveriam vender menos aos finais de semana.\n\n**12.** Lojas deveriam vender menos durante os feriados escolares.\n",
"_____no_output_____"
],
[
"## 2.4. Feature Engineering",
"_____no_output_____"
]
],
[
[
"# year\ndf2['year'] = df2['date'].dt.year\n# month\ndf2['month'] = df2['date'].dt.month\n# day\ndf2['day'] = df2['date'].dt.day\n# week of year\ndf2['week_of_year'] = df2['date'].dt.weekofyear\n# year week\ndf2['year_week'] = df2['date'].dt.strftime('%Y-%W')\n\n# competition since\ndf2['competition_since'] = df2.apply(lambda x: datetime.datetime(year=x['competition_open_since_year'], month=x['competition_open_since_month'], day=1), axis=1)\ndf2['competition_time_month'] = ((df2['date'] - df2['competition_since'])/30).apply(lambda x: x.days).astype(np.int64) # tempo que competição está aberta em meses\n\n# promo since\ndf2['promo_since'] = df2['promo2_since_year'].astype(str) + '-' + df2['promo2_since_week'].astype(str)\ndf2['promo_since'] = df2['promo_since'].apply(lambda x: datetime.datetime.strptime(x + '-1', '%Y-%W-%w') - datetime.timedelta(days=7))\ndf2['promo_time_week'] = ((df2['date'] - df2['promo_since'])/7).apply(lambda x: x.days).astype(np.int64) #tempo que a promoção está ativa em semanas\n\n\n# assortment\ndf2['assortment'] = df2['assortment'].apply(lambda x: 'basic' if x == 'a' else 'extra' if x == 'b' else 'extended')\n\n# state holiday\ndf2['state_holiday'] = df2['state_holiday'].apply(lambda x: 'public_holiday' if x == 'a' else 'eater_holiday' if x == 'b' else 'christmas' if x == 'c' else 'regular_day')",
"<ipython-input-27-6a52b62f4fd9>:8: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df2['week_of_year'] = df2['date'].dt.weekofyear\n"
],
[
"df2.head().T",
"_____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",
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
4aad8a391cf1ed25586242a0bc4e136ff7eb27f2
| 181,759 |
ipynb
|
Jupyter Notebook
|
Modulo 4 - Analisi per regioni/regioni/Campania/Confronto CAMPANIA.ipynb
|
SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths
|
c418eba90dc07f58633e7e4cd2719c46f0a6b202
|
[
"Unlicense"
] | 3 |
2021-04-02T21:54:52.000Z
|
2021-04-13T14:24:29.000Z
|
Modulo 4 - Analisi per regioni/regioni/Campania/Confronto CAMPANIA.ipynb
|
SofiaBlack/COVID-19_deaths_analysis
|
c418eba90dc07f58633e7e4cd2719c46f0a6b202
|
[
"Unlicense"
] | null | null | null |
Modulo 4 - Analisi per regioni/regioni/Campania/Confronto CAMPANIA.ipynb
|
SofiaBlack/COVID-19_deaths_analysis
|
c418eba90dc07f58633e7e4cd2719c46f0a6b202
|
[
"Unlicense"
] | null | null | null | 105.796857 | 56,220 | 0.833796 |
[
[
[
"<h1>REGIONE CAMPANIA</h1>",
"_____no_output_____"
],
[
"Confronto dei dati relativi ai decessi registrati dall'ISTAT e i decessi causa COVID-19 registrati dalla Protezione Civile Italiana con i decessi previsti dal modello predittivo SARIMA.",
"_____no_output_____"
],
[
"<h2>DECESSI MENSILI REGIONE CAMPANIA ISTAT</h2>",
"_____no_output_____"
],
[
"Il DataFrame contiene i dati relativi ai decessi mensili della regione <b>Campania</b> dal <b>2015</b> al <b>30 settembre 2020</b>.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n\nimport pandas as pd\ndecessi_istat = pd.read_csv('../../csv/regioni/campania.csv')\ndecessi_istat.head()",
"_____no_output_____"
],
[
"decessi_istat['DATA'] = pd.to_datetime(decessi_istat['DATA'])\ndecessi_istat.TOTALE = pd.to_numeric(decessi_istat.TOTALE)\n",
"_____no_output_____"
]
],
[
[
"<h3>Recupero dei dati inerenti al periodo COVID-19</h3>",
"_____no_output_____"
]
],
[
[
"decessi_istat = decessi_istat[decessi_istat['DATA'] > '2020-02-29']\ndecessi_istat.head()\n",
"_____no_output_____"
]
],
[
[
"<h3>Creazione serie storica dei decessi ISTAT</h3>",
"_____no_output_____"
]
],
[
[
"decessi_istat = decessi_istat.set_index('DATA')\ndecessi_istat = decessi_istat.TOTALE\ndecessi_istat",
"_____no_output_____"
]
],
[
[
"<h2>DECESSI MENSILI REGIONE ABRUZZO CAMPANIA DAL COVID</h2>",
"_____no_output_____"
],
[
"Il DataFrame contine i dati forniti dalla Protezione Civile relativi ai decessi mensili della regione <b>Campania</b> da <b> marzo 2020</b> al <b>30 settembre 2020</b>.",
"_____no_output_____"
]
],
[
[
"covid = pd.read_csv('../../csv/regioni_covid/campania.csv')\ncovid.head()",
"_____no_output_____"
],
[
"covid['data'] = pd.to_datetime(covid['data'])\ncovid.deceduti = pd.to_numeric(covid.deceduti)",
"_____no_output_____"
],
[
"covid = covid.set_index('data')\ncovid.head()",
"_____no_output_____"
]
],
[
[
"<h3>Creazione serie storica dei decessi COVID-19</h3>",
"_____no_output_____"
]
],
[
[
"covid = covid.deceduti",
"_____no_output_____"
]
],
[
[
"<h2>PREDIZIONE DECESSI MENSILI REGIONE SECONDO MODELLO SARIMA</h2>",
"_____no_output_____"
],
[
"Il DataFrame contiene i dati riguardanti i decessi mensili della regione <b>Campania</b> secondo la predizione del modello SARIMA applicato. ",
"_____no_output_____"
]
],
[
[
"predictions = pd.read_csv('../../csv/pred/predictions_SARIMA_campania.csv')\npredictions.head()",
"_____no_output_____"
],
[
"predictions.rename(columns={'Unnamed: 0': 'Data', 'predicted_mean':'Totale'}, inplace=True)\npredictions.head()",
"_____no_output_____"
],
[
"predictions['Data'] = pd.to_datetime(predictions['Data'])\npredictions.Totale = pd.to_numeric(predictions.Totale)",
"_____no_output_____"
]
],
[
[
"<h3>Recupero dei dati inerenti al periodo COVID-19</h3>",
"_____no_output_____"
]
],
[
[
"predictions = predictions[predictions['Data'] > '2020-02-29']\npredictions.head()",
"_____no_output_____"
],
[
"predictions = predictions.set_index('Data')\npredictions.head()",
"_____no_output_____"
]
],
[
[
"<h3>Creazione serie storica dei decessi secondo la predizione del modello</h3>",
"_____no_output_____"
]
],
[
[
"predictions = predictions.Totale",
"_____no_output_____"
]
],
[
[
"<h1>INTERVALLI DI CONFIDENZA",
"_____no_output_____"
],
[
"<h3>Limite massimo",
"_____no_output_____"
]
],
[
[
"upper = pd.read_csv('../../csv/upper/predictions_SARIMA_campania_upper.csv')\nupper.head()",
"_____no_output_____"
],
[
"upper.rename(columns={'Unnamed: 0': 'Data', 'upper TOTALE':'Totale'}, inplace=True)\nupper['Data'] = pd.to_datetime(upper['Data'])\nupper.Totale = pd.to_numeric(upper.Totale)\nupper.head()",
"_____no_output_____"
],
[
"upper = upper[upper['Data'] > '2020-02-29']\nupper = upper.set_index('Data')\nupper.head()",
"_____no_output_____"
],
[
"upper = upper.Totale",
"_____no_output_____"
]
],
[
[
"<h3>Limite minimo",
"_____no_output_____"
]
],
[
[
"lower = pd.read_csv('../../csv/lower/predictions_SARIMA_campania_lower.csv')\nlower.head()",
"_____no_output_____"
],
[
"lower.rename(columns={'Unnamed: 0': 'Data', 'lower TOTALE':'Totale'}, inplace=True)\nlower['Data'] = pd.to_datetime(lower['Data'])\nlower.Totale = pd.to_numeric(lower.Totale)\nlower.head()",
"_____no_output_____"
],
[
"lower = lower[lower['Data'] > '2020-02-29']\nlower = lower.set_index('Data')\nlower.head()",
"_____no_output_____"
],
[
"lower = lower.Totale",
"_____no_output_____"
]
],
[
[
"<h1> CONFRONTO DELLE SERIE STORICHE </h1>",
"_____no_output_____"
],
[
"Di seguito il confronto grafico tra le serie storiche dei <b>decessi totali mensili</b>, dei <b>decessi causa COVID-19</b> e dei <b>decessi previsti dal modello SARIMA</b> della regione <b>Campania</b>.\n<br />\nI mesi di riferimento sono: <b>marzo</b>, <b>aprile</b>, <b>maggio</b>, <b>giugno</b>, <b>luglio</b>, <b>agosto</b> e <b>settembre</b>.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15,4))\nplt.title('CAMPANIA - Confronto decessi totali, decessi causa covid e decessi del modello predittivo', size=18)\nplt.plot(covid, label='decessi causa covid')\nplt.plot(decessi_istat, label='decessi totali')\nplt.plot(predictions, label='predizione modello')\nplt.legend(prop={'size': 12})\nplt.show()",
"_____no_output_____"
],
[
"plt.figure(figsize=(15,4))\nplt.title(\"CAMPANIA - Confronto decessi totali ISTAT con decessi previsti dal modello\", size=18)\nplt.plot(predictions, label='predizione modello')\nplt.plot(upper, label='limite massimo')\nplt.plot(lower, label='limite minimo')\nplt.plot(decessi_istat, label='decessi totali')\nplt.legend(prop={'size': 12})\nplt.show()",
"_____no_output_____"
]
],
[
[
"<h3>Calcolo dei decessi COVID-19 secondo il modello predittivo</h3>",
"_____no_output_____"
],
[
"Differenza tra i decessi totali rilasciati dall'ISTAT e i decessi secondo la previsione del modello SARIMA.",
"_____no_output_____"
]
],
[
[
"n = decessi_istat - predictions\nn_upper = decessi_istat - lower\nn_lower = decessi_istat - upper\n\nplt.figure(figsize=(15,4))\nplt.title(\"CAMPANIA - Confronto decessi accertati covid con decessi covid previsti dal modello\", size=18)\nplt.plot(covid, label='decessi covid accertati - Protezione Civile')\nplt.plot(n, label='devessi covid previsti - modello SARIMA')\nplt.plot(n_upper, label='limite massimo - modello SARIMA')\nplt.plot(n_lower, label='limite minimo - modello SARIMA')\nplt.legend(prop={'size': 12})\nplt.show()",
"_____no_output_____"
],
[
"d = decessi_istat.sum()\nprint(\"Decessi 2020:\", d)",
"Decessi 2020: 30414\n"
],
[
"d_m = predictions.sum()\nprint(\"Decessi attesi dal modello 2020:\", d_m)",
"Decessi attesi dal modello 2020: 31593.229323936735\n"
],
[
"d_lower = lower.sum()\nprint(\"Decessi attesi dal modello 2020 - livello mimino:\", d_lower)",
"Decessi attesi dal modello 2020 - livello mimino: 26819.861700678186\n"
]
],
[
[
"<h3>Numero totale dei decessi accertati COVID-19 regione Campania </h3>",
"_____no_output_____"
]
],
[
[
"m = covid.sum()\nprint(int(m))",
"463\n"
]
],
[
[
"<h3>Numero totale dei decessi COVID-19 previsti dal modello per la regione Campania </h3>",
"_____no_output_____"
],
[
"<h4>Valore medio",
"_____no_output_____"
]
],
[
[
"total = n.sum()\nprint(int(total))",
"-1179\n"
]
],
[
[
"<h4>Valore massimo",
"_____no_output_____"
]
],
[
[
"total_upper = n_upper.sum()\nprint(int(total_upper))",
"3594\n"
]
],
[
[
"<h4>Valore minimo",
"_____no_output_____"
]
],
[
[
"total_lower = n_lower.sum()\nprint(int(total_lower))",
"-5952\n"
]
],
[
[
"<h3>Calcolo del numero dei decessi COVID-19 non registrati secondo il modello predittivo SARIMA della regione Campania</h3>",
"_____no_output_____"
],
[
"<h4>Valore medio",
"_____no_output_____"
]
],
[
[
"x = decessi_istat - predictions - covid\nx = x.sum()\nprint(int(x))",
"-1642\n"
]
],
[
[
"<h4>Valore massimo",
"_____no_output_____"
]
],
[
[
"x_upper = decessi_istat - lower - covid\nx_upper = x_upper.sum()\nprint(int(x_upper))",
"3131\n"
]
],
[
[
"<h4>Valore minimo",
"_____no_output_____"
]
],
[
[
"x_lower = decessi_istat - upper - covid\nx_lower = x_lower.sum()\nprint(int(x_lower))",
"-6415\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",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aad94d8ca24e3cdbc1448b01eed309cdef5c525
| 38,691 |
ipynb
|
Jupyter Notebook
|
Untitled.ipynb
|
vivek7415/object_detection
|
ee79ecfac459d8a39a033ae66471551d6e9176c1
|
[
"MIT"
] | 1 |
2019-06-26T07:15:38.000Z
|
2019-06-26T07:15:38.000Z
|
Untitled.ipynb
|
vivek7415/object_detection
|
ee79ecfac459d8a39a033ae66471551d6e9176c1
|
[
"MIT"
] | null | null | null |
Untitled.ipynb
|
vivek7415/object_detection
|
ee79ecfac459d8a39a033ae66471551d6e9176c1
|
[
"MIT"
] | null | null | null | 40.942857 | 136 | 0.409837 |
[
[
[
"import torch",
"_____no_output_____"
],
[
"from torch.autograd import Variable\nimport cv2\nfrom data import BaseTransform, VOC_CLASSES as labelmap\nfrom ssd import build_ssd\nimport imageio",
"_____no_output_____"
],
[
"def detect(frame, net, transform):\n height, width = frame.shape[:2]\n frame_t = transform(frame)[0]\n x = torch.from_numpy(frame_t).permute(2,0,1)\n x = x.unsqueeze(0)\n x = Variable(x)\n \n y = net(x)\n \n detections = y.data\n \n scale = torch.Tensor([width, height, width, height])\n print(detections)\n for i in range(detections.size(1)):\n j=0\n while detections[0,i,j,0]>=0.5:\n pt = (detections[0,i,j,1:]*scale).numpy()\n cv2.rectangle(frame, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])), (0,0,255), 2)\n cv2.putText(frame, labelmap[i-1], (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,0,0), 2, cv2.LINE_AA)\n \n j += 1\n return frame\n\nnet = build_ssd('test')\nnet.load_state_dict(torch.load('ssd300_mAP_77.43_v2.pth', map_location= lambda storage, loc: storage))\n\ntransform = BaseTransform(net.size, (104/256.0, 117/256.0, 123/256.0))\n\n# reader = imageio.get_reader('epic_horses.mp4')\n# FPS = reader.get_meta_data()['fps']\n# writer = imageio.get_writer('output1.mp4', fps = FPS)\n\n# for i, frame in enumerate(reader):\n# frame = detect(frame, net.eval(), transform)\n# writer.append_data(frame)\n# print(i)\n# writer.close\n\n\nvideo_capture = cv2.VideoCapture(0)\nwhile True:\n _, frame = video_capture.read()\n# gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n canvas = detect(frame, net.eval(), transform)\n cv2.imshow('Video', canvas)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\nvideo_capture.release()\ncv2.destroyAllWindows()",
"\n( 0 , 0 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 1 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 2 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ... \n\n( 0 ,18 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,19 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,20 ,.,.) = \n 0.0346 0.4434 0.5009 0.7146 0.8581\n 0.0152 0.4807 0.4704 0.6426 0.7745\n 0.0136 0.8563 0.6066 1.0055 0.9368\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n[torch.FloatTensor of size 1x21x200x5]\n\n\n( 0 , 0 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 1 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 2 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ... \n\n( 0 ,18 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,19 ,.,.) = \n 0.0134 0.0326 0.0717 0.9764 0.8986\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,20 ,.,.) = \n 0.0325 0.4421 0.4946 0.7137 0.8462\n 0.0278 0.0326 0.0717 0.9764 0.8986\n 0.0120 0.1623 0.5371 0.9969 0.9952\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n[torch.FloatTensor of size 1x21x200x5]\n\n\n( 0 , 0 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 1 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 2 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ... \n\n( 0 ,18 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,19 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,20 ,.,.) = \n 0.0328 0.4487 0.5058 0.7142 0.8505\n 0.0241 0.0262 0.0837 0.9695 0.8967\n 0.0123 0.1454 0.5401 0.9925 0.9939\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n[torch.FloatTensor of size 1x21x200x5]\n\n\n( 0 , 0 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 1 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 2 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ... \n\n( 0 ,18 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,19 ,.,.) = \n 0.0126 0.0519 0.0380 0.9226 0.9471\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,20 ,.,.) = \n 0.0424 0.4461 0.4945 0.7106 0.8516\n 0.0246 0.0519 0.0380 0.9226 0.9471\n 0.0124 0.4785 0.4427 0.6452 0.7277\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n[torch.FloatTensor of size 1x21x200x5]\n\n\n( 0 , 0 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 1 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 , 2 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ... \n\n( 0 ,18 ,.,.) = \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,19 ,.,.) = \n 0.0104 0.0070 0.0698 0.9892 0.8981\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n\n( 0 ,20 ,.,.) = \n 0.0313 0.0359 0.0348 0.9264 0.9324\n 0.0267 0.4435 0.4564 0.7028 0.7928\n 0.0159 0.1475 0.5321 1.0077 0.9936\n ⋮ \n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n 0.0000 0.0000 0.0000 0.0000 0.0000\n[torch.FloatTensor of size 1x21x200x5]\n\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
4aad9f8010e22b113ef3f7ffa96affacaaba8d4e
| 28,424 |
ipynb
|
Jupyter Notebook
|
notebooks/cmssw.ipynb
|
edcuba/particleflow
|
1c6189f499ae4807ecca42d459e363fd5b3a12ab
|
[
"Apache-2.0"
] | null | null | null |
notebooks/cmssw.ipynb
|
edcuba/particleflow
|
1c6189f499ae4807ecca42d459e363fd5b3a12ab
|
[
"Apache-2.0"
] | null | null | null |
notebooks/cmssw.ipynb
|
edcuba/particleflow
|
1c6189f499ae4807ecca42d459e363fd5b3a12ab
|
[
"Apache-2.0"
] | null | null | null | 38.101877 | 317 | 0.578596 |
[
[
[
"import pickle\nimport numpy as np\nimport awkward\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\nimport uproot\nimport boost_histogram as bh\nimport mplhep\n\nmplhep.style.use(\"CMS\")",
"_____no_output_____"
],
[
"CMS_PF_CLASS_NAMES = [\"none\" \"charged hadron\", \"neutral hadron\", \"hfem\", \"hfhad\", \"photon\", \"electron\", \"muon\"]\n\nELEM_LABELS_CMS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\nELEM_NAMES_CMS = [\"NONE\", \"TRACK\", \"PS1\", \"PS2\", \"ECAL\", \"HCAL\", \"GSF\", \"BREM\", \"HFEM\", \"HFHAD\", \"SC\", \"HO\"]\n\nCLASS_LABELS_CMS = [0, 211, 130, 1, 2, 22, 11, 13]\nCLASS_NAMES_CMS = [\"none\", \"ch.had\", \"n.had\", \"HFEM\", \"HFHAD\", \"$\\gamma$\", \"$e^\\pm$\", \"$\\mu^\\pm$\"]\n\nclass_names = {k: v for k, v in zip(CLASS_LABELS_CMS, CLASS_NAMES_CMS)}",
"_____no_output_____"
],
[
"physics_process = \"qcd\" #\"ttbar\", \"qcd\"\n\nif physics_process == \"qcd\":\n data_baseline = awkward.Array(pickle.load(open(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.0/out.pkl\", \"rb\")))\n data_mlpf = awkward.Array(pickle.load(open(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.13/out.pkl\", \"rb\")))\n\n fi1 = uproot.open(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.0/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root\")\n fi2 = uproot.open(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.13/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root\")\nelif physics_process == \"ttbar\":\n data_mlpf = awkward.Array(pickle.load(open(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.13/out.pkl\", \"rb\")))\n data_baseline = awkward.Array(pickle.load(open(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.0/out.pkl\", \"rb\")))\n\n fi1 = uproot.open(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.0/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root\")\n fi2 = uproot.open(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.13/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root\")",
"_____no_output_____"
],
[
"def sample_label(ax, physics_process=physics_process, additional_text=\"\", x=0.01, y=0.93):\n plt.text(x, y,\n physics_process_str[physics_process]+additional_text,\n ha=\"left\", size=20,\n transform=ax.transAxes\n )\n \nphysics_process_str = {\n \"ttbar\": \"$t\\\\bar{t}$ events\",\n \"singlepi\": \"single $\\pi^{\\pm}$ events\",\n \"qcd\": \"QCD events\",\n}",
"_____no_output_____"
],
[
"def ratio_unc(h0, h1):\n ratio = h0/h1\n \n c0 = h0.values()\n c1 = h1.values()\n v0 = np.sqrt(c0)\n v1 = np.sqrt(c1)\n \n unc_ratio = ratio.values()*np.sqrt((v0/c0)**2 + (v1/c1)**2)\n \n return ratio, unc_ratio",
"_____no_output_____"
],
[
"def plot_candidates_pf_vs_mlpf(variable, varname, bins):\n plt.figure(figsize=(16,16))\n ax = plt.axes()\n\n hists_baseline = []\n hists_mlpf = []\n iplot = 1\n for pid in [13,11,22,1,2,130,211]:\n msk1 = np.abs(data_baseline[\"particleFlow\"][\"pdgId\"]) == pid\n msk2 = np.abs(data_mlpf[\"particleFlow\"][\"pdgId\"]) == pid\n\n d1 = awkward.flatten(data_baseline[\"particleFlow\"][variable][msk1])\n d2 = awkward.flatten(data_mlpf[\"particleFlow\"][variable][msk2])\n \n h1 = bh.Histogram(bh.axis.Variable(bins))\n h1.fill(d1)\n h2 = bh.Histogram(bh.axis.Variable(bins))\n h2.fill(d2)\n \n ax = plt.subplot(3,3,iplot)\n plt.sca(ax)\n\n mplhep.histplot(h1, histtype=\"step\", lw=2, label=\"PF\");\n mplhep.histplot(h2, histtype=\"step\", lw=2, label=\"MLPF\");\n \n if variable!=\"eta\":\n plt.yscale(\"log\")\n\n plt.legend(loc=\"best\", frameon=False, title=class_names[pid])\n plt.xlabel(varname)\n plt.ylabel(\"Number of particles / bin\")\n sample_label(ax, x=0.08)\n\n iplot += 1\n \n hists_baseline.append(h1)\n hists_mlpf.append(h2)\n plt.tight_layout()\n return hists_baseline, hists_mlpf\n\ndef plot_candidates_pf_vs_mlpf_single(hists, ncol=1):\n #plt.figure(figsize=(10, 13))\n f, (a0, a1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [3, 1]}, sharex=True)\n \n plt.sca(a0)\n mplhep.cms.label(\"Preliminary\", data=False, loc=0, rlabel=\"Run 3 (14 TeV)\")\n v1 = mplhep.histplot([h[bh.rebin(2)] for h in hists[0]], stack=True, label=[class_names[k] for k in [13,11,22,1,2,130,211]], lw=1)\n v2 = mplhep.histplot([h[bh.rebin(2)] for h in hists[1]], stack=True, color=[x.stairs.get_edgecolor() for x in v1][::-1], lw=2, histtype=\"errorbar\")\n plt.yscale(\"log\")\n plt.ylim(top=1e8)\n sample_label(a0)\n \n if ncol==1:\n legend1 = plt.legend(v1, [x.legend_artist.get_label() for x in v1], loc=(0.40, 0.25), title=\"PF\", ncol=1)\n legend2 = plt.legend(v2, [x.legend_artist.get_label() for x in v1], loc=(0.65, 0.25), title=\"MLPF\", ncol=1)\n elif ncol==2:\n legend1 = plt.legend(v1, [x.legend_artist.get_label() for x in v1], loc=(0.05, 0.50), title=\"PF\", ncol=2)\n legend2 = plt.legend(v2, [x.legend_artist.get_label() for x in v1], loc=(0.50, 0.50), title=\"MLPF\", ncol=2)\n\n plt.gca().add_artist(legend1)\n plt.ylabel(\"Total number of particles / bin\")\n \n plt.sca(a1)\n sum_h0 = sum(hists[0])\n sum_h1 = sum(hists[1])\n ratio = sum_h0/sum_h1\n \n ratio, unc_ratio = ratio_unc(sum_h0, sum_h1)\n \n mplhep.histplot(ratio, histtype=\"errorbar\", color=\"black\", yerr=unc_ratio)\n plt.ylim(0,2)\n plt.axhline(1.0, color=\"black\", ls=\"--\")\n plt.ylabel(\"PF / MLPF\")\n\n #lt.tight_layout()\n\n #cms_label(ax)\n #sample_label(ax)\n \n return a0, a1",
"_____no_output_____"
],
[
"hists = plot_candidates_pf_vs_mlpf(\"pt\", \"PFCandidate $p_T$ [GeV]\", np.linspace(0,200,101))\nplt.savefig(\"candidates_pt_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"a0, a1 = plot_candidates_pf_vs_mlpf_single(hists)\nplt.xlabel(\"PFCandidate $p_T$ [GeV]\")\nplt.savefig(\"candidates_pt_single_{}.pdf\".format(physics_process), bbox_inches=\"tight\")\nplt.savefig(\"candidates_pt_single_{}.png\".format(physics_process), dpi=400, bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"hists = plot_candidates_pf_vs_mlpf(\"eta\", \"PFCandidate $\\eta$\", np.linspace(-6, 6,101))\nplt.savefig(\"candidates_eta_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"a0, a1 = plot_candidates_pf_vs_mlpf_single(hists, ncol=2)\na0.set_yscale(\"log\")\na0.set_ylim(10,1e10)\nplt.xlabel(\"PFCandidate $\\eta$\")\nplt.savefig(\"candidates_eta_single_{}.pdf\".format(physics_process), bbox_inches=\"tight\")\nplt.savefig(\"candidates_eta_single_{}.png\".format(physics_process), dpi=400, bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"def plot_pf_vs_mlpf_jet(jetcoll, variable, bins, jetcoll_name, cumulative=False, binwnorm=False):\n f, (a0, a1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [3, 1]}, sharex=True)\n plt.sca(a0)\n mplhep.cms.label(\"Preliminary\", data=False, loc=0, rlabel=\"Run 3 (14 TeV)\")\n\n h1 = bh.Histogram(bh.axis.Variable(bins))\n h1.fill(awkward.flatten(data_baseline[jetcoll][variable]))\n if cumulative:\n h1[:] = np.sum(h1.values()) - np.cumsum(h1)\n\n h2 = bh.Histogram(bh.axis.Variable(bins))\n h2.fill(awkward.flatten(data_mlpf[jetcoll][variable]))\n if cumulative:\n h2[:] = np.sum(h2.values()) - np.cumsum(h2)\n\n mplhep.histplot(h1, histtype=\"step\", lw=2, label=\"PF\", binwnorm=binwnorm);\n mplhep.histplot(h2, histtype=\"step\", lw=2, label=\"MLPF\", binwnorm=binwnorm);\n #cms_label(ax)\n sample_label(a0, additional_text=jetcoll_name)\n\n plt.ylabel(\"Number of jets / GeV\")\n plt.legend(loc=1, frameon=False)\n \n plt.sca(a1)\n plt.axhline(1.0, color=\"black\", ls=\"--\")\n plt.ylim(0,2)\n ratio, unc_ratio = ratio_unc(h1, h2)\n \n mplhep.histplot(h1/h2, histtype=\"errorbar\", color=\"black\", yerr=unc_ratio)\n return a0, a1\n ",
"_____no_output_____"
],
[
"def varbins(b0, b1):\n return np.concatenate([b0[:-1], b1])",
"_____no_output_____"
],
[
"jet_bins = varbins(np.linspace(0,100,21), np.linspace(100,200,5))",
"_____no_output_____"
],
[
"a0, a1 = plot_pf_vs_mlpf_jet(\"ak4PFJetsCHS\", \"pt\", jet_bins, \", AK4 CHS jets\", cumulative=False, binwnorm=1)\na0.set_yscale(\"log\")\na0.set_ylim(1, 1e5)\na1.set_ylabel(\"PF / MLPF\")\n#plt.ylim(top=1e6)\nplt.xlabel(\"jet $p_T$ [GeV]\")\nplt.savefig(\"ak4jet_chs_pt_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"a0, a1 = plot_pf_vs_mlpf_jet(\"ak4PFJetsPuppi\", \"pt\", jet_bins, \", AK4 PUPPI jets\", cumulative=False, binwnorm=1)\na0.set_yscale(\"log\")\na1.set_ylabel(\"PF / MLPF\")\na0.set_ylim(1, 1e4)\nplt.xlabel(\"jet $p_T$ [GeV]\")\nplt.savefig(\"ak4jet_puppi_pt_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"a0, a1 = plot_pf_vs_mlpf_jet(\"ak4PFJetsCHS\", \"eta\", np.linspace(-6, 6, 61), \", AK4 CHS jets\", cumulative=False, binwnorm=None)\n#a0.set_yscale(\"log\")\na0.set_ylim(0, 8000)\na1.set_ylabel(\"PF / MLPF\")\na0.set_ylabel(\"Number of jets / 0.2\")\nplt.xlabel(\"jet $\\eta$\")\nplt.savefig(\"ak4jet_chs_eta_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"a0, a1 = plot_pf_vs_mlpf_jet(\"ak4PFJetsPuppi\", \"eta\", np.linspace(-6, 6, 61), \", AK4 PUPPI jets\", cumulative=False, binwnorm=None)\na0.set_ylim(0,2000)\na1.set_ylabel(\"PF / MLPF\")\nplt.xlabel(\"jet $\\eta$\")\na0.set_ylabel(\"Number of jets / 0.2\")\nplt.savefig(\"ak4jet_puppi_eta_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"met_bins = varbins(np.linspace(0,150,21), np.linspace(150,450,5))",
"_____no_output_____"
],
[
"a0, a1 = plot_pf_vs_mlpf_jet(\"pfMet\", \"pt\", met_bins, \", PF MET\", cumulative=False, binwnorm=1)\na0.set_yscale(\"log\")\na1.set_ylabel(\"PF / MLPF\")\na0.set_ylim(top=1e3)\na0.set_ylabel(\"Number of events / GeV\")\nplt.xlabel(\"MET $p_T$ [GeV]\")\nplt.savefig(\"pfmet_pt_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"a0, a1 = plot_pf_vs_mlpf_jet(\"pfMet\", \"pt\", met_bins, \", PF MET\", cumulative=True, binwnorm=None)\na0.set_yscale(\"log\")\na1.set_ylabel(\"PF / MLPF\")\na0.set_ylim(top=4000)\nplt.xlabel(\"MET $p_T$ [GeV]\")\na0.set_ylabel(\"Cumulative events\")\nplt.savefig(\"pfmet_c_pt_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"a0, a1 = plot_pf_vs_mlpf_jet(\"pfMetPuppi\", \"pt\", met_bins, \", PUPPI MET\", cumulative=False, binwnorm=1)\na0.set_yscale(\"log\")\na0.set_ylim(top=1e3)\nplt.xlabel(\"MET $p_T$ [GeV]\")\na0.set_ylabel(\"Number of events / GeV\")\nplt.savefig(\"pfmet_puppi_pt_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"a0, a1 = plot_pf_vs_mlpf_jet(\"pfMetPuppi\", \"pt\", met_bins, \", PUPPI MET\", cumulative=True, binwnorm=None)\na0.set_yscale(\"log\")\na1.set_ylabel(\"PF / MLPF\")\na0.set_ylim(top=4000)\nplt.xlabel(\"MET $p_T$ [GeV]\")\na0.set_ylabel(\"Cumulative events\")\nplt.savefig(\"pfmet_puppi_c_pt_{}.pdf\".format(physics_process), bbox_inches=\"tight\")",
"_____no_output_____"
],
[
"timing_output = \"\"\"\nNelem=1600 mean_time=4.66 ms stddev_time=2.55 ms mem_used=711 MB\nNelem=1920 mean_time=4.74 ms stddev_time=0.52 ms mem_used=711 MB\nNelem=2240 mean_time=5.53 ms stddev_time=0.63 ms mem_used=711 MB\nNelem=2560 mean_time=5.88 ms stddev_time=0.52 ms mem_used=711 MB\nNelem=2880 mean_time=6.22 ms stddev_time=0.63 ms mem_used=745 MB\nNelem=3200 mean_time=6.50 ms stddev_time=0.64 ms mem_used=745 MB\nNelem=3520 mean_time=7.07 ms stddev_time=0.61 ms mem_used=745 MB\nNelem=3840 mean_time=7.53 ms stddev_time=0.68 ms mem_used=745 MB\nNelem=4160 mean_time=7.76 ms stddev_time=0.69 ms mem_used=745 MB\nNelem=4480 mean_time=8.66 ms stddev_time=0.72 ms mem_used=745 MB\nNelem=4800 mean_time=9.00 ms stddev_time=0.57 ms mem_used=745 MB\nNelem=5120 mean_time=9.22 ms stddev_time=0.84 ms mem_used=745 MB\nNelem=5440 mean_time=9.64 ms stddev_time=0.73 ms mem_used=812 MB\nNelem=5760 mean_time=10.39 ms stddev_time=1.06 ms mem_used=812 MB\nNelem=6080 mean_time=10.77 ms stddev_time=0.69 ms mem_used=812 MB\nNelem=6400 mean_time=11.33 ms stddev_time=0.75 ms mem_used=812 MB\nNelem=6720 mean_time=12.19 ms stddev_time=0.77 ms mem_used=812 MB\nNelem=7040 mean_time=12.54 ms stddev_time=0.72 ms mem_used=812 MB\nNelem=7360 mean_time=13.08 ms stddev_time=0.78 ms mem_used=812 MB\nNelem=7680 mean_time=13.71 ms stddev_time=0.81 ms mem_used=812 MB\nNelem=8000 mean_time=14.11 ms stddev_time=0.74 ms mem_used=812 MB\nNelem=8320 mean_time=14.85 ms stddev_time=0.86 ms mem_used=812 MB\nNelem=8640 mean_time=15.36 ms stddev_time=0.79 ms mem_used=812 MB\nNelem=8960 mean_time=16.76 ms stddev_time=1.06 ms mem_used=812 MB\nNelem=9280 mean_time=17.27 ms stddev_time=0.71 ms mem_used=812 MB\nNelem=9600 mean_time=17.97 ms stddev_time=0.85 ms mem_used=812 MB\nNelem=9920 mean_time=18.73 ms stddev_time=0.94 ms mem_used=812 MB\nNelem=10240 mean_time=19.26 ms stddev_time=0.89 ms mem_used=812 MB\nNelem=10560 mean_time=19.91 ms stddev_time=0.90 ms mem_used=946 MB\nNelem=10880 mean_time=20.55 ms stddev_time=0.87 ms mem_used=946 MB\nNelem=11200 mean_time=21.82 ms stddev_time=0.78 ms mem_used=940 MB\nNelem=11520 mean_time=22.48 ms stddev_time=0.75 ms mem_used=940 MB\nNelem=11840 mean_time=23.33 ms stddev_time=0.98 ms mem_used=940 MB\nNelem=12160 mean_time=24.28 ms stddev_time=0.85 ms mem_used=940 MB\nNelem=12480 mean_time=24.85 ms stddev_time=0.67 ms mem_used=940 MB\nNelem=12800 mean_time=25.58 ms stddev_time=0.68 ms mem_used=940 MB\nNelem=13120 mean_time=26.58 ms stddev_time=0.78 ms mem_used=940 MB\nNelem=13440 mean_time=27.15 ms stddev_time=0.63 ms mem_used=940 MB\nNelem=13760 mean_time=27.72 ms stddev_time=0.85 ms mem_used=940 MB\nNelem=14080 mean_time=28.08 ms stddev_time=0.66 ms mem_used=940 MB\nNelem=14400 mean_time=28.70 ms stddev_time=0.73 ms mem_used=940 MB\nNelem=14720 mean_time=29.22 ms stddev_time=0.66 ms mem_used=940 MB\nNelem=15040 mean_time=29.73 ms stddev_time=0.80 ms mem_used=940 MB\nNelem=15360 mean_time=30.71 ms stddev_time=0.85 ms mem_used=940 MB\nNelem=15680 mean_time=31.15 ms stddev_time=0.74 ms mem_used=940 MB\nNelem=16000 mean_time=31.74 ms stddev_time=0.80 ms mem_used=940 MB\nNelem=16320 mean_time=32.27 ms stddev_time=0.77 ms mem_used=940 MB\nNelem=16640 mean_time=33.07 ms stddev_time=1.08 ms mem_used=940 MB\nNelem=16960 mean_time=33.60 ms stddev_time=0.69 ms mem_used=940 MB\nNelem=17280 mean_time=34.43 ms stddev_time=0.64 ms mem_used=940 MB\nNelem=17600 mean_time=35.34 ms stddev_time=0.75 ms mem_used=940 MB\nNelem=17920 mean_time=35.84 ms stddev_time=0.68 ms mem_used=940 MB\nNelem=18240 mean_time=36.51 ms stddev_time=0.85 ms mem_used=940 MB\nNelem=18560 mean_time=37.23 ms stddev_time=0.87 ms mem_used=940 MB\nNelem=18880 mean_time=37.72 ms stddev_time=0.78 ms mem_used=940 MB\nNelem=19200 mean_time=38.33 ms stddev_time=0.87 ms mem_used=940 MB\nNelem=19520 mean_time=38.95 ms stddev_time=0.87 ms mem_used=940 MB\nNelem=19840 mean_time=39.73 ms stddev_time=0.74 ms mem_used=940 MB\nNelem=20160 mean_time=40.27 ms stddev_time=0.81 ms mem_used=940 MB\nNelem=20480 mean_time=40.86 ms stddev_time=0.74 ms mem_used=940 MB\nNelem=20800 mean_time=41.71 ms stddev_time=0.94 ms mem_used=940 MB\nNelem=21120 mean_time=42.35 ms stddev_time=1.38 ms mem_used=1209 MB\nNelem=21440 mean_time=42.91 ms stddev_time=1.18 ms mem_used=1209 MB\nNelem=21760 mean_time=43.40 ms stddev_time=0.98 ms mem_used=1184 MB\nNelem=22080 mean_time=44.43 ms stddev_time=1.04 ms mem_used=1184 MB\nNelem=22400 mean_time=45.22 ms stddev_time=1.02 ms mem_used=1184 MB\nNelem=22720 mean_time=45.57 ms stddev_time=0.94 ms mem_used=1184 MB\nNelem=23040 mean_time=46.21 ms stddev_time=0.86 ms mem_used=1184 MB\nNelem=23360 mean_time=46.85 ms stddev_time=0.95 ms mem_used=1184 MB\nNelem=23680 mean_time=47.52 ms stddev_time=1.57 ms mem_used=1184 MB\nNelem=24000 mean_time=48.31 ms stddev_time=0.74 ms mem_used=1184 MB\nNelem=24320 mean_time=48.92 ms stddev_time=0.75 ms mem_used=1184 MB\nNelem=24640 mean_time=49.70 ms stddev_time=0.92 ms mem_used=1184 MB\nNelem=24960 mean_time=50.26 ms stddev_time=0.93 ms mem_used=1184 MB\nNelem=25280 mean_time=50.98 ms stddev_time=0.89 ms mem_used=1184 MB\n\"\"\"",
"_____no_output_____"
],
[
"time_x = []\ntime_y = []\ntime_y_err = []\ngpu_mem_use = []\nfor line in timing_output.split(\"\\n\"):\n if len(line)>0:\n spl = line.split()\n time_x.append(int(spl[0].split(\"=\")[1]))\n time_y.append(float(spl[1].split(\"=\")[1]))\n time_y_err.append(float(spl[3].split(\"=\")[1]))\n gpu_mem_use.append(float(spl[5].split(\"=\")[1]))",
"_____no_output_____"
],
[
"import glob\nnelem = []\nfor fi in glob.glob(\"../data/TTbar_14TeV_TuneCUETP8M1_cfi/raw/*.pkl\"):\n d = pickle.load(open(fi, \"rb\"))\n for elem in d:\n X = elem[\"Xelem\"][(elem[\"Xelem\"][\"typ\"]!=2)&(elem[\"Xelem\"][\"typ\"]!=3)]\n nelem.append(X.shape[0])",
"_____no_output_____"
],
[
"plt.figure(figsize=(7, 7))\nax = plt.axes()\nplt.hist(nelem, bins=np.linspace(2000,6000,100));\nplt.ylabel(\"Number of events / bin\")\nplt.xlabel(\"PFElements per event\")\ncms_label(ax)\nsample_label(ax, physics_process=\"ttbar\")",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 3))\nax = plt.axes()\nmplhep.cms.label(\"Preliminary\", data=False, loc=0, rlabel=\"Run 3 (14 TeV)\")\nplt.errorbar(time_x, time_y, yerr=time_y_err, marker=\".\")\nplt.axvline(np.mean(nelem)-np.std(nelem), color=\"black\", ls=\"--\", lw=1.0)\nplt.axvline(np.mean(nelem)+np.std(nelem), color=\"black\", ls=\"--\", lw=1.0)\n#plt.xticks(time_x, time_x);\nplt.xlim(0,30000)\nplt.ylim(0,100)\nplt.ylabel(\"runtime [ms/ev]\")\nplt.xlabel(\"PFElements per event\")\n#plt.legend(loc=4, frameon=False)\n#cms_label(ax, y=0.93, x1=0.07, x2=0.99)\nplt.text(4000, 20, \"typical Run3 range\", rotation=90, fontsize=10)\nplt.text(6000, 50, \"Inference with ONNXRuntime in a single CPU thread,\\nsingle GPU stream on NVIDIA RTX2060S 8GB.\\nNot a production-like setup. Synthetic inputs.\\nModel throughput only, no data preparation.\\nPerformance vary depending on the chosen\\noptimizations and hyperparameters.\", fontsize=10)\nplt.savefig(\"runtime_scaling.pdf\", bbox_inches=\"tight\")\nplt.savefig(\"runtime_scaling.png\", bbox_inches=\"tight\", dpi=300)",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 3))\nax = plt.axes()\nmplhep.cms.label(\"Preliminary\", data=False, loc=0, rlabel=\"Run 3 (14 TeV)\")\n\nplt.plot(time_x, gpu_mem_use, marker=\".\")\nplt.axvline(np.mean(nelem)-np.std(nelem), color=\"black\", ls=\"--\", lw=1.0)\nplt.axvline(np.mean(nelem)+np.std(nelem), color=\"black\", ls=\"--\", lw=1.0)\n#plt.xticks(time_x, time_x);\nplt.xlim(0,30000)\nplt.ylim(0,3000)\nplt.ylabel(\"GPU RSS [MB]\")\nplt.xlabel(\"PFElements per event\")\n#cms_label(ax, y=0.93, x1=0.07, x2=0.99)\nplt.text(4000, 1000, \"typical Run3 range\", rotation=90, fontsize=10)\nplt.text(6000, 1400, \"Inference with ONNXRuntime in a single CPU thread,\\nsingle GPU stream on NVIDIA RTX2060S 8GB.\\nNot a production-like setup. Synthetic inputs.\\nModel throughput only, no data preparation.\\nPerformance vary depending on the chosen\\noptimizations and hyperparameters.\", fontsize=10)\nplt.savefig(\"memory_scaling.pdf\", bbox_inches=\"tight\")\nplt.savefig(\"memory_scaling.png\", bbox_inches=\"tight\", dpi=300)",
"_____no_output_____"
],
[
"def get_cputime(infile):\n times = {}\n for line in open(infile).readlines():\n if \"TimeModule\" in line:\n module = line.split()[4]\n time = float(line.split()[5])\n if not module in times:\n times[module] = []\n times[module].append(time)\n for k in times.keys():\n times[k] = 1000.0*np.array(times[k])\n return times",
"_____no_output_____"
],
[
"cputime_baseline = get_cputime(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.0/times.txt\")\ncputime_mlpf = get_cputime(\"/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.13/times.txt\")",
"_____no_output_____"
],
[
"np.mean(cputime_baseline[\"PFBlockProducer\"]+ cputime_baseline[\"PFProducer\"])",
"_____no_output_____"
],
[
"np.std(cputime_baseline[\"PFBlockProducer\"]+ cputime_baseline[\"PFProducer\"])",
"_____no_output_____"
],
[
"np.mean(cputime_mlpf[\"MLPFProducer\"])",
"_____no_output_____"
],
[
"np.std(cputime_mlpf[\"MLPFProducer\"])",
"_____no_output_____"
],
[
"plt.hist(cputime_baseline[\"PFBlockProducer\"]+ cputime_baseline[\"PFProducer\"], bins=np.linspace(0,500,100), label=\"baseline PF\")\nplt.hist(cputime_mlpf[\"MLPFProducer\"], bins=np.linspace(0,500,100), label=\"MLPF\");",
"_____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"
]
] |
4aada26092ae8eb8a5018c7421a9e731906ab4b0
| 21,332 |
ipynb
|
Jupyter Notebook
|
Give Life_ Predict Blood Donations/notebook.ipynb
|
Feliren88/DataCamp_projects
|
2b6fb9e6df698c6d0f998497abdd7373c1107a4c
|
[
"Apache-2.0"
] | 1 |
2020-04-07T17:59:13.000Z
|
2020-04-07T17:59:13.000Z
|
Give Life_ Predict Blood Donations/notebook.ipynb
|
Feliren88/DataCamp_projects
|
2b6fb9e6df698c6d0f998497abdd7373c1107a4c
|
[
"Apache-2.0"
] | null | null | null |
Give Life_ Predict Blood Donations/notebook.ipynb
|
Feliren88/DataCamp_projects
|
2b6fb9e6df698c6d0f998497abdd7373c1107a4c
|
[
"Apache-2.0"
] | null | null | null | 21,332 | 21,332 | 0.66126 |
[
[
[
"## 1. Inspecting transfusion.data file\n<p><img src=\"https://assets.datacamp.com/production/project_646/img/blood_donation.png\" style=\"float: right;\" alt=\"A pictogram of a blood bag with blood donation written in it\" width=\"200\"></p>\n<p>Blood transfusion saves lives - from replacing lost blood during major surgery or a serious injury to treating various illnesses and blood disorders. Ensuring that there's enough blood in supply whenever needed is a serious challenge for the health professionals. According to <a href=\"https://www.webmd.com/a-to-z-guides/blood-transfusion-what-to-know#1\">WebMD</a>, \"about 5 million Americans need a blood transfusion every year\".</p>\n<p>Our dataset is from a mobile blood donation vehicle in Taiwan. The Blood Transfusion Service Center drives to different universities and collects blood as part of a blood drive. We want to predict whether or not a donor will give blood the next time the vehicle comes to campus.</p>\n<p>The data is stored in <code>datasets/transfusion.data</code> and it is structured according to RFMTC marketing model (a variation of RFM). We'll explore what that means later in this notebook. First, let's inspect the data.</p>",
"_____no_output_____"
]
],
[
[
"# Print out the first 5 lines from the transfusion.data file\n!head -n 5 datasets/transfusion.data",
"Recency (months),Frequency (times),Monetary (c.c. blood),Time (months),\"whether he/she donated blood in March 2007\"\r\r\n2 ,50,12500,98 ,1\r\r\n0 ,13,3250,28 ,1\r\r\n1 ,16,4000,35 ,1\r\r\n2 ,20,5000,45 ,1\r\r\n"
]
],
[
[
"## 2. Loading the blood donations data\n<p>We now know that we are working with a typical CSV file (i.e., the delimiter is <code>,</code>, etc.). We proceed to loading the data into memory.</p>",
"_____no_output_____"
]
],
[
[
"# Import pandas\nimport pandas as pd\n\n# Read in dataset\ntransfusion = pd.read_csv('datasets/transfusion.data')\n\n# Print out the first rows of our dataset\ntransfusion.head()",
"_____no_output_____"
]
],
[
[
"## 3. Inspecting transfusion DataFrame\n<p>Let's briefly return to our discussion of RFM model. RFM stands for Recency, Frequency and Monetary Value and it is commonly used in marketing for identifying your best customers. In our case, our customers are blood donors.</p>\n<p>RFMTC is a variation of the RFM model. Below is a description of what each column means in our dataset:</p>\n<ul>\n<li>R (Recency - months since the last donation)</li>\n<li>F (Frequency - total number of donation)</li>\n<li>M (Monetary - total blood donated in c.c.)</li>\n<li>T (Time - months since the first donation)</li>\n<li>a binary variable representing whether he/she donated blood in March 2007 (1 stands for donating blood; 0 stands for not donating blood)</li>\n</ul>\n<p>It looks like every column in our DataFrame has the numeric type, which is exactly what we want when building a machine learning model. Let's verify our hypothesis.</p>",
"_____no_output_____"
]
],
[
[
"# Print a concise summary of transfusion DataFrame\ntransfusion.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 748 entries, 0 to 747\nData columns (total 5 columns):\nRecency (months) 748 non-null int64\nFrequency (times) 748 non-null int64\nMonetary (c.c. blood) 748 non-null int64\nTime (months) 748 non-null int64\nwhether he/she donated blood in March 2007 748 non-null int64\ndtypes: int64(5)\nmemory usage: 29.3 KB\n"
]
],
[
[
"## 4. Creating target column\n<p>We are aiming to predict the value in <code>whether he/she donated blood in March 2007</code> column. Let's rename this it to <code>target</code> so that it's more convenient to work with.</p>",
"_____no_output_____"
]
],
[
[
"# Rename target column as 'target' for brevity \ntransfusion.rename(\n columns={'whether he/she donated blood in March 2007':'target'},\n inplace=True\n)\n\n# Print out the first 2 rows\ntransfusion.head(2)",
"_____no_output_____"
]
],
[
[
"## 5. Checking target incidence\n<p>We want to predict whether or not the same donor will give blood the next time the vehicle comes to campus. The model for this is a binary classifier, meaning that there are only 2 possible outcomes:</p>\n<ul>\n<li><code>0</code> - the donor will not give blood</li>\n<li><code>1</code> - the donor will give blood</li>\n</ul>\n<p>Target incidence is defined as the number of cases of each individual target value in a dataset. That is, how many 0s in the target column compared to how many 1s? Target incidence gives us an idea of how balanced (or imbalanced) is our dataset.</p>",
"_____no_output_____"
]
],
[
[
"# Print target incidence proportions, rounding output to 3 decimal places\ntransfusion.target.value_counts(normalize=True).round(3)",
"_____no_output_____"
]
],
[
[
"## 6. Splitting transfusion into train and test datasets\n<p>We'll now use <code>train_test_split()</code> method to split <code>transfusion</code> DataFrame.</p>\n<p>Target incidence informed us that in our dataset <code>0</code>s appear 76% of the time. We want to keep the same structure in train and test datasets, i.e., both datasets must have 0 target incidence of 76%. This is very easy to do using the <code>train_test_split()</code> method from the <code>scikit learn</code> library - all we need to do is specify the <code>stratify</code> parameter. In our case, we'll stratify on the <code>target</code> column.</p>",
"_____no_output_____"
]
],
[
[
"# Import train_test_split method\nfrom sklearn.model_selection import train_test_split\n\n# Split transfusion DataFrame into\n# X_train, X_test, y_train and y_test datasets,\n# stratifying on the `target` column\nX_train, X_test, y_train, y_test = train_test_split(\n transfusion.drop(columns='target'),\n transfusion.target,\n test_size=0.25,\n random_state=42,\n stratify=transfusion.target\n)\n\n# Print out the first 2 rows of X_train\nX_train.head(2)",
"_____no_output_____"
]
],
[
[
"## 7. Selecting model using TPOT\n<p><a href=\"https://github.com/EpistasisLab/tpot\">TPOT</a> is a Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming.</p>\n<p><img src=\"https://assets.datacamp.com/production/project_646/img/tpot-ml-pipeline.png\" alt=\"TPOT Machine Learning Pipeline\"></p>\n<p>TPOT will automatically explore hundreds of possible pipelines to find the best one for our dataset. Note, the outcome of this search will be a <a href=\"https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html\">scikit-learn pipeline</a>, meaning it will include any pre-processing steps as well as the model.</p>\n<p>We are using TPOT to help us zero in on one model that we can then explore and optimize further.</p>",
"_____no_output_____"
]
],
[
[
"# Import TPOTClassifier and roc_auc_score\nfrom tpot import TPOTClassifier\nfrom sklearn.metrics import roc_auc_score\n\n# Instantiate TPOTClassifier\ntpot = TPOTClassifier(\n generations=5,\n population_size=20,\n verbosity=2,\n scoring='roc_auc',\n random_state=42,\n disable_update_check=True,\n config_dict='TPOT light'\n)\ntpot.fit(X_train, y_train)\n\n# AUC score for tpot model\ntpot_auc_score = roc_auc_score(y_test, tpot.predict_proba(X_test)[:, 1])\nprint(f'\\nAUC score: {tpot_auc_score:.4f}')\n\n# Print best pipeline steps\nprint('\\nBest pipeline steps:', end='\\n')\nfor idx, (name, transform) in enumerate(tpot.fitted_pipeline_.steps, start=1):\n # Print idx and transform\n print(f'{idx}. {transform}')",
"_____no_output_____"
]
],
[
[
"## 8. Checking the variance\n<p>TPOT picked <code>LogisticRegression</code> as the best model for our dataset with no pre-processing steps, giving us the AUC score of 0.7850. This is a great starting point. Let's see if we can make it better.</p>\n<p>One of the assumptions for linear regression models is that the data and the features we are giving it are related in a linear fashion, or can be measured with a linear distance metric. If a feature in our dataset has a high variance that's an order of magnitude or more greater than the other features, this could impact the model's ability to learn from other features in the dataset.</p>\n<p>Correcting for high variance is called normalization. It is one of the possible transformations you do before training a model. Let's check the variance to see if such transformation is needed.</p>",
"_____no_output_____"
]
],
[
[
"# X_train's variance, rounding the output to 3 decimal places\nX_train.var().round(3)",
"_____no_output_____"
]
],
[
[
"## 9. Log normalization\n<p><code>Monetary (c.c. blood)</code>'s variance is very high in comparison to any other column in the dataset. This means that, unless accounted for, this feature may get more weight by the model (i.e., be seen as more important) than any other feature.</p>\n<p>One way to correct for high variance is to use log normalization.</p>",
"_____no_output_____"
]
],
[
[
"# Import numpy\nimport numpy as np\n\n# Copy X_train and X_test into X_train_normed and X_test_normed\nX_train_normed, X_test_normed = X_train.copy(), X_test.copy()\n\n# Specify which column to normalize\ncol_to_normalize = 'Monetary (c.c. blood)'\n\n# Log normalization\nfor df_ in [X_train_normed, X_test_normed]:\n # Add log normalized column\n df_['monetary_log'] = np.log(df_[col_to_normalize])\n # Drop the original column\n df_.drop(columns=col_to_normalize, inplace=True)\n\n# Check the variance for X_train_normed\nX_train_normed.var().round(3)",
"_____no_output_____"
]
],
[
[
"## 10. Training the linear regression model\n<p>The variance looks much better now. Notice that now <code>Time (months)</code> has the largest variance, but it's not the <a href=\"https://en.wikipedia.org/wiki/Order_of_magnitude\">orders of magnitude</a> higher than the rest of the variables, so we'll leave it as is.</p>\n<p>We are now ready to train the linear regression model.</p>",
"_____no_output_____"
]
],
[
[
"# Importing modules\nfrom sklearn import linear_model.LogisticRegression\n\n# Instantiate LogisticRegression\nlogreg = LogisticRegression(\n solver='liblinear',\n random_state=42\n)\n\n# Train the model\nfit(X_train_normed, y_train)\n\n# AUC score for tpot model\nlogreg_auc_score = roc_auc_score(y_test, logreg.predict_proba(X_test_normed)[:, 1])\nprint(f'\\nAUC score: {logreg_auc_score:.4f}')",
"_____no_output_____"
]
],
[
[
"## 11. Conclusion\n<p>The demand for blood fluctuates throughout the year. As one <a href=\"https://www.kjrh.com/news/local-news/red-cross-in-blood-donation-crisis\">prominent</a> example, blood donations slow down during busy holiday seasons. An accurate forecast for the future supply of blood allows for an appropriate action to be taken ahead of time and therefore saving more lives.</p>\n<p>In this notebook, we explored automatic model selection using TPOT and AUC score we got was 0.7850. This is better than simply choosing <code>0</code> all the time (the target incidence suggests that such a model would have 76% success rate). We then log normalized our training data and improved the AUC score by 0.5%. In the field of machine learning, even small improvements in accuracy can be important, depending on the purpose.</p>\n<p>Another benefit of using logistic regression model is that it is interpretable. We can analyze how much of the variance in the response variable (<code>target</code>) can be explained by other variables in our dataset.</p>",
"_____no_output_____"
]
],
[
[
"# Importing itemgetter\nfrom operator import itemgetter\n\n# Sort models based on their AUC score from highest to lowest\nsorted(\n [('tpot', tpot_auc_score), ('logreg', logreg_auc_score)],\n key=itemgetter(1),\n reverse=True \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"
]
] |
4aadbcb2bf4698de097a181b4ad8eb668a6fc8d1
| 14,266 |
ipynb
|
Jupyter Notebook
|
Data Structures/Arrays and Linked List/linked_lists/Implementing and traversing a linked list.ipynb
|
michal0janczyk/udacity_data_structures_and_algorithms_nanodegree
|
3ec4bb94158d4dee59056703e63cb0fab07cb18c
|
[
"Unlicense"
] | null | null | null |
Data Structures/Arrays and Linked List/linked_lists/Implementing and traversing a linked list.ipynb
|
michal0janczyk/udacity_data_structures_and_algorithms_nanodegree
|
3ec4bb94158d4dee59056703e63cb0fab07cb18c
|
[
"Unlicense"
] | null | null | null |
Data Structures/Arrays and Linked List/linked_lists/Implementing and traversing a linked list.ipynb
|
michal0janczyk/udacity_data_structures_and_algorithms_nanodegree
|
3ec4bb94158d4dee59056703e63cb0fab07cb18c
|
[
"Unlicense"
] | null | null | null | 26.665421 | 241 | 0.560774 |
[
[
[
"# Implementing and traversing a linked list\n\nIn this notebook we'll get some practice implementing a basic linked list—something like this: \n\n<img style=\"float: left;\" src=\"assets/linked_list_head_none.png\">\n",
"_____no_output_____"
],
[
"**Note** - This notebook contains a few audio walkthroughs of the code cells. <font color=\"red\">If you face difficulty in listening to the audio, try reconnecting your audio headsets, and use either Chrome or Firefox browser.</font> ",
"_____no_output_____"
],
[
"## Key characteristics\n\nFirst, let's review the overall abstract concepts for this data structure. To get started, click the walkthrough button below.",
"_____no_output_____"
],
[
"<span class=\"graffiti-highlight graffiti-id_fx1ii1b-id_p4ecakd\"><i></i><button>Walkthrough</button></span>",
"_____no_output_____"
],
[
"## Exercise 1 - Implementing a simple linked list",
"_____no_output_____"
],
[
"Now that we've talked about the abstract characteristics that we want our linked list to have, let's look at how we might implement one in Python.",
"_____no_output_____"
],
[
"<span class=\"graffiti-highlight graffiti-id_rytkj5r-id_b4xxfs5\"><i></i><button>Walkthrough</button></span>",
"_____no_output_____"
],
[
"#### Step 1. Once you've seen the walkthrough, give it a try for yourself:\n* Create a `Node` class with `value` and `next` attributes\n* Use the class to create the `head` node with the value `2`\n* Create and link a second node containing the value `1`\n* Try printing the values (`1` and `2`) on the nodes you created (to make sure that you can access them!)",
"_____no_output_____"
],
[
"<span class=\"graffiti-highlight graffiti-id_jnw1zp8-id_uu0moco\"><i></i><button>Show Solution</button></span>",
"_____no_output_____"
],
[
"At this point, our linked list looks like this: \n\n<img style=\"float: left;\" src=\"assets/linked_list_two_nodes.png\">",
"_____no_output_____"
],
[
"Our goal is to extend the list until it looks like this:\n\n<img style=\"float: left;\" src=\"assets/linked_list_head_none.png\">",
"_____no_output_____"
],
[
"To do this, we need to create three more nodes, and we need to attach each one to the `next` attribute of the node that comes before it. Notice that we don't have a direct reference to any of the nodes other than the `head` node!\n\nSee if you can write the code to finish creating the above list:\n\n#### Step 2. Add three more nodes to the list, with the values `4`, `3`, and `5`",
"_____no_output_____"
],
[
"<span class=\"graffiti-highlight graffiti-id_2ptxe7t-id_6dz27pa\"><i></i><button>Show Solution</button></span>",
"_____no_output_____"
],
[
"Let's print the values of all the nodes to check if it worked. If you successfully created (and linked) all the nodes, the following should print out `2`, `1`, `4`, `3`, `5`:",
"_____no_output_____"
]
],
[
[
"print(head.value)\nprint(head.next.value)\nprint(head.next.next.value)\nprint(head.next.next.next.value)\nprint(head.next.next.next.next.value)",
"_____no_output_____"
]
],
[
[
"## Exercise 2 - Traversing the list",
"_____no_output_____"
],
[
"We successfully created a simple linked list. But printing all the values like we did above was pretty tedious. What if we had a list with 1,000 nodes? \n\nLet's see how we might traverse the list and print all the values, no matter how long it might be.",
"_____no_output_____"
],
[
"<span class=\"graffiti-highlight graffiti-id_fgyadie-id_g9gdx9q\"><i></i><button>Walkthrough</button></span>",
"_____no_output_____"
],
[
"Once you've seen the walkthrough, give it a try for yourself.\n#### Step 3. Write a function that loops through the nodes of the list and prints all of the values",
"_____no_output_____"
],
[
"<span class=\"graffiti-highlight graffiti-id_oc8545r-id_rhj3m0h\"><i></i><button>Show Solution</button></span>",
"_____no_output_____"
],
[
"## Creating a linked list using iteration",
"_____no_output_____"
],
[
"Previously, we created a linked list using a very manual and tedious method. We called `next` multiple times on our `head` node. \n\nNow that we know about iterating over or traversing the linked list, is there a way we can use that to create a linked list?\n\nWe've provided our solution below—but it might be a good exercise to see what you can come up with first. Here's the goal:\n\n#### Step 4. See if you can write the code for the `create_linked_list` function below\n* The function should take a Python list of values as input and return the `head` of a linked list that has those values\n* There's some test code, and also a solution, below—give it a try for yourself first, but don't hesitate to look over the solution if you get stuck",
"_____no_output_____"
]
],
[
[
"def create_linked_list(input_list):\n \"\"\"\n Function to create a linked list\n @param input_list: a list of integers\n @return: head node of the linked list\n \"\"\"\n head = None\n return head",
"_____no_output_____"
]
],
[
[
"Test your function by running this cell:",
"_____no_output_____"
]
],
[
[
"### Test Code\ndef test_function(input_list, head):\n try:\n if len(input_list) == 0:\n if head is not None:\n print(\"Fail\")\n return\n for value in input_list:\n if head.value != value:\n print(\"Fail\")\n return\n else:\n head = head.next\n print(\"Pass\")\n except Exception as e:\n print(\"Fail: \" + e)\n \n \n\ninput_list = [1, 2, 3, 4, 5, 6]\nhead = create_linked_list(input_list)\ntest_function(input_list, head)\n\ninput_list = [1]\nhead = create_linked_list(input_list)\ntest_function(input_list, head)\n\ninput_list = []\nhead = create_linked_list(input_list)\ntest_function(input_list, head)\n",
"_____no_output_____"
]
],
[
[
"Below is one possible solution. Walk through the code and make sure you understand what each part does. Compare it to your own solution—did your code work similarly or did you take a different approach?",
"_____no_output_____"
],
[
"<span class=\"graffiti-highlight graffiti-id_y5x3zt8-id_2txpe86\"><i></i><button>Hide Solution</button></span>",
"_____no_output_____"
]
],
[
[
"def create_linked_list(input_list):\n head = None\n for value in input_list:\n if head is None:\n head = Node(value) \n else:\n # Move to the tail (the last node)\n current_node = head\n while current_node.next:\n current_node = current_node.next\n \n current_node.next = Node(value)\n return head",
"_____no_output_____"
]
],
[
[
"### A more efficient solution\n\nThe above solution works, but it has some shortcomings. In this next walkthrough, we'll demonstrate a different approach and see how its efficiency compares to the solution above.",
"_____no_output_____"
],
[
"<span class=\"graffiti-highlight graffiti-id_ef8aj0i-id_uy9snfg\"><i></i><button>Walkthrough</button></span>",
"_____no_output_____"
],
[
"#### Step 5. Once you've seen the walkthrough, see if you can implement the more efficient version for yourself",
"_____no_output_____"
]
],
[
[
"def create_linked_list_better(input_list):\n head = None\n # TODO: Implement the more efficient version that keeps track of the tail\n return head",
"_____no_output_____"
],
[
"### Test Code\ndef test_function(input_list, head):\n try:\n if len(input_list) == 0:\n if head is not None:\n print(\"Fail\")\n return\n for value in input_list:\n if head.value != value:\n print(\"Fail\")\n return\n else:\n head = head.next\n print(\"Pass\")\n except Exception as e:\n print(\"Fail: \" + e)\n \n \n\ninput_list = [1, 2, 3, 4, 5, 6]\nhead = create_linked_list_better(input_list)\ntest_function(input_list, head)\n\ninput_list = [1]\nhead = create_linked_list_better(input_list)\ntest_function(input_list, head)\n\ninput_list = []\nhead = create_linked_list_better(input_list)\ntest_function(input_list, head)",
"Pass\nPass\nPass\n"
]
],
[
[
"<span class=\"graffiti-highlight graffiti-id_lkzu4kb-id_vxxcdfn\"><i></i><button>Show Solution</button></span>",
"_____no_output_____"
]
]
] |
[
"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"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4aadcbefaf9fad8f8fea0a9dfc34006875af7364
| 24,797 |
ipynb
|
Jupyter Notebook
|
football-predictions/notebooks/s.o-data-preprocessing.ipynb
|
samie-hash/data-science-repo
|
574ebad704e3f2ebce18f573af87cd95571b4cc9
|
[
"MIT"
] | null | null | null |
football-predictions/notebooks/s.o-data-preprocessing.ipynb
|
samie-hash/data-science-repo
|
574ebad704e3f2ebce18f573af87cd95571b4cc9
|
[
"MIT"
] | null | null | null |
football-predictions/notebooks/s.o-data-preprocessing.ipynb
|
samie-hash/data-science-repo
|
574ebad704e3f2ebce18f573af87cd95571b4cc9
|
[
"MIT"
] | null | null | null | 30.957553 | 118 | 0.326733 |
[
[
[
"# Data Preprocessing",
"_____no_output_____"
]
],
[
[
"import string\nimport pandas as pd\n\nimport src.features.build_features as buif\nfrom src.utils import utils, config",
"_____no_output_____"
],
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"PATH = '../data/raw'\nfootball = utils.load_merge_data(path=PATH, keep='E0', usecols=config.TRAIN_COLUMNS, seasons=6) # Last 6 seasons",
"_____no_output_____"
],
[
"football.tail()",
"_____no_output_____"
],
[
"football.head()",
"_____no_output_____"
],
[
"football.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1900 entries, 0 to 1899\nData columns (total 24 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Div 1900 non-null object\n 1 Date 1900 non-null object\n 2 HomeTeam 1900 non-null object\n 3 AwayTeam 1900 non-null object\n 4 FTHG 1900 non-null object\n 5 FTAG 1900 non-null object\n 6 FTR 1900 non-null object\n 7 HTHG 1900 non-null object\n 8 HTAG 1900 non-null object\n 9 HTR 1900 non-null object\n 10 Referee 1900 non-null object\n 11 HS 1900 non-null object\n 12 AS 1900 non-null object\n 13 HST 1900 non-null object\n 14 AST 1900 non-null object\n 15 HF 1900 non-null object\n 16 AF 1900 non-null object\n 17 HC 1900 non-null object\n 18 AC 1900 non-null object\n 19 HY 1900 non-null object\n 20 AY 1900 non-null object\n 21 HR 1900 non-null object\n 22 AR 1900 non-null object\n 23 SeasonLabel 1900 non-null object\ndtypes: object(24)\nmemory usage: 356.4+ KB\n"
],
[
"preprocessor = buif.Preprocessor() # preprocessor transformer\nprocessed_data = preprocessor.fit_transform(football)\nprocessed_data.head()",
"_____no_output_____"
],
[
"processed_data.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1900 entries, 0 to 1899\nData columns (total 24 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Div 1900 non-null object \n 1 Date 1900 non-null datetime64[ns]\n 2 HomeTeam 1900 non-null object \n 3 AwayTeam 1900 non-null object \n 4 FTHG 1900 non-null int64 \n 5 FTAG 1900 non-null int64 \n 6 FTR 1900 non-null object \n 7 HTHG 1900 non-null int64 \n 8 HTAG 1900 non-null int64 \n 9 HTR 1900 non-null object \n 10 Referee 1900 non-null object \n 11 HS 1900 non-null int64 \n 12 AS 1900 non-null int64 \n 13 HST 1900 non-null int64 \n 14 AST 1900 non-null int64 \n 15 HF 1900 non-null int64 \n 16 AF 1900 non-null int64 \n 17 HC 1900 non-null int64 \n 18 AC 1900 non-null int64 \n 19 HY 1900 non-null int64 \n 20 AY 1900 non-null int64 \n 21 HR 1900 non-null int64 \n 22 AR 1900 non-null int64 \n 23 SeasonLabel 1900 non-null object \ndtypes: datetime64[ns](1), int64(16), object(7)\nmemory usage: 356.4+ KB\n"
],
[
"# Save processed file to interim\nFILE_PATH = '../data/interim/eo_football_interim'\nprocessed_data.to_csv(FILE_PATH, index=None)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aadd1e805cf2108f574abfe2b66b0c9fd42a811
| 44,372 |
ipynb
|
Jupyter Notebook
|
TVBR_Instacart_25%-Copy6.ipynb
|
mengzaiqiao/TVBR
|
cdac86a753c41f8f3c55a025be8d88dd305325f5
|
[
"MIT"
] | null | null | null |
TVBR_Instacart_25%-Copy6.ipynb
|
mengzaiqiao/TVBR
|
cdac86a753c41f8f3c55a025be8d88dd305325f5
|
[
"MIT"
] | null | null | null |
TVBR_Instacart_25%-Copy6.ipynb
|
mengzaiqiao/TVBR
|
cdac86a753c41f8f3c55a025be8d88dd305325f5
|
[
"MIT"
] | null | null | null | 67.640244 | 342 | 0.465203 |
[
[
[
"### Install Beta-recsys",
"_____no_output_____"
],
[
"## Loading dataset",
"_____no_output_____"
]
],
[
[
"import sys\n\nsys.path.append(\"../\")\n\nimport random\n\nimport numpy as np\n\nfrom beta_rec.data.grocery_data import GroceryData\nfrom beta_rec.datasets.instacart import Instacart_25\n\nseed = 2021\nrandom.seed(seed) # Fix random seeds for reproducibility\nnp.random.seed(seed)\n\n# make sure that you have already download the Instacart data from this link: https://www.kaggle.com/c/instacart-market-basket-analysis#\n# uncompressed them and put them in this folder: ../datasets/instacart_25/raw/*.csv\n\n\ndataset = Instacart_25(\n min_u_c=20, min_i_c=30, min_o_c=10\n) # Specifying the filtering conditions.\n\n# Split the data\nsplit_dataset = dataset.load_temporal_basket_split(test_rate=0.2, n_test=10)\ndata = GroceryData(split_dataset)",
"--------------------------------------------------------------------------------\nLoaded training set statistics\n+---------+------------+------------+--------------+-----------------+-------------+\n| | col_user | col_item | col_rating | col_timestamp | col_order |\n|---------+------------+------------+--------------+-----------------+-------------|\n| count | 3857794 | 3857794 | 3857794 | 3857794 | 3857794 |\n| nunique | 23093 | 14565 | 1 | 3857794 | 373719 |\n+---------+------------+------------+--------------+-----------------+-------------+\nvalid_data_0 statistics\n+---------+------------+------------+--------------+-----------------+\n| | col_user | col_item | col_rating | col_timestamp |\n|---------+------------+------------+--------------+-----------------|\n| count | 3076168 | 3076168 | 3076168 | 3076168 |\n| nunique | 22475 | 14565 | 2 | 1 |\n+---------+------------+------------+--------------+-----------------+\ntest_data_0 statistics\n+---------+------------+------------+--------------+-----------------+\n| | col_user | col_item | col_rating | col_timestamp |\n|---------+------------+------------+--------------+-----------------|\n| count | 3072601 | 3072601 | 3072601 | 3072601 |\n| nunique | 22434 | 14565 | 2 | 1 |\n+---------+------------+------------+--------------+-----------------+\n--------------------------------------------------------------------------------\nAfter intersection, testing set [0] statistics\n+---------+------------+------------+--------------+-----------------+\n| | col_user | col_item | col_rating | col_timestamp |\n|---------+------------+------------+--------------+-----------------|\n| count | 3072601 | 3072601 | 3072601 | 3072601 |\n| nunique | 22434 | 14565 | 2 | 1 |\n+---------+------------+------------+--------------+-----------------+\nAfter intersection, validation set [0] statistics\n+---------+------------+------------+--------------+-----------------+\n| | col_user | col_item | col_rating | col_timestamp |\n|---------+------------+------------+--------------+-----------------|\n| count | 3076168 | 3076168 | 3076168 | 3076168 |\n| nunique | 22475 | 14565 | 2 | 1 |\n+---------+------------+------------+--------------+-----------------+\nFilling alias table\nFilling alias table\nExecute [__init__] method costing 84367.53 ms\nExecute [__init__] method costing 0.00 ms\n"
]
],
[
[
"### Model config",
"_____no_output_____"
]
],
[
[
"config = {\"config_file\": \"../configs/tvbr_default.json\"}\nconfig[\"n_sample\"] = 1000000 # To reduce the test running time\nconfig[\"max_epoch\"] = 80\nconfig[\"emb_dim\"] = 64\nconfig[\"time_step\"] = 50\nconfig[\"batch_size\"] = 2048\n# config[\"tunable\"] = [\n# {\"name\": \"lr\", \"type\": \"choice\", \"values\": [0.5, 0.05, 0.025, 0.001, 0.005]},\n# ]\n# config[\"tune\"] = True\n# the 'config_file' key is required, that is used load a default config.\n# Other keys can be specified to replace the default settings.",
"_____no_output_____"
]
],
[
[
"### Model intialization and training",
"_____no_output_____"
]
],
[
[
"from beta_rec.recommenders import TVBR\n\nfor item_fea_type in [\n \"random\",\n \"cate\",\n \"cate_word2vec\",\n \"cate_bert\",\n \"cate_one_hot\",\n \"random_word2vec\",\n \"random_bert\",\n# \"random_one_hot\",\n# \"random_bert_word2vec_one_hot\",\n# \"random_cate_word2vec\",\n# \"random_cate_bert\",\n# \"random_cate_one_hot\",\n# \"random_cate_bert_word2vec_one_hot\",\n]:\n config[\"item_fea_type\"] = item_fea_type\n lr = 0.001\n time_step = 20\n config[\"lr\"] = lr\n config[\"time_step\"] = time_step\n config[\"root_dir\"] = \"/home/zm324/workspace/beta-recsys/\"\n config[\"dataset\"] = \"instacart_25\"\n model = TVBR(config)\n model.train(data)\n model.test(data.test)\n # @To be discussed\n# model.train(train_df)\n# Case 1, without validation, stop training by loss or max_epoch\n\n# model.train(train_df,valid_df[0])\n# Case 2, with validation, stop training by performance on validation set\n\n# model.train(train_df,valid_df[0],test_df[0])\n# Case 3, same as Case 2, but also evaluate performance for each epoch on test set.\n\n# Note that the best model will be save automatically, and record the model-save-dir.",
"Search default config file in /home/zm324/anaconda3/envs/beta_rec/configs/tvbr_default.json\nFound default config file in /home/zm324/anaconda3/envs/beta_rec/configs/tvbr_default.json\nloading config file /home/zm324/anaconda3/envs/beta_rec/configs/tvbr_default.json\n--------------------------------------------------------------------------------\nReceived parameters from command line (or default):\n+----+-----------------------+------------------------------------+\n| | keys | values |\n|----+-----------------------+------------------------------------|\n| 0 | system:root_dir | /home/zm324/workspace/beta-recsys/ |\n| 1 | model:n_sample | 1000000 |\n| 2 | model:max_epoch | 80 |\n| 3 | model:emb_dim | 64 |\n| 4 | model:time_step | 20 |\n| 5 | model:batch_size | 2048 |\n| 6 | model:lr | 0.001 |\n| 7 | dataset:item_fea_type | random |\n| 8 | dataset:dataset | instacart_25 |\n+----+-----------------------+------------------------------------+\n--------------------------------------------------------------------------------\nlogs will save in file: /home/zm324/workspace/beta-recsys/logs/TVBR_default_20211212_123804_murihu .stdout.log .stderr.log\n2021-12-12 12:38:04 [INFO]-\nPython version: 3.8.5 (default, Sep 4 2020, 07:30:14) \n[GCC 7.3.0\n2021-12-12 12:38:04 [INFO]-\n2021-12-12 12:38:04 [INFO]-Pytorch version: 1.7.1\n2021-12-12 12:38:04 [INFO]-The intermediate running statuses will be reported in folder: /home/zm324/workspace/beta-recsys/runs/TVBR_default_20211212_123804_murihu\n2021-12-12 12:38:04 [INFO]-Model checkpoint will save in file: /home/zm324/workspace/beta-recsys/checkpoints/TVBR_default_20211212_123804_murihu\n2021-12-12 12:38:04 [INFO]-Performance result will save in file: /home/zm324/workspace/beta-recsys/results/tvbr_result.csv\n2021-12-12 12:38:04 [INFO]---------------------------------------------------------------------------------\n2021-12-12 12:38:04 [INFO]-System configs\n2021-12-12 12:38:04 [INFO]-\n+----+----------------+-----------------------------------------------------------------------------------+\n| | keys | values |\n|----+----------------+-----------------------------------------------------------------------------------|\n| 0 | root_dir | /home/zm324/workspace/beta-recsys |\n| 1 | log_dir | logs/ |\n| 2 | result_dir | results/ |\n| 3 | process_dir | /home/zm324/workspace/beta-recsys/processes/ |\n| 4 | checkpoint_dir | checkpoints/ |\n| 5 | dataset_dir | datasets/ |\n| 6 | run_dir | /home/zm324/workspace/beta-recsys/runs/TVBR_default_20211212_123804_murihu |\n| 7 | tune_dir | /home/zm324/workspace/beta-recsys/tune_results/ |\n| 8 | device | gpu |\n| 9 | seed | 2020 |\n| 10 | metrics | ['ndcg', 'precision', 'recall', 'map'] |\n| 11 | k | [5, 10, 20] |\n| 12 | valid_metric | ndcg |\n| 13 | valid_k | 10 |\n| 14 | result_file | /home/zm324/workspace/beta-recsys/results/tvbr_result.csv |\n| 15 | save_mode | average |\n| 16 | model_run_id | TVBR_default_20211212_123804_murihu |\n| 17 | log_file | /home/zm324/workspace/beta-recsys/logs/TVBR_default_20211212_123804_murihu |\n| 18 | model_save_dir | /home/zm324/workspace/beta-recsys/checkpoints/TVBR_default_20211212_123804_murihu |\n+----+----------------+-----------------------------------------------------------------------------------\n2021-12-12 12:38:04 [INFO]-\n2021-12-12 12:38:04 [INFO]---------------------------------------------------------------------------------\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aadd32e2548f07458f04520124b858557b52d5d
| 6,176 |
ipynb
|
Jupyter Notebook
|
examples/Python/Advanced/pointcloud_outlier_removal.ipynb
|
sxcblh/Open3D
|
96f8470ca0a3ca358001800d91d72bcb97278d15
|
[
"MIT"
] | null | null | null |
examples/Python/Advanced/pointcloud_outlier_removal.ipynb
|
sxcblh/Open3D
|
96f8470ca0a3ca358001800d91d72bcb97278d15
|
[
"MIT"
] | null | null | null |
examples/Python/Advanced/pointcloud_outlier_removal.ipynb
|
sxcblh/Open3D
|
96f8470ca0a3ca358001800d91d72bcb97278d15
|
[
"MIT"
] | null | null | null | 34.892655 | 207 | 0.567034 |
[
[
[
"import open3d as o3d\nimport numpy as np\nimport os\nimport sys\n\n# monkey patches visualization and provides helpers to load geometries\nsys.path.append('..')\nimport open3d_tutorial as o3dtut\n# change to True if you want to interact with the visualization windows\no3dtut.interactive = not \"CI\" in os.environ",
"_____no_output_____"
]
],
[
[
"# Point cloud outlier removal\nWhen collecting data from scanning devices, the resulting point cloud tends to contain noise and artifacts that one would like to remove. This tutorial addresses the outlier removal features of Open3D.",
"_____no_output_____"
],
[
"## Prepare input data\nA point cloud is loaded and downsampled using `voxel_downsample`.",
"_____no_output_____"
]
],
[
[
"print(\"Load a ply point cloud, print it, and render it\")\npcd = o3d.io.read_point_cloud(\"../../TestData/ICP/cloud_bin_2.pcd\")\no3d.visualization.draw_geometries([pcd], zoom=0.3412, \n front=[0.4257, -0.2125, -0.8795],\n lookat=[2.6172, 2.0475, 1.532],\n up=[-0.0694, -0.9768, 0.2024])\n\nprint(\"Downsample the point cloud with a voxel of 0.02\")\nvoxel_down_pcd = pcd.voxel_down_sample(voxel_size=0.02)\no3d.visualization.draw_geometries([voxel_down_pcd], zoom=0.3412, \n front=[0.4257, -0.2125, -0.8795],\n lookat=[2.6172, 2.0475, 1.532],\n up=[-0.0694, -0.9768, 0.2024])",
"_____no_output_____"
]
],
[
[
"Alternatively, use `uniform_down_sample` to downsample the point cloud by collecting every n-th points.",
"_____no_output_____"
]
],
[
[
"print(\"Every 5th points are selected\")\nuni_down_pcd = pcd.uniform_down_sample(every_k_points=5)\no3d.visualization.draw_geometries([uni_down_pcd], zoom=0.3412, \n front=[0.4257, -0.2125, -0.8795],\n lookat=[2.6172, 2.0475, 1.532],\n up=[-0.0694, -0.9768, 0.2024])",
"_____no_output_____"
]
],
[
[
"## Select down sample\nThe following helper function uses `select_by_index`, which takes a binary mask to output only the selected points. The selected points and the non-selected points are visualized.",
"_____no_output_____"
]
],
[
[
"def display_inlier_outlier(cloud, ind):\n inlier_cloud = cloud.select_by_index(ind)\n outlier_cloud = cloud.select_by_index(ind, invert=True)\n\n print(\"Showing outliers (red) and inliers (gray): \")\n outlier_cloud.paint_uniform_color([1, 0, 0])\n inlier_cloud.paint_uniform_color([0.8, 0.8, 0.8])\n o3d.visualization.draw_geometries([inlier_cloud, outlier_cloud], \n zoom=0.3412, \n front=[0.4257, -0.2125, -0.8795],\n lookat=[2.6172, 2.0475, 1.532],\n up=[-0.0694, -0.9768, 0.2024])",
"_____no_output_____"
]
],
[
[
"## Statistical outlier removal\n`statistical_outlier_removal` removes points that are further away from their neighbors compared to the average for the point cloud. It takes two input parameters:\n\n- `nb_neighbors`, which specifies how many neighbors are taken into account in order to calculate the average distance for a given point.\n- `std_ratio`, which allows setting the threshold level based on the standard deviation of the average distances across the point cloud. The lower this number the more aggressive the filter will be.",
"_____no_output_____"
]
],
[
[
"print(\"Statistical oulier removal\")\ncl, ind = voxel_down_pcd.remove_statistical_outlier(nb_neighbors=20,\n std_ratio=2.0)\ndisplay_inlier_outlier(voxel_down_pcd, ind)",
"_____no_output_____"
]
],
[
[
"## Radius outlier removal\n`radius_outlier_removal` removes points that have few neighbors in a given sphere around them. Two parameters can be used to tune the filter to your data:\n\n- `nb_points`, which lets you pick the minimum amount of points that the sphere should contain.\n- `radius`, which defines the radius of the sphere that will be used for counting the neighbors.",
"_____no_output_____"
]
],
[
[
"print(\"Radius oulier removal\")\ncl, ind = voxel_down_pcd.remove_radius_outlier(nb_points=16, radius=0.05)\ndisplay_inlier_outlier(voxel_down_pcd, ind)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aadfd39398b9e9d0f45622c8c9f514cc90207e5
| 70,998 |
ipynb
|
Jupyter Notebook
|
12_01_quantum_spin_chain.ipynb
|
Price-L/Comp_Phys
|
40ec1ddf10dad0d7109fcb8845fe93b578027533
|
[
"MIT"
] | null | null | null |
12_01_quantum_spin_chain.ipynb
|
Price-L/Comp_Phys
|
40ec1ddf10dad0d7109fcb8845fe93b578027533
|
[
"MIT"
] | null | null | null |
12_01_quantum_spin_chain.ipynb
|
Price-L/Comp_Phys
|
40ec1ddf10dad0d7109fcb8845fe93b578027533
|
[
"MIT"
] | null | null | null | 51.634909 | 10,540 | 0.612383 |
[
[
[
"# Quantum Spins\n\nWe are going consider a magnetic insulator, \na Mott insulator. In this problem we have a valence electron per\natom, with very localized wave-functions. The Coulomb repulsion between\nelectrons on the same orbital is so strong, that electrons are bound to\ntheir host atom, and cannot move. For this reason, charge disappears\nfrom the equation, and the only remaining degree of freedom is the spin\nof the electrons. The corresponding local state can therefore be either\n$|\\uparrow\\rangle$ or $|\\downarrow\\rangle$. The only interaction taking\nplace is a process that “flips” two anti-aligned neighboring spins\n$|\\uparrow\\rangle|\\downarrow\\rangle \\rightarrow |\\downarrow\\rangle|\\uparrow\\rangle$.\n\nLet us now consider a collection of spins residing on site of a\n–one-dimensional for simplicity– lattice. An arbitrary state of\n$N$-spins can be described by using the $S^z$ projection\n($\\uparrow,\\downarrow$) of each spin as: $|s_1,s_2,..., s_N\\rangle$. As\nwe can easily see, there are $2^N$ of such configurations.\n\nLet us now consider a collection of spins residing on site of a\n–one-dimensional for simplicity– lattice. An arbitrary state of\n$N$-spins can be described by using the $S^z$ projection\n($\\uparrow,\\downarrow$) of each spin as: $|s_1,s_2,..., s_N\\rangle$. As\nwe can easily see, there are $2^N$ of such configurations.\n\nWe shall describe the interactions between neighboring spins using the\nso-called Heisenberg Hamiltonian:\n\n$$\\hat{H}=\\sum_{i=1}^{N-1} \\hat{\\mathbf{S}}_i \\cdot \\hat{\\mathbf{S}}_{i+1}\n$$\n\nwhere $\\hat{\\mathbf{S}}_i = (\\hat{S}^x,\\hat{S}^y,\\hat{S}^z)$ is the spin\noperator acting on the spin on site $i$.\n\nSince we are concerned about spins one-half, $S=1/2$, all these\noperators have a $2\\times2$ matrix representation, related to the\nwell-known Pauli matrices:\n\n$$S^z = \\left(\n\\begin{array}{cc}\n1/2 & 0 \\\\\n0 & -1/2\n\\end{array}\n\\right),\nS^x = \\left(\n\\begin{array}{cc}\n0 & 1/2 \\\\\n1/2 & 0\n\\end{array}\n\\right),\nS^y = \\left(\n\\begin{array}{cc}\n0 & -i/2 \\\\\ni/2 & 0\n\\end{array}\n\\right),\n$$\n\nThese matrices act on two-dimensional vectors defined by the basis\nstates $|\\uparrow\\rangle$ and $|\\downarrow\\rangle$. It is useful to\nintroduce the identities:\n$$\\hat{S}^\\pm = \\left(\\hat{S}^x \\pm i \\hat{S}^y\\right),$$ where $S^+$\nand $S^-$ are the spin raising and lowering operators. It is intuitively\neasy to see why by looking at how they act on the basis states:\n$\\hat{S}^+|\\downarrow\\rangle = |\\uparrow\\rangle$ and\n$\\hat{S}^-|\\uparrow\\rangle = |\\downarrow\\rangle$. Their corresponding\n$2\\times2$ matrix representations are: $$S^+ = \\left(\n\\begin{array}{cc}\n0 & 1 \\\\\n0 & 0\n\\end{array}\n\\right),\nS^- = \\left(\n\\begin{array}{cc}\n0 & 0 \\\\\n1 & 0\n\\end{array}\n\\right),\n$$\n\nWe can now re-write the Hamiltonian (\\[heisenberg\\]) as:\n$$\\hat{H}=\\sum_{i=1}^{N-1}\n\\hat{S}^z_i \\hat{S}^z_{i+1} +\n\\frac{1}{2}\\left[\n\\hat{S}^+_i \\hat{S}^-_{i+1} +\n\\hat{S}^-_i \\hat{S}^+_{i+1}\n\\right]\n$$ The first term in this expression is diagonal and\ndoes not flip spins. This is the so-called Ising term. The second term\nis off-diagonal, and involves lowering and raising operators on\nneighboring spins, and is responsible for flipping anti-aligned spins.\nThis is the “$XY$” part of the Hamiltonian.\n\nThe Heisenberg spin chain is a paradigmatic model in condensed matter.\nNot only it is attractive due to its relative simplicity, but can also\ndescribe real materials that can be studied experimentally. The\nHeisenberg chain is also a prototypical integrable system, that can be\nsolved exactly by the Bethe Ansatz, and can be studied using\nbosonization techniques and conformal field theory.\n\nThe Heisenberg spin chain is a paradigmatic model in condensed matter.\nNot only it is attractive due to its relative simplicity, but can also\ndescribe real materials that can be studied experimentally. The\nHeisenberg chain is also a prototypical integrable system, that can be\nsolved exactly by the Bethe Ansatz, and can be studied using\nbosonization techniques and conformal field theory.\n\nIn these lectures, we will be interested in obtaining its ground state\nproperties of this model by numerically solving the time-independent\nSchrödinger equation: $$\\hat{H}|\\Psi\\rangle = E|\\Psi\\rangle,$$ where $H$\nis the Hamiltonian of the problem, $|\\Psi\\rangle$ its eigenstates, with\nthe corresponding eigenvalues, or energies $E$.\n\nExact diagonalization\n=====================\n\n\n#### Pictorial representation of the Hamiltonian building recursion explained in the text. At each step, the block size is increased by adding a spin at a time.\n\nIn this section we introduce a technique that will allow us to calculate\nthe ground state, and even excited states of small Heisenberg chains.\nExact Diagonalization (ED) is a conceptually simple technique which\nbasically consists of diagonalizing the Hamiltonian matrix by brute\nforce. Same as for the spin operators, the Hamiltonian also has a\ncorresponding matrix representation. In principle, if we are able to\ncompute all the matrix elements, we can use a linear algebra package to\ndiagonalize it and obtain all the eigenvalues and eigenvectors @lapack.\n\nIn these lectures we are going to follow a quite unconventional\nprocedure to describe how this technique works. It is important to point out that this\nis a quite inefficient and impractical way to diagonalize the\nHamiltonian, and more sophisticated techniques are generally used in\npractice.\n\nTwo-spin problem\n----------------\n\nThe Hilbert space for the two-spin problem consists of four possible\nconfigurations of two spins\n$$\\left\\{ |\\uparrow\\uparrow\\rangle,|\\uparrow\\downarrow\\rangle,|\\downarrow\\uparrow\\rangle,|\\downarrow\\downarrow\\rangle \\right\\}$$\n\nThe problem is described by the Hamiltonian: $$\\hat{H}=\n\\hat{S}^z_1 \\hat{S}^z_2 +\n\\frac{1}{2}\\left[\n\\hat{S}^+_1 \\hat{S}^-_2 +\n\\hat{S}^-_1 \\hat{S}^+_2\n\\right]$$\n\nThe corresponding matrix will have dimensions $4 \\times 4$. In order to\ncompute this matrix we shall use some simple matrix algebra to first\nobtain the single-site operators in the expanded Hilbert space. This is\ndone by following the following simple scheme: And operator $O_1$ acting\non the left spin, will have the following $4 \\times 4$ matrix form:\n$$\\tilde{O}_1 = O_1 \\otimes {1}_2\n$$ Similarly, for an operator $O_2$ acting on the right\nspin: $$\\tilde{O}_2 = {1}_2 \\otimes O_2\n$$ where we introduced the $n \\times n$ identity matrix\n${1}_n$. The product of two operators acting on different sites\ncan be obtained as: $$\\tilde{O}_{12} = O_1 \\otimes O_2$$ It is easy to\nsee that the Hamiltonian matrix will be given by: $$H_{12}=\nS^z \\otimes S^z +\n\\frac{1}{2}\\left[\nS^+ \\otimes S^- +\nS^- \\otimes S^+\n\\right]$$ where we used the single spin ($2 \\times 2$) matrices $S^z$\nand $S^\\pm$. We leave as an exercise for the reader to show that the\nfinal form of the matrix is:\n\n$$H_{12} = \\left(\n\\begin{array}{cccc}\n1/4 & 0 & 0 & 0 \\\\\n0 & -1/4 & 1/2 & 0 \\\\\n0 & 1/2 & -1/4 & 0 \\\\\n0 & 0 & 0 & 1/4 \\\\\n\\end{array}\n\\right),\n$$\n\nObtaining the eigenvalues and eigenvectors is also a straightforward\nexercise: two of them are already given, and the entire problem now\nreduces to diagonalizing a two by two matrix. We therefore obtain the\nwell known result: The ground state\n$|s\\rangle = 1/\\sqrt{2}\\left[ |\\uparrow\\downarrow\\rangle - |\\downarrow\\uparrow\\rangle \\right]$,\nhas energy $E_s=-3/4$, and the other three eigenstates\n$\\left\\{|\\uparrow\\uparrow\\rangle,|\\downarrow\\downarrow\\rangle,1/\\sqrt{2}\\left[ |\\uparrow\\downarrow\\rangle + |\\downarrow\\uparrow\\rangle \\right] \\right\\}$\nform a multiplet with energy $E_t=1/4$.\n\nMany spins\n----------\n\nImagine now that we add a third spin to the right of our two spins. We\ncan use the previous result to obtain the new $8 \\times 8$ Hamiltonian\nmatrix as: $$H_{3}=\nH_{2} \\otimes {1}_2 +\n\\tilde{S}^z_2 \\otimes S^z +\n\\frac{1}{2}\\left[\n\\tilde{S}^+_2 \\otimes S^- +\n\\tilde{S}^-_2 \\otimes S^+\n\\right]$$ Here we used the single spin $S^z_1$, $S^\\pm_1$, and the\n\\`tilde\\` matrices defined in Eqs.(\\[tildeL\\]) and (\\[tildeR\\]):\n$$\\tilde{S}^z_2 = {1}_2 \\otimes S^z,$$ and\n$$\\tilde{S}^\\pm_2 = {1}_2 \\otimes S^\\pm,$$\n\nIt is easy to see that this leads to a recursion scheme to construct the\n$2^i \\times 2^i$ Hamiltonian matrix the $i^\\mathrm{th}$ step as:\n\n$$H_{i}=\nH_{i-1} \\otimes {1}_2 +\n\\tilde{S}^z_{i-1} \\otimes S^z +\n\\frac{1}{2}\\left[\n\\tilde{S}^+_{i-1} \\otimes S^- +\n\\tilde{S}^-_{i-1} \\otimes S^+\n\\right]$$\n\nwith $$\\tilde{S}^z_{i-1} = {1}_{2^{i-2}} \\otimes S^z,$$ and\n$$\\tilde{S}^\\pm_{i-1} = {1}_{2^{i-2}} \\otimes S^\\pm,$$\n\nThis recursion algorithm can be visualized as a left ‘block’, to which\nwe add new ‘sites’ or spins to the right, one at a time, as shown in\nFig.\\[fig:block\\].The block has a ‘block Hamiltonian’, $H_L$, that is\niteratively built by connecting to the new spins through the\ncorresponding interaction terms.\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nfrom matplotlib import pyplot\n\n# PARAMETERS\nnsites = 8\n\n#Single site operators\nsz0 = np.zeros(shape=(2,2)) # single site Sz\nsplus0 = np.zeros(shape=(2,2)) # single site S+\nsz0[0,0] = -0.5\nsz0[1,1] = 0.5\nsplus0[1,0] = 1.0\n\nterm_szsz = np.zeros(shape=(4,4)) #auxiliary matrix to store Sz.Sz\nterm_szsz = np.kron(sz0,sz0)\n\nterm_spsm = np.zeros(shape=(4,4)) #auxiliary matrix to store 1/2 S+.S-\nterm_spsm = np.kron(splus0,np.transpose(splus0))*0.5\nterm_spsm += np.transpose(term_spsm)\n\nh12 = term_szsz+term_spsm\n\nH = np.zeros(shape=(2,2))\nfor i in range(1,nsites):\n\n diml = 2**(i-1) # 2^i\n dim = diml*2\n \n print (\"ADDING SITE \",i,\" DIML= \",diml)\n\n Ileft = np.eye(diml)\n Iright = np.eye(2)\n\n # We add the term for the interaction S_i.S_{i+1}\n\n aux = np.zeros(shape=(dim,dim))\n aux = np.kron(H,Iright)\n H = aux\n\n H = H + np.kron(Ileft,h12)\n\nw, v = np.linalg.eigh(H) #Diagonalize the matrix\nprint(w)",
"ADDING SITE 1 DIML= 1\nADDING SITE 2 DIML= 2\nADDING SITE 3 DIML= 4\nADDING SITE 4 DIML= 8\nADDING SITE 5 DIML= 16\nADDING SITE 6 DIML= 32\nADDING SITE 7 DIML= 64\n[-3.3749326 -2.98224049 -2.98224049 -2.98224049 -2.50372907 -2.50372907\n -2.50372907 -2.33380386 -2.10812936 -2.10812936 -2.10812936 -2.0567576\n -2.0567576 -2.0567576 -1.91720711 -1.84883362 -1.84883362 -1.84883362\n -1.8316135 -1.8316135 -1.8316135 -1.8316135 -1.8316135 -1.67470637\n -1.67470637 -1.67470637 -1.64520463 -1.46566636 -1.46566636 -1.46566636\n -1.46566636 -1.46566636 -1.42441526 -1.42441526 -1.42441526 -1.39501087\n -1.22827398 -1.22827398 -1.22827398 -1.22563298 -1.22563298 -1.22563298\n -1.22563298 -1.22563298 -1.12098189 -1.03810412 -1.03810412 -1.03810412\n -1.03810412 -1.03810412 -0.99669162 -0.99669162 -0.99669162 -0.98276266\n -0.98276266 -0.98276266 -0.80242001 -0.80242001 -0.80242001 -0.80242001\n -0.80242001 -0.72918536 -0.72918536 -0.72918536 -0.72745015 -0.72745015\n -0.72745015 -0.6984272 -0.62176807 -0.62176807 -0.62176807 -0.62176807\n -0.62176807 -0.62128849 -0.61664185 -0.61664185 -0.61664185 -0.48599396\n -0.48599396 -0.48599396 -0.4510669 -0.4510669 -0.4510669 -0.4510669\n -0.4510669 -0.44720335 -0.44720335 -0.44720335 -0.39170281 -0.39170281\n -0.39170281 -0.39170281 -0.39170281 -0.37901811 -0.31675346 -0.31675346\n -0.31675346 -0.30093324 -0.30093324 -0.30093324 -0.30093324 -0.30093324\n -0.2170348 -0.2170348 -0.2170348 -0.17387953 -0.17387953 -0.17387953\n -0.17387953 -0.17387953 -0.17387953 -0.17387953 -0.12025775 -0.12025775\n -0.12025775 -0.07856615 -0.07856615 -0.07856615 -0.07856615 -0.07856615\n -0.04799743 -0.04799743 -0.04799743 -0.04799743 -0.04799743 -0.0155351\n 0.04289322 0.04289322 0.04289322 0.04289322 0.04289322 0.04289322\n 0.04289322 0.12769422 0.12769422 0.12769422 0.16805495 0.16805495\n 0.16805495 0.25423037 0.25423037 0.25423037 0.25423037 0.25423037\n 0.3208237 0.3208237 0.3208237 0.34784113 0.35531584 0.35531584\n 0.35531584 0.35531584 0.35531584 0.36731657 0.36731657 0.36731657\n 0.36731657 0.36731657 0.36731657 0.36731657 0.41720711 0.53535109\n 0.53535109 0.53535109 0.59949643 0.59949643 0.59949643 0.64679072\n 0.64679072 0.64679072 0.64679072 0.64679072 0.75 0.75\n 0.75 0.75 0.75 0.75 0.75 0.777125\n 0.777125 0.777125 0.81450906 0.81450906 0.81450906 0.81450906\n 0.81450906 0.85384723 0.95091982 0.95091982 0.95091982 0.97628634\n 0.97628634 0.97628634 0.97628634 0.97628634 1.039326 1.039326\n 1.039326 1.039326 1.039326 1.13268343 1.13268343 1.13268343\n 1.13268343 1.13268343 1.13268343 1.13268343 1.17046791 1.17046791\n 1.17046791 1.18631931 1.18631931 1.18631931 1.18631931 1.18631931\n 1.32342873 1.32342873 1.32342873 1.38251439 1.39334097 1.39334097\n 1.39334097 1.39334097 1.39334097 1.45710678 1.45710678 1.45710678\n 1.45710678 1.45710678 1.45710678 1.45710678 1.49369887 1.49369887\n 1.49369887 1.58935298 1.58935298 1.58935298 1.58935298 1.58935298\n 1.67387953 1.67387953 1.67387953 1.67387953 1.67387953 1.67387953\n 1.67387953 1.75 1.75 1.75 1.75 1.75\n 1.75 1.75 1.75 1.75 ]\n"
],
[
"from matplotlib import pyplot\npyplot.rcParams['axes.linewidth'] = 2 #set the value globally\n%matplotlib inline\n\nBeta = np.arange(0.1,10,0.1)\net = np.copy(Beta)\nn = 0\nfor x in Beta:\n p = np.exp(-w*x)\n z = np.sum(p)\n et[n] = np.dot(w,p)/z\n print (x,et[n]) \n n+=1\n\npyplot.plot(1/Beta,et,lw=2);\n \n \n \n ",
"0.1 -0.13440094427539903\n0.2 -0.2745106220291552\n0.30000000000000004 -0.4192870911355526\n0.4 -0.5675111660216381\n0.5 -0.7178307681913986\n0.6 -0.8688168893699839\n0.7000000000000001 -1.0190260819336356\n0.8 -1.167063391675081\n0.9 -1.3116396792650657\n1.0 -1.4516183124034265\n1.1 -1.5860479724220509\n1.2000000000000002 -1.714180378979959\n1.3000000000000003 -1.8354736576118653\n1.4000000000000001 -1.949583532313432\n1.5000000000000002 -2.056345366485309\n1.6 -2.155750314045565\n1.7000000000000002 -2.2479186067208534\n1.8000000000000003 -2.333072470791156\n1.9000000000000001 -2.4115105081323973\n2.0 -2.483584724611145\n2.1 -2.549680826427394\n2.2 -2.610201969519424\n2.3000000000000003 -2.6655558432015374\n2.4000000000000004 -2.716144781467402\n2.5000000000000004 -2.7623584995787276\n2.6 -2.8045690239636674\n2.7 -2.8431273972140207\n2.8000000000000003 -2.878361778912821\n2.9000000000000004 -2.910576613895644\n3.0000000000000004 -2.940052593457619\n3.1 -2.9670471865212606\n3.2 -2.9917955639500233\n3.3000000000000003 -3.0145117788059745\n3.4000000000000004 -3.035390098252337\n3.5000000000000004 -3.0546064094468397\n3.6 -3.0723196429088726\n3.7 -3.0886731733195503\n3.8000000000000003 -3.103796170357368\n3.9000000000000004 -3.1178048817330026\n4.0 -3.1308038377109333\n4.1 -3.142886971630536\n4.2 -3.154138654702368\n4.3 -3.16463464600466\n4.3999999999999995 -3.174442960414687\n4.5 -3.1836246583926866\n4.6 -3.1922345622559467\n4.7 -3.2003219039634057\n4.8 -3.2079309095711137\n4.9 -3.215101325488383\n5.0 -3.221868891516565\n5.1 -3.2282657654275697\n5.2 -3.2343209035664526\n5.3 -3.2400604016634493\n5.4 -3.2455077997309707\n5.5 -3.250684354611485\n5.6 -3.25560928344012\n5.7 -3.2602999809967206\n5.8 -3.2647722136486683\n5.9 -3.269040292330319\n6.0 -3.273117226767761\n6.1 -3.2770148629393656\n6.2 -3.28074400556245\n6.3 -3.2843145272139194\n6.4 -3.287735465526885\n6.5 -3.2910151097550813\n6.6 -3.294161077861073\n6.7 -3.2971803851619477\n6.8 -3.3000795054560577\n6.9 -3.3028644254554345\n7.0 -3.3055406932597697\n7.1 -3.3081134615283663\n7.2 -3.31058752593522\n7.3 -3.312967359428785\n7.4 -3.3152571427610007\n7.5 -3.3174607916994545\n7.6 -3.319581981290975\n7.7 -3.3216241675047438\n7.8 -3.3235906065466003\n7.9 -3.325484372104261\n8.0 -3.3273083707543263\n8.1 -3.329065355736452\n8.2 -3.330757939277211\n8.3 -3.3323886036259625\n8.4 -3.3339597109468744\n8.5 -3.335473512195249\n8.6 -3.3369321550919087\n8.7 -3.338337691296708\n8.8 -3.339692082870839\n8.9 -3.3409972081075736\n9.0 -3.342254866802048\n9.1 -3.3434667850227884\n9.2 -3.344634619440467\n9.3 -3.3457599612632443\n9.4 -3.3468443398222694\n9.5 -3.347889225846049\n9.6 -3.3488960344579564\n9.700000000000001 -3.349866127927187\n9.8 -3.3508008182000277\n9.9 -3.351701369235202\n"
]
],
[
[
"#### Challenge 12.1:\n\nCompute the energy and specific heat of the spin chain with $L=12$ as a function of temperature, for $T < 4$.",
"_____no_output_____"
],
[
"# A practical exact diagonalization algorithm\n\n1. Initialization: Topology of the lattice, neighbors, and signs. \n2. Contruction of a basis suitable for the problem. \n3. Constuction of the matrix element of the Hamiltonian. \n4. Diagonalization of the matrix. \n5. Calculation of observables or expectation values.\n\nAs we shall see below, we are going to need the concept of “binary\nword”. A binary word is the binary representation of an integer (in\npowers of ‘two’, i.e. $n=\\sum_{i}b_{i}.2^{i}$), and consist of a\nsequence of ‘bits’. A bit $b_{i}$ in the binary basis correspond to our\ndigits in the decimal system, and can assumme the values ‘zero’ or\n‘one’. At this stage we consider appropriate to introduce the logical\noperators `AND, OR, XOR`. The binary operators act between bits and\ntheir multiplication tables are listed below\n\n**AND** | 0 | 1\n:---:|:---:|:---:\n**0** | 0 | 0\n**1** | 0 | 1\n\n**OR** | 0 | 1\n:---:|:---:|:---:\n**0** | 0 | 1\n**1** | 1 | 1\n\n**XOR** | 0 | 1\n:---:|:---:|:---:\n**0** | 0 | 1\n**1** | 1 | 0\n\n\nThe bit manipulation is a very useful tool, and most of the programming\nlanguages provide the needed commands.\n\n## Initilalization and definitions\n\nIn the program, it is convenient to store in arrays all those quantities\nthat will be used more frequently. In particular, we must determine the\ntopology of the cluster, labeling the sites, and storing the components\nof the lattice vectors. We must also generate arrays with the nearest\nneighbors, and the next-nearest neighbors, according to our needs.\n\n## Construction of the basis\n\nMemory limitations impose severe restrictions on the size of the\nclusters that can be studied with this method. To understand this point,\nnote that although the lowest energy state can be written in the\n$\\{|\\phi\n_{n}\\rangle \\}$ basis as\n$|\\psi _{0}\\rangle =\\sum_{m}c_{m}|\\phi _{m}\\rangle $, this expression is\nof no practical use unless $|\\phi _{m}\\rangle $ itself is expressed in a\nconvenient basis to which the Hamiltonian can be easily applied. A\nnatural orthonormal basis for fermion systems is the occupation number\nrepresentation, describing all the possible distributions of $N_{e}$\nelectrons over $N$ sites, while for spin systems it is covenient to work\nin a basis where the $S_{z}$ is defined at every site, schematically\nrepresented as $|n\\rangle =|\\uparrow \\downarrow \\uparrow ...\\rangle $.\nThe size of this type of basis set\ngrows exponentially with the system size. In practice this problem can be\nconsiderably alleviated by the use of symmetries of the Hamiltonian that\nreduces the matrix to a block-form. The most obvious symmetry is the\nnumber of particles in the problem which is usually conserved at least\nfor fermionic problems. The total projection of the spin\n$S_{total}^{z}$, is also a good quantum number. For translationally\ninvariant problems, the total momentum $\\mathbf{k%\n}$ of the system is also conserved introducing a reduction of $1/N$ in\nthe number of states (this does not hold for models with open boundary\nconditions or explicit disorder). In addition, several Hamiltonians have\nadditional symmetries. On a square lattice, rotations in $\\pi /2$ about\na given site, spin inversion, and reflections with respect to the\nlattice axis are good quantum numbers (although care must be taken in\ntheir implementation since some of these operations are combinations of\nothers and thus not independent). \n\nIn the following we shall consider a spin-1/2 Heisenberg chain as a\npractical example. In this model it is useful to represent the spins\npointing in the ‘up’ direction by a digit ‘1’, and the down-spins by a\n‘0’. Following this rule, a state in the $S^{z}$ basis can be\nrepresented by a sequence of ones and zeroes, i.e., a “binary word”.\nThus, two Néel configurations in the 4-site chain can be seen as\n$$\\begin{aligned}\n\\mid \\uparrow \\downarrow \\uparrow \\downarrow \\rangle \\equiv |1010\\rangle , \\\\\n\\mid \\downarrow \\uparrow \\downarrow \\uparrow \\rangle \\equiv |0101\\rangle .\\end{aligned}$$\nOnce the up-spins have been placed the whole configuration has been\nuniquely determined since the remaining sites can only be occupied by\ndown-spins. The resulting binary number can be easily converted into\nintegers $i\\equiv\n\\sum_{l}b_{l}.2^{l}$, where the summation is over all the sites of the\nlattice, and $b_{l}$ can be $1$ or $0$. For example:\n$$\\begin{array}{lllll}\n2^{3} & 2^{2} & 2^{1} & 2^{0} & \\\\\n1 & 0 & 1 & 0 & \\rightarrow 2^{1}+2^{3}=10, \\\\\n0 & 1 & 0 & 1 & \\rightarrow 2^{0}+2^{2}=5.\n\\end{array}$$\n\nUsing the above convention, we can construct the whole basis for the\ngiven problem. However, we must consider the memory limitations of our\ncomputer, introducing some symetries to make the problem more tractable.\nThe symetries are operations that commute with the Hamiltonian, allowing\nus to divide the basis in subspaces with well defined quantum numbers.\nBy means of similarity transformations we can generate a sequence of\nsmaller matrices along the diagonal (i.e. the Hamiltonian matrix is\n“block diagonal”), and each of them can be diagonalized independently.\nFor fermionic systems, the simplest symmetries are associated to the\nconservation of the number of particles and the projection\n$S_{total}^{z}$ of the total spin in the $z$ direction. In the spin-1/2\nHeisenberg model, a matrix with $2^{N}\\times 2^{N}$ elements can be\nreduced to $2S+1$ smaller matrices, corresponding to the projections $%\nm=(N_{\\uparrow }-N_{\\downarrow })/2=-S,-S+1,...,S-1,S$, with $S=N/2$.\n\nThe dimension of each of these subspaces is obtained from the\ncombinatory number $\\left(\n\\begin{array}{c}\nN \\\\\nN_{\\uparrow }\n\\end{array}\n\\right) = \\frac{N!}{N_{\\uparrow }!N_{\\downarrow }!}$.\n\n#### Example: 4-site Heisenberg chain\n\nThe total basis has\n$2^{4}=16$ states that can be grouped in\n$4+1=5$ subspaces with well defined values of the quantum\nnumber $m=S^z$. The dimensions of these subspaces are:\n\n m | dimension \n:--:|:--:\n-2 | 1 \n-1 | 4 \n0 | 6 \n2 | 4 \n1 | 1 \n \nSince we know that the ground state of the Hilbert\nchain is a singlet, we are only interested in the subspace with\n</span>$S_{total}^{z}=m=0$<span>. For our example, this subspace is\ngiven by (in increasing order): </span> \n$$\\begin{eqnarray}\n\\mid \\downarrow \\downarrow \\uparrow \\uparrow \\rangle & \\equiv &|0011\\rangle\n\\equiv |3\\rangle , \\\\\n\\mid \\downarrow \\uparrow \\downarrow \\uparrow \\rangle &\\equiv &|0101\\rangle\n\\equiv |5\\rangle , \\\\\n\\mid \\downarrow \\uparrow \\uparrow \\downarrow \\rangle &\\equiv &|0110\\rangle\n\\equiv |6\\rangle , \\\\\n\\mid \\uparrow \\downarrow \\downarrow \\uparrow \\rangle &\\equiv &|1001\\rangle\n\\equiv |9\\rangle , \\\\\n\\mid \\uparrow \\downarrow \\uparrow \\downarrow \\rangle &\\equiv &|1010\\rangle\n\\equiv |10\\rangle , \\\\\n\\mid \\uparrow \\uparrow \\downarrow \\downarrow \\rangle &\\equiv &|1010\\rangle\n\\equiv |12\\rangle .\n\\end{eqnarray}\n$$\n\nGenerating the possible configurations of $N$ up-spins (or\nspinless fermions) in $L$ sites is equivalent to the problem of\ngenerating the corresponding combinations of zeroes and ones in\nlexicographic order.\n\n## Construction of the Hamiltonian matrix elements\n\nWe now have to address the problem of generating all the Hamiltonian matrix elements\n. These are obtained by the application of the\nHamiltonian on each state of the basis $|\\phi \\rangle $, generating all\nthe values\n$H_{\\phi ,\\phi ^{\\prime }}=\\langle \\phi ^{\\prime }|{{\\hat{H}}}%\n|\\phi \\rangle $. We illustrate this procedure in the following\npseudocode:\n\n    **for** each term ${\\hat{H}_i}$ of the Hamiltonian ${\\hat{H}}$\n\n        **for** all the states $|\\phi\\rangle $ in the basis\n\n            $\\hat{H}_i|\\phi\\rangle = \\langle \\phi^{\\prime }|{\\hat{H}_i}|\\phi\\rangle |\\phi^{\\prime }\\rangle $ \n\n            \n$H_{\\phi,\\phi^{\\prime }}=H_{\\phi,\\phi^{\\prime }} + \\langle \\phi^{\\prime }|{\\hat{H}_i}|\\phi\\rangle $\n\n        **end for**\n\n    **end for**\n\nAs the states are representated by binary words, the spin operators (as\nwell as the creation and destructions operators) can be be easily\nimplemented using the logical operators `AND, OR, XOR`.\n\nAs a practical example let us consider the spin-1/2 Heisenberg\nHamiltonian on the 4-sites chain:\n$${{\\hat{H}}}=J\\sum_{i=0}^{3}\\mathbf{S}_{i}.\\mathbf{S}_{i+1}=J%\n\\sum_{i=0}^{3}S_{i}^{z}.S_{i+1}^{z}+\\frac{J}{2}%\n\\sum_{i=0}^{3}(S_{i}^{+}S_{i+1}^{-}+S_{i}^{-}S_{i+1}^{+}), $$\n\nwith $\\mathbf{S}_{4}=\\mathbf{S}_{0}$, due to the periodic boundary\nconditions. To evaluate the matrix elements in the basis (\\[basis0\\]) we\nmust apply each term of ${{\\hat{H}}}$ on such states. The first term is\ncalled Ising term, and is diagonal in this basis (also called Ising\nbasis). The last terms, or fluctuation terms, give strictly off-diagonal\ncontributions to the matrix in this representation (when symmetries are\nconsidered, they can also have diagonal contributions). These\nfluctuations cause an exchange in the spin orientation between neighbors\nwith opposite spins, e.g. $\\uparrow \\downarrow \\rightarrow $\n$\\downarrow \\uparrow $. The way to implement spin-flip operations of\nthis kind on the computer is defining new ‘masks’. A mask for this\noperation is a binary number with ‘zeroes’ everywhere, except in the\npositions of the spins to be flipped, e.g 00..0110...00. Then, the\nlogical operator `XOR` is used between the initial state and the mask to\ninvert the bits (spins) at the positions indicated by the mask. For\nexample, (0101)$\\mathtt{.}$`XOR.`(1100)=(1001), i.e., 5`.XOR.`12=9. It\nis useful to store all the masks for a given geometry in memory,\ngenerating them immediately after the tables for the sites and neighbors.\n\n<span>In the Heisenberg model the spin flips can be implemented using\nmasks, with ‘zeroes’ everywhere, except in the positions of the spins to\nbe flipped. To illustrate this let us show the effect of the\noff-diagonal terms on one of the Néel configurations:</span>\n$$\\begin{eqnarray}\nS_{0}^{+}S_{1}^{-}\\,+S_{0}^{-}S_{1}^{+}\\,|0101\\rangle &\\equiv &(0011)\\mathtt{%\n.XOR.}(0101)=3\\mathtt{.XOR.}5=(0110)=6\\equiv \\,|0110\\rangle , \\\\\nS_{1}^{+}S_{2}^{-}+S_{1}^{-}S_{2}^{+}\\,\\,|0101\\rangle &\\equiv &(0110)\\mathtt{%\n.XOR.}(0101)=6\\mathtt{.XOR.}5=(0011)=3\\equiv \\,|0011\\rangle , \\\\\nS_{2}^{+}S_{3}^{-}+S_{2}^{-}S_{3}^{+}\\,\\,|0101\\rangle &\\equiv &(1100)\\mathtt{%\n.XOR.}(0101)=12\\mathtt{.XOR.}5=(1001)=9\\equiv \\,|1001\\rangle , \\\\\nS_{3}^{+}S_{0}^{-}\\,+S_{3}^{-}S_{0}^{+}|0101\\rangle &\\equiv &(1001)\\mathtt{%\n.XOR.}(0101)=9\\mathtt{.XOR.}5=(1100)=12\\equiv \\,|1100\\rangle .%\n\\end{eqnarray}$$\n\n<span>After applying the Hamiltonian (\\[h4\\]) on our basis states, the\nreader can verify as an exercise that we obtain </span>\n$$\\begin{eqnarray}\n{{\\hat{H}}}\\,|0101\\rangle &=&-J\\,|0101\\rangle +\\frac{J}{2}\\left[\n\\,|1100\\rangle +\\,|1001\\rangle +\\,|0011\\rangle +\\,|0110\\rangle \\right] , \\\\\n{{\\hat{H}}}\\,|1010\\rangle &=&-J\\,|1010\\rangle +\\frac{J}{2}\\left[\n\\,|1100\\rangle +\\,|1001\\rangle +\\,|0011\\rangle +\\,|0110\\rangle \\right] , \\\\\n{{\\hat{H}}}\\,|0011\\rangle &=&\\frac{J}{2}\\left[ \\,\\,|0101\\rangle\n+\\,|1010\\rangle \\right] , \\\\\n{{\\hat{H}}}\\,|0110\\rangle &=&\\frac{J}{2}\\left[ \\,\\,|0101\\rangle\n+\\,|1010\\rangle \\right] , \\\\\n{{\\hat{H}}}\\,|1001\\rangle &=&\\frac{J}{2}\\left[ \\,|0101\\rangle +\\,|1010\\rangle\n\\right] , \\\\\n{{\\hat{H}}}\\,|1100\\rangle &=&\\frac{J}{2}\\left[ \\,|0101\\rangle +\\,|1010\\rangle\n\\right] .%\n\\end{eqnarray}$$\n\n<span>The resulting matrix for the operator </span>$\\hat{H}$<span>in the\n</span>$S^{z}$<span> representation is: </span> $$H=J\\left(\n\\begin{array}{llllll}\n0 & 1/2 & 0 & 0 & 1/2 & 0 \\\\\n1/2 & -1 & 1/2 & 1/2 & 0 & 1/2 \\\\\n0 & 1/2 & 0 & 0 & 1/2 & 0 \\\\\n0 & 1/2 & 0 & 0 & 1/2 & 0 \\\\\n1/2 & 0 & 1/2 & 1/2 & -1 & 1/2 \\\\\n0 & 1/2 & 0 & 0 & 1/2 & 0\n\\end{array}\n\\right) . $$",
"_____no_output_____"
]
],
[
[
"class BoundaryCondition:\n RBC, PBC = range(2)\n\nclass Direction:\n RIGHT, TOP, LEFT, BOTTOM = range(4)\n \nL = 8\nNup = 2\nmaxdim = 2**L\nbc = BoundaryCondition.PBC\n\n# Tables for energy\n\nhdiag = np.zeros(4) # Diagonal energies\nhflip = np.zeros(4) # off-diagonal terms\n\nhdiag[0] = +0.25\nhdiag[1] = -0.25\nhdiag[2] = -0.25\nhdiag[3] = +0.25\n\nhflip[0] = 0.\nhflip[1] = 0.5\nhflip[2] = 0.5\nhflip[3] = 0.\n\n#hflip *= 2\n#hdiag *= 0.\n\n# Lattice geometry (1D chain)\n\nnn = np.zeros(shape=(L,4), dtype=np.int16)\nfor i in range(L):\n nn[i, Direction.RIGHT] = i-1\n nn[i, Direction.LEFT] = i+1\n\nif(bc == BoundaryCondition.RBC): # Open Boundary Conditions\n nn[0, Direction.RIGHT] = -1 # This means error\n nn[L-1, Direction.LEFT] = -1\nelse: # Periodic Boundary Conditions\n nn[0, Direction.RIGHT] = L-1 # We close the ring\n nn[L-1, Direction.LEFT] = 0\n \n# We build basis\n\nbasis = []\n\ndim = 0\nfor state in range(maxdim):\n basis.append(state)\n dim += 1\n\nprint (\"Basis:\")\nprint (basis)\n\n# We build Hamiltonian matrix\n\nH = np.zeros(shape=(dim,dim))\n\ndef IBITS(n,i):\n return ((n >> i) & 1)\n\nfor i in range(dim):\n state = basis[i]\n\n # Diagonal term\n for site_i in range(L):\n site_j = nn[site_i, Direction.RIGHT]\n if(site_j != -1): # This would happen for open boundary conditions\n two_sites = IBITS(state,site_i) | (IBITS(state,site_j) << 1)\n value = hdiag[two_sites]\n H[i,i] += value\n\n \nfor i in range(dim):\n state = basis[i]\n\n # Off-diagonal term\n for site_i in range(L):\n site_j = nn[site_i, Direction.RIGHT]\n\n if(site_j != -1):\n mask = (1 << site_i) | (1 << site_j)\n two_sites = IBITS(state,site_i) | (IBITS(state,site_j) << 1)\n value = hflip[two_sites]\n if(value != 0.):\n new_state = (state ^ mask)\n j = new_state\n H[i,j] += value\n\nprint(H)\nd, v = np.linalg.eigh(H) #Diagonalize the matrix \nprint(\"===================================================================================================================\")\nprint(d)\n",
"Basis:\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255]\n[[2. 0. 0. ... 0. 0. 0. ]\n [0. 1. 0.5 ... 0. 0. 0. ]\n [0. 0.5 1. ... 0. 0. 0. ]\n ...\n [0. 0. 0. ... 1. 0.5 0. ]\n [0. 0. 0. ... 0.5 1. 0. ]\n [0. 0. 0. ... 0. 0. 2. ]]\n===================================================================================================================\n[-3.65109341e+00 -3.12841906e+00 -3.12841906e+00 -3.12841906e+00\n -2.69962815e+00 -2.45873851e+00 -2.45873851e+00 -2.45873851e+00\n -2.45873851e+00 -2.45873851e+00 -2.45873851e+00 -2.14514837e+00\n -2.14514837e+00 -2.14514837e+00 -2.14514837e+00 -2.14514837e+00\n -2.14514837e+00 -1.85463768e+00 -1.85463768e+00 -1.85463768e+00\n -1.85463768e+00 -1.85463768e+00 -1.85463768e+00 -1.80193774e+00\n -1.80193774e+00 -1.80193774e+00 -1.80193774e+00 -1.80193774e+00\n -1.70710678e+00 -1.70710678e+00 -1.61803399e+00 -1.61803399e+00\n -1.26703510e+00 -1.26703510e+00 -1.26703510e+00 -1.26703510e+00\n -1.26703510e+00 -1.26703510e+00 -1.26703510e+00 -1.26703510e+00\n -1.26703510e+00 -1.26703510e+00 -1.20163968e+00 -1.20163968e+00\n -1.20163968e+00 -1.14412281e+00 -1.14412281e+00 -1.14412281e+00\n -1.14412281e+00 -1.14412281e+00 -1.14412281e+00 -1.14412281e+00\n -1.14412281e+00 -1.14412281e+00 -1.14412281e+00 -1.00000000e+00\n -1.00000000e+00 -1.00000000e+00 -8.58923550e-01 -8.58923550e-01\n -8.58923550e-01 -8.58923550e-01 -8.58923550e-01 -8.58923550e-01\n -7.60876722e-01 -7.26109445e-01 -6.28378427e-01 -6.28378427e-01\n -6.28378427e-01 -6.28378427e-01 -6.28378427e-01 -6.28378427e-01\n -5.96968283e-01 -5.96968283e-01 -5.96968283e-01 -5.96968283e-01\n -5.96968283e-01 -5.96968283e-01 -5.12683203e-01 -5.12683203e-01\n -5.12683203e-01 -5.12683203e-01 -5.12683203e-01 -5.12683203e-01\n -4.45041868e-01 -4.45041868e-01 -4.45041868e-01 -4.45041868e-01\n -4.45041868e-01 -4.37016024e-01 -4.37016024e-01 -4.37016024e-01\n -4.37016024e-01 -4.37016024e-01 -4.37016024e-01 -4.37016024e-01\n -4.37016024e-01 -4.37016024e-01 -4.37016024e-01 -2.92893219e-01\n -2.92893219e-01 -2.58652023e-01 -2.58652023e-01 -2.58652023e-01\n -2.58652023e-01 -2.58652023e-01 -2.58652023e-01 -2.58652023e-01\n -2.58652023e-01 -2.58652023e-01 -2.58652023e-01 -7.75689638e-16\n -7.63208968e-16 -4.57134676e-16 -4.13645713e-16 -3.39947086e-16\n -3.06926362e-16 -2.34643233e-16 -1.74475331e-16 -1.72272455e-16\n -1.38134367e-16 -1.37645901e-16 -1.32021661e-16 -7.69140168e-17\n 4.75886108e-17 5.83588051e-17 7.00756471e-17 9.12342182e-17\n 1.26508026e-16 2.24592706e-16 2.86790224e-16 4.82216812e-16\n 5.84928975e-16 9.02098163e-16 2.65452712e-01 2.65452712e-01\n 2.65452712e-01 2.65452712e-01 2.65452712e-01 2.65452712e-01\n 2.92893219e-01 2.92893219e-01 2.92893219e-01 2.92893219e-01\n 2.92893219e-01 2.92893219e-01 2.92893219e-01 2.92893219e-01\n 2.92893219e-01 2.92893219e-01 2.92893219e-01 2.92893219e-01\n 2.92893219e-01 2.92893219e-01 3.77202854e-01 4.37016024e-01\n 4.37016024e-01 4.37016024e-01 4.37016024e-01 4.37016024e-01\n 4.37016024e-01 4.37016024e-01 4.37016024e-01 4.37016024e-01\n 4.37016024e-01 4.51605963e-01 4.51605963e-01 4.51605963e-01\n 4.51605963e-01 4.51605963e-01 4.51605963e-01 6.18033989e-01\n 6.18033989e-01 8.92693358e-01 8.92693358e-01 8.92693358e-01\n 8.92693358e-01 8.92693358e-01 8.92693358e-01 1.00000000e+00\n 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00\n 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00\n 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00\n 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00\n 1.00000000e+00 1.00000000e+00 1.14412281e+00 1.14412281e+00\n 1.14412281e+00 1.14412281e+00 1.14412281e+00 1.14412281e+00\n 1.14412281e+00 1.14412281e+00 1.14412281e+00 1.14412281e+00\n 1.24697960e+00 1.24697960e+00 1.24697960e+00 1.24697960e+00\n 1.24697960e+00 1.33005874e+00 1.33005874e+00 1.33005874e+00\n 1.44572599e+00 1.44572599e+00 1.44572599e+00 1.44572599e+00\n 1.44572599e+00 1.44572599e+00 1.46050487e+00 1.52568712e+00\n 1.52568712e+00 1.52568712e+00 1.52568712e+00 1.52568712e+00\n 1.52568712e+00 1.52568712e+00 1.52568712e+00 1.52568712e+00\n 1.52568712e+00 1.70710678e+00 1.70710678e+00 1.70710678e+00\n 1.70710678e+00 1.70710678e+00 1.70710678e+00 1.70710678e+00\n 1.70710678e+00 1.70710678e+00 1.70710678e+00 1.70710678e+00\n 1.70710678e+00 1.70710678e+00 1.70710678e+00 2.00000000e+00\n 2.00000000e+00 2.00000000e+00 2.00000000e+00 2.00000000e+00\n 2.00000000e+00 2.00000000e+00 2.00000000e+00 2.00000000e+00]\n"
],
[
"# Using quantum number conservation : Sz\n\nbasis = []\n\ndim = 0\nfor state in range(maxdim):\n n_ones = 0\n for bit in range(L):\n n_ones += IBITS(state,bit)\n print (state,n_ones)\n if(n_ones == Nup):\n basis.append(state)\n dim += 1\n\nprint (\"Dim=\",dim)\nprint (\"Basis:\")\nprint (basis)\n\n#hflip[:] *= 2\n# We build Hamiltonian matrix\n\nH = np.zeros(shape=(dim,dim))\n\ndef IBITS(n,i):\n return ((n >> i) & 1)\n\nfor i in range(dim):\n state = basis[i]\n\n # Diagonal term\n for site_i in range(L):\n site_j = nn[site_i, Direction.RIGHT]\n if(site_j != -1): # This would happen for open boundary conditions\n two_sites = IBITS(state,site_i) | (IBITS(state,site_j) << 1)\n value = hdiag[two_sites]\n H[i,i] += value\n\n\ndef bisect(state, basis): \n # Binary search, only works in a sorted list of integers\n # state : integer we seek\n # basis : list of sorted integers in increasing order\n # ret_val : return value, position on the list, -1 if not found\n \n ret_val = -1\n dim = len(basis)\n \n# for i in range(dim):\n# if(state == basis[i]):\n# return i\n\n origin = 0\n end = dim-1\n middle = (origin+end)/2\n\n while(1):\n index_old = middle\n\n middle = (origin+end)//2\n\n if(state < basis[middle]):\n end = middle\n else:\n origin = middle\n\n if(basis[middle] == state):\n break\n\n if(middle == index_old):\n if(middle == end):\n end = end - 1\n else:\n origin = origin + 1\n\n ret_val = middle\n return ret_val \n\n \nfor i in range(dim):\n state = basis[i]\n\n # Off-diagonal term\n for site_i in range(L):\n site_j = nn[site_i, Direction.RIGHT]\n\n if(site_j != -1):\n mask = (1 << site_i) | (1 << site_j)\n two_sites = IBITS(state,site_i) | (IBITS(state,site_j) << 1)\n value = hflip[two_sites]\n if(value != 0.):\n new_state = (state ^ mask)\n j = bisect(new_state, basis)\n H[i,j] += value\n\nprint(H)\nd, v = np.linalg.eigh(H) #Diagonalize the matrix \nprint(d,np.min(d))\nprint(v[:,0])",
"0 0\n1 1\n2 1\n3 2\n4 1\n5 2\n6 2\n7 3\n8 1\n9 2\n10 2\n11 3\n12 2\n13 3\n14 3\n15 4\nDim= 6\nBasis:\n[3, 5, 6, 9, 10, 12]\n[[ 0.25 0.5 0. 0. 0. 0. ]\n [ 0.5 -0.75 0.5 0.5 0. 0. ]\n [ 0. 0.5 -0.25 0. 0.5 0. ]\n [ 0. 0.5 0. -0.25 0.5 0. ]\n [ 0. 0. 0.5 0.5 -0.75 0.5 ]\n [ 0. 0. 0. 0. 0.5 0.25]]\n[-1.6160254 -0.95710678 -0.25 0.1160254 0.45710678 0.75 ] -1.6160254037844386\n[ 0.14942925 -0.55767754 0.40824829 0.40824829 -0.55767754 0.14942925]\n"
]
],
[
[
"Obtaining the ground-state: Lanczos diagonalization\n---------------------------------------------------\n\nOnce we have a superblock matrix, we can apply a library routine to\nobtain the ground state of the superblock $|\\Psi\\rangle$. The two\nalgorithms widely used for this purpose are the Lanczos and Davidson\ndiagonalization. Both are explained to great extent in Ref.@noack, so we\nrefer the reader to this material for further information. In these\nnotes we will briefly explain the Lanczos procedure.\n\nThe basic idea of the Lanczos method is that a special basis can be constructed\nwhere the Hamiltonian has a tridiagonal representation. This is carried\nout iteratively as shown below. First, it is necessary to select an\narbitrary seed vector $|\\phi _{0}\\rangle $ in the Hilbert space of the\nmodel being studied. If we are seeking the ground-state of the model,\nthen it is necessary that the overlap between the actual ground-state\n$|\\psi\n_{0}\\rangle $, and the initial state $|\\phi _{0}\\rangle $ be nonzero. If\nno “a priori” information about the ground state is known, this\nrequirement is usually easily satisfied by selecting an initial state\nwith *randomly* chosen coefficients in the working basis that is being\nused. If some other information of the ground state is known, like its\ntotal momentum and spin, then it is convenient to initiate the\niterations with a state already belonging to the subspace having those\nquantum numbers (and still with random coefficients within this\nsubspace).\n\nAfter $|\\phi _{0}\\rangle $ is selected, define a new vector by applying\nthe Hamiltonian ${{\\hat{H}}}$, over the initial state. Subtracting the\nprojection over $|\\phi _{0}\\rangle $, we obtain\n$$|\\phi _{1}\\rangle ={{\\hat{H}}}|\\phi _{0}\\rangle -\\frac{{\\langle }\\phi _{0}|{{%\n\\hat{H}}}|{\\phi }_{0}{\\rangle }}{\\langle \\phi _{0}|\\phi _{0}\\rangle }|\\phi\n_{0}\\rangle ,$$ that satisfies $\\langle \\phi _{0}|\\phi _{1}\\rangle =0$.\nNow, we can construct a new state that is orthogonal to the previous two\nas,\n$$|\\phi _{2}\\rangle ={{\\hat{H}}}|\\phi _{1}\\rangle -{\\frac{{\\langle \\phi _{1}|{%\n\\hat{H}}|\\phi _{1}\\rangle }}{{\\langle \\phi _{1}|\\phi _{1}\\rangle }}}|\\phi\n_{1}\\rangle -{\\frac{{\\langle \\phi _{1}|\\phi _{1}\\rangle }}{{\\langle \\phi\n_{0}|\\phi _{0}\\rangle }}}|\\phi _{0}\\rangle .$$ It can be easily checked\nthat $\\langle \\phi _{0}|\\phi _{2}\\rangle\n=\\langle \\phi _{1}|\\phi _{2}\\rangle =0$. The procedure can be\ngeneralized by defining an orthogonal basis recursively as,\n$$|\\phi _{n+1}\\rangle ={{\\hat{H}}}|\\phi _{n}\\rangle -a_{n}|\\phi _{n}\\rangle\n-b_{n}^{2}|\\phi _{n-1}\\rangle ,$$ where $n=0,1,2,...$, and the\ncoefficients are given by\n$$a_{n}={\\frac{{\\langle \\phi _{n}|{\\hat{H}}|\\phi _{n}\\rangle }}{{\\langle \\phi\n_{n}|\\phi _{n}\\rangle }}},\\qquad b_{n}^{2}={\\frac{{\\langle \\phi _{n}|\\phi\n_{n}\\rangle }}{{\\langle \\phi _{n-1}|\\phi _{n-1}\\rangle }}},$$\nsupplemented by $b_{0}=0$, $|\\phi _{-1}\\rangle =0$. In this basis, it\ncan be shown that the Hamiltonian matrix becomes, $$H=\\left(\n\\begin{array}{lllll}\na_{0} & b_{1} & 0 & 0 & ... \\\\\nb_{1} & a_{1} & b_{2} & 0 & ... \\\\\n0 & b_{2} & a_{2} & b_{3} & ... \\\\\n0 & 0 & b_{3} & a_{3} & ... \\\\\n\\vdots\n{} &\n\\vdots\n&\n\\vdots\n&\n\\vdots\n&\n\\end{array}\n\\right)$$ i.e. it is tridiagonal as expected. Once in this form the\nmatrix can be diagonalized easily using standard library subroutines.\nHowever, note that to diagonalize completely a Hamiltonian on a finite\ncluster, a number of iterations equal to the size of the Hilbert space\n(or the subspace under consideration) are needed. In practice this would\ndemand a considerable amount of CPU time. However, one of the advantages\nof this technique is that accurate enough information about the ground\nstate of the problem can be obtained after a small number of iterations\n(typically of the order of $\\sim 100$ or less).\n\nAnother way to formulate the problem is by obtaining the tridiagonal\nform of the Hamiltonian starting from a Krylov basis, which is spanned\nby the vectors\n$$\\left\\{|\\phi_0\\rangle,\\hat{H}|\\phi_0\\rangle,\\hat{H}^2|\\phi_0\\rangle,...,\\hat{H}^n|\\phi_0\\rangle\\right\\}$$\nand asking that each vector be orthogonal to the previous two. Notice\nthat each new iteration of the process requires one application of the\nHamiltonian. Most of the time this simple procedure works for practical\npurposes, but care must be payed to the possibility of losing\northogonality between the basis vectors. This may happen due to the\nfinite machine precision. In that case, a re-orthogonalization procedure\nmay be required.\n\nNotice that the new super-Hamiltonian matrix has dimensions\n$D_L D_R d^2 \\times D_L D_R d^2$. This could be a large matrix. In\nstate-of-the-art simulations with a large number of states, one does not\nbuild this matrix in memory explicitly, but applies the operators to the\nstate directly in the diagonalization routine.",
"_____no_output_____"
]
],
[
[
"def lanczos(m, seed, maxiter, tol, use_seed, calc_gs, force_maxiter = False):\n x1 = seed\n x2 = seed\n gs = seed\n a = np.zeros(100)\n b = np.zeros(100)\n z = np.zeros((100,100))\n lvectors = []\n control_max = maxiter;\n\n if(maxiter == -1):\n force_maxiter = False\n\n if(control_max == 0):\n gs = 1\n maxiter = 1\n return(e0,gs)\n \n x1[:] = 0\n x2[:] = 0\n gs[:] = 0\n maxiter = 0\n a[:] = 0.0\n b[:] = 0.0\n if(use_seed):\n x1 = seed\n else :\n x1 = np.random.random(x1.shape[0])*2-1.\n\n b[0] = np.sqrt(np.dot(x1,x1))\n x1 = x1 / b[0]\n x2[:] = 0\n b[0] = 1.\n\n e0 = 9999\n nmax = min(99, gs.shape[0])\n for iter in range(1,nmax+1):\n eini = e0\n if(b[iter - 1] != 0.):\n aux = x1\n x1 = -b[iter-1] * x2\n x2 = aux / b[iter-1]\n\n aux = np.dot(m,x2)\n x1 = x1 + aux\n a[iter] = np.dot(x1, x2)\n x1 = x1 - x2*a[iter]\n b[iter] = np.sqrt(np.dot(x1, x1))\n lvectors.append(x2) \n\n z.resize((iter+1,iter+1))\n z[:,:] = 0\n for i in range(0,iter-1):\n z[i,i+1] = b[i+1]\n z[i+1,i] = b[i+1]\n z[i,i] = a[i+1]\n z[iter-1,iter-1]=a[iter]\n d, v = np.linalg.eig(z)\n col = 0\n n = 0\n e0 = 9999\n for e in d:\n if(e < e0):\n e0 = e\n col = n\n n+=1\n e0 = d[col]\n print (\"Iter = \",iter,\" Ener = \",e0)\n if((force_maxiter and iter >= control_max) or (iter >= gs.shape[0] or iter == 99 or abs(b[iter]) < tol) or \\\n ((not force_maxiter) and abs(eini-e0) <= tol)):\n # converged\n gs = 0.\n for i in range(0,iter):\n gs += v[i,col]*lvectors[i]\n print (\"E0 = \", e0, np.sqrt(np.dot(gs,gs)))\n maxiter = iter\n return(e0,gs) # We return with ground states energy\n",
"_____no_output_____"
],
[
"seed = np.zeros(H.shape[0])",
"_____no_output_____"
],
[
"e0, gs = lanczos(H,seed,6,1.e-5,False,False)",
"Iter = 1 Ener = -0.6848415206892902\nIter = 2 Ener = -1.9335584929208487\nIter = 3 Ener = -1.9939600915319768\nIter = 4 Ener = -1.999999999999999\nE0 = -1.999999999999999 0.9999999999999997\n"
],
[
"print(gs)",
"[ 0.28867513 -0.57735027 0.28867513 0.28867513 -0.57735027 0.28867513]\n"
],
[
"print(np.dot(gs,gs))",
"0.9999999999999994\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4aae11fccc213e0742e77fd569c3c01f2cf0a844
| 366,050 |
ipynb
|
Jupyter Notebook
|
misc/deep_learning_notes/Ch5_Deep_Reinforcement_Learning/Simple Q-Learning Frozen Lake (grid world).ipynb
|
tmjnow/MoocX
|
52c8450ff7ecc8450a8adc2457233d5777a3d5bb
|
[
"MIT"
] | 7 |
2017-06-13T05:24:15.000Z
|
2022-01-09T01:10:28.000Z
|
misc/deep_learning_notes/Ch5_Deep_Reinforcement_Learning/Simple Q-Learning Frozen Lake (grid world).ipynb
|
tmjnow/MoocX
|
52c8450ff7ecc8450a8adc2457233d5777a3d5bb
|
[
"MIT"
] | 11 |
2017-05-08T23:30:50.000Z
|
2017-06-24T21:57:42.000Z
|
misc/deep_learning_notes/Ch5_Deep_Reinforcement_Learning/Simple Q-Learning Frozen Lake (grid world).ipynb
|
kinshuk4/MoocX
|
52c8450ff7ecc8450a8adc2457233d5777a3d5bb
|
[
"MIT"
] | 4 |
2017-10-05T12:56:53.000Z
|
2020-06-14T17:01:32.000Z
| 1,257.90378 | 193,610 | 0.947483 |
[
[
[
"# A Table based Q-Learning Reinforcement Agent in A Grid World\n\nThis is a simple example of a Q-Learning agent. The Q function is a table, and each decision is made by sampling the Q-values for a particular state thermally. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport random\nimport gym\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nfrom IPython.display import clear_output\nfrom tqdm import tqdm",
"_____no_output_____"
],
[
"env = gym.make('FrozenLake-v0')",
"[2017-03-24 09:58:26,166] Making new env: FrozenLake-v0\n"
],
[
"Q = np.zeros([env.observation_space.n, env.action_space.n])",
"_____no_output_____"
],
[
"# Set learning parameters\ndecision_temperature = 0.01\nl_rate = 0.5\ny = .99\ne = 0.1\nnum_episodes = 900\n\n# create lists to contain total rewawrds and steps per episode\n\nepi_length = []\nrs = []\n\nfor i in tqdm(range(num_episodes)):\n s = env.reset()\n r_total = 0\n done = False\n number_jumps = 0\n\n # limit numerb of jumps\n while number_jumps < 99:\n number_jumps += 1\n\n softmax = np.exp(Q[s]/decision_temperature)\n rand_n = np.random.rand() * np.sum(softmax)\n \n # pick the next action randomly\n acc = 0\n for ind in range(env.action_space.n):\n acc += softmax[ind]\n if acc >= rand_n:\n a = ind\n break\n \n #print(a, softmax, rand_n)\n \n # a = np.argmax(Q[s, :] + np.random.randn(1, env.action_space.n) * (1./(i+1)))\n\n s_next, r, done, _ = env.step(a)\n\n\n Q_next_value = Q[s_next]\n\n\n max_Q_next = np.max(Q[s_next,:])\n\n # now update Q\n Q[s, a] += l_rate * (r + y * max_Q_next \\\n - Q[s, a])\n\n r_total += r\n s = s_next\n if done:\n # be more conservative as we learn more\n e = 1./((i/50) + 10)\n break\n\n if i%900 == 899:\n\n clear_output(wait=True)\n print(\"success rate: \" + str(sum(rs[-200:])/2) + \"%\")\n\n plt.figure(figsize=(8, 8))\n plt.subplot(211)\n plt.title(\"Jumps Per Episode\", fontsize=18)\n plt.plot(epi_length[-200:], \"#23aaff\")\n plt.subplot(212)\n plt.title('Reward For Each Episode (0/1)', fontsize=18)\n plt.plot(rs[-200:], \"o\", color='#23aaff', alpha=0.1)\n \n plt.figure(figsize=(6, 6))\n plt.title('Decision Table', fontsize=18)\n plt.xlabel(\"States\", fontsize=15)\n plt.ylabel('Actions', fontsize=15)\n plt.imshow(Q.T)\n plt.show()\n\n epi_length.append(number_jumps)\n rs.append(r_total)",
"success rate: 71.5%\n"
],
[
"def mv_avg(xs, n):\n return [sum(xs[i:i+n])/n for i in range(len(xs)-n)]\n# plt.plot(mv_avg(rs, 200))",
"_____no_output_____"
],
[
"plt.figure(figsize=(8, 8))\nplt.subplot(211)\nplt.title(\"Jumps Per Episode\", fontsize=18)\nplt.plot(epi_length, \"#23aaff\", linewidth=0.1, alpha=0.7,\n label=\"raw data\")\nplt.plot(mv_avg(epi_length, 200), color=\"blue\", alpha=0.3, linewidth=4, \n label=\"Moving Average\")\nplt.legend(loc=(1.05, 0), frameon=False, fontsize=15)\nplt.subplot(212)\nplt.title('Reward For Each Episode (0/1)', fontsize=18)\n#plt.plot(rs, \"o\", color='#23aaff', alpha=0.2, markersize=0.4, label=\"Reward\")\nplt.plot(mv_avg(rs, 200), color=\"red\", alpha=0.5, linewidth=4, label=\"Moving Average\")\nplt.ylim(-0.1, 1.1)\nplt.legend(loc=(1.05, 0), frameon=False, fontsize=15)\nplt.savefig('./figures/Frozen-Lake-v0-thermal-table.png', dpi=300, bbox_inches='tight')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aae1677b556a254f98fc141454763e8145c535d
| 442,639 |
ipynb
|
Jupyter Notebook
|
WeatherPy/WeatherPy.ipynb
|
mindyketchum9/Python-APIs
|
3eae24406444ecf75a0f043dc968ab7488acab36
|
[
"ADSL"
] | null | null | null |
WeatherPy/WeatherPy.ipynb
|
mindyketchum9/Python-APIs
|
3eae24406444ecf75a0f043dc968ab7488acab36
|
[
"ADSL"
] | null | null | null |
WeatherPy/WeatherPy.ipynb
|
mindyketchum9/Python-APIs
|
3eae24406444ecf75a0f043dc968ab7488acab36
|
[
"ADSL"
] | null | null | null | 145.175139 | 28,188 | 0.853217 |
[
[
[
"# WeatherPy\n----\n\n#### Note\n* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.",
"_____no_output_____"
]
],
[
[
"!pip install citipy",
"Collecting citipy\n Downloading citipy-0.0.5.tar.gz (557 kB)\nCollecting kdtree>=0.12\n Downloading kdtree-0.16-py2.py3-none-any.whl (7.7 kB)\nBuilding wheels for collected packages: citipy\n Building wheel for citipy (setup.py): started\n Building wheel for citipy (setup.py): finished with status 'done'\n Created wheel for citipy: filename=citipy-0.0.5-py3-none-any.whl size=559707 sha256=0192289556d18699867c6aaeef058bca327cf1478f84d64115349b4b78bcdd75\n Stored in directory: c:\\users\\mindy\\appdata\\local\\pip\\cache\\wheels\\eb\\07\\14\\1c448d9fabf3aceac66270933ecae15693974a1b7f91266841\nSuccessfully built citipy\nInstalling collected packages: kdtree, citipy\nSuccessfully installed citipy-0.0.5 kdtree-0.16\n"
],
[
"# Dependencies and Setup\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport requests\nimport time\nimport seaborn as sns\nimport requests\nimport time\nimport urllib\nimport json\nfrom scipy.stats import linregress\n\n# Import API key\nfrom api_keys import weather_api_key\n\n# Incorporated citipy to determine city based on latitude and longitude\nfrom citipy import citipy\n\n# Output File (CSV)\noutput_data_file = \"output_data/cities.csv\"\n\n# Range of latitudes and longitudes\nlat_range = (-90, 90)\nlng_range = (-180, 180)",
"_____no_output_____"
]
],
[
[
"## Generate Cities List",
"_____no_output_____"
]
],
[
[
" # List for holding lat_lngs and cities\nlat_lngs = []\ncities = []\n\n# Create a set of random lat and lng combinations\nlats = np.random.uniform(low=-90.000, high=90.000, size=1500)\nlngs = np.random.uniform(low=-180.000, high=180.000, size=1500)\nlat_lngs = zip(lats, lngs)\n\n# Identify nearest city for each lat, lng combination\nfor lat_lng in lat_lngs:\n city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name\n \n # If the city is unique, then add it to a our cities list\n if city not in cities:\n cities.append(city)\n\n# Print the city count to confirm sufficient count\nlen(cities)",
"_____no_output_____"
]
],
[
[
"### Perform API Calls\n* Perform a weather check on each city using a series of successive API calls.\n* Include a print log of each city as it'sbeing processed (with the city number and city name).\n",
"_____no_output_____"
]
],
[
[
"#Build URL\nurl = \"http://api.openweathermap.org/data/2.5/weather?\"\nunits = \"imperial\" \nwkey = \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\nappid = wkey\nsettings = {\"units\": \"imperial\", \"appid\": wkey}\nurl = f\"{url}appid={wkey}&units={units}\"",
"_____no_output_____"
],
[
"url",
"_____no_output_____"
],
[
"# List of city data\ncity_data = []\n\n# Print to logger\nprint(\"Beginning Data Retrieval \")\nprint(\"-----------------------------\")\n\n# Create counters\nrecord_count = 1\nset_count = 1\n\n# Loop through all the cities in our list\nfor i, city in enumerate(cities):\n \n # Group cities in sets of 50 for logging purposes\n if (i % 50 == 0 and i >= 50):\n set_count += 1\n record_count = 0\n\n # Create endpoint URL with each city\n city_url = url + \"&q=\" + urllib.request.pathname2url(city)\n\n # Log the url, record, and set numbers\n print(\"Processing Record %s of Set %s | %s\" % (record_count, set_count, city))\n print(city_url)\n\n # Add 1 to the record count\n record_count += 1\n\n # Run an API request for each of the cities\n try:\n # Parse the JSON and retrieve data\n city_weather = requests.get(city_url).json()\n\n # Parse out the max temp, humidity, and cloudiness\n city_latitute = city_weather[\"coord\"][\"lat\"]\n city_longitude = city_weather[\"coord\"][\"lon\"]\n city_max_temperature = city_weather[\"main\"][\"temp_max\"]\n city_humidity = city_weather[\"main\"][\"humidity\"]\n city_clouds = city_weather[\"clouds\"][\"all\"]\n city_wind = city_weather[\"wind\"][\"speed\"]\n city_country = city_weather[\"sys\"][\"country\"]\n city_date = city_weather[\"dt\"]\n\n # Append the City information into city_data list\n city_data.append({\"City\": city, \n \"Lat\": city_latitute, \n \"Lng\": city_longitude, \n \"Max Temp\": city_max_temperature,\n \"Humidity\": city_humidity,\n \"Cloudiness\": city_clouds,\n \"Wind Speed\": city_wind,\n \"Country\": city_country,\n \"Date\": city_date})\n\n # If an error is experienced, skip the city\n except:\n print(\"City not found...\")\n pass\n \n# Indicate that Data Loading is complete \nprint(\"-----------------------------\")\nprint(\"Data Retrieval Complete \")\nprint(\"-----------------------------\")",
"Beginning Data Retrieval \n-----------------------------\nProcessing Record 1 of Set 1 | barrow\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=barrow\nProcessing Record 2 of Set 1 | atuona\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=atuona\nProcessing Record 3 of Set 1 | conde\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=conde\nProcessing Record 4 of Set 1 | rikitea\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=rikitea\nProcessing Record 5 of Set 1 | hambantota\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=hambantota\nProcessing Record 6 of Set 1 | qasigiannguit\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=qasigiannguit\nProcessing Record 7 of Set 1 | hilo\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=hilo\nProcessing Record 8 of Set 1 | tasiilaq\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=tasiilaq\nProcessing Record 9 of Set 1 | attawapiskat\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=attawapiskat\nCity not found...\nProcessing Record 10 of Set 1 | boa vista\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=boa%20vista\nProcessing Record 11 of Set 1 | ondo\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=ondo\nProcessing Record 12 of Set 1 | asau\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=asau\nProcessing Record 13 of Set 1 | puerto ayora\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=puerto%20ayora\nProcessing Record 14 of Set 1 | provideniya\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=provideniya\nProcessing Record 15 of Set 1 | hermanus\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=hermanus\nProcessing Record 16 of Set 1 | hobart\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=hobart\nProcessing Record 17 of Set 1 | belaya gora\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=belaya%20gora\nProcessing Record 18 of Set 1 | khatanga\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=khatanga\nProcessing Record 19 of Set 1 | codrington\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=codrington\nProcessing Record 20 of Set 1 | xai-xai\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=xai-xai\nProcessing Record 21 of Set 1 | buala\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=buala\nProcessing Record 22 of Set 1 | saleaula\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=saleaula\nCity not found...\nProcessing Record 23 of Set 1 | clyde river\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=clyde%20river\nProcessing Record 24 of Set 1 | mahebourg\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=mahebourg\nProcessing Record 25 of Set 1 | nanortalik\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=nanortalik\nProcessing Record 26 of Set 1 | shibukawa\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=shibukawa\nProcessing Record 27 of Set 1 | tsihombe\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=tsihombe\nCity not found...\nProcessing Record 28 of Set 1 | belushya guba\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=belushya%20guba\nCity not found...\nProcessing Record 29 of Set 1 | albany\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=albany\nProcessing Record 30 of Set 1 | klaksvik\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=klaksvik\nProcessing Record 31 of Set 1 | kyra\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=kyra\nProcessing Record 32 of Set 1 | ushuaia\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=ushuaia\nProcessing Record 33 of Set 1 | linchuan\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=linchuan\nCity not found...\nProcessing Record 34 of Set 1 | diego de almagro\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=diego%20de%20almagro\nProcessing Record 35 of Set 1 | kununurra\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=kununurra\nProcessing Record 36 of Set 1 | punta arenas\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=punta%20arenas\nProcessing Record 37 of Set 1 | yerbogachen\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=yerbogachen\nProcessing Record 38 of Set 1 | menongue\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=menongue\nProcessing Record 39 of Set 1 | merrill\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=merrill\nProcessing Record 40 of Set 1 | guerrero negro\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=guerrero%20negro\nProcessing Record 41 of Set 1 | taolanaro\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=taolanaro\nCity not found...\nProcessing Record 42 of Set 1 | busselton\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=busselton\nProcessing Record 43 of Set 1 | vila franca do campo\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=vila%20franca%20do%20campo\nProcessing Record 44 of Set 1 | bredasdorp\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=bredasdorp\nProcessing Record 45 of Set 1 | khasan\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=khasan\nProcessing Record 46 of Set 1 | playa del carmen\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=playa%20del%20carmen\nProcessing Record 47 of Set 1 | kodiak\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=kodiak\nProcessing Record 48 of Set 1 | kangaatsiaq\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=kangaatsiaq\nProcessing Record 49 of Set 1 | dajal\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=dajal\nProcessing Record 50 of Set 1 | jamestown\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=jamestown\nProcessing Record 0 of Set 2 | nikolskoye\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=nikolskoye\nProcessing Record 1 of Set 2 | fortuna\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=fortuna\nProcessing Record 2 of Set 2 | tuktoyaktuk\nhttp://api.openweathermap.org/data/2.5/weather?appid=5b6dc96509919ee7bd36f35c7e82e7cd&units=imperial&q=tuktoyaktuk\n"
]
],
[
[
"### Convert Raw Data to DataFrame\n* Export the city data into a .csv.\n* Display the DataFrame",
"_____no_output_____"
]
],
[
[
"\n# Convert array of JSONs into Pandas DataFrame\ncity_data_pd = pd.DataFrame(city_data)\n\n# Export the City_Data into a csv\ncity_data_pd.to_csv(\"WeatherPy.csv\",encoding=\"utf-8\",index=False)\n\n\n# Show Record Count\ncity_data_pd.count()",
"_____no_output_____"
],
[
"city_data_pd = pd.read_csv(\"WeatherPy.csv\")",
"_____no_output_____"
],
[
"# Display the City Data Frame\ncity_data_pd.head()",
"_____no_output_____"
],
[
"city_data_pd.describe()",
"_____no_output_____"
]
],
[
[
"## Inspect the data and remove the cities where the humidity > 100%.\n----\nSkip this step if there are no cities that have humidity > 100%. ",
"_____no_output_____"
]
],
[
[
"# Get the indices of cities that have humidity over 100%.",
"_____no_output_____"
],
[
"# Make a new DataFrame equal to the city data to drop all humidity outliers by index.\nPassing \"inplace=False\" will make a copy of the city_data DataFrame, which we call \"clean_city_data\".\n",
"_____no_output_____"
]
],
[
[
"## Plotting the Data\n* Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.\n* Save the plotted figures as .pngs.",
"_____no_output_____"
],
[
"## Latitude vs. Temperature Plot",
"_____no_output_____"
]
],
[
[
"\n# Build a scatter plot for each data type\nplt.scatter(city_data_pd[\"Lat\"], city_data_pd[\"Max Temp\"], marker=\"o\", s=10)\n\n# Incorporate the other graph properties\nplt.title(\"City Latitude vs. Max Temperature\")\nplt.ylabel(\"Max. Temperature (F)\")\nplt.xlabel(\"Latitude\")\nplt.grid(True)\n\n# Save the figure\n\n\n# Show plot\nplt.show()",
"_____no_output_____"
],
[
"# In the city latitude vs max temperature, we can see that areas further away from the equator (-60 are 80) are much colder \n# and places that are closer to the equator (0), are generally warmer. ",
"_____no_output_____"
]
],
[
[
"## Latitude vs. Humidity Plot",
"_____no_output_____"
]
],
[
[
"# Build a scatter plot for each data type\nplt.scatter(city_data_pd[\"Lat\"], city_data_pd[\"Humidity\"], marker=\"o\", s=10)\n\n# Incorporate the other graph properties\nplt.title(\"City Latitude vs. Humidity\")\nplt.ylabel(\"Humidity (%)\")\nplt.xlabel(\"Latitude\")\nplt.grid(True)\n\n# Save the figure\n#plt.savefig(\"Output_Plots/Humidity_vs_Latitude.png\")\n\n# Show plot\nplt.show()",
"_____no_output_____"
],
[
"# It does not look like there is a correlation between humidity and latitude. Humidity is generally based on location to water.",
"_____no_output_____"
]
],
[
[
"## Latitude vs. Cloudiness Plot",
"_____no_output_____"
]
],
[
[
"\n# Build a scatter plot for each data type\nplt.scatter(city_data_pd[\"Lat\"], city_data_pd[\"Cloudiness\"], marker=\"o\", s=10)\n\n# Incorporate the other graph properties\nplt.title(\"City Latitude vs. Cloudiness\")\nplt.ylabel(\"Cloudiness (%)\")\nplt.xlabel(\"Latitude\")\nplt.grid(True)\n\n# Save the gragh\n\n\n# Show plot\nplt.show()",
"_____no_output_____"
],
[
"# It does not appear there is a correlation between latitude and cloudiness. Weather is dependent upon many factors.",
"_____no_output_____"
]
],
[
[
"## Latitude vs. Wind Speed Plot",
"_____no_output_____"
]
],
[
[
"# Build a scatter plot for each data type\nplt.scatter(city_data_pd[\"Lat\"], city_data_pd[\"Wind Speed\"], marker=\"o\", s=10)\n\n# Incorporate the other graph properties\nplt.title(\"City Latitude vs. Wind Speed\")\nplt.ylabel(\"Wind Speed (mph)\")\nplt.xlabel(\"Latitude\")\nplt.grid(True)\n\n# Save the figure\n\n\n# Show plot\nplt.show()",
"_____no_output_____"
],
[
"# It does not appear there is a correlation between latitude and wind speed. \n# Wind speed is based on a variety of factors including weather and geography.",
"_____no_output_____"
]
],
[
[
"## Linear Regression",
"_____no_output_____"
]
],
[
[
"df_NorthernHem = city_data_pd.loc[city_data_pd[\"Lat\"] > 0]\ndf_SouthernHem = city_data_pd.loc[city_data_pd[\"Lat\"] < 0]",
"_____no_output_____"
],
[
"x_values = df_NorthernHem[\"Lat\"]\ny_values = df_NorthernHem[\"Max Temp\"]",
"_____no_output_____"
],
[
"def regressplot(x_values, y_values):\n\n # Perform a linear regression on temperature vs. latitude\n (slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)\n\n # Get regression values\n regress_values = x_values * slope + intercept\n print(regress_values)\n\n # Create line equation string\n line_eq = \"y = \" + str(round(slope,2)) + \"x +\" + str(round(intercept,2))\n\n # Build a scatter plot for each data type\n plt.scatter(x_values, y_values , marker=\"o\", s=10)\n plt.plot(x_values,regress_values,\"r-\")\n\n # Incorporate the other graph properties\n\n plt.xlabel(\"Latitude\")\n plt.grid(True)\n plt.annotate(line_eq,(20,15),fontsize=15,color=\"red\")\n\n\n \n # Print r value\n print(f\"The r-value is: {rvalue**2}\")\n\n # Save the figure\n\n\n # Show plot\n plt.show()",
"_____no_output_____"
],
[
"plt.title(\"City Latitude vs. Max Temperature\")\nplt.ylabel(\"Max. Temperature (F)\")\n\nregressplot(x_values, y_values)",
"0 47.843475\n4 85.489254\n5 49.270283\n6 77.627369\n7 51.124555\n ... \n540 63.134004\n541 85.835847\n542 73.970812\n543 65.646803\n544 71.255834\nName: Lat, Length: 370, dtype: float64\nThe r-value is: 0.6631338107300853\n"
]
],
[
[
"#### Northern Hemisphere - Max Temp vs. Latitude Linear Regression",
"_____no_output_____"
]
],
[
[
"x_values = df_SouthernHem[\"Lat\"]\ny_values = df_SouthernHem[\"Max Temp\"]",
"_____no_output_____"
],
[
"plt.title(\"City Latitude vs. Max Temperature\")\nplt.ylabel(\"Max. Temperature (F)\")\n\nregressplot(x_values, y_values)",
"1 74.367787\n2 76.417787\n3 63.617390\n11 81.679993\n13 54.497309\n ... \n531 66.127430\n532 73.229794\n535 73.375070\n536 77.588063\n539 59.299476\nName: Lat, Length: 175, dtype: float64\nThe r-value is: 0.5179371276334398\n"
]
],
[
[
"#### Southern Hemisphere - Max Temp vs. Latitude Linear Regression",
"_____no_output_____"
]
],
[
[
"x_values = df_SouthernHem[\"Lat\"]\ny_values = df_SouthernHem[\"Max Temp\"]",
"_____no_output_____"
],
[
"plt.title(\"City Latitude vs. Max Temperature\")\nplt.ylabel(\"Max. Temperature (F)\")\n\nregressplot(x_values, y_values)",
"1 74.367787\n2 76.417787\n3 63.617390\n11 81.679993\n13 54.497309\n ... \n531 66.127430\n532 73.229794\n535 73.375070\n536 77.588063\n539 59.299476\nName: Lat, Length: 175, dtype: float64\nThe r-value is: 0.5179371276334398\n"
]
],
[
[
"#### Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression",
"_____no_output_____"
]
],
[
[
"x_values = df_NorthernHem[\"Lat\"]\ny_values = df_NorthernHem[\"Humidity\"]",
"_____no_output_____"
],
[
"plt.title(\"City Latitude vs. Humidity\")\nplt.ylabel(\"Humidity (%)\")\n\nregressplot(x_values, y_values)",
"1 71.976144\n2 72.391436\n3 69.798310\n11 73.457463\n13 67.950748\n ... \n531 70.306798\n532 71.745607\n535 71.775037\n536 72.628513\n539 68.923579\nName: Lat, Length: 175, dtype: float64\nThe r-value is: 0.014859238841164014\n"
]
],
[
[
"#### Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression",
"_____no_output_____"
]
],
[
[
"x_values = df_SouthernHem[\"Lat\"]\ny_values = df_SouthernHem[\"Humidity\"]",
"_____no_output_____"
],
[
"plt.title(\"City Latitude vs. Humidity\")\nplt.ylabel(\"Humidity (%)\")\n\nregressplot(x_values, y_values)",
"1 71.976144\n2 72.391436\n3 69.798310\n11 73.457463\n13 67.950748\n ... \n531 70.306798\n532 71.745607\n535 71.775037\n536 72.628513\n539 68.923579\nName: Lat, Length: 175, dtype: float64\nThe r-value is: 0.014859238841164014\n"
]
],
[
[
"#### Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression",
"_____no_output_____"
]
],
[
[
"x_values = df_NorthernHem[\"Lat\"]\ny_values = df_NorthernHem[\"Cloudiness\"]",
"_____no_output_____"
],
[
"plt.title(\"City Latitude vs. Cloudiness\")\nplt.ylabel(\"Cloudiness (%)\")\n\nregressplot(x_values, y_values)",
"0 51.177521\n4 47.785547\n5 51.048962\n6 48.493921\n7 50.881888\n ... \n540 49.799808\n541 47.754318\n542 48.823386\n543 49.573399\n544 49.068012\nName: Lat, Length: 370, dtype: float64\nThe r-value is: 0.000652749347632978\n"
]
],
[
[
"#### Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression",
"_____no_output_____"
]
],
[
[
"x_values = df_SouthernHem[\"Lat\"]\ny_values = df_SouthernHem[\"Cloudiness\"]",
"_____no_output_____"
],
[
"plt.title(\"City Latitude vs. Cloudiness\")\nplt.ylabel(\"Cloudiness (%)\")\n\nregressplot(x_values, y_values)",
"1 46.973037\n2 47.942082\n3 41.891273\n11 50.429553\n13 37.580167\n ... \n531 43.077781\n532 46.435103\n535 46.503775\n536 48.495278\n539 39.850174\nName: Lat, Length: 175, dtype: float64\nThe r-value is: 0.01691477549608124\n"
]
],
[
[
"#### Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression",
"_____no_output_____"
]
],
[
[
"x_values = df_NorthernHem[\"Lat\"]\ny_values = df_NorthernHem[\"Wind Speed\"]",
"_____no_output_____"
],
[
"plt.title(\"City Latitude vs. Wind Speed\")\nplt.ylabel(\"Wind Speed (mph)\")\n\nregressplot(x_values, y_values)",
"1 46.973037\n2 47.942082\n3 41.891273\n11 50.429553\n13 37.580167\n ... \n531 43.077781\n532 46.435103\n535 46.503775\n536 48.495278\n539 39.850174\nName: Lat, Length: 175, dtype: float64\nThe r-value is: 0.01691477549608124\n"
]
],
[
[
"#### Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression",
"_____no_output_____"
]
],
[
[
"x_values = df_SouthernHem[\"Lat\"]\ny_values = df_SouthernHem[\"Wind Speed\"]",
"_____no_output_____"
],
[
"plt.title(\"City Latitude vs. Wind Speed\")\nplt.ylabel(\"Wind Speed (mph)\")\n\nregressplot(x_values, y_values)",
"1 8.008997\n2 7.884980\n3 8.659353\n11 7.566637\n13 9.211082\n ... \n531 8.507506\n532 8.077841\n535 8.069052\n536 7.814183\n539 8.920570\nName: Lat, Length: 175, dtype: float64\nThe r-value is: 0.013088588753058851\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",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aae173359bc5400d2b8c008217566679653f3bc
| 100,752 |
ipynb
|
Jupyter Notebook
|
notebooks/sklearn-svm-toy.ipynb
|
CSCfi/machine-learning-scripts
|
005f9343fb703ca2b6b11b5c2369e19efcaa5f62
|
[
"MIT"
] | 59 |
2018-04-27T04:34:41.000Z
|
2022-03-16T02:43:50.000Z
|
machine-learning-scripts/notebooks/sklearn-svm-toy.ipynb
|
exajobs/machine-learning-collection
|
84444f0bfe351efea6e3b2813e47723bd8d769cc
|
[
"MIT"
] | 1 |
2020-10-10T05:04:00.000Z
|
2020-10-12T08:19:38.000Z
|
notebooks/sklearn-svm-toy.ipynb
|
CSCfi/machine-learning-scripts
|
005f9343fb703ca2b6b11b5c2369e19efcaa5f62
|
[
"MIT"
] | 53 |
2017-04-14T09:35:04.000Z
|
2022-02-28T19:19:36.000Z
| 189.383459 | 34,944 | 0.906066 |
[
[
[
"# Binary classification with Support Vector Machines (SVM)",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import LinearSVC, SVC\nfrom ipywidgets import interact, interactive, fixed\nfrom numpy.random import default_rng\n\nplt.rcParams['figure.figsize'] = [9.5, 6]\nrng = default_rng(seed=42)",
"_____no_output_____"
]
],
[
[
"## Two Gaussian distributions\n\nLet's generate some data, two sets of Normally distributed points...",
"_____no_output_____"
]
],
[
[
"def plot_data():\n plt.xlim(0.0, 1.0)\n plt.ylim(0.0, 1.0)\n plt.plot(x1, y1, 'bs', markersize=6)\n plt.plot(x2, y2, 'rx', markersize=6)",
"_____no_output_____"
],
[
"s1=0.01\ns2=0.01\nn1=30\nn2=30\n\nx1, y1 = rng.multivariate_normal([0.5, 0.3], [[s1, 0], [0, s1]], n1).T\nx2, y2 = rng.multivariate_normal([0.7, 0.7], [[s2, 0], [0, s2]], n2).T\nplot_data()\nplt.suptitle('generated data points')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Separating hyperplane\n\nLinear classifiers: separate the two distributions with a line (hyperplane)",
"_____no_output_____"
]
],
[
[
"def plot_line(slope, intercept, show_params=False):\n x_vals = np.linspace(0.0, 1.0)\n y_vals = slope*x_vals +intercept\n plt.plot(x_vals, y_vals, '--')\n if show_params:\n plt.title('slope={:.4f}, intercept={:.4f}'.format(slope, intercept))",
"_____no_output_____"
]
],
[
[
"You can try out different parameters (slope, intercept) for the line. Note that there are many (in fact an infinite number) of lines that separate the two classes.",
"_____no_output_____"
]
],
[
[
"#plot_data()\n#plot_line(-1.1, 1.1)\n#plot_line(-0.23, 0.62)\n#plot_line(-0.41, 0.71)\n#plt.savefig('just_points2.png')",
"_____no_output_____"
],
[
"def do_plot_interactive(slope=-1.0, intercept=1.0):\n plot_data()\n plot_line(slope, intercept, True)\n plt.suptitle('separating hyperplane (line)')\n\ninteractive_plot = interactive(do_plot_interactive, slope=(-2.0, 2.0), intercept=(0.5, 1.5))\noutput = interactive_plot.children[-1]\noutput.layout.height = '450px'\ninteractive_plot",
"_____no_output_____"
]
],
[
[
"## Logistic regression\n\nLet's create a training set $\\mathbf{X}$ with labels in $\\mathbf{y}$ with our points (in shuffled order).",
"_____no_output_____"
]
],
[
[
"X = np.block([[x1, x2], [y1, y2]]).T\ny = np.hstack((np.repeat(0, len(x1)), np.repeat(1, len(x2))))\n\nrand_idx = rng.permutation(len(x1) + len(x2))\nX = X[rand_idx]\ny = y[rand_idx]\nprint(X.shape, y.shape)\nprint(X[:10,:])\nprint(y[:10].reshape(-1,1))",
"(60, 2) (60,)\n[[0.51278404 0.26837574]\n [0.53126656 0.55528875]\n [0.41755188 0.36505928]\n [0.76255904 0.66906535]\n [0.48151376 0.23190705]\n [0.49831988 0.21469561]\n [0.640585 0.55539421]\n [0.77112266 0.77933472]\n [0.50660307 0.41272412]\n [0.65727474 0.71585397]]\n[[0]\n [1]\n [0]\n [1]\n [0]\n [0]\n [1]\n [1]\n [0]\n [1]]\n"
]
],
[
[
"The task is now to learn a classification model $\\mathbf{y} = f(\\mathbf{X})$.",
"_____no_output_____"
],
[
"First, let's try [logistic regression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html).",
"_____no_output_____"
]
],
[
[
"clf_lr = LogisticRegression(penalty='none')\nclf_lr.fit(X, y)",
"_____no_output_____"
],
[
"w1 = clf_lr.coef_[0][0]\nw2 = clf_lr.coef_[0][1]\nb = clf_lr.intercept_[0]\n\nplt.suptitle('Logistic regression')\nplot_data()\nplot_line(slope=-w1/w2, intercept=-b/w2, show_params=True)",
"_____no_output_____"
]
],
[
[
"## Linear SVM",
"_____no_output_____"
]
],
[
[
"clf_lsvm = SVC(C=1000, kernel='linear')\nclf_lsvm.fit(X, y)",
"_____no_output_____"
],
[
"w1 = clf_lsvm.coef_[0][0]\nw2 = clf_lsvm.coef_[0][1]\nb = clf_lsvm.intercept_[0]\n\nplt.suptitle('Linear SVM')\nplot_data()\nplot_line(slope=-w1/w2, intercept=-b/w2, show_params=True)",
"_____no_output_____"
],
[
"def plot_clf(clf):\n # plot the decision function\n ax = plt.gca()\n xlim = ax.get_xlim()\n ylim = ax.get_ylim()\n\n # create grid to evaluate model\n xx = np.linspace(xlim[0], xlim[1], 30)\n yy = np.linspace(ylim[0], ylim[1], 30)\n YY, XX = np.meshgrid(yy, xx)\n xy = np.vstack([XX.ravel(), YY.ravel()]).T\n Z = clf.decision_function(xy).reshape(XX.shape)\n\n # plot decision boundary and margins\n ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,\n linestyles=['--', '-', '--'])\n # plot support vectors\n ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100,\n linewidth=1, facecolors='none', edgecolors='k')",
"_____no_output_____"
]
],
[
[
"Let's try different $C$ values. We'll also visualize the margins and support vectors.",
"_____no_output_____"
]
],
[
[
"def do_plot_svm(C=1000.0):\n clf = SVC(C=C, kernel='linear')\n clf.fit(X, y)\n plot_data()\n plot_clf(clf)\n \ninteractive_plot = interactive(do_plot_svm, C=widgets.FloatLogSlider(value=1000, base=10, min=-0.5, max=4, step=0.2))\noutput = interactive_plot.children[-1]\noutput.layout.height = '400px'\ninteractive_plot",
"_____no_output_____"
],
[
"#do_plot_svm()\n#plt.savefig('linear-svm.png')",
"_____no_output_____"
]
],
[
[
"## Kernel SVM",
"_____no_output_____"
]
],
[
[
"clf_ksvm = SVC(C=10, kernel='rbf')\nclf_ksvm.fit(X, y)",
"_____no_output_____"
],
[
"plot_data()\nplot_clf(clf_ksvm)\nplt.savefig('kernel-svm.png')",
"_____no_output_____"
],
[
"def do_plot_svm(C=1000.0):\n clf = SVC(C=C, kernel='rbf')\n clf.fit(X, y)\n plot_data()\n plot_clf(clf)\n \ninteractive_plot = interactive(do_plot_svm, C=widgets.FloatLogSlider(value=100, base=10, min=-1, max=3, step=0.2))\noutput = interactive_plot.children[-1]\noutput.layout.height = '400px'\ninteractive_plot",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4aae1c201086396bf86aa8065bec3acd63bb0a89
| 78,028 |
ipynb
|
Jupyter Notebook
|
Folders/Optimizing_Model.ipynb
|
Z1WenChen/Project_2
|
bf3a0f6d6eab1b20cef3de2adb066fe6ed3af255
|
[
"MIT"
] | null | null | null |
Folders/Optimizing_Model.ipynb
|
Z1WenChen/Project_2
|
bf3a0f6d6eab1b20cef3de2adb066fe6ed3af255
|
[
"MIT"
] | null | null | null |
Folders/Optimizing_Model.ipynb
|
Z1WenChen/Project_2
|
bf3a0f6d6eab1b20cef3de2adb066fe6ed3af255
|
[
"MIT"
] | null | null | null | 43.984216 | 170 | 0.371021 |
[
[
[
"import pandas as pd\nfrom finta import TA\nimport numpy as np",
"_____no_output_____"
],
[
"#yahoo finance stock data (for longer timeframe)\nimport yfinance as yf\n\ndef stock_df(ticker, start, end):\n stock = yf.Ticker(ticker)\n stock_df = stock.history(start = start, end = end)\n return stock_df\n\nstart = pd.to_datetime('2015-01-01')\nend = pd.to_datetime('today')\n \nspy_df = stock_df('SPY', start, end)\n\nlen(spy_df)",
"_____no_output_____"
],
[
"# spy_df[\"Monetary Gain\"] = spy_df[\"Close\"].diff()\nspy_df['Actual Return'] = spy_df[\"Close\"].pct_change()\n\nspy_df.loc[(spy_df['Actual Return'] >= 0), 'Return Direction'] = 1\nspy_df.loc[(spy_df['Actual Return'] < 0), 'Return Direction'] = 0\n\n# spy_df['Trades'] = np.abs(spy_df['Trading Signal'].diff())\n\n# spy_df['Strategy Returns'] = spy_df['Actual Return'] * spy_df['Trading Signal'].shift()\n\nspy_df.dropna(inplace= True)\n\nspy_df.tail(20)",
"_____no_output_____"
],
[
"spy_technical_indicators = pd.DataFrame()\n\n#Creating RSI evaluation metrics \nspy_technical_indicators[\"RSI\"] = TA.RSI(spy_df, 14)\nspy_technical_indicators[\"RSI Evaluation\"] = \"No Abnormalities\"\nspy_technical_indicators.loc[spy_technical_indicators[\"RSI\"] > 70, 'RSI Evaluation'] = \"Overvalued\"\nspy_technical_indicators.loc[spy_technical_indicators[\"RSI\"] < 30, 'RSI Evaluation'] = \"Undervalued\"\n\nspy_technical_indicators[\"RSI Lag\"] = spy_technical_indicators[\"RSI Evaluation\"].shift(1)\n\n\nfor index, row in spy_technical_indicators.iterrows():\n if (spy_technical_indicators.loc[index, \"RSI Evaluation\"] == \"No Abnormalities\" and spy_technical_indicators.loc[index, \"RSI Lag\"] == \"Undervalued\"):\n spy_technical_indicators.loc[index, \"RSI Evaluation\"] = \"RSI Bullish Signal\"\n if (spy_technical_indicators.loc[index, \"RSI Evaluation\"] == \"No Abnormalities\" and spy_technical_indicators.loc[index, \"RSI Lag\"] == \"Overvalued\"):\n spy_technical_indicators.loc[index, \"RSI Evaluation\"] = \"RSI Bearish Signal\"\n\n\nspy_technical_indicators.drop(columns = [\"RSI Lag\"], inplace = True)\n \n#Creating CCI evaluation metrics \nspy_technical_indicators[\"CCI\"] = TA.CCI(spy_df, 14)\nspy_technical_indicators[\"CCI Lag\"] = spy_technical_indicators[\"CCI\"].shift(1)\n\nfor index, row in spy_technical_indicators.iterrows():\n if (spy_technical_indicators.loc[index, \"CCI\"] > spy_technical_indicators.loc[index, \"CCI Lag\"]):\n if (spy_technical_indicators.loc[index, \"CCI\"] > 0 and spy_technical_indicators.loc[index, \"CCI Lag\"] < 0):\n spy_technical_indicators.loc[index, \"CCI Evaluation\"] = \"CCI Uptrend\"\n else:\n spy_technical_indicators.loc[index, \"CCI Evaluation\"] = \"CCI Potential Uptrend\"\n \n if (spy_technical_indicators.loc[index, \"CCI\"] < spy_technical_indicators.loc[index, \"CCI Lag\"]):\n if (spy_technical_indicators.loc[index, \"CCI\"] < 0 and spy_technical_indicators.loc[index, \"CCI Lag\"] > 0):\n spy_technical_indicators.loc[index, \"CCI Evaluation\"] = \"CCI Downtrend\"\n else:\n spy_technical_indicators.loc[index, \"CCI Evaluation\"] = \"CCI Potential Downtrend\"\n\nspy_technical_indicators.drop(columns = [\"CCI Lag\"], inplace = True)\n\n#Creating Rate of Change evaluation metrics\nspy_technical_indicators[\"ROC\"] = TA.ROC(spy_df, 20)\nspy_technical_indicators[\"ROC Lag\"] = spy_technical_indicators[\"ROC\"].shift(1)\n\nfor index, row in spy_technical_indicators.iterrows():\n if (spy_technical_indicators.loc[index, \"ROC\"] > 0 and spy_technical_indicators.loc[index, \"ROC Lag\"] < 0):\n spy_technical_indicators.loc[index, \"ROC Evaluation\"] = \"ROC Rising Momentum\"\n if (spy_technical_indicators.loc[index, \"ROC\"] < 0 and spy_technical_indicators.loc[index, \"ROC Lag\"] > 0):\n spy_technical_indicators.loc[index, \"ROC Evaluation\"] = \"ROC Falling Momentum\"\n else:\n spy_technical_indicators.loc[index, \"ROC Evaluation\"] = \"ROC Uninterpretable\"\n \nspy_technical_indicators.drop(columns = [\"ROC Lag\"], inplace = True)\n\n#Creating Stochasic Indicator evaluation metrics\nspy_technical_indicators[\"STO\"] = TA.STOCH(spy_df)\n\n\nspy_technical_indicators[\"Returns\"] = spy_df[\"Return Direction\"]\nspy_technical_indicators.dropna(inplace = True)\n\nspy_technical_indicators",
"_____no_output_____"
],
[
"from sklearn.preprocessing import StandardScaler,OneHotEncoder\n\ncategorical_variables = list(spy_technical_indicators.dtypes[spy_technical_indicators.dtypes == \"object\"].index)\n\ncategorical_variables\nenc = OneHotEncoder(sparse= False)\nencoded_data = enc.fit_transform(spy_technical_indicators[categorical_variables])\n\nencoded_df = pd.DataFrame(encoded_data, columns = enc.get_feature_names(categorical_variables), index = spy_technical_indicators.index)\n\nencoded_df = pd.concat([encoded_df, spy_technical_indicators.drop(columns = categorical_variables)], axis = 1)\nencoded_df",
"_____no_output_____"
],
[
"import tensorflow as tf\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.models import Sequential\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nX = encoded_df.drop(columns = [\"Returns\"])\ny = encoded_df[\"Returns\"]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)\n\nscaler = StandardScaler()\n\nX_scaler = scaler.fit(X_train)\n\nX_train_scaled = X_scaler.transform(X_train)\nX_test_scaled = X_scaler.transform(X_test)",
"_____no_output_____"
],
[
"neural = Sequential()\n\nnumber_input_features = len(X.columns)\nhidden_nodes_layer1 = (number_input_features + 1) // 2 \nhidden_nodes_layer2 = (hidden_nodes_layer1 + 1) // 2\n\nneural.add(Dense(units=hidden_nodes_layer1, input_dim=number_input_features, activation=\"elu\"))\nneural.add(Dense(units=hidden_nodes_layer2, activation=\"elu\"))\nneural.add(Dense(units=1, activation=\"sigmoid\"))\n\nneural.summary()",
"Model: \"sequential\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n dense (Dense) (None, 8) 128 \n \n dense_1 (Dense) (None, 4) 36 \n \n dense_2 (Dense) (None, 1) 5 \n \n=================================================================\nTotal params: 169\nTrainable params: 169\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"neural.compile(loss = \"binary_crossentropy\", optimizer = \"adam\", metrics = [\"accuracy\"])\n\nmodel = neural.fit(X_train_scaled, y_train, epochs = 200)",
"Epoch 1/200\n41/41 [==============================] - 0s 592us/step - loss: 0.5881 - accuracy: 0.7056\nEpoch 2/200\n41/41 [==============================] - 0s 598us/step - loss: 0.5306 - accuracy: 0.7597\nEpoch 3/200\n41/41 [==============================] - 0s 623us/step - loss: 0.4941 - accuracy: 0.7727\nEpoch 4/200\n41/41 [==============================] - 0s 823us/step - loss: 0.4654 - accuracy: 0.7941\nEpoch 5/200\n41/41 [==============================] - 0s 848us/step - loss: 0.4433 - accuracy: 0.8124\nEpoch 6/200\n41/41 [==============================] - 0s 848us/step - loss: 0.4259 - accuracy: 0.8253\nEpoch 7/200\n41/41 [==============================] - 0s 947us/step - loss: 0.4130 - accuracy: 0.8322\nEpoch 8/200\n41/41 [==============================] - 0s 873us/step - loss: 0.4050 - accuracy: 0.8284\nEpoch 9/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3989 - accuracy: 0.8413\nEpoch 10/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3940 - accuracy: 0.8322\nEpoch 11/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3905 - accuracy: 0.8375\nEpoch 12/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3870 - accuracy: 0.8391\nEpoch 13/200\n41/41 [==============================] - 0s 923us/step - loss: 0.3842 - accuracy: 0.8398\nEpoch 14/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3816 - accuracy: 0.8413\nEpoch 15/200\n41/41 [==============================] - 0s 898us/step - loss: 0.3795 - accuracy: 0.8421\nEpoch 16/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3775 - accuracy: 0.8429\nEpoch 17/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3759 - accuracy: 0.8452\nEpoch 18/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3750 - accuracy: 0.8444\nEpoch 19/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3746 - accuracy: 0.8444\nEpoch 20/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3726 - accuracy: 0.8436\nEpoch 21/200\n41/41 [==============================] - 0s 698us/step - loss: 0.3717 - accuracy: 0.8391\nEpoch 22/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3709 - accuracy: 0.8429\nEpoch 23/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3712 - accuracy: 0.8436\nEpoch 24/200\n41/41 [==============================] - 0s 574us/step - loss: 0.3697 - accuracy: 0.8452\nEpoch 25/200\n41/41 [==============================] - 0s 648us/step - loss: 0.3697 - accuracy: 0.8429\nEpoch 26/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3687 - accuracy: 0.8452\nEpoch 27/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3688 - accuracy: 0.8429\nEpoch 28/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3678 - accuracy: 0.8429\nEpoch 29/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3678 - accuracy: 0.8406\nEpoch 30/200\n41/41 [==============================] - 0s 947us/step - loss: 0.3679 - accuracy: 0.8436\nEpoch 31/200\n41/41 [==============================] - 0s 898us/step - loss: 0.3670 - accuracy: 0.8467\nEpoch 32/200\n41/41 [==============================] - 0s 898us/step - loss: 0.3668 - accuracy: 0.8436\nEpoch 33/200\n41/41 [==============================] - 0s 898us/step - loss: 0.3671 - accuracy: 0.8429\nEpoch 34/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3667 - accuracy: 0.8452\nEpoch 35/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3662 - accuracy: 0.8459\nEpoch 36/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3660 - accuracy: 0.8444\nEpoch 37/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3660 - accuracy: 0.8459\nEpoch 38/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3653 - accuracy: 0.8497\nEpoch 39/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3655 - accuracy: 0.8474\nEpoch 40/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3651 - accuracy: 0.8444\nEpoch 41/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3648 - accuracy: 0.8482\nEpoch 42/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3648 - accuracy: 0.8482\nEpoch 43/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3653 - accuracy: 0.8459\nEpoch 44/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3645 - accuracy: 0.8444\nEpoch 45/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3644 - accuracy: 0.8444\nEpoch 46/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3654 - accuracy: 0.8429\nEpoch 47/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3649 - accuracy: 0.8444\nEpoch 48/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3640 - accuracy: 0.8482\nEpoch 49/200\n41/41 [==============================] - 0s 898us/step - loss: 0.3641 - accuracy: 0.8459\nEpoch 50/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3641 - accuracy: 0.8459\nEpoch 51/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3640 - accuracy: 0.8459\nEpoch 52/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3641 - accuracy: 0.8444\nEpoch 53/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3632 - accuracy: 0.8429\nEpoch 54/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3633 - accuracy: 0.8467\nEpoch 55/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3629 - accuracy: 0.8482\nEpoch 56/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3626 - accuracy: 0.8429\nEpoch 57/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3625 - accuracy: 0.8436\nEpoch 58/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3628 - accuracy: 0.8490\nEpoch 59/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3621 - accuracy: 0.8459\nEpoch 60/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3627 - accuracy: 0.8467\nEpoch 61/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3617 - accuracy: 0.8444\nEpoch 62/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3619 - accuracy: 0.8482\nEpoch 63/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3620 - accuracy: 0.8444\nEpoch 64/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3626 - accuracy: 0.8452\nEpoch 65/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3614 - accuracy: 0.8490\nEpoch 66/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3615 - accuracy: 0.8459\nEpoch 67/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3611 - accuracy: 0.8482\nEpoch 68/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3610 - accuracy: 0.8459\nEpoch 69/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3618 - accuracy: 0.8474\nEpoch 70/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3610 - accuracy: 0.8482\nEpoch 71/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3611 - accuracy: 0.8474\nEpoch 72/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3607 - accuracy: 0.8467\nEpoch 73/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3607 - accuracy: 0.8474\nEpoch 74/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3600 - accuracy: 0.8482\nEpoch 75/200\n41/41 [==============================] - 0s 972us/step - loss: 0.3604 - accuracy: 0.8490\nEpoch 76/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3605 - accuracy: 0.8459\nEpoch 77/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3605 - accuracy: 0.8421\nEpoch 78/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3597 - accuracy: 0.8505\nEpoch 79/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3598 - accuracy: 0.8490\nEpoch 80/200\n41/41 [==============================] - 0s 898us/step - loss: 0.3600 - accuracy: 0.8467\nEpoch 81/200\n41/41 [==============================] - 0s 898us/step - loss: 0.3594 - accuracy: 0.8482\nEpoch 82/200\n41/41 [==============================] - 0s 2ms/step - loss: 0.3597 - accuracy: 0.8482\nEpoch 83/200\n41/41 [==============================] - 0s 923us/step - loss: 0.3588 - accuracy: 0.8467\nEpoch 84/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3595 - accuracy: 0.8459\nEpoch 85/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3588 - accuracy: 0.8474\nEpoch 86/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3590 - accuracy: 0.8459\nEpoch 87/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3592 - accuracy: 0.8482\nEpoch 88/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3580 - accuracy: 0.8474\nEpoch 89/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3580 - accuracy: 0.8490\nEpoch 90/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3577 - accuracy: 0.8474\nEpoch 91/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3581 - accuracy: 0.8497\nEpoch 92/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3573 - accuracy: 0.8474\nEpoch 93/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3576 - accuracy: 0.8490\nEpoch 94/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3575 - accuracy: 0.8474\nEpoch 95/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3569 - accuracy: 0.8444\nEpoch 96/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3565 - accuracy: 0.8474\nEpoch 97/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3561 - accuracy: 0.8490\nEpoch 98/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3560 - accuracy: 0.8467\nEpoch 99/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3562 - accuracy: 0.8467\nEpoch 100/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3563 - accuracy: 0.8436\nEpoch 101/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3566 - accuracy: 0.8459\nEpoch 102/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3563 - accuracy: 0.8474\nEpoch 103/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3544 - accuracy: 0.8474\nEpoch 104/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3544 - accuracy: 0.8490\nEpoch 105/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3538 - accuracy: 0.8482\nEpoch 106/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3536 - accuracy: 0.8490\nEpoch 107/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3537 - accuracy: 0.8452\nEpoch 108/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3533 - accuracy: 0.8490\nEpoch 109/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3526 - accuracy: 0.8474\nEpoch 110/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3526 - accuracy: 0.8497\nEpoch 111/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3521 - accuracy: 0.8482\nEpoch 112/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3524 - accuracy: 0.8482\nEpoch 113/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3512 - accuracy: 0.8497\nEpoch 114/200\n41/41 [==============================] - 0s 844us/step - loss: 0.3513 - accuracy: 0.8459\nEpoch 115/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3511 - accuracy: 0.8467\nEpoch 116/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3512 - accuracy: 0.8482\nEpoch 117/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3504 - accuracy: 0.8459\nEpoch 118/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3495 - accuracy: 0.8474\nEpoch 119/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3502 - accuracy: 0.8474\nEpoch 120/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3495 - accuracy: 0.8467\nEpoch 121/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3490 - accuracy: 0.8459\nEpoch 122/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3488 - accuracy: 0.8474\nEpoch 123/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3487 - accuracy: 0.8505\nEpoch 124/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3480 - accuracy: 0.8459\nEpoch 125/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3475 - accuracy: 0.8467\nEpoch 126/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3474 - accuracy: 0.8497\nEpoch 127/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3475 - accuracy: 0.8459\nEpoch 128/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3473 - accuracy: 0.8490\nEpoch 129/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3467 - accuracy: 0.8513\nEpoch 130/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3464 - accuracy: 0.8452\nEpoch 131/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3455 - accuracy: 0.8490\nEpoch 132/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3460 - accuracy: 0.8467\nEpoch 133/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3454 - accuracy: 0.8467\nEpoch 134/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3460 - accuracy: 0.8459\nEpoch 135/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3444 - accuracy: 0.8467\nEpoch 136/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3442 - accuracy: 0.8513\nEpoch 137/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3441 - accuracy: 0.8513\nEpoch 138/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3439 - accuracy: 0.8505\nEpoch 139/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3434 - accuracy: 0.8505\nEpoch 140/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3438 - accuracy: 0.8497\nEpoch 141/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3431 - accuracy: 0.8497\nEpoch 142/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3428 - accuracy: 0.8520\nEpoch 143/200\n41/41 [==============================] - 0s 923us/step - loss: 0.3432 - accuracy: 0.8482\nEpoch 144/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3425 - accuracy: 0.8543\nEpoch 145/200\n41/41 [==============================] - 0s 947us/step - loss: 0.3424 - accuracy: 0.8474\nEpoch 146/200\n41/41 [==============================] - 0s 922us/step - loss: 0.3419 - accuracy: 0.8505\nEpoch 147/200\n41/41 [==============================] - 0s 923us/step - loss: 0.3420 - accuracy: 0.8497\nEpoch 148/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3422 - accuracy: 0.8520\nEpoch 149/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3412 - accuracy: 0.8528\nEpoch 150/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3413 - accuracy: 0.8490\nEpoch 151/200\n41/41 [==============================] - 0s 723us/step - loss: 0.3409 - accuracy: 0.8497\nEpoch 152/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3403 - accuracy: 0.8535\nEpoch 153/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3408 - accuracy: 0.8520\nEpoch 154/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3402 - accuracy: 0.8520\nEpoch 155/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3401 - accuracy: 0.8528\nEpoch 156/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3401 - accuracy: 0.8505\nEpoch 157/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3405 - accuracy: 0.8543\nEpoch 158/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3392 - accuracy: 0.8528\nEpoch 159/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3391 - accuracy: 0.8551\nEpoch 160/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3387 - accuracy: 0.8551\nEpoch 161/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3387 - accuracy: 0.8528\nEpoch 162/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3391 - accuracy: 0.8528\nEpoch 163/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3383 - accuracy: 0.8535\nEpoch 164/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3387 - accuracy: 0.8535\nEpoch 165/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3383 - accuracy: 0.8566\nEpoch 166/200\n41/41 [==============================] - 0s 723us/step - loss: 0.3384 - accuracy: 0.8535\nEpoch 167/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3376 - accuracy: 0.8589\nEpoch 168/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3375 - accuracy: 0.8551\nEpoch 169/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3379 - accuracy: 0.8490\nEpoch 170/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3388 - accuracy: 0.8543\nEpoch 171/200\n41/41 [==============================] - 0s 598us/step - loss: 0.3372 - accuracy: 0.8551\nEpoch 172/200\n41/41 [==============================] - 0s 623us/step - loss: 0.3371 - accuracy: 0.8543\nEpoch 173/200\n41/41 [==============================] - 0s 648us/step - loss: 0.3367 - accuracy: 0.8551\nEpoch 174/200\n41/41 [==============================] - 0s 648us/step - loss: 0.3361 - accuracy: 0.8543\nEpoch 175/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3365 - accuracy: 0.8566\nEpoch 176/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3365 - accuracy: 0.8543\nEpoch 177/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3359 - accuracy: 0.8574\nEpoch 178/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3366 - accuracy: 0.8558\nEpoch 179/200\n41/41 [==============================] - 0s 873us/step - loss: 0.3357 - accuracy: 0.8574\nEpoch 180/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3358 - accuracy: 0.8543\nEpoch 181/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3355 - accuracy: 0.8574\nEpoch 182/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3356 - accuracy: 0.8566\nEpoch 183/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3357 - accuracy: 0.8589\nEpoch 184/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3354 - accuracy: 0.8558\nEpoch 185/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3353 - accuracy: 0.8581\nEpoch 186/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3346 - accuracy: 0.8581\nEpoch 187/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3345 - accuracy: 0.8558\nEpoch 188/200\n41/41 [==============================] - 0s 1ms/step - loss: 0.3354 - accuracy: 0.8551\nEpoch 189/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3347 - accuracy: 0.8574\nEpoch 190/200\n41/41 [==============================] - 0s 972us/step - loss: 0.3348 - accuracy: 0.8551\nEpoch 191/200\n41/41 [==============================] - 0s 997us/step - loss: 0.3345 - accuracy: 0.8551\nEpoch 192/200\n41/41 [==============================] - 0s 698us/step - loss: 0.3336 - accuracy: 0.8558\nEpoch 193/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3350 - accuracy: 0.8535\nEpoch 194/200\n41/41 [==============================] - 0s 848us/step - loss: 0.3341 - accuracy: 0.8589\nEpoch 195/200\n41/41 [==============================] - 0s 823us/step - loss: 0.3345 - accuracy: 0.8535\nEpoch 196/200\n41/41 [==============================] - 0s 773us/step - loss: 0.3345 - accuracy: 0.8528\nEpoch 197/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3335 - accuracy: 0.8543\nEpoch 198/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3341 - accuracy: 0.8551\nEpoch 199/200\n41/41 [==============================] - 0s 748us/step - loss: 0.3338 - accuracy: 0.8513\nEpoch 200/200\n41/41 [==============================] - 0s 798us/step - loss: 0.3347 - accuracy: 0.8535\n"
],
[
"Y_prediction = (neural.predict(X_train_scaled) > 0.5).astype(\"int32\")\nY_prediction = Y_prediction.squeeze()\n\nresults = pd.DataFrame( {\"Predictions\": Y_prediction, \"Actual\": y_train})\ndisplay(results)\n\nmodel_loss, model_accuracy = neural.evaluate(X_test_scaled,y_test,verbose=2)\nprint(f\"Loss: {model_loss}, Accuracy: {model_accuracy}\")",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aae27e81c8a68996ffbdb3e5c2821e0bda57a3d
| 4,203 |
ipynb
|
Jupyter Notebook
|
notebooks/2018-10-25-compare-multiple-step-vs-single-step.ipynb
|
kbren/uwnet
|
aac01e243c19686b10c214b1c56b0bb7b7e06a07
|
[
"MIT"
] | 1 |
2020-06-22T19:36:34.000Z
|
2020-06-22T19:36:34.000Z
|
notebooks/2018-10-25-compare-multiple-step-vs-single-step.ipynb
|
kbren/uwnet
|
aac01e243c19686b10c214b1c56b0bb7b7e06a07
|
[
"MIT"
] | null | null | null |
notebooks/2018-10-25-compare-multiple-step-vs-single-step.ipynb
|
kbren/uwnet
|
aac01e243c19686b10c214b1c56b0bb7b7e06a07
|
[
"MIT"
] | 2 |
2021-01-05T10:57:32.000Z
|
2022-02-07T19:01:53.000Z
| 31.133333 | 293 | 0.578872 |
[
[
[
"We saw in this [journal entry](http://wiki.noahbrenowitz.com/doku.php?id=journal:2018-10:day-2018-10-24#run_110) that multiple-step trained neural network gives a very imbalanced estimate, but the two-step trained neural network gives a good answer. Where do these two patterns disagree?",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport xarray as xr\nimport click\nimport torch\nfrom uwnet.model import call_with_xr\nimport holoviews as hv\nfrom holoviews.operation import decimate\nhv.extension('bokeh')\n\n\ndef column_integrate(data_array, mass):\n return (data_array * mass).sum('z')\n\n\ndef compute_apparent_sources(model_path, ds):\n model = torch.load(model_path)\n \n return call_with_xr(model, ds, drop_times=0)\n\ndef get_single_location(ds, location=(32,0)):\n y, x = location\n return ds.isel(y=slice(y,y+1), x=slice(x,x+1))\n\ndef dict_to_dataset(datasets, dim='key'):\n \"\"\"Concatenate a dict of datasets along a new axis\"\"\"\n keys, values = zip(*datasets.items())\n idx = pd.Index(keys, name=dim)\n return xr.concat(values, dim=idx)\n\ndef dataarray_to_table(dataarray):\n return dataarray.to_dataset('key').to_dataframe().reset_index()\n\ndef get_apparent_sources(model_paths, data_path):\n ds = xr.open_dataset(data_path)\n location = get_single_location(ds, location=(32,0))\n sources = {training_strategy: compute_apparent_sources(model_path, location)\n for training_strategy, model_path in model_paths.items()}\n return dict_to_dataset(sources)",
"_____no_output_____"
],
[
"model_paths = {\n 'multi': '../models/113/3.pkl',\n 'single': '../models/110/3.pkl'\n}\n\ndata_path = \"../data/processed/training.nc\"\n\nsources = get_apparent_sources(model_paths, data_path)",
"_____no_output_____"
]
],
[
[
"# Apparent moistening and heating\n\nHere we scatter plot the apparent heating and moistening:",
"_____no_output_____"
]
],
[
[
"%%opts Scatter[width=500, height=500, color_index='z'](cmap='viridis', alpha=.2)\n%%opts Curve(color='black')\n\nlims = (-30, 40)\ndf = dataarray_to_table(sources.QT)\nmoisture_source = hv.Scatter(df, kdims=[\"multi\", \"single\"]).groupby('z').redim.range(multi=lims, single=lims) \\\n *hv.Curve((lims, lims))\n\nlims = (-30, 40)\ndf = dataarray_to_table(sources.SLI)\nheating = hv.Scatter(df, kdims=[\"multi\", \"single\"]).groupby('z').redim.range(multi=lims, single=lims) \\\n *hv.Curve((lims, lims))\n\n\nmoisture_source.relabel(\"Moistening (g/kg/day)\") + heating.relabel(\"Heating (K/day)\")",
"_____no_output_____"
]
],
[
[
"The multistep moistening is far too negative in the upper parts of the atmosphere, and the corresponding heating is too positive. Does this **happen because the moisture is negative in those regions**.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aae2b55fd36eccd1b2567ab480ca4373a0b745e
| 50,734 |
ipynb
|
Jupyter Notebook
|
2. Filtrado de DataFrames y Series - ejercicio.ipynb
|
IrayP/PythonExamenFinal
|
65229846ce58bdf2d1310e9beb2be247cb552c3b
|
[
"Apache-2.0"
] | null | null | null |
2. Filtrado de DataFrames y Series - ejercicio.ipynb
|
IrayP/PythonExamenFinal
|
65229846ce58bdf2d1310e9beb2be247cb552c3b
|
[
"Apache-2.0"
] | null | null | null |
2. Filtrado de DataFrames y Series - ejercicio.ipynb
|
IrayP/PythonExamenFinal
|
65229846ce58bdf2d1310e9beb2be247cb552c3b
|
[
"Apache-2.0"
] | null | null | null | 43.925541 | 13,884 | 0.546261 |
[
[
[
"# Ejercicio - Busqueda de Alojamiento en Airbnb.\n\nSupongamos que somos un agente de [Airbnb](http://www.airbnb.com) localizado en Lisboa, y tenemos que atender peticiones de varios clientes. Tenemos un archivo llamado `airbnb.csv` (en la carpeta data) donde tenemos información de todos los alojamientos de Airbnb en Lisboa.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\ndf_airbnb = pd.read_csv(\"./src/pandas/airbnb.csv\")",
"_____no_output_____"
],
[
"df_airbnb.head()",
"_____no_output_____"
],
[
"df_airbnb.dtypes",
"_____no_output_____"
]
],
[
[
"En concreto el dataset tiene las siguientes variables:\n- room_id: el identificador de la propiedad\n- host_id: el identificador del dueño de la propiedad\n- room_type: tipo de propiedad (vivienda completa/(habitacion para compartir/habitación privada)\n- neighborhood: el barrio de Lisboa\n- reviews: El numero de opiniones\n- overall_satisfaction: Puntuacion media del apartamento\n- accommodates: El numero de personas que se pueden alojar en la propiedad\n- bedrooms: El número de habitaciones\n- price: El precio (en euros) por noche",
"_____no_output_____"
],
[
"## Usando Pandas",
"_____no_output_____"
],
[
"### Caso 1.\n\nAlicia va a ir a Lisboa durante una semana con su marido y sus 2 hijos. Están buscando un apartamento con habitaciones separadas para los padres y los hijos. No les importa donde alojarse o el precio, simplemente quieren tener una experiencia agradable. Esto significa que solo aceptan lugares con más de 10 críticas con una puntuación mayor de 4. Cuando seleccionemos habitaciones para Alicia, tenemos que asegurarnos de ordenar las habitaciones de mejor a peor puntuación. Para aquellas habitaciones que tienen la misma puntuación, debemos mostrar antes aquellas con más críticas. Debemos darle 3 alternativas.",
"_____no_output_____"
]
],
[
[
"df_airbnb.room_type.unique()",
"_____no_output_____"
],
[
"df_airbnb.accommodates.unique()",
"_____no_output_____"
],
[
"df_airbnb.bedrooms.unique()",
"_____no_output_____"
],
[
"df_airbnb.reviews.unique() #>10 críticas",
"_____no_output_____"
],
[
"df_airbnb.overall_satisfaction.unique() #>4 puntos",
"_____no_output_____"
],
[
"condicion = (df_airbnb.room_type == \"Private room\") & (df_airbnb.accommodates == 4) & (df_airbnb.bedrooms == 2.0) & (df_airbnb.reviews > 10) & (df_airbnb.overall_satisfaction > 4.0)",
"_____no_output_____"
],
[
"df_airbnb[condicion].sort_values(by=[\"overall_satisfaction\",\"reviews\"],ascending=False).head(3)",
"_____no_output_____"
]
],
[
[
"### Caso 2\n\nRoberto es un casero que tiene una casa en Airbnb. De vez en cuando nos llama preguntando sobre cuales son las críticas de su alojamiento. Hoy está particularmente enfadado, ya que su hermana Clara ha puesto una casa en Airbnb y Roberto quiere asegurarse de que su casa tiene más críticas que las de Clara. Tenemos que crear un dataframe con las propiedades de ambos. Las id de las casas de Roberto y Clara son 97503 y 90387 respectivamente. Finalmente guardamos este dataframe como excel llamado \"roberto.xls",
"_____no_output_____"
]
],
[
[
"df_airbnb.room_id.unique()",
"_____no_output_____"
],
[
"df_airbnb_2 = df_airbnb.set_index(\"room_id\").copy()\ndf_airbnb_2.head()",
"_____no_output_____"
],
[
"df_roberto = df_airbnb_2.loc[[97503,90387]]\ndf_roberto",
"_____no_output_____"
],
[
"df_roberto.to_excel(\"./roberto.xlsx\",sheet_name=\"datos\",encoding=\"utf-8\")",
"_____no_output_____"
]
],
[
[
"\n### Caso 3\n\nDiana va a Lisboa a pasar 3 noches y quiere conocer a gente nueva. Tiene un presupuesto de 50€ para su alojamiento. Debemos buscarle las 10 propiedades más baratas, dandole preferencia a aquellas que sean habitaciones compartidas *(room_type == Shared room)*, y para aquellas viviendas compartidas debemos elegir aquellas con mejor puntuación.",
"_____no_output_____"
]
],
[
[
"df_airbnb_1 = df_airbnb[df_airbnb.price <= 50].sort_values(by=\"price\",ascending=True).head(10)\ndf_airbnb_1",
"_____no_output_____"
],
[
"df_airbnb_1[df_airbnb_1.room_type == \"Shared room\"].sort_values(by = \"overall_satisfaction\",ascending=False)",
"_____no_output_____"
]
],
[
[
"## Usando MatPlot",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### Caso 1.\n\nRealizar un gráfico circular, de la cantidad de tipo de habitaciones `room_type` ",
"_____no_output_____"
]
],
[
[
"df_airbnb.room_type.value_counts().plot.pie(\n #labels=[\"AA\", \"BB\"],\n autopct=\"%.2f\",\n fontsize=12)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aae365e07e589785041f726f50c7d175509a8cf
| 22,175 |
ipynb
|
Jupyter Notebook
|
notebooks/91_Acs_Download_VS.ipynb
|
BNIA/VitalSigns
|
1c06284a7423fb837890b5d4b42567e8f14bf278
|
[
"Apache-2.0"
] | 1 |
2022-02-03T21:21:39.000Z
|
2022-02-03T21:21:39.000Z
|
notebooks/91_Acs_Download_VS.ipynb
|
BNIA/VitalSigns
|
1c06284a7423fb837890b5d4b42567e8f14bf278
|
[
"Apache-2.0"
] | null | null | null |
notebooks/91_Acs_Download_VS.ipynb
|
BNIA/VitalSigns
|
1c06284a7423fb837890b5d4b42567e8f14bf278
|
[
"Apache-2.0"
] | null | null | null | 22,175 | 22,175 | 0.56487 |
[
[
[
"# ACS Download\n\n## ACS TOOL STEP 1 -> SETUP : \n\n#### Uses: csa2tractcrosswalk.csv, VitalSignsCensus_ACS_Tables.xlsx\n#### Creates: ./AcsDataRaw/ ./AcsDataClean/",
"_____no_output_____"
],
[
"### Import Modules & Construct Path Handlers",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nimport pandas as pd\n\npd.set_option('display.expand_frame_repr', False)\npd.set_option('display.precision', 2)",
"_____no_output_____"
]
],
[
[
"### Get Vital Signs Reference Table",
"_____no_output_____"
]
],
[
[
"acs_tables = pd.read_csv('https://raw.githubusercontent.com/bniajfi/bniajfi/main/vs_acs_table_ids.csv')",
"_____no_output_____"
],
[
"acs_tables.head()",
"_____no_output_____"
]
],
[
[
"### Get Tract/ CSA CrossWalk",
"_____no_output_____"
]
],
[
[
"file = 'https://raw.githubusercontent.com/bniajfi/bniajfi/main/CSA-to-Tract-2010.csv'\ncrosswalk = pd.read_csv( file )\ncrosswalk = dict(zip(crosswalk['TRACTCE10'], crosswalk['CSA2010'] ) )",
"_____no_output_____"
]
],
[
[
"### Get retrieve_acs_data function",
"_____no_output_____"
]
],
[
[
"!pip install dataplay geopandas VitalSigns",
"_____no_output_____"
],
[
"import VitalSigns as vs",
"_____no_output_____"
],
[
"from VitalSigns import acsDownload",
"_____no_output_____"
],
[
"help(acsDownload)",
"_____no_output_____"
],
[
"help(vs.acsDownload.retrieve_acs_data)",
"Help on function retrieve_acs_data in module VitalSigns.acsDownload:\n\nretrieve_acs_data(state, county, tract, tableId, year, save)\n\n"
]
],
[
[
"### Column Operations",
"_____no_output_____"
]
],
[
[
"import csv # 'quote all'\ndef fixColNamesForCSV(x): return str(x)[:] if str(x) in [\"NAME\",\"state\",\"county\",\"tract\", \"CSA\"] else str(x)[12:]",
"_____no_output_____"
]
],
[
[
"## ACS TOOL STEP 2 -> Execute :",
"_____no_output_____"
]
],
[
[
"acs_tables.head()",
"_____no_output_____"
]
],
[
[
"### Save the ACS Data",
"_____no_output_____"
]
],
[
[
"# Set Index df.set_index(\"NAME\", inplace = True) \n# Save raw to '../../data/3_outputs/acs/raw/'+year+'/'+tableId+'_'+description+'_5y'+year+'_est.csv'\n# Tract to CSA df['CSA'] = df.apply(lambda row: crosswalk.get(int(row['tract']), \"empty\"), axis=1)\n# Save 4 use '../../data/2_cleaned/acs/'+tableId+'_'+description+'_5y'+year+'_est.csv'\n\nyear = '19'\ncount = 0\nstartFrom = 0\n\nstate = '24'\ncounty = '510'\ntract = '*'\ntableId = 'B19001'\nsaveAcs = True\n\n# For each ACS Table\nfor x, row in acs_tables.iterrows():\n count += 1\n\n # Grab its Meta Data\n description = str(acs_tables.loc[x, 'shortname'])\n tableId = str(acs_tables.loc[x, 'id'])\n yearExists = int(acs_tables.loc[x, year+'_exists'])\n\n # If the Indicator is valid for the year \n # use startFrom to being at a specific count\n if yearExists and count >= startFrom:\n print(str(count)+') '+tableId + ' ' + description)\n\n # retrieve the Python ACS indicator\n print('sending retrieve_acs_data', year, tableId)\n df = vs.acsDownload.retrieve_acs_data(state, county, tract, tableId, year, saveAcs)\n\n\n df.set_index(\"NAME\", inplace = True) \n\n # Save the Data as Raw\n # We do not want the id in the column names\n saveThis = df.rename( columns = lambda x : ( fixColNamesForCSV(x) ) )\n saveThis.to_csv('./AcsDataRaw/'+tableId+'_'+description+'_5y'+year+'_est.csv', quoting=csv.QUOTE_ALL)\n\n # Match Tract to CSA\n df['CSA'] = df.apply(lambda row: crosswalk.get(int(row['tract']), \"empty\"), axis=1)\n\n # Save the data (again) as Cleaned for me to use in the next scripts\n df.to_csv('./AcsDataClean/'+tableId+'_5y'+year+'_est.csv', quoting=csv.QUOTE_ALL) \n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# ACS Create Indicators\n\nACS TOOL STEP 1 -> SETUP : \n\nUses: ./AcsDataClean/ VitalSignsCensus_ACS_Tables.xlsx VitalSignsCensus_ACS_compare_data.xlsm\n\nCreates: ./VSData/",
"_____no_output_____"
],
[
"### Get Vital Signs Reference Table",
"_____no_output_____"
]
],
[
[
"ls",
"_____no_output_____"
],
[
"file = 'VitalSignsCensus_ACS_Tables.xlsx'\nxls = pd.ExcelFile(findFile('./', file))\nindicators = pd.read_excel(xls, sheet_name='indicators', index_col=0 )",
"_____no_output_____"
],
[
"indicators.head(30)",
"_____no_output_____"
]
],
[
[
"## ACS TOOL STEP 2 -> Execute :",
"_____no_output_____"
],
[
"### Create ACS Indicators",
"_____no_output_____"
],
[
"#### Settings/ Get Data",
"_____no_output_____"
]
],
[
[
"flag = True;\nyear = '19'\nvsTbl = pd.read_excel(xls, sheet_name=str('vs'+year), index_col=0 )\n\n# Prepare the Compare Historic Data\nfile = 'VitalSignsCensus_ACS_compare_data.xlsm'\ncompare_table = pd.read_excel(findFile('./', file), None);\ncomparable = False\nif( str('VS'+year) in compare_table.keys() ):\n compare_table = compare_table[str('VS'+year)]\n comparable = True \n columnsNames = compare_table.iloc[0]\n compare_table = compare_table.drop(compare_table.index[0])\n compare_table.set_index(['CSA2010'], drop = True, inplace = True)",
"_____no_output_____"
]
],
[
[
"#### Create Indicators",
"_____no_output_____"
]
],
[
[
"# For Each Indicator\nfor x, row in indicators.iterrows():\n # Grab its Meta Data\n shortSource = str(indicators.loc[x, 'Short Source'])\n shortName = str(indicators.loc[x, 'ShortName'])[:-2]\n yearExists = int(float(indicators.loc[x, year+'_exists']))\n indicator = str(indicators.loc[x, 'Indicator'])\n indicator_number = str(indicators.index.tolist().index(x)+1 )\n fileLocation = str(findFile( './', shortName+'.py') ) \n\n # If the Indicator is valid for the year, and uses ACS Data, and method exists\n flag = True if fileLocation != str('None') else False\n flag = True if flag and yearExists else False\n flag = True if flag and shortSource in ['ACS', 'Census'] else False\n if flag:\n\n print(shortSource, shortName, yearExists, indicator, fileLocation, indicator_number )\n \n # retrieve the Python ACS indicator\n module = __import__( shortName )\n result = getattr( module, shortName )( year )\n\n # Put Baltimore City at the bottom of the list\n idx = result.index.tolist()\n idx.pop(idx.index('Baltimore City')) \n result = result.reindex(idx+['Baltimore City']) \n\n # Write the results back into the XL dataframe\n vsTbl[ str(indicator_number + '_' +shortName ) ] = result\n\n # Save the Data\n result.to_csv('./VSData/vs'+ str(year)+'_'+shortName+'.csv')\n \n# drop columns with any empty values\nvsTbl = vsTbl.dropna(axis=1, how='any')\n \n# Save the Data\nfile = 'VS'+str(year)+'_indicators.xlsx'\nfile = findFile( 'VSData', file)\n# writer = pd.ExcelWriter(file)\n\n#vsTbl.to_excel(writer, str(year+'New_VS_Values') )\n\n# Save the Data\nvsTbl.to_csv('./VSData/vs'+str(year+'_New_VS_Values')+'.csv')\n\n# Include Historic Data if exist\nif( comparable ): \n # add historic indicator to excel doc\n # compare_table.to_excel(writer,sheet_name = str(year+'Original_VS_Values') ) \n \n # compare sets\n info = pd.DataFrame()\n diff = pd.DataFrame()\n simi = pd.DataFrame()\n\n for column in vsTbl:\n number = ''\n plchld = ''\n if str(column[0:3]).isdigit(): plchld = 3\n elif str(column[0:2]).isdigit(): plchld = 2\n else: number = plchld = 1\n number = int(column[0:plchld])\n if number == 98: twoNotThree = False;\n new = pd.to_numeric(vsTbl[column], downcast='float')\n old = pd.to_numeric(compare_table[number], downcast='float', errors='coerce')\n\n info[str(number)+'_Error#_'] = old - new\n diff[str(number)+'_Error#_'] = old - new\n info[str(number)+'_Error%_'] = old / new\n simi[str(number)+'_Error%_'] = old / new\n info[str(number)+'_new_'+column[plchld:]] = vsTbl[column]\n info[str(number)+'_old_'+columnsNames[number]] = compare_table[number]\n\n\n #info.to_csv('./VSData/vs_comparisons_'+ str(year)+'.csv')\n #diff.to_csv('./VSData/vs_differences_'+ str(year)+'.csv')\n\n # Save the info dataframe\n #info.to_excel(writer, str(year+'_ExpandedView') )\n # Save the diff dataframe\n #diff.to_excel(writer,sheet_name = str(year+'_Error') ) \n # Save the diff dataframe\n #simi.to_excel(writer,sheet_name = str(year+'_Similarity_Ratio') ) \n \n info.to_csv('./VSData/vs'+str(year+'_ExpandedView')+'.csv')\n diff.to_csv('./VSData/vs'+str(year+'_Error')+'.csv')\n simi.to_csv('./VSData/vs'+str(year+'_Similarity_Ratio')+'.csv')\n\n# writer.save()\n",
"_____no_output_____"
]
],
[
[
"#### Compare Historic Indicators",
"_____no_output_____"
]
],
[
[
"ls",
"_____no_output_____"
],
[
"# Quick test\nshortName = str('hh25inc')\nyear = 19\n# retrieve the Python ACS indicator\nmodule = __import__( shortName )\nresult = getattr( module, shortName )( year )\nresult",
"_____no_output_____"
],
[
"# Delete Unassigned--Jail\ndf = df[df.index != 'Unassigned--Jail']\n\n# Move Baltimore to Bottom\nbc = df.loc[ 'Baltimore City' ]\ndf = df.drop( df.index[1] )\ndf.loc[ 'Baltimore City' ] = bc",
"_____no_output_____"
],
[
"vsTbl['18_fam']",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4aae4b9dd479ba1c2fcad180a84107285049d2b8
| 106,176 |
ipynb
|
Jupyter Notebook
|
Log_Regularization/lockout01_log.ipynb
|
warbelo/Lockout
|
f579ab3b3e2aff6ae8738899852adbf3a7733e70
|
[
"MIT"
] | 2 |
2021-09-08T18:56:51.000Z
|
2022-01-06T15:09:12.000Z
|
Log_Regularization/lockout01_log.ipynb
|
warbelo/Lockout
|
f579ab3b3e2aff6ae8738899852adbf3a7733e70
|
[
"MIT"
] | null | null | null |
Log_Regularization/lockout01_log.ipynb
|
warbelo/Lockout
|
f579ab3b3e2aff6ae8738899852adbf3a7733e70
|
[
"MIT"
] | null | null | null | 155.22807 | 60,116 | 0.884258 |
[
[
[
"# Logarithmic Regularization: Dataset 1",
"_____no_output_____"
]
],
[
[
"# Import libraries and modules\nimport numpy as np\nimport pandas as pd\n\nimport xgboost as xgb\nfrom xgboost import plot_tree\n\nfrom sklearn.metrics import r2_score, classification_report, confusion_matrix, \\\n roc_curve, roc_auc_score, plot_confusion_matrix, f1_score, \\\n balanced_accuracy_score, accuracy_score, mean_squared_error, \\\n log_loss\nfrom sklearn.datasets import make_friedman1\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.linear_model import LogisticRegression, LinearRegression, SGDClassifier, \\\n Lasso, lasso_path\nfrom sklearn.preprocessing import StandardScaler, LabelBinarizer\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn_pandas import DataFrameMapper\n\nimport scipy\nfrom scipy import stats\n\nimport os\nimport shutil\nfrom pathlib import Path\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport cv2\nimport itertools\n\nimport time\nimport tqdm\nimport copy\nimport warnings\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision.models as models\nfrom torch.utils.data import Dataset\n\nimport PIL\nimport joblib\nimport json\n\n# import mysgd",
"_____no_output_____"
],
[
"# Import user-defined modules\nimport sys\nimport imp\nsys.path.append('/Users/arbelogonzalezw/Documents/ML_WORK/LIBS/Lockdown')\nimport tools_general as tg\nimport tools_pytorch as tp\nimport lockdown as ld\nimp.reload(tg)\nimp.reload(tp)\nimp.reload(ld)",
"_____no_output_____"
]
],
[
[
"## Read, clean, and save data",
"_____no_output_____"
]
],
[
[
"# Read X and y\nX = pd.read_csv('/Users/arbelogonzalezw/Documents/ML_WORK/Project_Jerry_Lockdown/dataset_10LungCarcinoma/GDS3837_gene_profile.csv', index_col=0)\ndfy = pd.read_csv('/Users/arbelogonzalezw/Documents/ML_WORK/Project_Jerry_Lockdown/dataset_10LungCarcinoma/GDS3837_output.csv', index_col=0)",
"_____no_output_____"
],
[
"# Change column names\ncols = X.columns.tolist()\nfor i in range(len(cols)):\n cols[i] = cols[i].lower()\n cols[i] = cols[i].replace('-', '_')\n cols[i] = cols[i].replace('.', '_')\n cols[i] = cols[i].strip()\nX.columns = cols\n\ncols = dfy.columns.tolist()\nfor i in range(len(cols)):\n cols[i] = cols[i].lower()\n cols[i] = cols[i].replace('-', '_')\n cols[i] = cols[i].replace('.', '_')\n cols[i] = cols[i].strip()\ndfy.columns = cols\n\n# Set target\ndfy['disease_state'] = dfy['disease_state'].str.replace(' ', '_')\ndfy.replace({'disease_state': {\"lung_cancer\": 1, \"control\": 0}}, inplace=True)\nY = pd.DataFrame(dfy['disease_state'])",
"_____no_output_____"
],
[
"# Split and save data set\nxtrain, xvalid, xtest, ytrain, yvalid, ytest = tg.split_data(X, Y)\ntg.save_data(X, xtrain, xvalid, xtest, Y, ytrain, yvalid, ytest, 'dataset/')\ntg.save_list(X.columns.to_list(), 'dataset/X.columns')\ntg.save_list(Y.columns.to_list(), 'dataset/Y.columns')\n\n# \nprint(\"- X size: {}\\n\".format(X.shape))\nprint(\"- xtrain size: {}\".format(xtrain.shape))\nprint(\"- xvalid size: {}\".format(xvalid.shape))\nprint(\"- xtest size: {}\".format(xtest.shape))",
"- X size: (120, 54675)\n\n- xtrain size: (72, 54675)\n- xvalid size: (24, 54675)\n- xtest size: (24, 54675)\n"
]
],
[
[
"## Load Data",
"_____no_output_____"
]
],
[
[
"# Select type of processor to be used\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nif device == torch.device('cuda'):\n print(\"-Type of precessor to be used: 'gpu'\")\n !nvidia-smi\nelse:\n print(\"-Type of precessor to be used: 'cpu'\")\n \n# Choose device\n# torch.cuda.set_device(6)",
"-Type of precessor to be used: 'cpu'\n"
],
[
"# Read data\nX, x_train, x_valid, x_test, Y, ytrain, yvalid, ytest = tp.load_data_clf('dataset/')\ncols_X = tg.read_list('dataset/X.columns')\ncols_Y = tg.read_list('dataset/Y.columns')",
"_____no_output_____"
],
[
"# Normalize data\nxtrain, xvalid, xtest = tp.normalize_x(x_train, x_valid, x_test)",
"_____no_output_____"
],
[
"# Create dataloaders\ndl_train, dl_valid, dl_test = tp.make_DataLoaders(xtrain, xvalid, xtest, ytrain, yvalid, ytest, \n tp.dataset_tabular, batch_size=10000)",
"(train, valid, test) = (1, 1, 1)\n"
],
[
"# NN architecture with its corresponding forward method\nclass MyNet(nn.Module):\n \n# .Network architecture\n def __init__(self, features, layer_sizes):\n super(MyNet, self).__init__()\n \n self.classifier = nn.Sequential(\n nn.Linear(features, layer_sizes[0], bias=True),\n nn.ReLU(inplace=True),\n nn.Linear(layer_sizes[0], layer_sizes[1], bias=True)\n )\n\n# .Forward function\n def forward(self, x):\n x = self.classifier(x)\n return x",
"_____no_output_____"
]
],
[
[
"## Lockout (Log, beta=0.7)",
"_____no_output_____"
]
],
[
[
"# TRAIN WITH LOCKDOWN\nmodel = MyNet(n_features, n_layers)\nmodel.load_state_dict(torch.load('./model_forward_valid_min.pth'))\nmodel.eval()\n\nregul_type = [('classifier.0.weight', 2), ('classifier.2.weight', 2)]\nregul_path = [('classifier.0.weight', True), ('classifier.2.weight', False)]\n\nlockout_s = ld.lockdown(model, lr=1e-2, \n regul_type=regul_type, \n regul_path=regul_path, \n loss_type=2, tol_grads=1e-2)",
"_____no_output_____"
],
[
"lockout_s.train(dl_train, dl_valid, dl_test, epochs=5000, early_stop=15, tol_loss=1e-5, epochs2=100000,\n train_how=\"decrease_t0\")",
"{'classifier.0.weight': tensor(-97250.3672), 'classifier.2.weight': tensor(-2.6552)} {'classifier.0.weight': tensor(-97506.0234)}\n"
],
[
"# Save model, data\ntp.save_model(lockout_s.model_best_valid, 'model_lockout_valid_min_log7_path.pth')\ntp.save_model(lockout_s.model_last, 'model_lockout_last_log7_path.pth')\nlockout_s.path_data.to_csv('data_lockout_log7_path.csv')",
"_____no_output_____"
],
[
"# Relevant plots\ndf = pd.read_csv('data_lockout_log7_path.csv')\ndf.plot('iteration', y=['t0_calc__classifier.0.weight', 't0_used__classifier.0.weight'], \n figsize=(8,6))\nplt.show()",
"_____no_output_____"
],
[
"# L1\nnn = int(1e2)\ndata_tmp = pd.read_csv('data_lockout_l1.csv', index_col=0)\ndata_lockout_l1 = pd.DataFrame(columns=['sparcity', 'train_accu', 'valid_accu', 'test_accu', 't0_used'])\nxgrid, step = np.linspace(0., 1., num=nn,endpoint=True, retstep=True)\nfor x in xgrid:\n msk = (data_tmp['sparcity__classifier.0.weight'] >= x) & \\\n (data_tmp['sparcity__classifier.0.weight'] < x+step)\n train_accu = data_tmp.loc[msk, 'train_accu'].mean()\n valid_accu = data_tmp.loc[msk, 'valid_accu'].mean()\n test_accu = data_tmp.loc[msk, 'test_accu'].mean()\n t0_used = data_tmp.loc[msk, 't0_used__classifier.0.weight'].mean()\n data_lockout_l1 = data_lockout_l1.append({'sparcity': x, \n 'train_accu': train_accu, \n 'valid_accu': valid_accu, \n 'test_accu': test_accu, \n 't0_used': t0_used}, ignore_index=True)\ndata_lockout_l1.dropna(axis='index', how='any', inplace=True)",
"_____no_output_____"
],
[
"# Log, beta=0.7\nnn = int(1e2)\ndata_tmp = pd.read_csv('data_lockout_log7_path.csv', index_col=0)\ndata_lockout_log7 = pd.DataFrame(columns=['sparcity', 'train_accu', 'valid_accu', 'test_accu', 't0_used'])\nxgrid, step = np.linspace(0., 1., num=nn,endpoint=True, retstep=True)\nfor x in xgrid:\n msk = (data_tmp['sparcity__classifier.0.weight'] >= x) & \\\n (data_tmp['sparcity__classifier.0.weight'] < x+step)\n train_accu = data_tmp.loc[msk, 'train_accu'].mean()\n valid_accu = data_tmp.loc[msk, 'valid_accu'].mean()\n test_accu = data_tmp.loc[msk, 'test_accu'].mean()\n t0_used = data_tmp.loc[msk, 't0_used__classifier.0.weight'].mean()\n data_lockout_log7 = data_lockout_log7.append({'sparcity': x, \n 'train_accu': train_accu, \n 'valid_accu': valid_accu, \n 'test_accu': test_accu, \n 't0_used': t0_used}, ignore_index=True)\ndata_lockout_log7.dropna(axis='index', how='any', inplace=True)",
"_____no_output_____"
],
[
"# Plot\nfig, axes = plt.subplots(figsize=(9,6))\n\naxes.plot(n_features*data_lockout_l1.loc[2:, 'sparcity'], \n 1.0 - data_lockout_l1.loc[2:, 'valid_accu'], \n \"-\", linewidth=4, markersize=10, label=\"Lockout(L1)\", \n color=\"tab:orange\")\naxes.plot(n_features*data_lockout_log7.loc[3:,'sparcity'], \n 1.0 - data_lockout_log7.loc[3:, 'valid_accu'], \n \"-\", linewidth=4, markersize=10, label=r\"Lockout(Log, $\\beta$=0.7)\", \n color=\"tab:green\")\n\naxes.grid(True, zorder=2)\naxes.set_xlabel(\"number of selected features\", fontsize=16)\naxes.set_ylabel(\"Validation Error\", fontsize=16)\naxes.tick_params(axis='both', which='major', labelsize=14)\naxes.set_yticks(np.linspace(5e-3, 4.5e-2, 5, endpoint=True))\n# axes.ticklabel_format(axis='y', style='sci', scilimits=(0,0))\naxes.set_xlim(0, 54800)\naxes.legend(fontsize=16)\n\nplt.tight_layout()\nplt.savefig('error_vs_features_log_dataset10.pdf', bbox_inches='tight')\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aae53b532b71a974f5863a187e51a272f5426e8
| 6,138 |
ipynb
|
Jupyter Notebook
|
list & dictionary comprehension practice.ipynb
|
milkywaysandy/My-python-learning-journal
|
f20e62595d22f5deed8c1bf5a30c8d80eed56fca
|
[
"MIT"
] | null | null | null |
list & dictionary comprehension practice.ipynb
|
milkywaysandy/My-python-learning-journal
|
f20e62595d22f5deed8c1bf5a30c8d80eed56fca
|
[
"MIT"
] | null | null | null |
list & dictionary comprehension practice.ipynb
|
milkywaysandy/My-python-learning-journal
|
f20e62595d22f5deed8c1bf5a30c8d80eed56fca
|
[
"MIT"
] | null | null | null | 20.80678 | 121 | 0.45927 |
[
[
[
"List Comprehension\n#[lst] = [action- expression for placement- items in list if condition]",
"_____no_output_____"
],
[
"lst = [[1,2],[2,3]]\na = [x for l in lst for x in l]\nprint(a)",
"[1, 2, 2, 3]\n"
],
[
"lst = [[1,2],[2,3]]\nb = []\nfor l in lst:\n for x in l:\n b.append(x)\nprint(b)",
"[1, 2, 2, 3]\n"
],
[
"lst = [1,2,3]\ndef list_doubler(lst):\n doubled = []\n for num in lst:\n doubled.append(num*2)\n return doubled\nprint(list_doubler(lst))",
"[2, 4, 6]\n"
],
[
"lst = [4,5,6]\ndef list_doubler1(lst):\n return [num * 2 for num in lst]\nprint(list_doubler1(lst))",
"[8, 10, 12]\n"
],
[
"def long_words(lst):\n words = []\n for word in lst:\n if len(word) > 5:\n words.append(word)\n return words",
"_____no_output_____"
],
[
"def long_words(lst):\n return [word for word in lst if len(word) > 5]",
"_____no_output_____"
],
[
"#Dictionary Comprehension\n#dictionary = {key: value for vars in iterable}",
"_____no_output_____"
],
[
"square_dict = dict()\nfor num in range(1, 11):\n square_dict[num] = num*num\nprint(square_dict)",
"{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}\n"
],
[
"square_dict = {num: num*num for num in range(1, 11)}\nprint(square_dict)",
"{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}\n"
],
[
"original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}\n\neven_dict = {k: v for (k, v) in original_dict.items() if v % 2 == 0 if v < 40}\nprint(even_dict)",
"{'jack': 38}\n"
],
[
"dictionary = dict()\nfor k1 in range(2, 5):\n dictionary[k1] = dict()\n for k2 in range(1, 6):\n dictionary[k1][k2] = k1*k2\nprint(dictionary)",
"{2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}, 3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15}, 4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20}}\n"
],
[
"dictionary = {k1: {k2: k1 * k2 for k2 in range(1, 6)} for k1 in range(2, 5)}\nprint(dictionary)",
"{2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}, 3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15}, 4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20}}\n"
],
[
"#dictionary with lambda (short made-function) \n#filter()(select if true), map()(go through a function) and reduce()(每樣interated).",
"_____no_output_____"
],
[
"# Initialize `fahrenheit` dictionary \nfahrenheit = {'t1':-30, 't2':-20, 't3':-10, 't4':0}\n\n#Get the corresponding `celsius` values\ncelsius = list(map(lambda x: (float(5)/9)*(x-32), fahrenheit.values()))\n\n#Create the `celsius` dictionary\ncelsius_dict = dict(zip(fahrenheit.keys(), celsius))\n\nprint(celsius_dict)",
"{'t1': -34.44444444444444, 't2': -28.88888888888889, 't3': -23.333333333333336, 't4': -17.77777777777778}\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aae5aed4231c368b304d9ccc5cb016c7c473368
| 1,788 |
ipynb
|
Jupyter Notebook
|
tests/data/notebook_for_testing_copy.ipynb
|
caioariede/nbQA
|
bb8baf47e4b0b431628edf28b1008397edb936a3
|
[
"MIT"
] | null | null | null |
tests/data/notebook_for_testing_copy.ipynb
|
caioariede/nbQA
|
bb8baf47e4b0b431628edf28b1008397edb936a3
|
[
"MIT"
] | 2 |
2020-10-17T01:39:37.000Z
|
2020-10-17T09:08:30.000Z
|
tests/data/notebook_for_testing_copy.ipynb
|
caioariede/nbQA
|
bb8baf47e4b0b431628edf28b1008397edb936a3
|
[
"MIT"
] | null | null | null | 18.060606 | 56 | 0.43736 |
[
[
[
"import os\n\nimport glob\n\nimport nbqa",
"_____no_output_____"
]
],
[
[
"# Some markdown cell containing \\n",
"_____no_output_____"
]
],
[
[
"%%time\ndef hello(name: str = \"world\\n\"):\n \"\"\"\n Greet user.\n\n Examples\n --------\n >>> hello()\n 'hello world\\\\n'\n >>> hello(\"goodbye\")\n 'hello goodby'\n \"\"\"\n if True:\n %time # indented magic!\n return f'hello {name}'\n\n\nhello(3)",
"CPU times: user 9 µs, sys: 6 µs, total: 15 µs\nWall time: 17.9 µs\n"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aae64cc4a1cd15ff18ab84ecbd4a229c339c299
| 185,632 |
ipynb
|
Jupyter Notebook
|
Notebook_PPGI_IRIS.ipynb
|
mfalbano3/UNINOVE
|
c6de1e08ef4d9f4320bfa5e08bd6c93068df6479
|
[
"Apache-2.0"
] | 1 |
2020-05-25T21:22:55.000Z
|
2020-05-25T21:22:55.000Z
|
Notebook_PPGI_IRIS.ipynb
|
mfalbano3/UNINOVE
|
c6de1e08ef4d9f4320bfa5e08bd6c93068df6479
|
[
"Apache-2.0"
] | null | null | null |
Notebook_PPGI_IRIS.ipynb
|
mfalbano3/UNINOVE
|
c6de1e08ef4d9f4320bfa5e08bd6c93068df6479
|
[
"Apache-2.0"
] | null | null | null | 122.691342 | 21,296 | 0.755295 |
[
[
[
"Base Iris - Uninove",
"_____no_output_____"
],
[
"# Bibliotecas",
"_____no_output_____"
]
],
[
[
"\nlibrary(factoextra)\nlibrary(cluster)\nlibrary(csv)\nlibrary(xlsx)\nlibrary(arules)\nlibrary(caTools)\nlibrary(rpart)\nlibrary(rpart.plot)\nlibrary(caret)\nlibrary(e1071)\nlibrary(ROCR)\nlibrary(pROC)\nlibrary(PRROC)\nlibrary(caret)",
"_____no_output_____"
],
[
"Data <- iris",
"_____no_output_____"
],
[
"#Boxplot\nboxplot(iris)\n\n#Sumário\nsummary(iris)",
"_____no_output_____"
],
[
"#Dividindo conjunto em treino e teste\n\nset.seed(1)\n\n\ndivisao = sample.split(iris$Species, SplitRatio = 0.8)\nbase_treinamento = subset(iris, divisao == TRUE)\nbase_teste = subset(iris, divisao == FALSE)",
"_____no_output_____"
],
[
"for (i in 2:5) {\n plot(base_treinamento[,i], col=base_treinamento$Species ,\n main=names(base_treinamento)[i])\n}",
"_____no_output_____"
],
[
"plot(base_treinamento[,-1],col = base_treinamento$Species)\n",
"_____no_output_____"
],
[
"#Criando um classificador\nclassificador = rpart(formula = Species ~., data = base_treinamento)\nprint(classificador)\nprp(classificador)",
"n= 120 \n\nnode), split, n, loss, yval, (yprob)\n * denotes terminal node\n\n1) root 120 80 setosa (0.33333333 0.33333333 0.33333333) \n 2) Petal.Length< 2.6 40 0 setosa (1.00000000 0.00000000 0.00000000) *\n 3) Petal.Length>=2.6 80 40 versicolor (0.00000000 0.50000000 0.50000000) \n 6) Petal.Width< 1.75 43 4 versicolor (0.00000000 0.90697674 0.09302326) *\n 7) Petal.Width>=1.75 37 1 virginica (0.00000000 0.02702703 0.97297297) *\n"
],
[
"#Mostrando a árvore de decisão\nrpart.plot(classificador)",
"_____no_output_____"
],
[
"#Mostrando previsões\n\nprevisao = predict(classificador, newdata = base_treinamento[-5])\nprevisao\n",
"_____no_output_____"
],
[
"#Matriz de confusão e resultados\n\nprevisoes = predict(classificador, newdata = base_treinamento[-5], type = 'class')\nprevisoes\nmatriz_confusao = table (base_treinamento[,5], previsoes)\nprint(matriz_confusao)\n",
"_____no_output_____"
],
[
"confusionMatrix(matriz_confusao)",
"_____no_output_____"
],
[
"#Curva ROC\n\ndata.frame(base_treinamento)\ndf <- data.frame(base_treinamento) \n\n",
"_____no_output_____"
],
[
"pROC_obj <- roc(df$Sepal.Width,df$Petal.Length,\n smoothed = TRUE,\n # arguments for ci\n ci=TRUE, ci.alpha=0, stratified=FALSE,\n # arguments for plot\n plot=TRUE, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE,\n print.auc=TRUE, show.thres=TRUE)\n\n\nsens.ci <- ci.se(pROC_obj)\n",
"Warning message in roc.default(df$Sepal.Width, df$Petal.Length, smoothed = TRUE, :\n\"'response' has more than two levels. Consider setting 'levels' explicitly or using 'multiclass.roc' instead\"Setting levels: control = 2.2, case = 2.3\nSetting direction: controls > cases\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aae7b06a9450201c829c31fda0ec221dae0c255
| 1,278 |
ipynb
|
Jupyter Notebook
|
MassLuminosityProject/SummerResearch/PhilMarshallMeeting_20170707.ipynb
|
davidthomas5412/PanglossNotebooks
|
719a3b9a5d0e121f0e9bc2a92a968abf7719790f
|
[
"MIT"
] | null | null | null |
MassLuminosityProject/SummerResearch/PhilMarshallMeeting_20170707.ipynb
|
davidthomas5412/PanglossNotebooks
|
719a3b9a5d0e121f0e9bc2a92a968abf7719790f
|
[
"MIT"
] | 2 |
2016-12-13T02:05:57.000Z
|
2017-01-21T02:16:27.000Z
|
MassLuminosityProject/SummerResearch/PhilMarshallMeeting_20170707.ipynb
|
davidthomas5412/PanglossNotebooks
|
719a3b9a5d0e121f0e9bc2a92a968abf7719790f
|
[
"MIT"
] | null | null | null | 23.236364 | 310 | 0.570423 |
[
[
[
"Remember to bring up getting DESC membership to access NERSC.",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4aae9105d38791f94d2a6f511c2d739a0aa87595
| 153,958 |
ipynb
|
Jupyter Notebook
|
WebVisualizations/.ipynb_checkpoints/csv_to_html-checkpoint.ipynb
|
v33na/Web-Design-Challenge
|
4e7088aaab4fa33a1d4c869de01b22f7bc00c027
|
[
"ADSL"
] | 1 |
2021-08-31T05:37:35.000Z
|
2021-08-31T05:37:35.000Z
|
WebVisualizations/.ipynb_checkpoints/csv_to_html-checkpoint.ipynb
|
v33na/Web-Design-Challenge
|
4e7088aaab4fa33a1d4c869de01b22f7bc00c027
|
[
"ADSL"
] | null | null | null |
WebVisualizations/.ipynb_checkpoints/csv_to_html-checkpoint.ipynb
|
v33na/Web-Design-Challenge
|
4e7088aaab4fa33a1d4c869de01b22f7bc00c027
|
[
"ADSL"
] | 1 |
2021-09-03T14:23:19.000Z
|
2021-09-03T14:23:19.000Z
| 747.368932 | 148,586 | 0.389769 |
[
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"df = pd.read_csv('./Resources/cities.csv')\ndf.head()",
"_____no_output_____"
],
[
"html_table=df.to_html()\nhtml_table",
"_____no_output_____"
],
[
"df.to_html('table.html')",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4aae9549507d01f9a837d6c1ced59832ad245c2d
| 16,911 |
ipynb
|
Jupyter Notebook
|
Regression/Combined_Cycle_Power_Plant/Scikit-learn.ipynb
|
Harpreetsingh31/MachineLearning
|
67d7e80d06db6e7f6135f652f1f26280fe48d907
|
[
"MIT"
] | null | null | null |
Regression/Combined_Cycle_Power_Plant/Scikit-learn.ipynb
|
Harpreetsingh31/MachineLearning
|
67d7e80d06db6e7f6135f652f1f26280fe48d907
|
[
"MIT"
] | null | null | null |
Regression/Combined_Cycle_Power_Plant/Scikit-learn.ipynb
|
Harpreetsingh31/MachineLearning
|
67d7e80d06db6e7f6135f652f1f26280fe48d907
|
[
"MIT"
] | null | null | null | 47.771186 | 199 | 0.442552 |
[
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.preprocessing import scale\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.cross_validation import cross_val_score\nfrom sklearn.model_selection import train_test_split\n\nfrom keras.layers import Dense\nfrom keras.models import Sequential",
"_____no_output_____"
],
[
"df = pd.read_csv('ccpp.csv')\n\n#Inputs and Output\nX = scale(np.array(df.drop(['PE'],1)))\ny = np.array(df['PE'])\ny = y.reshape((y.shape[0],1))\n\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size = .20,random_state = 42)",
"_____no_output_____"
],
[
"clf = LinearRegression()\n\n#Compute cross_validation\ncv_score = cross_val_score(clf,X,y,cv=5)\nprint('CV Score: {}'.format((cv_score)))\nprint('Average 5_fold CV Score: {}'.format(np.mean(cv_score)))\n\nclf.fit(X_train,y_train)\ny_pred =clf.predict(X_test)\nscore = clf.score(X_test,y_test)\ncoeff = clf.coef_\ninter = clf.intercept_\n\nrmse = np.sqrt(mean_squared_error(y_test,y_pred))\nprint('RMSE: {}'.format(rmse))\nprint('Coefficients: {}'.format(coeff))\nprint('Intercept: {}'.format(inter))\n#print('Coefficients' + coeff)",
"CV Score: [0.92994188 0.91956987 0.93114222 0.92812498 0.93352748]\nAverage 5_fold CV Score: 0.9284612870118183\nRMSE: 4.428101774539945\nCoefficients: [[-14.73251595 -2.98326107 0.34593379 -2.30884968]]\nIntercept: [454.42894375]\n"
],
[
"#Initializing Neural\nmodel = Sequential()\n\nmodel.add(Dense(4, input_dim=4, activation='relu'))\n\nmodel.add(Dense(3, activation='relu'))\n#model.add(Dense(2, activation='relu'))\n\nmodel.add(Dense(1, activation='relu'))\n\nmodel.compile(loss='mean_squared_error', optimizer = 'adam',metrics=['accuracy'])\n\nhistory = model.fit(X_train,y_train,nb_epoch= 100, verbose=1,batch_size=10)\n\n[test_loss, test_acc] = model.evaluate(X_test, y_test, batch_size=10) \n\nprint(\"Evaluation result on Test Data : Loss = {}, accuracy = {}\".format(test_loss, test_acc))",
"c:\\users\\harpreet singh\\appdata\\local\\programs\\python\\python36-64\\lib\\site-packages\\keras\\models.py:944: UserWarning: The `nb_epoch` argument in `fit` has been renamed `epochs`.\n warnings.warn('The `nb_epoch` argument in `fit` '\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4aaea6df44605c1977da51fecd46eeb1fe8b293d
| 4,940 |
ipynb
|
Jupyter Notebook
|
notebooks/icos_jupyter_notebooks/visualization_average_footprints.ipynb
|
ICOS-Carbon-Portal/jupyter
|
628c16b18352411a6c5cd9b44ed0c01aad9cf3ac
|
[
"CC-BY-4.0"
] | 6 |
2020-12-26T07:39:57.000Z
|
2021-06-11T20:21:39.000Z
|
notebooks/icos_jupyter_notebooks/visualization_average_footprints.ipynb
|
ICOS-Carbon-Portal/jupyter
|
628c16b18352411a6c5cd9b44ed0c01aad9cf3ac
|
[
"CC-BY-4.0"
] | 53 |
2020-02-25T13:48:17.000Z
|
2022-03-25T10:13:53.000Z
|
notebooks/icos_jupyter_notebooks/visualization_average_footprints.ipynb
|
ICOS-Carbon-Portal/jupyter
|
628c16b18352411a6c5cd9b44ed0c01aad9cf3ac
|
[
"CC-BY-4.0"
] | 6 |
2020-03-30T10:40:44.000Z
|
2021-03-19T11:30:18.000Z
| 48.910891 | 881 | 0.688664 |
[
[
[
"<img src=\"logos/Icos_cp_Logo_RGB.svg\" align=\"right\" width=\"400\"> <br clear=\"all\" />\n\n\n# Visualization of average footprints\n\n\nFor questions and feedback contact [email protected]\n\nTo use the tool, <span style=\"background-color: #FFFF00\">run all the Notebook cells</span> (see image below).\n\n<img src=\"network_characterization/screenshots_for_into_texts/how_to_run.PNG\" align=\"left\"> <br clear=\"all\" />\n\n\n\n#### STILT footprints\nSTILT is implemented as an <a href=\"https://www.icos-cp.eu/data-services/tools/stilt-footprint\" target=\"blank\">online tool</a> at the ICOS Carbon Portal. Output footprints are presented on a grid with 1/12×1/8 degrees cells (approximately 10km x 10km) where the cell values represent the cell area’s estimated surface influence (“sensitivity”) in ppm / (μmol/ (m²s)) on the atmospheric tracer concentration at the station. Individual footprints are generated every three hours (between 0:00 and 21:00 UTC) and are based on a 10-days backward simulation.\n\nOn the ICOS Carbon Portal JupyterHub there are Notebook tools that use STILT footprints such as <a href=\"https://exploredata.icos-cp.eu/user/jupyter/notebooks/icos_jupyter_notebooks/station_characterization.ipynb\">station characterization</a> and <a href=\"https://exploredata.icos-cp.eu/user/jupyter/notebooks/icos_jupyter_notebooks/network_characterization.ipynb\">network characterization</a>. In the station characterization tool there is a visualization method that aggregates the surface influence into bins in different directions and at different distance intervals of the station. Without aggregation of the surface influence it can be difficult to understand to what degree different regions fluxes can be expected to influence the concentration at the station. In this tool an additional method to aggregate and visualize the surface influence is presented. \n\nExample of average footprint for Hylemossa (tall tower - 150 meters - atmospheric station located in Sweden) displayed using logarithmic scale:\n\n<img src=\"network_characterization/screenshots_for_into_texts/hyltemossa_2018_log.PNG\" align=\"left\" width=\"400\"> <br clear=\"all\" />\n\n\n#### Percent of the footprint sensitivity \nThis tool generates a map with decreasing intensity in color from 10 to 90% of the footprint sensitivity. This is achieved by including the sensitivity values of the footprint cells in descending order until the 10%, 20%, 30% etc. is reached. In terms of Carbon Portal tools, it is important for an understanding of results in the network characterization tool where the user decides what percent of the footprint should be used for the analysis: The 10 days’ backward simulation means that a footprint can have a very large extent. When averaging many footprints almost the entire STILT model domain (Europe) will have influenced the concentration at the station at some point in time. Deciding on a percent threshold limits the footprint coverage to areas with more significant influence. This tool shows how the user choice will influence the result.\n\nExample using the 2018 average footprint for Hyltemossa: \n\n<img src=\"network_characterization/screenshots_for_into_texts/hyltemossa_2018.PNG\" align=\"left\" width=\"400\"> <br clear=\"all\" />\n",
"_____no_output_____"
]
],
[
[
"%%javascript\nIPython.OutputArea.prototype._should_scroll = function(lines) {\n return false;\n}",
"_____no_output_____"
],
[
"import sys\nsys.path.append('./network_characterization')\nimport gui_percent_aggregate_footprints",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
]
] |
4aaead47f8a3bf19ed0739854c644b3e022bee9c
| 2,967 |
ipynb
|
Jupyter Notebook
|
Welcome_To_Colaboratory.ipynb
|
zsiranovic/aima-python-1
|
2b00ab6697acfd52f52ff4901a7322f27619d2c0
|
[
"MIT"
] | 1 |
2020-10-16T16:03:17.000Z
|
2020-10-16T16:03:17.000Z
|
Welcome_To_Colaboratory.ipynb
|
zsiranovic/aima-python-1
|
2b00ab6697acfd52f52ff4901a7322f27619d2c0
|
[
"MIT"
] | null | null | null |
Welcome_To_Colaboratory.ipynb
|
zsiranovic/aima-python-1
|
2b00ab6697acfd52f52ff4901a7322f27619d2c0
|
[
"MIT"
] | null | null | null | 29.376238 | 246 | 0.507246 |
[
[
[
"<a href=\"https://colab.research.google.com/github/zsiranovic/aima-python-1/blob/master/Welcome_To_Colaboratory.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"<p><img alt=\"Colaboratory logo\" height=\"45px\" src=\"/img/colab_favicon.ico\" align=\"left\" hspace=\"10px\" vspace=\"0px\"></p>\n\n<h1>What is Colaboratory?</h1>\n\nColaboratory, or \"Colab\" for short, allows you to write and execute Python in your browser, with \n- Zero configuration required\n- Free access to GPUs\n- Easy sharing\n\nWhether you're a **student**, a **data scientist** or an **AI researcher**, Colab can make your work easier. Watch [Introduction to Colab](https://www.youtube.com/watch?v=inN8seMm7UI) to learn more, or just get started below!",
"_____no_output_____"
],
[
"## **Getting started**\n\nThe document you are reading is not a static web page, but an interactive environment called a **Colab notebook** that lets you write and execute code.\n\nFor example, here is a **code cell** with a short Python script that computes a value, stores it in a variable, and prints the result:",
"_____no_output_____"
]
],
[
[
"seconds_in_a_day = 24 * 60 * 60\nseconds_in_a_day",
"_____no_output_____"
],
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
4aaeaf7c778c6ca2825f2efe672805b7e2cc062f
| 539,419 |
ipynb
|
Jupyter Notebook
|
module4-makefeatures/LS_DS_114_Make_Features_Assignment.ipynb
|
strangelycutlemon/DS-Unit-1-Sprint-1-Dealing-With-Data
|
8b63cb627149a85b90503f0688fb424fb8fdb243
|
[
"MIT"
] | null | null | null |
module4-makefeatures/LS_DS_114_Make_Features_Assignment.ipynb
|
strangelycutlemon/DS-Unit-1-Sprint-1-Dealing-With-Data
|
8b63cb627149a85b90503f0688fb424fb8fdb243
|
[
"MIT"
] | null | null | null |
module4-makefeatures/LS_DS_114_Make_Features_Assignment.ipynb
|
strangelycutlemon/DS-Unit-1-Sprint-1-Dealing-With-Data
|
8b63cb627149a85b90503f0688fb424fb8fdb243
|
[
"MIT"
] | null | null | null | 44.668682 | 1,121 | 0.269038 |
[
[
[
"<a href=\"https://colab.research.google.com/github/strangelycutlemon/DS-Unit-1-Sprint-1-Dealing-With-Data/blob/master/module4-makefeatures/LS_DS_114_Make_Features_Assignment.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"<img align=\"left\" src=\"https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png\" width=200> ",
"_____no_output_____"
],
[
"# ASSIGNMENT\n\n- Replicate the lesson code.\n\n - This means that if you haven't followed along already, type out the things that we did in class. Forcing your fingers to hit each key will help you internalize the syntax of what we're doing.\n - [Lambda Learning Method for DS - By Ryan Herr](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit?usp=sharing)\n- Convert the `term` column from string to integer.\n- Make a column named `loan_status_is_great`. It should contain the integer 1 if `loan_status` is \"Current\" or \"Fully Paid.\" Else it should contain the integer 0.\n\n- Make `last_pymnt_d_month` and `last_pymnt_d_year` columns.",
"_____no_output_____"
]
],
[
[
"##### Begin Working Here #####\n# Get data\n!wget https://resources.lendingclub.com/LoanStats_2018Q4.csv.zip\n!unzip LoanStats_2018Q4.csv.zip\n!head LoanStats_2018Q4.zip",
"--2019-08-08 21:32:44-- https://resources.lendingclub.com/LoanStats_2018Q4.csv.zip\nResolving resources.lendingclub.com (resources.lendingclub.com)... 64.48.1.20\nConnecting to resources.lendingclub.com (resources.lendingclub.com)|64.48.1.20|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: unspecified [application/zip]\nSaving to: ‘LoanStats_2018Q4.csv.zip.1’\n\nLoanStats_2018Q4.cs [ <=> ] 21.56M 811KB/s in 28s \n\n2019-08-08 21:33:12 (797 KB/s) - ‘LoanStats_2018Q4.csv.zip.1’ saved [22606280]\n\nArchive: LoanStats_2018Q4.csv.zip\nreplace LoanStats_2018Q4.csv? [y]es, [n]o, [A]ll, [N]one, [r]ename: head: cannot open 'LoanStats_2018Q4.zip' for reading: No such file or directory\n"
],
[
"!tail LoanStats_2018Q4.csv",
"\"\",\"\",\"5600\",\"5600\",\"5600\",\" 36 months\",\" 13.56%\",\"190.21\",\"C\",\"C1\",\"\",\"n/a\",\"RENT\",\"15600\",\"Not Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"credit_card\",\"Credit card refinancing\",\"836xx\",\"ID\",\"15.31\",\"0\",\"Aug-2012\",\"0\",\"\",\"97\",\"9\",\"1\",\"5996\",\"34.5%\",\"11\",\"w\",\"4404.61\",\"4404.61\",\"1701.34\",\"1701.34\",\"1195.39\",\"505.95\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"190.21\",\"Aug-2019\",\"Jul-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"5996\",\"0\",\"0\",\"0\",\"1\",\"20\",\"0\",\"\",\"0\",\"2\",\"3017\",\"35\",\"17400\",\"1\",\"0\",\"0\",\"3\",\"750\",\"4689\",\"45.5\",\"0\",\"0\",\"20\",\"73\",\"13\",\"13\",\"0\",\"13\",\"\",\"20\",\"\",\"0\",\"3\",\"5\",\"4\",\"4\",\"1\",\"9\",\"10\",\"5\",\"9\",\"0\",\"0\",\"0\",\"0\",\"100\",\"25\",\"1\",\"0\",\"17400\",\"5996\",\"8600\",\"0\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"23000\",\"23000\",\"23000\",\" 36 months\",\" 15.02%\",\"797.53\",\"C\",\"C3\",\"Tax Consultant\",\"10+ years\",\"MORTGAGE\",\"75000\",\"Source Verified\",\"Oct-2018\",\"Charged Off\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"352xx\",\"AL\",\"20.95\",\"1\",\"Aug-1985\",\"2\",\"22\",\"\",\"12\",\"0\",\"22465\",\"43.6%\",\"28\",\"w\",\"0.00\",\"0.00\",\"1547.08\",\"1547.08\",\"1025.67\",\"521.41\",\"0.0\",\"0.0\",\"0.0\",\"Dec-2018\",\"797.53\",\"\",\"Nov-2018\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"259658\",\"4\",\"2\",\"3\",\"3\",\"6\",\"18149\",\"86\",\"4\",\"6\",\"12843\",\"56\",\"51500\",\"2\",\"2\",\"5\",\"11\",\"21638\",\"26321\",\"44.1\",\"0\",\"0\",\"12\",\"397\",\"4\",\"4\",\"6\",\"5\",\"22\",\"4\",\"22\",\"0\",\"4\",\"5\",\"7\",\"14\",\"3\",\"9\",\"19\",\"5\",\"12\",\"0\",\"0\",\"0\",\"7\",\"96.4\",\"14.3\",\"0\",\"0\",\"296500\",\"40614\",\"47100\",\"21000\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"10000\",\"10000\",\"10000\",\" 36 months\",\" 15.02%\",\"346.76\",\"C\",\"C3\",\"security guard\",\"5 years\",\"MORTGAGE\",\"38000\",\"Not Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"443xx\",\"OH\",\"13.16\",\"3\",\"Jul-1982\",\"0\",\"6\",\"\",\"11\",\"0\",\"5634\",\"37.1%\",\"16\",\"w\",\"7902.84\",\"7902.84\",\"3112.5\",\"3112.50\",\"2097.16\",\"1015.34\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"346.76\",\"Aug-2019\",\"Jul-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"155\",\"77424\",\"0\",\"1\",\"0\",\"0\",\"34\",\"200\",\"10\",\"1\",\"1\",\"1866\",\"42\",\"15200\",\"2\",\"0\",\"0\",\"2\",\"7039\",\"4537\",\"50.1\",\"0\",\"0\",\"34\",\"434\",\"11\",\"11\",\"3\",\"11\",\"6\",\"17\",\"6\",\"0\",\"3\",\"5\",\"5\",\"6\",\"1\",\"8\",\"11\",\"5\",\"11\",\"0\",\"0\",\"0\",\"1\",\"73.3\",\"40\",\"0\",\"0\",\"91403\",\"9323\",\"9100\",\"2000\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"5000\",\"5000\",\"5000\",\" 36 months\",\" 13.56%\",\"169.83\",\"C\",\"C1\",\"Payoff Clerk\",\"10+ years\",\"MORTGAGE\",\"35360\",\"Not Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"381xx\",\"TN\",\"11.3\",\"1\",\"Jun-2006\",\"0\",\"21\",\"\",\"9\",\"0\",\"2597\",\"27.3%\",\"15\",\"f\",\"3932.69\",\"3932.69\",\"1524.7\",\"1524.70\",\"1067.31\",\"457.39\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"169.83\",\"Aug-2019\",\"Jul-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"1413\",\"69785\",\"0\",\"2\",\"0\",\"1\",\"16\",\"2379\",\"40\",\"3\",\"4\",\"1826\",\"32\",\"9500\",\"0\",\"0\",\"1\",\"5\",\"8723\",\"1174\",\"60.9\",\"0\",\"0\",\"147\",\"85\",\"9\",\"9\",\"2\",\"10\",\"21\",\"9\",\"21\",\"0\",\"1\",\"3\",\"2\",\"2\",\"6\",\"6\",\"7\",\"3\",\"9\",\"0\",\"0\",\"0\",\"3\",\"92.9\",\"50\",\"0\",\"0\",\"93908\",\"4976\",\"3000\",\"6028\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"10000\",\"10000\",\"9750\",\" 36 months\",\" 11.06%\",\"327.68\",\"B\",\"B3\",\"\",\"n/a\",\"RENT\",\"44400\",\"Source Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"credit_card\",\"Credit card refinancing\",\"980xx\",\"WA\",\"11.78\",\"0\",\"Oct-2008\",\"2\",\"40\",\"\",\"15\",\"0\",\"6269\",\"13.1%\",\"25\",\"f\",\"7800.53\",\"7605.52\",\"2933.76\",\"2860.42\",\"2199.47\",\"734.29\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"327.68\",\"Aug-2019\",\"Jul-2019\",\"0\",\"53\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"520\",\"16440\",\"3\",\"1\",\"1\",\"1\",\"2\",\"10171\",\"100\",\"2\",\"5\",\"404\",\"28\",\"47700\",\"0\",\"3\",\"5\",\"6\",\"1265\",\"20037\",\"2.3\",\"0\",\"0\",\"61\",\"119\",\"1\",\"1\",\"0\",\"1\",\"\",\"1\",\"40\",\"1\",\"2\",\"4\",\"6\",\"8\",\"3\",\"14\",\"22\",\"4\",\"15\",\"0\",\"0\",\"0\",\"3\",\"92\",\"0\",\"0\",\"0\",\"57871\",\"16440\",\"20500\",\"10171\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"10000\",\"10000\",\"10000\",\" 36 months\",\" 16.91%\",\"356.08\",\"C\",\"C5\",\"Key Accounts Manager\",\"2 years\",\"RENT\",\"80000\",\"Not Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"other\",\"Other\",\"021xx\",\"MA\",\"17.72\",\"1\",\"Sep-2006\",\"0\",\"14\",\"\",\"17\",\"0\",\"1942\",\"30.8%\",\"31\",\"w\",\"7950.71\",\"7950.71\",\"3195.33\",\"3195.33\",\"2049.29\",\"1146.04\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"356.08\",\"Aug-2019\",\"Jul-2019\",\"0\",\"25\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"59194\",\"0\",\"15\",\"1\",\"1\",\"12\",\"57252\",\"85\",\"0\",\"0\",\"1942\",\"80\",\"6300\",\"0\",\"5\",\"0\",\"1\",\"3482\",\"2058\",\"48.5\",\"0\",\"0\",\"144\",\"142\",\"40\",\"12\",\"0\",\"131\",\"30\",\"\",\"30\",\"3\",\"1\",\"1\",\"1\",\"5\",\"22\",\"2\",\"9\",\"1\",\"17\",\"0\",\"0\",\"0\",\"1\",\"74.2\",\"0\",\"0\",\"0\",\"73669\",\"59194\",\"4000\",\"67369\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\n\nTotal amount funded in policy code 1: 2050909275\nTotal amount funded in policy code 2: 820109297\n"
],
[
"import pandas as pd\n\n# Set Display options\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\n\ndf = pd.read_csv('LoanStats_2018Q4.csv', header=1, skipfooter=2, engine='python')\nprint(df.shape)\ndf.head()\n",
"(128412, 144)\n"
],
[
"df.tail()",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"df.isnull().sum().sort_values(ascending=False)",
"_____no_output_____"
],
[
"df = df.drop(columns=['id', 'member_id', 'desc', 'url'], axis='columns')",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
],
[
"# remove percent signs and convert to floats\ntype(df['int_rate'])",
"_____no_output_____"
],
[
"df['int_rate']",
"_____no_output_____"
],
[
"int_rate = '15.02%'\nint_rate[:-1]",
"_____no_output_____"
],
[
"int_list = ['15.02%', '13.56%', '16.91%']\nint_list[:2]\n",
"_____no_output_____"
],
[
"int_rate.strip('%')",
"_____no_output_____"
],
[
"type(int_rate.strip('%'))",
"_____no_output_____"
],
[
"float(int_rate.strip('%'))",
"_____no_output_____"
],
[
"type(float(int_rate.strip('%')))",
"_____no_output_____"
],
[
"def remove_percent_to_float(string):\n return float(string.strip('%'))\nint_list = ['15.02%', '13.56%', '16.91%']\n[remove_percent_to_float(item) for item in int_list]",
"_____no_output_____"
],
[
"df['int_rate'] = df['int_rate'].apply(remove_percent_to_float)",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df['emp_title'].value_counts(dropna=False).head(20)",
"_____no_output_____"
],
[
"df['emp_title'].value_counts(dropna=False).reset_index().shape",
"_____no_output_____"
],
[
"df.describe(exclude='number')",
"_____no_output_____"
],
[
"df['emp_title'].isnull().sum()",
"_____no_output_____"
],
[
"import numpy as np\ntype(np.NaN)",
"_____no_output_____"
],
[
"examples = ['owner', 'Supervisor', 'Project Manager', np.NaN]\n\ndef clean_title(item):\n if isinstance(item, str):\n return item.strip().title()\n else:\n return \"Unknown\"\n\n [clean_title(item) for item in examples] \n",
"_____no_output_____"
],
[
"df['emp_title'] = df['emp_title'].apply(clean_title)\n\ndf.head()",
"_____no_output_____"
],
[
"df['emp_title'].value_counts(dropna=False).head(20)",
"_____no_output_____"
],
[
"df['emp_title'].describe(exclude='number')",
"_____no_output_____"
],
[
"df['emp_title'].nunique()",
"_____no_output_____"
],
[
"df['emp_title_manager'] = True\nprint(df['emp_title_manager'])",
"0 True\n1 True\n2 True\n3 True\n4 True\n5 True\n6 True\n7 True\n8 True\n9 True\n10 True\n11 True\n12 True\n13 True\n14 True\n15 True\n16 True\n17 True\n18 True\n19 True\n20 True\n21 True\n22 True\n23 True\n24 True\n25 True\n26 True\n27 True\n28 True\n29 True\n30 True\n31 True\n32 True\n33 True\n34 True\n35 True\n36 True\n37 True\n38 True\n39 True\n40 True\n41 True\n42 True\n43 True\n44 True\n45 True\n46 True\n47 True\n48 True\n49 True\n50 True\n51 True\n52 True\n53 True\n54 True\n55 True\n56 True\n57 True\n58 True\n59 True\n60 True\n61 True\n62 True\n63 True\n64 True\n65 True\n66 True\n67 True\n68 True\n69 True\n70 True\n71 True\n72 True\n73 True\n74 True\n75 True\n76 True\n77 True\n78 True\n79 True\n80 True\n81 True\n82 True\n83 True\n84 True\n85 True\n86 True\n87 True\n88 True\n89 True\n90 True\n91 True\n92 True\n93 True\n94 True\n95 True\n96 True\n97 True\n98 True\n99 True\n100 True\n101 True\n102 True\n103 True\n104 True\n105 True\n106 True\n107 True\n108 True\n109 True\n110 True\n111 True\n112 True\n113 True\n114 True\n115 True\n116 True\n117 True\n118 True\n119 True\n120 True\n121 True\n122 True\n123 True\n124 True\n125 True\n126 True\n127 True\n128 True\n129 True\n130 True\n131 True\n132 True\n133 True\n134 True\n135 True\n136 True\n137 True\n138 True\n139 True\n140 True\n141 True\n142 True\n143 True\n144 True\n145 True\n146 True\n147 True\n148 True\n149 True\n150 True\n151 True\n152 True\n153 True\n154 True\n155 True\n156 True\n157 True\n158 True\n159 True\n160 True\n161 True\n162 True\n163 True\n164 True\n165 True\n166 True\n167 True\n168 True\n169 True\n170 True\n171 True\n172 True\n173 True\n174 True\n175 True\n176 True\n177 True\n178 True\n179 True\n180 True\n181 True\n182 True\n183 True\n184 True\n185 True\n186 True\n187 True\n188 True\n189 True\n190 True\n191 True\n192 True\n193 True\n194 True\n195 True\n196 True\n197 True\n198 True\n199 True\n200 True\n201 True\n202 True\n203 True\n204 True\n205 True\n206 True\n207 True\n208 True\n209 True\n210 True\n211 True\n212 True\n213 True\n214 True\n215 True\n216 True\n217 True\n218 True\n219 True\n220 True\n221 True\n222 True\n223 True\n224 True\n225 True\n226 True\n227 True\n228 True\n229 True\n230 True\n231 True\n232 True\n233 True\n234 True\n235 True\n236 True\n237 True\n238 True\n239 True\n240 True\n241 True\n242 True\n243 True\n244 True\n245 True\n246 True\n247 True\n248 True\n249 True\n ... \n128162 True\n128163 True\n128164 True\n128165 True\n128166 True\n128167 True\n128168 True\n128169 True\n128170 True\n128171 True\n128172 True\n128173 True\n128174 True\n128175 True\n128176 True\n128177 True\n128178 True\n128179 True\n128180 True\n128181 True\n128182 True\n128183 True\n128184 True\n128185 True\n128186 True\n128187 True\n128188 True\n128189 True\n128190 True\n128191 True\n128192 True\n128193 True\n128194 True\n128195 True\n128196 True\n128197 True\n128198 True\n128199 True\n128200 True\n128201 True\n128202 True\n128203 True\n128204 True\n128205 True\n128206 True\n128207 True\n128208 True\n128209 True\n128210 True\n128211 True\n128212 True\n128213 True\n128214 True\n128215 True\n128216 True\n128217 True\n128218 True\n128219 True\n128220 True\n128221 True\n128222 True\n128223 True\n128224 True\n128225 True\n128226 True\n128227 True\n128228 True\n128229 True\n128230 True\n128231 True\n128232 True\n128233 True\n128234 True\n128235 True\n128236 True\n128237 True\n128238 True\n128239 True\n128240 True\n128241 True\n128242 True\n128243 True\n128244 True\n128245 True\n128246 True\n128247 True\n128248 True\n128249 True\n128250 True\n128251 True\n128252 True\n128253 True\n128254 True\n128255 True\n128256 True\n128257 True\n128258 True\n128259 True\n128260 True\n128261 True\n128262 True\n128263 True\n128264 True\n128265 True\n128266 True\n128267 True\n128268 True\n128269 True\n128270 True\n128271 True\n128272 True\n128273 True\n128274 True\n128275 True\n128276 True\n128277 True\n128278 True\n128279 True\n128280 True\n128281 True\n128282 True\n128283 True\n128284 True\n128285 True\n128286 True\n128287 True\n128288 True\n128289 True\n128290 True\n128291 True\n128292 True\n128293 True\n128294 True\n128295 True\n128296 True\n128297 True\n128298 True\n128299 True\n128300 True\n128301 True\n128302 True\n128303 True\n128304 True\n128305 True\n128306 True\n128307 True\n128308 True\n128309 True\n128310 True\n128311 True\n128312 True\n128313 True\n128314 True\n128315 True\n128316 True\n128317 True\n128318 True\n128319 True\n128320 True\n128321 True\n128322 True\n128323 True\n128324 True\n128325 True\n128326 True\n128327 True\n128328 True\n128329 True\n128330 True\n128331 True\n128332 True\n128333 True\n128334 True\n128335 True\n128336 True\n128337 True\n128338 True\n128339 True\n128340 True\n128341 True\n128342 True\n128343 True\n128344 True\n128345 True\n128346 True\n128347 True\n128348 True\n128349 True\n128350 True\n128351 True\n128352 True\n128353 True\n128354 True\n128355 True\n128356 True\n128357 True\n128358 True\n128359 True\n128360 True\n128361 True\n128362 True\n128363 True\n128364 True\n128365 True\n128366 True\n128367 True\n128368 True\n128369 True\n128370 True\n128371 True\n128372 True\n128373 True\n128374 True\n128375 True\n128376 True\n128377 True\n128378 True\n128379 True\n128380 True\n128381 True\n128382 True\n128383 True\n128384 True\n128385 True\n128386 True\n128387 True\n128388 True\n128389 True\n128390 True\n128391 True\n128392 True\n128393 True\n128394 True\n128395 True\n128396 True\n128397 True\n128398 True\n128399 True\n128400 True\n128401 True\n128402 True\n128403 True\n128404 True\n128405 True\n128406 True\n128407 True\n128408 True\n128409 True\n128410 True\n128411 True\nName: emp_title_manager, Length: 128412, dtype: bool\n"
],
[
"df['emp_title_manager'] = df['emp_title'].str.contains(\"Manager\")\ndf.head()",
"_____no_output_____"
],
[
"condition = (df['emp_title_manager'] == True)\nmanagers = df[condition]\nprint(managers.shape)\nmanagers.head()",
"(17882, 141)\n"
],
[
"managers = df[df['emp_title'].str.contains('Manager')]\nprint(managers.shape)\nmanagers.head()",
"_____no_output_____"
],
[
"plebians = df[df['emp_title_manager'] == False]\nprint(plebians.shape)\nplebians.head()",
"_____no_output_____"
],
[
"managers['int_rate'].hist(bins=20);",
"_____no_output_____"
],
[
"plebians['int_rate'].hist(bins=20);",
"_____no_output_____"
],
[
"managers['int_rate'].plot.density()",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"plebians['int_rate'].plot.density()",
"_____no_output_____"
],
[
"managers['int_rate'].plot.density()",
"_____no_output_____"
],
[
"managers['int_rate'].plot.density()",
"_____no_output_____"
],
[
"managers['int_rate'].mean()",
"_____no_output_____"
],
[
"plebians['int_rate'].mean()",
"_____no_output_____"
],
[
"df['issue_d']",
"_____no_output_____"
],
[
"df['issue_d'].describe()",
"_____no_output_____"
],
[
"df['issue_d'].value_counts()",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
],
[
"df['issue_d'] = pd.to_datetime(df['issue_d'], infer_datetime_format=True)",
"_____no_output_____"
],
[
"df['issue_d'].head().values",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
],
[
"df['issue_d'].dt.year",
"_____no_output_____"
],
[
"df['issue_d'].dt.month",
"_____no_output_____"
],
[
"df['issue_year'] = df['issue_d'].dt.year",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"\ndf['issue_month'] = df['issue_d'].dt.month",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"[col for col in df if col.endswith('_d')]",
"_____no_output_____"
],
[
"df['earliest_cr_line'].head()",
"_____no_output_____"
],
[
"df['earliest_cr_line'] = pd.to_datetime(df['earliest_cr_line'],\n infer_datetime_format=True)",
"_____no_output_____"
],
[
"df['days_from_earliest_credit_to_issue'] = (df['issue_d'] - df['earliest_cr_line']).dt.days\ndf['days_from_earliest_credit_to_issue'].describe()",
"_____no_output_____"
],
[
"# convert 'term' column to int dtype\ndef remove_months(string):\n return int(string.strip(' months'))\ndf['term'] = df['term'].apply(lambda string: int(string.strip(' months')))\ndf['term'].head()",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"# make loan_status_is_great column \n# def great_or_not(stringy):\n \n# if stringy.str.contains('Current|Fully Paid', regex=True):\n# return True\n# else:\n# return False\n\n# df[\"loan_status_is_great\"] = df[\"loan_status\"].str.contains(\"Current|Fully Paid\")\n\ndf['loan_status_is_great'] = [1 if x in ['Current','Fully Paid'] else 0 for x in df['loan_status']]\n\n# lambda x: True if df['loan_status'].str.contains('Current|Fully Paid', regex=True)\n\n\n",
"_____no_output_____"
],
[
"df['loan_status_is_great'].head()",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"df['loan_status_is_great'].head()",
"_____no_output_____"
],
[
"df['last_pymnt_d'] = pd.to_datetime(df['last_pymnt_d'], infer_datetime_format=True)\ndf['last_pymnt_d_month'] = df['last_pymnt_d'].dt.month\ndf['last_pymnt_d_year'] = df['last_pymnt_d'].dt.year",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# STRETCH OPTIONS\n\nYou can do more with the LendingClub or Instacart datasets.\n\nLendingClub options:\n- There's one other column in the dataframe with percent signs. Remove them and convert to floats. You'll need to handle missing values.\n- Modify the `emp_title` column to replace titles with 'Other' if the title is not in the top 20. \n- Take initiatve and work on your own ideas!\n\nInstacart options:\n- Read [Instacart Market Basket Analysis, Winner's Interview: 2nd place, Kazuki Onodera](http://blog.kaggle.com/2017/09/21/instacart-market-basket-analysis-winners-interview-2nd-place-kazuki-onodera/), especially the **Feature Engineering** section. (Can you choose one feature from his bulleted lists, and try to engineer it with pandas code?)\n- Read and replicate parts of [Simple Exploration Notebook - Instacart](https://www.kaggle.com/sudalairajkumar/simple-exploration-notebook-instacart). (It's the Python Notebook with the most upvotes for this Kaggle competition.)\n- Take initiative and work on your own ideas!",
"_____no_output_____"
],
[
"You can uncomment and run the cells below to re-download and extract the Instacart data",
"_____no_output_____"
]
],
[
[
"# !wget https://s3.amazonaws.com/instacart-datasets/instacart_online_grocery_shopping_2017_05_01.tar.gz",
"_____no_output_____"
],
[
"# !tar --gunzip --extract --verbose --file=instacart_online_grocery_shopping_2017_05_01.tar.gz",
"_____no_output_____"
],
[
"# %cd instacart_2017_05_01",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"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"
],
[
"markdown"
],
[
"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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
4aaebc3131c998ddf1b653cef91328650017eebf
| 110,329 |
ipynb
|
Jupyter Notebook
|
Diversos/Exercicio Foursquare.ipynb
|
ClaudiaCCordeiro/Curso_IBM
|
2123ebf48e0657f61998f38fe803203be51877ff
|
[
"MIT"
] | null | null | null |
Diversos/Exercicio Foursquare.ipynb
|
ClaudiaCCordeiro/Curso_IBM
|
2123ebf48e0657f61998f38fe803203be51877ff
|
[
"MIT"
] | null | null | null |
Diversos/Exercicio Foursquare.ipynb
|
ClaudiaCCordeiro/Curso_IBM
|
2123ebf48e0657f61998f38fe803203be51877ff
|
[
"MIT"
] | null | null | null | 44.830963 | 251 | 0.416119 |
[
[
[
"Teste foursquare",
"_____no_output_____"
]
],
[
[
"import requests # library to handle requests\nimport pandas as pd # library for data analsysis\nimport numpy as np # library to handle data in a vectorized manner\nimport random # library for random number generation\n\n!conda install -c conda-forge geopy --yes \nfrom geopy.geocoders import Nominatim # module to convert an address into latitude and longitude values\n\n# libraries for displaying images\nfrom IPython.display import Image \nfrom IPython.core.display import HTML \n\n# tranforming json file into a pandas dataframe library\nfrom pandas.io.json import json_normalize\n\n!conda install -c conda-forge folium=0.5.0 --yes\nimport folium # plotting library\n\nimport json\n\nimport os\nimport branca\nimport io\n#import plotly.graph_objs as go \n#from plotly.offline import plot\n\nprint('Folium installed')\nprint('Libraries imported.')",
"Collecting package metadata (current_repodata.json): ...working... done\nSolving environment: ...working... done\n\n# All requested packages already installed.\n\nCollecting package metadata (current_repodata.json): ...working... done\nSolving environment: ...working... done\n\n# All requested packages already installed.\n\nFolium installed\nLibraries imported.\n"
],
[
"#CLIENT_ID = 'T1F14ZSMPK4DKKGTZASK3MLJU0RMKYNKQXTIYYW3SSTJHY4W' # your Foursquare ID\n#CLIENT_SECRET = 'ATJZAHQ1BW4ODDIPDNVPTR1D3ZTLPVNQAGBTJX1JMUIMKQLE' # your Foursquare Secret\nVERSION = '20180604'\n\n#print('Your credentails:')\n#print('CLIENT_ID: ' + CLIENT_ID)\n#print('CLIENT_SECRET:' + CLIENT_SECRET)",
"_____no_output_____"
],
[
"url ='https://api.foursquare.com/v2/venues/search?client_id=T1F14ZSMPK4DKKGTZASK3MLJU0RMKYNKQXTIYYW3SSTJHY4W&client_secret=ATJZAHQ1BW4ODDIPDNVPTR1D3ZTLPVNQAGBTJX1JMUIMKQLE&ll=-8.0615379,-34.895044&&v=20180604&categoryId=4bf58dd8d48988d104941735'",
"_____no_output_____"
],
[
"results = requests.get(url).json()\nresults",
"_____no_output_____"
],
[
"# assign relevant part of JSON to venues\nvenues = results['response']['venues']\n\n# tranform venues into a dataframe\ndataframe = json_normalize(venues)\ndataframe.head()",
"_____no_output_____"
],
[
"dataframe.head()",
"_____no_output_____"
],
[
"dataframe.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 30 entries, 0 to 29\nData columns (total 18 columns):\ncategories 30 non-null object\nhasPerk 30 non-null bool\nid 30 non-null object\nlocation.address 25 non-null object\nlocation.cc 30 non-null object\nlocation.city 28 non-null object\nlocation.country 30 non-null object\nlocation.crossStreet 7 non-null object\nlocation.distance 30 non-null int64\nlocation.formattedAddress 30 non-null object\nlocation.labeledLatLngs 30 non-null object\nlocation.lat 30 non-null float64\nlocation.lng 30 non-null float64\nlocation.neighborhood 1 non-null object\nlocation.postalCode 16 non-null object\nlocation.state 28 non-null object\nname 30 non-null object\nreferralId 30 non-null object\ndtypes: bool(1), float64(2), int64(1), object(14)\nmemory usage: 4.1+ KB\n"
],
[
"# keep only columns that include venue name, and anything that is associated with location\nfiltered_columns = ['name', 'categories'] + [col for col in dataframe.columns if col.startswith('location.')] + ['id']\ndataframe_filtered = dataframe.loc[:, filtered_columns]\n\n# function that extracts the category of the venue\ndef get_category_type(row):\n try:\n categories_list = row['categories']\n except:\n categories_list = row['venue.categories']\n \n if len(categories_list) == 0:\n return None\n else:\n return categories_list[0]['name']\n\n# filter the category for each row\ndataframe_filtered['categories'] = dataframe_filtered.apply(get_category_type, axis=1)\n\n# clean column names by keeping only last term\ndataframe_filtered.columns = [column.split('.')[-1] for column in dataframe_filtered.columns]\n\ndataframe_filtered",
"_____no_output_____"
],
[
"dataframe_filtered.head()",
"_____no_output_____"
],
[
"dataframe_filtered.name\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaec1b87f67eb49fa5b2308f91195080c6b2474
| 26,069 |
ipynb
|
Jupyter Notebook
|
site/en/tutorials/keras/basic_regression.ipynb
|
iggy12345/docs
|
cc5c7559f7ed822c97cb750fc789964b505210e4
|
[
"Apache-2.0"
] | null | null | null |
site/en/tutorials/keras/basic_regression.ipynb
|
iggy12345/docs
|
cc5c7559f7ed822c97cb750fc789964b505210e4
|
[
"Apache-2.0"
] | null | null | null |
site/en/tutorials/keras/basic_regression.ipynb
|
iggy12345/docs
|
cc5c7559f7ed822c97cb750fc789964b505210e4
|
[
"Apache-2.0"
] | null | null | null | 30.633373 | 414 | 0.510798 |
[
[
[
"##### Copyright 2018 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
],
[
"#@title MIT License\n#\n# Copyright (c) 2017 François Chollet\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.",
"_____no_output_____"
]
],
[
[
"# Regression: predict fuel efficiency",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/keras/basic_regression\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/keras/basic_regression.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/tutorials/keras/basic_regression.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"In a *regression* problem, we aim to predict the output of a continuous value, like a price or a probability. Contrast this with a *classification* problem, where we aim to select a class from a list of classes (for example, where a picture contains an apple or an orange, recognizing which fruit is in the picture).\n\nThis notebook uses the classic [Auto MPG](https://archive.ics.uci.edu/ml/datasets/auto+mpg) Dataset and builds a model to predict the fuel efficiency of late-1970s and early 1980s automobiles. To do this, we'll provide the model with a description of many automobiles from that time period. This description includes attributes like: cylinders, displacement, horsepower, and weight.\n\nThis example uses the `tf.keras` API, see [this guide](https://www.tensorflow.org/guide/keras) for details.",
"_____no_output_____"
]
],
[
[
"# Use seaborn for pairplot\n!pip install seaborn",
"_____no_output_____"
],
[
"from __future__ import absolute_import, division, print_function\n\nimport pathlib\n\nimport pandas as pd\nimport seaborn as sns\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nprint(tf.__version__)",
"_____no_output_____"
]
],
[
[
"## The Auto MPG dataset\n\nThe dataset is available from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/).\n\n",
"_____no_output_____"
],
[
"### Get the data\nFirst download the dataset.",
"_____no_output_____"
]
],
[
[
"dataset_path = keras.utils.get_file(\"auto-mpg.data\", \"https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data\")\ndataset_path",
"_____no_output_____"
]
],
[
[
"Import it using pandas",
"_____no_output_____"
]
],
[
[
"column_names = ['MPG','Cylinders','Displacement','Horsepower','Weight',\n 'Acceleration', 'Model Year', 'Origin'] \nraw_dataset = pd.read_csv(dataset_path, names=column_names,\n na_values = \"?\", comment='\\t',\n sep=\" \", skipinitialspace=True)\n\ndataset = raw_dataset.copy()\ndataset.tail()",
"_____no_output_____"
]
],
[
[
"### Clean the data\n\nThe dataset contains a few unknown values. ",
"_____no_output_____"
]
],
[
[
"dataset.isna().sum()",
"_____no_output_____"
]
],
[
[
"To keep this initial tutorial simple drop those rows. ",
"_____no_output_____"
]
],
[
[
"dataset = dataset.dropna()",
"_____no_output_____"
]
],
[
[
"The `\"Origin\"` column is really categorical, not numeric. So convert that to a one-hot:",
"_____no_output_____"
]
],
[
[
"origin = dataset.pop('Origin')",
"_____no_output_____"
],
[
"dataset['USA'] = (origin == 1)*1.0\ndataset['Europe'] = (origin == 2)*1.0\ndataset['Japan'] = (origin == 3)*1.0\ndataset.tail()",
"_____no_output_____"
]
],
[
[
"### Split the data into train and test\n\nNow split the dataset into a training set and a test set.\n\nWe will use the test set in the final evaluation of our model.",
"_____no_output_____"
]
],
[
[
"train_dataset = dataset.sample(frac=0.8,random_state=0)\ntest_dataset = dataset.drop(train_dataset.index)",
"_____no_output_____"
]
],
[
[
"### Inspect the data\n\nHave a quick look at the joint distribution of a few pairs of columns from the training set.",
"_____no_output_____"
]
],
[
[
"sns.pairplot(train_dataset[[\"MPG\", \"Cylinders\", \"Displacement\", \"Weight\"]], diag_kind=\"kde\")",
"_____no_output_____"
]
],
[
[
"Also look at the overall statistics:",
"_____no_output_____"
]
],
[
[
"train_stats = train_dataset.describe()\ntrain_stats.pop(\"MPG\")\ntrain_stats = train_stats.transpose()\ntrain_stats",
"_____no_output_____"
]
],
[
[
"### Split features from labels\n\nSeparate the target value, or \"label\", from the features. This label is the value that you will train the model to predict.",
"_____no_output_____"
]
],
[
[
"train_labels = train_dataset.pop('MPG')\ntest_labels = test_dataset.pop('MPG')",
"_____no_output_____"
]
],
[
[
"### Normalize the data\n\nLook again at the `train_stats` block above and note how different the ranges of each feature are.",
"_____no_output_____"
],
[
"It is good practice to normalize features that use different scales and ranges. Although the model *might* converge without feature normalization, it makes training more difficult, and it makes the resulting model dependent on the choice of units used in the input. \n\nNote: Although we intentionally generate these statistics from only the training dataset, these statistics will also be used to normalize the test dataset. We need to do that to project the test dataset into the same distribution that the model has been trained on.",
"_____no_output_____"
]
],
[
[
"def norm(x):\n return (x - train_stats['mean']) / train_stats['std']\nnormed_train_data = norm(train_dataset)\nnormed_test_data = norm(test_dataset)",
"_____no_output_____"
]
],
[
[
"This normalized data is what we will use to train the model.\n\nCaution: The statistics used to normalize the inputs here (mean and standard deviation) need to be applied to any other data that is fed to the model, along with the one-hot encoding that we did earlier. That includes the test set as well as live data when the model is used in production.",
"_____no_output_____"
],
[
"## The model",
"_____no_output_____"
],
[
"### Build the model\n\nLet's build our model. Here, we'll use a `Sequential` model with two densely connected hidden layers, and an output layer that returns a single, continuous value. The model building steps are wrapped in a function, `build_model`, since we'll create a second model, later on.",
"_____no_output_____"
]
],
[
[
"def build_model():\n model = keras.Sequential([\n layers.Dense(64, activation=tf.nn.relu, input_shape=[len(train_dataset.keys())]),\n layers.Dense(64, activation=tf.nn.relu),\n layers.Dense(1)\n ])\n\n optimizer = tf.keras.optimizers.RMSprop(0.001)\n\n model.compile(loss='mse',\n optimizer=optimizer,\n metrics=['mae', 'mse'])\n return model",
"_____no_output_____"
],
[
"model = build_model()",
"_____no_output_____"
]
],
[
[
"### Inspect the model\n\nUse the `.summary` method to print a simple description of the model",
"_____no_output_____"
]
],
[
[
"model.summary()",
"_____no_output_____"
]
],
[
[
"\nNow try out the model. Take a batch of `10` examples from the training data and call `model.predict` on it.",
"_____no_output_____"
]
],
[
[
"example_batch = normed_train_data[:10]\nexample_result = model.predict(example_batch)\nexample_result",
"_____no_output_____"
]
],
[
[
"It seems to be working, and it produces a result of the expected shape and type.",
"_____no_output_____"
],
[
"### Train the model\n\nTrain the model for 1000 epochs, and record the training and validation accuracy in the `history` object.",
"_____no_output_____"
]
],
[
[
"# Display training progress by printing a single dot for each completed epoch\nclass PrintDot(keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs):\n if epoch % 100 == 0: print('')\n print('.', end='')\n\nEPOCHS = 1000\n\nhistory = model.fit(\n normed_train_data, train_labels,\n epochs=EPOCHS, validation_split = 0.2, verbose=0,\n callbacks=[PrintDot()])",
"_____no_output_____"
]
],
[
[
"Visualize the model's training progress using the stats stored in the `history` object.",
"_____no_output_____"
]
],
[
[
"hist = pd.DataFrame(history.history)\nhist['epoch'] = history.epoch\nhist.tail()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\ndef plot_history(history):\n hist = pd.DataFrame(history.history)\n hist['epoch'] = history.epoch\n \n plt.figure()\n plt.xlabel('Epoch')\n plt.ylabel('Mean Abs Error [MPG]')\n plt.plot(hist['epoch'], hist['mean_absolute_error'],\n label='Train Error')\n plt.plot(hist['epoch'], hist['val_mean_absolute_error'],\n label = 'Val Error')\n plt.legend()\n plt.ylim([0,5])\n \n plt.figure()\n plt.xlabel('Epoch')\n plt.ylabel('Mean Square Error [$MPG^2$]')\n plt.plot(hist['epoch'], hist['mean_squared_error'],\n label='Train Error')\n plt.plot(hist['epoch'], hist['val_mean_squared_error'],\n label = 'Val Error')\n plt.legend()\n plt.ylim([0,20])\n\nplot_history(history)",
"_____no_output_____"
]
],
[
[
"This graph shows little improvement, or even degradation in the validation error after about 100 epochs. Let's update the `model.fit` call to automatically stop training when the validation score doesn't improve. We'll use an *EarlyStopping callback* that tests a training condition for every epoch. If a set amount of epochs elapses without showing improvement, then automatically stop the training.\n\nYou can learn more about this callback [here](https://www.tensorflow.org/versions/master/api_docs/python/tf/keras/callbacks/EarlyStopping).",
"_____no_output_____"
]
],
[
[
"model = build_model()\n\n# The patience parameter is the amount of epochs to check for improvement\nearly_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)\n\nhistory = model.fit(normed_train_data, train_labels, epochs=EPOCHS,\n validation_split = 0.2, verbose=0, callbacks=[early_stop, PrintDot()])\n\nplot_history(history)",
"_____no_output_____"
]
],
[
[
"The graph shows that on the validation set, the average error is usually around +/- 2 MPG. Is this good? We'll leave that decision up to you.\n\nLet's see how well the model generalizes by using the **test** set, which we did not use when training the model. This tells us how well we can expect the model to predict when we use it in the real world.",
"_____no_output_____"
]
],
[
[
"loss, mae, mse = model.evaluate(normed_test_data, test_labels, verbose=0)\n\nprint(\"Testing set Mean Abs Error: {:5.2f} MPG\".format(mae))",
"_____no_output_____"
]
],
[
[
"### Make predictions\n\nFinally, predict MPG values using data in the testing set:",
"_____no_output_____"
]
],
[
[
"test_predictions = model.predict(normed_test_data).flatten()\n\nplt.scatter(test_labels, test_predictions)\nplt.xlabel('True Values [MPG]')\nplt.ylabel('Predictions [MPG]')\nplt.axis('equal')\nplt.axis('square')\nplt.xlim([0,plt.xlim()[1]])\nplt.ylim([0,plt.ylim()[1]])\n_ = plt.plot([-100, 100], [-100, 100])\n",
"_____no_output_____"
]
],
[
[
"It looks like our model predicts reasonably well. Let's take a look at the error distribution.",
"_____no_output_____"
]
],
[
[
"error = test_predictions - test_labels\nplt.hist(error, bins = 25)\nplt.xlabel(\"Prediction Error [MPG]\")\n_ = plt.ylabel(\"Count\")",
"_____no_output_____"
]
],
[
[
"It's not quite gaussian, but we might expect that because the number of samples is very small.",
"_____no_output_____"
],
[
"## Conclusion\n\nThis notebook introduced a few techniques to handle a regression problem.\n\n* Mean Squared Error (MSE) is a common loss function used for regression problems (different loss functions are used for classification problems).\n* Similarly, evaluation metrics used for regression differ from classification. A common regression metric is Mean Absolute Error (MAE).\n* When numeric input data features have values with different ranges, each feature should be scaled independently to the same range.\n* If there is not much training data, one technique is to prefer a small network with few hidden layers to avoid overfitting.\n* Early stopping is a useful technique to prevent overfitting.",
"_____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"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4aaed2e6e5343a1fabf9b8b673a00e374385c71c
| 225,737 |
ipynb
|
Jupyter Notebook
|
lectures/Week3.ipynb
|
s183920/comsocsci2021
|
a089639a7691dcfa643d655892aaf8897dab24fa
|
[
"MIT"
] | null | null | null |
lectures/Week3.ipynb
|
s183920/comsocsci2021
|
a089639a7691dcfa643d655892aaf8897dab24fa
|
[
"MIT"
] | null | null | null |
lectures/Week3.ipynb
|
s183920/comsocsci2021
|
a089639a7691dcfa643d655892aaf8897dab24fa
|
[
"MIT"
] | null | null | null | 223.060277 | 70,176 | 0.892561 |
[
[
[
"# Overview\n\nNetworks (a.k.a. graphs) are widely used mathematical objects for representing and analysing social systems. \nThis week is about getting familiar with networks, and we'll focus on four main aspects:\n\n* Basic mathematical description of networks\n* The `NetworkX` library.\n* Building the network of GME redditors.\n* Basic analysis of the network of GME redditors.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport networkx as nx\nimport scipy\n\n",
"_____no_output_____"
]
],
[
[
"# Part 1: Basic mathematical description of networks\n\nThis week, let's start with some lecturing. You will watch some videos made by Sune for his course _Social Graphs and Interactions_, where he covers networks in details. \n\n> **_Video Lecture_**. Start by watching the [\"History of Networks\"](https://youtu.be/qjM9yMarl70). \n",
"_____no_output_____"
]
],
[
[
"from IPython.display import YouTubeVideo\nYouTubeVideo(\"qjM9yMarl70\",width=800, height=450)",
"_____no_output_____"
]
],
[
[
"> **_Video Lecture_**. Then check out a few comments on [\"Network Notation\"](https://youtu.be/MMziC5xktHs). ",
"_____no_output_____"
]
],
[
[
"YouTubeVideo(\"MMziC5xktHs\",width=800, height=450)",
"_____no_output_____"
]
],
[
[
"> _Reading_. We'll be reading the textbook _Network Science_ (NS) by Laszlo Barabasi. You can read the whole \n> thing for free [**here**](http://barabasi.com/networksciencebook/). \n> \n> * Read chapter 1\\.\n> * Read chapter 2\\.\n> ",
"_____no_output_____"
],
[
"> _Exercises_ \n> _Chapter 1_ (Don't forget that you should be answering these in a Jupyter notebook.) \n> \n> * List three different real networks and state the nodes and links for each of them.\n>\n><b> Answer: </b> Facebook (nodes = people, links = friendships), busroutes (nodes = stops, links = busses), power grid (nodes = power plants, links = cables)\n>\n> * Tell us of the network you are personally most interested in. Address the following questions:\n> * What are its nodes and links? \n> * How large is it? \n> * Can be mapped out? \n> * Why do you care about it? \n><b> Answer: </b> A network of interest could nbe courses at DTU, where the nodes are the courses and links are requirements (requiered courses have a directed link to the course), the size is the number of courses at DTU and it can be mapped out. I care about because it shows which courses give access to the most new courses and what courses are needed for a specific course\n> * In your view what would be the area where network science could have the biggest impact in the next decade? Explain your answer - and base it on the text in the book. \n\n\n>\n> _Chapter 2_\n> \n> * Section 2.5 states that real networks are sparse. Can you think of a real network where each node has _many_ connections? Is that network still sparse? If yes, can you explain why?\n><b> Answer: </b> A network representing people that know each other, each node is a person, this is very sparse as people only know a very small fraction of all people in the entire world\n> There are more questions on Chapter 2 below.\n> ",
"_____no_output_____"
],
[
"# Part 2: Exercises using the `NetworkX` library\n\nWe will analyse networks in Python using the [NetworkX](https://networkx.org/) library. The cool thing about networkx is that it includes a lot of algorithms and metrics for analysing networks, so you don't have to code things from scratch. Get started by running the magic ``pip install networkx`` command. Then, get familiar with the library through the following exercises: \n\n> *Exercises*:\n\n> * Go to the NetworkX project's [tutorial page](https://networkx.org/documentation/stable/tutorial.html). The goal of this exercise is to create your own notebook that contains the entire tutorial. You're free to add your own (e.g. shorter) comments in place of the ones in the official tutorial - and change the code to make it your own where ever it makes sense.\n> * Go to Section 2.12: [Homework](http://networksciencebook.com/chapter/2#homework2), then\n> * Write the solution for exercise 2.1 (the 'Königsberg Problem') from NS in your notebook.\n> * Solve exercise 2.3 ('Graph representation') from NS using NetworkX in your notebook. (You don't have to solve the last sub-question about cycles of length 4 ... but I'll be impressed if you do it).\n> * Solve exercise 2.5 ('Bipartite Networks') from NS using NetworkX in your notebook.",
"_____no_output_____"
],
[
"### NetworkX tutorial\nsee seperate notebook",
"_____no_output_____"
],
[
"### Königsberg Problem \nWhich of the icons in Image 2.19 can be drawn without raising yourpencil from the paper, and without drawing any line more than once? Why?\n\n> a) only two edges has an uneven number of nodes and must therefore be start and finish <br>\n> c) all nodes have an even number of edges <br>\n> d) only two nodes have an uneven number of edges",
"_____no_output_____"
],
[
"### Graph Representation\nThe adjacency matrix is a useful graph representation for many analytical calculations. However, when we need to store a network in a computer, we can save computer memory by offering the list of links in a Lx2 matrix, whose rows contain the starting and end point i and j of each link. Construct for the networks (a) and (b) in Imade 2.20:",
"_____no_output_____"
]
],
[
[
"nodes = np.arange(1,7)\nedges = [(1,2), (2, 3), (2,4), (3,1), (3,2), (4,1), (6,1), (6,3)]\n\nG1 = nx.DiGraph()\nG1.add_nodes_from(nodes)\nG1.add_edges_from(edges)\nG2 = nx.Graph(G1)\n\nplt.figure(figsize = (10, 5))\nplt.subplot(121)\nnx.draw_shell(G2, with_labels = True)\nplt.subplot(122)\nnx.draw_shell(G1, with_labels = True)",
"_____no_output_____"
],
[
"bold = \"\\033[1m\"\nend = '\\033[0m'\n\nprint(bold,\"Adjacency matrix for undirected: \\n\", end, nx.linalg.graphmatrix.adjacency_matrix(G2).todense(), \"\\n\")\nprint(bold,\"Adjacency matrix for directed: \\n\", end, nx.linalg.graphmatrix.adjacency_matrix(G1).todense(), \"\\n\")\n\nprint(bold, \"Linked list for undirected: \", end, G2.edges, \"\\n\")\nprint(bold, \"Linked list for directed: \", end, G1.edges, \"\\n\")\n\nprint(bold, \"Average clustering coefficient for undirected: \", end, nx.average_clustering(G2), \"\\n\")\n\nprint(bold, \"Swapping 5 and 6: \", end)\nprint(\"Swapping the label of nodes 5 and 6 in the undirected graph, will swap the rows and columns of 5 and 6 inb the adjacency matrix and in the linked list all 5's are replaced with 6 and vice versa\\n\")\n\nprint(bold, \"Adjacency matrix vs linked list: \", end)\nprint(\"In a linked list we will not have informatiuon about node 5 being present, as it has no edges, but it will appear in the adjacency matrix\\n\")\n\nprint(bold,\"Paths of length 3\", end)\nA1 = nx.to_numpy_matrix(G2)\nA2 = nx.to_numpy_matrix(G1)\n# see for explanation of matrix stuff: https://quickmathintuitions.org/finding-paths-length-n-graph/\nprint(f\"There are {(A1@A1@A1)[0,2]} paths of length 3 from 1 to 3 in the undirected graph\")\nprint(f\"There are {(A2@A2@A2)[0,2]} paths of length 3 from 1 to 3 in the directed graph\\n\")\n\ncycles = [x for x in list(nx.simple_cycles(G2.to_directed())) if len(x) == 4]\nprint(bold, \"Number of cycles with length 4: \", end, len(cycles))",
"\u001b[1m Adjacency matrix for undirected: \n \u001b[0m [[0 1 1 1 0 1]\n [1 0 1 1 0 0]\n [1 1 0 0 0 1]\n [1 1 0 0 0 0]\n [0 0 0 0 0 0]\n [1 0 1 0 0 0]] \n\n\u001b[1m Adjacency matrix for directed: \n \u001b[0m [[0 1 0 0 0 0]\n [0 0 1 1 0 0]\n [1 1 0 0 0 0]\n [1 0 0 0 0 0]\n [0 0 0 0 0 0]\n [1 0 1 0 0 0]] \n\n\u001b[1m Linked list for undirected: \u001b[0m [(1, 2), (1, 3), (1, 4), (1, 6), (2, 3), (2, 4), (3, 6)] \n\n\u001b[1m Linked list for directed: \u001b[0m [(1, 2), (2, 3), (2, 4), (3, 1), (3, 2), (4, 1), (6, 1), (6, 3)] \n\n\u001b[1m Average clustering coefficient for undirected: \u001b[0m 0.6388888888888888 \n\n\u001b[1m Swapping 5 and 6: \u001b[0m\nSwapping the label of nodes 5 and 6 in the undirected graph, will swap the rows and columns of 5 and 6 inb the adjacency matrix and in the linked list all 5's are replaced with 6 and vice versa\n\n\u001b[1m Adjacency matrix vs linked list: \u001b[0m\nIn a linked list we will not have informatiuon about node 5 being present, as it has no edges, but it will appear in the adjacency matrix\n\n\u001b[1m Paths of length 3 \u001b[0m\nThere are 7.0 paths of length 3 from 1 to 3 in the undirected graph\nThere are 0.0 paths of length 3 from 1 to 3 in the directed graph\n\n\u001b[1m Number of cycles with length 4: \u001b[0m 4\n"
]
],
[
[
"### Bipartite networks",
"_____no_output_____"
]
],
[
[
"nodes = np.arange(1, 12)\nedges = [(1,7), (2,9), (3,7), (3,8), (3,9), (4,9), (4,10), (5,9), (5,11), (6,11)]\nG = nx.Graph()\nG.add_nodes_from(nodes)\nG.add_edges_from(edges)\ncolor_map = [\"green\" if x >=7 else \"purple\" for x in range(1, 12)]\n\nX, Y = nx.bipartite.sets(G)\npos = dict()\npos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1\npos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2\nnx.draw(G, pos=pos, with_labels = True, node_color = color_map)\nplt.show()",
"_____no_output_____"
],
[
"bold = \"\\033[1m\"\nend = '\\033[0m'\n\nprint(bold,\"Adjacency matrix:\\n\", end, nx.linalg.graphmatrix.adjacency_matrix(G).todense(), \"\\n\")\nprint(\"Block diagnoal as nodes < 7 are not connected with each other and nodes >6 are not connected with each other\\n\")\n\npurp_proj = nx.algorithms.bipartite.projected_graph(G, list(G.nodes)[:6])\ngreen_proj = nx.algorithms.bipartite.projected_graph(G, list(G.nodes)[7:])\nprint(bold, \"Projections\", end)\nprint(\"Adjacency matrix of purple projection:\\n\", nx.to_numpy_matrix(purp_proj))\nprint(\"Adjacency matrix of green projection:\\n\", nx.to_numpy_matrix(green_proj), \"\\n\")\n\nprint(bold, \"Average degree\", end)\nprint(\"Average degree of purple nodes: \", sum([G.degree[i] for i in range(1, 7)])/6)\nprint(\"Average degree of green nodes: \", sum([G.degree[i] for i in range(7, 12)])/5, \"\\n\")\n\nprint(bold, \"Average degree in projections\", end)\nprint(\"Average degree in purple projection: \", sum([purp_proj.degree[i] for i in range(1, 7)])/6)\nprint(\"Average degree in green projection: \", sum([green_proj.degree[i] for i in range(7, 12)])/5)",
"\u001b[1m Adjacency matrix:\n \u001b[0m [[0 0 0 0 0 0 1 0 0 0 0]\n [0 0 0 0 0 0 0 0 1 0 0]\n [0 0 0 0 0 0 1 1 1 0 0]\n [0 0 0 0 0 0 0 0 1 1 0]\n [0 0 0 0 0 0 0 0 1 0 1]\n [0 0 0 0 0 0 0 0 0 0 1]\n [1 0 1 0 0 0 0 0 0 0 0]\n [0 0 1 0 0 0 0 0 0 0 0]\n [0 1 1 1 1 0 0 0 0 0 0]\n [0 0 0 1 0 0 0 0 0 0 0]\n [0 0 0 0 1 1 0 0 0 0 0]] \n\nBlock diagnoal as nodes < 7 are not connected with each other and nodes >6 are not connected with each other\n\n\u001b[1m Projections \u001b[0m\nAdjacency matrix of purple projection:\n [[0. 0. 1. 0. 0. 0.]\n [0. 0. 1. 1. 1. 0.]\n [1. 1. 0. 1. 1. 0.]\n [0. 1. 1. 0. 1. 0.]\n [0. 1. 1. 1. 0. 1.]\n [0. 0. 0. 0. 1. 0.]]\nAdjacency matrix of green projection:\n [[0. 1. 0. 0. 1.]\n [1. 0. 1. 1. 1.]\n [0. 1. 0. 0. 0.]\n [0. 1. 0. 0. 0.]\n [1. 1. 0. 0. 0.]] \n\n\u001b[1m Average degree \u001b[0m\nAverage degree of purple nodes: 1.6666666666666667\nAverage degree of green nodes: 2.0 \n\n\u001b[1m Average degree in projections \u001b[0m\nAverage degree in purple projection: 2.6666666666666665\nAverage degree in green projection: 2.0\n"
]
],
[
[
"# Part 3: Building the GME redditors network",
"_____no_output_____"
],
[
"Ok, enough with theory :) It is time to go back to our cool dataset it took us so much pain to download! And guess what? We will build the network of GME Redditors. Then, we will use some Network Science to study some of its properties.",
"_____no_output_____"
],
[
"\n> \n> *Exercise*: Build the network of Redditors discussing about GME on r\\wallstreetbets. In this network, nodes correspond to authors of comments, and a direct link going from node _A_ to node _B_ exists if _A_ ever answered a submission or a comment by _B_. The weight on the link corresponds to the number of times _A_ answered _B_. You can build the network as follows:\n>\n> 1. Open the _comments dataset_ and the _submission datasets_ (the first contains all the comments and the second cointains all the submissions) and store them in two Pandas DataFrames.\n> 2. Create three dictionaries, using the command ``dict(zip(keys,values))``, where keys and values are columns in your dataframes. The three dictionaries are the following:\n> * __comment_authors__: (_comment id_, _comment author_)\n> * __parent__: (_comment id_ , _parent id_)\n> * __submission_authors__: (_submission id_, _submission author_)\n>\n> where above I indicated the (key, value) tuples contained in each dictionary.\n>\n> 3. Create a function that take as input a _comment id_ and outputs the author of its parent. The function does two things:\n> * First, it calls the dictionary __parent__, to find the _parent id_ of the comment identified by a given _comment id_. \n> * Then, it finds the author of _parent id_. \n> * if the _parent id_ starts with \"t1_\", call the __comment_authors__ dictionary (for key=parent_id[3:])\n> * if the _parent id_ starts with \"t3_\", call the __submission_authors__ dictionars (for key=parent_id[3:])\n>\n> where by parent_id[3:], I mean that the first three charachters of the _parent id_ (either \"t1_\" or \"t3_\" should be ingnored).\n>\n> 4. Apply the function you created in step 3. to all the comment ids in your comments dataframe. Store the output in a new column, _\"parent author\"_, of the comments dataframe. \n> 5. For now, we will focus on the genesis of the GME community on Reddit, before all the hype started and many new redditors jumped on board. For this reason, __filter all the comments written before Dec 31st, 2020__. Also, remove deleted users by filtering all comments whose author or parent author is equal to \"[deleted]\". \n> 6. Create the weighted edge-list of your network as follows: consider all comments (after applying the filtering step above), groupby (\"_author_\", _\"parent author\"_) and count. \n> 7. Create a [``DiGraph``](https://networkx.org/documentation/stable//reference/classes/digraph.html) using networkx. Then, use the networkx function [``add_weighted_edges_from``](https://networkx.org/documentation/networkx-1.9/reference/generated/networkx.DiGraph.add_weighted_edges_from.html) to create a weighted, directed, graph starting from the edgelist you created in step 5.",
"_____no_output_____"
]
],
[
[
"# data\ncomments_org = pd.read_csv(\"Data/week1/gme_reddit_comments.csv\", parse_dates = [\"creation_date\"])\nsubmissions_org = pd.read_csv(\"Data/week1/gme_reddit_submissions.csv\", parse_dates = [\"creation_date\"])\n\n# dictionaries\ncomment_authors = dict(zip(comments_org[\"id\"], comments_org[\"author\"]))\nparent = dict(zip(comments_org[\"id\"], comments_org[\"parent_id\"]))\nsubmissions_authors = dict(zip(submissions_org[\"id\"], submissions_org[\"author\"]))\n\n# function for getting author of parent id\ndef get_parent_author(comment_id):\n parent_id = parent[comment_id]\n t_parent_id = parent_id[:3]\n parent_id = parent_id[3:]\n \n try:\n if t_parent_id == \"t1_\":\n return comment_authors[parent_id]# if parent_id in comment_authors.keys else None\n elif t_parent_id == \"t3_\":\n return submissions_authors[parent_id]\n else:\n return -1\n except KeyError:\n return -1\n \n# create parent_author column in comments dataframe\ncomments = comments_org\ncomments[\"parent_author\"] = list(map(get_parent_author, comments[\"id\"])) #get_parent_author(comments.id)\n\n# remove unwanted authors\ncomments = comments[comments.parent_author != -1] # remove rows with keyerror (around 14k rows)\ncomments = comments[comments.creation_date <= \"2020-12-31\"] # remove comments from after 31/12-2020\ncomments = comments[(comments.author != \"[deleted]\") & (comments.parent_author != \"[deleted]\")]# remove deleted users\n",
"_____no_output_____"
],
[
"#Create the weighted edge-list of your network\ncomments_network = comments.groupby([\"author\", \"parent_author\"]).size()\ncomments_network = comments_network.reset_index()\ncomments_network.columns = [\"author\", \"parent_author\",\"weight\"]\ncomments_network.to_csv(\"Data/week4/comments_network.csv\", index = False)",
"_____no_output_____"
],
[
"# plot a subset of the users to view graph\ncomments1 = comments_network[:10]\nG_subset = nx.from_pandas_edgelist(comments1, \"author\", \"parent_author\", \"weight\", create_using = nx.DiGraph())\nnx.draw_shell(G_subset, with_labels = True)\nplt.show()\n\n# create the complete graph - is the direction correct? should it go from parent_author to author following a tree structure?\nG = nx.from_pandas_edgelist(comments_network, \"author\", \"parent_author\", \"weight\", create_using = nx.DiGraph())",
"_____no_output_____"
]
],
[
[
"# Part 4: Preliminary analysis of the GME redditors network",
"_____no_output_____"
],
[
"We begin with a preliminary analysis of the network.\n\n> \n> *Exercise: Basic Analysis of the Redditors Network*\n> * Why do you think I want you guys to use a _directed_ graph? Could have we used an undirected graph instead?\n> * What is the total number of nodes in the network? What is the total number of links? What is the density of the network (the total number of links over the maximum number of links)?\n> * What are the average, median, mode, minimum and maximum value of the in-degree (number of incoming edges per redditor)? And of the out-degree (number of outgoing edges per redditor)? How do you intepret the results?\n> * List the top 5 Redditors by in-degree and out-degree. What is their average score over time? At which point in time did they join the discussion on GME? When did they leave it?\n> * Plot the distribution of in-degrees and out-degrees, using a logarithmic binning (see last week's exercise 4). \n> * Plot a scatter plot of the the in- versus out- degree for all redditors. Comment on the relation between the two.\n> * Plot a scatter plot of the the in- degree versus average score for all redditors. Comment on the relation between the two.\n\n\n<b> Answers </b>\n> * The graph has a direction to indicate which users commented on which other users posts. All childs of a node becomes the users who have posted on that nodes posts\n",
"_____no_output_____"
],
[
"## Stats",
"_____no_output_____"
]
],
[
[
"# answers to question 2 and 3\nbold = \"\\033[1m\"\nend = '\\033[0m'\n\nN_nodes = len(G.nodes)\nN_links = len(G.edges)\nmax_links = N_nodes*(N_nodes-1)/2\nnetwork_density = N_links/max_links\nin_degrees = list(dict(G.in_degree()).values())\nout_degrees = list(dict(G.out_degree()).values())\n\n\nprint(bold, \"Number of nodes in the network: \", end, N_nodes)\nprint(bold, \"The total number of links: \", end, N_links)\nprint(bold, \"Max/Potentiel number of links: \", end, max_links)\nprint(bold, \"Density of the network: \", end, network_density)\n# stats for degrees\nprint(bold, \"Stats for in degree of network:\",end)\nprint(\"\\tMean = \", np.mean(in_degrees))\nprint(\"\\tMedian = \", np.median(in_degrees))\nprint(\"\\tMode = \", max(in_degrees, key = in_degrees.count))\nprint(\"\\tMin = \", min(in_degrees))\nprint(\"\\tMax = \", max(in_degrees))\nprint(bold, \"Stats for out degree of network:\",end)\nprint(\"\\tMean = \", np.mean(out_degrees))\nprint(\"\\tMedian = \", np.median(out_degrees))\nprint(\"\\tMode = \", max(out_degrees, key = out_degrees.count))\nprint(\"\\tMin = \", min(out_degrees))\nprint(\"\\tMax = \", max(out_degrees))\n\n",
"\u001b[1m Number of nodes in the network: \u001b[0m 30039\n\u001b[1m The total number of links: \u001b[0m 96518\n\u001b[1m Max/Potentiel number of links: \u001b[0m 451155741.0\n\u001b[1m Density of the network: \u001b[0m 0.0002139349923511225\n\u001b[1m Stats for in degree of network: \u001b[0m\n\tMean = 3.2130896501215087\n\tMedian = 1.0\n\tMode = 1\n\tMin = 0\n\tMax = 787\n\u001b[1m Stats for out degree of network: \u001b[0m\n\tMean = 3.2130896501215087\n\tMedian = 0.0\n\tMode = 0\n\tMin = 0\n\tMax = 2826\n"
]
],
[
[
"## Top redditors ",
"_____no_output_____"
]
],
[
[
"top = 5 #number of user to rank\n\ntop_redditors = comments.groupby([\"author\"]).agg({'score' : ['mean'], 'creation_date':['min', 'max']})\ntop_redditors.columns = [\"avg_score\", \"date_joined\", \"date_left\"]\ntop_redditors[\"days_active\"] = top_redditors[\"date_left\"] - top_redditors[\"date_joined\"]\ntop_redditors = top_redditors.join(pd.DataFrame(G.in_degree(), columns = [\"author\", \"in_degree\"]).set_index(\"author\"), how = \"left\")\ntop_redditors = top_redditors.join(pd.DataFrame(G.out_degree(), columns = [\"author\", \"out_degree\"]).set_index(\"author\"), how = \"left\")\ntop_redditors = top_redditors.reset_index()\n\ndisplay(f\"Top {top} redditors by in-degree: \", top_redditors.sort_values(\"in_degree\", ascending=False)[:top]) \ndisplay(f\"Top {top} redditors by out-degree: \", top_redditors.sort_values(\"out_degree\", ascending=False)[:top]) \n",
"_____no_output_____"
]
],
[
[
"## Plots",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(2, 2, figsize = (15,10))\n# fig.tight_layout(h_pad=5, v_pad = 3)\nfig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=.2, hspace=.3)\n\n# distribution of in degree\n# min(top_redditors.in_degree), max(top_redditors.in_degree) # 1, 787\nbins = np.logspace(0, np.log10(787), 50)\nhist, edges = np.histogram(top_redditors[\"in_degree\"], bins = bins)\nx = (edges[1:] + edges[:-1])/2.\n# remove 0 entries\nxx, yy = zip(*[(i,j) for (i,j) in zip(x, hist) if j > 0])\n\nax = plt.subplot(2,2,1)\nax.plot(xx, yy, marker = \".\")\nax.set_xlabel(\"In degree of redditors [log10]\")\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\nax.set_title(\"In degree distribution\")\n\n# distribution of out degree\n# min(top_redditors.in_degree), max(top_redditors.in_degree) # 0, 2826 - log(0) set to 0\nbins = np.logspace(0, np.log10(2826), 50)\nhist, edges = np.histogram(top_redditors[\"out_degree\"], bins = bins)\nx = (edges[1:] + edges[:-1])/2.\n# remove 0 entries\nxx, yy = zip(*[(i,j) for (i,j) in zip(x, hist) if j > 0])\n\nax = plt.subplot(2,2,2)\nax.plot(xx, yy, marker = \".\")\nax.set_xlabel(\"Out degree of redditors [log10]\")\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\nax.set_title(\"Out-degree distribution\")\n\n# scatter plot for in- versus out degree\nax = plt.subplot(2, 2, 3)\nax.scatter(top_redditors.in_degree, top_redditors.out_degree)\nax.set_xlabel(\"in-degree of redditor\")\nax.set_ylabel(\"out-degree of redditor\")\nax.set_yscale(\"log\")\nax.set_xscale(\"log\")\nax.set_title(\"In-degree vs out-degree\")\nax.set_ylim(1e-1, 1e4)\n\n\n# scatter plot for in-degree vs average score\nax = plt.subplot(2, 2, 4)\nax.scatter(top_redditors.in_degree, top_redditors.avg_score)\nax.set_xlabel(\"in-degree of redditor\")\nax.set_ylabel(\"average score of redditor\")\nax.set_title(\"In-degree vs average score\")\nax.set_yscale(\"log\")\nax.set_xscale(\"log\")\nax.set_ylim(1e-2, 1e4)\n\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"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aaee926a0b268b9d20e210552d521954dd04bf5
| 11,033 |
ipynb
|
Jupyter Notebook
|
prepare for data analysis test/sklearn20180616.ipynb
|
itwill009/TR
|
52c7c5a248a92125308705268816d07881f04918
|
[
"MIT"
] | 2 |
2018-05-23T14:27:17.000Z
|
2018-05-23T14:27:19.000Z
|
prepare for data analysis test/sklearn20180616.ipynb
|
itwill009/TL
|
52c7c5a248a92125308705268816d07881f04918
|
[
"MIT"
] | 2 |
2018-04-23T07:03:39.000Z
|
2018-04-23T07:10:38.000Z
|
prepare for data analysis test/sklearn20180616.ipynb
|
itwill009/TR
|
52c7c5a248a92125308705268816d07881f04918
|
[
"MIT"
] | null | null | null | 45.590909 | 3,067 | 0.656394 |
[
[
[
"from sklearn.datasets import load_files",
"_____no_output_____"
],
[
"reviews_train = load_files('data/aclImdb/train/')",
"_____no_output_____"
],
[
"text_train, y_train = reviews_train.data, reviews_train.target",
"_____no_output_____"
],
[
"print(type(text_train))\nprint(len(text_train))\nprint(text_train[6])",
"<class 'list'>\n75000\nb'Gloomy Sunday - Ein Lied von Liebe und Tod directed by Rolf Sch\\xc3\\xbcbel in 1999 is a romantic, absorbing, beautiful, and heartbreaking movie. It started like Jules and Jim; it ended as one of Agatha Christie\\'s books, and in between it said something about love, friendship, devotion, jealousy, war, Holocaust, dignity, and betrayal, and it did better than The Black Book which is much more popular. It is not perfect, and it made me, a cynic, wonder in the end on the complexity of the relationships and sensational revelations, and who is who to whom but the movie simply overwhelmed me. Perfect or not, it is unforgettable. All four actors as the parts of the tragic not even a triangle but a rectangle were terrific. I do believe that three men could fell deeply for one girl as beautiful and dignified as Ilona in a star-making performance by young Hungarian actress Erica Marozs\\xc3\\xa1n and who would not? The titular song is haunting, sad, and beautiful, and no doubt deserves the movie been made about it and its effect on the countless listeners. I love the movie and I am surprised that it is so little known in this country. It is a gem.<br /><br />The fact that it is based on a story of the song that had played such important role in the lives of all characters made me do some research, and the real story behind the song of Love and Death seems as fascinating as the fictional one. The song was composed in 1930s by Rezs\\xc3\\xb6 Seress and was believed to have caused many suicides in Hungary and all over Europe as the world was moving toward the most devastating War of the last century. Rezs\\xc3\\xb6 Seress, a Jewish-Hungarian pianist and composer, was thrown to the Concentration Camp but survived, unlike his mother. In January, 1968, Seress committed suicide in Budapest by jumping out of a window. According to his obituary in the New York Times, \"Mr. Seres complained that the success of \"Gloomy Sunday\" actually increased his unhappiness, because he knew he would never be able to write a second hit.\" <br /><br />Many singers from all over the world have recorded their versions of the songs in different languages. Over 70 performers have covered the song since 1935, and some famous names include Billie Holiday, Paul Robeson, Pyotr Leschenko (in Russian, under title \"Mratschnoje Woskresenje\"), Bjork, Sarah McLachlan, and many more. The one that really got to me and made me shiver is by Diamanda Gal\\xc3\\xa1s, the Greek born American singer/pianist/performer with the voice of such tragic power that I still can\\'t get over her singing. Gal\\xc3\\xa1s has been described as \"capable of the most unnerving vocal terror\", and in her work she mostly concentrates on the topics of \"suffering, despair, condemnation, injustice and loss of dignity.\" When she sings the Song of Love and Death, her voice that could\\'ve belonged to the most tragic heroines of Ancient Greece leaves no hope and brings the horror and grief of love lost forever to the unbearable and incomparable heights.<br /><br />8.5/10'\n"
],
[
"text_train = [doc.replace(b\"<br />\",b\" \") for doc in text_train]",
"_____no_output_____"
],
[
"text_train[6]",
"_____no_output_____"
],
[
"import numpy as np\n\nprint(np.bincount(y_train))",
"[12500 12500 50000]\n"
],
[
"sample = ['The fool doth think he is wise,','but the wise man knows himself to be a fool']",
"_____no_output_____"
],
[
"from sklearn.feature_extraction.text import CountVectorizer\n\nvect = CountVectorizer()\nvect.fit(sample)",
"_____no_output_____"
],
[
"print(len(vect.vocabulary_))\nprint(vect.vocabulary_)",
"13\n{'the': 9, 'fool': 3, 'doth': 2, 'think': 10, 'he': 4, 'is': 6, 'wise': 12, 'but': 1, 'man': 8, 'knows': 7, 'himself': 5, 'to': 11, 'be': 0}\n"
],
[
"bag_of_words = vect.transform(sample)\nprint(repr(bag_of_words))",
"<2x13 sparse matrix of type '<class 'numpy.int64'>'\n\twith 16 stored elements in Compressed Sparse Row format>\n"
],
[
"print(bag_of_words.toarray())",
"[[0 0 1 1 1 0 1 0 0 1 1 0 1]\n [1 1 0 1 0 1 0 1 1 1 0 1 1]]\n"
],
[
"vect = CountVectorizer().fit(text_train)\nx_train = vect.transform(text_train)\nprint(repr(x_train))",
"<75000x124255 sparse matrix of type '<class 'numpy.int64'>'\n\twith 10315542 stored elements in Compressed Sparse Row format>\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaef54aad07f9fae7e1cbe30f971038f1320e5d
| 3,660 |
ipynb
|
Jupyter Notebook
|
KCF/.ipynb_checkpoints/README-checkpoint.ipynb
|
encodingintuition/MachineLearningWorkbook
|
fb8e985475ad930c30092a0b1a27f4b8be3c7979
|
[
"MIT"
] | null | null | null |
KCF/.ipynb_checkpoints/README-checkpoint.ipynb
|
encodingintuition/MachineLearningWorkbook
|
fb8e985475ad930c30092a0b1a27f4b8be3c7979
|
[
"MIT"
] | null | null | null |
KCF/.ipynb_checkpoints/README-checkpoint.ipynb
|
encodingintuition/MachineLearningWorkbook
|
fb8e985475ad930c30092a0b1a27f4b8be3c7979
|
[
"MIT"
] | null | null | null | 19.677419 | 102 | 0.492896 |
[
[
[
"# KCF Web Analytics \n<hr/>",
"_____no_output_____"
],
[
"Time-series (line plot)\n- per day \n- per \n\nAcquisition\n- Sessions (n, percent )\n- New Session (percent )\n- New User (n, percent )\n\nBehavor\n- pageviews\n- Bounce Rate\n- Pages / Session\n- Avg. Session Duration \n\nConversions\n- Conversion Rate \n- Goal Completions \n- Goal Value \n",
"_____no_output_____"
],
[
"Main Questions:\n- How much viewing does KCF get.\n - n per time\n - year, mo, D, H, day of week, part of month, \n - quality per time\n - n per page (geographical within site architecture)\n \n- What platforms \n - moblie vs desktop \n - what does this tell us?\n - when people make time for KCF like FEELINGS -> activities\n- What social media feed the site / which pages on the site\n - list of social \n - sessions \n ",
"_____no_output_____"
],
[
"- What is the archetype of the individual who will achive your goal through their partisipation?",
"_____no_output_____"
]
],
[
[
"A visual graph of the relationship between these variables ",
"_____no_output_____"
]
],
[
[
"#### Goals\n- Goal 1 \n - Angel donation (fund us)\n- Goal 2 \n - large private donation (fund us)\n- Goal 3 \n - spead the word (share our vibe)",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"This is a look at the anlytics for KCF ",
"_____no_output_____"
],
[
"Primary Dimension, Secondary Dimension\n\n",
"_____no_output_____"
],
[
"Main - Dashboard \n- Pageviews website in total (vs page value) - Behavior\n- pageviews per page \n\n",
"_____no_output_____"
]
],
[
[
"landing Page\n(bridge page)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
4aaef80d7af5a9b4577198f2d021ec5094bb6247
| 27,481 |
ipynb
|
Jupyter Notebook
|
Corona.ipynb
|
ayushman17/COVID-19-Detector
|
940b2f4ade2cde98f35b634e8861f9d5557c223b
|
[
"MIT"
] | 2 |
2020-05-14T22:18:26.000Z
|
2020-05-20T13:04:35.000Z
|
Corona.ipynb
|
ayushman17/COVID-19-Detector
|
940b2f4ade2cde98f35b634e8861f9d5557c223b
|
[
"MIT"
] | null | null | null |
Corona.ipynb
|
ayushman17/COVID-19-Detector
|
940b2f4ade2cde98f35b634e8861f9d5557c223b
|
[
"MIT"
] | null | null | null | 27.842958 | 216 | 0.337943 |
[
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"## Reading Data",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('data.csv')",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 2999 entries, 0 to 2998\nData columns (total 6 columns):\nfever 2999 non-null float64\nbodyPain 2999 non-null int64\nage 2999 non-null int64\nrunnyNose 2999 non-null int64\ndiffBreath 2999 non-null int64\ninfectionProb 2999 non-null int64\ndtypes: float64(1), int64(5)\nmemory usage: 140.7 KB\n"
],
[
"df['fever'].value_counts()",
"_____no_output_____"
],
[
"df['diffBreath'].value_counts()",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"## Train Test Splitting",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"def data_split(data, ratio):\n np.random.seed(42)\n shuffled = np.random.permutation(len(data))\n test_set_size = int(len(data) * ratio)\n test_indices = shuffled[:test_set_size]\n train_indices = shuffled[test_set_size:]\n return data.iloc[train_indices], data.iloc[test_indices]",
"_____no_output_____"
],
[
"np.random.permutation(7)",
"_____no_output_____"
],
[
"train, test = data_split(df, 0.2)",
"_____no_output_____"
],
[
"train",
"_____no_output_____"
],
[
"test",
"_____no_output_____"
],
[
"X_train = train[['fever', 'bodyPain', 'age', 'runnyNose', 'diffBreath']].to_numpy()\nX_test = test[['fever', 'bodyPain', 'age', 'runnyNose', 'diffBreath']].to_numpy()",
"_____no_output_____"
],
[
"Y_train = train[['infectionProb']].to_numpy().reshape(2400,)\nY_test = test[['infectionProb']].to_numpy().reshape(599,)",
"_____no_output_____"
],
[
"Y_train",
"_____no_output_____"
],
[
"from sklearn.linear_model import LogisticRegression",
"_____no_output_____"
],
[
"clf = LogisticRegression()\nclf.fit(X_train, Y_train)",
"C:\\Users\\Ayushman singh\\Anaconda3\\lib\\site-packages\\sklearn\\linear_model\\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n FutureWarning)\n"
],
[
"inputFeatures = [101, 1, 22, -1, 1]\ninfProb =clf.predict_proba([inputFeatures])[0][1]",
"_____no_output_____"
],
[
"infProb",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaefe3a61445717d9f8ddc8d677f6ff95f634ca
| 10,897 |
ipynb
|
Jupyter Notebook
|
28Octubre.ipynb
|
ibzan79/daa_2021_1
|
74585f5d2e0a742d63ea102f3d776dfe388daa9f
|
[
"MIT"
] | null | null | null |
28Octubre.ipynb
|
ibzan79/daa_2021_1
|
74585f5d2e0a742d63ea102f3d776dfe388daa9f
|
[
"MIT"
] | null | null | null |
28Octubre.ipynb
|
ibzan79/daa_2021_1
|
74585f5d2e0a742d63ea102f3d776dfe388daa9f
|
[
"MIT"
] | null | null | null | 27.65736 | 226 | 0.358447 |
[
[
[
"<a href=\"https://colab.research.google.com/github/ibzan79/daa_2021_1/blob/master/28Octubre.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"h1 = 0\nh2 = 0\nm1 = 0\nm2 = 0 # 1440 + 24 *6\ncontador = 0 # 5 + (1440 + ?) * 2 + 144 + 24 + 2= 3057\noperaciones = 5\n\nwhile [h1, h2, m1, m2] != [2,3,5,9]:\n if [h1, h2] == [m2, m1]:\n \n print(h1, h2,\":\", m1, m2) \n m2 = m2 + 1\n operaciones += 1\n\n if m2 == 10:\n m2 = 0\n m1 = m1 + 1\n operaciones += 2\n\n if m1 == 6:\n h2 = h2 + 1\n m2 = 0\n operaciones += 2\n contador = contador + 1\n operaciones += 1\n\n m2 = m2 + 1\n operaciones += 1\n if m2 == 10:\n m2 = 0\n m1 = m1 + 1\n operaciones += 2\n if m1 == 6:\n m1 = 0\n h2 = h2 +1\n operaciones += 2\n if h2 == 10:\n h2 = 0\n h1 = h1 +1\n operaciones += 2\nprint(\"Numero de palindromos: \",contador)\nprint(f\"Operaciones: {operaciones}\")",
"0 0 : 0 0\n0 1 : 1 0\n0 2 : 2 0\n0 3 : 3 0\n0 4 : 4 0\n0 5 : 5 0\n1 0 : 0 1\n1 1 : 1 1\n1 2 : 2 1\n1 3 : 3 1\n1 4 : 4 1\n1 5 : 5 1\n2 0 : 0 2\n2 1 : 1 2\n2 2 : 2 2\n2 3 : 3 2\nNumero de palindromos: 16\nOperaciones: 1796\n"
],
[
"horario=\"0000\"\ncontador=0\noperaciones = 2\nwhile horario!=\"2359\":\n inv=horario[::-1]\n if horario==inv:\n contador+=1\n operaciones += 1\n print(horario[0:2],\":\",horario[2:4])\n new=int(horario)\n new+=1\n horario=str(new).zfill(4)\n operaciones += 4\nprint(\"son \",contador,\"palindromos\")\nprint(f\"Operaciones: {operaciones}\")\n# 2 + (2360 * 4 ) + 24",
"00 : 00\n01 : 10\n02 : 20\n03 : 30\n04 : 40\n05 : 50\n06 : 60\n07 : 70\n08 : 80\n09 : 90\n10 : 01\n11 : 11\n12 : 21\n13 : 31\n14 : 41\n15 : 51\n16 : 61\n17 : 71\n18 : 81\n19 : 91\n20 : 02\n21 : 12\n22 : 22\n23 : 32\nson 24 palindromos\nOperaciones: 9462\n"
],
[
"lista=[]\nfor i in range(0,24,1): # 24\n for j in range(0,60,1): # 60 1440\n if i<10:\n if j<10:\n lista.append(\"0\"+str(i)+\":\"+\"0\"+str(j))\n elif j>=10:\n lista.append(\"0\"+str(i)+\":\"+str(j))\n else:\n if i>=10:\n if j<10:\n lista.append(str(i)+\":\"+\"0\"+str(j))\n elif j>=10:\n lista.append(str(i)+\":\"+str(j))\n# 1440 + 2 + 1440 + 16 * 2 = 2900\nlista2=[]\ncontador=0\nfor i in range(len(lista)): # 1440\n x=lista[i][::-1]\n if x==lista[i]:\n lista2.append(x)\n contador=contador+1\nprint(contador)\nfor j in (lista2):\n print(j)",
"16\n00:00\n01:10\n02:20\n03:30\n04:40\n05:50\n10:01\n11:11\n12:21\n13:31\n14:41\n15:51\n20:02\n21:12\n22:22\n23:32\n"
],
[
"for x in range (0,24,1):\n for y in range(0,60,1): #1440 * 3 +13 = 4333\n hora=str(x)+\":\"+str(y)\n if x<10:\n hora=\"0\"+str(x)+\":\"+str(y)\n if y<10:\n hora=str(x)+\"0\"+\":\"+str(y)\n\n p=hora[::-1]\n if p==hora:\n print(f\"{hora} es palindromo\")",
"01:10 es palindromo\n02:20 es palindromo\n03:30 es palindromo\n04:40 es palindromo\n05:50 es palindromo\n11:11 es palindromo\n12:21 es palindromo\n13:31 es palindromo\n14:41 es palindromo\n15:51 es palindromo\n21:12 es palindromo\n22:22 es palindromo\n23:32 es palindromo\n"
],
[
"#solucion:\ntotal = int(0) #Contador de numero de palindromos\nfor hor in range(0,24): #Bucles anidados for para dar aumentar las horas y los minutos al mismo tiempo\n for min in range(0,60): \n\n hor_n = str(hor) #Variables\n min_n = str(min)\n\n if (hor<10): #USamos condiciones para que las horas y los minutos no rebasen el horario\n hor_n = (\"0\"+hor_n)\n\n if (min<10):\n min_n = (\"0\"+ min_n)\n\n if (hor_n[::-1] == min_n): #Mediante un slicing le damos el formato a las horas para que este empiece desde la derecha\n print(\"{}:{}\".format(hor_n,min_n))\n total += 1\n#1 + 1440 * 5 =7201",
"00:00\n01:10\n02:20\n03:30\n04:40\n05:50\n10:01\n11:11\n12:21\n13:31\n14:41\n15:51\n20:02\n21:12\n22:22\n23:32\n"
],
[
"palindronum= int(0)\nfor hor in range(0,24):\n for min in range(0,60): # 1440\n principio= str(hor)\n final= str(min)\n if (hor<10):\n principio=(\"0\"+principio)\n if (min<10):\n final=(\"0\"+final)\n if (principio[::-1]==final):\n print(principio +\":\"+final)\n palindronum= palindronum+1\nprint(palindronum)\n# 1 + 1440 * 5 = 7201",
"00:00\n01:10\n02:20\n03:30\n04:40\n05:50\n10:01\n11:11\n12:21\n13:31\n14:41\n15:51\n20:02\n21:12\n22:22\n23:32\n16\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaf06cede1ebdbe1a79072e5eede4a77d16d8af
| 6,640 |
ipynb
|
Jupyter Notebook
|
lab02/ix-lab2/notebooks/ix-lab2-notebook-part2.ipynb
|
Battleman/InternetAnalyticsW
|
005e5de6c0e591be6dc303ec46cc82249e70f666
|
[
"MIT"
] | null | null | null |
lab02/ix-lab2/notebooks/ix-lab2-notebook-part2.ipynb
|
Battleman/InternetAnalyticsW
|
005e5de6c0e591be6dc303ec46cc82249e70f666
|
[
"MIT"
] | null | null | null |
lab02/ix-lab2/notebooks/ix-lab2-notebook-part2.ipynb
|
Battleman/InternetAnalyticsW
|
005e5de6c0e591be6dc303ec46cc82249e70f666
|
[
"MIT"
] | null | null | null | 36.888889 | 482 | 0.583283 |
[
[
[
"# Networks: structure, evolution & processes\n**Internet Analytics - Lab 2**\n\n---\n\n**Group:** W\n\n**Names:**\n\n* Olivier Cloux\n* Thibault Urien\n* Saskia Reiss\n\n---\n\n#### Instructions\n\n*This is a template for part 2 of the lab. Clearly write your answers, comments and interpretations in Markodown cells. Don't forget that you can add $\\LaTeX$ equations in these cells. Feel free to add or remove any cell.*\n\n*Please properly comment your code. Code readability will be considered for grading. To avoid long cells of codes in the notebook, you can also embed long python functions and classes in a separate module. Don’t forget to hand in your module if that is the case. In multiple exercises, you are required to come up with your own method to solve various problems. Be creative and clearly motivate and explain your methods. Creativity and clarity will be considered for grading.*",
"_____no_output_____"
],
[
"---\n\n## 2.2 Network sampling\n\n#### Exercise 2.7: Random walk on the Facebook network",
"_____no_output_____"
]
],
[
[
"import requests\nimport random\nimport numpy as np\nURL_TEMPLATE = 'http://iccluster118.iccluster.epfl.ch:{p}/v1.0/facebook?user={user_id}';\n\ndef json_format(uid):\n port = 5050\n url = URL_TEMPLATE.format(user_id=uid, p=port)\n response = requests.get(url)\n return response.json()",
"_____no_output_____"
],
[
"def crawler(maximum, TP_prob, seed):\n \"\"\"Crawls facebook from a seed node.\n \n Keyword arguments:\n maximum -- numberof nodes to crawl\n TP_prob -- probability to keep crawling.\n seed -- first node\n \n Crawls Facebook users to find age of users. With probability TP_prob, crawler keeps going\n from user to user. Otherwise, it jumps to a random node, that was already seen (friend of a visited node)\n but not yet visited.\n \n return a table containing the ages of visited nodes\n \"\"\"\n #quick check of parameters\n if(maximum < 1 or TP_prob < 0 or TP_prob > 1 or not isinstance(seed, str)):\n print(\"Error, bad parameter\")\n return [-1]\n #needed global variables\n vis = set() #keep track of visited nodes\n age = [] #list of ages, to be returned\n buffer_max = 100;\n buffer = set([]) #buffer of nodes to visit when TP\n user_id = seed #UID of starting node\n i = 0\n while i < maximum:\n data = json_format(user_id)\n #retrieve list of friends not yet visited\n friends_list = set(data['friends']).difference(vis)\n \n age.append(data['age'])\n \n #creates buffer of possible nodes to teleport to.\n #each node adds few of its friends. \n if(len(buffer) > buffer_max): #If buffer full, remove 10 random and add 10 new.\n to_remove = random.sample(buffer, 10)\n buffer = buffer.difference(to_remove)\n #take at most 10 friends uid from current node.\n some_random_friends = random.sample(friends_list, min(len(friends_list), 10))\n buffer = buffer.union(set(some_random_friends))\n buffer.discard(user_id) #ensure current uid not in buffer, to avoid duplicate visit\n \n #actual crawling. Teleport if current node has no friend or \n #if given probability was met, otherwise keep crawling\n if(random.randrange(0, 1) < theta and (len(friends_list) is not 0)): #continue crawling\n user_id = random.sample(friends_list, 1).pop()\n else: #Teleport to random node in the buffer\n user_id = random.sample(buffer, 1).pop() \n vis.add(user_id)\n i += 1\n return age",
"_____no_output_____"
],
[
"N = 5000;\nseed = 'f30ff3966f16ed62f5165a229a19b319'\ntheta = 0.85 #random jump with prob 0.15\nage = crawler(N, theta, seed)\nprint('The mean age is',np.mean(age))",
"_____no_output_____"
]
],
[
[
"#### Exercise 2.8",
"_____no_output_____"
],
[
"We obtain a mean age of about 20-22 (small variations depending on the theta of random teleport and the randomness of jumps). The real mean age being 43, we see a huge variation. \n\nThis can be explained with the *friendship paradox*. Young people have more (young) friends (so the younger population is more connected than their elders), and older people have fewer friends. Also, we can imagine older people have a majority of younger facebook friends because with friends of same age, they may prefer using other mediums to keep contact. Older people represents dead ends, with few and young friends. The crawler will so find young nodes more easily. \n\nA solution to that would be to ponderate the nodes, according to the number of friends. An other possibility would be to select more easily nodes with few friends ; that is, when chosing a node, pick with higher probability the ones with few friends.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4aaf0b2e5511684ebe396946f07d15873b1000b0
| 3,293 |
ipynb
|
Jupyter Notebook
|
python/setup.ipynb
|
zhongqi1112/Hulk
|
9e7e65368b8091068755ebf70c1e28ee883a480d
|
[
"MIT"
] | null | null | null |
python/setup.ipynb
|
zhongqi1112/Hulk
|
9e7e65368b8091068755ebf70c1e28ee883a480d
|
[
"MIT"
] | null | null | null |
python/setup.ipynb
|
zhongqi1112/Hulk
|
9e7e65368b8091068755ebf70c1e28ee883a480d
|
[
"MIT"
] | null | null | null | 21.383117 | 145 | 0.526875 |
[
[
[
"# Setup Environment",
"_____no_output_____"
],
[
"## Python",
"_____no_output_____"
],
[
"```\n# python version\npython -V\npython3 -V\npip -V\n\n# update pip\npip install -U pip\npython3 -m pip install -U pip\n# list installed packages\npip list\n```",
"_____no_output_____"
],
[
"## Anaconda",
"_____no_output_____"
],
[
"```\n# conda information\nconda info \n# update conda\nconda update -n base -c defaults conda\nconda update --all\n# see path of conda environment\nconda info --envs\n# remove environment\nconda env remove -n <environment_name>\n# list installed packages\nconda list\n```",
"_____no_output_____"
],
[
"## Environment",
"_____no_output_____"
],
[
"### Create an environment by YAML\n\n```\nconda env create -f env.yml\n# activate environment\nconda activate env_name\n```",
"_____no_output_____"
],
[
"### Create an environment by txt\n\n```\nconda create --name env_name python=3.8\n# activate environment\nconda activate env_name\n# install libraries required:\npip install -r requirements.txt\n# checking libraries installed\npip freeze\n```",
"_____no_output_____"
],
[
"## PyCharm",
"_____no_output_____"
],
[
"### setup Interpreter\n* PyCharm -> Preferences -> Project: Name -> Project Interpreter -> Gear Icon -> Add -> Conda Environment -> Existing environment -> ...\n* check environment path by: `conda info --envs`\n* select environment path followed by `bin/python`, for example\n `/Users/zq/opt/anaconda3/envs/rait_env/bin/python`\n* select checkbox \"Make available to all projects\"\n* apply the changes\n\nRef: https://www.youtube.com/watch?v=yQo1kb0_8EI",
"_____no_output_____"
],
[
"### Add configuration\nadd configuration -> + icon\n* Script path: the python file will be compiled\n* Python interpreter: the interpreter is created",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4aaf1e980bc0a53bd6e61b5a39d455227f38d80d
| 38,898 |
ipynb
|
Jupyter Notebook
|
1_machine_learning_foundation/week1/Getting Started With SFrames.ipynb
|
phattp/machine-learning-university-of-washington
|
afdb09b54ca9d80115bba36f26bb84961c1159d4
|
[
"MIT"
] | null | null | null |
1_machine_learning_foundation/week1/Getting Started With SFrames.ipynb
|
phattp/machine-learning-university-of-washington
|
afdb09b54ca9d80115bba36f26bb84961c1159d4
|
[
"MIT"
] | null | null | null |
1_machine_learning_foundation/week1/Getting Started With SFrames.ipynb
|
phattp/machine-learning-university-of-washington
|
afdb09b54ca9d80115bba36f26bb84961c1159d4
|
[
"MIT"
] | null | null | null | 40.773585 | 155 | 0.50725 |
[
[
[
"# Fire up GraphLab Create",
"_____no_output_____"
]
],
[
[
"import graphlab",
"_____no_output_____"
]
],
[
[
"# Load a tabular data set",
"_____no_output_____"
]
],
[
[
"sf = graphlab.SFrame('people-example.csv')",
"This non-commercial license of GraphLab Create for academic use is assigned to [email protected] and will expire on November 01, 2019.\n"
]
],
[
[
"# SFrame basics",
"_____no_output_____"
]
],
[
[
"sf #we can view fist few line of table",
"_____no_output_____"
],
[
"sf.head()",
"_____no_output_____"
],
[
"sf.tail()",
"_____no_output_____"
]
],
[
[
"# GraphLab Canvas",
"_____no_output_____"
]
],
[
[
"graphlab.canvas.set_target('browser', 8888)",
"_____no_output_____"
],
[
"graphlab.canvas.set_target('ipynb')",
"_____no_output_____"
],
[
"sf['age'].show(view='Categorical')",
"_____no_output_____"
]
],
[
[
"# Inspect columns of dataset",
"_____no_output_____"
]
],
[
[
"sf['Country']",
"_____no_output_____"
],
[
"sf['age']",
"_____no_output_____"
],
[
"sf['age'].mean()",
"_____no_output_____"
],
[
"sf['age'].max()",
"_____no_output_____"
]
],
[
[
"# Create new columns in out SFrame",
"_____no_output_____"
]
],
[
[
"sf",
"_____no_output_____"
],
[
"sf['Full Name'] = sf['First Name'] + ' ' + sf['Last Name']",
"_____no_output_____"
],
[
"sf",
"_____no_output_____"
],
[
"sf['age'] + sf['age']",
"_____no_output_____"
]
],
[
[
"# Use the apply function to do a advance transformation of our data",
"_____no_output_____"
]
],
[
[
"sf['Country']",
"_____no_output_____"
],
[
"sf['Country'].show()",
"_____no_output_____"
],
[
"def transform_country(country):\n if country == 'USA':\n return 'United States'\n else:\n return country",
"_____no_output_____"
],
[
"transform_country('Brazil')",
"_____no_output_____"
],
[
"transform_country('Brasil')",
"_____no_output_____"
],
[
"transform_country('USA')",
"_____no_output_____"
],
[
"sf['Country'].apply(transform_country)",
"_____no_output_____"
],
[
"sf['Country'] = sf['Country'].apply(transform_country)",
"_____no_output_____"
],
[
"sf['Country']",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaf284158aadd8917be005920bcf0c436fc98dd
| 12,548 |
ipynb
|
Jupyter Notebook
|
ExtracionDeInfo.ipynb
|
Howl24/Lineup-Prediction
|
9b890a52a444010a6a07de807426305fae5a4058
|
[
"MIT"
] | null | null | null |
ExtracionDeInfo.ipynb
|
Howl24/Lineup-Prediction
|
9b890a52a444010a6a07de807426305fae5a4058
|
[
"MIT"
] | null | null | null |
ExtracionDeInfo.ipynb
|
Howl24/Lineup-Prediction
|
9b890a52a444010a6a07de807426305fae5a4058
|
[
"MIT"
] | null | null | null | 32.174359 | 135 | 0.528451 |
[
[
[
"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nURLPRI = \"http://www.losmundialesdefutbol.com\"\nurl = \"http://www.losmundialesdefutbol.com/mundiales.php\"",
"_____no_output_____"
],
[
"def returnWebObject(url):\n return BeautifulSoup(urlopen(url) , \"lxml\")",
"_____no_output_____"
],
[
"class Player:\n def __init__(self, name ,position, wasCaptain):\n self.name = name\n self.position = position\n self.wasCaptain = False\n def __str__(self):\n return self.name\n def __repr__(self):\n return self.name",
"_____no_output_____"
],
[
"class Team:\n def __init__(self , name , goal ):\n self.name = name\n self.goal = goal\n self.formation = None\n self.players = list()\n def getStringFromFormation(self):\n # Example 4-4-2\n pass",
"_____no_output_____"
],
[
"class Match:\n def __init__(self , firstTeam , secondTeam ,goals ,info):\n self.firstTeam = Team(firstTeam , goals[0])\n self.secondTeam = Team(secondTeam , goals[1])\n self.info = info",
"_____no_output_____"
],
[
"\nclass WorldCup:\n def __init__(self , year , location , champion) :\n self.champion = champion\n self.location = location\n self.year = year\n self.countries = set()\n self.matches = list()\n def __str__(self):\n return \"Copa del mundo del \" + str(self.year) + \" /Campeon \" + self.champion + \"/Lugar: \" + self.location \n def __repr__(self):\n return \"Copa del mundo del \" + str(self.year) + \" /Campeon \" + self.champion + \"/Lugar: \" + self.location ",
"_____no_output_____"
],
[
"pageListWorldSoccerCups = returnWebObject(URLPRI)\nlistWorldCups = list()\ntableWordChampions = pageListWorldSoccerCups.find(\"div\", {\"class\": \"rd-100-40 rd-pad-0-l2\"})\nfor x in tableWordChampions.find_all(\"tr\"):\n if x.find(\"div\", {\"class\" : \"left\" , \"style\":\"width: 50% ; min-width: 100px\"}):\n auxSplit = x.text.split()\n listWorldCups.append(WorldCup(int(auxSplit[0]) , auxSplit[1] ,auxSplit[2]))\nlistWorldCups = listWorldCups[::-1]\nlistWorldCups",
"_____no_output_____"
],
[
"pageListWorldSoccerCups = returnWebObject(url)",
"_____no_output_____"
],
[
"linksResultsWorlCupsMatches = []\nfor link in pageListWorldSoccerCups.findAll(\"a\",href=True):\n if \"resultados\" in link[\"href\"]:\n linksResultsWorlCupsMatches.append(link[\"href\"])\nlinksResultsWorlCupsMatches",
"_____no_output_____"
],
[
"webPages = list()\nfor links in linksResultsWorlCupsMatches:\n webPages.append(returnWebObject(URLPRI+\"/\"+links))\n",
"_____no_output_____"
],
[
"def getGoals(result):\n goals = result.split(\"-\")\n return int(goals[0]),int(goals[1])\ndef cleanWords(firsWord , secondWord = None):\n if secondWord == None :\n return firsWord .strip()\n else:\n return firsWord.strip() , secondWord.strip()",
"_____no_output_____"
],
[
"for i , worldCup in enumerate(webPages): \n for row in worldCup.findAll(\"div\",{\"class\": \"margen-t3 clearfix\"}): # Una linea de la pagina \n infoMatch = row.find(\"div\",{\"class\":\"game margen-b3 clearfix\"})\n firstTeam = infoMatch.find(\"div\",{\"class\":\"left margen-b1 clearfix\"})\n secondTeam = infoMatch.find(\"div\",{\"class\": \"left a-left margen-b1 clearfix\"})\n firstTeam , secondTeam = cleanWords(firstTeam.text , secondTeam.text) \n listWorldCups[i].countries.add(secondTeam)\n listWorldCups[i].countries.add(firstTeam)\n if i != 0:\n for result in infoMatch.find(\"div\",{\"class\" : \"left a-center margen-b3 clearfix\"}).findAll(\"a\",href=True):\n continue\n listWorldCups[i].matches.append(Match(firstTeam , secondTeam , getGoals(result.text), result[\"href\"]))\n else :\n listWorldCups[i].matches.append(Match(firstTeam , secondTeam , (0,0), \"\"))\n",
"_____no_output_____"
],
[
"listWorldCups = listWorldCups[1:] # No se esta considerando el mundial del 2018",
"_____no_output_____"
],
[
"def getLinkForMatch(info):\n #con esto obtenemos los links necesarios \n if \"..\" in info:\n return URLPRI + info[2:]\n else :\n return URLPRI + info",
"_____no_output_____"
],
[
"def getPlayerInfo(row):\n name = \"\"\n wasCapitan = False\n pos = cleanWords(str(row.find(\"td\").text))\n for x in row.find(\"div\",{\"style\":\"float: left ; \"}).text.split():\n if x == \"(C)\":\n wasCapitan = True\n else:\n name = x + \" \" + name\n return Player(name, pos , wasCapitan)",
"_____no_output_____"
],
[
"for worldCups in listWorldCups[0:1]:\n for match in worldCups.matches[0:1]:\n contain = returnWebObject(getLinkForMatch(match.info))\n firstTable = contain.find(\"div\",{\"class\":\"rd-100-50 rd-pad-0-r2\"})\n formation = dict()\n for i , row in enumerate(firstTable.findAll(\"tr\",{\"style\":\"vertical-align: top\"})):\n if i > 10:\n break\n player = getPlayerInfo(row)\n try:\n formation[player.position] = formation[player.position] +1\n except:\n formation[player.position] = 1\n match.firstTeam.players.append(player)\n match.firstTeam.formation = formation\n secondTable = contain.find(\"div\",{\"class\":\"rd-100-50 rd-pad-0-l2\"})\n formation = dict()\n for i , row in enumerate(secondTable.findAll(\"tr\",{\"style\":\"vertical-align: top\"})):\n if i > 10:\n break\n player = getPlayerInfo(row)\n try:\n formation[player.position] = formation[player.position] +1\n except:\n formation[player.position] = 1\n match.secondTeam.players.append(player)\n match.secondTeam.formation = formation\n \n ",
"_____no_output_____"
],
[
"listWorldCups[0].matches[0].secondTeam.players = list()\nlistWorldCups[0].matches[1].firstTeam.players = list()",
"_____no_output_____"
],
[
"listWorldCups[0].matches[0].secondTeam.players",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaf351e160e7e7949b39d8e81321654f985c94c
| 13,460 |
ipynb
|
Jupyter Notebook
|
examples/training/random_forest/example_allstate.ipynb
|
IBM/snapml-examples
|
6e7c61f1fd30d5f896371da2d3bbea173f968135
|
[
"Apache-2.0"
] | 6 |
2021-10-05T16:31:08.000Z
|
2022-02-25T06:07:05.000Z
|
examples/training/random_forest/example_allstate.ipynb
|
IBM/snapml-examples
|
6e7c61f1fd30d5f896371da2d3bbea173f968135
|
[
"Apache-2.0"
] | 1 |
2021-02-25T22:47:15.000Z
|
2021-02-26T20:26:41.000Z
|
examples/training/random_forest/example_allstate.ipynb
|
IBM/snapml-examples
|
6e7c61f1fd30d5f896371da2d3bbea173f968135
|
[
"Apache-2.0"
] | 6 |
2021-05-07T17:03:04.000Z
|
2022-01-12T16:56:02.000Z
| 29.911111 | 213 | 0.580015 |
[
[
[
"```\nCopyright 2021 IBM Corporation\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 http://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.\n```",
"_____no_output_____"
],
[
"# Random Forest on Allstate Dataset\n\n## Background \n\nThe goal of this competition is to predict Bodily Injury Liability Insurance claim payments based on the characteristics of the insured’s vehicle. \n\n## Source\n\nThe raw dataset can be obtained directly from the [Allstate Claim Prediction Challenge](https://www.kaggle.com/c/ClaimPredictionChallenge).\n\nIn this example, we download the dataset directly from Kaggle using their API. In order for to work work, you must:\n1. Login into Kaggle and accept the [competition rules](https://www.kaggle.com/c/ClaimPredictionChallenge/rules).\n2. Folow [these instructions](https://www.kaggle.com/docs/api) to install your API token on your machine.\n\n## Goal\nThe goal of this notebook is to illustrate how Snap ML can accelerate training of a random forest model on this dataset.\n\n## Code",
"_____no_output_____"
]
],
[
[
"cd ../../",
"/localhome/tpa/snapml-examples/examples\n"
],
[
"CACHE_DIR='cache-dir'",
"_____no_output_____"
],
[
"import numpy as np\nimport time\nfrom datasets import Allstate\nfrom sklearn.ensemble import RandomForestClassifier\nfrom snapml import RandomForestClassifier as SnapRandomForestClassifier\nfrom sklearn.metrics import roc_auc_score as score",
"_____no_output_____"
],
[
"dataset = Allstate(cache_dir=CACHE_DIR)\nX_train, X_test, y_train, y_test = dataset.get_train_test_split()",
"Reading binary Allstate dataset (cache) from disk.\n"
],
[
"print(\"Number of examples: %d\" % (X_train.shape[0]))\nprint(\"Number of features: %d\" % (X_train.shape[1]))\nprint(\"Number of classes: %d\" % (len(np.unique(y_train))))",
"Number of examples: 9229003\nNumber of features: 87\n"
],
[
"# the dataset is highly imbalanced\nlabels, sizes = np.unique(y_train, return_counts=True)\nprint(\"%6.2f %% of the training transactions belong to class 0\" % (sizes[0]*100.0/(sizes[0]+sizes[1])))\nprint(\"%6.2f %% of the training transactions belong to class 1\" % (sizes[1]*100.0/(sizes[0]+sizes[1])))\n\nfrom sklearn.utils.class_weight import compute_sample_weight\nw_train = compute_sample_weight('balanced', y_train)\nw_test = compute_sample_weight('balanced', y_test)",
" 99.27 % of the training transactions belong to class 0\n 0.73 % of the training transactions belong to class 1\n"
],
[
"model = RandomForestClassifier(max_depth=6, n_estimators=100, n_jobs=4, random_state=42)\nt0 = time.time()\nmodel.fit(X_train, y_train, sample_weight=w_train)\nt_fit_sklearn = time.time()-t0\nscore_sklearn = score(y_test, model.predict_proba(X_test)[:,1], sample_weight=w_test)\nprint(\"Training time (sklearn): %6.2f seconds\" % (t_fit_sklearn))\nprint(\"ROC AUC score (sklearn): %.4f\" % (score_sklearn))",
"Training time (sklearn): 570.29 seconds\nROC AUC score (sklearn): 0.5980\n"
],
[
"model = SnapRandomForestClassifier(max_depth=6, n_estimators=100, n_jobs=4, random_state=42, use_histograms=True)\nt0 = time.time()\nmodel.fit(X_train, y_train, sample_weight=w_train)\nt_fit_snapml = time.time()-t0\nscore_snapml = score(y_test, model.predict_proba(X_test)[:,1], sample_weight=w_test)\nprint(\"Training time (snapml): %6.2f seconds\" % (t_fit_snapml))\nprint(\"ROC AUC score (snapml): %.4f\" % (score_snapml))",
"Training time (snapml): 209.51 seconds\nROC AUC score (snapml): 0.5977\n"
],
[
"speed_up = t_fit_sklearn/t_fit_snapml\nscore_diff = (score_snapml-score_sklearn)/score_sklearn\nprint(\"Speed-up: %.1f x\" % (speed_up))\nprint(\"Relative diff. in score: %.4f\" % (score_diff))",
"Speed-up: 2.7 x\nRelative diff. in score: -0.0006\n"
]
],
[
[
"## Disclaimer\n\nPerformance results always depend on the hardware and software environment. \n\nInformation regarding the environment that was used to run this notebook are provided below:",
"_____no_output_____"
]
],
[
[
"import utils\nenvironment = utils.get_environment()\nfor k,v in environment.items():\n print(\"%15s: %s\" % (k, v))",
" platform: Linux-4.15.0-151-generic-x86_64-with-glibc2.10\n cpu_count: 40\n cpu_freq_min: 800.0\n cpu_freq_max: 2101.0\n total_memory: 250.58893203735352\n snapml_version: 1.8.1\nsklearn_version: 1.0.1\nxgboost_version: 1.3.3\nlightgbm_version: 3.1.1\n"
]
],
[
[
"## Record Statistics\n\nFinally, we record the enviroment and performance statistics for analysis outside of this standalone notebook.",
"_____no_output_____"
]
],
[
[
"import scrapbook as sb\nsb.glue(\"result\", {\n 'dataset': dataset.name,\n 'n_examples_train': X_train.shape[0],\n 'n_examples_test': X_test.shape[0],\n 'n_features': X_train.shape[1],\n 'n_classes': len(np.unique(y_train)),\n 'model': type(model).__name__,\n 'score': score.__name__,\n 't_fit_sklearn': t_fit_sklearn,\n 'score_sklearn': score_sklearn,\n 't_fit_snapml': t_fit_snapml,\n 'score_snapml': score_snapml,\n 'score_diff': score_diff,\n 'speed_up': speed_up,\n **environment,\n})",
"/localhome/tpa/anaconda3/envs/snapenv/lib/python3.8/site-packages/papermill/iorw.py:50: FutureWarning: pyarrow.HadoopFileSystem is deprecated as of 2.0.0, please use pyarrow.fs.HadoopFileSystem instead.\n from pyarrow import HadoopFileSystem\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aaf38590258e1080743ec5427e34b07ef09279f
| 12,333 |
ipynb
|
Jupyter Notebook
|
NotebookConstruction.ipynb
|
willeppy/lux-logger
|
7418e6f03df22e59743ad4a810b169b1ba0a35b5
|
[
"Apache-2.0"
] | null | null | null |
NotebookConstruction.ipynb
|
willeppy/lux-logger
|
7418e6f03df22e59743ad4a810b169b1ba0a35b5
|
[
"Apache-2.0"
] | null | null | null |
NotebookConstruction.ipynb
|
willeppy/lux-logger
|
7418e6f03df22e59743ad4a810b169b1ba0a35b5
|
[
"Apache-2.0"
] | 2 |
2020-09-30T23:49:40.000Z
|
2021-02-11T23:09:58.000Z
| 36.705357 | 112 | 0.465823 |
[
[
[
"import nbformat as nbf\nimport glob\nimport json\nimport pandas as pd",
"_____no_output_____"
],
[
"all_logs = glob.glob(\"../logs/*.json\")\n\n# formats all logs properly \n# key = session ID\n# value = json w/ same format as what was originally held in nb metadata\nformatted_logs = {}\n\nfor log in all_logs:\n f = open(log, 'r')\n \n # merges body sent from various HTTP Posts\n entries = f.read().split('}{')\n for i in range(len(entries)):\n entries[i] = '{' + entries[i] + '}'\n entries[0] = entries[0][1:]\n entries[-1] = entries[-1][:-1]\n formatted_log = json.loads(entries[0])\n for i in range(1,len(entries)):\n j = json.loads(entries[i])\n history = j['history']\n formatted_log['history'].extend(history)\n \n # get time user started ipynb\n formatted_log['startTime'] = formatted_log['history'][0]['time']\n formatted_log['endTime'] = formatted_log['history'][len(formatted_log['history'])-1]['time']\n \n # separates user hash from file name (sessionID)\n names = log.split('_')\n formatted_log['userHash'] = names[0][5:]\n \n # excluding Jerry and Doris and potentially others\n exclude_list = ['bca87887a1cc89312f7d073fd007ea68', '1a735d0ee6a6f9d7fdab573b50851da7']\n if names[0][5:] not in exclude_list:\n formatted_logs[names[1][:-5]] = formatted_log\n",
"_____no_output_____"
],
[
"df = pd.DataFrame(formatted_logs).transpose().sort_values('userHash')\ndf",
"_____no_output_____"
],
[
"len(df[df[\"nbName\"]=='4-Data-Playground.ipynb'])",
"_____no_output_____"
],
[
"df[\"length\"] = df.history.apply(lambda x: len(x))",
"_____no_output_____"
],
[
"# df[(df[\"nbName\"]=='4-Data-Playground.ipynb') &(df[\"length\"]>3)]",
"_____no_output_____"
],
[
"for entry in df.values:\n nb = nbf.v4.new_notebook()\n code = \"import lux\\nimport pandas as pd\"\n nb['cells'] = [nbf.v4.new_code_cell(code)]\n nb['kernelspec'] = {\"display_name\": \"Python 3\", \"language\": \"python\",\"name\": \"python3\"}\n for log_entry in entry[1]:\n if log_entry['type'] == 'executeCodeCell':\n nb['cells'].append(nbf.v4.new_code_cell(log_entry['code']))\n name = entry[4][3:] + entry[0]\n nbf.write(nb, '../constructed_nbs/' + name+\".ipynb\")",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaf48884e8c34291c932045ec1364e3c892dc06
| 95,109 |
ipynb
|
Jupyter Notebook
|
autoencoder/Convolutional_Autoencoder_Solution.ipynb
|
freedomkwok/deep-learning
|
f7c2bce1d9416f5db969860cdd64b20e4b2305c6
|
[
"MIT"
] | null | null | null |
autoencoder/Convolutional_Autoencoder_Solution.ipynb
|
freedomkwok/deep-learning
|
f7c2bce1d9416f5db969860cdd64b20e4b2305c6
|
[
"MIT"
] | null | null | null |
autoencoder/Convolutional_Autoencoder_Solution.ipynb
|
freedomkwok/deep-learning
|
f7c2bce1d9416f5db969860cdd64b20e4b2305c6
|
[
"MIT"
] | null | null | null | 229.178313 | 48,642 | 0.890063 |
[
[
[
"# Convolutional Autoencoder\n\nSticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"from tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data', validation_size=0)",
"Extracting MNIST_data/train-images-idx3-ubyte.gz\nExtracting MNIST_data/train-labels-idx1-ubyte.gz\nExtracting MNIST_data/t10k-images-idx3-ubyte.gz\nExtracting MNIST_data/t10k-labels-idx1-ubyte.gz\n"
],
[
"img = mnist.train.images[2]\nplt.imshow(img.reshape((28, 28)), cmap='Greys_r')",
"_____no_output_____"
]
],
[
[
"## Network Architecture\n\nThe encoder part of the network will be a typical convolutional pyramid. Each convolutional layer will be followed by a max-pooling layer to reduce the dimensions of the layers. The decoder though might be something new to you. The decoder needs to convert from a narrow representation to a wide reconstructed image. For example, the representation could be a 4x4x8 max-pool layer. This is the output of the encoder, but also the input to the decoder. We want to get a 28x28x1 image out from the decoder so we need to work our way back up from the narrow decoder input layer. A schematic of the network is shown below.\n\n<img src='assets/convolutional_autoencoder.png' width=500px>\n\nHere our final encoder layer has size 4x4x8 = 128. The original images have size 28x28 = 784, so the encoded vector is roughly 16% the size of the original image. These are just suggested sizes for each of the layers. Feel free to change the depths and sizes, but remember our goal here is to find a small representation of the input data.\n\n### What's going on with the decoder\n\nOkay, so the decoder has these \"Upsample\" layers that you might not have seen before. First off, I'll discuss a bit what these layers *aren't*. Usually, you'll see **transposed convolution** layers used to increase the width and height of the layers. They work almost exactly the same as convolutional layers, but in reverse. A stride in the input layer results in a larger stride in the transposed convolution layer. For example, if you have a 3x3 kernel, a 3x3 patch in the input layer will be reduced to one unit in a convolutional layer. Comparatively, one unit in the input layer will be expanded to a 3x3 path in a transposed convolution layer. The TensorFlow API provides us with an easy way to create the layers, [`tf.nn.conv2d_transpose`](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d_transpose). \n\nHowever, transposed convolution layers can lead to artifacts in the final images, such as checkerboard patterns. This is due to overlap in the kernels which can be avoided by setting the stride and kernel size equal. In [this Distill article](http://distill.pub/2016/deconv-checkerboard/) from Augustus Odena, *et al*, the authors show that these checkerboard artifacts can be avoided by resizing the layers using nearest neighbor or bilinear interpolation (upsampling) followed by a convolutional layer. In TensorFlow, this is easily done with [`tf.image.resize_images`](https://www.tensorflow.org/versions/r1.1/api_docs/python/tf/image/resize_images), followed by a convolution. Be sure to read the Distill article to get a better understanding of deconvolutional layers and why we're using upsampling.\n\n> **Exercise:** Build the network shown above. Remember that a convolutional layer with strides of 1 and 'same' padding won't reduce the height and width. That is, if the input is 28x28 and the convolution layer has stride = 1 and 'same' padding, the convolutional layer will also be 28x28. The max-pool layers are used the reduce the width and height. A stride of 2 will reduce the size by a factor of 2. Odena *et al* claim that nearest neighbor interpolation works best for the upsampling, so make sure to include that as a parameter in `tf.image.resize_images` or use [`tf.image.resize_nearest_neighbor`]( `https://www.tensorflow.org/api_docs/python/tf/image/resize_nearest_neighbor). For convolutional layers, use [`tf.layers.conv2d`](https://www.tensorflow.org/api_docs/python/tf/layers/conv2d). For example, you would write `conv1 = tf.layers.conv2d(inputs, 32, (5,5), padding='same', activation=tf.nn.relu)` for a layer with a depth of 32, a 5x5 kernel, stride of (1,1), padding is 'same', and a ReLU activation. Similarly, for the max-pool layers, use [`tf.layers.max_pooling2d`](https://www.tensorflow.org/api_docs/python/tf/layers/max_pooling2d).",
"_____no_output_____"
]
],
[
[
"inputs_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='inputs')\ntargets_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='targets')\n\n### Encoder\nconv1 = tf.layers.conv2d(inputs_, 16, (3,3), padding='same', activation=tf.nn.relu)\n# Now 28x28x16\nmaxpool1 = tf.layers.max_pooling2d(conv1, (2,2), (2,2), padding='same')\n# Now 14x14x16\nconv2 = tf.layers.conv2d(maxpool1, 8, (3,3), padding='same', activation=tf.nn.relu)\n# Now 14x14x8\nmaxpool2 = tf.layers.max_pooling2d(conv2, (2,2), (2,2), padding='same')\n# Now 7x7x8\nconv3 = tf.layers.conv2d(maxpool2, 8, (3,3), padding='same', activation=tf.nn.relu)\n# Now 7x7x8\nencoded = tf.layers.max_pooling2d(conv3, (2,2), (2,2), padding='same')\n# Now 4x4x8\n\n### Decoder\nupsample1 = tf.image.resize_nearest_neighbor(encoded, (7,7))\n# Now 7x7x8\nconv4 = tf.layers.conv2d(upsample1, 8, (3,3), padding='same', activation=tf.nn.relu)\n# Now 7x7x8\nupsample2 = tf.image.resize_nearest_neighbor(conv4, (14,14))\n# Now 14x14x8\nconv5 = tf.layers.conv2d(upsample2, 8, (3,3), padding='same', activation=tf.nn.relu)\n# Now 14x14x8\nupsample3 = tf.image.resize_nearest_neighbor(conv5, (28,28))\n# Now 28x28x8\nconv6 = tf.layers.conv2d(upsample3, 16, (3,3), padding='same', activation=tf.nn.relu)\n# Now 28x28x16\n\nlogits = tf.layers.conv2d(conv6, 1, (3,3), padding='same', activation=None)\n#Now 28x28x1\n\ndecoded = tf.nn.sigmoid(logits, name='decoded')\n\nloss = tf.nn.sigmoid_cross_entropy_with_logits(labels=targets_, logits=logits)\ncost = tf.reduce_mean(loss)\nopt = tf.train.AdamOptimizer(0.001).minimize(cost)",
"_____no_output_____"
]
],
[
[
"## Training\n\nAs before, here wi'll train the network. Instead of flattening the images though, we can pass them in as 28x28x1 arrays.",
"_____no_output_____"
]
],
[
[
"sess = tf.Session()",
"_____no_output_____"
],
[
"epochs = 20\nbatch_size = 200\nsess.run(tf.global_variables_initializer())\nfor e in range(epochs):\n for ii in range(mnist.train.num_examples//batch_size):\n batch = mnist.train.next_batch(batch_size)\n imgs = batch[0].reshape((-1, 28, 28, 1))\n batch_cost, _ = sess.run([cost, opt], feed_dict={inputs_: imgs,\n targets_: imgs})\n\n print(\"Epoch: {}/{}...\".format(e+1, epochs),\n \"Training loss: {:.4f}\".format(batch_cost))",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(20,4))\nin_imgs = mnist.test.images[:10]\nreconstructed = sess.run(decoded, feed_dict={inputs_: in_imgs.reshape((10, 28, 28, 1))})\n\nfor images, row in zip([in_imgs, reconstructed], axes):\n for img, ax in zip(images, row):\n ax.imshow(img.reshape((28, 28)), cmap='Greys_r')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n\nfig.tight_layout(pad=0.1)",
"_____no_output_____"
],
[
"sess.close()",
"_____no_output_____"
]
],
[
[
"## Denoising\n\nAs I've mentioned before, autoencoders like the ones you've built so far aren't too useful in practive. However, they can be used to denoise images quite successfully just by training the network on noisy images. We can create the noisy images ourselves by adding Gaussian noise to the training images, then clipping the values to be between 0 and 1. We'll use noisy images as input and the original, clean images as targets. Here's an example of the noisy images I generated and the denoised images.\n\n\n\n\nSince this is a harder problem for the network, we'll want to use deeper convolutional layers here, more feature maps. I suggest something like 32-32-16 for the depths of the convolutional layers in the encoder, and the same depths going backward through the decoder. Otherwise the architecture is the same as before.\n\n> **Exercise:** Build the network for the denoising autoencoder. It's the same as before, but with deeper layers. I suggest 32-32-16 for the depths, but you can play with these numbers, or add more layers.",
"_____no_output_____"
]
],
[
[
"inputs_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='inputs')\ntargets_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='targets')\n\n### Encoder\nconv1 = tf.layers.conv2d(inputs_, 32, (3,3), padding='same', activation=tf.nn.relu)\n# Now 28x28x32\nmaxpool1 = tf.layers.max_pooling2d(conv1, (2,2), (2,2), padding='same')\n# Now 14x14x32\nconv2 = tf.layers.conv2d(maxpool1, 32, (3,3), padding='same', activation=tf.nn.relu)\n# Now 14x14x32\nmaxpool2 = tf.layers.max_pooling2d(conv2, (2,2), (2,2), padding='same')\n# Now 7x7x32\nconv3 = tf.layers.conv2d(maxpool2, 16, (3,3), padding='same', activation=tf.nn.relu)\n# Now 7x7x16\nencoded = tf.layers.max_pooling2d(conv3, (2,2), (2,2), padding='same')\n# Now 4x4x16\n\n### Decoder\nupsample1 = tf.image.resize_nearest_neighbor(encoded, (7,7))\n# Now 7x7x16\nconv4 = tf.layers.conv2d(upsample1, 16, (3,3), padding='same', activation=tf.nn.relu)\n# Now 7x7x16\nupsample2 = tf.image.resize_nearest_neighbor(conv4, (14,14))\n# Now 14x14x16\nconv5 = tf.layers.conv2d(upsample2, 32, (3,3), padding='same', activation=tf.nn.relu)\n# Now 14x14x32\nupsample3 = tf.image.resize_nearest_neighbor(conv5, (28,28))\n# Now 28x28x32\nconv6 = tf.layers.conv2d(upsample3, 32, (3,3), padding='same', activation=tf.nn.relu)\n# Now 28x28x32\n\nlogits = tf.layers.conv2d(conv6, 1, (3,3), padding='same', activation=None)\n#Now 28x28x1\n\ndecoded = tf.nn.sigmoid(logits, name='decoded')\n\nloss = tf.nn.sigmoid_cross_entropy_with_logits(labels=targets_, logits=logits)\ncost = tf.reduce_mean(loss)\nopt = tf.train.AdamOptimizer(0.001).minimize(cost)",
"_____no_output_____"
],
[
"sess = tf.Session()",
"_____no_output_____"
],
[
"epochs = 100\nbatch_size = 200\n# Set's how much noise we're adding to the MNIST images\nnoise_factor = 0.5\nsess.run(tf.global_variables_initializer())\nfor e in range(epochs):\n for ii in range(mnist.train.num_examples//batch_size):\n batch = mnist.train.next_batch(batch_size)\n # Get images from the batch\n imgs = batch[0].reshape((-1, 28, 28, 1))\n \n # Add random noise to the input images\n noisy_imgs = imgs + noise_factor * np.random.randn(*imgs.shape)\n # Clip the images to be between 0 and 1\n noisy_imgs = np.clip(noisy_imgs, 0., 1.)\n \n # Noisy images as inputs, original images as targets\n batch_cost, _ = sess.run([cost, opt], feed_dict={inputs_: noisy_imgs,\n targets_: imgs})\n\n print(\"Epoch: {}/{}...\".format(e+1, epochs),\n \"Training loss: {:.4f}\".format(batch_cost))",
"_____no_output_____"
]
],
[
[
"## Checking out the performance\n\nHere I'm adding noise to the test images and passing them through the autoencoder. It does a suprising great job of removing the noise, even though it's sometimes difficult to tell what the original number is.",
"_____no_output_____"
]
],
[
[
"fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(20,4))\nin_imgs = mnist.test.images[:10]\nnoisy_imgs = in_imgs + noise_factor * np.random.randn(*in_imgs.shape)\nnoisy_imgs = np.clip(noisy_imgs, 0., 1.)\n\nreconstructed = sess.run(decoded, feed_dict={inputs_: noisy_imgs.reshape((10, 28, 28, 1))})\n\nfor images, row in zip([noisy_imgs, reconstructed], axes):\n for img, ax in zip(images, row):\n ax.imshow(img.reshape((28, 28)), cmap='Greys_r')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\nfig.tight_layout(pad=0.1)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aaf58ee7daea760c77c7e8fc829fbb726cf69a8
| 45,146 |
ipynb
|
Jupyter Notebook
|
figures/.ipynb_checkpoints/AGII_QuadratischeGleichungen-checkpoint.ipynb
|
georgkaufmann/lecture_agII
|
d042dae2a9ab3e47387744da7d6c47c382130acb
|
[
"MIT"
] | null | null | null |
figures/.ipynb_checkpoints/AGII_QuadratischeGleichungen-checkpoint.ipynb
|
georgkaufmann/lecture_agII
|
d042dae2a9ab3e47387744da7d6c47c382130acb
|
[
"MIT"
] | null | null | null |
figures/.ipynb_checkpoints/AGII_QuadratischeGleichungen-checkpoint.ipynb
|
georgkaufmann/lecture_agII
|
d042dae2a9ab3e47387744da7d6c47c382130acb
|
[
"MIT"
] | null | null | null | 186.553719 | 24,892 | 0.890201 |
[
[
[
"# Quadratische Gleichungen\n***",
"_____no_output_____"
],
[
"Eine *quadratische Gleichung* hat die Form:\n$$\na x^2 + b x + c = 0\n$$\nmit $a$, $b$ und $c$ den Koeffizienten.",
"_____no_output_____"
],
[
"Dividieren wir die Gleichung durch $a$, folgt die *Normalenform*:\n$$\nx^2 + {b \\over a} x + {c \\over a} = 0\n$$",
"_____no_output_____"
],
[
"## Zerlegung in Linearfaktoren\n\nDie *quadratische Gleichung* \n$$\nax^2+bx+c=0\n$$\nkann in *Linearfaktoren* zerlegt werden:\n$$\na (x-x_1) (x-x_2) = 0\n$$",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"import numpy as np\nimport cmath\nimport matplotlib.pyplot as plt\n# coefficients\na = 1\nb = 0\nc = 0\n# calculate determinant\ndet=np.sqrt(b**2-4*a*c)\nprint ('det: ',det)\nx = np.linspace(-10,10,41)\ny1 = a*x**2 + b*x + c\nplt.plot([-10,10],[0,0],linestyle='dashed',color='grey',linewidth=1)\nplt.plot(x,y1,linestyle='solid',color='red',linewidth=4,label='y1')\nplt.show()",
"det: 0.0\n"
]
],
[
[
"Die Anzahl der Nullstellen kann durch die *Determinante* bestimmt werden.\n$$\nD=\\sqrt{b^2 - 4ac}\n$$\n\nEs gilt\n- $D>0$: Zwei reelle Nullstellen $x_1$ und $x_2$\n- $D=0$: Eine reelle Nullstelle $x_1$\n- $D<0$: Keine reelle Nullstelle (aber ...)",
"_____no_output_____"
],
[
"Die Lösungen der quadratischen Gleichung lassen sich mit folgender Formel berechnen:\n$$\nx_{1,2} = {{-b \\pm \\sqrt{b^2 - 4ac}} \\over {2a}}\n$$",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport cmath\na = 1\nb = 0\nc = -1\nprint ('Coefficients a,b,c: ',a,b,c)\nx1 = (-b+np.sqrt(b**2-4*a*c) / (2*a))\nx2 = (-b-np.sqrt(b**2-4*a*c) / (2*a))\nprint ('Solutions x1/2: ',x1,x2)\n",
"Coefficients a,b,c: 1 0 -1\nSolutions x1/2: 1.0 -1.0\n"
]
],
[
[
"Wie kommen wir auf die Lösungsformel?\n\nStarte mit der quadratischen Gleichung und ergänze, um eine binomische Formel zu bekommen:\n$$\n\\begin{array}{rcll}\nax^2+bx+c &=& 0 & | -c\\\\\nax^2+bx &=& -c & |\\times 4a\\\\\n4a^2x^2+4abx &=& -4ac & | +b^2 \\\\\n(2ax)^2 + 2 \\times 2abx + b^2 &=& b^2-4ac & | \\mbox{umformen auf bin. Formel}\\\\\n(2ax+b)^2 &=& b^2-4ac & | \\sqrt{}\\\\\n2ax+b &=& \\pm \\sqrt{b^2-4ac} & | -b\\\\\n2ax &=& -b \\pm \\sqrt{b^2-4ac} & |/(2a) \\\\\nx &=& {{-b \\pm \\sqrt{b^2-4ac}} \\over {2a}}\n\\end{array}\n$$",
"_____no_output_____"
],
[
"## Beispiele",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport cmath\nimport matplotlib.pyplot as plt\n# define functions\nx = np.linspace(-10,10,41)\ny1 = x**2 + 2*x - 35\ny2 = x**2 -4*x + 4\ny3 = x**2+12*x+37\n# plot functions\nplt.plot([-10,10],[0,0],linestyle='dashed',color='grey',linewidth=1)\nplt.plot(x,y1,linestyle='solid',color='red',linewidth=3,label='x$^2$+2x-35')\nplt.plot(x,y2,linestyle='solid',color='green',linewidth=3,label='x$^2$-4x+4')\nplt.plot(x,y3,linestyle='solid',color='blue',linewidth=3,label='x$^2$+12x+37')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
4aaf5d69ce3710684b405b2a87df08fbb9c60d6a
| 583,693 |
ipynb
|
Jupyter Notebook
|
modules/interpretability/class_lung_lesion.ipynb
|
YuanTingHsieh/Tutorials
|
c29cbb2febc439d41b1ed14a17825ca519e4d959
|
[
"Apache-2.0"
] | null | null | null |
modules/interpretability/class_lung_lesion.ipynb
|
YuanTingHsieh/Tutorials
|
c29cbb2febc439d41b1ed14a17825ca519e4d959
|
[
"Apache-2.0"
] | null | null | null |
modules/interpretability/class_lung_lesion.ipynb
|
YuanTingHsieh/Tutorials
|
c29cbb2febc439d41b1ed14a17825ca519e4d959
|
[
"Apache-2.0"
] | null | null | null | 757.059663 | 510,684 | 0.945074 |
[
[
[
"This tutorial trains a 3D densenet for lung lesion classification from CT image patches.\n\nThe goal is to demonstrate MONAI's class activation mapping functions for visualising the classification models.\n\nFor the demo data:\n- Please see the `bbox_gen.py` script for generating the patch classification data from MSD task06_lung (available via `monai.apps.DecathlonDataset`).\n- Alternatively, the patch dataset (~130MB) is available for direct downloading at: https://drive.google.com/drive/folders/1vl330aJew1NCc31IVYJSAh3y0XdDdydi\n\n[](https://colab.research.google.com/github/Project-MONAI/tutorials/blob/master/modules/interpretability/class_lung_lesion.ipynb)",
"_____no_output_____"
]
],
[
[
"!python -c \"import monai\" || pip install -q \"monai-weekly[tqdm]\"",
"_____no_output_____"
],
[
"import glob\nimport os\nimport random\nimport tempfile\n\nimport matplotlib.pyplot as plt\nimport monai\nimport numpy as np\nimport torch\nfrom IPython.display import clear_output\nfrom monai.networks.utils import eval_mode\nfrom monai.transforms import (\n AddChanneld,\n Compose,\n LoadImaged,\n RandFlipd,\n RandRotate90d,\n RandSpatialCropd,\n Resized,\n ScaleIntensityRanged,\n ToTensord,\n)\nfrom monai.visualize import plot_2d_or_3d_image\nfrom sklearn.metrics import (\n ConfusionMatrixDisplay,\n classification_report,\n confusion_matrix,\n)\nfrom torch.utils.tensorboard import SummaryWriter\n\nmonai.config.print_config()\nrandom_seed = 42\nmonai.utils.set_determinism(random_seed)\nnp.random.seed(random_seed)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")",
"MONAI version: 0.4.0+21.g86c43cf.dirty\nNumpy version: 1.19.5\nPytorch version: 1.7.1\nMONAI flags: HAS_EXT = False, USE_COMPILED = False\nMONAI rev id: 86c43cf24f57370fbbc12923d09b0f52e7952cb9\n\nOptional dependencies:\nPytorch Ignite version: 0.4.2\nNibabel version: 3.2.1\nscikit-image version: 0.18.1\nPillow version: 8.1.0\nTensorboard version: 2.4.0\ngdown version: 3.12.2\nTorchVision version: 0.8.2\nITK version: 5.1.2\ntqdm version: 4.51.0\nlmdb version: 1.0.0\npsutil version: 5.8.0\n\nFor details about installing the optional dependencies, please visit:\n https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\n\n"
],
[
"directory = os.environ.get(\"MONAI_DATA_DIRECTORY\")\nroot_dir = (\n tempfile.mkdtemp() if directory is None else os.path.expanduser(directory)\n)\n\ndata_path = os.path.join(root_dir, \"patch\")\n!cd {root_dir} && [ -f \"lung_lesion_patches.tar.gz\" ] || gdown --id 1Jte6L7B_5q9XMgOCAq1Ldn29F1aaIxjW \\\n && mkdir -p {data_path} && tar -xvf \"lung_lesion_patches.tar.gz\" -C {data_path} > /dev/null",
"_____no_output_____"
],
[
"lesion = glob.glob(os.path.join(data_path, \"lesion_*\"))\nnon_lesion = glob.glob(os.path.join(data_path, \"norm_*\"))\n# optionally make sure there's 50:50 lesion vs non-lesion\nbalance_classes = True\nif balance_classes:\n print(\n f\"Before balance -- Num lesion: {len(lesion)},\"\n f\" num non-lesion: {len(non_lesion)}\"\n )\n num_to_keep = min(len(lesion), len(non_lesion))\n lesion = lesion[:num_to_keep]\n non_lesion = non_lesion[:num_to_keep]\n print(\n f\"After balance -- Num lesion: {len(lesion)},\"\n f\" num non-lesion: {len(non_lesion)}\"\n )\nlabels = np.asarray(\n [[0.0, 1.0]] * len(lesion) + [[1.0, 0.0]] * len(non_lesion)\n)\n\nall_files = [\n {\"image\": img, \"label\": label}\n for img, label in zip(lesion + non_lesion, labels)\n]\nrandom.shuffle(all_files)\nprint(f\"total items: {len(all_files)}\")",
"Before balance -- Num lesion: 64, num non-lesion: 187\nAfter balance -- Num lesion: 64, num non-lesion: 64\ntotal items: 128\n"
]
],
[
[
"Split the data into 80% training and 20% validation\n",
"_____no_output_____"
]
],
[
[
"train_frac, val_frac = 0.8, 0.2\nn_train = int(train_frac * len(all_files)) + 1\nn_val = min(len(all_files) - n_train, int(val_frac * len(all_files)))\n\ntrain_files, val_files = all_files[:n_train], all_files[-n_val:]\ntrain_labels = [data[\"label\"] for data in train_files]\nprint(f\"total train: {len(train_files)}\")\n\nval_labels = [data[\"label\"] for data in val_files]\nn_neg, n_pos = np.sum(np.asarray(val_labels) == 0), np.sum(\n np.asarray(val_labels) == 1\n)\nprint(f\"total valid: {len(val_labels)}\")",
"total train: 103\ntotal valid: 25\n"
]
],
[
[
"Create the data loaders. These loaders will be used for both training/validation, as well as visualisations.",
"_____no_output_____"
]
],
[
[
"# Define transforms for image\nwin_size = (196, 196, 144)\ntrain_transforms = Compose(\n [\n LoadImaged(\"image\"),\n AddChanneld(\"image\"),\n ScaleIntensityRanged(\n \"image\",\n a_min=-1000.0,\n a_max=500.0,\n b_min=0.0,\n b_max=1.0,\n clip=True,\n ),\n RandFlipd(\"image\", spatial_axis=0, prob=0.5),\n RandFlipd(\"image\", spatial_axis=1, prob=0.5),\n RandFlipd(\"image\", spatial_axis=2, prob=0.5),\n RandSpatialCropd(\"image\", roi_size=(64, 64, 40)),\n Resized(\"image\", win_size, \"trilinear\", True),\n RandRotate90d(\"image\", prob=0.5, spatial_axes=[0, 1]),\n ToTensord(\"image\"),\n ]\n)\nval_transforms = Compose(\n [\n LoadImaged(\"image\"),\n AddChanneld(\"image\"),\n ScaleIntensityRanged(\n \"image\",\n a_min=-1000.0,\n a_max=500.0,\n b_min=0.0,\n b_max=1.0,\n clip=True,\n ),\n Resized(\"image\", win_size, \"trilinear\", True),\n ToTensord((\"image\", \"label\")),\n ]\n)\n\npersistent_cache = os.path.join(root_dir, \"persistent_cache\")\ntrain_ds = monai.data.PersistentDataset(\n data=train_files, transform=train_transforms, cache_dir=persistent_cache\n)\ntrain_loader = monai.data.DataLoader(\n train_ds, batch_size=2, shuffle=True, num_workers=2, pin_memory=True\n)\nval_ds = monai.data.PersistentDataset(\n data=val_files, transform=val_transforms, cache_dir=persistent_cache\n)\nval_loader = monai.data.DataLoader(\n val_ds, batch_size=2, num_workers=2, pin_memory=True\n)",
"_____no_output_____"
]
],
[
[
"Start the model, loss function, and optimizer.",
"_____no_output_____"
]
],
[
[
"model = monai.networks.nets.DenseNet121(\n spatial_dims=3, in_channels=1, out_channels=2\n).to(device)\nbce = torch.nn.BCEWithLogitsLoss()\n\n\ndef criterion(logits, target):\n return bce(logits.view(-1), target.view(-1))\n\n\noptimizer = torch.optim.Adam(model.parameters(), 1e-5)",
"_____no_output_____"
]
],
[
[
"Run training iterations.",
"_____no_output_____"
]
],
[
[
"\n# start training\nval_interval = 1\nmax_epochs = 100\nbest_metric = best_metric_epoch = -1\nepoch_loss_values = []\nmetric_values = []\nscaler = torch.cuda.amp.GradScaler()\nfor epoch in range(max_epochs):\n clear_output()\n print(\"-\" * 10)\n print(f\"epoch {epoch + 1}/{max_epochs}\")\n model.train()\n epoch_loss = step = 0\n for batch_data in train_loader:\n inputs, labels = (\n batch_data[\"image\"].to(device),\n batch_data[\"label\"].to(device),\n )\n optimizer.zero_grad()\n with torch.cuda.amp.autocast():\n outputs = model(inputs)\n loss = criterion(outputs.float(), labels.float())\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n epoch_loss += loss.item()\n epoch_len = len(train_ds) // train_loader.batch_size\n if step % 50 == 0:\n print(f\"{step}/{epoch_len}, train_loss: {loss.item():.4f}\")\n step += 1\n epoch_loss /= step\n epoch_loss_values.append(epoch_loss)\n print(f\"epoch {epoch + 1} average loss: {epoch_loss:.4f}\")\n\n if (epoch + 1) % val_interval == 0:\n with eval_mode(model):\n num_correct = 0.0\n metric_count = 0\n for val_data in val_loader:\n val_images, val_labels = (\n val_data[\"image\"].to(device),\n val_data[\"label\"].to(device),\n )\n val_outputs = model(val_images)\n value = torch.eq(\n val_outputs.argmax(dim=1), val_labels.argmax(dim=1)\n )\n metric_count += len(value)\n num_correct += value.sum().item()\n metric = num_correct / metric_count\n metric_values.append(metric)\n if metric >= best_metric:\n best_metric = metric\n best_metric_epoch = epoch + 1\n torch.save(\n model.state_dict(),\n \"best_metric_model_classification3d_array.pth\",\n )\n print(\n f\"current epoch: {epoch + 1} current accuracy: {metric:.4f}\"\n f\" best accuracy: {best_metric:.4f}\"\n f\" at epoch {best_metric_epoch}\"\n )\nprint(\n f\"train completed, best_metric: {best_metric:.4f} at\"\n f\" epoch: {best_metric_epoch}\"\n)",
"----------\nepoch 100/100\n0/51, train_loss: 0.0902\n50/51, train_loss: 0.0978\nepoch 100 average loss: 0.2973\ncurrent epoch: 100 current accuracy: 0.8000 best accuracy: 0.9200 at epoch 18\ntrain completed, best_metric: 0.9200 at epoch: 18\n"
],
[
"plt.plot(epoch_loss_values, label=\"training loss\")\nval_epochs = np.linspace(\n 1, max_epochs, np.floor(max_epochs / val_interval).astype(np.int32)\n)\nplt.plot(val_epochs, metric_values, label=\"validation acc\")\nplt.legend()\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Value\")",
"_____no_output_____"
],
[
"# Reload the best network and display info\nmodel_3d = monai.networks.nets.DenseNet121(\n spatial_dims=3, in_channels=1, out_channels=2\n).to(device)\nmodel_3d.load_state_dict(\n torch.load(\"best_metric_model_classification3d_array.pth\")\n)\nmodel_3d.eval()\n\ny_pred = torch.tensor([], dtype=torch.float32, device=device)\ny = torch.tensor([], dtype=torch.long, device=device)\n\nfor val_data in val_loader:\n val_images = val_data[\"image\"].to(device)\n val_labels = val_data[\"label\"].to(device).argmax(dim=1)\n\n outputs = model_3d(val_images)\n y_pred = torch.cat([y_pred, outputs.argmax(dim=1)], dim=0)\n y = torch.cat([y, val_labels], dim=0)\n\nprint(\n classification_report(\n y.cpu().numpy(),\n y_pred.cpu().numpy(),\n target_names=[\"non-lesion\", \"lesion\"],\n )\n)\n\ncm = confusion_matrix(\n y.cpu().numpy(),\n y_pred.cpu().numpy(),\n normalize=\"true\",\n)\ndisp = ConfusionMatrixDisplay(\n confusion_matrix=cm,\n display_labels=[\"non-lesion\", \"lesion\"],\n)\ndisp.plot(ax=plt.subplots(1, 1, facecolor=\"white\")[1])",
" precision recall f1-score support\n\n non-lesion 1.00 0.86 0.92 14\n lesion 0.85 1.00 0.92 11\n\n accuracy 0.92 25\n macro avg 0.92 0.93 0.92 25\nweighted avg 0.93 0.92 0.92 25\n\n"
]
],
[
[
"# Interpretability\n\nUse GradCAM and occlusion sensitivity for network interpretability.\n\nThe occlusion sensitivity returns two images: the sensitivity image and the most probable class.\n\n* Sensitivity image -- how the probability of an inferred class changes as the corresponding part of the image is occluded.\n * Big decreases in the probability imply that that region was important in inferring the given class\n * The output is the same as the input, with an extra dimension of size N appended. Here, N is the number of inferred classes. To then see the sensitivity image of the class we're interested (maybe the true class, maybe the predcited class, maybe anything else), we simply do ``im[...,i]``.\n* Most probable class -- if that part of the image is covered up, does the predicted class change, and if so, to what? This feature is not used in this notebook.",
"_____no_output_____"
]
],
[
[
"# cam = monai.visualize.CAM(nn_module=model_3d, target_layers=\"class_layers.relu\", fc_layers=\"class_layers.out\")\ncam = monai.visualize.GradCAM(\n nn_module=model_3d, target_layers=\"class_layers.relu\"\n)\n# cam = monai.visualize.GradCAMpp(nn_module=model_3d, target_layers=\"class_layers.relu\")\nprint(\n \"original feature shape\",\n cam.feature_map_size([1, 1] + list(win_size), device),\n)\nprint(\"upsampled feature shape\", [1, 1] + list(win_size))\n\nocc_sens = monai.visualize.OcclusionSensitivity(\n nn_module=model_3d, mask_size=12, n_batch=1, stride=28\n)\n\n# For occlusion sensitivity, inference must be run many times. Hence, we can use a\n# bounding box to limit it to a 2D plane of interest (z=the_slice) where each of\n# the arguments are the min and max for each of the dimensions (in this case CHWD).\nthe_slice = train_ds[0][\"image\"].shape[-1] // 2\nocc_sens_b_box = [-1, -1, -1, -1, -1, -1, the_slice, the_slice]",
"original feature shape torch.Size([1, 1, 6, 6, 4])\nupsampled feature shape [1, 1, 196, 196, 144]\n"
],
[
"train_transforms.set_random_state(42)\nn_examples = 5\nsubplot_shape = [3, n_examples]\nfig, axes = plt.subplots(*subplot_shape, figsize=(25, 15), facecolor=\"white\")\nitems = np.random.choice(len(train_ds), size=len(train_ds))\n\nexample = 0\nfor item in items:\n\n data = train_ds[\n item\n ] # this fetches training data with random augmentations\n image, label = data[\"image\"].to(device).unsqueeze(0), data[\"label\"][1]\n y_pred = model_3d(image)\n pred_label = y_pred.argmax(1).item()\n # Only display tumours images\n if label != 1 or label != pred_label:\n continue\n\n img = image.detach().cpu().numpy()[..., the_slice]\n\n name = \"actual: \"\n name += \"lesion\" if label == 1 else \"non-lesion\"\n name += \"\\npred: \"\n name += \"lesion\" if pred_label == 1 else \"non-lesion\"\n name += f\"\\nlesion: {y_pred[0,1]:.3}\"\n name += f\"\\nnon-lesion: {y_pred[0,0]:.3}\"\n\n # run CAM\n cam_result = cam(x=image, class_idx=None)\n cam_result = cam_result[..., the_slice]\n\n # run occlusion\n occ_result, _ = occ_sens(x=image, b_box=occ_sens_b_box)\n occ_result = occ_result[..., pred_label]\n\n for row, (im, title) in enumerate(\n zip(\n [img, cam_result, occ_result],\n [name, \"CAM\", \"Occ. sens.\"],\n )\n ):\n cmap = \"gray\" if row == 0 else \"jet\"\n ax = axes[row, example]\n if isinstance(im, torch.Tensor):\n im = im.cpu().detach()\n im_show = ax.imshow(im[0][0], cmap=cmap)\n\n ax.set_title(title, fontsize=25)\n ax.axis(\"off\")\n fig.colorbar(im_show, ax=ax)\n\n example += 1\n if example == n_examples:\n break",
"Computing occlusion sensitivity: 100%|██████████| 49/49 [00:02<00:00, 19.81it/s]\nComputing occlusion sensitivity: 100%|██████████| 49/49 [00:02<00:00, 19.80it/s]\nComputing occlusion sensitivity: 100%|██████████| 49/49 [00:02<00:00, 19.83it/s]\nComputing occlusion sensitivity: 100%|██████████| 49/49 [00:02<00:00, 19.82it/s]\nComputing occlusion sensitivity: 100%|██████████| 49/49 [00:02<00:00, 19.82it/s]\n"
],
[
"\nwith SummaryWriter(log_dir=\"logs\") as writer:\n plot_2d_or_3d_image(img, step=0, writer=writer, tag=\"Input\")\n plot_2d_or_3d_image(cam_result, step=0, writer=writer, tag=\"CAM\")\n plot_2d_or_3d_image(occ_result, step=0, writer=writer, tag=\"OccSens\")",
"_____no_output_____"
],
[
"%load_ext tensorboard\n%tensorboard --logdir logs",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4aaf752d516e537317aa5ec1b9532e113cf498c9
| 5,986 |
ipynb
|
Jupyter Notebook
|
harmonica/examples/getting_started.ipynb
|
aclark-aquaveo/harmonica
|
c7e8b5911c2f52d8bed0b7115ab9330915eedc87
|
[
"BSD-3-Clause"
] | 9 |
2018-09-15T07:16:19.000Z
|
2022-02-08T21:28:45.000Z
|
harmonica/examples/getting_started.ipynb
|
cateseale/harmonica
|
6938e8b40ef3927528fd6c6f43459ffd815c6142
|
[
"BSD-3-Clause"
] | 8 |
2018-09-13T15:20:19.000Z
|
2019-08-16T14:36:12.000Z
|
harmonica/examples/getting_started.ipynb
|
cateseale/harmonica
|
6938e8b40ef3927528fd6c6f43459ffd815c6142
|
[
"BSD-3-Clause"
] | 11 |
2018-09-20T19:53:07.000Z
|
2022-03-19T04:24:59.000Z
| 20.712803 | 128 | 0.531574 |
[
[
[
"from datetime import datetime\nimport numpy as np\n\nfrom pytides.tide import Tide as pyTide\nimport harmonica\nfrom harmonica.harmonica import Tide",
"_____no_output_____"
]
],
[
[
"# Tidal Reconstruction",
"_____no_output_____"
]
],
[
[
"Tide.reconstruct_tide?",
"_____no_output_____"
]
],
[
[
"## Required Input",
"_____no_output_____"
]
],
[
[
"# location of interest\nlocation = (38.375789, -74.943915)\n# datetime object of time zero\ntime_zero = datetime.now()\n# array of hour offsets from time zero (MUST BE IN HOURS)\nhours_offset_from_zero = np.arange(0, 1000, 1, dtype=float)",
"_____no_output_____"
]
],
[
[
"## Optional Input",
"_____no_output_____"
]
],
[
[
"# set the model name\nmodel_name = 'tpxo9'\n# requested constituent(s) \nconstituents = None\n# should phase be all positive [0 360]?\npositive_phase = True\n# output file\noutfile = None",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"#### Process input data",
"_____no_output_____"
]
],
[
[
"# convert the numpy array of offset time to datetime objects\ntimes = pyTide._times(time_zero, hours_offset_from_zero)",
"_____no_output_____"
]
],
[
[
"#### Reconstruct tides",
"_____no_output_____"
]
],
[
[
"# reconstruct the tide\ntide = Tide().reconstruct_tide(loc=location, times=times, model=model_name, cons=constituents, \n positive_ph=positive_phase)",
"_____no_output_____"
]
],
[
[
"#### View/Save output",
"_____no_output_____"
]
],
[
[
"# if output file requested\nif outfile is not None:\n # write to file\n tide.data.to_csv(outfile, sep='\\t', header=True, index=False)\n \n# display the dataframe\ndisplay(tide.data)",
"_____no_output_____"
]
],
[
[
"---\n---",
"_____no_output_____"
],
[
"# Tidal Deconstruction",
"_____no_output_____"
]
],
[
[
"Tide.deconstruct_tide?",
"_____no_output_____"
]
],
[
[
"## Required Input",
"_____no_output_____"
]
],
[
[
"# datetime object of time zero\ntime_zero = datetime.now()\n# array of hour offsets from time zero (MUST BE IN HOURS)\nhours_offset_from_zero = np.arange(0, 1000, 1, dtype=float)\n# array of water levels\nwater_level = np.cos(hours_offset_from_zero)",
"_____no_output_____"
]
],
[
[
"## Optional Input",
"_____no_output_____"
]
],
[
[
"# list of requested constituents\nrequested_cons = ['M2', 'S2','N2','K1','M4','O1']\n# number of required periods for inclusion of consituents\nperiods = 4\n# should phase be all positive [0 360]?\npositive_ph = False\n# output file\ndecomp_out = None",
"_____no_output_____"
]
],
[
[
"#### Process input data",
"_____no_output_____"
]
],
[
[
"# convert the numpy array of offset time to datetime objects\ntimes = pyTide._times(time_zero, hours_offset_from_zero)",
"_____no_output_____"
]
],
[
[
"#### Deconstruct tides",
"_____no_output_____"
]
],
[
[
"constituents = Tide().deconstruct_tide(water_level, times, cons=requested_cons, n_period=periods, positive_ph=positive_ph)",
"_____no_output_____"
],
[
"constituents.constituents.data",
"_____no_output_____"
],
[
"# if output file requested\nif decomp_out is not None:\n # write to file\n constituents.constituents.data.to_csv(decomp_out, sep='\\t', header=True, index=False)\n \n# display the dataframe\ndisplay(constituents.constituents.data)",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4aaf7a030a1879c8580d2ec4331294a5f00967fb
| 97,083 |
ipynb
|
Jupyter Notebook
|
Materials/161103-run-plot2.ipynb
|
Space-Monkey-KD/Noisy-Labels-Problems
|
4b40ef695d0be9a3dba6be636c774338406567c0
|
[
"MIT"
] | null | null | null |
Materials/161103-run-plot2.ipynb
|
Space-Monkey-KD/Noisy-Labels-Problems
|
4b40ef695d0be9a3dba6be636c774338406567c0
|
[
"MIT"
] | null | null | null |
Materials/161103-run-plot2.ipynb
|
Space-Monkey-KD/Noisy-Labels-Problems
|
4b40ef695d0be9a3dba6be636c774338406567c0
|
[
"MIT"
] | null | null | null | 141.934211 | 38,506 | 0.84298 |
[
[
[
"FN = '161103-run-plot'",
"_____no_output_____"
]
],
[
[
"Plot validation accuracy vs. noise level for different experiments",
"_____no_output_____"
],
[
"the results of the experiments are accumlated in:",
"_____no_output_____"
]
],
[
[
"FN1 = '160919-run-plot'",
"_____no_output_____"
]
],
[
[
"each experiment is run by `run.bash` which runs the same experiment with different training size (`down_sample=.2,.5,1`) and in each time it runs (`run_all.bash`) with 5 different seeds.\nEach such run of `jacob-reed.py` includes a loop over different `noise_level`",
"_____no_output_____"
]
],
[
[
"%%bash -s \"{FN1}\"\necho $1\n# ./run.bash --FN=data/$1\n./run.bash --FN=data/$1 --model=simple --beta=0\n# ./run.bash --FN=data/$1 --model=complex --beta=0 --pretrain=2\n# ./run.bash --FN=data/$1 --model=reed_hard --beta=0.8\n# ./run.bash --FN=data/$1 --model=reed_soft --beta=0.95",
"160919-run-plot\nWritining all results to data/160919-run-plot...\nMNIST training data set label distribution [5923 6742 5958 6131 5842 5421 5918 6265 5851 5949]\ntest distribution [ 980 1135 1032 1010 982 892 958 1028 974 1009]\nstratified train [5923 6742 5958 6131 5842 5421 5918 6265 5851 5949]\nX_train shape: (60000, 784)\n60000 train samples\n10000 test samples\nExperiment SMp_46-7904213568_10s\nRandom classification {'baseline_loss': 2.322647158050537, 'loss': 2.3050852592468263, 'channeled_acc': 0.13830000000000001, 'channeled_loss': 2.3050852592468263, 'baseline_acc': 0.13769999999999999}\nNOISE: level 0.3000 error 0.3000\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.300000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 11.864706327819825, 'loss': 0.83415239267349239, 'channeled_acc': 0.56630000000000003, 'channeled_loss': 0.83415239267349239, 'baseline_acc': 0.19689999999999999}\nNOISE: level 0.3600 error 0.3600\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.360000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.273705223083496, 'loss': 0.91065117282867436, 'channeled_acc': 0.58830000000000005, 'channeled_loss': 0.91065117282867436, 'baseline_acc': 0.19600000000000001}\nNOISE: level 0.3800 error 0.3800\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.380000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.337561065673828, 'loss': 0.94412724514007573, 'channeled_acc': 0.58689999999999998, 'channeled_loss': 0.94412724514007573, 'baseline_acc': 0.19689999999999999}\nNOISE: level 0.4000 error 0.4000\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.400000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.204453985595704, 'loss': 0.96354956874847408, 'channeled_acc': 0.57440000000000002, 'channeled_loss': 0.96354956874847408, 'baseline_acc': 0.19289999999999999}\nNOISE: level 0.4200 error 0.4200\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.420000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.331268045043945, 'loss': 0.99219519462585448, 'channeled_acc': 0.54259999999999997, 'channeled_loss': 0.99219519462585448, 'baseline_acc': 0.1883}\nNOISE: level 0.4400 error 0.4400\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.440000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.069080349731445, 'loss': 1.0225821649551392, 'channeled_acc': 0.53580000000000005, 'channeled_loss': 1.0225821649551392, 'baseline_acc': 0.19320000000000001}\nNOISE: level 0.4600 error 0.4600\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.460000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.501775045776368, 'loss': 1.0341131059646607, 'channeled_acc': 0.58919999999999995, 'channeled_loss': 1.0341131059646607, 'baseline_acc': 0.19700000000000001}\nNOISE: level 0.4700 error 0.4700\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.470000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.460718850708007, 'loss': 1.047412922668457, 'channeled_acc': 0.59050000000000002, 'channeled_loss': 1.047412922668457, 'baseline_acc': 0.1961}\nNOISE: level 0.4750 error 0.4750\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.475000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.175910626220704, 'loss': 1.0648763029098511, 'channeled_acc': 0.58979999999999999, 'channeled_loss': 1.0648763029098511, 'baseline_acc': 0.19689999999999999}\nNOISE: level 0.4800 error 0.4800\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.480000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.485722811889648, 'loss': 1.0613928880691528, 'channeled_acc': 0.59050000000000002, 'channeled_loss': 1.0613928880691528, 'baseline_acc': 0.1968}\nNOISE: level 0.4850 error 0.4850\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.485000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.443034471130371, 'loss': 0.99367585935592651, 'channeled_acc': 0.57150000000000001, 'channeled_loss': 0.99367585935592651, 'baseline_acc': 0.1956}\nNOISE: level 0.4900 error 0.4900\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.490000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.467528878784179, 'loss': 1.0770502014160157, 'channeled_acc': 0.58979999999999999, 'channeled_loss': 1.0770502014160157, 'baseline_acc': 0.19600000000000001}\nNOISE: level 0.4950 error 0.4950\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.495000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 12.516313090515137, 'loss': 1.015339421081543, 'channeled_acc': 0.57520000000000004, 'channeled_loss': 1.015339421081543, 'baseline_acc': 0.1966}\nNOISE: level 0.5000 error 0.5000\nLoading data/160919-run-plot.BM_46-7904213568_10s.0.500000.hdf5 to model_1\ninput_1 skipping this is empty file layer\nhidden loading 784x500 500 500x300 300 hidden dense_1/kernel:0 is missing dense_1/bias:0 is missing dense_2/kernel:0 is missing dense_2/bias:0 is missing (bad #wgts) ABORT\nEnd classification {'baseline_loss': 10.998359754943849, 'loss': 0.96647218112945554, 'channeled_acc': 0.47899999999999998, 'channeled_loss': 0.96647218112945554, 'baseline_acc': 0.2949}\n"
],
[
"import fasteners\nimport time\nimport os\nfrom collections import defaultdict\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"import pickle\nimport warnings ; warnings.filterwarnings(\"ignore\")\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.rcParams['axes.facecolor'] = 'white'",
"_____no_output_____"
],
[
"with fasteners.InterProcessLock('/tmp/%s.lock_file'%FN1):\n with open('data/%s.results.pkl'%FN1,'rb') as fp:\n results = pickle.load(fp)",
"_____no_output_____"
],
[
"experiments = set([k[0] for k in results.keys()]) # find all unique experiments from experiment,noise keys\nexperiments = sorted(experiments)",
"_____no_output_____"
],
[
"print experiments",
"['BM_46-7904213568_10s', 'SMp_46-7904213568_10s']\n"
]
],
[
[
"The different models for which we have results. Composed from the following:\n* B baseline, S simple, C complex, R reed soft, r reed hard\n* M for MLP, C for CNN\n* If the model is not baseline then beta is less than 1 and its value **after the decimal dot** appears (e.g. beta=0.85 will show as 85.) Note that if beta happens to be zero then nothing will appear\n* Pre-training using labels generated by: p=baseline, q=simple model. r=use simple weights as a start point for the bias of the channel matrix instead of rebuilding it from the labels predicted by the simple model\n* If model is complex then the value (usually 0) used to initialize channel matrix weights (unless it was 0.1)",
"_____no_output_____"
]
],
[
[
"print \"Models:\",', '.join(set(x.split('-')[0] for x in experiments))",
"Models: BM_46, SMp_46\n"
]
],
[
[
"The noise used:",
"_____no_output_____"
]
],
[
[
"print \"Noise:\",', '.join(set(x.split('-')[1].split('_')[0] for x in experiments))",
"Noise: 7904213568\n"
],
[
"for x in experiments:\n print x\nprint x.split('-')[1].split('_')",
"BM_46-7904213568_10s\nSMp_46-7904213568_10s\n['7904213568', '10s']\n"
]
],
[
[
"different seeds used",
"_____no_output_____"
],
[
"size of training data used. Multiply by 10 to get percentage, s at the end indicate that the number of labels in training set is stratified",
"_____no_output_____"
]
],
[
[
"print \"Training size:\",', '.join(set(x.split('-')[1].split('_')[1] for x in experiments))",
"Training size: 10s\n"
]
],
[
[
"Count how many experiments (by different seeds) we did for every model/train-size combinations",
"_____no_output_____"
]
],
[
[
"e2n = defaultdict(int)\nfor e in reversed(experiments):\n model_noise, seed, train_size = e.split('_')\n e2n['_'.join([model_noise, train_size])] += 1\n# e2n",
"_____no_output_____"
],
[
"#http://people.duke.edu/~ccc14/pcfb/analysis.html\ndef bootstrap(data, num_samples, statistic, alpha):\n \"\"\"Returns bootstrap estimate of 100.0*(1-alpha) CI for statistic.\"\"\"\n n = len(data)\n idx = np.random.randint(0, n, (num_samples, n))\n samples = data[idx]\n stat = np.sort(statistic(samples, 1))\n return (stat[int((alpha/2.0)*num_samples)],\n stat[int((1-alpha/2.0)*num_samples)])",
"_____no_output_____"
]
],
[
[
"convert model code to label we will use in the graph's legend",
"_____no_output_____"
]
],
[
[
"namelookup = {'CMp0':'Complex baseline-labels',\n 'CMq0':'Complex', # simple-labels',\n 'CCq0':'Complex CNN', # simple-labels',\n 'CMr0':'Complex simple-weights',\n 'BM':'Baseline','BC':'Baseline CNN',\n 'SMp':'Simple','SMP':'Simple soft confusion',\n 'SCp':'Simple CNN','SCP':'Simple CNN soft confusion',\n 'rM8p':'Reed hard','RM95p':'Reed soft',\n 'rC8p':'Reed hard','RC95p':'Reed soft',\n 'rMp':'Reed hard beta=0','RMp':'Reed soft beta=0'}",
"_____no_output_____"
]
],
[
[
"the order in which the graphs will appear in the legend (and colors)",
"_____no_output_____"
]
],
[
[
"model_order = {'SMp':3, 'SCp':3, 'CMp0':0, 'CMq0':1, 'CCq0':1, 'CMr0':2,\n 'rM8p':4, 'rC8p':4, 'rMp':5,\n 'RM95p':6, 'RC95p':6, 'RMp':7,\n 'BM':8,'BC':9, 'SMP':10}",
"_____no_output_____"
],
[
"def plot(idx, models=None, perm=None, down_samples=None,xlim=(0.3,0.5),ylim=(0.4,1),title='', stat=np.mean):\n \"\"\"\n models - list of str\n take only experiments that starts with one of the str in models.\n down_samples - list of float or str\n take only results with specificed down sample\n title - if None then dont produce any title. If string then build a title which includes in it the given str\n \"\"\"\n if down_samples is not None:\n if not isinstance(down_samples,list):\n down_samples = [down_samples]\n down_samples = [down_sample if isinstance(down_sample, basestring)\n else '%g'%(down_sample*10)\n for down_sample in down_samples]\n\n plt.subplot(idx)\n \n e2xy = defaultdict(lambda : defaultdict(list))\n for e in reversed(experiments):\n if down_samples is not None:\n for down_sample in down_samples:\n if e.endswith('_'+down_sample) or e.endswith('_'+down_sample+'s'):\n break\n else:\n continue\n if models:\n for model in models:\n if e.startswith(model):\n break\n else:\n continue\n else:\n model = e.split('-')[0]\n down_sample = e.split('_')[-1]\n if perm is not None:\n pperm = e.split('-')[1].split('_')[0]\n if pperm != perm:\n continue\n \n X = [k[1] for k in results.keys() if k[0] == e]\n Y = []\n for n in X:\n d = results[(e,n)][1]\n for k in ['baseline_acc', 'acc']:\n if k in d:\n Y.append(d[k])\n break\n else:\n raise Exception('validation accuracy not found')\n X, Y = zip(*sorted(zip(X,Y),key=lambda x: x[0]))\n \n for x,y in zip(X,Y):\n e2xy[(model,down_sample)][x] += [y]\n \n Y = np.array(Y)\n\n keys = sorted(e2xy.keys(),key=lambda md: (model_order[md[0].split('-')[0]], (' ' if len(md[1])-int(md[1].endswith('s'))==1 else '') + md[1]))\n\n # determine if all down_sample are stratified (True) or all not stratified (False) or mixed (Nones)\n all_stratified = None\n for model,down_sample in keys:\n if all_stratified is None:\n all_stratified = down_sample.endswith('s')\n elif all_stratified != down_sample.endswith('s'):\n all_stratified = None\n break\n\n for c, (model,down_sample) in enumerate(keys):\n xy = e2xy[(model,down_sample)]\n X = []\n Y = []\n Ys = []\n for x in sorted(xy.keys()):\n X.append(x)\n Y.append(stat(xy[x]))\n Ys.append(xy[x])\n error_bars = []\n for y,ys in zip(Y,Ys):\n ym, yp = bootstrap(np.array(ys), 10000, stat, 0.05)\n error_bars.append((y-ym,yp-y))\n X = np.array(X)\n \n colors = ['b','g','r','c','m','k']\n linestyles=['solid', 'dashed','dashdot','dotted']\n color = colors[c % len(colors)]\n linestyle = linestyles[(c//len(colors))%len(linestyles)]\n plt.errorbar(X + 0.001*np.random.random(len(X)),\n Y, yerr=np.array(error_bars).T, ecolor=color, elinewidth=2, alpha=0.2,\n fmt='none')\n # label of each graph is the model name in English and\n # if we have more than one downsample option then also add it to the label\n if model in namelookup:\n label = namelookup[model]\n else:\n label = namelookup[model.split('-')[0]] + ' ' + model.split('-')[1]\n if down_samples is None or len(down_samples) > 1:\n if all_stratified is None:\n label += ' '+(down_sample[:-1]+'0% stratified' if down_sample.endswith('s') else down_sample+'0%')\n else:\n label += ' '+(down_sample[:-1] if down_sample.endswith('s') else down_sample)+'0%'\n plt.plot(X,Y, color=color, linestyle=linestyle, label=label)\n plt.legend(loc='lower left')\n plt.ylabel('test accuracy', fontsize=18)\n plt.xlabel('noise fraction', fontsize=18);\n if title is not None:\n title = 'MNIST '+title\n if all_stratified:\n title += ' stratified'\n plt.title(title)\n # The range of X and Y is exactly like in other paper\n if xlim is not None:\n plt.xlim(*xlim)\n if ylim is not None:\n plt.ylim(*ylim)",
"_____no_output_____"
],
[
"plt.figure(figsize=(12,10))\nplot(111, down_samples=1.0, models=['BM','SMp','CMq0','rM8p','RM95p'], title=None, perm='7904213568') ",
"_____no_output_____"
],
[
"plt.figure(figsize=(12,10))\nplot(111, down_samples=.5, models=['BM','SMp','CMq0','rM8p','RM95p'], title=None, perm='7904213568') ",
"_____no_output_____"
],
[
"plt.figure(figsize=(12,10))\nplot(111, down_samples=.2, models=['BM','SMp','CMq0','rM8p','RM95p'], title=None, perm='7904213568') ",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4aafa9204423f5357a6c3a6ceeacddb09deae78b
| 90,257 |
ipynb
|
Jupyter Notebook
|
supervised/linear_regression.ipynb
|
transedward/ml-playground
|
f273ea923cd442f5a51b73c14eb220f3d2b11151
|
[
"MIT"
] | 18 |
2016-11-29T14:20:40.000Z
|
2021-04-13T03:10:57.000Z
|
supervised/linear_regression.ipynb
|
transedward/ml-playground
|
f273ea923cd442f5a51b73c14eb220f3d2b11151
|
[
"MIT"
] | 1 |
2019-02-21T00:47:04.000Z
|
2019-02-21T00:47:04.000Z
|
supervised/linear_regression.ipynb
|
transedward/ml-playground
|
f273ea923cd442f5a51b73c14eb220f3d2b11151
|
[
"MIT"
] | 9 |
2017-03-06T13:31:15.000Z
|
2021-09-20T19:31:43.000Z
| 527.818713 | 63,330 | 0.935761 |
[
[
[
"import sys\nif \"../\" not in sys.path:\n sys.path.append(\"../\")\n\nfrom sklearn.datasets import make_regression\n\nfrom dataset.synthetic import make_wave\nfrom supervised.linear_regression import LinearRegressionGD, LinearRegression\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\nimport seaborn as sns\nsns.set_context('notebook')\nsns.set_style('white')\n\n# for auto-reloading external modules\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"X, y = make_wave(n_samples=1000)",
"_____no_output_____"
],
[
"model_gd = LinearRegressionGD(lr=0.001, max_iters=2000, verbose=False)\n%time model_gd.fit(X, y)",
"CPU times: user 136 ms, sys: 3.2 ms, total: 139 ms\nWall time: 139 ms\n"
],
[
"plt.plot(model_gd.loss_history)",
"_____no_output_____"
],
[
"# Compare with (closed form) LinearRegression\nmodel = LinearRegression()\n%time model.fit(X, y)",
"CPU times: user 1.43 ms, sys: 987 µs, total: 2.42 ms\nWall time: 6.88 ms\n"
],
[
"plt.scatter(X, y, c='r', marker='x')\nplt.plot(X, model_gd.predict(X), label='Linear regression (Gradient descent)')\nplt.plot(X, model.predict(X), label='Linear regression (closed form)')\nplt.legend(loc=4);",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aafb282a722e3ddd058873163bf539fd73c7ae9
| 1,210 |
ipynb
|
Jupyter Notebook
|
my_first_jupyter_notebook.ipynb
|
pwillits/astr-119-session-5
|
03606cbc40efc89bdfa14fd2eaf64695d065e5bb
|
[
"MIT"
] | null | null | null |
my_first_jupyter_notebook.ipynb
|
pwillits/astr-119-session-5
|
03606cbc40efc89bdfa14fd2eaf64695d065e5bb
|
[
"MIT"
] | null | null | null |
my_first_jupyter_notebook.ipynb
|
pwillits/astr-119-session-5
|
03606cbc40efc89bdfa14fd2eaf64695d065e5bb
|
[
"MIT"
] | null | null | null | 17.285714 | 63 | 0.481818 |
[
[
[
"import numpy as np",
"_____no_output_____"
],
[
"n = 10 #define an integer\nx = np.arange(n, dtype=float) #define an array",
"_____no_output_____"
],
[
"print(x)",
"_____no_output_____"
]
],
[
[
"# THIS IS MARKDOWN\n\nIt's great! yeah!",
"_____no_output_____"
]
]
] |
[
"code",
"markdown"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
4aafb862bcd4b59c8ce3fe305524f9ad7a6c8cbc
| 30,292 |
ipynb
|
Jupyter Notebook
|
ShikakuSolver.ipynb
|
jraska1/py-notebooks
|
9d113bec33bc672f5c60ba4f9d0c8f5005b40e2c
|
[
"Apache-2.0"
] | null | null | null |
ShikakuSolver.ipynb
|
jraska1/py-notebooks
|
9d113bec33bc672f5c60ba4f9d0c8f5005b40e2c
|
[
"Apache-2.0"
] | null | null | null |
ShikakuSolver.ipynb
|
jraska1/py-notebooks
|
9d113bec33bc672f5c60ba4f9d0c8f5005b40e2c
|
[
"Apache-2.0"
] | null | null | null | 32.854664 | 254 | 0.426218 |
[
[
[
"[Shikaku](https://en.wikipedia.org/wiki/Shikaku) je jedna z japonských logických her, kterou publikoval časopis Nikoli. Jako obvykle se jedná o deskovou hru, kterou je možné hrát na čtvercové nebo obdélníkové desce.\n\nÚkolem je rozdělit desku na obdélníky, které jí plně pokrývají a vzájemně se nepřekrývají. Každý obdélník je určen jednou pozicí na desce s číslem udávajícím jeho plochu ve čtvercích.\nV zadání úlohy je tedy na desce tolik čísel, kolik je požadovaných obdélníků. Součet čísel pak představuje plochu celé desky.\n\nNapříklad zadání by mohlo vypadat následovně:\n\n\n```\n ---------------\n| | | | 4 |\n ---------------\n| | 8 | | |\n ---------------\n| | | 4 | |\n ---------------\n| | | | |\n ---------------\n\n```\n\nPokusil jsem se tedy napsat řešení pro takovou hru. Nejdříve pomocí backtracking a následně také Constraint Programming. Třeba příjdete na nějaké jiné řešení.\n",
"_____no_output_____"
],
[
"# Zdroj testovacích dat\n\nProtože budu zkoušet dva postupy, vytvořil jsem si nejdříve jeden společný zdroj testovacích dat.\nJe to jedna třída `DataSource` v samostatném modulu. Ta obsahuje několik zadání hry a metody, jak s nimi jednoduše pracovat.\n\nJednodušší bude asi ukázka, jak s tím zdrojem testovacích vzorků pracuji:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom ShikakuSource import DataSource\n\nsource = DataSource()",
"_____no_output_____"
]
],
[
[
"Počet vzorků zadání hry ve zdroji:",
"_____no_output_____"
]
],
[
[
"print(len(source))",
"8\n"
]
],
[
[
"Rozměry hrací desky pro jedem vzorek s pořadovým číslem 1:",
"_____no_output_____"
]
],
[
[
"print(source.shape(1))",
"(4, 4)\n"
]
],
[
[
"Zadání pro jeden vzorek ve formě pole (pořadové číslo 1):",
"_____no_output_____"
]
],
[
[
"print(source.board(1))",
"[[0 0 0 4]\n [0 8 0 0]\n [0 0 4 0]\n [0 0 0 0]]\n"
]
],
[
[
"Zdrojová data vzorku s pořadovým číslem 1, jedná se o souřadnice na desce a hodnotu políčka:",
"_____no_output_____"
]
],
[
[
"print(source.data(1))",
"[((0, 3), 4), ((1, 1), 8), ((2, 2), 4)]\n"
]
],
[
[
"# Řešení s pomocí backtracking\nNejdříve se pokusím na to jít tak, jak by asi každý očekával. Prostě budu zkoušet kombinace obdélníků, dokud nenajdu přijatelné řešení.",
"_____no_output_____"
],
[
"## Přípravné práce\nBude asi dobré si připravit nějaké nástroje pro práci s obdélníky. Proto jsem si vytvořil jednu třídu `Rectangle` a nějaké pomocné funkce pro práci s nimi.",
"_____no_output_____"
]
],
[
[
"class Rectangle:\n\n def __init__(self, corner, shape, board_shape):\n if not all((0 <= corner[i] < board_shape[0] and 0 < shape[i] <= board_shape[i] for i in (0, 1))):\n raise ValueError('coordinates are invalid')\n if not all((0 <= corner[i] + shape[i] <= board_shape[i] for i in (0, 1))):\n raise ValueError('coordinates are invalid')\n self.corner, self.shape, self.board_shape = corner, shape, board_shape\n\n def __iter__(self):\n yield self.corner\n yield self.shape\n\n def __eq__(self, other):\n return isinstance(other, type(self)) and tuple(self) == tuple(other)\n\n def __ne__(self, other):\n return not (self == other)\n\n def __lt__(self, other):\n return tuple(self) < tuple(other)\n\n def __repr__(self):\n return type(self).__name__ + repr(tuple(self))\n\n def inside(self, position):\n return all((self.corner[i] <= position[i] < self.corner[i] + self.shape[i] for i in (0, 1)))\n\n def slice(self):\n return tuple((slice(self.corner[i], self.corner[i] + self.shape[i]) for i in (0, 1)))\n\n def board(self):\n b = np.zeros(self.board_shape, dtype=int)\n b[slice()] = 1\n return b",
"_____no_output_____"
]
],
[
[
"Nejdříve funkce pro výpočet rozměrů obdélníků tak, aby měly požadovanou plochu.\n\nParametrem je kromě plochy obdélníka také velikost hrací desky, neb nechci řešit obdélníky, které by se mně na desku vůbec nevešly.",
"_____no_output_____"
]
],
[
[
"def dimensions_for_area(area, board_shape):\n for i in range(1, area + 1):\n if area % i == 0:\n rows, cols = i, area // i\n if rows <= board_shape[0] and cols <= board_shape[0]:\n yield rows, cols\n \nprint(list(dimensions_for_area(8, (4, 4))))",
"[(2, 4), (4, 2)]\n"
]
],
[
[
"Úkolem další funkce bude najít všechny přijatelné obdélníky pro konkrétní pozici na desce tak, aby obdélníky měly požadované rozměry a na desku se vešly.\n\nParametry funkce jsou:\n* pozice na desce, vůči které se obdélníky vztahují (každý obdélník musí tuto ozici obsahovat)\n* požadované rozměry obdélníku\n* velikost hrací desky\n\nVýsledkem je generátor takových obdélníků.",
"_____no_output_____"
]
],
[
[
"def rectangles_for_position(position, shape, board_shape):\n for i in (a for a in range(max(position[0] - (shape[0] - 1), 0), position[0] + 1) if a + shape[0] <= board_shape[0]):\n for j in (b for b in range(max(position[1] - (shape[1] - 1), 0), position[1] + 1) if b + shape[1] <= board_shape[1]):\n yield Rectangle((i, j), shape, board_shape)\n\nprint(list(rectangles_for_position((2, 2), (1, 4), (4, 4))))\nprint(list(rectangles_for_position((2, 2), (4, 1), (4, 4))))",
"[Rectangle((2, 0), (1, 4))]\n[Rectangle((0, 2), (4, 1))]\n"
]
],
[
[
"Spojením dvou výše uvedených funkci jsem nyní schopen napsat funkci, která mně vrátí všechny přijatelné obdélníky pro pozici s uvedením požadované plochy\n\nParametry funkce:\n* pozice na desce, vůči které se obdélníky vztahují\n* požadovaná plocha obdélníku\n* velikost hrací desky\n\nVýsledkem je opět generátor obdélníků, které vyhovují požadavkům.",
"_____no_output_____"
]
],
[
[
"def all_for_position(position, area, board_shape):\n for shape in dimensions_for_area(area, board_shape):\n for rect in rectangles_for_position(position, shape, board_shape):\n yield rect\n\nprint(list(all_for_position((2, 2), 4, (4, 4))))",
"[Rectangle((2, 0), (1, 4)), Rectangle((1, 1), (2, 2)), Rectangle((1, 2), (2, 2)), Rectangle((2, 1), (2, 2)), Rectangle((2, 2), (2, 2)), Rectangle((0, 2), (4, 1))]\n"
]
],
[
[
"Poslední funkcí z této části bude funkce, která mně ze všech obdélníků přijatelných pro jednu pozici vybere pouze ty obdélníky, které neobsahují pozice jiných obdélníků (to je to pravidlo, že pozice s číslem může ležet pouze v jednom obdélníku).\n\nParametry funkce:\n* pozice na desce, vůči které se obdélníky vztahují\n* požadovaná plocha obdélníku\n* zdrojová data pro jedno zadání hry\n* velikost hrací desky\n\nVýsledkem je generátor takových obdélníků.",
"_____no_output_____"
]
],
[
[
"def possible_for_position(position, area, data, board_shape):\n for rect in all_for_position(position, area, board_shape):\n if all((not rect.inside(p) for p, v in data if p != position)):\n yield rect\n \nprint(list(possible_for_position((2, 2), 4, source.data(1), (4, 4)))) ",
"[Rectangle((2, 0), (1, 4)), Rectangle((1, 2), (2, 2)), Rectangle((2, 1), (2, 2)), Rectangle((2, 2), (2, 2)), Rectangle((0, 2), (4, 1))]\n"
]
],
[
[
"## Řešení\nA nyní již vlastní řešení pomocí backtrack. \n\nPro vyhodnocení, zda se mně obdélníky překrývají, budu používat numpy pole.\n\nBudu postupně procházet všechna zadání. Pro každé zadání pak:\n1. nejdříve vytisknu zadání\n1. vytvořím si prázdnou desku\n1. pro každou pozici zadání vytvořím seznam všech přijatelných obdélniků\n1. spustím funkci `solve()`, která:\n- postupně prochází všechny přijatelné obdélníky pro pozici\n- obdélník promitne na desku\n- pokud na desce není konflik, pokračuje rekurzivně na další pozici\n5. v případě, že jsem nějaké řešení našel, tak jej vytisknu\n\nVýsledek uvidíte po spuštění:",
"_____no_output_____"
]
],
[
[
"for sample in range(len(source)):\n print(source.board(sample))\n print('.' * 40)\n\n board = np.zeros(source.shape(sample), dtype=int)\n\n possible_rectangles = []\n for pos, val in source.data(sample):\n possible_rectangles.append(list(possible_for_position(pos, val, source.data(sample), source.shape(sample))))\n\n def solve(index=0):\n if index >= len(possible_rectangles):\n return True, []\n for rec in possible_rectangles[index]:\n board[rec.slice()] += 1\n if (board <= 1).all():\n ok, result = solve(index + 1)\n if ok:\n result.insert(0, rec)\n return True, result\n board[rec.slice()] -= 1\n else:\n return False, None\n\n ok, result = solve()\n if ok:\n b = np.zeros(source.shape(sample), dtype=int)\n for val, rec in enumerate(result):\n b[rec.slice()] += 1\n if (b == 1).all():\n b = np.zeros(source.shape(sample), dtype=object)\n for val, rec in enumerate(result):\n b[rec.slice()] = chr(ord('A') + val)\n print(b)\n else:\n print(\"SOLUTION IS NOT VALID\")\n\n print()\n print('=' * 40)\n print()",
"[[0 2]\n [2 0]]\n........................................\n[['A' 'A']\n ['B' 'B']]\n\n========================================\n\n[[0 0 0 4]\n [0 8 0 0]\n [0 0 4 0]\n [0 0 0 0]]\n........................................\n[['B' 'B' 'A' 'A']\n ['B' 'B' 'A' 'A']\n ['B' 'B' 'C' 'C']\n ['B' 'B' 'C' 'C']]\n\n========================================\n\n[[2 0 0 0 0]\n [0 0 2 0 4]\n [0 0 3 2 0]\n [0 4 0 2 0]\n [4 0 0 2 0]]\n........................................\n[['A' 'A' 'B' 'C' 'C']\n ['H' 'F' 'B' 'C' 'C']\n ['H' 'F' 'D' 'E' 'E']\n ['H' 'F' 'D' 'G' 'G']\n ['H' 'F' 'D' 'I' 'I']]\n\n========================================\n\n[[0 0 2 0 0]\n [5 2 0 0 0]\n [0 3 2 0 0]\n [0 0 0 3 4]\n [0 0 2 0 2]]\n........................................\n[['B' 'C' 'A' 'A' 'G']\n ['B' 'C' 'E' 'F' 'G']\n ['B' 'D' 'E' 'F' 'G']\n ['B' 'D' 'H' 'F' 'G']\n ['B' 'D' 'H' 'I' 'I']]\n\n========================================\n\n[[0 0 0 0 0 0 6]\n [2 0 0 3 0 0 0]\n [0 3 0 0 0 6 0]\n [0 0 0 0 0 3 0]\n [3 6 0 0 0 3 0]\n [0 5 0 0 0 2 0]\n [2 0 0 0 3 2 0]]\n........................................\n[['B' 'A' 'A' 'A' 'A' 'A' 'A']\n ['B' 'C' 'C' 'C' 'E' 'E' 'E']\n ['G' 'D' 'D' 'D' 'E' 'E' 'E']\n ['G' 'H' 'H' 'H' 'F' 'F' 'F']\n ['G' 'H' 'H' 'H' 'I' 'I' 'I']\n ['J' 'J' 'J' 'J' 'J' 'K' 'K']\n ['L' 'L' 'M' 'M' 'M' 'N' 'N']]\n\n========================================\n\n[[0 0 3 0 2 0 0]\n [0 0 5 0 0 0 0]\n [0 3 0 0 0 0 0]\n [0 2 0 4 4 0 4]\n [0 0 2 0 0 0 2]\n [2 2 2 0 0 6 0]\n [0 2 0 0 2 2 0]]\n........................................\n[['A' 'A' 'A' 'B' 'B' 'N' 'H']\n ['C' 'C' 'C' 'C' 'C' 'N' 'H']\n ['D' 'D' 'D' 'F' 'G' 'N' 'H']\n ['E' 'E' 'I' 'F' 'G' 'N' 'H']\n ['K' 'L' 'I' 'F' 'G' 'N' 'J']\n ['K' 'L' 'M' 'F' 'G' 'N' 'J']\n ['O' 'O' 'M' 'P' 'P' 'Q' 'Q']]\n\n========================================\n\n[[ 0 0 0 4 0 0 2 0 0 0]\n [ 3 0 0 2 0 0 6 0 4 0]\n [ 0 4 0 0 0 0 0 0 4 8]\n [ 0 0 4 0 15 0 0 0 0 0]\n [ 2 0 0 0 0 0 0 2 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 4 0 12 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 3 0]\n [ 0 2 0 0 5 0 0 4 2 0]\n [ 0 0 2 0 0 0 6 0 0 0]]\n........................................\n[['C' 'A' 'A' 'A' 'A' 'B' 'B' 'F' 'F' 'I']\n ['C' 'G' 'G' 'D' 'E' 'E' 'E' 'F' 'F' 'I']\n ['C' 'G' 'G' 'D' 'E' 'E' 'E' 'H' 'H' 'I']\n ['J' 'J' 'J' 'J' 'K' 'K' 'K' 'H' 'H' 'I']\n ['L' 'O' 'O' 'O' 'K' 'K' 'K' 'M' 'M' 'I']\n ['L' 'O' 'O' 'O' 'K' 'K' 'K' 'S' 'P' 'I']\n ['N' 'O' 'O' 'O' 'K' 'K' 'K' 'S' 'P' 'I']\n ['N' 'O' 'O' 'O' 'K' 'K' 'K' 'S' 'P' 'I']\n ['N' 'Q' 'R' 'R' 'R' 'R' 'R' 'S' 'T' 'T']\n ['N' 'Q' 'U' 'U' 'V' 'V' 'V' 'V' 'V' 'V']]\n\n========================================\n\n[[ 0 0 4 0 0 0 2 6 0 0]\n [ 0 0 0 0 0 5 0 0 0 0]\n [ 0 0 2 0 3 0 3 0 0 0]\n [ 0 0 0 0 0 0 0 2 4 0]\n [ 9 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 12 0 0 0 0 9 0]\n [ 0 4 0 0 0 0 0 0 0 3]\n [ 0 0 0 12 0 0 0 0 0 0]\n [ 0 2 0 0 0 0 4 0 4 0]\n [ 0 0 0 7 0 0 0 0 3 0]]\n........................................\n[['J' 'A' 'A' 'A' 'A' 'B' 'B' 'C' 'C' 'C']\n ['J' 'D' 'D' 'D' 'D' 'D' 'G' 'C' 'C' 'C']\n ['J' 'E' 'E' 'F' 'F' 'F' 'G' 'H' 'I' 'I']\n ['J' 'M' 'K' 'K' 'K' 'K' 'G' 'H' 'I' 'I']\n ['J' 'M' 'K' 'K' 'K' 'K' 'L' 'L' 'L' 'N']\n ['J' 'M' 'K' 'K' 'K' 'K' 'L' 'L' 'L' 'N']\n ['J' 'M' 'O' 'O' 'O' 'O' 'L' 'L' 'L' 'N']\n ['J' 'P' 'O' 'O' 'O' 'O' 'Q' 'Q' 'R' 'R']\n ['J' 'P' 'O' 'O' 'O' 'O' 'Q' 'Q' 'R' 'R']\n ['S' 'S' 'S' 'S' 'S' 'S' 'S' 'T' 'T' 'T']]\n\n========================================\n\n"
]
],
[
[
"# Řešení s využitím OR-Tools\n\nJako základ celého řešení je vytvoření modelu hry s využitím připravených nástrojů z knihovny OR-Tools. ",
"_____no_output_____"
]
],
[
[
"from ortools.sat.python import cp_model",
"_____no_output_____"
]
],
[
[
"Tímto modelem je třída, která je potomkem třídy `CpSolverSolutionCallback`. \n\nVlastní nastavení modelu se děje v metodě `__init__`. ",
"_____no_output_____"
]
],
[
[
"class GameBoard(cp_model.CpSolverSolutionCallback):\n\n def __init__(self, data, board_shape):\n cp_model.CpSolverSolutionCallback.__init__(self)\n self.model = cp_model.CpModel()\n\n self.shape = board_shape\n self.rectangles = []\n intervals_x, intervals_y = [], []\n\n for i, ((x, y), val) in enumerate(data):\n x1, y1 = self.model.NewIntVar(0, x, f\"X1:{i}\"), self.model.NewIntVar(0, y, f\"Y1:{i}\")\n x2, y2 = self.model.NewIntVar(x, board_shape[0] - 1, f\"X2:{i}\"), self.model.NewIntVar(y, board_shape[1] - 1, f\"Y2:{i}\")\n self.rectangles.append((x1, y1, x2, y2))\n\n size_x = self.model.NewIntVar(1, board_shape[0], f\"dimX:{i}\")\n size_y = self.model.NewIntVar(1, board_shape[1], f\"dimY:{i}\")\n\n self.model.Add(x1 + size_x <= board_shape[0])\n self.model.Add(y1 + size_y <= board_shape[1])\n\n self.model.Add(x1 + size_x > x)\n self.model.Add(y1 + size_y > y)\n\n self.model.AddMultiplicationEquality(val, [size_x, size_y])\n\n intervals_x.append(self.model.NewIntervalVar(x1, size_x, x2 + 1, f\"IX:{i}\"))\n intervals_y.append(self.model.NewIntervalVar(y1, size_y, y2 + 1, f\"IY:{i}\"))\n\n self.model.AddNoOverlap2D(intervals_x, intervals_y)\n\n def OnSolutionCallback(self):\n a = np.zeros(self.shape, dtype=object)\n for i, (x1, y1, x2, y2) in enumerate(self.rectangles):\n x1, y1, x2, y2 = self.Value(x1), self.Value(y1), self.Value(x2), self.Value(y2)\n a[x1:x2+1, y1:y2+1] = chr(ord('A') + i)\n print(a)\n self.StopSearch()\n\n def solve(self):\n cp_model.CpSolver().SearchForAllSolutions(self.model, self)",
"_____no_output_____"
]
],
[
[
"## Nastavení modelu\nParametry pro nastavení modelu jsou zdrojová data zadání hry a velikost hrací desky.\n\nPři nastavení proměnných modelu a omezení budu postupně procházet zadání pro všechny obdélníky.\n\n### Proměnné pro obdélníky\nV mém modelu bude každý obdélník představován levým-horním a pravým-dolním rohem (proměnné x1, y1, x2 a y2).\nSoučasně je u každé proměnné omezení hodnot tak, aby bylo zajištěno, že (x1, y1) <= (x, y) a (x2, y2) >= (x, y).\n\nDále mám vytvořené proměnné představující velikost strany obdélníku, size_x a size_y. Pro ně je nastaveno omezení, že nesmí přesáhnout velikost hrací desky.\n\n### Omezení pro obdélníky\nDo modelu jsem doplnil omezení pro levý-horní roh a velikost strany obdélníku. Jejich součet nesmí přesáhnout hranice hrací desky.\n\nA také je zde omezení, že součet levého-horního rohu a velikosti obdélníku musí zajistit zahrnutí referenční pozice obdélníku v zadání. \n\nPosledním omezením, které se vztahuje k jednomu obdélníku, je požadavek na velikost jeho plochy jako součin velikosti jeho stran.\n\n### Intervaly obdélníků v osách\nAbych mohl zajistit to, že se mně obdélníky nebudou překrývat, potřebuji vytvořit ještě jednu sadu proměnných. \nJsou to tzv. intervaly a představují vztah mezi souřadnicemi obdélníku a velikostí jeho stran.\n\nVšechny intervaly si přidám do dvou polí, protože v této podobě je budu potřebovat pro poslední omezení.\n\n### Omezení na překryv obdélníků\nPoslední, co potřebuji zajistit je omezení, aby se mně dva obdélníky nepřekrývaly.\n\nToho můžu docílit pomocí metody `AddNoOverlap2D`, která jako parametry potřebuje právě pole intervalů v osách x a y.",
"_____no_output_____"
],
[
"## Výkonné metody \n\nVe třídě `GameBoard` mám definovány ještě dvě metody:\n\nMetoda **OnSolutionCallback** se zavolá, když solver najde nějaké řešení. V mém případě si vyzvednu rohy všech obdélníků, promítnu je do numpy pole a vytisknu.\n\nNásledně pak ještě vyvolám zastavení činnosti solveru. To proto, že mne bude zajímat pouze první nalezené řešení. \n\nMetoda **solve** zajistí vyvolání vlastního solveru nad modelem. To je tedy ta výkonná část celého řešení.\n\nA to je co se týká vytvoření modelu a jeho řešení vše potřebné. Následuje již pouze vyzkoušení, jak to celé funguje.",
"_____no_output_____"
],
[
"## Vyzkoušení řešení hry\n\nProjdu všechna zadání hry a spustím na ně řešení. No a pak se uvidí.",
"_____no_output_____"
]
],
[
[
"for sample in range(len(source)):\n print(source.board(sample))\n print('.' * 40)\n\n board = GameBoard(source.data(sample), source.shape(sample))\n board.solve()\n\n print()\n print('=' * 40)\n print()",
"[[0 2]\n [2 0]]\n........................................\n[['B' 'A']\n ['B' 'A']]\n\n========================================\n\n[[0 0 0 4]\n [0 8 0 0]\n [0 0 4 0]\n [0 0 0 0]]\n........................................\n[['B' 'B' 'C' 'A']\n ['B' 'B' 'C' 'A']\n ['B' 'B' 'C' 'A']\n ['B' 'B' 'C' 'A']]\n\n========================================\n\n[[2 0 0 0 0]\n [0 0 2 0 4]\n [0 0 3 2 0]\n [0 4 0 2 0]\n [4 0 0 2 0]]\n........................................\n[['A' 'A' 'B' 'C' 'C']\n ['H' 'F' 'B' 'C' 'C']\n ['H' 'F' 'D' 'E' 'E']\n ['H' 'F' 'D' 'G' 'G']\n ['H' 'F' 'D' 'I' 'I']]\n\n========================================\n\n[[0 0 2 0 0]\n [5 2 0 0 0]\n [0 3 2 0 0]\n [0 0 0 3 4]\n [0 0 2 0 2]]\n........................................\n[['B' 'C' 'A' 'A' 'G']\n ['B' 'C' 'E' 'F' 'G']\n ['B' 'D' 'E' 'F' 'G']\n ['B' 'D' 'H' 'F' 'G']\n ['B' 'D' 'H' 'I' 'I']]\n\n========================================\n\n[[0 0 0 0 0 0 6]\n [2 0 0 3 0 0 0]\n [0 3 0 0 0 6 0]\n [0 0 0 0 0 3 0]\n [3 6 0 0 0 3 0]\n [0 5 0 0 0 2 0]\n [2 0 0 0 3 2 0]]\n........................................\n[['B' 'A' 'A' 'A' 'A' 'A' 'A']\n ['B' 'C' 'C' 'C' 'E' 'E' 'E']\n ['G' 'D' 'D' 'D' 'E' 'E' 'E']\n ['G' 'H' 'H' 'H' 'F' 'F' 'F']\n ['G' 'H' 'H' 'H' 'I' 'I' 'I']\n ['J' 'J' 'J' 'J' 'J' 'K' 'K']\n ['L' 'L' 'M' 'M' 'M' 'N' 'N']]\n\n========================================\n\n[[0 0 3 0 2 0 0]\n [0 0 5 0 0 0 0]\n [0 3 0 0 0 0 0]\n [0 2 0 4 4 0 4]\n [0 0 2 0 0 0 2]\n [2 2 2 0 0 6 0]\n [0 2 0 0 2 2 0]]\n........................................\n[['A' 'A' 'A' 'B' 'B' 'N' 'H']\n ['C' 'C' 'C' 'C' 'C' 'N' 'H']\n ['D' 'D' 'D' 'F' 'G' 'N' 'H']\n ['E' 'E' 'I' 'F' 'G' 'N' 'H']\n ['K' 'L' 'I' 'F' 'G' 'N' 'J']\n ['K' 'L' 'M' 'F' 'G' 'N' 'J']\n ['O' 'O' 'M' 'P' 'P' 'Q' 'Q']]\n\n========================================\n\n[[ 0 0 0 4 0 0 2 0 0 0]\n [ 3 0 0 2 0 0 6 0 4 0]\n [ 0 4 0 0 0 0 0 0 4 8]\n [ 0 0 4 0 15 0 0 0 0 0]\n [ 2 0 0 0 0 0 0 2 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 4 0 12 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 3 0]\n [ 0 2 0 0 5 0 0 4 2 0]\n [ 0 0 2 0 0 0 6 0 0 0]]\n........................................\n[['C' 'A' 'A' 'A' 'A' 'B' 'B' 'F' 'F' 'I']\n ['C' 'G' 'G' 'D' 'E' 'E' 'E' 'F' 'F' 'I']\n ['C' 'G' 'G' 'D' 'E' 'E' 'E' 'H' 'H' 'I']\n ['J' 'J' 'J' 'J' 'K' 'K' 'K' 'H' 'H' 'I']\n ['L' 'O' 'O' 'O' 'K' 'K' 'K' 'M' 'M' 'I']\n ['L' 'O' 'O' 'O' 'K' 'K' 'K' 'S' 'P' 'I']\n ['N' 'O' 'O' 'O' 'K' 'K' 'K' 'S' 'P' 'I']\n ['N' 'O' 'O' 'O' 'K' 'K' 'K' 'S' 'P' 'I']\n ['N' 'Q' 'R' 'R' 'R' 'R' 'R' 'S' 'T' 'T']\n ['N' 'Q' 'U' 'U' 'V' 'V' 'V' 'V' 'V' 'V']]\n\n========================================\n\n[[ 0 0 4 0 0 0 2 6 0 0]\n [ 0 0 0 0 0 5 0 0 0 0]\n [ 0 0 2 0 3 0 3 0 0 0]\n [ 0 0 0 0 0 0 0 2 4 0]\n [ 9 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 12 0 0 0 0 9 0]\n [ 0 4 0 0 0 0 0 0 0 3]\n [ 0 0 0 12 0 0 0 0 0 0]\n [ 0 2 0 0 0 0 4 0 4 0]\n [ 0 0 0 7 0 0 0 0 3 0]]\n........................................\n[['J' 'A' 'A' 'A' 'A' 'B' 'B' 'C' 'C' 'C']\n ['J' 'D' 'D' 'D' 'D' 'D' 'G' 'C' 'C' 'C']\n ['J' 'E' 'E' 'F' 'F' 'F' 'G' 'H' 'I' 'I']\n ['J' 'M' 'K' 'K' 'K' 'K' 'G' 'H' 'I' 'I']\n ['J' 'M' 'K' 'K' 'K' 'K' 'L' 'L' 'L' 'N']\n ['J' 'M' 'K' 'K' 'K' 'K' 'L' 'L' 'L' 'N']\n ['J' 'M' 'O' 'O' 'O' 'O' 'L' 'L' 'L' 'N']\n ['J' 'P' 'O' 'O' 'O' 'O' 'Q' 'Q' 'R' 'R']\n ['J' 'P' 'O' 'O' 'O' 'O' 'Q' 'Q' 'R' 'R']\n ['S' 'S' 'S' 'S' 'S' 'S' 'S' 'T' 'T' 'T']]\n\n========================================\n\n"
]
],
[
[
"A to je vše.",
"_____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"
] |
[
[
"markdown",
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aafb90f56c137ed2fc368368321e88889060605
| 440,512 |
ipynb
|
Jupyter Notebook
|
Running - MD - Integration methods.ipynb
|
jennyfothergill/hoomd-examples
|
0e21f63a06a3ef6f69eb565799f5ff5a218bbb36
|
[
"BSD-3-Clause"
] | 12 |
2016-12-05T14:21:32.000Z
|
2022-03-30T17:38:53.000Z
|
Running - MD - Integration methods.ipynb
|
jennyfothergill/hoomd-examples
|
0e21f63a06a3ef6f69eb565799f5ff5a218bbb36
|
[
"BSD-3-Clause"
] | 1 |
2017-03-13T08:11:20.000Z
|
2017-04-04T00:22:05.000Z
|
Running - MD - Integration methods.ipynb
|
jennyfothergill/hoomd-examples
|
0e21f63a06a3ef6f69eb565799f5ff5a218bbb36
|
[
"BSD-3-Clause"
] | 10 |
2017-03-21T13:54:42.000Z
|
2021-09-17T12:53:23.000Z
| 2,917.298013 | 436,104 | 0.914454 |
[
[
[
"import hoomd\nimport hoomd.md\nimport ex_render",
"_____no_output_____"
],
[
"hoomd.context.initialize('--mode=cpu');\nsystem = hoomd.init.create_lattice(unitcell=hoomd.lattice.sq(a=1.05), n=10);\nd = hoomd.dump.gsd(\"trajectory.gsd\", period=50, group=hoomd.group.all(), overwrite=True);\nnl = hoomd.md.nlist.cell();\nlj = hoomd.md.pair.lj(r_cut=3.0, nlist=nl);\nlj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0);",
"HOOMD-blue v2.1.8 CUDA (7.5) DOUBLE HPMC_MIXED MPI SSE SSE2 SSE3 \nCompiled: 07/21/2017\nCopyright 2009-2016 The Regents of the University of Michigan.\n-----\nYou are using HOOMD-blue. Please cite the following:\n* J A Anderson, C D Lorenz, and A Travesset. \"General purpose molecular dynamics\n simulations fully implemented on graphics processing units\", Journal of\n Computational Physics 227 (2008) 5342--5359\n* J Glaser, T D Nguyen, J A Anderson, P Liu, F Spiga, J A Millan, D C Morse, and\n S C Glotzer. \"Strong scaling of general-purpose molecular dynamics simulations\n on GPUs\", Computer Physics Communications 192 (2015) 97--107\n-----\nHOOMD-blue is running on the CPU\nnotice(2): Group \"all\" created containing 100 particles\n"
]
],
[
[
"# Integration methods\n\nApply any number of different integration methods to different groups of particles. For example, integrate only a portion of the system to leave a fixed wall built of particles.",
"_____no_output_____"
]
],
[
[
"hoomd.md.integrate.mode_standard(dt=0.005);\nhoomd.md.integrate.langevin(group=hoomd.group.tags(0,79), kT=1.0, seed=2);",
"notice(2): Group \"tags 0-79\" created containing 80 particles\nnotice(2): integrate.langevin/bd is using specified gamma values\n"
]
],
[
[
"Examine how the system configuration evolves over time. [ex_render](ex_render.py) is a helper script that builds animated gifs from trajectory files and system snapshots. It is part of the [hoomd-examples](https://github.com/glotzerlab/hoomd-examples) repository and designed only to render these examples.",
"_____no_output_____"
]
],
[
[
"hoomd.run(300, quiet=True);\nex_render.display_movie(ex_render.render_disk_frame, 'trajectory.gsd')",
"notice(2): -- Neighborlist exclusion statistics -- :\nnotice(2): Particles with 0 exclusions : 100\nnotice(2): Neighbors included by diameter : no\nnotice(2): Neighbors excluded when in the same body: no\n"
]
],
[
[
"## Other types of integration methods\n\nHOOMD supports Velocity-Verlet (nve), the Nosé-Hoover thermostat (nvt), the Martyna-Tobias-Klein barostat (npt, nph), langevin, brownian, berendsen, and other integration methods",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aafea1384ec0e3c4cc17333f21f47cdf0806739
| 35,400 |
ipynb
|
Jupyter Notebook
|
Real_Data/Buenrostro_2018/run_clustering_buenrostro2018.ipynb
|
DaneseAnna/scATAC-benchmarking
|
b85fd3bdc1594028110222a5a0317e6ecf3761e9
|
[
"MIT"
] | 2 |
2019-12-02T13:01:35.000Z
|
2019-12-02T15:55:07.000Z
|
Real_Data/Buenrostro_2018/run_clustering_buenrostro2018.ipynb
|
huidongchen/scATAC-benchmarking
|
31d71d60536e8f4bf5bae314630013feaff3caf2
|
[
"MIT"
] | null | null | null |
Real_Data/Buenrostro_2018/run_clustering_buenrostro2018.ipynb
|
huidongchen/scATAC-benchmarking
|
31d71d60536e8f4bf5bae314630013feaff3caf2
|
[
"MIT"
] | null | null | null | 35.223881 | 312 | 0.507627 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport scanpy as sc\nimport os\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.metrics.cluster import adjusted_rand_score\nfrom sklearn.metrics.cluster import adjusted_mutual_info_score\nfrom sklearn.metrics.cluster import homogeneity_score\nimport rpy2.robjects as robjects\nfrom rpy2.robjects import pandas2ri",
"_____no_output_____"
],
[
"df_metrics = pd.DataFrame(columns=['ARI_Louvain','ARI_kmeans','ARI_HC',\n 'AMI_Louvain','AMI_kmeans','AMI_HC',\n 'Homogeneity_Louvain','Homogeneity_kmeans','Homogeneity_HC'])",
"_____no_output_____"
],
[
"workdir = './output/'\npath_fm = os.path.join(workdir,'feature_matrices/')\npath_clusters = os.path.join(workdir,'clusters/')\npath_metrics = os.path.join(workdir,'metrics/')\nos.system('mkdir -p '+path_clusters)\nos.system('mkdir -p '+path_metrics)",
"_____no_output_____"
],
[
"metadata = pd.read_csv('./input/metadata.tsv',sep='\\t',index_col=0)\nnum_clusters = len(np.unique(metadata['label']))\nprint(num_clusters)",
"10\n"
],
[
"files = [x for x in os.listdir(path_fm) if x.startswith('FM')]\nlen(files)",
"_____no_output_____"
],
[
"files",
"_____no_output_____"
],
[
"def getNClusters(adata,n_cluster,range_min=0,range_max=3,max_steps=20):\n this_step = 0\n this_min = float(range_min)\n this_max = float(range_max)\n while this_step < max_steps:\n print('step ' + str(this_step))\n this_resolution = this_min + ((this_max-this_min)/2)\n sc.tl.louvain(adata,resolution=this_resolution)\n this_clusters = adata.obs['louvain'].nunique()\n \n print('got ' + str(this_clusters) + ' at resolution ' + str(this_resolution))\n \n if this_clusters > n_cluster:\n this_max = this_resolution\n elif this_clusters < n_cluster:\n this_min = this_resolution\n else:\n return(this_resolution, adata)\n this_step += 1\n \n print('Cannot find the number of clusters')\n print('Clustering solution from last iteration is used:' + str(this_clusters) + ' at resolution ' + str(this_resolution))",
"_____no_output_____"
],
[
"for file in files:\n file_split = file.split('_')\n method = file_split[1]\n dataset = file_split[2].split('.')[0]\n if(len(file_split)>3):\n method = method + '_' + '_'.join(file_split[3:]).split('.')[0]\n print(method)\n\n pandas2ri.activate()\n readRDS = robjects.r['readRDS']\n df_rds = readRDS(os.path.join(path_fm,file))\n fm_mat = pandas2ri.ri2py(robjects.r['data.frame'](robjects.r['as.matrix'](df_rds)))\n fm_mat.fillna(0,inplace=True)\n fm_mat.columns = metadata.index\n \n adata = sc.AnnData(fm_mat.T)\n adata.var_names_make_unique()\n adata.obs = metadata.loc[adata.obs.index,]\n df_metrics.loc[method,] = \"\"\n #Louvain\n sc.pp.neighbors(adata, n_neighbors=15,use_rep='X')\n# sc.tl.louvain(adata)\n getNClusters(adata,n_cluster=num_clusters)\n #kmeans\n kmeans = KMeans(n_clusters=num_clusters, random_state=2019).fit(adata.X)\n adata.obs['kmeans'] = pd.Series(kmeans.labels_,index=adata.obs.index).astype('category')\n #hierachical clustering\n hc = AgglomerativeClustering(n_clusters=num_clusters).fit(adata.X)\n adata.obs['hc'] = pd.Series(hc.labels_,index=adata.obs.index).astype('category')\n #clustering metrics\n \n #adjusted rank index\n ari_louvain = adjusted_rand_score(adata.obs['label'], adata.obs['louvain'])\n ari_kmeans = adjusted_rand_score(adata.obs['label'], adata.obs['kmeans'])\n ari_hc = adjusted_rand_score(adata.obs['label'], adata.obs['hc'])\n #adjusted mutual information\n ami_louvain = adjusted_mutual_info_score(adata.obs['label'], adata.obs['louvain'],average_method='arithmetic')\n ami_kmeans = adjusted_mutual_info_score(adata.obs['label'], adata.obs['kmeans'],average_method='arithmetic') \n ami_hc = adjusted_mutual_info_score(adata.obs['label'], adata.obs['hc'],average_method='arithmetic')\n #homogeneity\n homo_louvain = homogeneity_score(adata.obs['label'], adata.obs['louvain'])\n homo_kmeans = homogeneity_score(adata.obs['label'], adata.obs['kmeans'])\n homo_hc = homogeneity_score(adata.obs['label'], adata.obs['hc'])\n\n df_metrics.loc[method,['ARI_Louvain','ARI_kmeans','ARI_HC']] = [ari_louvain,ari_kmeans,ari_hc]\n df_metrics.loc[method,['AMI_Louvain','AMI_kmeans','AMI_HC']] = [ami_louvain,ami_kmeans,ami_hc]\n df_metrics.loc[method,['Homogeneity_Louvain','Homogeneity_kmeans','Homogeneity_HC']] = [homo_louvain,homo_kmeans,homo_hc] \n adata.obs[['louvain','kmeans','hc']].to_csv(os.path.join(path_clusters ,method + '_clusters.tsv'),sep='\\t')",
"ChromVAR_motifs\n"
],
[
"df_metrics.to_csv(path_metrics+'clustering_scores.csv')",
"_____no_output_____"
],
[
"df_metrics",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aafeb609378837baddde2503f8bb30906a37556
| 18,687 |
ipynb
|
Jupyter Notebook
|
Analysing Ad Budgets for different media channels/WORK DONE/Analysing Ad Budgets for different media channels.ipynb
|
NeoWist/aiengineer-simplylearn-projects
|
6b0c2413c4882e8c711918b4541b6de1a5237f2e
|
[
"MIT"
] | null | null | null |
Analysing Ad Budgets for different media channels/WORK DONE/Analysing Ad Budgets for different media channels.ipynb
|
NeoWist/aiengineer-simplylearn-projects
|
6b0c2413c4882e8c711918b4541b6de1a5237f2e
|
[
"MIT"
] | null | null | null |
Analysing Ad Budgets for different media channels/WORK DONE/Analysing Ad Budgets for different media channels.ipynb
|
NeoWist/aiengineer-simplylearn-projects
|
6b0c2413c4882e8c711918b4541b6de1a5237f2e
|
[
"MIT"
] | null | null | null | 23.50566 | 224 | 0.410767 |
[
[
[
"<img src=\"http://cfs22.simplicdn.net/ice9/new_logo.svgz \"/>\n\n# Assignment 01: Evaluate the Ad Budget Dataset of XYZ Firm\n\n*The comments/sections provided are your cues to perform the assignment. You don't need to limit yourself to the number of rows/cells provided. You can add additional rows in each section to add more lines of code.*\n\n*If at any point in time you need help on solving this assignment, view our demo video to understand the different steps of the code.*\n\n**Happy coding!**\n\n* * *",
"_____no_output_____"
],
[
"#### 1: Import the dataset",
"_____no_output_____"
]
],
[
[
"#Import the required libraries\nimport pandas as pd",
"_____no_output_____"
],
[
"#Import the advertising dataset\ndf_adv_data = pd.read_csv('Advertising Budget and Sales.csv', index_col=0)",
"_____no_output_____"
]
],
[
[
"#### 2: Analyze the dataset",
"_____no_output_____"
]
],
[
[
"#View the initial few records of the dataset\ndf_adv_data.head()",
"_____no_output_____"
],
[
"#Check the total number of elements in the dataset\ndf_adv_data.size",
"_____no_output_____"
]
],
[
[
"#### 3: Find the features or media channels used by the firm",
"_____no_output_____"
]
],
[
[
"#Check the number of observations (rows) and attributes (columns) in the dataset\ndf_adv_data.shape",
"_____no_output_____"
],
[
"#View the names of each of the attributes\ndf_adv_data.columns",
"_____no_output_____"
]
],
[
[
"#### 4: Create objects to train and test the model; find the sales figures for each channel",
"_____no_output_____"
]
],
[
[
"#Create a feature object from the columns\nX_feature = df_adv_data[['Newspaper Ad Budget ($)','Radio Ad Budget ($)','TV Ad Budget ($)']]",
"_____no_output_____"
],
[
"#View the feature object\nX_feature.head()",
"_____no_output_____"
],
[
"#Create a target object (Hint: use the sales column as it is the response of the dataset)\nY_target = df_adv_data[['Sales ($)']]",
"_____no_output_____"
],
[
"#View the target object\nY_target.head()",
"_____no_output_____"
],
[
"#Verify if all the observations have been captured in the feature object\nX_feature.shape",
"_____no_output_____"
],
[
"#Verify if all the observations have been captured in the target object\nY_target.shape",
"_____no_output_____"
]
],
[
[
"#### 5: Split the original dataset into training and testing datasets for the model",
"_____no_output_____"
]
],
[
[
"#Split the dataset (by default, 75% is the training data and 25% is the testing data)\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(X_feature,Y_target,random_state=1)",
"_____no_output_____"
],
[
"#Verify if the training and testing datasets are split correctly (Hint: use the shape() method)\nprint(x_train.shape)\nprint(x_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)",
"(150, 3)\n(50, 3)\n(150, 1)\n(50, 1)\n"
]
],
[
[
"#### 6: Create a model to predict the sales outcome",
"_____no_output_____"
]
],
[
[
"#Create a linear regression model\nfrom sklearn.linear_model import LinearRegression\nlinreg = LinearRegression()\nlinreg.fit(x_train,y_train)",
"_____no_output_____"
],
[
"#Print the intercept and coefficients \nprint(linreg.intercept_)\nprint(linreg.coef_)",
"[2.87696662]\n[[0.00345046 0.17915812 0.04656457]]\n"
],
[
"#Predict the outcome for the testing dataset\ny_pred = linreg.predict(x_test)\ny_pred",
"_____no_output_____"
]
],
[
[
"#### 7: Calculate the Mean Square Error (MSE)",
"_____no_output_____"
]
],
[
[
"#Import required libraries for calculating MSE (mean square error)\nfrom sklearn import metrics\nimport numpy as np",
"_____no_output_____"
],
[
"#Calculate the MSE\nprint(np.sqrt(metrics.mean_squared_error(y_test,y_pred)))",
"1.4046514230328957\n"
],
[
"print('True' , y_test.values[0:10])\nprint()\nprint('Pred' , y_pred[0:10])",
"True [[23.8]\n [16.6]\n [ 9.5]\n [14.8]\n [17.6]\n [25.5]\n [16.9]\n [12.9]\n [10.5]\n [17.1]]\n\nPred [[21.70910292]\n [16.41055243]\n [ 7.60955058]\n [17.80769552]\n [18.6146359 ]\n [23.83573998]\n [16.32488681]\n [13.43225536]\n [ 9.17173403]\n [17.333853 ]]\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.