markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Reset the `TF_CONFIG` environment variable, you'll see more about this later. | os.environ.pop('TF_CONFIG', None) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Be sure that the current directory is on python's path. This allows the notebook to import the files written by `%%writefile` later. | if '.' not in sys.path:
sys.path.insert(0, '.') | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Now import TensorFlow. | import tensorflow as tf | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Dataset and model definition Next create an `mnist.py` file with a simple model and dataset setup. This python file will be used by the worker-processes in this tutorial: | %%writefile mnist.py
import os
import tensorflow as tf
import numpy as np
def mnist_dataset(batch_size):
(x_train, y_train), _ = tf.keras.datasets.mnist.load_data()
# The `x` arrays are in uint8 and have values in the range [0, 255].
# You need to convert them to float32 with values in the range [0, 1]
x_trai... | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Try training the model for a small number of epochs and observe the results of a single worker to make sure everything works correctly. As training progresses, the loss should drop and the accuracy should increase. | import mnist
batch_size = 64
single_worker_dataset = mnist.mnist_dataset(batch_size)
single_worker_model = mnist.build_and_compile_cnn_model()
single_worker_model.fit(single_worker_dataset, epochs=3, steps_per_epoch=70) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Multi-worker ConfigurationNow let's enter the world of multi-worker training. In TensorFlow, the `TF_CONFIG` environment variable is required for training on multiple machines, each of which possibly has a different role. `TF_CONFIG` is a JSON string used to specify the cluster configuration on each worker that is par... | tf_config = {
'cluster': {
'worker': ['localhost:12345', 'localhost:23456']
},
'task': {'type': 'worker', 'index': 0}
} | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Here is the same `TF_CONFIG` serialized as a JSON string: | json.dumps(tf_config) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
There are two components of `TF_CONFIG`: `cluster` and `task`.* `cluster` is the same for all workers and provides information about the training cluster, which is a dict consisting of different types of jobs such as `worker`. In multi-worker training with `MultiWorkerMirroredStrategy`, there is usually one `worker` th... | os.environ['GREETINGS'] = 'Hello TensorFlow!' | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
You can access the environment variable from a subprocesses: | %%bash
echo ${GREETINGS} | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
In the next section, you'll use this to pass the `TF_CONFIG` to the worker subprocesses. You would never really launch your jobs this way, but it's sufficient for the purposes of this tutorial: To demonstrate a minimal multi-worker example. Choose the right strategyIn TensorFlow there are two main forms of distributed... | strategy = tf.distribute.MultiWorkerMirroredStrategy() | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Note: `TF_CONFIG` is parsed and TensorFlow's GRPC servers are started at the time `MultiWorkerMirroredStrategy()` is called, so the `TF_CONFIG` environment variable must be set before a `tf.distribute.Strategy` instance is created. Since `TF_CONFIG` is not set yet the above strategy is effectively single-worker trainin... | with strategy.scope():
# Model building/compiling need to be within `strategy.scope()`.
multi_worker_model = mnist.build_and_compile_cnn_model() | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Note: Currently there is a limitation in `MultiWorkerMirroredStrategy` where TensorFlow ops need to be created after the instance of strategy is created. If you see `RuntimeError: Collective ops must be configured at program startup`, try creating the instance of `MultiWorkerMirroredStrategy` at the beginning of the pr... | %%writefile main.py
import os
import json
import tensorflow as tf
import mnist
per_worker_batch_size = 64
tf_config = json.loads(os.environ['TF_CONFIG'])
num_workers = len(tf_config['cluster']['worker'])
strategy = tf.distribute.MultiWorkerMirroredStrategy()
global_batch_size = per_worker_batch_size * num_workers
... | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
In the code snippet above note that the `global_batch_size`, which gets passed to `Dataset.batch`, is set to `per_worker_batch_size * num_workers`. This ensures that each worker processes batches of `per_worker_batch_size` examples regardless of the number of workers. The current directory now contains both Python file... | %%bash
ls *.py | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
So json-serialize the `TF_CONFIG` and add it to the environment variables: | os.environ['TF_CONFIG'] = json.dumps(tf_config) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Now, you can launch a worker process that will run the `main.py` and use the `TF_CONFIG`: | # first kill any previous runs
%killbgscripts
%%bash --bg
python main.py &> job_0.log | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
There are a few things to note about the above command:1. It uses the `%%bash` which is a [notebook "magic"](https://ipython.readthedocs.io/en/stable/interactive/magics.html) to run some bash commands.2. It uses the `--bg` flag to run the `bash` process in the background, because this worker will not terminate. It wait... | import time
time.sleep(10) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Now look what's been output to the worker's logfile so far: | %%bash
cat job_0.log | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
The last line of the log file should say: `Started server with target: grpc://localhost:12345`. The first worker is now ready, and is waiting for all the other worker(s) to be ready to proceed. So update the `tf_config` for the second worker's process to pick up: | tf_config['task']['index'] = 1
os.environ['TF_CONFIG'] = json.dumps(tf_config) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Now launch the second worker. This will start the training since all the workers are active (so there's no need to background this process): | %%bash
python main.py | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Now if you recheck the logs written by the first worker you'll see that it participated in training that model: | %%bash
cat job_0.log | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Unsurprisingly this ran _slower_ than the the test run at the beginning of this tutorial. Running multiple workers on a single machine only adds overhead. The goal here was not to improve the training time, but only to give an example of multi-worker training. | # Delete the `TF_CONFIG`, and kill any background tasks so they don't affect the next section.
os.environ.pop('TF_CONFIG', None)
%killbgscripts | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Multi worker training in depthSo far this tutorial has demonstrated a basic multi-worker setup. The rest of this document looks in detail other factors which may be useful or important for real use cases. Dataset shardingIn multi-worker training, dataset sharding is needed to ensure convergence and performance.The ex... | options = tf.data.Options()
options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
global_batch_size = 64
multi_worker_dataset = mnist.mnist_dataset(batch_size=64)
dataset_no_auto_shard = multi_worker_dataset.with_options(options) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
EvaluationIf you pass `validation_data` into `model.fit`, it will alternate between training and evaluation for each epoch. The evaluation taking `validation_data` is distributed across the same set of workers and the evaluation results are aggregated and available for all workers. Similar to training, the validation ... | model_path = '/tmp/keras-model'
def _is_chief(task_type, task_id):
# Note: there are two possible `TF_CONFIG` configuration.
# 1) In addition to `worker` tasks, a `chief` task type is use;
# in this case, this function should be modified to
# `return task_type == 'chief'`.
# 2) Only `worker` t... | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
With that, you're now ready to save: | multi_worker_model.save(write_model_path) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
As described above, later on the model should only be loaded from the path chief saved to, so let's remove the temporary ones the non-chief workers saved: | if not _is_chief(task_type, task_id):
tf.io.gfile.rmtree(os.path.dirname(write_model_path)) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Now, when it's time to load, let's use convenient `tf.keras.models.load_model` API, and continue with further work. Here, assume only using single worker to load and continue training, in which case you do not call `tf.keras.models.load_model` within another `strategy.scope()`. | loaded_model = tf.keras.models.load_model(model_path)
# Now that the model is restored, and can continue with the training.
loaded_model.fit(single_worker_dataset, epochs=2, steps_per_epoch=20) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Checkpoint saving and restoringOn the other hand, checkpointing allows you to save model's weights and restore them without having to save the whole model. Here, you'll create one `tf.train.Checkpoint` that tracks the model, which is managed by a `tf.train.CheckpointManager` so that only the latest checkpoint is prese... | checkpoint_dir = '/tmp/ckpt'
checkpoint = tf.train.Checkpoint(model=multi_worker_model)
write_checkpoint_dir = write_filepath(checkpoint_dir, task_type, task_id)
checkpoint_manager = tf.train.CheckpointManager(
checkpoint, directory=write_checkpoint_dir, max_to_keep=1) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Once the `CheckpointManager` is set up, you're now ready to save, and remove the checkpoints non-chief workers saved. | checkpoint_manager.save()
if not _is_chief(task_type, task_id):
tf.io.gfile.rmtree(write_checkpoint_dir) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
Now, when you need to restore, you can find the latest checkpoint saved using the convenient `tf.train.latest_checkpoint` function. After restoring the checkpoint, you can continue with training. | latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)
checkpoint.restore(latest_checkpoint)
multi_worker_model.fit(multi_worker_dataset, epochs=2, steps_per_epoch=20) | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
BackupAndRestore callbackBackupAndRestore callback provides fault tolerance functionality, by backing up the model and current epoch number in a temporary checkpoint file under `backup_dir` argument to `BackupAndRestore`. This is done at the end of each epoch.Once jobs get interrupted and restart, the callback restore... | # Multi-worker training with MultiWorkerMirroredStrategy.
callbacks = [tf.keras.callbacks.experimental.BackupAndRestore(backup_dir='/tmp/backup')]
with strategy.scope():
multi_worker_model = mnist.build_and_compile_cnn_model()
multi_worker_model.fit(multi_worker_dataset,
epochs=3,
... | _____no_output_____ | Apache-2.0 | site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb | minamstar/docs-l10n |
[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb) **Detect posology relations**... | import os
import json
with open('/content/spark_nlp_for_healthcare.json', 'r') as f:
license_keys = json.load(f)
license_keys.keys()
secret = license_keys['SECRET']
os.environ['SPARK_NLP_LICENSE'] = license_keys['SPARK_NLP_LICENSE']
os.environ['AWS_ACCESS_KEY_ID'] = license_keys['AWS_ACCESS_KEY_ID']
os.environ['... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb | ewbolme/spark-nlp-workshop |
Install dependencies | # Install Java
! apt-get update -qq
! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null
! java -version
# Install pyspark
! pip install --ignore-installed -q pyspark==2.4.4
# Install Spark NLP
! pip install --ignore-installed spark-nlp==$sparknlp_version
! python -m pip install --upgrade spark-nlp-jsl==$jsl_v... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb | ewbolme/spark-nlp-workshop |
Import dependencies into Python | os.environ['JAVA_HOME'] = "/usr/lib/jvm/java-8-openjdk-amd64"
os.environ['PATH'] = os.environ['JAVA_HOME'] + "/bin:" + os.environ['PATH']
import pandas as pd
from pyspark.ml import Pipeline
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
import sparknlp
from sparknlp.annotator import *
from spa... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb | ewbolme/spark-nlp-workshop |
Start the Spark session | spark = sparknlp_jsl.start(secret) | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb | ewbolme/spark-nlp-workshop |
2. Select the Relation Extraction model and construct the pipeline Select the models:* Posology Relation Extraction models: **posology_re**For more details: https://github.com/JohnSnowLabs/spark-nlp-modelspretrained-models---spark-nlp-for-healthcare | # Change this to the model you want to use and re-run the cells below.
RE_MODEL_NAME = "posology_re"
NER_MODEL_NAME = "ner_posology_large" | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb | ewbolme/spark-nlp-workshop |
Create the pipeline | document_assembler = DocumentAssembler() \
.setInputCol('text')\
.setOutputCol('document')
sentence_detector = SentenceDetector() \
.setInputCols(['document'])\
.setOutputCol('sentences')
tokenizer = Tokenizer()\
.setInputCols(['sentences']) \
.setOutputCol('tokens')
pos_tagger = PerceptronMo... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb | ewbolme/spark-nlp-workshop |
3. Create example inputs | # Enter examples as strings in this array
input_list = [
"""The patient is a 40-year-old white male who presents with a chief complaint of "chest pain". The patient is diabetic and has a prior history of coronary artery disease. The patient presents today stating that his chest pain started yesterday evening and has be... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb | ewbolme/spark-nlp-workshop |
4. Run the pipeline | df = spark.createDataFrame(pd.DataFrame({"text": input_list}))
result = pipeline_model.transform(df)
light_result = light_pipeline.fullAnnotate(input_list[0]) | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb | ewbolme/spark-nlp-workshop |
5. Visualize helper function for visualization | def get_relations_df (results, rel='clinical_relations'):
rel_pairs=[]
for rel in results[rel]:
rel_pairs.append((
rel.result,
rel.metadata['entity1'],
rel.metadata['entity1_begin'],
rel.metadata['entity1_end'],
rel.metadata['chunk1'],
rel.m... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb | ewbolme/spark-nlp-workshop |
Лекция 7. Разреженные матрицы и прямые методы для решения больших разреженных систем План на сегодняшнюю лекцию- Плотные неструктурированные матрицы и распределённое хранение- Разреженные матрицы и форматы их представления- Быстрая реализация умножения разреженной матрицы на вектор - Метод Гаусса для разреженных матр... | from IPython.display import IFrame
IFrame('http://yifanhu.net/GALLERY/GRAPHS/search.html', 500, 500) | _____no_output_____ | MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Разреженные матрицы и глубокое обучение- DNN имеют очень много параметров- Некоторые из них могут быть избыточными- Как уменьшить число параметров без серьёзной потери в точности?- [Sparse variational dropout method](https://github.com/ars-ashuha/variational-dropout-sparsifies-dnn) даёт существенно разреженные фильтры... | import numpy as np
import scipy as sp
import scipy.sparse
from scipy.sparse import csc_matrix, csr_matrix
import matplotlib.pyplot as plt
import scipy.linalg
import scipy.sparse.linalg
%matplotlib inline
n = 5
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse... | _____no_output_____ | MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Шаблон разреженности- Команда ```spy``` рисует шаблон разреженности данной матрицы: пиксель $(i, j)$ отображается на рисунке, если соответствующий элемент матрицы ненулевой.- Шаблон разреженности действительно очень важен для понимания сложности алгоритмов линейной алгебры для разреженных матриц. - Зачастую шаблона р... | import numpy as np
import scipy as sp
import scipy.sparse
import scipy.sparse.linalg
from scipy.sparse import csc_matrix, csr_matrix, coo_matrix
import matplotlib.pyplot as plt
%matplotlib inline
n = 1000
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse.eye(... | 7.91 ms ± 453 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
10.8 ms ± 536 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
| MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Видно, что **CSR** быстрее, и чем менее структурирован шаблон разреженности, тем выше выигрыш в скорости. Разреженные матрицы и эффективность- Использование разреженных матриц приводит к уменьшению сложности- Но они не очень подходят для параллельных/GPU реализаций - Они не показывают максимальную эффективность из-за ... | import numpy as np
import time
n = 4000
a = np.random.randn(n, n)
v = np.random.randn(n)
t = time.time()
np.dot(a, v)
t = time.time() - t
print('Time: {0: 3.1e}, Efficiency: {1: 3.1e} Gflops'.\
format(t, ((2 * n ** 2)/t) / 10 ** 9))
n = 4000
ex = np.ones(n);
a = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1... | Time: 1.3e-04, Efficiency: 9.0e-02 Gflops
| MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Случайный доступ к данным и промахи в обращении к кешу- Сначала все элементы матрицы и вектора хранятся в оперативной памяти (RAM – Random Access Memory)- Если вы хотите вычислить произведение матрицы на вектор, часть элементов матрицы и вектора перемещаются в кеш (быстрой памяти малого объёма), см. [лекцию об алгорит... | n = 10
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse.eye(n)
A = sp.sparse.kron(lp1, e) + sp.sparse.kron(e, lp1)
A = csr_matrix(A)
rhs = np.ones(n * n)
sol = sp.sparse.linalg.spsolve(A, rhs)
_, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(sol)
ax1.set_title('N... | _____no_output_____ | MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
LU разложение разреженной матрицы- Почему разреженная линейная система может быть решена быстрее, чем плотная? С помощью какого метода? - В LU разложении матрицы $A$ факторы $L$ и $U$ могут быть также разреженными:$$A = L U$$- А решение линейной системы с разреженной треугольной матрицей может быть вычислено очень быс... | n = 7
ex = np.ones(n);
a = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
b = np.array(np.linalg.inv(a.toarray()))
print(a.toarray())
print(b) | [[-2. 1. 0. 0. 0. 0. 0.]
[ 1. -2. 1. 0. 0. 0. 0.]
[ 0. 1. -2. 1. 0. 0. 0.]
[ 0. 0. 1. -2. 1. 0. 0.]
[ 0. 0. 0. 1. -2. 1. 0.]
[ 0. 0. 0. 0. 1. -2. 1.]
[ 0. 0. 0. 0. 0. 1. -2.]]
[[-0.875 -0.75 -0.625 -0.5 -0.375 -0.25 -0.125]
[-0.75 -1.5 -1.25 -1. -0.75 -0.5 -0.25 ... | MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
А факторы...- $L$ и $U$ обычно разрежены- В случае трёхдиагональной матрицы они даже бидиагональны! | from scipy.sparse.linalg import splu
T = splu(a.tocsc(), permc_spec="NATURAL")
plt.spy(T.L) | _____no_output_____ | MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Отметим, что ```splu``` со значением параметра ```permc_spec``` по умолчанию даёт перестановку, которая не даёт бидиагональные факторы: | from scipy.sparse.linalg import splu
T = splu(a.tocsc())
plt.spy(T.L)
print(T.perm_c) | [0 1 2 3 5 4 6]
| MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Двумерный случайВ двумерном случае всё гораздо хуже: | n = 20
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse.eye(n)
A = sp.sparse.kron(lp1, e) + sp.sparse.kron(e, lp1)
A = csc_matrix(A)
T = scipy.sparse.linalg.spilu(A)
plt.spy(T.L, marker='.', color='k', markersize=8) | _____no_output_____ | MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Для правильной перестановки в двумерном случае число ненулевых элементов в $L$ растёт как $\mathcal{O}(N \log N)$. Однако сложность равна $\mathcal{O}(N^{3/2})$. Разреженные матрицы и теория графов- Число ненулей в факторах из LU разложения тесно связано с теорией графов.- Пакет ``networkx`` можно использовать для виз... | import networkx as nx
n = 10
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse.eye(n)
A = sp.sparse.kron(lp1, e) + sp.sparse.kron(e, lp1)
A = csc_matrix(A)
G = nx.Graph(A)
nx.draw(G, pos=nx.spectral_layout(G), node_size=10) | _____no_output_____ | MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Заполнение (fill-in)- Заполнение матрицы – это элементы, которые были **нулями**, но стали **ненулями** в процессе выполнения алгоритма.- Заполнение может быть различным для различных перестановок. Итак, до того как делать факторизацию матрицы нам необходимо переупорядочить её элементы так, чтобы заполнение факторов б... | import numpy as np
import scipy.sparse as spsp
import scipy.sparse.linalg as spsplin
import scipy.linalg as splin
import matplotlib.pyplot as plt
%matplotlib inline
A = spsp.coo_matrix((np.random.randn(10), ([0, 0, 0, 0, 1, 1, 2, 2, 3, 3],
[0, 1, 2, 3, 0, 1, 0, 2, 0, 3])))
p... | Original matrix
| MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Блочный случай$$PAP^\top = \begin{bmatrix} A_{11} & & A_{13} \\ & A_{22} & A_{23} \\ A_{31} & A_{32} & A_{33}\end{bmatrix}$$тогда$$PAP^\top = \begin{bmatrix} A_{11} & 0 & 0 \\ 0 & A_{22} & 0 \\ A_{31} & A_{32} & A_{33} - A_{31}A_{11}^{-1} A_{13} - A_{32}A_{22}^{-1}A_{23} \end{bmatrix} \begin{bmatrix} I & 0 & A_{11}... | import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import networkx as nx
kn = nx.read_gml('karate.gml')
print("Number of vertices = {}".format(kn.number_of_nodes()))
print("Number of edges = {}".format(kn.number_of_edges()))
nx.draw_networkx(kn, node_color="red") #Draw the graph
Laplacian = nx.laplac... | _____no_output_____ | MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
Резюме по примеру использования спектрального разбиения графа- Мы вызвали функцию из SciPy для поиска фиксированного числа собственных векторов и собственных значений, которые минимальны (возможны другие опции)- Детали методов, которые реализованы в этих функциях, обсудим уже скоро- Вектор Фидлера даёт простой способ ... | from IPython.core.display import HTML
def css_styling():
styles = open("./styles/custom.css", "r").read()
return HTML(styles)
css_styling() | _____no_output_____ | MIT | lectures/lecture7/lecture7.ipynb | AlexanderSLevin/nla2020_ozon |
The stereology moduleThe main purpose of stereology is to extract quantitative information from microscope images relating two-dimensional measures obtained on sections to three-dimensional parameters defining the structure. The aim of stereology is not to reconstruct the 3D geometry of the material (as in tomography)... | # Load the script first (change the path to GrainSizeTools_script.py accordingly!)
%run C:/Users/marco/Documents/GitHub/GrainSizeTools/grain_size_tools/GrainSizeTools_script.py
# Import the example dataset
filepath = 'C:/Users/marco/Documents/GitHub/GrainSizeTools/grain_size_tools/DATA/data_set.txt'
dataset = pd.read_c... | _____no_output_____ | Apache-2.0 | grain_size_tools/example_notebooks/stereology_module_examples.ipynb | jwestraadt/GrainSizeTools |
The Saltykov method> **What is it?**>> It is a stereological method that approximates the actual grain size distribution from the histogram of the apparent grain size distribution. The method is distribution-free, meaning that no assumption is made upon the type of statistical distribution, making the method very vers... | fig1, (ax1, ax2) = stereology.Saltykov(dataset['diameters'], numbins=11, calc_vol=50)
fig1.savefig("saltykov_plot.png", dpi=150) | _____no_output_____ | Apache-2.0 | grain_size_tools/example_notebooks/stereology_module_examples.ipynb | jwestraadt/GrainSizeTools |
Now let's assume that we want to use the class densities estimated by Saltykov's method to calculate the specific volume of each or one of the classes. We have two options here. | stereology.Saltykov? | [1;31mSignature:[0m
[0mstereology[0m[1;33m.[0m[0mSaltykov[0m[1;33m([0m[1;33m
[0m [0mdiameters[0m[1;33m,[0m[1;33m
[0m [0mnumbins[0m[1;33m=[0m[1;36m10[0m[1;33m,[0m[1;33m
[0m [0mcalc_vol[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m[1;33m
[0m [0mtext_file[0m[1;33m=[0m[1;32mNone... | Apache-2.0 | grain_size_tools/example_notebooks/stereology_module_examples.ipynb | jwestraadt/GrainSizeTools |
The input parameter ``text_file`` allows you to save a text file with the data in tabular format, you only have to declare the name of the file and the file type, either txt or csv (as in the function documentation example). Alternatively, you can use the Saltykov function to directly return the density and the midpoin... | mid_points, densities = stereology.Saltykov(dataset['diameters'], numbins=11, return_data=True)
print(densities) | [1.31536871e-03 2.17302235e-02 2.25631643e-02 1.45570771e-02
6.13586532e-03 2.24830266e-03 1.29306084e-03 3.60326809e-04
0.00000000e+00 0.00000000e+00 4.11071036e-05]
| Apache-2.0 | grain_size_tools/example_notebooks/stereology_module_examples.ipynb | jwestraadt/GrainSizeTools |
As you may notice, these density values do not add up to 1 or 100. | np.sum(densities) | _____no_output_____ | Apache-2.0 | grain_size_tools/example_notebooks/stereology_module_examples.ipynb | jwestraadt/GrainSizeTools |
This is because the script normalized the frequencies of the different classes so that the integral over the range (not the sum) is one (see FAQs for an explanation on this). If you want to calculate the relative proportion for each class you must multiply the value of the densities by the bin size. After doing this, y... | corrected_densities = densities * 14.236
np.sum(corrected_densities) | _____no_output_____ | Apache-2.0 | grain_size_tools/example_notebooks/stereology_module_examples.ipynb | jwestraadt/GrainSizeTools |
So for example if you have a volume of rock of say 100 cm2 and you want to estimate what proportion of that volume is occupied by each grain size class/range, you could estimate it as follows: | # I use np.around to round the values
np.around(corrected_densities * 100, 2) | _____no_output_____ | Apache-2.0 | grain_size_tools/example_notebooks/stereology_module_examples.ipynb | jwestraadt/GrainSizeTools |
The two-step method> **What is it?**>> It is a stereological method that approximates the actual grain size distribution. The method is distribution-dependent, meaning that it is assumed that the distribution of grain sizes follows a lognormal distribution. The method fit a lognormal distribution on top of the Saltyko... | fig2, ax = stereology.calc_shape(dataset['diameters'])
fig2.savefig("2step_plot.png", dpi=150) | _____no_output_____ | Apache-2.0 | grain_size_tools/example_notebooks/stereology_module_examples.ipynb | jwestraadt/GrainSizeTools |
Convolutional Neural Network Author: Ivan Bongiorni, Data Scientist at GfK.[LinkedIn profile](https://www.linkedin.com/in/ivan-bongiorni-b8a583164/)In this Notebook I will implement a **basic CNN in TensorFlow 2.0**. I will use the famous **Fashion MNIST** dataset, [published by Zalando](https://github.com/zalandorese... | # Import necessary modules
import numpy as np
import pandas as pd
import tensorflow as tf
print(tf.__version__)
from sklearn.utils import shuffle
from matplotlib import pyplot as plt
import seaborn | 2.0.0-beta0
| MIT | TensorFlow2.0__03.01_Convolutional_Neural_Network.ipynb | Gautamtverma/TensorFlow2.0_Notebooks |
0. Import data + DataprepThe dataset comes already divided in 60k and 10k Train and Test images. I will now import Training data, and leave Test for later. In order to dataprep image data, I need to reshape the pixel into `(, 28, 28, 1)` arrays; the 1 at the end represents the channel: 1 for black and white images, 3 ... | df = pd.read_csv('fashion-mnist_train.csv')
# extract labels, one-hot encode them
label = df.label
label = pd.get_dummies(label)
label = label.values
label = label.astype(np.float32)
df.drop('label', axis = 1, inplace = True)
df = df.values
df = df.astype(np.float32)
# reshape and scale data
df = df.reshape((len(df)... | _____no_output_____ | MIT | TensorFlow2.0__03.01_Convolutional_Neural_Network.ipynb | Gautamtverma/TensorFlow2.0_Notebooks |
1. CNN architectureI will feed images into a set of **convolutional** and **max-pooling layers**:- Conv layers are meant to extract relevant informations from pixel data. A number of *filters* scroll through the image, learning the most relevant informations to extract.- Max-Pool layers instead are meant to drasticall... | from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten, Dense, BatchNormalization, Dropout
from tensorflow.keras.activations import relu, elu, softmax
CNN = Sequential([
Conv2D(32, kernel_size = (3, 3), activation = elu,
kernel_initializer = 'he_nor... | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 26, 26, 32) 320
____________________________________... | MIT | TensorFlow2.0__03.01_Convolutional_Neural_Network.ipynb | Gautamtverma/TensorFlow2.0_Notebooks |
2. Training with Mini Batch Gradient DescentThe training part is no different from mini batch gradient descent training of feed-forward classifiers. I wrote [a Notebook on this technique](https://github.com/IvanBongiorni/TensorFlow2.0_Tutorial/blob/master/TensorFlow2.0_02_MiniBatch_Gradient_Descent.ipynb) in which I e... | @tf.function
def fetch_batch(X, y, batch_size, epoch):
start = epoch*batch_size
X_batch = X[start:start+batch_size, :, :]
y_batch = y[start:start+batch_size, :]
return X_batch, y_batch
# To measure execution time
import time
start = time.time() | _____no_output_____ | MIT | TensorFlow2.0__03.01_Convolutional_Neural_Network.ipynb | Gautamtverma/TensorFlow2.0_Notebooks |
There is one big difference with respect to previous training exercises. Since this Network has a high number of parameters (approx 4.4 million) it will require comparatively longer training times. For this reason, I will measure training not just in *epochs*, but also in *cycles*.At each training cycle, I will shuffle... | from tensorflow.keras.losses import CategoricalCrossentropy
from tensorflow.keras.metrics import CategoricalAccuracy
loss = tf.keras.losses.CategoricalCrossentropy()
accuracy = tf.keras.metrics.CategoricalAccuracy()
optimizer = tf.optimizers.Adam(learning_rate = 0.0001)
### TRAINING
cycles = 50
batch_size = 120
... | _____no_output_____ | MIT | TensorFlow2.0__03.01_Convolutional_Neural_Network.ipynb | Gautamtverma/TensorFlow2.0_Notebooks |
3. TestLet's now test the model on the Test set. I will repeat the dataprep part on it: | # Dataprep Test data
test = pd.read_csv('fashion-mnist_test.csv')
test_label = pd.get_dummies(test.label)
test_label = test_label.values
test_label = test_label.astype(np.float32)
test.drop('label', axis = 1, inplace = True)
test = test.values
test = test.astype(np.float32)
test = test / 255.
test = test.reshape((... | _____no_output_____ | MIT | TensorFlow2.0__03.01_Convolutional_Neural_Network.ipynb | Gautamtverma/TensorFlow2.0_Notebooks |
Data Processing | import numpy as np
import pandas as pd
df_orig = pd.DataFrame([['big', 2.00, 'black', 'coffee'],
['medium', 1.90, 'black', 'coffee'],
['small', 1.80, 'black', 'coffee'],
['small', 1.20, 'brown', 'tea'],
['medium', 1.30, 'brown', 'tea']],
... | _____no_output_____ | MIT | data-processing.ipynb | ryubidragonfire/python-machine-learning-101 |
Categorical Data- **nominal**- **ordinal** Encoding Norminal: `LabelEncoder` | df = df_orig.copy()
from sklearn.preprocessing import LabelEncoder
class_le = LabelEncoder()
y = class_le.fit_transform(df['drink']) # y can now be used as labels
print(y[0:5])
class_le.classes_ | [0 0 0 1 1]
| MIT | data-processing.ipynb | ryubidragonfire/python-machine-learning-101 |
Encoding Norminal into One-Hot: `LabelEncoder` | df = df_orig.copy()
from sklearn.preprocessing import OneHotEncoder
colour_le = LabelEncoder()
colour_le.fit_transform(df['colour'].values)
colour_le.classes_
df['colour']
X = pd.get_dummies(df[['price', 'colour']])
X | _____no_output_____ | MIT | data-processing.ipynb | ryubidragonfire/python-machine-learning-101 |
Hmm ... Encoding Nominal: `OneHotEncoder` ?? | df = df_orig.copy()
from sklearn.preprocessing import OneHotEncoder
colour_le = LabelEncoder()
df['colour'] = colour_le.fit_transform(df['colour'].values)
colour_le.classes_
df['colour']
from sklearn.preprocessing import OneHotEncoder
#ohe = OneHotEncoder(categorical_features=[2], sparse=False) # feature column number... | C:\WinPython-64bit-3.4.4.3Qt5\python-3.4.4.amd64\lib\site-packages\sklearn\utils\validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a... | MIT | data-processing.ipynb | ryubidragonfire/python-machine-learning-101 |
Encoding Ordinal: `.map`Order does has a meaning. | df = df_orig.copy()
size_map = {'big':3, 'medium':2, 'small':1}
df['size'] = df['size'].map(size_map)
df | _____no_output_____ | MIT | data-processing.ipynb | ryubidragonfire/python-machine-learning-101 |
Below won't preserve the intended order!! | df = df_orig.copy()
np.unique(df['size'])
size_map = {category:idx for idx, category in enumerate(np.unique(df['size']))}
size_map | _____no_output_____ | MIT | data-processing.ipynb | ryubidragonfire/python-machine-learning-101 |
quant-econ Solutions: Modeling Career Choice Solutions for http://quant-econ.net/py/career.html | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from quantecon import DiscreteRV, compute_fixed_point
from career import CareerWorkerProblem | _____no_output_____ | BSD-3-Clause | career/career_solutions_py.ipynb | indextrading/my |
Exercise 1 Simulate job / career paths. In reading the code, recall that `optimal_policy[i, j]` = policy at$(\theta_i, \epsilon_j)$ = either 1, 2 or 3; meaning 'stay put', 'new job' and'new life'. | wp = CareerWorkerProblem()
v_init = np.ones((wp.N, wp.N))*100
v = compute_fixed_point(wp.bellman_operator, v_init, verbose=False)
optimal_policy = wp.get_greedy(v)
F = DiscreteRV(wp.F_probs)
G = DiscreteRV(wp.G_probs)
def gen_path(T=20):
i = j = 0
theta_index = []
epsilon_index = []
for t in range(T)... | _____no_output_____ | BSD-3-Clause | career/career_solutions_py.ipynb | indextrading/my |
Exercise 2 The median for the original parameterization can be computed as follows |
wp = CareerWorkerProblem()
v_init = np.ones((wp.N, wp.N))*100
v = compute_fixed_point(wp.bellman_operator, v_init)
optimal_policy = wp.get_greedy(v)
F = DiscreteRV(wp.F_probs)
G = DiscreteRV(wp.G_probs)
def gen_first_passage_time():
t = 0
i = j = 0
while 1:
if optimal_policy[i, j] == 1: # Stay ... | Iteration Distance Elapsed (seconds)
---------------------------------------------
5 4.073e+00 9.388e-02
10 3.151e+00 1.871e-01
15 2.438e+00 2.811e-01
20 1.887e+00 3.741e-01
25 1.460e+00 4.675e-01 ... | BSD-3-Clause | career/career_solutions_py.ipynb | indextrading/my |
To compute the median with $\beta=0.99$ instead of the default value $\beta=0.95$,replace `wp = CareerWorkerProblem()` with `wp = CareerWorkerProblem(beta=0.99)`The medians are subject to randomness, but should be about 7 and 11respectively. Not surprisingly, more patient workers will wait longer to settle down to the... | from matplotlib import cm
wp = CareerWorkerProblem()
v_init = np.ones((wp.N, wp.N))*100
v = compute_fixed_point(wp.bellman_operator, v_init)
optimal_policy = wp.get_greedy(v)
fig, ax = plt.subplots(figsize=(6,6))
tg, eg = np.meshgrid(wp.theta, wp.epsilon)
lvls=(0.5, 1.5, 2.5, 3.5)
ax.contourf(tg, eg, optimal_policy.T... | Iteration Distance Elapsed (seconds)
---------------------------------------------
5 4.073e+00 9.415e-02
10 3.151e+00 1.866e-01
15 2.438e+00 2.793e-01
20 1.887e+00 3.721e-01
25 1.460e+00 4.647e-01 ... | BSD-3-Clause | career/career_solutions_py.ipynb | indextrading/my |
Encoding | """Byte pair encoding utilities"""
@lru_cache()
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a corresponding list of unicode strings.
The reversible bpe codes work on unicode strings.
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
When yo... | _____no_output_____ | MIT | main/nbs/mdling/fineTuning/gpt-2_fine_tuning.ipynb | jason424217/Artificial-Code-Gen |
Model | class HParams():
n_vocab=50257
n_ctx=1024
n_embd=768
n_head=12
n_layer=12
def __init__(self, n_vocab, n_ctx, n_embd, n_head, n_layer):
self.n_vocab = n_vocab
self.n_ctx = n_ctx
self.n_embd = n_embd
self.n_head = n_head
self.n_layer = n_layer
def default_hparams():
return HParams(
... | _____no_output_____ | MIT | main/nbs/mdling/fineTuning/gpt-2_fine_tuning.ipynb | jason424217/Artificial-Code-Gen |
Sample from Model | def top_k_logits(logits, k):
if k == 0:
# no truncation
return logits
def _top_k():
values, _ = tf.nn.top_k(logits, k=k)
min_values = values[:, -1, tf.newaxis]
return tf.compat.v1.where(
logits < min_values,
tf.ones_like(logits, dtype=logits.dtype... | _____no_output_____ | MIT | main/nbs/mdling/fineTuning/gpt-2_fine_tuning.ipynb | jason424217/Artificial-Code-Gen |
Embedding Methods | import math
class Embedder:
def __init__(self, chkpt_path, chunk_size):
tf.compat.v1.disable_eager_execution()
self.g = tf.Graph()
with self.g.as_default():
self.context = tf.compat.v1.placeholder(tf.int32, [1, None])
self.sess = tf.compat.v1.Session(graph=self.g)
... | _____no_output_____ | MIT | main/nbs/mdling/fineTuning/gpt-2_fine_tuning.ipynb | jason424217/Artificial-Code-Gen |
Задание 2.2 - Введение в PyTorchДля этого задания потребуется установить версию PyTorch 1.0https://pytorch.org/get-started/locally/В этом задании мы познакомимся с основными компонентами PyTorch и натренируем несколько небольших моделей.GPU нам пока не понадобится.Основные ссылки: https://pytorch.org/tutorials/beginn... | import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as dset
from torch.utils.data.sampler import SubsetRandomSampler, Sampler
from torchvision import transforms
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np | _____no_output_____ | MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
Как всегда, начинаем с загрузки данныхPyTorch поддерживает загрузку SVHN из коробки. | # First, lets load the dataset
data_train = dset.SVHN('./data/', split='train',
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.43,0.44,0.47],
std=[0.20,0.20,0.2... | _____no_output_____ | MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
Теперь мы разделим данные на training и validation с использованием классов `SubsetRandomSampler` и `DataLoader`.`DataLoader` подгружает данные, предоставляемые классом `Dataset`, во время тренировки и группирует их в батчи.Он дает возможность указать `Sampler`, который выбирает, какие примеры из датасета использовать ... | batch_size = 64
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
data_size = data_train.data.shape[0]
validation_split = .2
split = int(np.floor(validation_split * data_size))
indices = list(range(data_size))
np.random.shuffle(indices)
train_indices, val_indices = indices[split:]... | cuda:0
| MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
В нашей задаче мы получаем на вход изображения, но работаем с ними как с одномерными массивами. Чтобы превратить многомерный массив в одномерный, мы воспользуемся очень простым вспомогательным модулем `Flattener`. | sample, label = data_train[0]
print("SVHN data sample shape: ", sample.shape)
# As you can see, the data is shaped like an image
# We'll use a special helper module to shape it into a tensor
class Flattener(nn.Module):
def forward(self, x):
batch_size, *_ = x.shape
return x.view(batch_size, -1) | SVHN data sample shape: torch.Size([3, 32, 32])
| MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
И наконец, мы создаем основные объекты PyTorch:- `nn_model` - собственно, модель с нейросетью- `loss` - функцию ошибки, в нашем случае `CrossEntropyLoss`- `optimizer` - алгоритм оптимизации, в нашем случае просто `SGD` | nn_model = nn.Sequential(
Flattener(),
nn.Linear(3*32*32, 100),
nn.ReLU(inplace=True),
nn.Linear(100, 10),
)
nn_model.type(torch.FloatTensor)
# We will minimize cross-entropy between the ground truth and
# network predictions using an SGD optimizer
loss = nn.Cr... | _____no_output_____ | MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
Тренируем!Ниже приведена функция `train_model`, реализующая основной цикл тренировки PyTorch.Каждую эпоху эта функция вызывает функцию `compute_accuracy`, которая вычисляет точность на validation, эту последнюю функцию предлагается реализовать вам. | # This is how to implement the same main train loop in PyTorch. Pretty easy, right?
def train_model(model, train_loader, val_loader, loss, optimizer, num_epochs):
loss_history = []
train_history = []
val_history = []
model.to(device)
for epoch in range(num_epochs):
model.train() # Enter... | Average loss: 1.837043, Train accuracy: 0.405078, Val accuracy: 0.548222
Average loss: 1.463647, Train accuracy: 0.577927, Val accuracy: 0.598457
Average loss: 1.383073, Train accuracy: 0.616217, Val accuracy: 0.628217
| MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
После основного циклаПосмотрим на другие возможности и оптимизации, которые предоставляет PyTorch.Добавьте еще один скрытый слой размера 100 нейронов к модели | # Since it's so easy to add layers, let's add some!
# TODO: Implement a model with 2 hidden layers of the size 100
nn_model = nn.Sequential(
Flattener(),
nn.Linear(3*32*32, 100),
nn.ReLU(inplace=True),
nn.Linear(100, 100),
nn.ReLU(inplace=True),
... | Average loss: 2.179205, Train accuracy: 0.201515, Val accuracy: 0.232885
Average loss: 1.987170, Train accuracy: 0.291813, Val accuracy: 0.346939
Average loss: 1.779322, Train accuracy: 0.389875, Val accuracy: 0.422292
Average loss: 1.700140, Train accuracy: 0.426373, Val accuracy: 0.424886
Average loss: 1.678671, Trai... | MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
Добавьте слой с Batch Normalization | # We heard batch normalization is powerful, let's use it!
# TODO: Add batch normalization after each of the hidden layers of the network, before or after non-linearity
# Hint: check out torch.nn.BatchNorm1d
nn_model = nn.Sequential(
Flattener(),
nn.Linear(3*32*32, 100),
nn.BatchNorm... | _____no_output_____ | MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
Добавьте уменьшение скорости обучения по ходу тренировки. | # Learning rate annealing
# Reduce your learning rate 2x every 2 epochs
# Hint: look up learning rate schedulers in PyTorch. You might need to extend train_model function a little bit too!
nn_model = nn.Sequential(
Flattener(),
nn.Linear(3*32*32, 100),
nn.BatchNorm1d(100),
... | Average loss: 1.806619, Train accuracy: 0.427038, Val accuracy: 0.588561
Average loss: 1.406469, Train accuracy: 0.619988, Val accuracy: 0.684254
Average loss: 1.321503, Train accuracy: 0.667935, Val accuracy: 0.712716
Average loss: 1.282513, Train accuracy: 0.689452, Val accuracy: 0.717289
Average loss: 1.259725, Trai... | MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
Визуализируем ошибки моделиПопробуем посмотреть, на каких изображениях наша модель ошибается.Для этого мы получим все предсказания модели на validation set и сравним их с истинными метками (ground truth).Первая часть - реализовать код на PyTorch, который вычисляет все предсказания модели на validation set. Чтобы это ... | class SubsetSampler(Sampler):
r"""Samples elements with given indices sequentially
Arguments:
indices (ndarray): indices of the samples to take
"""
def __init__(self, indices):
self.indices = indices
def __iter__(self):
return (self.indices[i] for i in range(len(self.indic... | _____no_output_____ | MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
Confusion matrixПервая часть визуализации - вывести confusion matrix (https://en.wikipedia.org/wiki/Confusion_matrix ).Confusion matrix - это матрица, где каждой строке соответствуют классы предсказанный, а столбцу - классы истинных меток (ground truth). Число с координатами `i,j` - это количество сэмплов класса `j`, ... | def visualize_confusion_matrix(confusion_matrix):
"""
Visualizes confusion matrix
confusion_matrix: np array of ints, x axis - predicted class, y axis - actual class
[i][j] should have the count of samples that were predicted to be class i,
but have j in the ... | [3 2 1 ... 1 1 2]
[0 7 1 ... 1 1 2]
| MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
Наконец, посмотрим на изображения, соответствующие некоторым элементам этой матрицы.Как и раньше, вам дана функция `visualize_images`, которой нужно воспрользоваться при реализации функции `visualize_predicted_actual`. Эта функция должна вывести несколько примеров, соответствующих заданному элементу матрицы.Визуализиру... | data_train_images = dset.SVHN('./data/', split='train')
def visualize_images(indices, data, title='', max_num=10):
"""
Visualizes several images from the dataset
indices: array of indices to visualize
data: torch Dataset with the images
title: string, title of the plot
max_num: int, max numbe... | _____no_output_____ | MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
Переходим к свободным упражнениям!Натренируйте модель как можно лучше - экспериментируйте сами!Что следует обязательно попробовать:- перебор гиперпараметров с помощью валидационной выборки- другие оптимизаторы вместо SGD- изменение количества слоев и их размеров- наличие Batch NormalizationНо ограничиваться этим не ст... | nn_model = nn.Sequential(
Flattener(),
nn.Linear(3*32*32, 100),
nn.BatchNorm1d(100),
nn.ReLU(inplace=True),
nn.Linear(100, 100),
nn.BatchNorm1d(100),
nn.ReLU(inplace=True),
nn.Linear(100, 10)
)
optimizer = optim.Ad... | Test accuracy: 0.8045
| MIT | assignments/assignment2/PyTorch.ipynb | BearingBall/dlcourse_ai-master |
RegularizationWelcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that **overfitting can be a serious problem**, if the training dataset is not big enough. Sure it does well on the training set, but the learned network **doesn't generalize to new examples** that it... | # import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
import sklearn.da... | /home/jovyan/work/week5/Regularization/reg_utils.py:85: SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert(parameters['W' + str(l)].shape == layer_dims[l], layer_dims[l-1])
/home/jovyan/work/week5/Regularization/reg_utils.py:86: SyntaxWarning: assertion is always true, perhaps remove parenthe... | MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
**Problem Statement**: You have just been hired as an AI expert by the French Football Corporation. They would like you to recommend positions where France's goal keeper should kick the ball so that the French team's players can then hit it with their head. **Figure 1** : **Football field** The goal keeper kicks the ... | train_X, train_Y, test_X, test_Y = load_2D_dataset() | _____no_output_____ | MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head after the French goal keeper has shot the ball from the left side of the football field.- If the dot is blue, it means the French player managed to hit the ball with his/her head- If the dot is red, it me... | def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1):
"""
Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (1 ... | _____no_output_____ | MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
Let's train the model without any regularization, and observe the accuracy on the train/test sets. | parameters = model(train_X, train_Y)
print ("On the training set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters) | Cost after iteration 0: 0.6557412523481002
Cost after iteration 10000: 0.16329987525724216
Cost after iteration 20000: 0.13851642423255986
| MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
The train accuracy is 94.8% while the test accuracy is 91.5%. This is the **baseline model** (you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model. | plt.title("Model without regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y) | _____no_output_____ | MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting. 2 - L2 RegularizationThe standard way to avoid overfitting is called **L2 regularization**. It consists of appropriately modifying your cost function, from:$$J = -... | # GRADED FUNCTION: compute_cost_with_regularization
def compute_cost_with_regularization(A3, Y, parameters, lambd):
"""
Implement the cost function with L2 regularization. See formula (2) above.
Arguments:
A3 -- post-activation, output of forward propagation, of shape (output size, number of examp... | cost = 1.78648594516
| MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
**Expected Output**: **cost** 1.78648594516 Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost. **Exercise**: Implement the changes needed in backward propagation to take i... | # GRADED FUNCTION: backward_propagation_with_regularization
def backward_propagation_with_regularization(X, Y, cache, lambd):
"""
Implements the backward propagation of our baseline model to which we added an L2 regularization.
Arguments:
X -- input dataset, of shape (input size, number of example... | dW1 = [[-0.25604646 0.12298827 -0.28297129]
[-0.17706303 0.34536094 -0.4410571 ]]
dW2 = [[ 0.79276486 0.85133918]
[-0.0957219 -0.01720463]
[-0.13100772 -0.03750433]]
dW3 = [[-1.77691347 -0.11832879 -0.09397446]]
| MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.