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
ec50ceb72857f61d62fb2f44f8e5375979e2e7cd
15,829
ipynb
Jupyter Notebook
classifier_scratch.ipynb
dyf/nnxt
caa28635ec6a804bcad545abdd667749cab52048
[ "MIT" ]
null
null
null
classifier_scratch.ipynb
dyf/nnxt
caa28635ec6a804bcad545abdd667749cab52048
[ "MIT" ]
null
null
null
classifier_scratch.ipynb
dyf/nnxt
caa28635ec6a804bcad545abdd667749cab52048
[ "MIT" ]
null
null
null
58.409594
1,361
0.638638
[ [ [ "import pandas as pd\nreads_matrix = pd.read_hdf('all_reads_matrix.h5', key='matrix')", "_____no_output_____" ], [ "organisms = pd.read_csv('all_reads_matrix_organisms.csv', index_col='sample_id')", "_____no_output_____" ], [ "import torch", "_____no_output_____" ], [ "model = torch.nn.Sequential(\n torch.nn.Linear(15501, 8192),\n torch.nn.Dropout(.1),\n torch.nn.ReLU(),\n torch.nn.Linear(8192, 4096),\n torch.nn.Dropout(.1),\n torch.nn.ReLU(),\n torch.nn.Linear(4096, 2048),\n torch.nn.Dropout(.1),\n torch.nn.ReLU(),\n torch.nn.Linear(2048, 1024),\n torch.nn.ReLU(),\n torch.nn.Linear(1024, 512),\n torch.nn.ReLU(),\n torch.nn.Linear(512, 256),\n torch.nn.ReLU(), \n torch.nn.Linear(256, 128),\n torch.nn.ReLU(),\n torch.nn.Linear(128, 1),\n torch.nn.Sigmoid()\n)", "_____no_output_____" ], [ "criterion = torch.nn.BCELoss()", "_____no_output_____" ], [ "learning_rate = 0.001\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)", "_____no_output_____" ], [ "import numpy as np\nclass HMDataSet(torch.utils.data.Dataset):\n def __init__(self, reads_matrix, organisms):\n self.reads_matrix = reads_matrix\n self.organisms = organisms\n \n omap = { 'Mus musculus': 0, 'Homo sapiens': 1}\n self.ocats = organisms.organism.map(omap).values\n \n def __len__(self):\n return self.organisms.shape[0]\n \n def __getitem__(self, idx):\n return self.reads_matrix.iloc[idx].values, self.ocats[idx]", "_____no_output_____" ], [ "full_ds = HMDataSet(reads_matrix, organisms)", "_____no_output_____" ], [ "train_size = int(0.8 * len(full_ds))\ntest_size = len(full_ds) - train_size\ntrain_ds, test_ds = torch.utils.data.random_split(full_ds, [train_size, test_size])", "_____no_output_____" ], [ "params = {\n 'batch_size': 1000,\n 'shuffle': True,\n 'num_workers': 1\n}", "_____no_output_____" ], [ "use_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda:0\" if use_cuda else \"cpu\")", "_____no_output_____" ], [ "train_generator = torch.utils.data.DataLoader(train_ds, **params)\ntest_generator = torch.utils.data.DataLoader(test_ds, **params)", "_____no_output_____" ], [ "\nn_epochs = 10\nloss_history = []\nfor i in range(n_epochs):\n def closure():\n optimizer.zero_grad()\n output = model(X)\n loss = criterion(output, Y)\n loss.backward()\n return loss\n \n # Training\n for local_batch, local_labels in train_generator:\n print(local_batch, local_labels)\n # Transfer to GPU\n local_batch, local_labels = local_batch.to(device), local_labels.to(device)\n \n #loss = optimizer.step(closure)\n #print(f'Epoch: [{i+1}/{n_epochs}], Loss: {loss:.4f}')\n #loss_history.append(loss)", "_____no_output_____" ], [ "loss", "_____no_output_____" ], [ "loss", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec50dce740fcc7e5aee672e9e7c8c4bdf89af438
6,137
ipynb
Jupyter Notebook
notebooks/samples/TextAnalytics - Amazon Book Reviews with Word2Vec.ipynb
skonigs/mmlspark
45379694813458c5e113d84186c09b3a5c455cdc
[ "MIT" ]
1
2021-08-17T18:11:49.000Z
2021-08-17T18:11:49.000Z
notebooks/samples/TextAnalytics - Amazon Book Reviews with Word2Vec.ipynb
skonigs/mmlspark
45379694813458c5e113d84186c09b3a5c455cdc
[ "MIT" ]
1
2021-08-18T08:26:45.000Z
2021-08-18T08:26:45.000Z
notebooks/samples/TextAnalytics - Amazon Book Reviews with Word2Vec.ipynb
skonigs/mmlspark
45379694813458c5e113d84186c09b3a5c455cdc
[ "MIT" ]
1
2021-06-14T23:04:23.000Z
2021-06-14T23:04:23.000Z
29.085308
122
0.571452
[ [ [ "## TextAnalytics - Amazon Book Reviews with Word2Vec\n\nYet again, now using the `Word2Vec` Estimator from Spark. We can use the tree-based\nlearners from spark in this scenario due to the lower dimensionality representation of\nfeatures.", "_____no_output_____" ] ], [ [ "import pandas as pd\n", "_____no_output_____" ], [ "data = spark.read.parquet(\"wasbs://[email protected]/BookReviewsFromAmazon10K.parquet\")\ndata.limit(10).toPandas()", "_____no_output_____" ] ], [ [ "Modify the label column to predict a rating greater than 3.", "_____no_output_____" ] ], [ [ "processedData = data.withColumn(\"label\", data[\"rating\"] > 3) \\\n .select([\"text\", \"label\"])\nprocessedData.limit(5).toPandas()", "_____no_output_____" ] ], [ [ "Split the dataset into train, test and validation sets.", "_____no_output_____" ] ], [ [ "train, test, validation = processedData.randomSplit([0.60, 0.20, 0.20])", "_____no_output_____" ] ], [ [ "Use `Tokenizer` and `Word2Vec` to generate the features.", "_____no_output_____" ] ], [ [ "from pyspark.ml import Pipeline\nfrom pyspark.ml.feature import Tokenizer, Word2Vec\ntokenizer = Tokenizer(inputCol=\"text\", outputCol=\"words\")\npartitions = train.rdd.getNumPartitions()\nword2vec = Word2Vec(maxIter=4, seed=42, inputCol=\"words\", outputCol=\"features\",\n numPartitions=partitions)\ntextFeaturizer = Pipeline(stages = [tokenizer, word2vec]).fit(train)", "_____no_output_____" ] ], [ [ "Transform each of the train, test and validation datasets.", "_____no_output_____" ] ], [ [ "ptrain = textFeaturizer.transform(train).select([\"label\", \"features\"])\nptest = textFeaturizer.transform(test).select([\"label\", \"features\"])\npvalidation = textFeaturizer.transform(validation).select([\"label\", \"features\"])\nptrain.limit(5).toPandas()", "_____no_output_____" ] ], [ [ "Generate several models with different parameters from the training data.", "_____no_output_____" ] ], [ [ "from pyspark.ml.classification import LogisticRegression, RandomForestClassifier, GBTClassifier\nfrom mmlspark.train import TrainClassifier\nimport itertools\n\nlrHyperParams = [0.05, 0.2]\nlogisticRegressions = [LogisticRegression(regParam = hyperParam)\n for hyperParam in lrHyperParams]\nlrmodels = [TrainClassifier(model=lrm, labelCol=\"label\").fit(ptrain)\n for lrm in logisticRegressions]\n\nrfHyperParams = itertools.product([5, 10], [2, 3])\nrandomForests = [RandomForestClassifier(numTrees=hyperParam[0], maxDepth=hyperParam[1])\n for hyperParam in rfHyperParams]\nrfmodels = [TrainClassifier(model=rfm, labelCol=\"label\").fit(ptrain)\n for rfm in randomForests]\n\ngbtHyperParams = itertools.product([8, 16], [2, 3])\ngbtclassifiers = [GBTClassifier(maxBins=hyperParam[0], maxDepth=hyperParam[1])\n for hyperParam in gbtHyperParams]\ngbtmodels = [TrainClassifier(model=gbt, labelCol=\"label\").fit(ptrain)\n for gbt in gbtclassifiers]\n\ntrainedModels = lrmodels + rfmodels + gbtmodels", "_____no_output_____" ] ], [ [ "Find the best model for the given test dataset.", "_____no_output_____" ] ], [ [ "from mmlspark.automl import FindBestModel\nbestModel = FindBestModel(evaluationMetric=\"AUC\", models=trainedModels).fit(ptest)\nbestModel.getRocCurve().show()\nbestModel.getBestModelMetrics().show()\nbestModel.getAllModelMetrics().show()", "_____no_output_____" ] ], [ [ "Get the accuracy from the validation dataset.", "_____no_output_____" ] ], [ [ "from mmlspark.train import ComputeModelStatistics\npredictions = bestModel.transform(pvalidation)\nmetrics = ComputeModelStatistics().transform(predictions)\nprint(\"Best model's accuracy on validation set = \"\n + \"{0:.2f}%\".format(metrics.first()[\"accuracy\"] * 100))\nprint(\"Best model's AUC on validation set = \"\n + \"{0:.2f}%\".format(metrics.first()[\"AUC\"] * 100))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec50e1daa1a5485bbcecf0acb5d708dae7bfe71c
13,596
ipynb
Jupyter Notebook
01_basics/01_additional_lecture_notes/Bonus_ClassicalSeasonalDecomposition.ipynb
health-data-science-OR/forecasting
29d6c27661aa2ca471069d5d199d9c252ee6086a
[ "MIT" ]
2
2020-10-06T16:36:19.000Z
2021-02-27T11:11:42.000Z
Bonus_ClassicalSeasonalDecomposition.ipynb
TomMonks/psma-forecasting
ea8be4d194cad069d1cd19d6bc11b1f6e0179ac3
[ "MIT" ]
15
2020-08-04T08:43:49.000Z
2022-02-01T13:08:25.000Z
Bonus_ClassicalSeasonalDecomposition.ipynb
TomMonks/psma-forecasting
ea8be4d194cad069d1cd19d6bc11b1f6e0179ac3
[ "MIT" ]
1
2020-12-16T09:08:41.000Z
2020-12-16T09:08:41.000Z
24.72
233
0.565902
[ [ [ "# Bonus Lecture. \n\n## Classical Seasonal Decomposition\n\nIn this notebook you will learn how to:\n\n* Manually use additive and seasonal decomposition i.e. **without** using `statsmodels`\n* Seasonally adjust your time series to remove seasonal fluctuations.", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## The ED arrivals dataset.\n\nThe dataset we will use represent monthly adult (age > 18) arrivals to an Emergency Department. The observations are between April 2009 and May 2017. ", "_____no_output_____" ] ], [ [ "ed_month = pd.read_csv('data/ed_mth_ts.csv', index_col='date', parse_dates=True)\ned_month.index.freq = 'MS'\n\narrival_rate = ed_month['arrivals'] / ed_month.index.days_in_month", "_____no_output_____" ] ], [ [ "The first thing you should do when exploring a time series is check its length and duration.", "_____no_output_____" ] ], [ [ "#This tells us how many months are in the ts\narrival_rate.shape ", "_____no_output_____" ] ], [ [ "### Breaking a times series up into its trend and seasonal components.\n\nTo help visualise and understand trend and seasonality in a time series we can use seasonal decomposition.\n\nThis is a model based approach that breaks the time series into three components. The basic approach to seasonal decomposition has two forms: additive and multiplicative. \n\n#### Additive decomposition\n\nIf we assume that an observation at time t $Y_t$ is the additive sum of trend $T_t$, seasonality $S_t$ and random error $E_t$. then we have the following model.\n\n$Y_t = T_t + S_t + E_t$\n\nWe then to make this assumption when the seasonal fluctuations are constant across the time series. This looks like a reasonable assumption in the case of the ED data.\n\n#### Multiplicative decomposition\n\nIf the seasonal fluctuations of the data grow over time then it is best to a multiplicative model. Where an observation at time t $Y_t$ is the product of multiply the trend $T_t$, seasonality $S_t$ and random error $E_t$\n\n$Y_t = T_t \\cdot S_t \\cdot E_t$", "_____no_output_____" ], [ "## Manually performing a seasonal decomposition", "_____no_output_____" ], [ "Classical decomposition is straightfoward to implement. We will work with additive seasonality first.\n\n### **Additive Seasonality**\n\n**Step 1: Estimate the trend component**\n\nThe first thing to do is estimate the trend in the time series. We do this using a 12 month centered moving average.", "_____no_output_____" ] ], [ [ "decomp = pd.DataFrame(arrival_rate)\ndecomp.columns = ['actual']", "_____no_output_____" ], [ "decomp['trend'] = arrival_rate.rolling(window=12, center=True).mean()", "_____no_output_____" ], [ "ax = decomp.trend.plot(figsize=(12,4))\narrival_rate.plot(ax=ax)", "_____no_output_____" ] ], [ [ "**Step 2: Detrend the series**\n\nWe first need to **de-trend** the time series. In the additive model we do this by **subtracting** the trend from the actual observations of the time series.\n\n$Y_t - T_t = S_t + E_t$", "_____no_output_____" ] ], [ [ "detrended = decomp['actual'] - decomp['trend']", "_____no_output_____" ] ], [ [ "When we plot this notice that the upward trend of the data has been removed.", "_____no_output_____" ] ], [ [ "detrended.plot(figsize=(12,4))", "_____no_output_____" ] ], [ [ "**Step 3: Calculate the seasonal indicies**\n\nClassic decomposition assumes that seasonality is constant year to year. This means we only need to calculate one value for each month of the year.\n\nWe work with the detrended series. To calculate the seasonal indicies we group by month and take the average of the detrended series. This is easy in pandas with a group by operation.", "_____no_output_____" ] ], [ [ "seasonal_indexes = detrended.groupby(by=detrended.index.month).mean()", "_____no_output_____" ], [ "seasonal_indexes.plot(figsize=(12,4))", "_____no_output_____" ] ], [ [ "We then want to **map** the seasonal indicies to the rows in the time series. ", "_____no_output_____" ] ], [ [ "decomp['seasonal'] = decomp.index.month.map(seasonal_indexes)", "_____no_output_____" ], [ "decomp.head(10)", "_____no_output_____" ] ], [ [ "**Step 4: Calculate the remainder**\n\nThe irregular component $E_t$ is calculated by subtracting the trend and seasonal components from the actual.\n\n$E_t = Y_t - T_t - S_t$", "_____no_output_____" ] ], [ [ "decomp['resid'] = decomp['actual'] - decomp['trend'] - decomp['seasonal']", "_____no_output_____" ] ], [ [ "## Seasonal Decomposition Plot", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(4, 1, sharex=True, figsize=(12,9))\naxes[0].plot(decomp['actual'])\naxes[1].plot(decomp['trend'])\naxes[2].plot(decomp['seasonal'])\naxes[3].plot(decomp['resid'])\n\naxes[0].set_ylabel('actual')\naxes[1].set_ylabel('trend-cycle')\naxes[2].set_ylabel('seasonal')\naxes[3].set_ylabel('remainder')", "_____no_output_____" ] ], [ [ "## Seasonal Adjustment: A side product of decomposition\n\n$Y_t - S_t = T_t + E_t$\n\nMany economic time series are publishing using a seasonally adjusted data. This is achieved by subtrack the seasonal indicies from the observerd time series.", "_____no_output_____" ] ], [ [ "seasonal_adj = decomp['actual'] - decomp['seasonal']", "_____no_output_____" ], [ "fig, axes = plt.subplots(2, 1, sharex=True, figsize=(12,8))\naxes[0].plot(arrival_rate)\naxes[1].plot(seasonal_adj)", "_____no_output_____" ] ], [ [ "## Multiplicative Seasonality", "_____no_output_____" ] ], [ [ "sales = pd.read_csv('data/Alcohol_Sales.csv', index_col='DATE', parse_dates=True)\nsales.index.freq = 'MS'\nsales_rate = sales['sales'] / sales.index.days_in_month", "_____no_output_____" ], [ "sales_rate.plot(figsize=(12,4))", "_____no_output_____" ] ], [ [ "**Step 1: Estimate the trend component**\n\nAs before we will do this using a 12 month 'centered' moving average.", "_____no_output_____" ] ], [ [ "decomp = pd.DataFrame(sales_rate)\ndecomp.columns = ['actual']", "_____no_output_____" ], [ "decomp['trend'] = sales_rate.rolling(window=12, center=True).mean()", "_____no_output_____" ], [ "ax = decomp.trend.plot(figsize=(12,4))\nsales_rate.plot(ax=ax)", "_____no_output_____" ] ], [ [ "**Step 2: Detrend the series**\n\nWe first need to **de-trend** the time series. In the additive model we do this by **dividing** the trend from the actual observations of the time series.\n\n$Y_t = T_t \\cdot S_t \\cdot E_t$", "_____no_output_____" ] ], [ [ "detrended = decomp['actual'] / decomp['trend']", "_____no_output_____" ], [ "detrended.plot(figsize=(12,4))", "_____no_output_____" ] ], [ [ "**Step 3: Calculate the seasonal indicies**\n\nWe again work with the detrended series. To calculate the seasonal indicies we group by month and take the average of the detrended series. Note that the indicies are now proportion above and below the mean level of the series.", "_____no_output_____" ] ], [ [ "seasonal_indexes = detrended.groupby(by=detrended.index.month).mean()", "_____no_output_____" ], [ "seasonal_indexes.plot(figsize=(12,4))", "_____no_output_____" ] ], [ [ "We then want to **map** the seasonal indicies to the rows in the time series. ", "_____no_output_____" ] ], [ [ "decomp['seasonal'] = decomp.index.month.map(seasonal_indexes)", "_____no_output_____" ], [ "decomp.head(10)", "_____no_output_____" ] ], [ [ "**Step 4: Calculate the remainder**\n\nThe irregular component $E_t$ is calculated by dividing by the trend and seasonal components from the actual.\n\n$E_t = \\frac{Y_t}{T_t S_t}$", "_____no_output_____" ] ], [ [ "decomp['resid'] = decomp['actual'] / (decomp['trend'] * decomp['seasonal'])", "_____no_output_____" ], [ "decomp.head()", "_____no_output_____" ] ], [ [ "### Seasonal decomp plot", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(4, 1, sharex=True, figsize=(12,9))\naxes[0].plot(decomp['actual'])\naxes[1].plot(decomp['trend'])\naxes[2].plot(decomp['seasonal'])\naxes[3].plot(decomp['resid'])\n\naxes[0].set_ylabel('actual')\naxes[1].set_ylabel('trend-cycle')\naxes[2].set_ylabel('seasonal')\naxes[3].set_ylabel('remainder')", "_____no_output_____" ] ], [ [ "## Seasonal Adjustment.\n\n$\\frac{Y_t}{S_t} = T_t \\cdot E_t$\n\nMany economic time series are publishing using a seasonally adjusted data. This is achieved by dividing the observed time series by the seasonal indicies.", "_____no_output_____" ] ], [ [ "seasonal_adj = decomp['actual'] / decomp['seasonal']\nseasonal_adj.plot(figsize=(12,4))", "_____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", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec50f7483e7646f2cee042d7e22f702304a865f5
11,542
ipynb
Jupyter Notebook
courses/machine_learning/deepdive/07_structured/5_train.ipynb
jlewi/training-data-analyst
f183fe120ed93d845a231c2b740464b190ee6758
[ "Apache-2.0" ]
null
null
null
courses/machine_learning/deepdive/07_structured/5_train.ipynb
jlewi/training-data-analyst
f183fe120ed93d845a231c2b740464b190ee6758
[ "Apache-2.0" ]
null
null
null
courses/machine_learning/deepdive/07_structured/5_train.ipynb
jlewi/training-data-analyst
f183fe120ed93d845a231c2b740464b190ee6758
[ "Apache-2.0" ]
null
null
null
28.220049
553
0.56368
[ [ [ "<h1> Training on Cloud ML Engine </h1>\n\nThis notebook illustrates distributed training and hyperparameter tuning on Cloud ML Engine.", "_____no_output_____" ] ], [ [ "# change these to try this notebook out\nBUCKET = 'cloud-training-demos-ml'\nPROJECT = 'cloud-training-demos'\nREGION = 'us-central1'", "_____no_output_____" ], [ "import os\nos.environ['BUCKET'] = BUCKET\nos.environ['PROJECT'] = PROJECT\nos.environ['REGION'] = REGION", "_____no_output_____" ], [ "%%bash\nif ! gsutil ls | grep -q gs://${BUCKET}/; then\n gsutil mb -l ${REGION} gs://${BUCKET}\n # copy canonical set of preprocessed files if you didn't do previous notebook\n gsutil -m cp -R gs://cloud-training-demos/babyweight gs://${BUCKET}\nfi", "_____no_output_____" ], [ "%bash\ngsutil ls gs://${BUCKET}/babyweight/preproc/*-00000*", "gs://cloud-training-demos-ml/babyweight/preproc/eval.csv-00000-of-00012\ngs://cloud-training-demos-ml/babyweight/preproc/train.csv-00000-of-00043\n" ] ], [ [ "Now that we have the TensorFlow code working on a subset of the data, we can package the TensorFlow code up as a Python module and train it on Cloud ML Engine.\n<p>\n<h2> Train on Cloud ML Engine </h2>\n<p>\nTraining on Cloud ML Engine requires:\n<ol>\n<li> Making the code a Python package\n<li> Using gcloud to submit the training code to Cloud ML Engine\n</ol>\n<p>\nThe code in model.py is the same as in the TensorFlow notebook. I just moved it to a file so that I could package it up as a module.\n(explore the <a href=\"babyweight/trainer\">directory structure</a>).", "_____no_output_____" ] ], [ [ "%bash\ngrep \"^def\" babyweight/trainer/model.py", "def read_dataset(prefix, pattern, batch_size=512):\ndef get_wide_deep():\ndef serving_input_fn():\ndef experiment_fn(output_dir):\ndef train_and_evaluate(output_dir):\n" ] ], [ [ "After moving the code to a package, make sure it works standalone. (Note the --pattern and --train_examples lines so that I am not trying to boil the ocean on my laptop). Even then, this takes about <b>a minute</b> in which you won't see any output ...", "_____no_output_____" ] ], [ [ "%bash\necho \"bucket=${BUCKET}\"\nrm -rf babyweight_trained\nexport PYTHONPATH=${PYTHONPATH}:${PWD}/babyweight\npython -m trainer.task \\\n --bucket=${BUCKET} \\\n --output_dir=babyweight_trained \\\n --job-dir=./tmp \\\n --pattern=\"00000-of-\" --train_examples=500", "_____no_output_____" ] ], [ [ "Once the code works in standalone mode, you can run it on Cloud ML Engine. Because this is on the entire dataset, it will take a while. The training run took about <b> an hour </b> for me. You can monitor the job from the GCP console in the Cloud Machine Learning Engine section.", "_____no_output_____" ] ], [ [ "%bash\nOUTDIR=gs://${BUCKET}/babyweight/trained_model\nJOBNAME=babyweight_$(date -u +%y%m%d_%H%M%S)\necho $OUTDIR $REGION $JOBNAME\ngsutil -m rm -rf $OUTDIR\ngcloud ml-engine jobs submit training $JOBNAME \\\n --region=$REGION \\\n --module-name=trainer.task \\\n --package-path=$(pwd)/babyweight/trainer \\\n --job-dir=$OUTDIR \\\n --staging-bucket=gs://$BUCKET \\\n --scale-tier=STANDARD_1 \\\n --runtime-version=1.4 \\\n -- \\\n --bucket=${BUCKET} \\\n --output_dir=${OUTDIR} \\\n --train_examples=200000", "_____no_output_____" ] ], [ [ "When I ran it, training finished, and the evaluation happened three times (filter in Stackdriver on the word \"dict\"):\n<pre>\nSaving dict for global step 390632: average_loss = 1.06578, global_step = 390632, loss = 545.55\n</pre>\nThe final RMSE was 1.066 pounds.", "_____no_output_____" ] ], [ [ "from google.datalab.ml import TensorBoard\nTensorBoard().start('gs://{}/babyweight/trained_model'.format(BUCKET))", "_____no_output_____" ], [ "for pid in TensorBoard.list()['pid']:\n TensorBoard().stop(pid)\n print 'Stopped TensorBoard with pid {}'.format(pid)", "Stopped TensorBoard with pid 10437\n" ] ], [ [ "<h2> Hyperparameter tuning </h2>\n<p>\nAll of these are command-line parameters to my program. To do hyperparameter tuning, create hyperparam.xml and pass it as --configFile.\nThis step will take <b>1 hour</b> -- you can increase maxParallelTrials or reduce maxTrials to get it done faster. Since maxParallelTrials is the number of initial seeds to start searching from, you don't want it to be too large; otherwise, all you have is a random search.\n", "_____no_output_____" ] ], [ [ "%writefile hyperparam.yaml\ntrainingInput:\n scaleTier: STANDARD_1\n hyperparameters:\n hyperparameterMetricTag: average_loss\n goal: MINIMIZE\n maxTrials: 20\n maxParallelTrials: 5\n enableTrialEarlyStopping: True\n params:\n - parameterName: batch_size\n type: INTEGER\n minValue: 8\n maxValue: 512\n scaleType: UNIT_LOG_SCALE\n - parameterName: nembeds\n type: INTEGER\n minValue: 3\n maxValue: 30\n scaleType: UNIT_LINEAR_SCALE\n - parameterName: nnsize\n type: INTEGER\n minValue: 64\n maxValue: 512\n scaleType: UNIT_LOG_SCALE", "Overwriting hyperparam.yaml\n" ] ], [ [ "In reality, you would hyper-parameter tune over your entire dataset, and not on a smaller subset (see --pattern). But because this is a demo, I wanted it to finish quickly.", "_____no_output_____" ] ], [ [ "%bash\nOUTDIR=gs://${BUCKET}/babyweight/hyperparam\nJOBNAME=babyweight_$(date -u +%y%m%d_%H%M%S)\necho $OUTDIR $REGION $JOBNAME\ngsutil -m rm -rf $OUTDIR\ngcloud ml-engine jobs submit training $JOBNAME \\\n --region=$REGION \\\n --module-name=trainer.task \\\n --package-path=$(pwd)/babyweight/trainer \\\n --job-dir=$OUTDIR \\\n --staging-bucket=gs://$BUCKET \\\n --scale-tier=STANDARD_1 \\\n --config=hyperparam.yaml \\\n --runtime-version=1.4 \\\n -- \\\n --bucket=${BUCKET} \\\n --output_dir=${OUTDIR} \\\n --eval_steps=10 \\\n --pattern=\"00000-of-\" --train_examples=5000", "_____no_output_____" ], [ "%bash\ngcloud ml-engine jobs describe babyweight_180123_202458", "_____no_output_____" ] ], [ [ "<h2> Repeat training </h2>\n<p>\nThis time with tuned parameters (note last line)", "_____no_output_____" ] ], [ [ "%bash\nOUTDIR=gs://${BUCKET}/babyweight/trained_model\nJOBNAME=babyweight_$(date -u +%y%m%d_%H%M%S)\necho $OUTDIR $REGION $JOBNAME\ngsutil -m rm -rf $OUTDIR\ngcloud ml-engine jobs submit training $JOBNAME \\\n --region=$REGION \\\n --module-name=trainer.task \\\n --package-path=$(pwd)/babyweight/trainer \\\n --job-dir=$OUTDIR \\\n --staging-bucket=gs://$BUCKET \\\n --scale-tier=STANDARD_1 \\\n -- \\\n --bucket=${BUCKET} \\\n --output_dir=${OUTDIR} \\\n --train_examples=200000 --batch_size=35 --nembeds=16 --nnsize=281", "_____no_output_____" ] ], [ [ "Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec5102f3a00253efb1107e5faa9c89e8f57dd6c0
2,648
ipynb
Jupyter Notebook
04 OOPS-2/4.9 Operator Overloading.ipynb
suhassuhas/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
e660d5a83b80df9cb67b2d06f2b5ba182586f3da
[ "Unlicense" ]
4
2021-09-09T06:52:31.000Z
2022-01-09T00:05:11.000Z
04 OOPS-2/4.9 Operator Overloading.ipynb
rishitbhojak/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
3b5625df60f7ac554fae58dc8ea9fd42012cbfae
[ "Unlicense" ]
null
null
null
04 OOPS-2/4.9 Operator Overloading.ipynb
rishitbhojak/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
3b5625df60f7ac554fae58dc8ea9fd42012cbfae
[ "Unlicense" ]
5
2021-09-15T13:49:32.000Z
2022-01-20T20:37:46.000Z
21.884298
115
0.438822
[ [ [ "1 + 2 = 3\n\n\"Faz\" + \"eel\" --> \"Fazeel\"\n\np = point(1,2) p1 = point(3,4)\n\npoint <-- (4,6)\n\np2 = p + p1", "_____no_output_____" ] ], [ [ "class Point:\n \n def __init__(self, x, y):\n self.__x = x\n self.__y = y\n \n def __str__(self):\n return \"This point is at (\" + str(self.__x)+\",\" + str(self.__y) + \")\"\n \n def __add__(self, point_object):\n return Point(self.__x + point_object.__x, self.__y + point_object.__y)\n \np1 = Point(1,2)\np2 = Point(4,5)\np3 = p1 + p2\nprint(p3)\n\n", "This point is at (5,7)\n" ], [ "import math\nclass Point:\n \n def __init__(self, x, y):\n self.__x = x\n self.__y = y\n \n def __str__(self):\n return \"This point is at (\" + str(self.__x)+\",\" + str(self.__y) + \")\"\n \n def __add__(self, point_object):\n return Point(self.__x + point_object.__x, self.__y + point_object.__y)\n \n def __lt__(self, point_object):\n return math.sqrt(self.__x**2 + self.__y**2) < math.sqrt(point_object.__x**2 + point_object.__y**2)\np1 = Point(1,2)\np2 = Point(4,5)\np3 = p1 + p2\nprint(p3)\np4 = p1 < p2\nprint(p4)\nprint(p2 < p1)\n", "This point is at (5,7)\nTrue\nFalse\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
ec51082a4eea4c51be84bc9c5ca3b388884204eb
1,007,867
ipynb
Jupyter Notebook
Image description.ipynb
xsuryanshx/Caption-and-Attributes-Prediction-
a0ce72ca8c05a8dede08e07637c98cdc996783ef
[ "Apache-2.0" ]
null
null
null
Image description.ipynb
xsuryanshx/Caption-and-Attributes-Prediction-
a0ce72ca8c05a8dede08e07637c98cdc996783ef
[ "Apache-2.0" ]
null
null
null
Image description.ipynb
xsuryanshx/Caption-and-Attributes-Prediction-
a0ce72ca8c05a8dede08e07637c98cdc996783ef
[ "Apache-2.0" ]
null
null
null
637.084071
189,490
0.912098
[ [ [ "<a href=\"https://colab.research.google.com/github/xsuryanshx/Caption-and-Attributes-Prediction/blob/main/TM_Assignment1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "* Name - Suryansh Singh Rawat\r\n* Email - [email protected]\r\n* Phone - +917722035623", "_____no_output_____" ], [ "**Note**\r\n* We need to design two models where the first one will take any fashion image URL and generate an AI based description.\r\n* We are free to take your assumptions and solve the problem.\r\n* We are assuming that the input images in the model will be downloaded already.\r\n* The model gives a decent overall accuracy (~97%) and the performance on unseen images is also decent. ", "_____no_output_____" ], [ "Requirements", "_____no_output_____" ] ], [ [ "import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport nltk\r\nimport re\r\nimport string\r\nimport pickle\r\nimport cv2\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import WordNetLemmatizer \r\nlemmatizer = WordNetLemmatizer() \r\nimport tensorflow as tf\r\nfrom keras.utils import plot_model\r\nfrom tensorflow.keras.applications import ResNet50, imagenet_utils\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\nfrom tensorflow.keras.preprocessing.text import Tokenizer\r\nfrom tensorflow.keras.optimizers import Adam\r\nfrom sklearn.model_selection import train_test_split\r\nfrom tensorflow.keras.utils import to_categorical\r\nfrom tensorflow.keras.models import Sequential, Model\r\nfrom tensorflow.keras.layers import Conv2D, Dropout, MaxPooling2D, Flatten, Dense, BatchNormalization, Input, \\\r\n LSTM, Embedding, Input, TimeDistributed, Bidirectional, Activation, RepeatVector, Concatenate", "_____no_output_____" ], [ "from google.colab import drive\r\ndrive.mount('/content/drive')", "Mounted at /content/drive\n" ], [ "cd /content/drive/MyDrive/TM Assignment", "/content/drive/MyDrive/TM Assignment\n" ], [ "df = pd.read_excel('dataset 1.xlsx')\r\ndf.head()", "_____no_output_____" ], [ "#Adding a '.' before the image path to access it\r\ndf['Image_Path'] = '.'+df['Image_Path']\r\nimgpath = df['Image_Path']\r\ndescription = df['Description']", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "k = 30 #random number from 0-499\r\nimg = cv2.imread(imgpath[k])\r\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\nplt.imshow(img)\r\nplt.xlabel(description[k]);", "_____no_output_____" ] ], [ [ "Image Feature extraction using ResNet50 Model", "_____no_output_____" ] ], [ [ "#Downloadign ResNet50 Model\r\nResNet = ResNet50(include_top=True)", "_____no_output_____" ], [ "#Model layout\r\nResNet_model = ResNet50(weights='imagenet')\r\nResNet_model = Model(inputs=ResNet_model.inputs, outputs=ResNet_model.layers[-2].output)\r\nResNet_model.summary()", "Model: \"model_5\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_4 (InputLayer) [(None, 224, 224, 3) 0 \n__________________________________________________________________________________________________\nconv1_pad (ZeroPadding2D) (None, 230, 230, 3) 0 input_4[0][0] \n__________________________________________________________________________________________________\nconv1_conv (Conv2D) (None, 112, 112, 64) 9472 conv1_pad[0][0] \n__________________________________________________________________________________________________\nconv1_bn (BatchNormalization) (None, 112, 112, 64) 256 conv1_conv[0][0] \n__________________________________________________________________________________________________\nconv1_relu (Activation) (None, 112, 112, 64) 0 conv1_bn[0][0] \n__________________________________________________________________________________________________\npool1_pad (ZeroPadding2D) (None, 114, 114, 64) 0 conv1_relu[0][0] \n__________________________________________________________________________________________________\npool1_pool (MaxPooling2D) (None, 56, 56, 64) 0 pool1_pad[0][0] \n__________________________________________________________________________________________________\nconv2_block1_1_conv (Conv2D) (None, 56, 56, 64) 4160 pool1_pool[0][0] \n__________________________________________________________________________________________________\nconv2_block1_1_bn (BatchNormali (None, 56, 56, 64) 256 conv2_block1_1_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block1_1_relu (Activation (None, 56, 56, 64) 0 conv2_block1_1_bn[0][0] \n__________________________________________________________________________________________________\nconv2_block1_2_conv (Conv2D) (None, 56, 56, 64) 36928 conv2_block1_1_relu[0][0] \n__________________________________________________________________________________________________\nconv2_block1_2_bn (BatchNormali (None, 56, 56, 64) 256 conv2_block1_2_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block1_2_relu (Activation (None, 56, 56, 64) 0 conv2_block1_2_bn[0][0] \n__________________________________________________________________________________________________\nconv2_block1_0_conv (Conv2D) (None, 56, 56, 256) 16640 pool1_pool[0][0] \n__________________________________________________________________________________________________\nconv2_block1_3_conv (Conv2D) (None, 56, 56, 256) 16640 conv2_block1_2_relu[0][0] \n__________________________________________________________________________________________________\nconv2_block1_0_bn (BatchNormali (None, 56, 56, 256) 1024 conv2_block1_0_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block1_3_bn (BatchNormali (None, 56, 56, 256) 1024 conv2_block1_3_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block1_add (Add) (None, 56, 56, 256) 0 conv2_block1_0_bn[0][0] \n conv2_block1_3_bn[0][0] \n__________________________________________________________________________________________________\nconv2_block1_out (Activation) (None, 56, 56, 256) 0 conv2_block1_add[0][0] \n__________________________________________________________________________________________________\nconv2_block2_1_conv (Conv2D) (None, 56, 56, 64) 16448 conv2_block1_out[0][0] \n__________________________________________________________________________________________________\nconv2_block2_1_bn (BatchNormali (None, 56, 56, 64) 256 conv2_block2_1_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block2_1_relu (Activation (None, 56, 56, 64) 0 conv2_block2_1_bn[0][0] \n__________________________________________________________________________________________________\nconv2_block2_2_conv (Conv2D) (None, 56, 56, 64) 36928 conv2_block2_1_relu[0][0] \n__________________________________________________________________________________________________\nconv2_block2_2_bn (BatchNormali (None, 56, 56, 64) 256 conv2_block2_2_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block2_2_relu (Activation (None, 56, 56, 64) 0 conv2_block2_2_bn[0][0] \n__________________________________________________________________________________________________\nconv2_block2_3_conv (Conv2D) (None, 56, 56, 256) 16640 conv2_block2_2_relu[0][0] \n__________________________________________________________________________________________________\nconv2_block2_3_bn (BatchNormali (None, 56, 56, 256) 1024 conv2_block2_3_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block2_add (Add) (None, 56, 56, 256) 0 conv2_block1_out[0][0] \n conv2_block2_3_bn[0][0] \n__________________________________________________________________________________________________\nconv2_block2_out (Activation) (None, 56, 56, 256) 0 conv2_block2_add[0][0] \n__________________________________________________________________________________________________\nconv2_block3_1_conv (Conv2D) (None, 56, 56, 64) 16448 conv2_block2_out[0][0] \n__________________________________________________________________________________________________\nconv2_block3_1_bn (BatchNormali (None, 56, 56, 64) 256 conv2_block3_1_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block3_1_relu (Activation (None, 56, 56, 64) 0 conv2_block3_1_bn[0][0] \n__________________________________________________________________________________________________\nconv2_block3_2_conv (Conv2D) (None, 56, 56, 64) 36928 conv2_block3_1_relu[0][0] \n__________________________________________________________________________________________________\nconv2_block3_2_bn (BatchNormali (None, 56, 56, 64) 256 conv2_block3_2_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block3_2_relu (Activation (None, 56, 56, 64) 0 conv2_block3_2_bn[0][0] \n__________________________________________________________________________________________________\nconv2_block3_3_conv (Conv2D) (None, 56, 56, 256) 16640 conv2_block3_2_relu[0][0] \n__________________________________________________________________________________________________\nconv2_block3_3_bn (BatchNormali (None, 56, 56, 256) 1024 conv2_block3_3_conv[0][0] \n__________________________________________________________________________________________________\nconv2_block3_add (Add) (None, 56, 56, 256) 0 conv2_block2_out[0][0] \n conv2_block3_3_bn[0][0] \n__________________________________________________________________________________________________\nconv2_block3_out (Activation) (None, 56, 56, 256) 0 conv2_block3_add[0][0] \n__________________________________________________________________________________________________\nconv3_block1_1_conv (Conv2D) (None, 28, 28, 128) 32896 conv2_block3_out[0][0] \n__________________________________________________________________________________________________\nconv3_block1_1_bn (BatchNormali (None, 28, 28, 128) 512 conv3_block1_1_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block1_1_relu (Activation (None, 28, 28, 128) 0 conv3_block1_1_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block1_2_conv (Conv2D) (None, 28, 28, 128) 147584 conv3_block1_1_relu[0][0] \n__________________________________________________________________________________________________\nconv3_block1_2_bn (BatchNormali (None, 28, 28, 128) 512 conv3_block1_2_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block1_2_relu (Activation (None, 28, 28, 128) 0 conv3_block1_2_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block1_0_conv (Conv2D) (None, 28, 28, 512) 131584 conv2_block3_out[0][0] \n__________________________________________________________________________________________________\nconv3_block1_3_conv (Conv2D) (None, 28, 28, 512) 66048 conv3_block1_2_relu[0][0] \n__________________________________________________________________________________________________\nconv3_block1_0_bn (BatchNormali (None, 28, 28, 512) 2048 conv3_block1_0_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block1_3_bn (BatchNormali (None, 28, 28, 512) 2048 conv3_block1_3_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block1_add (Add) (None, 28, 28, 512) 0 conv3_block1_0_bn[0][0] \n conv3_block1_3_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block1_out (Activation) (None, 28, 28, 512) 0 conv3_block1_add[0][0] \n__________________________________________________________________________________________________\nconv3_block2_1_conv (Conv2D) (None, 28, 28, 128) 65664 conv3_block1_out[0][0] \n__________________________________________________________________________________________________\nconv3_block2_1_bn (BatchNormali (None, 28, 28, 128) 512 conv3_block2_1_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block2_1_relu (Activation (None, 28, 28, 128) 0 conv3_block2_1_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block2_2_conv (Conv2D) (None, 28, 28, 128) 147584 conv3_block2_1_relu[0][0] \n__________________________________________________________________________________________________\nconv3_block2_2_bn (BatchNormali (None, 28, 28, 128) 512 conv3_block2_2_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block2_2_relu (Activation (None, 28, 28, 128) 0 conv3_block2_2_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block2_3_conv (Conv2D) (None, 28, 28, 512) 66048 conv3_block2_2_relu[0][0] \n__________________________________________________________________________________________________\nconv3_block2_3_bn (BatchNormali (None, 28, 28, 512) 2048 conv3_block2_3_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block2_add (Add) (None, 28, 28, 512) 0 conv3_block1_out[0][0] \n conv3_block2_3_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block2_out (Activation) (None, 28, 28, 512) 0 conv3_block2_add[0][0] \n__________________________________________________________________________________________________\nconv3_block3_1_conv (Conv2D) (None, 28, 28, 128) 65664 conv3_block2_out[0][0] \n__________________________________________________________________________________________________\nconv3_block3_1_bn (BatchNormali (None, 28, 28, 128) 512 conv3_block3_1_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block3_1_relu (Activation (None, 28, 28, 128) 0 conv3_block3_1_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block3_2_conv (Conv2D) (None, 28, 28, 128) 147584 conv3_block3_1_relu[0][0] \n__________________________________________________________________________________________________\nconv3_block3_2_bn (BatchNormali (None, 28, 28, 128) 512 conv3_block3_2_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block3_2_relu (Activation (None, 28, 28, 128) 0 conv3_block3_2_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block3_3_conv (Conv2D) (None, 28, 28, 512) 66048 conv3_block3_2_relu[0][0] \n__________________________________________________________________________________________________\nconv3_block3_3_bn (BatchNormali (None, 28, 28, 512) 2048 conv3_block3_3_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block3_add (Add) (None, 28, 28, 512) 0 conv3_block2_out[0][0] \n conv3_block3_3_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block3_out (Activation) (None, 28, 28, 512) 0 conv3_block3_add[0][0] \n__________________________________________________________________________________________________\nconv3_block4_1_conv (Conv2D) (None, 28, 28, 128) 65664 conv3_block3_out[0][0] \n__________________________________________________________________________________________________\nconv3_block4_1_bn (BatchNormali (None, 28, 28, 128) 512 conv3_block4_1_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block4_1_relu (Activation (None, 28, 28, 128) 0 conv3_block4_1_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block4_2_conv (Conv2D) (None, 28, 28, 128) 147584 conv3_block4_1_relu[0][0] \n__________________________________________________________________________________________________\nconv3_block4_2_bn (BatchNormali (None, 28, 28, 128) 512 conv3_block4_2_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block4_2_relu (Activation (None, 28, 28, 128) 0 conv3_block4_2_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block4_3_conv (Conv2D) (None, 28, 28, 512) 66048 conv3_block4_2_relu[0][0] \n__________________________________________________________________________________________________\nconv3_block4_3_bn (BatchNormali (None, 28, 28, 512) 2048 conv3_block4_3_conv[0][0] \n__________________________________________________________________________________________________\nconv3_block4_add (Add) (None, 28, 28, 512) 0 conv3_block3_out[0][0] \n conv3_block4_3_bn[0][0] \n__________________________________________________________________________________________________\nconv3_block4_out (Activation) (None, 28, 28, 512) 0 conv3_block4_add[0][0] \n__________________________________________________________________________________________________\nconv4_block1_1_conv (Conv2D) (None, 14, 14, 256) 131328 conv3_block4_out[0][0] \n__________________________________________________________________________________________________\nconv4_block1_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block1_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_1_relu (Activation (None, 14, 14, 256) 0 conv4_block1_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block1_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block1_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block1_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block1_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_2_relu (Activation (None, 14, 14, 256) 0 conv4_block1_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block1_0_conv (Conv2D) (None, 14, 14, 1024) 525312 conv3_block4_out[0][0] \n__________________________________________________________________________________________________\nconv4_block1_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block1_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block1_0_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block1_0_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block1_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_add (Add) (None, 14, 14, 1024) 0 conv4_block1_0_bn[0][0] \n conv4_block1_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block1_out (Activation) (None, 14, 14, 1024) 0 conv4_block1_add[0][0] \n__________________________________________________________________________________________________\nconv4_block2_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block1_out[0][0] \n__________________________________________________________________________________________________\nconv4_block2_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block2_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block2_1_relu (Activation (None, 14, 14, 256) 0 conv4_block2_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block2_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block2_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block2_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block2_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block2_2_relu (Activation (None, 14, 14, 256) 0 conv4_block2_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block2_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block2_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block2_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block2_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block2_add (Add) (None, 14, 14, 1024) 0 conv4_block1_out[0][0] \n conv4_block2_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block2_out (Activation) (None, 14, 14, 1024) 0 conv4_block2_add[0][0] \n__________________________________________________________________________________________________\nconv4_block3_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block2_out[0][0] \n__________________________________________________________________________________________________\nconv4_block3_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block3_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block3_1_relu (Activation (None, 14, 14, 256) 0 conv4_block3_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block3_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block3_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block3_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block3_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block3_2_relu (Activation (None, 14, 14, 256) 0 conv4_block3_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block3_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block3_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block3_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block3_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block3_add (Add) (None, 14, 14, 1024) 0 conv4_block2_out[0][0] \n conv4_block3_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block3_out (Activation) (None, 14, 14, 1024) 0 conv4_block3_add[0][0] \n__________________________________________________________________________________________________\nconv4_block4_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block3_out[0][0] \n__________________________________________________________________________________________________\nconv4_block4_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block4_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block4_1_relu (Activation (None, 14, 14, 256) 0 conv4_block4_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block4_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block4_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block4_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block4_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block4_2_relu (Activation (None, 14, 14, 256) 0 conv4_block4_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block4_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block4_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block4_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block4_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block4_add (Add) (None, 14, 14, 1024) 0 conv4_block3_out[0][0] \n conv4_block4_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block4_out (Activation) (None, 14, 14, 1024) 0 conv4_block4_add[0][0] \n__________________________________________________________________________________________________\nconv4_block5_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block4_out[0][0] \n__________________________________________________________________________________________________\nconv4_block5_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block5_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block5_1_relu (Activation (None, 14, 14, 256) 0 conv4_block5_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block5_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block5_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block5_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block5_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block5_2_relu (Activation (None, 14, 14, 256) 0 conv4_block5_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block5_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block5_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block5_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block5_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block5_add (Add) (None, 14, 14, 1024) 0 conv4_block4_out[0][0] \n conv4_block5_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block5_out (Activation) (None, 14, 14, 1024) 0 conv4_block5_add[0][0] \n__________________________________________________________________________________________________\nconv4_block6_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block5_out[0][0] \n__________________________________________________________________________________________________\nconv4_block6_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block6_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block6_1_relu (Activation (None, 14, 14, 256) 0 conv4_block6_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block6_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block6_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block6_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block6_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block6_2_relu (Activation (None, 14, 14, 256) 0 conv4_block6_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block6_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block6_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block6_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block6_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block6_add (Add) (None, 14, 14, 1024) 0 conv4_block5_out[0][0] \n conv4_block6_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block6_out (Activation) (None, 14, 14, 1024) 0 conv4_block6_add[0][0] \n__________________________________________________________________________________________________\nconv5_block1_1_conv (Conv2D) (None, 7, 7, 512) 524800 conv4_block6_out[0][0] \n__________________________________________________________________________________________________\nconv5_block1_1_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block1_1_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_1_relu (Activation (None, 7, 7, 512) 0 conv5_block1_1_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block1_2_conv (Conv2D) (None, 7, 7, 512) 2359808 conv5_block1_1_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block1_2_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block1_2_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_2_relu (Activation (None, 7, 7, 512) 0 conv5_block1_2_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block1_0_conv (Conv2D) (None, 7, 7, 2048) 2099200 conv4_block6_out[0][0] \n__________________________________________________________________________________________________\nconv5_block1_3_conv (Conv2D) (None, 7, 7, 2048) 1050624 conv5_block1_2_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block1_0_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block1_0_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_3_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block1_3_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_add (Add) (None, 7, 7, 2048) 0 conv5_block1_0_bn[0][0] \n conv5_block1_3_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block1_out (Activation) (None, 7, 7, 2048) 0 conv5_block1_add[0][0] \n__________________________________________________________________________________________________\nconv5_block2_1_conv (Conv2D) (None, 7, 7, 512) 1049088 conv5_block1_out[0][0] \n__________________________________________________________________________________________________\nconv5_block2_1_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block2_1_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block2_1_relu (Activation (None, 7, 7, 512) 0 conv5_block2_1_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block2_2_conv (Conv2D) (None, 7, 7, 512) 2359808 conv5_block2_1_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block2_2_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block2_2_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block2_2_relu (Activation (None, 7, 7, 512) 0 conv5_block2_2_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block2_3_conv (Conv2D) (None, 7, 7, 2048) 1050624 conv5_block2_2_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block2_3_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block2_3_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block2_add (Add) (None, 7, 7, 2048) 0 conv5_block1_out[0][0] \n conv5_block2_3_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block2_out (Activation) (None, 7, 7, 2048) 0 conv5_block2_add[0][0] \n__________________________________________________________________________________________________\nconv5_block3_1_conv (Conv2D) (None, 7, 7, 512) 1049088 conv5_block2_out[0][0] \n__________________________________________________________________________________________________\nconv5_block3_1_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block3_1_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block3_1_relu (Activation (None, 7, 7, 512) 0 conv5_block3_1_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block3_2_conv (Conv2D) (None, 7, 7, 512) 2359808 conv5_block3_1_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block3_2_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block3_2_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block3_2_relu (Activation (None, 7, 7, 512) 0 conv5_block3_2_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block3_3_conv (Conv2D) (None, 7, 7, 2048) 1050624 conv5_block3_2_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block3_3_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block3_3_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block3_add (Add) (None, 7, 7, 2048) 0 conv5_block2_out[0][0] \n conv5_block3_3_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block3_out (Activation) (None, 7, 7, 2048) 0 conv5_block3_add[0][0] \n__________________________________________________________________________________________________\navg_pool (GlobalAveragePooling2 (None, 2048) 0 conv5_block3_out[0][0] \n==================================================================================================\nTotal params: 23,587,712\nTrainable params: 23,534,592\nNon-trainable params: 53,120\n__________________________________________________________________________________________________\n" ], [ "#Creating a dictionary of image path and predicted image feaure using ResNet50 Model\r\nimgfeatures = {}\r\ncount = 0\r\nfor i in range(len(imgpath)):\r\n img = cv2.imread(imgpath[i])\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n img = cv2.resize(img,(224,224))\r\n img = img.reshape(1,224,224,3)\r\n imgfeatures[imgpath[i]] = ResNet_model.predict(img)[0]\r\n count+=1\r\n if count%50 == 0:\r\n print(count,'image features predicted')", "50 image features predicted\n100 image features predicted\n150 image features predicted\n200 image features predicted\n250 image features predicted\n300 image features predicted\n350 image features predicted\n400 image features predicted\n450 image features predicted\n500 image features predicted\n" ], [ "#storing the image features\r\nwith open('imgfeatures.txt','wb') as f1:\r\n pickle.dump(imgfeatures,f1)", "_____no_output_____" ], [ "#loading the stored image feature dictionary\r\nimgfeatures = pickle.load(open('imgfeatures.txt','rb'))", "_____no_output_____" ], [ "#Creating dictionary of image path and image description\r\ncatalouge = {}\r\nfor i in range(len(imgpath)):\r\n catalouge[imgpath[i]] = str('seqstart ')+description[i]+str(' seqend')", "_____no_output_____" ] ], [ [ "NLP Model", "_____no_output_____" ] ], [ [ "#Model Tokenizer for descriptions\r\ntokenizer = Tokenizer() #split=\" \",filters='!\"#$%()*+,-.:;<=>?@[\\\\]^_`{|}~\\t\\n'\r\ndata = []\r\nfor i in range(len(description)):\r\n data.append(catalouge[imgpath[i]].lower())\r\n\r\ntokenizer.fit_on_texts(data)\r\n\r\ntotal_words = int(len(tokenizer.word_index))+1\r\nprint(total_words)\r\nprint(tokenizer.word_index)\r\nprint(tokenizer.word_counts)", "1526\n{'and': 1, 'a': 2, 'with': 3, 'this': 4, 'seqstart': 5, 'seqend': 6, 'the': 7, 'to': 8, 'for': 9, 'style': 10, 'dress': 11, 'top': 12, 'is': 13, 'in': 14, 'look': 15, 'sleeves': 16, 'of': 17, 'pair': 18, 'it': 19, 'heels': 20, 'from': 21, 'neck': 22, 'complete': 23, 'on': 24, 'at': 25, 'features': 26, 'crafted': 27, 'fit': 28, 'your': 29, 'neckline': 30, 'polyester': 31, 'by': 32, 'front': 33, 'back': 34, 'up': 35, 'cotton': 36, 'jumpsuit': 37, 'high': 38, 'black': 39, 'v': 40, 'statement': 41, 'an': 42, 'printed': 43, 'regular': 44, 'waist': 45, 'shoulder': 46, 'shirt': 47, 'blue': 48, 'zipper': 49, 'floral': 50, 'silhouette': 51, 'fastening': 52, 'tie': 53, 'ease': 54, 'wear': 55, 'casual': 56, 'accessories': 57, 'will': 58, 'long': 59, 'you': 60, 'short': 61, 'buy': 62, 'online': 63, 'white': 64, 'or': 65, 'perfect': 66, 'button': 67, 'crepe': 68, 'round': 69, 'side': 70, 'that': 71, 'knit': 72, 'has': 73, 'concealed': 74, 'detailing': 75, 'comfort': 76, 'fabric': 77, 'jeans': 78, 'featuring': 79, 'piece': 80, 'be': 81, 'wardrobe': 82, 'all': 83, 'straps': 84, 'make': 85, 'denims': 86, 'maxi': 87, 'sleeveless': 88, 'team': 89, 'flare': 90, 'chic': 91, 'lining': 92, 'hem': 93, 'br': 94, 'details': 95, 'one': 96, '3': 97, 'straight': 98, 'earrings': 99, 'rayon': 100, 'belt': 101, 'cut': 102, 'buttons': 103, 'pink': 104, 'pants': 105, 'print': 106, '4th': 107, 'off': 108, 'block': 109, 'gap': 110, 'bag': 111, 'only': 112, 'elegant': 113, 'overlapping': 114, 'collar': 115, 'create': 116, 'yours': 117, 'closure': 118, 'over': 119, 'li': 120, 'addition': 121, 'pockets': 122, 'stunning': 123, 'green': 124, 'detail': 125, 'made': 126, 'sneakers': 127, 'denim': 128, 'out': 129, 'collection': 130, 'soft': 131, 'design': 132, 'wrap': 133, 'hemline': 134, 'elasticated': 135, 'skinny': 136, 'left': 137, 't': 138, 'midi': 139, 'fine': 140, 'stylish': 141, 'colour': 142, 'georgette': 143, 'square': 144, 'can': 145, 'flared': 146, 'navy': 147, 'slit': 148, 'placket': 149, 'flats': 150, 'line': 151, 'dresses': 152, 'are': 153, 'peplum': 154, 'viscose': 155, 'yoke': 156, 'bottom': 157, 'skirt': 158, 'makes': 159, 'inside': 160, 'have': 161, 'trendy': 162, 'polka': 163, 'adjustable': 164, 'day': 165, 'wearing': 166, 'comes': 167, 'work': 168, 'add': 169, 'jewellery': 170, 'crop': 171, 'puff': 172, 'red': 173, 'length': 174, 'yellow': 175, 'gown': 176, 'maroon': 177, 'clutch': 178, 'strappy': 179, 'sleeve': 180, 'set': 181, 'center': 182, 'ruffles': 183, 'embroidery': 184, 'full': 185, 'smocked': 186, 'lace': 187, 'cool': 188, 'three': 189, 'ensemble': 190, 'western': 191, 'solid': 192, 'events': 193, 'twenty': 194, 'jacket': 195, 'as': 196, 'sweatshirt': 197, 'embellished': 198, 'embroidered': 199, 'subtle': 200, 'zip': 201, 'evening': 202, 'satin': 203, 'comfortable': 204, 'hand': 205, 'love': 206, 'pleated': 207, 'its': 208, 'centre': 209, 'fourth': 210, 'striped': 211, 'gold': 212, 'ready': 213, 'multi': 214, 'kazo': 215, 'color': 216, 'ruffled': 217, 'elastic': 218, 'trousers': 219, 'cute': 220, 'crossbody': 221, 'buttoned': 222, 'down': 223, 'easy': 224, 'sling': 225, 'season': 226, 'gathers': 227, \"it's\": 228, 'bottoms': 229, 'band': 230, 'crew': 231, 'wide': 232, 'go': 233, 'keyhole': 234, 'outfit': 235, 'great': 236, 'classic': 237, 'may': 238, 'signature': 239, 'smocking': 240, 'linen': 241, 'summer': 242, 'vero': 243, 'moda': 244, 'women': 245, 'accessorize': 246, 'height': 247, 'size': 248, 'jeggings': 249, 'must': 250, 'keep': 251, 'occasions': 252, 'pattern': 253, 'half': 254, 'jersey': 255, 'care': 256, 'which': 257, 'both': 258, 'sides': 259, 'cuff': 260, 'when': 261, 'pick': 262, 'next': 263, 'any': 264, 'frill': 265, 'deep': 266, 'light': 267, 'beige': 268, 'nude': 269, 'relaxed': 270, 'model': 271, \"5'6\": 272, 'xs': 273, 'mandarin': 274, 'leg': 275, 'take': 276, 'cuffs': 277, 'box': 278, 'get': 279, 'stilettos': 280, 'attached': 281, 'our': 282, 'handmade': 283, 'various': 284, 'slight': 285, 'stripe': 286, 'balloon': 287, 'ruffle': 288, 'days': 289, 'moss': 290, 'effortless': 291, 'brunch': 292, 'time': 293, 'payal': 294, 'footwear': 295, 'bell': 296, 'party': 297, 'looks': 298, 'don': 299, 'kurta': 300, 'peach': 301, 'check': 302, 'smart': 303, 'jaipur': 304, 'please': 305, 'note': 306, 'artisans': 307, 'therefore': 308, 'differences': 309, 'occur': 310, 'allows': 311, 'kind': 312, 'aesthetic': 313, 'natural': 314, 'tee': 315, 'stripes': 316, 'weekend': 317, 'unique': 318, 'shorts': 319, 'ruching': 320, 'strap': 321, 'logo': 322, 'halter': 323, 'incut': 324, 'waistline': 325, 'blazer': 326, 'shoulders': 327, 'dot': 328, 'torqadorn': 329, 'minimal': 330, 'silver': 331, 'fitted': 332, 'handbag': 333, 'asymmetrical': 334, 'embellishments': 335, 'pleats': 336, 'grey': 337, 'sized': 338, 'cover': 339, 'story': 340, 'mustard': 341, 'golden': 342, 'self': 343, 'matching': 344, 'kurti': 345, 'blend': 346, 'we': 347, 'new': 348, 'drawstring': 349, 'touch': 350, 'campus': 351, 'sutra': 352, 'favourite': 353, 'thigh': 354, 'girlfriend': 355, 'night': 356, 'give': 357, 'choice': 358, 'smooth': 359, 'sandals': 360, 'hook': 361, 'velvet': 362, 'ace': 363, 'pullover': 364, 'trend': 365, 'brown': 366, 'gorgeous': 367, 'need': 368, 'pure': 369, 'delicate': 370, 'slip': 371, 'simple': 372, 'pleat': 373, 'office': 374, 'created': 375, 'patterns': 376, 'very': 377, 'label': 378, 'extra': 379, 'fresh': 380, 'indigo': 381, 'handloom': 382, 'open': 383, 'twill': 384, 'mini': 385, 'sheath': 386, 'aeropostale': 387, 'around': 388, 'okhai': 389, 'vibrant': 390, 'graphic': 391, 'adds': 392, 'rust': 393, 'playsuit': 394, 'lapel': 395, 'sequin': 396, 'show': 397, 'pant': 398, 'olive': 399, 'fashion': 400, 'finished': 401, 'low': 402, 'those': 403, 'singhal': 404, 'finesse': 405, 'boyfriend': 406, 'garment': 407, 'broad': 408, 'range': 409, 'boat': 410, 'mish': 411, 'faballey': 412, 'daytime': 413, 'tan': 414, 'tip': 415, 'some': 416, 'metallic': 417, 'colours': 418, 'gathered': 419, 'refreshing': 420, 'breezy': 421, 'occasion': 422, 'forever': 423, 'bodice': 424, 'leggings': 425, 'also': 426, 'styled': 427, 'stud': 428, 'layered': 429, 'dyed': 430, 'legged': 431, 'classy': 432, 'feel': 433, 'everything': 434, 'multicolor': 435, 'attachment': 436, 'culottes': 437, 'sheer': 438, 'knot': 439, 'formal': 440, 'even': 441, 'while': 442, 'ribbed': 443, 'curved': 444, 'voile': 445, \"gap's\": 446, 'flutter': 447, 'inspire': 448, 'asymmetric': 449, 'cross': 450, 'beautiful': 451, 'cocktail': 452, 'free': 453, 'ritu': 454, 'kumar': 455, 'tube': 456, 'silk': 457, 'shrug': 458, 'yet': 459, 'mix': 460, 'pint': 461, 'eyelet': 462, 'woven': 463, 'fully': 464, 'banded': 465, 'through': 466, 'cuffed': 467, 'blouse': 468, 'coat': 469, 'designs': 470, 'glamorous': 471, 'store': 472, 'super': 473, 'slits': 474, 'tiered': 475, 'bodycon': 476, 'drop': 477, 'attic': 478, 'salt': 479, 'event': 480, 'platform': 481, 'fun': 482, 'foil': 483, 'janasya': 484, '4': 485, 'mid': 486, 'hip': 487, 'attain': 488, 'bust': 489, 'no': 490, 'fastened': 491, 'coconut': 492, 'khadi': 493, 'blended': 494, 'bold': 495, 'collared': 496, 'wooden': 497, 'motifs': 498, 'compliments': 499, 'number': 500, 'trims': 501, 'duty': 502, 'sweetheart': 503, 'weddings': 504, 'co': 505, 'ord': 506, 'essential': 507, 'paired': 508, 'along': 509, 'prints': 510, 'timeless': 511, 'versatile': 512, 'two': 513, 'blush': 514, 'pared': 515, 'pairing': 516, 'friends': 517, '100': 518, 'teaming': 519, 'elevate': 520, 'lined': 521, 'checks': 522, 'ikat': 523, 'fabnest': 524, 'slim': 525, 'body': 526, 'purple': 527, 'eye': 528, 'girls': 529, 'after': 530, 'do': 531, 'tailored': 532, 'uber': 533, 'mirror': 534, 'house': 535, 'rib': 536, 'into': 537, 'coloured': 538, 'fabricated': 539, 'amazing': 540, 'these': 541, 'apparels': 542, 'too': 543, 'rid': 544, \"'regular'\": 545, 'surely': 546, 'looking': 547, 'dhoti': 548, 'layer': 549, 'warm': 550, 'cropped': 551, 'chiffon': 552, 'shade': 553, 'friendly': 554, 'wrinkle': 555, 'criss': 556, 'resistant': 557, 'sure': 558, 'ruched': 559, 'pretty': 560, 'rise': 561, 'designed': 562, 'complement': 563, 'sweater': 564, 'cold': 565, 'small': 566, 'p': 567, 'b': 568, 'ul': 569, 'trouser': 570, 'dose': 571, 'well': 572, 'closet': 573, 'without': 574, 'like': 575, 'under': 576, 'chunky': 577, 'contemporary': 578, 'indian': 579, 'skirts': 580, 'panel': 581, 'functional': 582, 'tops': 583, 'cord': 584, 'baise': 585, 'gaba': 586, 'draped': 587, 'tulle': 588, 'airy': 589, 'palazzos': 590, 'flip': 591, 'flops': 592, 'shoe': 593, 'bunaai': 594, 'teamed': 595, 'definitely': 596, 'stand': 597, 'temperature': 598, 'drops': 599, 'mock': 600, 'good': 601, 'quality': 602, 'breathable': 603, 'special': 604, 'uneven': 605, 'net': 606, 'if': 607, 'want': 608, 'weekends': 609, 'bring': 610, 'it’s': 611, 'so': 612, 'pratap': 613, 'everyday': 614, 'split': 615, 'every': 616, 'bit': 617, 'thread': 618, 'dressing': 619, 'present': 620, 'allure': 621, 'elegance': 622, 'premium': 623, 'presents': 624, 'contrast': 625, 'more': 626, 'loop': 627, 'leather': 628, 'bespoke': 629, 'idalia': 630, 'gather': 631, 'quotient': 632, 'dates': 633, 'beads': 634, 'not': 635, 'freshen': 636, 'spells': 637, 'warmth': 638, 'fetch': 639, 'yourself': 640, 'elasticized': 641, 'brogues': 642, 'teal': 643, 'rose': 644, 'accentuated': 645, 'bomber': 646, 'tunic': 647, 'slide': 648, 'multiple': 649, 'simply': 650, 'dazzle': 651, 'flair': 652, 'sun': 653, 'using': 654, 'stylised': 655, 'chest': 656, 'nylon': 657, 'double': 658, 'vibe': 659, 'vacation': 660, 'perfectly': 661, 'overlap': 662, 'styling': 663, 'away': 664, 'cowl': 665, 'hoops': 666, 'toe': 667, 'sweat': 668, 'key': 669, 'hole': 670, 'what': 671, 'worn': 672, 'staple': 673, 'lycra': 674, 'buckle': 675, 'hair': 676, 'stiletto': 677, 'biba': 678, 'lbd': 679, 'accented': 680, 'hoop': 681, 'holiday': 682, 'separates': 683, 'tone': 684, 'camisole': 685, 'studs': 686, 'patterned': 687, 'way': 688, 'notch': 689, 'tea': 690, 'best': 691, 'poly': 692, 'attractive': 693, 'calf': 694, 'suitable': 695, 'bias': 696, 'cape': 697, 'touches': 698, 'washed': 699, 'wood': 700, 'circular': 701, 'mirrors': 702, 'separate': 703, \"aeropostale's\": 704, 'distressed': 705, 'twisted': 706, 'their': 707, 'build': 708, 'strike': 709, 'balance': 710, 'feels': 711, 'against': 712, 'skin': 713, 'bow': 714, 'single': 715, 'accentuate': 716, 'lilac': 717, 'tarun': 718, 'tahiliani': 719, 'crinkle': 720, 'festivity': 721, 'waisted': 722, 'purpose': 723, 'apart': 724, 'appeal': 725, 'throw': 726, 'bishop': 727, 'blouson': 728, 'inspired': 729, 'known': 730, 'hits': 731, 'lift': 732, 'mood': 733, 'real': 734, 'meetups': 735, 'steal': 736, 'buti': 737, 'having': 738, 'sleeved': 739, 'meant': 740, 'forward': 741, 'wrist': 742, 'easily': 743, 'transition': 744, 'traditional': 745, 'flattering': 746, 'better': 747, 'dreamy': 748, 'shine': 749, 'textured': 750, 'boots': 751, 'feminine': 752, 'ambraee': 753, 'differ': 754, 'picture': 755, 'dark': 756, 'abutilon': 757, 'amaiva': 758, 'piping': 759, 'tassels': 760, 'aurora': 761, 'alluring': 762, 'modal': 763, 'strings': 764, 'tassel': 765, 'loose': 766, 'pencil': 767, 'court': 768, 'level': 769, 'embellishment': 770, 'dinner': 771, 'thin': 772, 'dots': 773, 'they': 774, 'sequins': 775, 'winter': 776, 'apron': 777, 'inner': 778, 'drawcord': 779, 'ties': 780, 'culotte': 781, 'lets': 782, 'adjust': 783, 'meet': 784, 'constructed': 785, 'achieve': 786, 'that’s': 787, 'romantic': 788, 'wine': 789, 'business': 790, 'whether': 791, 'flavouring': 792, 'coffee': 793, 'taking': 794, 'project': 795, 'lead': 796, 'heading': 797, 'drinks': 798, \"torqadorn's\": 799, 'iridescent': 800, 'ways': 801, 'fabrication': 802, 'feature': 803, 'knitted': 804, 'dohyenne': 805, 'jogger': 806, 'ideal': 807, 'arrives': 808, 'mint': 809, 'pearl': 810, 'extending': 811, 'stretchable': 812, 'snuggly': 813, 'cardigan': 814, 'hems': 815, 'step': 816, 'breasted': 817, 'tulip': 818, 'ahead': 819, 'tier': 820, 'boasts': 821, 'combination': 822, 'dropped': 823, 'highly': 824, 'then': 825, 'divena': 826, 'answer': 827, 'presenting': 828, 'divenas': 829, 'rising': 830, 'tussles': 831, 'closed': 832, 'outing': 833, 'mojri': 834, 'ravishing': 835, 'desi': 836, 'vertical': 837, 'horizontal': 838, 'princess': 839, 'chain': 840, 'hint': 841, 'detailed': 842, 'scoop': 843, 'outings': 844, 'organic': 845, 'constellation': 846, 'meetings': 847, 'travel': 848, 'worthy': 849, 'update': 850, 'game': 851, 'shimmer': 852, 'frilled': 853, \"women's\": 854, 'fablestreet': 855, 'micro': 856, 'ripped': 857, 'flap': 858, 'amp': 859, 'roll': 860, 'type': 861, 'bleeding': 862, 'thereby': 863, 'making': 864, 'lasting': 865, 'absorbent': 866, 'armpit': 867, 'used': 868, 'underarm': 869, 'stains': 870, 'maison': 871, 'shefali': 872, 'jompers': 873, 'aaliya': 874, 'running': 875, 'speaks': 876, 'glass': 877, 'dance': 878, 'hands': 879, 'serious': 880, 'upgrade': 881, 'detachable': 882, 'orange': 883, 'opening': 884, 'stay': 885, 'edge': 886, 'antique': 887, 'pointed': 888, 'material': 889, 'anti': 890, 'according': 891, 'mesh': 892, 'decorated': 893, 'florals': 894, 'date': 895, 'rotation': 896, 'sequined': 897, 'charming': 898, 'false': 899, '2': 900, 'woman': 901, 'equal': 902, 'parts': 903, 'structured': 904, 'product': 905, 'twist': 906, 'flowy': 907, 'never': 908, 'dry': 909, 'india': 910, 'chinese': 911, 'scattered': 912, 'mauve': 913, 'things': 914, 'massive': 915, 'points': 916, 'tencel': 917, 'lyocell': 918, 'pumps': 919, 'polished': 920, 'handcrafted': 921, 'mul': 922, 'offers': 923, 'medium': 924, 'edited': 925, 'close': 926, 'excited': 927, 'announce': 928, 'awaited': 929, 'launch': 930, 'clothing': 931, 'painted': 932, 'textiles': 933, 'thrilled': 934, 'gilet': 935, 'equally': 936, 'leaf': 937, 'danglers': 938, 'charm': 939, 'bracelet': 940, 'ajrakh': 941, 'jigsaw': 942, 'panelling': 943, 'dungarees': 944, 'geometric': 945, 'glitter': 946, 'producing': 947, 'casuals': 948, 'cinch': 949, 'sparkle': 950, 'blanket': 951, 'stitch': 952, 'cheerful': 953, 'optimist': 954, 'destination': 955, 'solo': 956, 'cafe': 957, 'above': 958, 'kniited': 959, 'lovely': 960, 'hued': 961, 'options': 962, 'many': 963, 'scalloped': 964, 'fullness': 965, 'romance': 966, 'elevated': 967, 'let': 968, 'flatters': 969, 'who': 970, 'heavy': 971, 'envelope': 972, 'incuts': 973, 'revamp': 974, 'crotch': 975, 'mules': 976, 'spots': 977, 'fringe': 978, 'kitten': 979, 'plunging': 980, 'kimono': 981, 'pack': 982, 'burgundy': 983, 'exaggerated': 984, 'string': 985, 'butterfly': 986, 'daywear': 987, 'loops': 988, 'pristine': 989, \"isn't\": 990, 'restricted': 991, 'hour': 992, 'includes': 993, 'panelled': 994, 'confident': 995, 'hemp': 996, 'depending': 997, 'versatility': 998, 'desk': 999, 'either': 1000, 'beautifully': 1001, 'dusty': 1002, 'scores': 1003, 'bugle': 1004, 'own': 1005, 'does': 1006, 'accessory': 1007, 'adding': 1008, 'save': 1009, 'rusty': 1010, 'stacked': 1011, 'bracelets': 1012, 'rings': 1013, 'ankle': 1014, 'composition': 1015, 'relax': 1016, 'quarter': 1017, 'designer': 1018, 'womens': 1019, 'shift': 1020, 'accompaniment': 1021, 'chilly': 1022, 'theatre': 1023, 'indoors': 1024, 'poncho': 1025, 'rescue': 1026, 'touting': 1027, 'handkerchief': 1028, 'wonder': 1029, 'a\\xa0unique': 1030, 'de': 1031, 'structural': 1032, 'ambiguity': 1033, 'tacey': 1034, 'mocks': 1035, 'trials': 1036, 'promising': 1037, 'inverted': 1038, 'gulaal': 1039, 'zari': 1040, 'seam': 1041, 'choker': 1042, 'nose': 1043, 'pin': 1044, 'festive': 1045, 'fastens': 1046, 'sild': 1047, 'spring': 1048, 'lightweight': 1049, 'welt': 1050, 'cosy': 1051, 'threads': 1052, 'drawcords': 1053, 'hoodie': 1054, 'tank': 1055, 'blossom': 1056, 'colored': 1057, 'trench': 1058, 'broderie': 1059, 'sunny': 1060, 'pastel': 1061, 'heeled': 1062, 'hemmed': 1063, 'dangler': 1064, 'prepare': 1065, 'rendezvous': 1066, 'torso': 1067, 'racer': 1068, 'rivets': 1069, 'ushers': 1070, 'shirring': 1071, 'slinky': 1072, 'flowers': 1073, 'promises': 1074, 'rolled': 1075, 'armhole': 1076, 'highest': 1077, 'respite': 1078, 'seek': 1079, 'jodhpuri': 1080, 'weaves': 1081, 'flawless': 1082, 'finish': 1083, 'theis': 1084, 'polyster': 1085, \"won't\": 1086, 'soon': 1087, 'tiers': 1088, 'parties': 1089, 'cap': 1090, 'puffy': 1091, 'kaftaan': 1092, 'here': 1093, 'andromeda': 1094, 'pervasive': 1095, 'weight': 1096, 'fuss': 1097, 'gives': 1098, 'breathing': 1099, 'space': 1100, 'amplifying': 1101, 'hi': 1102, 'wearable': 1103, 'latest': 1104, 'quick': 1105, 'drying': 1106, 'helps': 1107, 'avoid': 1108, 'patches': 1109, 'polycotton': 1110, 'channel': 1111, 'retro': 1112, 'vibes': 1113, 'a\\xa0floral': 1114, 'print\\xa0fabric': 1115, 'a\\xa0self': 1116, 'till': 1117, 'dusk': 1118, 'sharp': 1119, 'creating': 1120, 'basics': 1121, 'basis': 1122, 'loungewear': 1123, 'canvas': 1124, 'branding': 1125, 'seasoned': 1126, 'knife': 1127, 'content': 1128, 'acrylic': 1129, 'head': 1130, 'with\\xa0open': 1131, 'flats\\xa0and': 1132, 'clip': 1133, 'attire': 1134, 'yarn': 1135, 'suited': 1136, 'slender': 1137, 'frames': 1138, 'spruce': 1139, 'weather': 1140, 'pieces': 1141, 'hot': 1142, 'muslin': 1143, 'tonal': 1144, 'ivory': 1145, 'base': 1146, 'joint': 1147, 'works': 1148, 'spot': 1149, 'flaunt': 1150, 'togethers': 1151, 'punctured': 1152, 'eyelets': 1153, 'ribbon': 1154, 'forming': 1155, 'secret': 1156, 'headed': 1157, 'hierarchy': 1158, 'why': 1159, 'satiny': 1160, 'texture': 1161, 'smashing': 1162, 'ceiling': 1163, 'called': 1164, '‘freedom’': 1165, 'movement': 1166, 'jive': 1167, 'shop': 1168, 'run': 1169, 'accent': 1170, 'cambric': 1171, 'maybe': 1172, 'visiting': 1173, 'friend’s': 1174, 'thick': 1175, 'elastication': 1176, 'going': 1177, 'construction': 1178, 'layering': 1179, 'tucked': 1180, 'master': 1181, 'art': 1182, 'lurex': 1183, 'updated': 1184, 'dainty': 1185, 'periwinkle': 1186, 'absolutely': 1187, 'cluster': 1188, 'shell': 1189, 'whereas': 1190, 'part': 1191, 'multitiered': 1192, 'metre': 1193, 'knee': 1194, 'a\\xa0baby': 1195, 'and\\xa0adjustable': 1196, 'obsessed': 1197, 'crowd': 1198, 'surplice': 1199, 'pill': 1200, 'intended': 1201, 'fall': 1202, 'image': 1203, \"5'3\": 1204, \"5'5\": 1205, 'vary': 1206, 'slightly': 1207, 'screen': 1208, 'settings': 1209, 'resolution': 1210, 'baby': 1211, 'strapless': 1212, 'fabulous': 1213, 'attires': 1214, 'ove': 1215, 'rit': 1216, 'border': 1217, '1': 1218, 'fixed': 1219, 'extended': 1220, 'accessorise': 1221, 'gaped': 1222, 'cups': 1223, 'cami': 1224, 'neutral': 1225, 'hue': 1226, 'floaty': 1227, 'prom': 1228, 'nights': 1229, 'brunches': 1230, 'cocktails': 1231, 'found': 1232, 'suede': 1233, 'epaulets': 1234, 'leading': 1235, 'dramatic': 1236, 'creation': 1237, 'reach': 1238, 'again': 1239, 'version': 1240, 'crinkled': 1241, 'notched': 1242, 'slides': 1243, 'cigarette': 1244, 'empire': 1245, 'tapered': 1246, 'ankles': 1247, 'pinstripe': 1248, 'wool': 1249, 'multicolored': 1250, 'serves': 1251, 'blank': 1252, 'slate': 1253, 'diamond': 1254, 'queen': 1255, 'anne': 1256, 'spotty': 1257, 'pointy': 1258, 'true': 1259, 'name': 1260, '‘spunk’': 1261, 'carries': 1262, 'fortitude': 1263, 'girl': 1264, 'door': 1265, 'tint': 1266, 'grit': 1267, 'one’s': 1268, 'personality': 1269, 'site': 1270, 'orion': 1271, 'right': 1272, 'aries': 1273, 'striking': 1274, 'phases': 1275, 'moon': 1276, 'flaps': 1277, 'dual': 1278, 'stitches': 1279, 'chirpy': 1280, 'sport': 1281, 'folded': 1282, 'royal': 1283, 'tote': 1284, 'dangling': 1285, 'enhance': 1286, 'multicolour': 1287, 'robin': 1288, 'minimalist': 1289, 'lightest': 1290, 'life': 1291, 'chores': 1292, 'bird': 1293, 'flairy': 1294, '‘bird': 1295, 'spirit’': 1296, 'filled': 1297, 'vine': 1298, 'plants': 1299, 'branches': 1300, 'carefree': 1301, 'really': 1302, 'big': 1303, 'prominent': 1304, 'abstract': 1305, 'paisley': 1306, 'jacquard': 1307, 'sakhi': 1308, 'pocket': 1309, 'curated': 1310, 'morden': 1311, 'carry': 1312, 'individually': 1313, 'always': 1314, 'come': 1315, 'handy': 1316, 'rushed': 1317, 'monday': 1318, 'mornings': 1319, 'checked': 1320, 'bardot': 1321, 'sees': 1322, 'coming': 1323, 'together': 1324, 'silhoutte': 1325, 'onverlapping': 1326, 'action': 1327, 'sunglasses': 1328, 'truebrowns': 1329, 'effortlessly': 1330, 'revive': 1331, 'outfits': 1332, 'beach': 1333, 'schiffli': 1334, 'passion': 1335, 'continues': 1336, 'slub': 1337, 'bouquet': 1338, 'rainbow': 1339, 'gleam': 1340, 'gathering': 1341, 'collars': 1342, 'quirky': 1343, 'crossover': 1344, 'confidence': 1345, 'glam': 1346, '62': 1347, '5cm': 1348, '34': 1349, '2cm': 1350, '68': 1351, '7cm': 1352, 'au': 1353, '8': 1354, 'internal': 1355, 'resin': 1356, 'attend': 1357, 'organza': 1358, 'about': 1359, 'june': 1360, 'building': 1361, 'embrace': 1362, 'modern': 1363, 'tuxedo': 1364, 'espresso': 1365, 'martini': 1366, 'glamour': 1367, 'alike': 1368, 'wavy': 1369, 'locks': 1370, 'sunshine': 1371, 'shades': 1372, 'hours': 1373, 'ups': 1374, 'pvc': 1375, 'spaghetti': 1376, 'wrong': 1377, 'contrasted': 1378, 'bestfriend': 1379, 'instructions': 1380, 'clean': 1381, 'wash': 1382, 'choli': 1383, 'palazzo': 1384, 'matter': 1385, 'china': 1386, 'course': 1387, 'runs': 1388, '‘chai': 1389, 'pe': 1390, 'charcha’': 1391, 'informative': 1392, 'gatherings': 1393, 'outgoing': 1394, 'summers': 1395, 'mobile': 1396, 'etc': 1397, 'potli': 1398, 'edges': 1399, 'turn': 1400, 'flex': 1401, 'pleates': 1402, 'drink': 1403, 'summery': 1404, 'combined': 1405, 'ballerina': 1406, 'flat': 1407, 'plethora': 1408, 'drama': 1409, \"you'll\": 1410, 'fashionable': 1411, 'soie': 1412, 'putting': 1413, 'trainer': 1414, 'darker': 1415, 'start': 1416, 'cum': 1417, '\\xa0': 1418, 'earring': 1419, 'boho': 1420, 'flirt': 1421, 'kaftan': 1422, 'sunrise': 1423, 'favourites': 1424, 'location': 1425, 'matte': 1426, 'giraffe': 1427, 'pop': 1428, 'contemproray': 1429, 'ensembles': 1430, 'living': 1431, 'rich': 1432, 'playful': 1433, 'calls': 1434, 'cozy': 1435, 'fleece': 1436, 'trim': 1437, 'crewneck': 1438, 'patch': 1439, '1969': 1440, 'applique': 1441, 'sage': 1442, 'adjustment': 1443, 'highlighted': 1444, 'demins': 1445, 'elevation': 1446, 'eco': 1447, 'fibres': 1448, \"that'll\": 1449, 'environmentally': 1450, 'sustainable': 1451, 'fibre': 1452, 'naturally': 1453, 'biodegradable': 1454, 'pulp': 1455, 'vented': 1456, 'vogue': 1457, 'slay': 1458, 'alternative': 1459, 'utility': 1460, 'strapped': 1461, 'wedge': 1462, 'espadrilles': 1463, 'busy': 1464, 'getaways': 1465, 'airport': 1466, 'shoes': 1467, 'pops': 1468, \"okhai's\": 1469, 'transcends': 1470, 'seasons': 1471, 'global': 1472, 'bouffant': 1473, 'elongated': 1474, 'should': 1475, 'compact': 1476, 'swanky': 1477, 'bay': 1478, 'sliders': 1479, 'street': 1480, 'alternatively': 1481, 'sporty': 1482, 'messy': 1483, 'flounce': 1484, 'commanding': 1485, 'makeover': 1486, 'towering': 1487, 'checkered': 1488, 'wedges': 1489, 'neatly': 1490, 'tied': 1491, 'sophisticated': 1492, 'corporate': 1493, 'overlay': 1494, 'meticulously': 1495, 'miniature': 1496, 'shrub': 1497, 'anything': 1498, 'dye': 1499, 'aline': 1500, 'basic': 1501, 'board': 1502, 'strip': 1503, 'closer': 1504, 'onto': 1505, 'magic': 1506, 'loved': 1507, 'ones': 1508, 'major': 1509, 'maker': 1510, 'fluted': 1511, 'lip': 1512, 'hanky': 1513, 'speckled': 1514, 'got': 1515, 'classier': 1516, 'cooler': 1517, 'mother': 1518, 'enthral': 1519, 'years': 1520, 'surprised': 1521, 'combinations': 1522, 'churidar': 1523, 'shaded': 1524, 'bead': 1525}\nOrderedDict([('seqstart', 500), ('this', 565), ('stylish', 23), ('foil', 4), ('print', 30), ('kurta', 8), ('from', 167), ('janasya', 4), ('is', 239), ('made', 26), ('of', 209), ('poly', 2), ('crepe', 48), ('and', 920), ('comes', 19), ('in', 227), ('an', 81), ('attractive', 2), ('peach', 8), ('color', 13), ('it', 181), ('features', 130), ('3', 33), ('4', 4), ('sleeve', 17), ('round', 48), ('neck', 163), ('a', 889), ('line', 21), ('calf', 2), ('length', 18), ('that', 46), ('suitable', 2), ('for', 309), ('casual', 61), ('occasions', 10), ('team', 36), ('with', 750), ('matching', 7), ('leggings', 5), ('chic', 35), ('look', 226), ('seqend', 500), ('check', 8), ('pattern', 10), ('top', 240), ('by', 115), ('work', 19), ('label', 6), ('crafted', 127), ('cotton', 91), ('featuring', 41), ('bias', 2), ('at', 138), ('the', 478), ('yoke', 20), ('straight', 33), ('bottom', 20), ('half', 10), ('smart', 8), ('neckline', 126), ('4th', 30), ('sleeves', 211), ('mid', 4), ('hip', 4), ('offers', 1), ('comfortable', 14), ('fit', 127), ('style', 285), ('trouser', 3), ('skirt', 20), ('medium', 1), ('high', 89), ('heels', 176), ('can', 22), ('also', 5), ('be', 40), ('styled', 5), ('pair', 184), ('stud', 5), ('earrings', 33), ('your', 127), ('regular', 76), ('sneakers', 26), ('to', 341), ('attain', 4), ('elegant', 29), ('printed', 77), ('details', 34), ('off', 30), ('white', 53), ('set', 17), ('jaipur', 8), ('kurti', 7), ('makes', 20), ('statement', 82), ('addition', 27), ('wardrobe', 38), ('accessories', 61), ('complete', 153), ('add', 19), ('extra', 6), ('dose', 3), ('blue', 68), ('cape', 2), ('twenty', 15), ('dresses', 21), ('black', 86), ('denims', 37), ('colour', 23), ('block', 30), ('will', 58), ('yellow', 18), ('polyester', 122), ('georgette', 23), ('maxi', 37), ('dress', 265), ('knit', 46), ('lining', 35), ('inside', 20), ('comfort', 44), ('overlapping', 29), ('v', 86), ('gathers', 12), ('bust', 4), ('flared', 22), ('attached', 9), ('belt', 32), ('waist', 73), ('concealed', 45), ('zipper', 67), ('on', 143), ('left', 24), ('no', 4), ('well', 3), ('edited', 1), ('closet', 3), ('without', 3), ('t', 24), ('shirt', 71), ('like', 3), ('one', 34), ('gap', 30), (\"it's\", 12), ('cut', 32), ('close', 1), ('soft', 25), ('jersey', 10), ('touches', 2), ('blend', 7), ('yours', 28), ('washed', 2), ('denim', 26), ('or', 50), ('layered', 5), ('under', 3), ('chunky', 3), ('we', 7), ('are', 21), ('excited', 1), ('announce', 1), ('our', 9), ('long', 57), ('awaited', 1), ('launch', 1), ('contemporary', 3), ('clothing', 1), ('indian', 3), ('hand', 14), ('painted', 1), ('textiles', 1), ('thrilled', 1), ('have', 20), ('fresh', 6), ('new', 7), ('please', 8), ('note', 8), ('piece', 41), ('handmade', 9), ('love', 14), ('care', 10), ('various', 9), ('artisans', 8), ('therefore', 8), ('slight', 9), ('differences', 8), ('design', 25), ('may', 11), ('occur', 8), ('which', 10), ('allows', 8), ('signature', 11), ('kind', 8), ('aesthetic', 8), ('pleated', 14), ('jacket', 15), ('fastened', 4), ('drawstring', 7), ('coconut', 4), ('wood', 2), ('buttons', 32), ('natural', 8), ('indigo', 6), ('dyed', 5), ('handloom', 6), ('khadi', 4), ('fabric', 43), ('gilet', 1), ('front', 99), ('open', 6), ('circular', 2), ('mirrors', 2), ('stripe', 9), ('twill', 6), ('jumpsuit', 90), ('wrap', 25), ('sleeveless', 37), ('back', 95), ('closure', 28), ('separate', 2), ('legged', 5), ('bottoms', 12), ('pockets', 27), ('both', 10), ('sides', 10), (\"aeropostale's\", 2), ('tee', 8), ('blended', 4), ('has', 46), ('all', 38), ('over', 28), ('floral', 66), ('classy', 5), ('feel', 5), ('wear', 62), ('everything', 5), ('distressed', 2), ('jeans', 43), ('equally', 1), ('bold', 4), ('mini', 6), ('skirts', 3), ('twisted', 2), ('panel', 3), ('stripes', 8), ('sheath', 6), ('functional', 3), ('button', 49), ('multicolor', 5), ('leaf', 1), ('collar', 29), ('tie', 63), ('up', 95), ('full', 16), ('cuff', 10), ('attachment', 5), ('hemline', 25), ('when', 10), ('tops', 3), ('their', 2), ('build', 2), ('strike', 2), ('perfect', 50), ('cord', 3), ('balance', 2), ('aeropostale', 6), ('feels', 2), ('against', 2), ('skin', 2), ('weekend', 8), ('culottes', 5), ('pink', 32), ('ruffled', 13), ('bow', 2), ('detailing', 45), ('around', 6), ('peplum', 21), ('sheer', 5), ('balloon', 9), ('smocked', 16), ('band', 12), ('baise', 3), ('gaba', 3), ('single', 2), ('straps', 38), ('lace', 16), ('knot', 5), ('danglers', 1), ('charm', 1), ('bracelet', 1), ('create', 29), ('trendy', 20), ('accentuate', 2), ('lilac', 2), ('draped', 3), ('tarun', 2), ('tahiliani', 2), ('crinkle', 2), ('tulle', 3), ('pick', 10), ('next', 10), ('festivity', 2), ('jewellery', 19), ('navy', 22), ('collared', 4), ('okhai', 6), ('wooden', 4), ('airy', 3), ('ajrakh', 1), ('motifs', 4), ('jigsaw', 1), ('panelling', 1), ('unique', 8), ('as', 15), ('formal', 5), ('waisted', 2), ('pants', 32), ('palazzos', 3), ('shorts', 8), ('even', 5), ('dungarees', 1), ('vibrant', 6), ('touch', 7), ('campus', 7), ('sutra', 7), ('flip', 3), ('flops', 3), ('shoe', 3), ('cool', 16), ('geometric', 1), ('bunaai', 3), ('buy', 55), ('online', 55), ('polka', 20), ('rayon', 33), ('midi', 24), ('flare', 36), ('silhouette', 66), ('ruching', 8), ('adjustable', 20), ('shoulder', 72), ('strap', 8), ('ruffle', 9), ('smocking', 11), ('ease', 63), ('crew', 12), ('short', 56), ('logo', 8), ('graphic', 6), ('wide', 12), ('square', 23), ('hem', 35), ('slit', 22), ('purpose', 2), ('teamed', 3), ('any', 10), ('definitely', 3), ('you', 57), ('stand', 3), ('apart', 2), ('compliments', 4), ('sweatshirt', 15), ('go', 12), ('number', 4), ('temperature', 3), ('drops', 3), ('glitter', 1), ('adds', 6), ('appeal', 2), ('while', 5), ('ribbed', 5), ('trims', 4), ('its', 14), ('throw', 2), ('duty', 4), ('days', 9), ('crop', 19), ('center', 17), ('frill', 10), ('bishop', 2), ('elastic', 13), ('rust', 6), ('moss', 9), ('sweetheart', 4), ('puff', 19), ('centre', 14), ('gown', 18), ('halter', 8), ('deep', 10), ('incut', 8), ('elasticated', 25), ('waistline', 8), ('blouson', 2), ('keyhole', 12), ('fastening', 65), ('red', 19), ('playsuit', 6), ('lapel', 6), ('blazer', 8), ('inspired', 2), ('mock', 3), ('known', 2), ('producing', 1), ('good', 3), ('quality', 3), ('casuals', 1), ('sequin', 6), ('embellished', 15), ('hits', 2), ('breathable', 3), ('linen', 11), ('effortless', 9), ('light', 10), ('lift', 2), ('mood', 2), ('cinch', 1), ('embroidered', 15), ('real', 2), ('sparkle', 1), ('subtle', 15), ('blanket', 1), ('stitch', 1), ('cheerful', 1), ('optimist', 1), ('destination', 1), ('day', 20), ('weddings', 4), ('brunch', 9), ('meetups', 2), ('solo', 1), ('time', 9), ('favourite', 7), ('cafe', 1), ('maroon', 18), ('co', 4), ('ord', 4), ('thigh', 7), ('above', 1), ('side', 47), ('zip', 15), ('shoulders', 8), ('steal', 2), ('show', 6), ('wearing', 20), ('clutch', 18), ('stunning', 27), ('evening', 15), ('buti', 2), ('make', 38), ('special', 3), ('summer', 11), ('essential', 4), ('paired', 4), ('uneven', 3), ('pant', 6), ('kniited', 1), ('having', 2), ('along', 4), ('net', 3), ('sleeved', 2), ('vero', 11), ('moda', 11), ('viscose', 21), ('placket', 22), ('curved', 5), ('trousers', 13), ('olive', 6), ('three', 16), ('fourth', 14), ('girlfriend', 7), ('ensemble', 16), ('green', 27), ('meant', 2), ('fashion', 6), ('forward', 2), ('women', 11), ('fine', 24), ('wrist', 2), ('outfit', 12), ('easily', 2), ('transition', 2), ('night', 7), ('accessorize', 11), ('flats', 22), ('cute', 13), ('crossbody', 13), ('bag', 30), ('lovely', 1), ('hued', 1), ('options', 1), ('many', 1), ('if', 3), ('want', 3), ('give', 7), ('traditional', 2), ('choice', 7), ('weekends', 3), ('finished', 6), ('prints', 4), ('skinny', 25), ('low', 6), ('ruffles', 17), ('voile', 5), ('beige', 10), ('only', 30), ('scalloped', 1), ('nude', 10), (\"gap's\", 5), ('smooth', 7), ('satin', 15), ('flattering', 2), ('better', 2), ('fullness', 1), ('out', 26), ('strappy', 18), ('sandals', 7), ('dot', 8), ('torqadorn', 8), ('detail', 27), ('relaxed', 10), ('bring', 3), ('romance', 1), ('dreamy', 2), ('it’s', 3), ('elevated', 1), ('flutter', 5), ('so', 3), ('let', 1), ('shine', 2), ('textured', 2), ('flatters', 1), ('those', 6), ('who', 1), ('heavy', 1), ('hook', 7), ('envelope', 1), ('minimal', 8), ('model', 10), ('height', 11), (\"5'6\", 10), ('size', 11), ('xs', 10), ('payal', 9), ('pratap', 3), ('great', 12), ('western', 16), ('collection', 26), ('silver', 8), ('footwear', 9), ('incuts', 1), ('velvet', 7), ('fitted', 8), ('revamp', 1), ('singhal', 6), ('embroidery', 17), ('crotch', 1), ('ace', 7), ('boots', 2), ('inspire', 5), ('finesse', 6), ('mules', 1), ('handbag', 8), ('pullover', 7), ('asymmetric', 5), ('buttoned', 13), ('down', 13), ('mandarin', 10), ('asymmetrical', 8), ('jeggings', 11), ('must', 11), ('boyfriend', 6), ('timeless', 4), ('spots', 1), ('feminine', 2), ('everyday', 3), ('trend', 7), ('brown', 7), ('solid', 16), ('ambraee', 2), ('garment', 6), ('differ', 2), ('picture', 2), ('split', 3), ('cross', 5), ('fringe', 1), ('broad', 6), ('classic', 12), ('gorgeous', 7), ('every', 3), ('bit', 3), ('beautiful', 5), ('cocktail', 5), ('kitten', 1), ('need', 7), ('leg', 10), ('pure', 7), ('thread', 3), ('versatile', 4), ('take', 10), ('dressing', 3), ('dark', 2), ('plunging', 1), ('delicate', 7), ('present', 3), ('allure', 3), ('elegance', 3), ('abutilon', 2), ('kimono', 1), ('pack', 1), ('premium', 3), ('range', 6), ('amaiva', 2), ('presents', 3), ('contrast', 3), ('piping', 2), ('bell', 9), ('more', 3), ('tassels', 2), ('burgundy', 1), ('two', 4), ('loop', 3), ('striped', 14), ('exaggerated', 1), ('aurora', 2), ('alluring', 2), ('free', 5), ('string', 1), ('modal', 2), ('slip', 7), ('butterfly', 1), ('daywear', 1), ('loops', 1), ('ritu', 5), ('kumar', 5), ('strings', 2), ('tassel', 2), ('embellishments', 8), ('loose', 2), ('pristine', 1), (\"isn't\", 1), ('restricted', 1), ('hour', 1), ('includes', 1), ('pencil', 2), ('court', 2), ('gold', 14), ('panelled', 1), ('leather', 3), ('tube', 5), ('bespoke', 3), ('silk', 5), ('blush', 4), ('pared', 4), ('party', 9), ('ready', 14), ('shrug', 5), ('idalia', 3), ('confident', 1), ('level', 2), ('yet', 5), ('multi', 14), ('kazo', 14), ('hemp', 1), ('boat', 6), ('embellishment', 2), ('gather', 3), ('depending', 1), ('versatility', 1), ('quotient', 3), ('desk', 1), ('dinner', 2), ('pairing', 4), ('either', 1), ('thin', 2), ('dots', 2), ('they', 2), ('friends', 4), ('dates', 3), ('beautifully', 1), ('dusty', 1), ('scores', 1), ('sequins', 2), ('bugle', 1), ('beads', 3), ('looks', 9), ('own', 1), ('does', 1), ('not', 3), ('accessory', 1), ('pleats', 8), ('adding', 1), ('mix', 5), ('mish', 6), ('freshen', 3), ('winter', 2), ('100', 4), ('spells', 3), ('warmth', 3), ('fetch', 3), ('yourself', 3), ('teaming', 4), ('grey', 8), ('faballey', 6), ('don', 9), ('daytime', 6), ('events', 16), ('pint', 5), ('sized', 8), ('elevate', 4), ('eyelet', 5), ('apron', 2), ('woven', 5), ('fully', 5), ('lined', 4), ('elasticized', 3), ('inner', 2), ('drawcord', 2), ('ties', 2), ('simple', 7), ('tan', 6), ('brogues', 3), ('teal', 3), ('easy', 13), ('pleat', 7), ('culotte', 2), ('cover', 8), ('story', 8), ('checks', 4), ('save', 1), ('rusty', 1), ('rose', 3), ('accentuated', 3), ('tip', 6), ('some', 6), ('stacked', 1), ('bracelets', 1), ('rings', 1), ('mustard', 8), ('br', 35), ('ankle', 1), ('composition', 1), ('ikat', 4), ('bomber', 3), ('relax', 1), ('lets', 2), ('adjust', 2), ('sling', 13), ('quarter', 1), ('designer', 1), ('fabnest', 4), ('womens', 1), ('shift', 1), ('tunic', 3), ('banded', 5), ('cuffs', 10), ('meet', 2), ('accompaniment', 1), ('chilly', 1), ('office', 7), ('theatre', 1), ('indoors', 1), ('poncho', 1), ('rescue', 1), ('touting', 1), ('handkerchief', 1), ('slide', 3), ('wonder', 1), ('slim', 4), ('a\\xa0unique', 1), ('de', 1), ('constructed', 2), ('structural', 1), ('ambiguity', 1), ('tacey', 1), ('through', 5), ('multiple', 3), ('mocks', 1), ('trials', 1), ('achieve', 2), ('body', 4), ('promising', 1), ('purple', 4), ('inverted', 1), ('box', 10), ('eye', 4), ('that’s', 2), ('romantic', 2), ('wine', 2), ('business', 2), ('whether', 2), ('flavouring', 2), ('coffee', 2), ('taking', 2), ('project', 2), ('lead', 2), ('simply', 3), ('heading', 2), ('girls', 4), ('after', 4), ('drinks', 2), ('do', 4), (\"torqadorn's\", 2), ('tailored', 4), ('iridescent', 2), ('ways', 2), ('dazzle', 3), ('flair', 3), ('uber', 4), ('cuffed', 5), ('sun', 3), ('gulaal', 1), ('mirror', 4), ('golden', 8), ('zari', 1), ('seam', 1), ('choker', 1), ('nose', 1), ('pin', 1), ('festive', 1), ('fastens', 1), ('using', 3), ('sild', 1), ('fabrication', 2), ('blouse', 5), ('spring', 1), ('stylised', 3), ('coat', 5), ('house', 4), ('feature', 2), ('lightweight', 1), ('welt', 1), ('cosy', 1), ('knitted', 2), ('threads', 1), ('drawcords', 1), ('hoodie', 1), ('metallic', 6), ('chest', 3), ('rib', 4), ('tank', 1), ('dohyenne', 2), ('jogger', 2), ('ideal', 2), ('arrives', 2), ('mint', 2), ('blossom', 1), ('pearl', 2), ('extending', 2), ('stretchable', 2), ('nylon', 3), ('colored', 1), ('get', 10), ('snuggly', 2), ('cardigan', 2), ('keep', 11), ('hems', 2), ('into', 4), ('step', 2), ('season', 13), ('double', 3), ('breasted', 2), ('trench', 1), ('broderie', 1), ('sunny', 1), ('pastel', 1), ('heeled', 1), ('tulip', 2), ('hemmed', 1), ('created', 7), ('stilettos', 10), ('ahead', 2), ('coloured', 4), ('self', 8), ('fabricated', 4), ('dangler', 1), ('amazing', 4), ('colours', 6), ('designs', 5), ('patterns', 7), ('these', 4), ('apparels', 4), ('very', 7), ('too', 4), ('rid', 4), (\"'regular'\", 4), ('gathered', 6), ('tier', 2), ('refreshing', 6), ('vibe', 3), ('vacation', 3), ('surely', 4), ('breezy', 6), ('perfectly', 3), ('prepare', 1), ('rendezvous', 1), ('boasts', 2), ('torso', 1), ('overlap', 3), ('racer', 1), ('rivets', 1), ('ushers', 1), ('shirring', 1), ('slinky', 1), ('flowers', 1), ('glamorous', 5), ('promises', 1), ('combination', 2), ('store', 5), ('super', 5), ('rolled', 1), ('dropped', 2), ('armhole', 1), ('styling', 3), ('looking', 4), ('highly', 2), ('then', 2), ('divena', 2), ('answer', 2), ('presenting', 2), ('divenas', 2), ('dhoti', 4), ('rising', 2), ('slits', 5), ('tussles', 2), ('closed', 2), ('outing', 2), ('mojri', 2), ('ravishing', 2), ('highest', 1), ('respite', 1), ('seek', 1), ('jodhpuri', 1), ('desi', 2), ('weaves', 1), ('flawless', 1), ('finish', 1), ('theis', 1), ('vertical', 2), ('horizontal', 2), ('princess', 2), ('layer', 4), ('polyster', 1), (\"won't\", 1), ('away', 3), ('soon', 1), ('cowl', 3), ('hoops', 3), ('chain', 2), ('tiered', 5), ('tiers', 1), ('parties', 1), ('toe', 3), ('hint', 2), ('warm', 4), ('detailed', 2), ('scoop', 2), ('cap', 1), ('cropped', 4), ('puffy', 1), ('chiffon', 4), ('kaftaan', 1), ('outings', 2), ('here', 1), ('organic', 2), ('shade', 4), ('andromeda', 1), ('constellation', 2), ('pervasive', 1), ('weight', 1), ('fuss', 1), ('gives', 1), ('breathing', 1), ('space', 1), ('amplifying', 1), ('friendly', 4), ('meetings', 2), ('hi', 1), ('wearable', 1), ('latest', 1), ('wrinkle', 4), ('travel', 2), ('quick', 1), ('drying', 1), ('helps', 1), ('avoid', 1), ('sweat', 3), ('patches', 1), ('criss', 4), ('polycotton', 1), ('channel', 1), ('retro', 1), ('vibes', 1), ('a\\xa0floral', 1), ('print\\xa0fabric', 1), ('a\\xa0self', 1), ('occasion', 6), ('worthy', 2), ('key', 3), ('hole', 3), ('till', 1), ('update', 2), ('what', 3), ('game', 2), ('dusk', 1), ('shimmer', 2), ('bodycon', 5), ('frilled', 2), (\"women's\", 2), ('fablestreet', 2), ('micro', 2), ('sharp', 1), ('creating', 1), ('basics', 1), ('worn', 3), ('basis', 1), ('loungewear', 1), ('staple', 3), ('ripped', 2), ('canvas', 1), ('branding', 1), ('seasoned', 1), ('knife', 1), ('lycra', 3), ('content', 1), ('flap', 2), ('acrylic', 1), ('buckle', 3), ('head', 1), ('forever', 6), ('amp', 2), ('with\\xa0open', 1), ('flats\\xa0and', 1), ('hair', 3), ('clip', 1), ('attire', 1), ('stiletto', 3), ('yarn', 1), ('suited', 1), ('slender', 1), ('frames', 1), ('spruce', 1), ('weather', 1), ('pieces', 1), ('hot', 1), ('roll', 2), ('type', 2), ('resistant', 4), ('sure', 4), ('bleeding', 2), ('thereby', 2), ('making', 2), ('lasting', 2), ('absorbent', 2), ('armpit', 2), ('used', 2), ('underarm', 2), ('stains', 2), ('drop', 5), ('maison', 2), ('shefali', 2), ('muslin', 1), ('tonal', 1), ('ivory', 1), ('base', 1), ('joint', 1), ('biba', 3), ('jompers', 2), ('ruched', 4), ('works', 1), ('spot', 1), ('pretty', 4), ('aaliya', 2), ('flaunt', 1), ('togethers', 1), ('punctured', 1), ('eyelets', 1), ('ribbon', 1), ('running', 2), ('forming', 1), ('secret', 1), ('headed', 1), ('hierarchy', 1), ('why', 1), ('speaks', 2), ('satiny', 1), ('texture', 1), ('smashing', 1), ('glass', 2), ('ceiling', 1), ('dance', 2), ('called', 1), ('‘freedom’', 1), ('movement', 1), ('jive', 1), ('shop', 1), ('run', 1), ('accent', 1), ('cambric', 1), ('hands', 2), ('maybe', 1), ('visiting', 1), ('friend’s', 1), ('serious', 2), ('thick', 1), ('elastication', 1), ('attic', 5), ('salt', 5), ('upgrade', 2), ('going', 1), ('construction', 1), ('layering', 1), ('tucked', 1), ('rise', 4), ('detachable', 2), ('master', 1), ('art', 1), ('orange', 2), ('lurex', 1), ('opening', 2), ('updated', 1), ('lbd', 3), ('dainty', 1), ('periwinkle', 1), ('designed', 4), ('stay', 2), ('absolutely', 1), ('cluster', 1), ('shell', 1), ('bodice', 6), ('whereas', 1), ('part', 1), ('multitiered', 1), ('metre', 1), ('accented', 3), ('hoop', 3), ('edge', 2), ('knee', 1), ('antique', 2), ('pointed', 2), ('holiday', 3), ('a\\xa0baby', 1), ('material', 2), ('and\\xa0adjustable', 1), ('obsessed', 1), ('crowd', 1), ('surplice', 1), ('anti', 2), ('pill', 1), ('intended', 1), ('fall', 1), ('according', 2), ('image', 1), (\"5'3\", 1), (\"5'5\", 1), ('vary', 1), ('slightly', 1), ('screen', 1), ('settings', 1), ('resolution', 1), ('baby', 1), ('strapless', 1), ('fabulous', 1), ('attires', 1), ('ove', 1), ('rit', 1), ('border', 1), ('1', 1), ('fixed', 1), ('extended', 1), ('accessorise', 1), ('gaped', 1), ('mesh', 2), ('cups', 1), ('cami', 1), ('neutral', 1), ('hue', 1), ('separates', 3), ('floaty', 1), ('decorated', 2), ('florals', 2), ('complement', 4), ('tone', 3), ('event', 5), ('prom', 1), ('date', 2), ('nights', 1), ('brunches', 1), ('cocktails', 1), ('found', 1), ('suede', 1), ('epaulets', 1), ('leading', 1), ('dramatic', 1), ('creation', 1), ('reach', 1), ('again', 1), ('version', 1), ('rotation', 2), ('crinkled', 1), ('notched', 1), ('slides', 1), ('cigarette', 1), ('empire', 1), ('tapered', 1), ('ankles', 1), ('pinstripe', 1), ('sweater', 4), ('wool', 1), ('platform', 5), ('multicolored', 1), ('camisole', 3), ('sequined', 2), ('serves', 1), ('blank', 1), ('slate', 1), ('diamond', 1), ('studs', 3), ('queen', 1), ('anne', 1), ('spotty', 1), ('pointy', 1), ('true', 1), ('name', 1), ('‘spunk’', 1), ('carries', 1), ('fortitude', 1), ('girl', 1), ('door', 1), ('tint', 1), ('grit', 1), ('one’s', 1), ('personality', 1), ('site', 1), ('charming', 2), ('orion', 1), ('right', 1), ('aries', 1), ('striking', 1), ('phases', 1), ('moon', 1), ('flaps', 1), ('dual', 1), ('stitches', 1), ('chirpy', 1), ('sport', 1), ('patterned', 3), ('folded', 1), ('royal', 1), ('tote', 1), ('dangling', 1), ('enhance', 1), ('multicolour', 1), ('way', 3), ('robin', 1), ('minimalist', 1), ('lightest', 1), ('cold', 4), ('false', 2), ('life', 1), ('chores', 1), ('bird', 1), ('flairy', 1), ('‘bird', 1), ('spirit’', 1), ('filled', 1), ('vine', 1), ('plants', 1), ('branches', 1), ('2', 2), ('carefree', 1), ('really', 1), ('small', 4), ('big', 1), ('prominent', 1), ('abstract', 1), ('paisley', 1), ('jacquard', 1), ('sakhi', 1), ('pocket', 1), ('curated', 1), ('morden', 1), ('carry', 1), ('individually', 1), ('always', 1), ('come', 1), ('handy', 1), ('rushed', 1), ('monday', 1), ('mornings', 1), ('checked', 1), ('bardot', 1), ('sees', 1), ('coming', 1), ('together', 1), ('silhoutte', 1), ('onverlapping', 1), ('action', 1), ('sunglasses', 1), ('fun', 5), ('truebrowns', 1), ('effortlessly', 1), ('revive', 1), ('outfits', 1), ('beach', 1), ('schiffli', 1), ('passion', 1), ('continues', 1), ('woman', 2), ('slub', 1), ('bouquet', 1), ('rainbow', 1), ('gleam', 1), ('gathering', 1), ('collars', 1), ('equal', 2), ('parts', 2), ('quirky', 1), ('structured', 2), ('crossover', 1), ('confidence', 1), ('glam', 1), ('product', 2), ('li', 28), ('62', 1), ('5cm', 1), ('34', 1), ('2cm', 1), ('68', 1), ('7cm', 1), ('au', 1), ('8', 1), ('internal', 1), ('resin', 1), ('attend', 1), ('organza', 1), ('about', 1), ('june', 1), ('building', 1), ('embrace', 1), ('modern', 1), ('tuxedo', 1), ('espresso', 1), ('martini', 1), ('glamour', 1), ('notch', 3), ('twist', 2), ('alike', 1), ('wavy', 1), ('locks', 1), ('sunshine', 1), ('shades', 1), ('hours', 1), ('ups', 1), ('pvc', 1), ('flowy', 2), ('spaghetti', 1), ('p', 4), ('b', 4), ('ul', 4), ('never', 2), ('wrong', 1), ('contrasted', 1), ('bestfriend', 1), ('instructions', 1), ('dry', 2), ('clean', 1), ('wash', 1), ('choli', 1), ('palazzo', 1), ('tea', 3), ('matter', 1), ('china', 1), ('course', 1), ('india', 2), ('runs', 1), ('‘chai', 1), ('pe', 1), ('charcha’', 1), ('informative', 1), ('gatherings', 1), ('outgoing', 1), ('summers', 1), ('mobile', 1), ('etc', 1), ('chinese', 2), ('potli', 1), ('scattered', 2), ('edges', 1), ('best', 3), ('turn', 1), ('flex', 1), ('pleates', 1), ('drink', 1), ('summery', 1), ('combined', 1), ('ballerina', 1), ('flat', 1), ('mauve', 2), ('plethora', 1), ('drama', 1), (\"you'll\", 1), ('fashionable', 1), ('soie', 1), ('putting', 1), ('trainer', 1), ('darker', 1), ('start', 1), ('cum', 1), ('\\xa0', 1), ('earring', 1), ('boho', 1), ('flirt', 1), ('kaftan', 1), ('sunrise', 1), ('favourites', 1), ('location', 1), ('matte', 1), ('giraffe', 1), ('pop', 1), ('contemproray', 1), ('ensembles', 1), ('living', 1), ('rich', 1), ('playful', 1), ('calls', 1), ('things', 2), ('massive', 2), ('points', 2), ('cozy', 1), ('fleece', 1), ('trim', 1), ('crewneck', 1), ('patch', 1), ('1969', 1), ('applique', 1), ('sage', 1), ('adjustment', 1), ('highlighted', 1), ('demins', 1), ('elevation', 1), ('eco', 1), ('tencel', 2), ('lyocell', 2), ('fibres', 1), (\"that'll\", 1), ('environmentally', 1), ('sustainable', 1), ('fibre', 1), ('naturally', 1), ('biodegradable', 1), ('pulp', 1), ('vented', 1), ('vogue', 1), ('slay', 1), ('alternative', 1), ('pumps', 2), ('utility', 1), ('strapped', 1), ('wedge', 1), ('espadrilles', 1), ('busy', 1), ('getaways', 1), ('airport', 1), ('shoes', 1), ('pops', 1), (\"okhai's\", 1), ('transcends', 1), ('seasons', 1), ('global', 1), ('bouffant', 1), ('elongated', 1), ('should', 1), ('compact', 1), ('swanky', 1), ('bay', 1), ('sliders', 1), ('street', 1), ('alternatively', 1), ('sporty', 1), ('messy', 1), ('flounce', 1), ('commanding', 1), ('makeover', 1), ('polished', 2), ('towering', 1), ('checkered', 1), ('wedges', 1), ('neatly', 1), ('tied', 1), ('sophisticated', 1), ('corporate', 1), ('overlay', 1), ('handcrafted', 2), ('meticulously', 1), ('miniature', 1), ('shrub', 1), ('anything', 1), ('dye', 1), ('aline', 1), ('basic', 1), ('board', 1), ('strip', 1), ('closer', 1), ('onto', 1), ('mul', 2), ('magic', 1), ('loved', 1), ('ones', 1), ('major', 1), ('maker', 1), ('fluted', 1), ('lip', 1), ('hanky', 1), ('speckled', 1), ('got', 1), ('classier', 1), ('cooler', 1), ('mother', 1), ('enthral', 1), ('years', 1), ('surprised', 1), ('combinations', 1), ('churidar', 1), ('shaded', 1), ('bead', 1)])\n" ], [ "#creating input sequence for predicting description\r\ninput_sequence = []\r\nimage_input = []\r\nfor j in range(len(data)):\r\n token_list = tokenizer.texts_to_sequences([data[j]])[0]\r\n for i in range(1,len(token_list)):\r\n n_grams = token_list[:i]\r\n input_sequence.append(n_grams)\r\n image_input.append(imgfeatures[imgpath[j]])\r\nprint(len(input_sequence))\r\nmax_len = max([len(x) for x in input_sequence])\r\nprint(max_len)\r\n\r\ninput_sequence = pad_sequences(input_sequence, maxlen=max_len, padding=\"pre\", truncating=\"pre\")", "18853\n111\n" ], [ "#input and output for predicting description\r\nx1, labels = input_sequence[:,:-1] , input_sequence[:,-1]\r\nx2 = tf.keras.utils.to_categorical(labels, num_classes=total_words)\r\n\r\nimage_input = np.array(image_input)\r\nx1 = np.array(x1)\r\nx2 = np.array(x2)\r\nimage_input.shape,x1.shape,x2.shape", "_____no_output_____" ] ], [ [ "Combined Model Training", "_____no_output_____" ] ], [ [ "# Model Layout\r\nembedding_size = 100\r\nimg_model = Sequential()\r\nimg_model.add(Dense(embedding_size, input_shape=(2048,), activation='relu'))\r\nimg_model.add(RepeatVector(max_len-1))\r\nimg_model.summary()\r\n\r\nnlp_model = Sequential()\r\nnlp_model.add(Embedding(input_dim=total_words, output_dim= embedding_size, input_length=max_len-1))\r\nnlp_model.add(tf.keras.layers.Bidirectional(LSTM(256, return_sequences=True)))\r\nnlp_model.add(Dense(128))\r\nnlp_model.add(Dropout(0.5))\r\nnlp_model.add(TimeDistributed(Dense(embedding_size)))\r\nnlp_model.summary()\r\n\r\nconcatenate = Concatenate()([img_model.output, nlp_model.output])\r\nx = tf.keras.layers.Bidirectional(LSTM(128, return_sequences=True))(concatenate)\r\nx = tf.keras.layers.Bidirectional(LSTM(256, return_sequences=False))(x)\r\nx = Dense(256)(x)\r\nx = Dropout(0.5)(x)\r\nx = Dense(total_words)(x)\r\nout = Activation('softmax')(x)\r\nmodel = Model(inputs=[img_model.input, nlp_model.input], outputs = out)\r\n\r\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\nmodel.summary()", "Model: \"sequential_32\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_52 (Dense) (None, 100) 204900 \n_________________________________________________________________\nrepeat_vector_16 (RepeatVect (None, 110, 100) 0 \n=================================================================\nTotal params: 204,900\nTrainable params: 204,900\nNon-trainable params: 0\n_________________________________________________________________\nModel: \"sequential_33\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_16 (Embedding) (None, 110, 100) 152600 \n_________________________________________________________________\nbidirectional_30 (Bidirectio (None, 110, 512) 731136 \n_________________________________________________________________\ndense_53 (Dense) (None, 110, 128) 65664 \n_________________________________________________________________\ndropout_23 (Dropout) (None, 110, 128) 0 \n_________________________________________________________________\ntime_distributed_16 (TimeDis (None, 110, 100) 12900 \n=================================================================\nTotal params: 962,300\nTrainable params: 962,300\nNon-trainable params: 0\n_________________________________________________________________\nModel: \"model_18\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\nembedding_16_input (InputLayer) [(None, 110)] 0 \n__________________________________________________________________________________________________\nembedding_16 (Embedding) (None, 110, 100) 152600 embedding_16_input[0][0] \n__________________________________________________________________________________________________\nbidirectional_30 (Bidirectional (None, 110, 512) 731136 embedding_16[0][0] \n__________________________________________________________________________________________________\ndense_52_input (InputLayer) [(None, 2048)] 0 \n__________________________________________________________________________________________________\ndense_53 (Dense) (None, 110, 128) 65664 bidirectional_30[0][0] \n__________________________________________________________________________________________________\ndense_52 (Dense) (None, 100) 204900 dense_52_input[0][0] \n__________________________________________________________________________________________________\ndropout_23 (Dropout) (None, 110, 128) 0 dense_53[0][0] \n__________________________________________________________________________________________________\nrepeat_vector_16 (RepeatVector) (None, 110, 100) 0 dense_52[0][0] \n__________________________________________________________________________________________________\ntime_distributed_16 (TimeDistri (None, 110, 100) 12900 dropout_23[0][0] \n__________________________________________________________________________________________________\nconcatenate_16 (Concatenate) (None, 110, 200) 0 repeat_vector_16[0][0] \n time_distributed_16[0][0] \n__________________________________________________________________________________________________\nbidirectional_31 (Bidirectional (None, 110, 256) 336896 concatenate_16[0][0] \n__________________________________________________________________________________________________\nbidirectional_32 (Bidirectional (None, 512) 1050624 bidirectional_31[0][0] \n__________________________________________________________________________________________________\ndense_55 (Dense) (None, 256) 131328 bidirectional_32[0][0] \n__________________________________________________________________________________________________\ndropout_24 (Dropout) (None, 256) 0 dense_55[0][0] \n__________________________________________________________________________________________________\ndense_56 (Dense) (None, 1526) 392182 dropout_24[0][0] \n__________________________________________________________________________________________________\nactivation_16 (Activation) (None, 1526) 0 dense_56[0][0] \n==================================================================================================\nTotal params: 3,078,230\nTrainable params: 3,078,230\nNon-trainable params: 0\n__________________________________________________________________________________________________\n" ], [ "#Model visualisation\r\nplot_model(model, show_shapes=True)", "_____no_output_____" ], [ "# trained the model\r\nhistory = model.fit([image_input, x1], x2, batch_size=64, epochs=80) ", "Epoch 1/80\n295/295 [==============================] - 27s 65ms/step - loss: 6.0305 - accuracy: 0.0414\nEpoch 2/80\n295/295 [==============================] - 19s 65ms/step - loss: 5.6220 - accuracy: 0.0462\nEpoch 3/80\n 34/295 [==>...........................] - ETA: 17s - loss: 5.2823 - accuracy: 0.1002" ], [ "def plot_graphs(history, string):\r\n plt.plot(history.history[string])\r\n plt.xlabel(\"Epochs\")\r\n plt.ylabel(string)\r\n plt.show()\r\nplot_graphs(history, 'accuracy')\r\nplot_graphs(history, 'loss')", "_____no_output_____" ], [ "#saving the trained model\r\nmodel.save('tm_assignment1 model 1.h5')", "_____no_output_____" ], [ "#loading the saved model\r\nmodel = tf.keras.models.load_model('tm_assignment1 model 1.h5')", "_____no_output_____" ] ], [ [ "Trying this model on unseen images", "_____no_output_____" ] ], [ [ "def predict_description(path):\r\n img = cv2.imread(path)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n img1 = cv2.resize(img,(224,224))\r\n img2 = img1.reshape(1,224,224,3)\r\n img_inp = np.array(ResNet_model.predict(img2)[0]).reshape(1,2048)\r\n\r\n seed_text = [\"seqstart\"]\r\n while (seed_text[-1]) != 'seqend':\r\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\r\n token_list = pad_sequences([token_list], maxlen=max_len-1, padding='pre')\r\n predicted = np.argmax(model.predict([img_inp, token_list], verbose=0))\r\n output_word = \"\"\r\n for word, index in tokenizer.word_index.items():\r\n if index == predicted:\r\n output_word = word\r\n break\r\n seed_text.append(output_word)\r\n if len(seed_text)>26:\r\n break\r\n seed_text = ' '.join(seed_text[1:-1])\r\n plt.imshow(img)\r\n plt.xlabel(seed_text);", "_____no_output_____" ], [ "predict_description(path = imgpath[2])", "_____no_output_____" ], [ "predict_description(path = './imgnew1.jpg')", "_____no_output_____" ], [ "predict_description(path = './imgnew2.jpg')", "_____no_output_____" ], [ "predict_description(path = './imgnew4.jpg')", "_____no_output_____" ], [ "predict_description(path = './imgnew5.jpg')", "_____no_output_____" ], [ "predict_description(path = './imgnew9.jpg')", "_____no_output_____" ], [ "predict_description(path = './imgnew11.jpg')", "_____no_output_____" ], [ "predict_description(path = './imgnew13.jpg')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec513af334c7f38f22de02a9e132a88f399d1944
5,839
ipynb
Jupyter Notebook
miscellaneous/magics.ipynb
ampl/amplcolab
3bb80f4650adfe3047aeaa821fcd1bd3580349c2
[ "MIT" ]
null
null
null
miscellaneous/magics.ipynb
ampl/amplcolab
3bb80f4650adfe3047aeaa821fcd1bd3580349c2
[ "MIT" ]
null
null
null
miscellaneous/magics.ipynb
ampl/amplcolab
3bb80f4650adfe3047aeaa821fcd1bd3580349c2
[ "MIT" ]
null
null
null
2,919.5
5,838
0.680425
[ [ [ "# Jupyter Notebook Integration\n[![magics.ipynb](https://img.shields.io/badge/github-%23121011.svg?logo=github)](https://github.com/ampl/amplcolab/blob/master/miscellaneous/magics.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ampl/amplcolab/blob/master/miscellaneous/magics.ipynb) [![Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://kaggle.com/kernels/welcome?src=https://github.com/ampl/amplcolab/blob/master/miscellaneous/magics.ipynb) [![Gradient](https://assets.paperspace.io/img/gradient-badge.svg)](https://console.paperspace.com/github/ampl/amplcolab/blob/master/miscellaneous/magics.ipynb) [![Open In SageMaker Studio Lab](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/ampl/amplcolab/blob/master/miscellaneous/magics.ipynb)\n\nDescription: Jupyter Notebook Integration with amplpy\n\nTags: amplpy, example\n\nNotebook author: Filipe Brandão\n\nModel author: N/A\n\nReferences: N/A", "_____no_output_____" ] ], [ [ "# Install dependencies\n!pip install -q amplpy ampltools", "_____no_output_____" ], [ "# Google Colab & Kaggle interagration\nMODULES=['ampl', 'gurobi']\nfrom ampltools import cloud_platform_name, ampl_notebook\nfrom amplpy import AMPL, register_magics\nif cloud_platform_name() is None:\n ampl = AMPL() # Use local installation of AMPL\nelse:\n ampl = ampl_notebook(modules=MODULES) # Install AMPL and use it\nregister_magics(ampl_object=ampl) # Evaluate %%ampl_eval cells with ampl.eval()", "_____no_output_____" ] ], [ [ "### Use `%%ampl_eval` to pass the model to AMPL", "_____no_output_____" ] ], [ [ "%%ampl_eval\nset SIZES;\nparam capacity >= 0;\nparam value {SIZES};\nvar Qty {SIZES} binary;\nmaximize TotVal: sum {s in SIZES} value[s] * Qty[s];\nsubject to Cap: sum {s in SIZES} s * Qty[s] <= capacity;", "_____no_output_____" ] ], [ [ "### Set data", "_____no_output_____" ] ], [ [ "ampl.set['SIZES'] = [5, 4, 6, 3]\nampl.param['value'] = [10, 40, 30, 50]\nampl.param['capacity'] = 10", "_____no_output_____" ] ], [ [ "### Use `%%ampl_eval` to display values", "_____no_output_____" ] ], [ [ "%%ampl_eval\ndisplay SIZES;\ndisplay value;\ndisplay capacity;", "set SIZES := 5 4 6 3;\n\nvalue [*] :=\n3 50\n4 40\n5 10\n6 30\n;\n\ncapacity = 10\n\n" ] ], [ [ "### Use amplpy to retrive values", "_____no_output_____" ] ], [ [ "print('SIZES:', ampl.set['SIZES'].getValues().toList())\nprint('value:', ampl.param['value'].getValues().toDict())\nprint('capacity:', ampl.param['capacity'].value())", "SIZES: [5.0, 4.0, 6.0, 3.0]\nvalue: {3.0: 50.0, 4.0: 40.0, 5.0: 10.0, 6.0: 30.0}\ncapacity: 10.0\n" ] ], [ [ "### Use `%%ampl_eval` to solve the model", "_____no_output_____" ] ], [ [ "%%ampl_eval\noption solver gurobi;\noption gurobi_options 'outlev=1';\nsolve;", "Gurobi 9.5.0: outlev=1\nSet parameter OutputFlag to value 1\nSet parameter InfUnbdInfo to value 1\nGurobi Optimizer version 9.5.0 build v9.5.0rc5 (mac64[x86])\nThread count: 4 physical cores, 8 logical processors, using up to 8 threads\nOptimize a model with 1 rows, 4 columns and 4 nonzeros\nModel fingerprint: 0x1dc33b55\nVariable types: 0 continuous, 4 integer (4 binary)\nCoefficient statistics:\n Matrix range [3e+00, 6e+00]\n Objective range [1e+01, 5e+01]\n Bounds range [1e+00, 1e+00]\n RHS range [1e+01, 1e+01]\nFound heuristic solution: objective 50.0000000\nPresolve removed 1 rows and 4 columns\nPresolve time: 0.00s\nPresolve: All rows and columns removed\n\nExplored 0 nodes (0 simplex iterations) in 0.00 seconds (0.00 work units)\nThread count was 1 (of 8 available processors)\n\nSolution count 2: 90 50 \n\nOptimal solution found (tolerance 1.00e-04)\nBest objective 9.000000000000e+01, best bound 9.000000000000e+01, gap 0.0000%\nSet parameter Presolve to value 0\nSet parameter Method to value 1\nGurobi Optimizer version 9.5.0 build v9.5.0rc5 (mac64[x86])\nThread count: 4 physical cores, 8 logical processors, using up to 8 threads\nOptimize a model with 1 rows, 4 columns and 4 nonzeros\nModel fingerprint: 0xe07c951d\nCoefficient statistics:\n Matrix range [3e+00, 6e+00]\n Objective range [1e+01, 5e+01]\n Bounds range [1e+00, 1e+00]\n RHS range [1e+01, 1e+01]\nIteration Objective Primal Inf. Dual Inf. Time\n 0 9.0000000e+01 0.000000e+00 0.000000e+00 0s\n\nSolved in 0 iterations and 0.00 seconds (0.00 work units)\nOptimal objective 9.000000000e+01\nGurobi 9.5.0: optimal solution; objective 90\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec51404765739bc970ba5ee5600aa3efa8965dbc
279,227
ipynb
Jupyter Notebook
.ipynb_checkpoints/auto_encorder_and_rnn-checkpoint.ipynb
NlGG/MachineLearning
0aea6288d027f4f19ca86a26c8a107c02913a082
[ "MIT" ]
null
null
null
.ipynb_checkpoints/auto_encorder_and_rnn-checkpoint.ipynb
NlGG/MachineLearning
0aea6288d027f4f19ca86a26c8a107c02913a082
[ "MIT" ]
null
null
null
.ipynb_checkpoints/auto_encorder_and_rnn-checkpoint.ipynb
NlGG/MachineLearning
0aea6288d027f4f19ca86a26c8a107c02913a082
[ "MIT" ]
null
null
null
254.3051
107,650
0.914206
[ [ [ "今回のレポートでは、①オートエンコーダの作成、②再帰型ニューラルネットワークの作成を試みた。", "_____no_output_____" ], [ "①コブダクラス型生産関数を再現できるオートエンコーダの作成が目標である。", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport numpy as np\nimport pylab as pl\nimport math \nfrom sympy import *\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom mpl_toolkits.mplot3d import Axes3D", "_____no_output_____" ], [ "from NN import NN", "_____no_output_____" ] ], [ [ "定義域は0≤x≤1である。", "_____no_output_____" ], [ "<P>コブ・ダグラス型生産関数は以下の通りである。</P>\n<P>z = x_1**0.5*x_2*0.5</P>", "_____no_output_____" ] ], [ [ "def example1(x_1, x_2):\n z = x_1**0.5*x_2*0.5\n return z\n\nfig = pl.figure()\nax = Axes3D(fig)\n\nX = np.arange(0, 1, 0.1)\nY = np.arange(0, 1, 0.1)\n\nX, Y = np.meshgrid(X, Y)\nZ = example1(X, Y)\n\nax.plot_surface(X, Y, Z, rstride=1, cstride=1)\n\npl.show()", "_____no_output_____" ] ], [ [ "NNのクラスはすでにNN.pyからimportしてある。", "_____no_output_____" ] ], [ [ "nn = NN()", "_____no_output_____" ] ], [ [ "以下に使い方を説明する。", "_____no_output_____" ], [ "初めに、このコブ・ダグラス型生産関数を用いる。", "_____no_output_____" ] ], [ [ "x_1 = Symbol('x_1')\nx_2 = Symbol('x_2')\nf = x_1**0.5*x_2*0.5", "_____no_output_____" ] ], [ [ "入力層、中間層、出力層を作る関数を実行する。引数には層の数を用いる。", "_____no_output_____" ] ], [ [ "nn.set_input_layer(2)", "_____no_output_____" ], [ "nn.set_hidden_layer(2)", "_____no_output_____" ], [ "nn.set_output_layer(2)", "_____no_output_____" ] ], [ [ "<p>nn.set_hidden_layer()は同時にシグモイド関数で変換する前の中間層も作る。</p>\n<p>set_output_layer()は同時にシグモイド関数で変換する前の出力層、さらに教師データを入れる配列も作る。</p>", "_____no_output_____" ], [ "nn.setup()で入力層ー中間層、中間層ー出力層間の重みを入れる配列を作成する。", "_____no_output_____" ], [ "nn.initialize()で重みを初期化する。重みは-1/√d ≤ w ≤ 1/√d (dは入力層及び中間層の数)の範囲で一様分布から決定される。", "_____no_output_____" ] ], [ [ "nn.setup()\nnn.initialize()", "_____no_output_____" ] ], [ [ "nn.supervised_function(f, idata)は教師データを作成する。引数は関数とサンプルデータをとる。", "_____no_output_____" ] ], [ [ "idata = [1, 2]", "_____no_output_____" ], [ "nn.supervised_function(f, idata)", "_____no_output_____" ] ], [ [ "nn.simulate(N, eta)は引数に更新回数と学習率をとる。普通はN=1で行うべきかもしれないが、工夫として作成してみた。N回学習した後に出力層を返す。", "_____no_output_____" ] ], [ [ "nn.simulate(1, 0.1)", "_____no_output_____" ] ], [ [ "nn.calculation()は学習せずに入力層から出力層の計算を行う。nn.simulate()内にも用いられている。", "_____no_output_____" ], [ "次に実際に学習を行う。サンプルデータは、", "_____no_output_____" ] ], [ [ "X = np.arange(0, 1, 0.2)\nY = np.arange(0, 1, 0.2)\nprint X, Y", "[ 0. 0.2 0.4 0.6 0.8] [ 0. 0.2 0.4 0.6 0.8]\n" ] ], [ [ "の組み合わせである。", "_____no_output_____" ] ], [ [ "X = np.arange(0, 1, 0.2)\nY = np.arange(0, 1, 0.2)\n\na = np.array([])\nb = np.array([])\nc = np.array([])\n\nnn = NN()\nnn.set_network()\n\nfor x in X:\n for y in Y:\n a = np.append(a, x)\n b = np.append(b, y)\n \nfor i in range(100):\n l = np.random.choice([i for i in range(len(a))])\n m = nn.main2(1, f, [a[l], b[l]], 0.5)\n\nfor x in X:\n for y in Y:\n idata = [x, y]\n c = np.append(c, nn.realize(f, idata))", "_____no_output_____" ], [ "a", "_____no_output_____" ], [ "b", "_____no_output_____" ], [ "c", "_____no_output_____" ] ], [ [ "例えば(0, 0)を入力すると0.52328635を返している(つまりa[0]とb[0]を入力して、c[0]の値を返している)。", "_____no_output_____" ], [ "ここでは交差検定は用いていない。", "_____no_output_____" ] ], [ [ "fig = pl.figure()\nax = Axes3D(fig)\n\nax.scatter(a, b, c)\n\npl.show()", "_____no_output_____" ] ], [ [ "確率的勾配降下法を100回繰り返したが見た感じから近づいている。回数を10000回に増やしてみる。", "_____no_output_____" ] ], [ [ "X = np.arange(0, 1, 0.2)\nY = np.arange(0, 1, 0.2)\n\na = np.array([])\nb = np.array([])\nc = np.array([])\n\nnn = NN()\nnn.set_network()\n\nfor x in X:\n for y in Y:\n a = np.append(a, x)\n b = np.append(b, y)\n \nfor i in range(10000):\n l = np.random.choice([i for i in range(len(a))])\n m = nn.main2(1, f, [a[l], b[l]], 0.5)\n\nfor x in X:\n for y in Y:\n idata = [x, y]\n c = np.append(c, nn.realize(f, idata))", "_____no_output_____" ], [ "fig = pl.figure()\nax = Axes3D(fig)\n\nax.scatter(a, b, c)\n\npl.show()", "_____no_output_____" ] ], [ [ "見た感じ随分近づいているように見える。", "_____no_output_____" ], [ "最後に交差検定を行う。", "_____no_output_____" ], [ "初めに学習回数が極めて少ないNNである。", "_____no_output_____" ] ], [ [ "X = np.arange(0, 1, 0.2)\nY = np.arange(0, 1, 0.2)\n\na = np.array([])\nb = np.array([])\nc = np.array([])\n\nfor x in X:\n for y in Y:\n a = np.append(a, x)\n b = np.append(b, y)\n\nevl = np.array([])\n\nfor i in range(len(a)):\n nn = NN()\n nn.set_network()\n for j in range(1):\n l = np.random.choice([i for i in range(len(a))])\n if l != i:\n nn.main2(1, f, [a[l], b[l]], 0.5)\n idata = [a[i], b[i]]\n est = nn.realize(f, idata)\n evl = np.append(evl, math.fabs(est - nn.supervised_data))", "_____no_output_____" ], [ "np.average(evl)", "_____no_output_____" ] ], [ [ "次に十分大きく(100回に)してみる。", "_____no_output_____" ] ], [ [ "X = np.arange(0, 1, 0.2)\nY = np.arange(0, 1, 0.2)\n\na = np.array([])\nb = np.array([])\nc = np.array([])\n\nnn = NN()\nnn.set_network(h=7)\n\nfor x in X:\n for y in Y:\n a = np.append(a, x)\n b = np.append(b, y)\n\nevl = np.array([])\n\nfor i in range(len(a)):\n nn = NN()\n nn.set_network()\n for j in range(100):\n l = np.random.choice([i for i in range(len(a))])\n if l != i:\n nn.main2(1, f, [a[l], b[l]], 0.5)\n idata = [a[i], b[i]]\n evl = np.append(evl, math.fabs(nn.realize(f, idata) - nn.supervised_data))", "_____no_output_____" ], [ "np.average(evl)", "_____no_output_____" ] ], [ [ "誤差の平均であるので小さい方よい。\n学習回数を増やした結果、精度が上がった。", "_____no_output_____" ], [ "最後にオートエンコーダを作成する。回数を増やした方がよいことが分かったため、10000回学習させてみる。", "_____no_output_____" ] ], [ [ "nn = NN()\nnn.set_network()", "_____no_output_____" ], [ "X = np.arange(0, 1, 0.05)\nY = np.arange(0, 1, 0.05)\n\na = np.array([])\nb = np.array([])\nc = np.array([])\n\nfor x in X:\n for y in Y:\n a = np.append(a, x)\n b = np.append(b, y)\n\nevl = np.array([])\n\ns = [i for i in range(len(a))]\n\nfor j in range(1000):\n l = np.random.choice(s)\n nn.main2(1, f, [a[l], b[l]], 0.5)", "_____no_output_____" ], [ "c = np.array([])\n\nfor i in range(len(a)):\n idata = [a[i], b[i]]\n c = np.append(c, nn.realize(f, idata))", "_____no_output_____" ], [ "fig = pl.figure()\nax = Axes3D(fig)\n\nax.scatter(a, b, c)\n\npl.show()", "_____no_output_____" ] ], [ [ "十分再現できていることが分かる。", "_____no_output_____" ], [ "②ゲーム理論で用いられるTit for Tatを再現してみる。二人のプレーヤーが互いにRNNで相手の行動を予測し、相手の行動に対してTit for Tatに基づいた行動を選択する。", "_____no_output_____" ] ], [ [ "from NN import RNN", "_____no_output_____" ] ], [ [ "最初の行動はRNNで指定できないので、所与となる。この初期値と裏切りに対する感応度で収束の仕方が決まる。", "_____no_output_____" ], [ "協調を1、裏切りを0としている。RNNの予測値は整数値でないが、p=(RNNの出力値)で次回に協調を行う。", "_____no_output_____" ], [ "例1:1期目に、プレーヤー1が協力、プレーヤー2が裏切り。", "_____no_output_____" ] ], [ [ "nn1 = RNN()\nnn1.set_network()\nnn2 = RNN()\nnn2.set_network()\n\nidata1 = [[1, 0]]\nidata2 = [[0, 1]]\nsdata1 = [[0]]\nsdata2 = [[1]]\n\nfor t in range(20):\n \n for i in range(10):\n nn1.main2(idata1, sdata2, 0.9)\n nn2.main2(idata2, sdata1, 0.9)\n \n idata1.append([sdata1[-1][0], sdata2[-1][0]])\n idata2.append([idata1[-1][1], idata1[-1][0]])\n \n n1r = nn1.realize(idata1)\n n2r = nn2.realize(idata1)\n sdata1.append([np.random.choice([1, 0], p=[n1r, 1-n1r])])\n \n sdata2.append([np.random.choice([1, 0], p=[n2r, 1-n2r])])\n \nidata.append([sdata1[-1][0], sdata2[-1][0]])\nprint nn1.realize(idata1), nn2.realize(idata), idata1", "_____no_output_____" ] ], [ [ "下の図より、最初は交互に相手にしっぺ返しをしているが、やがて両者が裏切り合うこと状態に収束する。", "_____no_output_____" ] ], [ [ "p1 = []\np2 = []\nfor i in range(len(idata1)):\n p1.append(idata1[i][0])\nfor i in range(len(idata2)):\n p2.append(idata2[i][0])\nplt.plot(p1, label='player1')\nplt.plot(p2, label='player2')", "_____no_output_____" ] ], [ [ "例2:1期目に、プレーヤー1が協力、プレーヤー2が協力。ただし、プレーヤー2は相手の裏切りをかなり警戒している。", "_____no_output_____" ], [ "警戒を表すためにp=(RNNの出力値 - 0.2)とする。p<0の場合はp=0に直す。", "_____no_output_____" ] ], [ [ "nn1 = RNN()\nnn1.set_network()\nnn2 = RNN()\nnn2.set_network()\n\nidata1 = [[1, 1]]\nidata2 = [[1, 1]]\nsdata1 = [[1]]\nsdata2 = [[1]]\n\nfor t in range(20):\n \n for i in range(10):\n nn1.main2(idata1, sdata2, 0.9)\n nn2.main2(idata2, sdata1, 0.9)\n \n idata1.append([sdata1[-1][0], sdata2[-1][0]])\n idata2.append([idata1[-1][1], idata1[-1][0]])\n \n n1r = nn1.realize(idata1)\n n2r = nn2.realize(idata1)\n \n prob1 = n1r \n prob2 = n2r - 0.3\n \n if prob2 < 0:\n prob2 = 0\n \n sdata1.append([np.random.choice([1, 0], p=[prob1, 1-prob1])])\n \n sdata2.append([np.random.choice([1, 0], p=[prob2, 1-prob2])])\n \nidata.append([sdata1[-1][0], sdata2[-1][0]])\nprint nn1.realize(idata1), nn2.realize(idata), idata1", "_____no_output_____" ], [ "p1 = []\np2 = []\nfor i in range(len(idata1)):\n p1.append(idata1[i][0])\nfor i in range(len(idata2)):\n p2.append(idata2[i][0])\nplt.plot(p1, label='player1')\nplt.plot(p2, label='player2')", "_____no_output_____" ] ], [ [ "例3:次に相手の行動を完全には観測できない場合を考える。t期の相手の行動をt+1期にノイズが加わって知る。例えば、1期目に相手が協調したことを、確率90%で2期目に正しく知れるが、10%で裏切りと誤って伝わる場合である。", "_____no_output_____" ], [ "ノイズは20%の確率で加わるものとする。その他の条件は例1と同じにした。", "_____no_output_____" ] ], [ [ "nn1 = RNN()\nnn1.set_network()\nnn2 = RNN()\nnn2.set_network()\n\nidata1 = [[1, 0]]\nidata2 = [[0, 1]]\nsdata1 = [[0]]\nsdata2 = [[1]]\n\nfor t in range(20):\n \n for i in range(10):\n nn1.main2(idata1, sdata2, 0.9)\n nn2.main2(idata2, sdata1, 0.9)\n \n idata1.append([sdata1[-1][0], np.random.choice([sdata2[-1][0], 1-sdata2[-1][0]], p=[0.8, 0.2])])\n idata2.append([sdata2[-1][0], np.random.choice([sdata1[-1][0], 1-sdata1[-1][0]], p=[0.8, 0.2])])\n \n n1r = nn1.realize(idata1)\n n2r = nn2.realize(idata1)\n \n prob1 = n1r \n prob2 = n2r \n \n sdata1.append([np.random.choice([1, 0], p=[prob1, 1-prob1])])\n \n sdata2.append([np.random.choice([1, 0], p=[prob2, 1-prob2])])\n \nidata.append([sdata1[-1][0], sdata2[-1][0]])\nprint nn1.realize(idata1), nn2.realize(idata), idata1", "_____no_output_____" ], [ "p1 = []\np2 = []\nfor i in range(len(idata1)):\n p1.append(idata1[i][0])\nfor i in range(len(idata2)):\n p2.append(idata2[i][0])\nplt.plot(p1, label='player1')\nplt.plot(p2, label='player2')", "_____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" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
ec514b7120ff4e779e34bd2986c51d04afa10d10
6,847
ipynb
Jupyter Notebook
notebooks-artificial-data/.ipynb_checkpoints/GenerateCertainNumberData-checkpoint.ipynb
algzjh/DataSynthesizer
ba3058dbcf1aad9860807e79adc8c6f7970c9b92
[ "MIT" ]
null
null
null
notebooks-artificial-data/.ipynb_checkpoints/GenerateCertainNumberData-checkpoint.ipynb
algzjh/DataSynthesizer
ba3058dbcf1aad9860807e79adc8c6f7970c9b92
[ "MIT" ]
null
null
null
notebooks-artificial-data/.ipynb_checkpoints/GenerateCertainNumberData-checkpoint.ipynb
algzjh/DataSynthesizer
ba3058dbcf1aad9860807e79adc8c6f7970c9b92
[ "MIT" ]
null
null
null
23.131757
81
0.372864
[ [ [ "import csv\nimport pandas as pd", "_____no_output_____" ], [ "input_file_path = \"./data/GeneratedInputData.csv\"\noutput_file_path = \"./data/GeneratedOutputData.csv\"", "_____no_output_____" ], [ "df = pd.read_csv(input_file_path)", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "num = 401", "_____no_output_____" ], [ "total_row = df.shape[0]", "_____no_output_____" ], [ "sample_df = df.groupby('z').apply(lambda x: x.sample(frac=num / total_row))", "_____no_output_____" ], [ "sample_df.head()", "_____no_output_____" ], [ "sample_df.shape[0]", "_____no_output_____" ], [ "sample_df.to_csv(output_file_path, index=False)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec514e3fa18f7a7126f7da892035508efe40afd4
3,758
ipynb
Jupyter Notebook
day9.ipynb
deyandyankov/aoc.jl
a53aa59a15d176b532f2907617d9fe8d70e10470
[ "MIT" ]
null
null
null
day9.ipynb
deyandyankov/aoc.jl
a53aa59a15d176b532f2907617d9fe8d70e10470
[ "MIT" ]
null
null
null
day9.ipynb
deyandyankov/aoc.jl
a53aa59a15d176b532f2907617d9fe8d70e10470
[ "MIT" ]
null
null
null
22.369048
107
0.460617
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ec515ee682583280d65a7082a3dc2af5adc0f997
95,943
ipynb
Jupyter Notebook
code/zhiyu/OTHER/ZZ_0618_periodic_boundaries.ipynb
charelF/ComplexSystems
3efc9b577ec777fcecbd5248bbbaf77b7d90fc65
[ "MIT" ]
null
null
null
code/zhiyu/OTHER/ZZ_0618_periodic_boundaries.ipynb
charelF/ComplexSystems
3efc9b577ec777fcecbd5248bbbaf77b7d90fc65
[ "MIT" ]
null
null
null
code/zhiyu/OTHER/ZZ_0618_periodic_boundaries.ipynb
charelF/ComplexSystems
3efc9b577ec777fcecbd5248bbbaf77b7d90fc65
[ "MIT" ]
null
null
null
227.353081
78,628
0.877511
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pds\nimport math\nimport random\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\nnp.random.seed(1)\nrandom.seed(1)", "_____no_output_____" ], [ "df = pds.read_csv(\"all_world_indices_clean.csv\")\ndf_spx = df[[\"Date\", \"SPX Index\"]]\ndf_spx[\"Date\"] = pds.to_datetime(df_spx[\"Date\"], format='%d/%m/%Y')\ndf_spx = df_spx.sort_values(by=\"Date\")\ndf_spx.reset_index(inplace=True)\nseries_array = np.array(df_spx[\"SPX Index\"])\nlog_ret_dat = np.diff(np.log(series_array))\nlog_ret_dat_stan = (log_ret_dat - np.mean(log_ret_dat)) / np.std(log_ret_dat)", "_____no_output_____" ], [ "# ============================= NEW ================================= #\ndef cluster_info(arr):\n \"\"\" number of clusters (nonzero fields separated by 0s) in array\n and size of cluster\n \"\"\"\n data = []\n k2coord = {}\n k = 0\n\n # =========================================================== #\n tmp_left = 0\n tmp_right = len(arr)-1\n \n if arr[0] != 0 and arr[-1] != 0: # periodic boundaries\n data.append(0)\n k2coord[k] = []\n \n for i in range(0,len(arr)):\n if arr[i] == 0:\n tmp_left = i\n break\n else:\n data[-1] += 1\n k2coord[k].append(i)\n \n if tmp_left != 0:\n for i in range(len(arr)-1,-1,-1):\n if arr[i] == 0:\n tmp_right = i+1\n break\n else:\n data[-1] += 1\n k2coord[k].append(i)\n\n for i in range(tmp_left, tmp_right):\n if arr[i] == 0 and arr[i+1] != 0:\n data.append(0)\n k += 1\n k2coord[k] = []\n if arr[i] != 0:\n data[-1] += 1\n k2coord[k].append(i)\n # =========================================================== # \n else:\n if arr[0] != 0: # left boundary\n data.append(0) # we will increment later in loop \n k2coord[k] = []\n else:\n k=-1\n\n # print(\"arr\", arr)\n # print(\"data\", data)\n\n for i in range(0,len(arr)-1):\n if arr[i] == 0 and arr[i+1] != 0:\n data.append(0)\n k += 1\n k2coord[k] = []\n if arr[i] != 0:\n data[-1] += 1\n k2coord[k].append(i)\n\n if arr[-1] != 0:\n if data: # if array is not empty\n data[-1] += 1 # right boundary\n k2coord[k].append(len(arr)-1)\n else:\n data.append(1) \n k2coord[k] = [len(arr)-1]\n \n Ncl = len(data) # number of clusters\n Nk = data # Nk[k] = size of cluster k\n coord2k = {e:k for k,v in k2coord.items() for e in v}\n return Ncl, Nk, k2coord, coord2k\n# ============================= NEW ================================= #\n\ndef trunc(X, high, low):\n return min(high, max(X, low))\n\ndef moving_average(x, w):\n return np.convolve(x, np.ones(w), 'valid') / w\n\ndef visualiseFAST(G, P, N, S, X, D):\n fig, (ax1,ax2) = plt.subplots(ncols=1, nrows=2, figsize=(12,4))\n ax1.imshow(G.T, cmap=\"bone\", interpolation=\"None\", aspect=\"auto\")\n ax2.semilogy(S)\n plt.show()\n\ndef visualiseNICE(G, P, N, S, X, D):\n fig, (ax1,ax2,ax3,ax4,ax5,ax6) = plt.subplots(\n ncols=1, nrows=6, figsize=(12,9), sharex=True, gridspec_kw = \n {'wspace':0, 'hspace':0.05, 'height_ratios':[1,2,1,1,1,1]}\n )\n im1 = ax1.imshow(G.T, cmap=\"bone\", interpolation=\"None\", aspect=\"auto\")\n im4 = ax4.imshow(P.T, cmap=\"hot\", interpolation=\"None\", aspect=\"auto\")\n amnwc = np.max(np.abs(N-initial_account_balance)) # absolute max net worth change\n vmin, vmax = initial_account_balance-amnwc, initial_account_balance+amnwc\n im5 = ax5.imshow(N.T, cmap=\"bwr\", interpolation=\"None\", aspect=\"auto\", vmin=vmin, vmax=vmax)\n\n size = \"15%\"\n\n cax1 = make_axes_locatable(ax1).append_axes('right', size=size, pad=0.05)\n fig.colorbar(im1, cax=cax1, orientation='vertical')\n cax4 = make_axes_locatable(ax4).append_axes('right', size=size, pad=0.05)\n fig.colorbar(im4, cax=cax4, orientation='vertical')\n cax5 = make_axes_locatable(ax5).append_axes('right', size=size, pad=0.05)\n fig.colorbar(im5, cax=cax5, orientation='vertical')\n\n cax2 = make_axes_locatable(ax2).append_axes('right', size=size, pad=0.05)\n cax2.hist(S, orientation=\"horizontal\", bins=np.linspace(np.min(S), np.max(S), len(S)//2))\n # cax2.hist(np.log10(S), orientation=\"horizontal\", bins=np.logspace(np.log10(np.min(S)), np.log10(np.max(S)), len(S)//2))\n # cax2.set_xscale(\"log\")\n # cax2.set_yscale(\"log\")\n cax2.get_xaxis().set_visible(False)\n cax2.get_yaxis().set_visible(False)\n\n cax3 = make_axes_locatable(ax3).append_axes('right', size=size, pad=0.05)\n cax3.hist(X, orientation=\"horizontal\", bins=np.linspace(np.min(X), np.max(X), len(X)//5))\n cax3.get_xaxis().set_visible(False)\n cax3.get_yaxis().set_visible(False)\n\n cax6 = make_axes_locatable(ax6).append_axes('right', size=size, pad=0.05)\n cax6.get_xaxis().set_visible(False)\n cax6.get_yaxis().set_visible(False)\n\n #ax2.set_yscale(\"log\")\n ax2.plot(S, label=\"S\")\n Ws = [25]\n for W in Ws:\n ax2.plot(np.arange(W-1, len(S)), moving_average(S, W), label=f\"MA{W}\")\n ax2.grid(alpha=0.4)\n # ax2.legend(ncol=len(Ws)+1)\n\n ax3.bar(np.arange(len(X)), X)\n ax3.grid(alpha=0.4)\n\n if D.shape[1] < 25:\n ax6.plot(D, color=\"black\", alpha=0.3)\n ax6.plot(np.mean(D,axis=1), color=\"black\", alpha=1)\n ax6.grid(alpha=0.4)\n \n\n ax6.set_xlabel(\"time\")\n # ax2.set_ylabel(\"standardised log returns\")\n ax2.set_ylabel(\"close price\")\n ax1.set_ylabel(\"agents\")\n ax3.set_ylabel(\"log return\")\n ax4.set_ylabel(\"portfolio\")\n ax5.set_ylabel(\"net worth\")\n ax6.set_ylabel(\"influence (I)\")\n\n # fig.colorbar(im, cax=ax4)\n\n plt.tight_layout()\n plt.show()", "_____no_output_____" ], [ "pd = 0.05 # Probability that an active trader diffuses\npe = 0.0001 # Probability that an inactive trader spontaneously enters\nph = 0.0485 # Probability that an active trader turns on \npa = 0.3 # Initial proportion of active traders\n\nN0 = 200\nN1 = 1000\n\nA = 1.8\na = 3.6\nh = 1\n\ninitial_stock_price = 100\n\ndrift = 0\n#max_look_back = 3\n\nG = np.zeros(shape=(N0,N1))\nG[0] = np.random.choice(a=[-1,0,1], p=[pa/2, 1-pa, pa/2], size=N1, replace=True)\n#G[0] = ((np.arange(0,N1)*6//N1)%3)-1\n# G[0] = ((np.arange(0,N1)*1//N1)%3)-1\n\nP = np.zeros_like(G) # portfolio: number of stocks\nN = np.zeros_like(G) # Net worth\nB = np.zeros_like(G) # acc balance\n\nB[0] = initial_account_balance # everyone start with 1000 money\nN[0] = B[0] # noone has stock initially\n\nD = np.zeros_like(G)\n\nX = np.zeros(N0)\nS = np.zeros(N0)\nS[0] = initial_stock_price\n\n\nfor t in range(N0-1):\n Ncl, Nk, k2coord, coord2k = cluster_info(G[t])\n\n Xt = 0\n for k, size in enumerate(Nk):\n tmp = 0\n for i in k2coord[k]:\n tmp += G[t,i]\n Xt += size * tmp\n X[t+1] = Xt/(10*N0)\n S[t+1] = S[t]*math.exp(X[t]) + drift\n\n xi = np.random.uniform(-1, 1, size=Ncl) # unique xi for each cluster k\n\n for i in range(N1):\n P[t+1,i] = P[t,i] + G[t,i]\n # their next balance is their current balance minus\n # their purchase (or sell) of stock at current price\n B[t+1,i] = B[t,i] - (G[t,i] * S[t])\n N[t+1,i] = B[t,i] + (P[t,i]*S[t])\n\n if G[t,i] != 0:\n # =================================================================\n\n # original -------------------------------------------------------------------------------\n k = coord2k[i]\n total = 0\n zeta = random.uniform(-1,1) # sampled for each unique (k,i)\n for j in k2coord[k]: # for each coordinate in cluster k\n eta = random.uniform(-1,1) # different for each cell\n sigma = G[t,j]\n cluster_influence = A*xi[k]\n member_influence = a*eta\n total += ((cluster_influence + member_influence) * sigma)\n self_influence = h*zeta\n I = (1 / len(k2coord[k])) * total + self_influence\n p = 1 / (1 + math.exp(-2 * I))\n\n\n # =================================================================\n if random.random() < p:\n G[t+1,i] = 1\n else:\n G[t+1,i] = -1\n\n \n # ==============================================================\n # batolozzi paper dynamics\n \n # trader influences non-active neighbour to join ph\n if G[t,i] != 0:\n stance = G[t,i]\n if random.random() < ph:\n if G[t,(i-1)%N1] == 0 and G[t,(i+1)%N1] == 0:\n ni = np.random.choice([-1,1])\n G[t+1,(i+ni)%N1] = np.random.choice([-1,1])\n elif G[t,(i-1)%N1] == 0:\n G[t+1,(i-1)%N1] = np.random.choice([-1,1])\n elif G[t,(i+1)%N1] == 0:\n G[t+1,(i+1)%N1] = np.random.choice([-1,1])\n else:\n continue\n\n # active trader diffuses if it has inactive neighbour\n # only happens at edge of cluster\n if G[t,i] != 0:\n if random.random() < pd:\n if (G[t,(i-1)%N1] == 0) or (G[t,(i+1)%N1] == 0):\n G[t+1,i] = 0\n else:\n continue\n\n # nontrader enters market\n if G[t,i] == 0:\n if random.random() < pe:\n G[t+1,i] = np.random.choice([-1,1])\n # ==============================================================\n\n\nfinal_trade = P[-1] * S[-1]\nB[-1] += final_trade\nN[-1] = B[-1]\n\nvisualiseNICE(G,P,N,S,X,D)\n# visualiseFAST(G,P,N,S,X,D)", "_____no_output_____" ], [ "df = pd.read_csv(\"all_world_indices_clean.csv\")\ndf_spx = df[[\"Date\", \"SPX Index\"]]\ndf_spx[\"Date\"] = pd.to_datetime(df_spx[\"Date\"], format='%d/%m/%Y')\ndf_spx = df_spx.sort_values(by=\"Date\")\ndf_spx.reset_index(inplace=True)\nseries_array = np.array(df_spx[\"SPX Index\"])\nlog_ret_dat = np.diff(np.log(series_array))\nlog_ret_dat_stan = (log_ret_dat - np.mean(log_ret_dat)) / np.std(log_ret_dat)", "_____no_output_____" ], [ "r = (X - np.mean(X)) / np.std(X)\n\nprint(np.std(r))\nprint(np.std(log_ret_dat_stan))\n\nfig = plt.figure(figsize=(8, 8))\nplt.hist(r, alpha=0.4, bins=30, label=\"CA\", density=True)\nplt.hist(log_ret_dat_stan, bins=30, alpha=0.4, label=\"S&P500\", density=True)\nplt.yscale(\"log\")\nplt.title(\"Log Return Distribution - Standardised\")\nplt.legend()\nplt.grid(alpha=0.2)\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
ec516c4c126cbae42e0f2512c54902921e1861bd
34,269
ipynb
Jupyter Notebook
doc/source/notebooks/basics/GPLVM.ipynb
akhayes/GPflow
ff339f8db879149c770e642b5a8ee6711ff26d11
[ "Apache-2.0" ]
null
null
null
doc/source/notebooks/basics/GPLVM.ipynb
akhayes/GPflow
ff339f8db879149c770e642b5a8ee6711ff26d11
[ "Apache-2.0" ]
null
null
null
doc/source/notebooks/basics/GPLVM.ipynb
akhayes/GPflow
ff339f8db879149c770e642b5a8ee6711ff26d11
[ "Apache-2.0" ]
null
null
null
86.103015
22,496
0.833932
[ [ [ "# Bayesian Gaussian Process Latent Variable Model (Bayesian GPLVM)\nThis notebook shows how to use the Bayesian GPLVM model. This is an unsupervised learning method usually used for dimensionality reduction. For an in-depth overview of GPLVMs,see *[1, 2]*.", "_____no_output_____" ] ], [ [ "import gpflow\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nimport gpflow\nfrom gpflow.utilities import ops, print_summary\nfrom gpflow.config import set_default_float, default_float, set_default_summary_fmt\nfrom gpflow.ci_utils import ci_niter\n\nset_default_float(np.float64)\nset_default_summary_fmt(\"notebook\")\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Data\nWe are using the \"three phase oil flow\" dataset used initially for demonstrating the Generative Topographic mapping from *[3]*.", "_____no_output_____" ] ], [ [ "data = np.load('./data/three_phase_oil_flow.npz')", "_____no_output_____" ] ], [ [ "Following the GPflow notation we assume this dataset has size [num_data, output_dim]", "_____no_output_____" ] ], [ [ "Y = tf.convert_to_tensor(data['Y'], dtype=default_float())", "_____no_output_____" ] ], [ [ "Integer in [0, 2] indicating to which class the datapoint belongs [num_data,]. Not used for model fitting, only for plotting afterwards.", "_____no_output_____" ] ], [ [ "labels = tf.convert_to_tensor(data['labels'])", "_____no_output_____" ], [ "print('Number of points: {} and Number of dimensions: {}'.format(Y.shape[0], Y.shape[1]))", "Number of points: 100 and Number of dimensions: 12\n" ] ], [ [ "## Model construction\n\nWe start by initialising the required variables:", "_____no_output_____" ] ], [ [ "latent_dim = 2 # number of latent dimensions\nnum_inducing = 20 # number of inducing pts\nnum_data = Y.shape[0] # number of data points", "_____no_output_____" ] ], [ [ "Initialise via PCA:", "_____no_output_____" ] ], [ [ "x_mean_init = tf.convert_to_tensor(ops.pca_reduce(Y, latent_dim), dtype=default_float())\nx_var_init = tf.convert_to_tensor(np.ones((num_data, latent_dim)), dtype=default_float())", "_____no_output_____" ] ], [ [ "Pick inducing inputs randomly from dataset initialisation:", "_____no_output_____" ] ], [ [ "inducing_variable = tf.convert_to_tensor(np.random.permutation(x_mean_init.numpy())[:num_inducing], dtype=default_float())", "_____no_output_____" ] ], [ [ "We construct a Squared Exponential (SE) kernel operating on the two-dimensional latent space. \nThe `ARD` parameter stands for Automatic Relevance Determination, which in practice means that\nwe learn a different lengthscale for each of the input dimensions. See [Manipulating kernels](../advanced/kernels.ipynb) for more information.", "_____no_output_____" ] ], [ [ "lengthscale = tf.convert_to_tensor([1.0] * latent_dim, dtype=default_float())\nkernel = gpflow.kernels.RBF(lengthscale=lengthscale, ard=True)", "_____no_output_____" ] ], [ [ "We have all the necessary ingredients to construct the model. GPflow contains an implementation of the Bayesian GPLVM:", "_____no_output_____" ] ], [ [ "gplvm = gpflow.models.BayesianGPLVM(Y,\n x_data_mean=x_mean_init,\n x_data_var=x_var_init,\n kernel=kernel,\n inducing_variable=inducing_variable)\n# Instead of passing an inducing_variable directly, we can also set the num_inducing_variables argument to an integer, which will randomly pick from the data.", "_____no_output_____" ] ], [ [ "We change the default likelihood variance, which is 1, to 0.01.", "_____no_output_____" ] ], [ [ "gplvm.likelihood.variance.assign(0.01)", "_____no_output_____" ] ], [ [ "Next we optimise the created model. Given that this model has a deterministic evidence lower bound (ELBO), we can use SciPy's L-BFGS-B optimiser.", "_____no_output_____" ] ], [ [ "opt = gpflow.optimizers.Scipy()\nmaxiter = ci_niter(1000)\n\[email protected](autograph=False)\ndef optimization_step():\n return - gplvm.log_marginal_likelihood()\n\n_ = opt.minimize(optimization_step, method=\"bfgs\", variables=gplvm.trainable_variables, options=dict(maxiter=maxiter))", "_____no_output_____" ] ], [ [ "## Model analysis\nGPflow allows you to inspect the learned model hyperparameters.", "_____no_output_____" ] ], [ [ "print_summary(gplvm)", "_____no_output_____" ] ], [ [ "## Plotting vs. Principle Component Analysis (PCA)\nThe reduction of the dimensionality of the dataset to two dimensions allows us to visualise the learned manifold.\nWe compare the Bayesian GPLVM's latent space to the deterministic PCA's one.", "_____no_output_____" ] ], [ [ "xpca = ops.pca_reduce(Y, latent_dim)\ngplvm_x_mean = gplvm.x_data_mean.numpy()\n\nf, ax = plt.subplots(1, 2, figsize=(10, 6))\n\nfor i in np.unique(labels):\n ax[0].scatter(xpca[labels==i, 0], xpca[labels==i, 1], label=i)\n ax[1].scatter(gplvm_x_mean[labels==i, 0], gplvm_x_mean[labels==i, 1], label=i)\n ax[0].set_title('PCA')\n ax[1].set_title('Bayesian GPLVM')", "_____no_output_____" ] ], [ [ "## References\n\\[1\\] Lawrence, Neil D. 'Gaussian process latent variable models for visualisation of high dimensional data'. *Advances in Neural Information Processing Systems*. 2004.\n\n\\[2\\] Titsias, Michalis, and Neil D. Lawrence. 'Bayesian Gaussian process latent variable model'. *Proceedings of the Thirteenth International Conference on Artificial Intelligence and Statistics*. 2010.\n\n\\[3\\] Bishop, Christopher M., and Gwilym D. James. 'Analysis of multiphase flows using dual-energy gamma densitometry and neural networks'. *Nuclear Instruments and Methods in Physics Research Section A: Accelerators, Spectrometers, Detectors and Associated Equipment* 327.2-3 (1993): 580-593.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec516d5bcaa81a9bed495590c703431ee4966e92
576,330
ipynb
Jupyter Notebook
examples/TIRAVEL_Quickstart.ipynb
SPARTA-dev/SPARTA
75ae5a740a15e22ab78c3d5350b7956d98e92f0b
[ "MIT" ]
12
2020-07-15T11:15:57.000Z
2022-03-26T16:29:13.000Z
examples/TIRAVEL_Quickstart.ipynb
SPARTA-dev/SPARTA
75ae5a740a15e22ab78c3d5350b7956d98e92f0b
[ "MIT" ]
2
2022-03-22T08:50:26.000Z
2022-03-22T09:53:00.000Z
examples/TIRAVEL_Quickstart.ipynb
SPARTA-dev/SPARTA
75ae5a740a15e22ab78c3d5350b7956d98e92f0b
[ "MIT" ]
1
2021-03-04T16:25:49.000Z
2021-03-04T16:25:49.000Z
1,138.992095
181,140
0.95936
[ [ [ "# TIRAVEL_Quickstart", "_____no_output_____" ], [ "### The notebook contains an RV calculation refinement tool, based on Zucker & Mazeh 2006 TIRAVEL - Template Independent RAdial VELocity measurement (arXiv:astro-ph/0607293).\n\nThis partial implementation of the TIRAVEL method enables using initial observation RV values to create a template for more accurate RV extraction.\n\nTo demonstrate our RV extraction and refinement process, we use HARPS observations of LTT 9779 (TOI-193) used by Jenkins Et. Al. to detect an ultra-hot Neptune with a period of 0.79 days (arXiv:2009.12832).\n", "_____no_output_____" ], [ "### 1 Imports & funcs", "_____no_output_____" ] ], [ [ "import sys\n\nfrom sparta.Auxil.PeriodicityDetector import PeriodicityDetector\nfrom sparta.UNICOR.Spectrum import Spectrum\nfrom sparta.UNICOR.Template import Template\nfrom sparta.Auxil.TimeSeries import TimeSeries\nfrom sparta.Observations import Observations\nimport numpy as np\nimport random\nfrom scipy import interpolate\nfrom PyAstronomy import pyasl\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nfrom copy import deepcopy", "_____no_output_____" ] ], [ [ "### 2 Using the Observations class to read and process the TOI-193 HARPS observations.\n\n`Observations` class enables one to load observation data from a given folder \nand place it into a TimeSeries object.", "_____no_output_____" ] ], [ [ "# Note we used sample_rate to sampple only half of the available observations\nobs_data = Observations(survey='HARPS', target_visits_lib='data/TOI193/', min_wv=4990, max_wv=5090, sample_rate=2)\n\nfor i in obs_data.observation_TimeSeries.vals:\n i = i.SpecPreProccess()\n \nplt.figure(figsize=(7, 3.5)) \nplt.title(\"TOI-193 observations\")\nplt.ylabel(\"Flux\")\nplt.xlabel(\"Wavelength (Angstrom)\")\n\nfor i, s in enumerate(obs_data.observation_TimeSeries.vals):\n plt.plot(s.wv[0], s.sp[0], alpha=0.3)\n\nplt.show()\n\nprint(len(obs_data.observation_TimeSeries.vals), \"epochs.\")", "_____no_output_____" ] ], [ [ "### 3 Using the Template class to download and process a matching library template.\n\n`Template` class enables downloading and processing PHEONIX library template for RV extraction.\nHere we use the published TOI-193 parameters. We also applying rotational and gaussian broadening to the spectrum.", "_____no_output_____" ] ], [ [ "# Loading a Phoenix synthetic spectrum\nt = Template(temp=5500, log_g=4.5, metal=0, alpha=0, min_val=4980, max_val=5100, air=False)\ntemplate_star_broadend = Template(template=Spectrum(wv=t.model.wv, sp=t.model.sp).InterpolateSpectrum())\n\nv_sin_i = 1.5\nprint('RotationalBroadening.', end=' ')\ntemplate_star_broadend.RotationalBroadening(epsilon=0.5, vsini=v_sin_i)\ntemplate_star_broadend = deepcopy(Template(template=Spectrum(wv=[template_star_broadend.model.wv[0]], sp=[template_star_broadend.model.sp[0]]).SpecPreProccess()))\ntemplate_star_broadend = Template(template=Spectrum(wv=template_star_broadend.model.wv, sp=template_star_broadend.model.sp).InterpolateSpectrum(delta=0.5))\n\nprint('GaussianBroadening.', end=' ')\ntemplate_star_broadend.GaussianBroadening(resolution=115_000)\n\n\ntemplate_star_final = Template(template=Spectrum(wv=template_star_broadend.model.wv, sp=template_star_broadend.model.sp).SpecPreProccess())\n", "RotationalBroadening. GaussianBroadening. " ], [ "plt.figure(figsize=(20,6)) \nplt.title(\"TOI-193 HARRPS observations VS. Library Template\")\nplt.ylabel(\"Flux\")\nplt.xlabel(\"Wavelength (Angstrom)\")\n\nplt.plot(template_star_final.model.wv[0], template_star_final.model.sp[0], alpha=0.3, color=\"blue\")\n\nfor i, s in enumerate(obs_data.observation_TimeSeries.vals):\n plt.plot(s.wv[0], s.sp[0], alpha=0.1)\n\nplt.legend([\"library template\"])\n\nplt.show()\n", "C:\\Users\\AbrahamBinnfeld\\AppData\\Roaming\\Python\\Python37\\site-packages\\IPython\\core\\pylabtools.py:132: UserWarning: Creating legend with loc=\"best\" can be slow with large amounts of data.\n fig.canvas.print_figure(bytes_io, **kw)\n" ] ], [ [ "### 3 Using fastccf method to extract RV values for the observations using the template.\n", "_____no_output_____" ] ], [ [ "calculated_vrad_list = obs_data.calc_rv_against_template(template_star_final, dv=0.1, # 0.01\n VelBound=[-117, 117], combine_ccfs=False,\n fastccf=True).vels", "100%|██████████████████████████████████████████████████████████████████████████████████| 16/16 [00:00<00:00, 18.10it/s]\n" ], [ "plt.figure(figsize=(8,5)) \nplt.title(\"TOI-193 Phase-Folded RVs\")\nplt.ylabel(\"RV (km/s)\")\nplt.xlabel(\"Phase\")\n\nplt.scatter([ttt % 0.79 for ttt in obs_data.observation_TimeSeries.times], calculated_vrad_list, alpha=0.4)\n\nplt.show()\n", "_____no_output_____" ] ], [ [ "### 3 Using TIRAVEL to refine our RV measurements.\n", "_____no_output_____" ] ], [ [ "template_TIRAVEL = obs_data.observation_TimeSeries.TIRAVEL([calculated_vrad_list])\nfor i in obs_data.observation_TimeSeries.vals:\n i = i.TrimSpec(Ntrim=150)", "_____no_output_____" ], [ "# tir = deepcopy(template_star_broadend)", "_____no_output_____" ], [ "refined_vrad_list = obs_data.calc_rv_against_template(template_TIRAVEL, dv=0.1,\n VelBound=[-117, 117], combine_ccfs=False,\n fastccf=True).vels", "100%|██████████████████████████████████████████████████████████████████████████████████| 16/16 [00:00<00:00, 40.64it/s]\n" ], [ "plt.figure(figsize=(20,6)) \n \nplt.plot(template_star_final.model.wv[0], template_star_final.model.sp[0], alpha=0.5)\nplt.plot(template_TIRAVEL.model.wv[0], template_TIRAVEL.model.sp[0], alpha=0.8)\n\nplt.legend([\"library template\", \"TIRAVEL template\"])\n\nplt.show()", "C:\\Users\\AbrahamBinnfeld\\AppData\\Roaming\\Python\\Python37\\site-packages\\IPython\\core\\pylabtools.py:132: UserWarning: Creating legend with loc=\"best\" can be slow with large amounts of data.\n fig.canvas.print_figure(bytes_io, **kw)\n" ], [ "plt.figure(figsize=(8,5)) \nplt.title(\"TOI-193 Phase-Folded RVs\")\nplt.ylabel(\"RV (km/s)\")\nplt.xlabel(\"Phase\")\n\nplt.scatter([ttt % 0.79 for ttt in obs_data.observation_TimeSeries.times], calculated_vrad_list, alpha=0.4)\nplt.scatter([ttt % 0.79 for ttt in obs_data.observation_TimeSeries.times], refined_vrad_list, alpha=0.4)\nplt.legend([\"orig_RVs\", \"TIRAVEL_RVs\"])\n\nplt.show()", "_____no_output_____" ] ], [ [ "### 2. Using the PeriodicityDetector class to run GLS on the spectra", "_____no_output_____" ] ], [ [ "# PeriodicityDetector object initialization\nobs_data.initialize_periodicity_detector(freq_range=(0.5, 2), periodogram_grid_resolution=1_000)\nobs_data.periodicity_detector.period = [0.792] # The published planetary period in days", "_____no_output_____" ] ], [ [ "First we will try running the GLS periodogram using our initial RV estimations.", "_____no_output_____" ] ], [ [ "obs_data.observation_TimeSeries.calculated_vrad_list = calculated_vrad_list", "_____no_output_____" ], [ "obs_data.periodicity_detector.run_GLS_process()\n\nobs_data.periodicity_detector.periodogram_plots(velocities_flag=True)\n\nplt.show()", "_____no_output_____" ] ], [ [ "The resulted periodogram doesn't present the highest peak in the expected published period.\n\nNow we'll run the periodogram on the refined RV data.", "_____no_output_____" ] ], [ [ "obs_data.observation_TimeSeries.calculated_vrad_list = refined_vrad_list", "_____no_output_____" ], [ "obs_data.periodicity_detector.run_GLS_process()\n\nobs_data.periodicity_detector.periodogram_plots(velocities_flag=True)\n\nplt.show()", "_____no_output_____" ] ], [ [ "As expected, the refined RV estimation present slightly better results in detecting the planetary period in the data.\n\nAlthough this is not a significant enough detection example, it is a light-weight demonstration to the TIRAVEL advantages.", "_____no_output_____" ] ] ]
[ "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", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
ec5176c82d1427de00eabdbfd4a37ae80e6e15ff
16,933
ipynb
Jupyter Notebook
.ipynb_checkpoints/Numpy Practice-checkpoint.ipynb
PatrickAttankurugu/numpy
55b7cb85a8fd9da10fb1082cd3654664c77776d4
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Numpy Practice-checkpoint.ipynb
PatrickAttankurugu/numpy
55b7cb85a8fd9da10fb1082cd3654664c77776d4
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Numpy Practice-checkpoint.ipynb
PatrickAttankurugu/numpy
55b7cb85a8fd9da10fb1082cd3654664c77776d4
[ "MIT" ]
null
null
null
16.682759
134
0.433827
[ [ [ "import numpy as np", "_____no_output_____" ], [ "array_a=np.array([1,2,3])", "_____no_output_____" ], [ "array_a", "_____no_output_____" ], [ "array_b=np.array([[1,2,3],[3,4,5],[6,7,8]])", "_____no_output_____" ], [ "array_b", "_____no_output_____" ], [ "np.mean(array_b,axis=0)", "_____no_output_____" ], [ "array1=np.array([[1,2,3],[4,5,6]])", "_____no_output_____" ], [ "array1", "_____no_output_____" ], [ "type(array1)", "_____no_output_____" ], [ "array1.shape", "_____no_output_____" ], [ "list_a=[[1,2,3,6],[4,5,6,8],[7,8,9,9]]", "_____no_output_____" ], [ "len(list_a)", "_____no_output_____" ], [ "type(list_a)", "_____no_output_____" ], [ "type(array_a)", "_____no_output_____" ], [ "confuse=np.array([1,2,3])", "_____no_output_____" ], [ "confuse", "_____no_output_____" ], [ "len(list_a)", "_____no_output_____" ], [ "len(list_a[0])", "_____no_output_____" ], [ "len(list_a)", "_____no_output_____" ], [ "len(list_a[0])", "_____no_output_____" ], [ "len(list_a[2])", "_____no_output_____" ], [ "print(list_a)", "[[1, 2, 3, 6], [4, 5, 6, 8], [7, 8, 9, 9]]\n" ], [ "p=list_a", "_____no_output_____" ], [ "np.array(p)", "_____no_output_____" ], [ "list_b=list_a[0]+list_a[1]", "_____no_output_____" ], [ "list_b", "_____no_output_____" ], [ "array_b=array_a[0]+array_a[1]", "_____no_output_____" ], [ "array_b", "_____no_output_____" ], [ "np.sqrt(array_a)", "_____no_output_____" ] ], [ [ "NUMPY FUNDAMENTALS", "_____no_output_____" ] ], [ [ "array_z=np.array([[2,3,4,5],[5,6,7,78],[3,4,7,5]])", "_____no_output_____" ], [ "array_z", "_____no_output_____" ], [ "array_z[0]", "_____no_output_____" ], [ "array_z[0][1]", "_____no_output_____" ], [ "array_z[2][2]", "_____no_output_____" ], [ "array_z[2][3]", "_____no_output_____" ], [ "array_z[-1]", "_____no_output_____" ], [ "array_z[-2]", "_____no_output_____" ] ], [ [ "We can assign values to individual elements of an array. See the code below. ", "_____no_output_____" ] ], [ [ "array_z[0,3]=9", "_____no_output_____" ], [ "array_z", "_____no_output_____" ] ], [ [ "To set all values of column 1 to 9 , we enter the command below. We have changed the fourth element of the first row from 5 to 9", "_____no_output_____" ] ], [ [ "array_z[:,1]=9", "_____no_output_____" ], [ "\narray_z", "_____no_output_____" ] ], [ [ "We want to now set all values of row 0 to 3", "_____no_output_____" ] ], [ [ "array_z[0]=3", "_____no_output_____" ], [ "array_z", "_____no_output_____" ] ], [ [ "We want to now set entire rows of an array to a list", "_____no_output_____" ] ], [ [ "someList=array_z[0]", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
ec5178700eb0d981d79228361ce6adb986dd635d
120,236
ipynb
Jupyter Notebook
intro-to-pytorch/Part 5 - Inference and Validation (Solution).ipynb
Swapnil2095/deep-learning-v2-pytorch
1c19cc523de12df5762294bcc0c7d07fc9bb782e
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 5 - Inference and Validation (Solution).ipynb
Swapnil2095/deep-learning-v2-pytorch
1c19cc523de12df5762294bcc0c7d07fc9bb782e
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 5 - Inference and Validation (Solution).ipynb
Swapnil2095/deep-learning-v2-pytorch
1c19cc523de12df5762294bcc0c7d07fc9bb782e
[ "MIT" ]
1
2021-01-09T15:58:44.000Z
2021-01-09T15:58:44.000Z
217.032491
51,824
0.893667
[ [ [ "# Inference and Validation\n\nNow that you have a trained network, you can use it for making predictions. This is typically called **inference**, a term borrowed from statistics. However, neural networks have a tendency to perform *too well* on the training data and aren't able to generalize to data that hasn't been seen before. This is called **overfitting** and it impairs inference performance. To test for overfitting while training, we measure the performance on data not in the training set called the **validation** set. We avoid overfitting through regularization such as dropout while monitoring the validation performance during training. In this notebook, I'll show you how to do this in PyTorch. \n\nAs usual, let's start by loading the dataset through torchvision. You'll learn more about torchvision and loading data in a later part. This time we'll be taking advantage of the test set which you can get by setting `train=False` here:\n\n```python\ntestset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)\n```\n\nThe test set contains images just like the training set. Typically you'll see 10-20% of the original dataset held out for testing and validation with the rest being used for training.", "_____no_output_____" ] ], [ [ "import torch\nfrom torchvision import datasets, transforms\n\n# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n# Download and load the training data\ntrainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n\n# Download and load the test data\ntestset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)", "_____no_output_____" ] ], [ [ "Here I'll create a model like normal, using the same one from my solution for part 4.", "_____no_output_____" ] ], [ [ "from torch import nn, optim\nimport torch.nn.functional as F\n\nclass Classifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(784, 256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 10)\n \n def forward(self, x):\n # make sure input tensor is flattened\n x = x.view(x.shape[0], -1)\n \n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.log_softmax(self.fc4(x), dim=1)\n \n return x", "_____no_output_____" ] ], [ [ "The goal of validation is to measure the model's performance on data that isn't part of the training set. Performance here is up to the developer to define though. Typically this is just accuracy, the percentage of classes the network predicted correctly. Other options are [precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall#Definition_(classification_context)) and top-5 error rate. We'll focus on accuracy here. First I'll do a forward pass with one batch from the test set.", "_____no_output_____" ] ], [ [ "model = Classifier()\n\nimages, labels = next(iter(testloader))\n# Get the class probabilities\nps = torch.exp(model(images))\n# Make sure the shape is appropriate, we should get 10 class probabilities for 64 examples\nprint(ps.shape)", "_____no_output_____" ] ], [ [ "With the probabilities, we can get the most likely class using the `ps.topk` method. This returns the $k$ highest values. Since we just want the most likely class, we can use `ps.topk(1)`. This returns a tuple of the top-$k$ values and the top-$k$ indices. If the highest value is the fifth element, we'll get back 4 as the index.", "_____no_output_____" ] ], [ [ "top_p, top_class = ps.topk(1, dim=1)\n# Look at the most likely classes for the first 10 examples\nprint(top_class[:10,:])", "_____no_output_____" ] ], [ [ "Now we can check if the predicted classes match the labels. This is simple to do by equating `top_class` and `labels`, but we have to be careful of the shapes. Here `top_class` is a 2D tensor with shape `(64, 1)` while `labels` is 1D with shape `(64)`. To get the equality to work out the way we want, `top_class` and `labels` must have the same shape.\n\nIf we do\n\n```python\nequals = top_class == labels\n```\n\n`equals` will have shape `(64, 64)`, try it yourself. What it's doing is comparing the one element in each row of `top_class` with each element in `labels` which returns 64 True/False boolean values for each row.", "_____no_output_____" ] ], [ [ "equals = top_class == labels.view(*top_class.shape)", "_____no_output_____" ] ], [ [ "Now we need to calculate the percentage of correct predictions. `equals` has binary values, either 0 or 1. This means that if we just sum up all the values and divide by the number of values, we get the percentage of correct predictions. This is the same operation as taking the mean, so we can get the accuracy with a call to `torch.mean`. If only it was that simple. If you try `torch.mean(equals)`, you'll get an error\n\n```\nRuntimeError: mean is not implemented for type torch.ByteTensor\n```\n\nThis happens because `equals` has type `torch.ByteTensor` but `torch.mean` isn't implement for tensors with that type. So we'll need to convert `equals` to a float tensor. Note that when we take `torch.mean` it returns a scalar tensor, to get the actual value as a float we'll need to do `accuracy.item()`.", "_____no_output_____" ] ], [ [ "accuracy = torch.mean(equals.type(torch.FloatTensor))\nprint(f'Accuracy: {accuracy.item()*100}%')", "_____no_output_____" ] ], [ [ "The network is untrained so it's making random guesses and we should see an accuracy around 10%. Now let's train our network and include our validation pass so we can measure how well the network is performing on the test set. Since we're not updating our parameters in the validation pass, we can speed up the by turning off gradients using `torch.no_grad()`:\n\n```python\n# turn off gradients\nwith torch.no_grad():\n # validation pass here\n for images, labels in testloader:\n ...\n```\n\n>**Exercise:** Implement the validation loop below. You can largely copy and paste the code from above, but I suggest typing it in because writing it out yourself is essential for building the skill. In general you'll always learn more by typing it rather than copy-pasting.", "_____no_output_____" ] ], [ [ "model = Classifier()\ncriterion = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.003)\n\nepochs = 30\nsteps = 0\n\ntrain_losses, test_losses = [], []\nfor e in range(epochs):\n running_loss = 0\n for images, labels in trainloader:\n \n optimizer.zero_grad()\n \n log_ps = model(images)\n loss = criterion(log_ps, labels)\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n \n else:\n test_loss = 0\n accuracy = 0\n \n # Turn off gradients for validation, saves memory and computations\n with torch.no_grad():\n for images, labels in testloader:\n log_ps = model(images)\n test_loss += criterion(log_ps, labels)\n \n ps = torch.exp(log_ps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor))\n \n train_losses.append(running_loss/len(trainloader))\n test_losses.append(test_loss/len(testloader))\n\n print(\"Epoch: {}/{}.. \".format(e+1, epochs),\n \"Training Loss: {:.3f}.. \".format(running_loss/len(trainloader)),\n \"Test Loss: {:.3f}.. \".format(test_loss/len(testloader)),\n \"Test Accuracy: {:.3f}\".format(accuracy/len(testloader)))", "_____no_output_____" ], [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "plt.plot(train_losses, label='Training loss')\nplt.plot(test_losses, label='Validation loss')\nplt.legend(frameon=False)", "_____no_output_____" ] ], [ [ "## Overfitting\n\nIf we look at the training and validation losses as we train the network, we can see a phenomenon known as overfitting.\n\n<img src='assets/overfitting.png' width=450px>\n\nThe network learns the training set better and better, resulting in lower training losses. However, it starts having problems generalizing to data outside the training set leading to the validation loss increasing. The ultimate goal of any deep learning model is to make predictions on new data, so we should strive to get the lowest validation loss possible. One option is to use the version of the model with the lowest validation loss, here the one around 8-10 training epochs. This strategy is called *early-stopping*. In practice, you'd save the model frequently as you're training then later choose the model with the lowest validation loss.\n\nThe most common method to reduce overfitting (outside of early-stopping) is *dropout*, where we randomly drop input units. This forces the network to share information between weights, increasing it's ability to generalize to new data. Adding dropout in PyTorch is straightforward using the [`nn.Dropout`](https://pytorch.org/docs/stable/nn.html#torch.nn.Dropout) module.\n\n```python\nclass Classifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(784, 256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 10)\n \n # Dropout module with 0.2 drop probability\n self.dropout = nn.Dropout(p=0.2)\n \n def forward(self, x):\n # make sure input tensor is flattened\n x = x.view(x.shape[0], -1)\n \n # Now with dropout\n x = self.dropout(F.relu(self.fc1(x)))\n x = self.dropout(F.relu(self.fc2(x)))\n x = self.dropout(F.relu(self.fc3(x)))\n \n # output so no dropout here\n x = F.log_softmax(self.fc4(x), dim=1)\n \n return x\n```\n\nDuring training we want to use dropout to prevent overfitting, but during inference we want to use the entire network. So, we need to turn off dropout during validation, testing, and whenever we're using the network to make predictions. To do this, you use `model.eval()`. This sets the model to evaluation mode where the dropout probability is 0. You can turn dropout back on by setting the model to train mode with `model.train()`. In general, the pattern for the validation loop will look like this, where you turn off gradients, set the model to evaluation mode, calculate the validation loss and metric, then set the model back to train mode.\n\n```python\n# turn off gradients\nwith torch.no_grad():\n \n # set model to evaluation mode\n model.eval()\n \n # validation pass here\n for images, labels in testloader:\n ...\n\n# set model back to train mode\nmodel.train()\n```", "_____no_output_____" ], [ "> **Exercise:** Add dropout to your model and train it on Fashion-MNIST again. See if you can get a lower validation loss.", "_____no_output_____" ] ], [ [ "class Classifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(784, 256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 10)\n\n # Dropout module with 0.2 drop probability\n self.dropout = nn.Dropout(p=0.2)\n\n def forward(self, x):\n # make sure input tensor is flattened\n x = x.view(x.shape[0], -1)\n\n # Now with dropout\n x = self.dropout(F.relu(self.fc1(x)))\n x = self.dropout(F.relu(self.fc2(x)))\n x = self.dropout(F.relu(self.fc3(x)))\n\n # output so no dropout here\n x = F.log_softmax(self.fc4(x), dim=1)\n\n return x", "_____no_output_____" ], [ "model = Classifier()\ncriterion = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.003)\n\nepochs = 30\nsteps = 0\n\ntrain_losses, test_losses = [], []\nfor e in range(epochs):\n running_loss = 0\n for images, labels in trainloader:\n \n optimizer.zero_grad()\n \n log_ps = model(images)\n loss = criterion(log_ps, labels)\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n \n else:\n test_loss = 0\n accuracy = 0\n \n # Turn off gradients for validation, saves memory and computations\n with torch.no_grad():\n model.eval()\n for images, labels in testloader:\n log_ps = model(images)\n test_loss += criterion(log_ps, labels)\n \n ps = torch.exp(log_ps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor))\n \n model.train()\n \n train_losses.append(running_loss/len(trainloader))\n test_losses.append(test_loss/len(testloader))\n\n print(\"Epoch: {}/{}.. \".format(e+1, epochs),\n \"Training Loss: {:.3f}.. \".format(running_loss/len(trainloader)),\n \"Test Loss: {:.3f}.. \".format(test_loss/len(testloader)),\n \"Test Accuracy: {:.3f}\".format(accuracy/len(testloader)))", "_____no_output_____" ], [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "plt.plot(train_losses, label='Training loss')\nplt.plot(test_losses, label='Validation loss')\nplt.legend(frameon=False)", "_____no_output_____" ] ], [ [ "## Inference\n\nNow that the model is trained, we can use it for inference. We've done this before, but now we need to remember to set the model in inference mode with `model.eval()`. You'll also want to turn off autograd with the `torch.no_grad()` context.", "_____no_output_____" ] ], [ [ "# Import helper module (should be in the repo)\nimport helper\n\n# Test out your network!\n\nmodel.eval()\n\ndataiter = iter(testloader)\nimages, labels = dataiter.next()\nimg = images[0]\n# Convert 2D image to 1D vector\nimg = img.view(1, 784)\n\n# Calculate the class probabilities (softmax) for img\nwith torch.no_grad():\n output = model.forward(img)\n\nps = torch.exp(output)\n\n# Plot the image and probabilities\nhelper.view_classify(img.view(1, 28, 28), ps, version='Fashion')", "_____no_output_____" ] ], [ [ "## Next Up!\n\nIn the next part, I'll show you how to save your trained models. In general, you won't want to train a model everytime you need it. Instead, you'll train once, save it, then load the model when you want to train more or use if for inference.", "_____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" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec517a3358c34f626f97f7d25373fd6c8db52488
466,710
ipynb
Jupyter Notebook
paralell.ipynb
reula/PIC-1D
84ba65cf0b4e603820e69aca47d321c4620ab2be
[ "CC0-1.0" ]
null
null
null
paralell.ipynb
reula/PIC-1D
84ba65cf0b4e603820e69aca47d321c4620ab2be
[ "CC0-1.0" ]
null
null
null
paralell.ipynb
reula/PIC-1D
84ba65cf0b4e603820e69aca47d321c4620ab2be
[ "CC0-1.0" ]
null
null
null
306.642576
34,422
0.72611
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ec518a174331c7236d2d421428dd7a79566649f7
26,989
ipynb
Jupyter Notebook
module2/assignment_kaggle_challenge_2.ipynb
Nckflannery/DS-Unit-2-Kaggle-Challenge
504d1e9b62de339fa359e69eecff8209411836bd
[ "MIT" ]
null
null
null
module2/assignment_kaggle_challenge_2.ipynb
Nckflannery/DS-Unit-2-Kaggle-Challenge
504d1e9b62de339fa359e69eecff8209411836bd
[ "MIT" ]
null
null
null
module2/assignment_kaggle_challenge_2.ipynb
Nckflannery/DS-Unit-2-Kaggle-Challenge
504d1e9b62de339fa359e69eecff8209411836bd
[ "MIT" ]
null
null
null
38.889049
316
0.537775
[ [ [ "<a href=\"https://colab.research.google.com/github/Nckflannery/DS-Unit-2-Kaggle-Challenge/blob/master/module2/assignment_kaggle_challenge_2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "Lambda School Data Science, Unit 2: Predictive Modeling\n\n# Kaggle Challenge, Module 2\n\n## Assignment\n- [ ] Read [“Adopting a Hypothesis-Driven Workflow”](https://outline.com/5S5tsB), a blog post by a Lambda DS student about the Tanzania Waterpumps challenge.\n- [ ] Continue to participate in our Kaggle challenge.\n- [ ] Try Ordinal Encoding.\n- [ ] Try a Random Forest Classifier.\n- [ ] Submit your predictions to our Kaggle competition. (Go to our Kaggle InClass competition webpage. Use the blue **Submit Predictions** button to upload your CSV file. Or you can use the Kaggle API to submit your predictions.)\n- [ ] Commit your notebook to your fork of the GitHub repo.\n\n## Stretch Goals\n\n### Doing\n- [ ] Add your own stretch goal(s) !\n- [ ] Do more exploratory data analysis, data cleaning, feature engineering, and feature selection.\n- [ ] Try other [categorical encodings](https://contrib.scikit-learn.org/categorical-encoding/).\n- [ ] Get and plot your feature importances.\n- [ ] Make visualizations and share on Slack.\n\n### Reading\n\nTop recommendations in _**bold italic:**_\n\n#### Decision Trees\n- A Visual Introduction to Machine Learning, [Part 1: A Decision Tree](http://www.r2d3.us/visual-intro-to-machine-learning-part-1/), and _**[Part 2: Bias and Variance](http://www.r2d3.us/visual-intro-to-machine-learning-part-2/)**_\n- [Decision Trees: Advantages & Disadvantages](https://christophm.github.io/interpretable-ml-book/tree.html#advantages-2)\n- [How a Russian mathematician constructed a decision tree — by hand — to solve a medical problem](http://fastml.com/how-a-russian-mathematician-constructed-a-decision-tree-by-hand-to-solve-a-medical-problem/)\n- [How decision trees work](https://brohrer.github.io/how_decision_trees_work.html)\n- [Let’s Write a Decision Tree Classifier from Scratch](https://www.youtube.com/watch?v=LDRbO9a6XPU)\n\n#### Random Forests\n- [_An Introduction to Statistical Learning_](http://www-bcf.usc.edu/~gareth/ISL/), Chapter 8: Tree-Based Methods\n- [Coloring with Random Forests](http://structuringtheunstructured.blogspot.com/2017/11/coloring-with-random-forests.html)\n- _**[Random Forests for Complete Beginners: The definitive guide to Random Forests and Decision Trees](https://victorzhou.com/blog/intro-to-random-forests/)**_\n\n#### Categorical encoding for trees\n- [Are categorical variables getting lost in your random forests?](https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/)\n- [Beyond One-Hot: An Exploration of Categorical Variables](http://www.willmcginnis.com/2015/11/29/beyond-one-hot-an-exploration-of-categorical-variables/)\n- _**[Categorical Features and Encoding in Decision Trees](https://medium.com/data-design/visiting-categorical-features-and-encoding-in-decision-trees-53400fa65931)**_\n- _**[Coursera — How to Win a Data Science Competition: Learn from Top Kagglers — Concept of mean encoding](https://www.coursera.org/lecture/competitive-data-science/concept-of-mean-encoding-b5Gxv)**_\n- [Mean (likelihood) encodings: a comprehensive study](https://www.kaggle.com/vprokopev/mean-likelihood-encodings-a-comprehensive-study)\n- [The Mechanics of Machine Learning, Chapter 6: Categorically Speaking](https://mlbook.explained.ai/catvars.html)\n\n#### Imposter Syndrome\n- [Effort Shock and Reward Shock (How The Karate Kid Ruined The Modern World)](http://www.tempobook.com/2014/07/09/effort-shock-and-reward-shock/)\n- [How to manage impostor syndrome in data science](https://towardsdatascience.com/how-to-manage-impostor-syndrome-in-data-science-ad814809f068)\n- [\"I am not a real data scientist\"](https://brohrer.github.io/imposter_syndrome.html)\n- _**[Imposter Syndrome in Data Science](https://caitlinhudon.com/2018/01/19/imposter-syndrome-in-data-science/)**_\n\n\n### More Categorical Encodings\n\n**1.** The article **[Categorical Features and Encoding in Decision Trees](https://medium.com/data-design/visiting-categorical-features-and-encoding-in-decision-trees-53400fa65931)** mentions 4 encodings:\n\n- **\"Categorical Encoding\":** This means using the raw categorical values as-is, not encoded. Scikit-learn doesn't support this, but some tree algorithm implementations do. For example, [Catboost](https://catboost.ai/), or R's [rpart](https://cran.r-project.org/web/packages/rpart/index.html) package.\n- **Numeric Encoding:** Synonymous with Label Encoding, or \"Ordinal\" Encoding with random order. We can use [category_encoders.OrdinalEncoder](https://contrib.scikit-learn.org/categorical-encoding/ordinal.html).\n- **One-Hot Encoding:** We can use [category_encoders.OneHotEncoder](http://contrib.scikit-learn.org/categorical-encoding/onehot.html).\n- **Binary Encoding:** We can use [category_encoders.BinaryEncoder](http://contrib.scikit-learn.org/categorical-encoding/binary.html).\n\n\n**2.** The short video \n**[Coursera — How to Win a Data Science Competition: Learn from Top Kagglers — Concept of mean encoding](https://www.coursera.org/lecture/competitive-data-science/concept-of-mean-encoding-b5Gxv)** introduces an interesting idea: use both X _and_ y to encode categoricals.\n\nCategory Encoders has multiple implementations of this general concept:\n\n- [CatBoost Encoder](http://contrib.scikit-learn.org/categorical-encoding/catboost.html)\n- [James-Stein Encoder](http://contrib.scikit-learn.org/categorical-encoding/jamesstein.html)\n- [Leave One Out](http://contrib.scikit-learn.org/categorical-encoding/leaveoneout.html)\n- [M-estimate](http://contrib.scikit-learn.org/categorical-encoding/mestimate.html)\n- [Target Encoder](http://contrib.scikit-learn.org/categorical-encoding/targetencoder.html)\n- [Weight of Evidence](http://contrib.scikit-learn.org/categorical-encoding/woe.html)\n\nCategory Encoder's mean encoding implementations work for regression problems or binary classification problems. \n\nFor multi-class classification problems, you will need to temporarily reformulate it as binary classification. For example:\n\n```python\nencoder = ce.TargetEncoder(min_samples_leaf=..., smoothing=...) # Both parameters > 1 to avoid overfitting\nX_train_encoded = encoder.fit_transform(X_train, y_train=='functional')\nX_val_encoded = encoder.transform(X_train, y_val=='functional')\n```\n\nFor this reason, mean encoding won't work well within pipelines for multi-class classification problems.\n\n**3.** The **[dirty_cat](https://dirty-cat.github.io/stable/)** library has a Target Encoder implementation that works with multi-class classification.\n\n```python\n dirty_cat.TargetEncoder(clf_type='multiclass-clf')\n```\nIt also implements an interesting idea called [\"Similarity Encoder\" for dirty categories](https://www.slideshare.net/GaelVaroquaux/machine-learning-on-non-curated-data-154905090).\n\nHowever, it seems like dirty_cat doesn't handle missing values or unknown categories as well as category_encoders does. And you may need to use it with one column at a time, instead of with your whole dataframe.\n\n**4. [Embeddings](https://www.kaggle.com/learn/embeddings)** can work well with sparse / high cardinality categoricals.\n\n_**I hope it’s not too frustrating or confusing that there’s not one “canonical” way to encode categorcals. It’s an active area of research and experimentation! Maybe you can make your own contributions!**_", "_____no_output_____" ], [ "### Setup\n\nYou can work locally (follow the [local setup instructions](https://lambdaschool.github.io/ds/unit2/local/)) or on Colab (run the code cell below).", "_____no_output_____" ] ], [ [ "%%capture\nimport sys\n\n# If you're on Colab:\nif 'google.colab' in sys.modules:\n DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge/master/data/'\n !pip install category_encoders==2.*\n\n# If you're working locally:\nelse:\n DATA_PATH = '../data/'", "_____no_output_____" ], [ "import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\ntrain = pd.merge(pd.read_csv(DATA_PATH+'waterpumps/train_features.csv'), \n pd.read_csv(DATA_PATH+'waterpumps/train_labels.csv'))\ntest = pd.read_csv(DATA_PATH+'waterpumps/test_features.csv')\nsample_submission = pd.read_csv(DATA_PATH+'waterpumps/sample_submission.csv')\n\ntrain.shape, test.shape", "_____no_output_____" ], [ "from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.impute import SimpleImputer\nimport category_encoders as ce\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nimport numpy as np", "_____no_output_____" ], [ "def wrangler(dataframe):\n\n x = dataframe.copy()\n \n # New Feature\n x['date_recorded_year'] = x['date_recorded'].str[:4].astype(int)\n x['years_before_service'] = x['date_recorded_year'] - x['construction_year']\n x.loc[(x['years_before_service']<0) | (x['years_before_service']>100), 'years_before_service'] = np.nan\n\n # Replace None, none, 0 with NaN values, and fix long/lat columns\n features_replace = ['scheme_name', 'installer', 'funder', 'wpt_name', 'longitude', 'latitude', 'population', 'years_before_service', 'amount_tsh', 'gps_height','num_private']\n x[features_replace] = x[features_replace].replace({'None':np.nan, 'none':np.nan, '0':np.nan, 0:np.nan, -2e-8:np.nan})\n for i in features_replace:\n x[i+'_MISSING'] = x[i].isnull()\n \n # Drop id\n drops = ['id', 'recorded_by']\n x = x.drop(drops, axis=1)\n\n return x", "_____no_output_____" ], [ "my_train, my_val = train_test_split(train, random_state=42)", "_____no_output_____" ], [ "my_train = wrangler(my_train)\nmy_val = wrangler(my_val)", "_____no_output_____" ], [ "target = 'status_group'\n\nX_train = my_train.drop(target, axis=1)\nX_val = my_val.drop(target, axis=1)\ny_train = my_train[target]\ny_val = my_val[target]", "_____no_output_____" ], [ "%%time\npipe = make_pipeline(\n ce.OrdinalEncoder(),\n SimpleImputer(strategy='median'),\n StandardScaler(),\n RandomForestClassifier(n_estimators=400, n_jobs=-1, random_state=42)\n)\npipe.fit(X_train, y_train)", "CPU times: user 1min 11s, sys: 1.76 s, total: 1min 12s\nWall time: 38.4 s\n" ], [ "print(f'Training Accuracy: {pipe.score(X_train, y_train)}')\nprint(f'Validation Accuracy: {pipe.score(X_val, y_val)}')", "Training Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8081481481481482\n" ], [ "X_test = wrangler(test)", "_____no_output_____" ], [ "y_pred = pipe.predict(X_test)\nsubmission = sample_submission.copy()\nsubmission['status_group'] = y_pred\nsubmission.to_csv('againagain.csv', index=False)", "_____no_output_____" ], [ "for i in [10,20,50,100,200,300,400,500,600,1000,2000]:\n for j in ['mean', 'median', 'most_frequent']:\n pipe = make_pipeline(\n ce.OrdinalEncoder(),\n SimpleImputer(strategy=j),\n StandardScaler(),\n RandomForestClassifier(n_estimators=i, n_jobs=-1, random_state=42)\n )\n pipe.fit(X_train, y_train)\n print(f'n_estimators: {i}')\n print(f'Strategy: {j}')\n print(f'Training Accuracy: {pipe.score(X_train, y_train)}')\n print(f'Validation Accuracy: {pipe.score(X_val, y_val)}')\n print('\\n')", "n_estimators: 10\nStrategy: mean\nTraining Accuracy: 0.9857912457912458\nValidation Accuracy: 0.7897643097643098\n\n\nn_estimators: 10\nStrategy: median\nTraining Accuracy: 0.9853872053872054\nValidation Accuracy: 0.7898989898989899\n\n\nn_estimators: 10\nStrategy: most_frequent\nTraining Accuracy: 0.9858361391694725\nValidation Accuracy: 0.7891582491582492\n\n\nn_estimators: 20\nStrategy: mean\nTraining Accuracy: 0.9959595959595959\nValidation Accuracy: 0.7975084175084175\n\n\nn_estimators: 20\nStrategy: median\nTraining Accuracy: 0.995645342312009\nValidation Accuracy: 0.7975084175084175\n\n\nn_estimators: 20\nStrategy: most_frequent\nTraining Accuracy: 0.9959147025813693\nValidation Accuracy: 0.7967003367003367\n\n\nn_estimators: 50\nStrategy: mean\nTraining Accuracy: 0.9994837261503928\nValidation Accuracy: 0.8032323232323232\n\n\nn_estimators: 50\nStrategy: median\nTraining Accuracy: 0.9995061728395062\nValidation Accuracy: 0.8037037037037037\n\n\nn_estimators: 50\nStrategy: most_frequent\nTraining Accuracy: 0.9995510662177329\nValidation Accuracy: 0.8036363636363636\n\n\nn_estimators: 100\nStrategy: mean\nTraining Accuracy: 0.9999551066217733\nValidation Accuracy: 0.8045117845117845\n\n\nn_estimators: 100\nStrategy: median\nTraining Accuracy: 0.9999551066217733\nValidation Accuracy: 0.8053872053872054\n\n\nn_estimators: 100\nStrategy: most_frequent\nTraining Accuracy: 0.9999326599326599\nValidation Accuracy: 0.8045791245791246\n\n\nn_estimators: 200\nStrategy: mean\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8058585858585858\n\n\nn_estimators: 200\nStrategy: median\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8062626262626262\n\n\nn_estimators: 200\nStrategy: most_frequent\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8043771043771044\n\n\nn_estimators: 300\nStrategy: mean\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8061952861952862\n\n\nn_estimators: 300\nStrategy: median\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8071380471380472\n\n\nn_estimators: 300\nStrategy: most_frequent\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.805993265993266\n\n\nn_estimators: 400\nStrategy: mean\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8063299663299663\n\n\nn_estimators: 400\nStrategy: median\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8068686868686868\n\n\nn_estimators: 400\nStrategy: most_frequent\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.805050505050505\n\n\nn_estimators: 500\nStrategy: mean\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8061279461279461\n\n\nn_estimators: 500\nStrategy: median\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8063973063973064\n\n\nn_estimators: 500\nStrategy: most_frequent\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.806060606060606\n\n\nn_estimators: 600\nStrategy: mean\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8063299663299663\n\n\nn_estimators: 600\nStrategy: median\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8062626262626262\n\n\nn_estimators: 600\nStrategy: most_frequent\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.804983164983165\n\n\nn_estimators: 1000\nStrategy: mean\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8074074074074075\n\n\nn_estimators: 1000\nStrategy: median\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.807070707070707\n\n\nn_estimators: 1000\nStrategy: most_frequent\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8061952861952862\n\n\nn_estimators: 2000\nStrategy: mean\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8061952861952862\n\n\nn_estimators: 2000\nStrategy: median\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.8057239057239057\n\n\nn_estimators: 2000\nStrategy: most_frequent\nTraining Accuracy: 0.9999775533108867\nValidation Accuracy: 0.805993265993266\n\n\n" ], [ "piper = make_pipeline(\n ce.OrdinalEncoder(),\n SimpleImputer(strategy='mean'),\n StandardScaler(),\n RandomForestClassifier(n_estimators=1000, n_jobs=-1, random_state=42)\n)\npiper.fit(X_train, y_train)\npiper.score(X_val, y_val)", "_____no_output_____" ], [ "y_pred1 = piper.predict(X_test)\nsubmission1 = sample_submission.copy()\nsubmission1['status_group'] = y_pred1\nsubmission1.to_csv('again2.csv', index=False)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec51938e057bfadffbd3c4bda4879b5c7fba0d4f
31,995
ipynb
Jupyter Notebook
homework1_Final.ipynb
Leozyc-waseda/DeepLearning_Course_Homework
f12d6fa5c230521c7023eb8ad4e62f525630c5ce
[ "MIT" ]
null
null
null
homework1_Final.ipynb
Leozyc-waseda/DeepLearning_Course_Homework
f12d6fa5c230521c7023eb8ad4e62f525630c5ce
[ "MIT" ]
null
null
null
homework1_Final.ipynb
Leozyc-waseda/DeepLearning_Course_Homework
f12d6fa5c230521c7023eb8ad4e62f525630c5ce
[ "MIT" ]
null
null
null
54.137056
12,688
0.69714
[ [ [ "# コンペティション課題1", "_____no_output_____" ], [ "## 目標値\n\nMSE (値は0以上で、小さいほどよい): 0.75未満 \n(これはあくまで「目標値」であるため、達成できなかったからといって不合格となったり、著しく成績が損なわれることはありません)", "_____no_output_____" ], [ "## ルール\n\n- 「修正しないでください」とあるセルを、修正しないでください。\n- モデルはニューラルネットに限定します。その他のモデルは使用しないでください。\n- 訓練データはtrain.csv、テストデータはtest.csvによって与えられます。\n- 以下のセルで定義されているx_train, t_train以外の学習データは使わないでください。", "_____no_output_____" ], [ "## 提出方法\n- 1つのファイルを提出していただきます。\n 1. テストデータに対する予測ラベルを`submission1_pred.csv`として保存・ダウンロードしてください。\n 2. 得られたCSVファイルを、Homeworkタブから**Day1 Pred (.csv)**を選択して提出してください。\n 3. それとは別に、最終提出に対応するノートブックをわかるようにiLect上に置いておいてください。\n\n\n- 成績優秀者には、次回講義にて取り組みの発表をお願いいたします。", "_____no_output_____" ], [ "## 評価方法\n\n- 予測ラベルに対するMSEで評価します。\n- MSEは0以上で、小さいほど良いです。\n\n## LeaderBoard\n\n- コンペティション期間中のLeaderBoardは提出されたcsvファイルのうち50%を使って計算されます。コンペティション終了時には提出されたcsvファイルのうち、コンペティション期間中のLeaderBoard計算に使われなかったもう半分のデータがスコア計算に使用されます。\n- このため、コンペ中の順位とコンペ終了後にLeaderBoardが更新された後の順位やスコアが食い違うことがあります。", "_____no_output_____" ], [ "## データの読み込み\n\n- このセルは修正しないでください。\n- 誤って修正した場合は、元ファイルをコピーし直してください。", "_____no_output_____" ] ], [ [ "from IPython.display import clear_output\n\n!pip install torchvision==0.6.1\nclear_output()\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport seaborn as sns\n%matplotlib inline\n\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\n\n\nDATA_PATH = '/root/userspace/public/day1/homework1/data/'\n\ntrain = pd.read_csv(DATA_PATH + 'train.csv')\ntrain = train.fillna(train.median()).values\nx_train = train[:, :-1]\nt_train = train[:, -1]\n\nx_test = pd.read_csv(DATA_PATH + 'test.csv')\nx_test = x_test.fillna(x_test.median()).values\n\nx_train, x_valid, t_train, t_valid = \\\n train_test_split(x_train, t_train, test_size=0.2, random_state=42)\n\n\nscaler = MinMaxScaler()\nx_train = scaler.fit_transform(x_train)\nx_valid = scaler.transform(x_valid)\nx_test = scaler.transform(x_test)\n\n\nclass TrainDataset(torch.utils.data.Dataset):\n \n def __init__(self, x_train, t_train):\n self.x_train = x_train\n self.t_train = t_train\n \n def __len__(self):\n return len(self.x_train)\n \n def __getitem__(self, idx):\n return torch.tensor(self.x_train[idx], dtype=torch.float), \\\n torch.tensor(self.t_train[idx], dtype=torch.float)\n\n \nclass TestDataset(torch.utils.data.Dataset):\n \n def __init__(self, x_test):\n self.x_test = x_test\n \n def __len__(self):\n return len(self.x_test)\n \n def __getitem__(self, idx):\n return torch.tensor(self.x_test[idx], dtype=torch.float)\n\n\ntrain_dataset = TrainDataset(x_train, t_train)\nvalid_dataset = TrainDataset(x_valid, t_valid)\ntest_dataset = TestDataset(x_test)", "_____no_output_____" ] ], [ [ "## ニューラルネットによる赤ワイン品質の回帰", "_____no_output_____" ] ], [ [ "DEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n# 精度向上ポイント: バッチサイズの大小\nBATCH_SIZE = 32\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset, \n batch_size=BATCH_SIZE,\n shuffle=True)\nvalid_loader = torch.utils.data.DataLoader(dataset=valid_dataset, \n batch_size=BATCH_SIZE)\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset, \n batch_size=BATCH_SIZE)\n\n# ニューラルネットの定義\n# 精度向上ポイント: 中間層の数・ユニット数の大小、活性化関数の選択\n# 精度向上ポイント(発展): ドロップアウト層・バッチノーマリゼーションの使用\nclass MLP(nn.Module):\n def __init__(self, num_features):\n super().__init__()\n self.layer_1 = nn.Linear(num_features, 256) # 入力層\n self.layer_2 = nn.Linear(256, 512) # 中間層\n self.layer_3 = nn.Linear(512, 256) # 中間層\n self.layer_out = nn.Linear(256, 1) # 出力層\n \n \n self.dropout1 = nn.Dropout(p=0.3)\n self.dropout2 = nn.Dropout(p=0.3)\n self.dropout3 = nn.Dropout(p=0.3)\n self.batchnorm1 = nn.BatchNorm1d(256)\n self.batchnorm2 = nn.BatchNorm1d(512)\n self.batchnorm3 = nn.BatchNorm1d(256)\n \n def forward(self, inputs): \n x = F.relu(self.dropout1((self.layer_1(inputs))))\n x = F.relu(self.dropout2(self.batchnorm2(self.layer_2(x))))\n \n x = torch.sigmoid(self.batchnorm3(self.layer_3(x)))\n x = self.dropout3(x)\n# x = F.relu(self.dropout3(self.batchnorm3(self.layer_3(x))))\n \n x = self.layer_out(x)\n return x\n\nprint(MLP)\n\nNUM_FEATURES = 11\nmlp = MLP(NUM_FEATURES)\nmlp.to(DEVICE)\n# 損失関数の定義\nloss_fn = nn.MSELoss()\n\n # オプティマイザの定義\n # 精度向上ポイント: 学習率の選択、オプティマイザの選択\n # 精度向上ポイント(発展): weight decayの大小、スケジューラの使用\nLEARNING_RATE = 1e-3\noptimizer = torch.optim.Adam(mlp.parameters(), lr=LEARNING_RATE,weight_decay=1e-6)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer,step_size=30,gamma=0.6)\n\n # 学習の実行\n # 精度向上ポイント: エポック数の大小\nNUM_EPOCHS =75\n#75 best \nloss_stats = {'train': [], 'valid': []}\nloss_stats = {'train': [], 'valid': []}\nfor e in range(1, NUM_EPOCHS+1):\n \n # 訓練\n train_epoch_loss = 0\n mlp.train()\n for x, t in train_loader:\n x, t = x.to(DEVICE), t.unsqueeze(1).to(DEVICE)\n optimizer.zero_grad() # 勾配の初期化\n pred = mlp(x) # 予測の計算(順伝播)\n loss = loss_fn(pred, t) # 損失関数の計算\n loss.backward() # 勾配の計算(逆伝播)\n optimizer.step() # 重みの更新\n train_epoch_loss += loss.item()\n scheduler.step()\n # 検証 \n with torch.no_grad():\n valid_epoch_loss = 0\n mlp.eval()\n for x, t in valid_loader:\n x, t = x.to(DEVICE), t.unsqueeze(1).to(DEVICE)\n pred = mlp(x) # 予測の計算(順伝播)\n loss = loss_fn(pred, t) # 損失関数の計算\n valid_epoch_loss += loss.item()\n \n loss_stats['train'].append(train_epoch_loss/len(train_loader))\n loss_stats['valid'].append(valid_epoch_loss/len(valid_loader)) \n \n print(f'Epoch {e+0:03}: | Train Loss: {train_epoch_loss/len(train_loader):.5f} \\\n| Val Loss: {valid_epoch_loss/len(valid_loader):.5f}')\n print('\\n learning rate ',optimizer.param_groups[0]['lr'])\n \n\n# 学習曲線の描画\ndf_loss = pd.DataFrame.from_dict(loss_stats).reset_index()\ndf_loss = df_loss.melt(id_vars=['index']).rename(columns={\"index\": \"epochs\"})\nsns.lineplot(data=df_loss, x=\"epochs\", y=\"value\", hue=\"variable\")\nplt.gca().get_xaxis().set_major_locator(ticker.MaxNLocator(integer=True))\n\n\n# 推論の実行\nmlp.eval()\npreds = []\nfor x in test_loader:\n x = x.to(DEVICE)\n pred = mlp(x)\n pred = pred.squeeze()\n preds.extend(pred.tolist())\n\nsubmission = pd.Series(preds, name='quality')\nsubmission.to_csv('/root/userspace/submission1_pred.csv', \n header=True, index_label='id')", "<class '__main__.MLP'>\nEpoch 001: | Train Loss: 12.33593 | Val Loss: 2.52964\n\n learning rate 0.001\nEpoch 002: | Train Loss: 1.32969 | Val Loss: 0.89618\n\n learning rate 0.001\nEpoch 003: | Train Loss: 0.93596 | Val Loss: 0.80768\n\n learning rate 0.001\nEpoch 004: | Train Loss: 0.93716 | Val Loss: 0.84817\n\n learning rate 0.001\nEpoch 005: | Train Loss: 0.90976 | Val Loss: 0.84713\n\n learning rate 0.001\nEpoch 006: | Train Loss: 0.88325 | Val Loss: 0.80585\n\n learning rate 0.001\nEpoch 007: | Train Loss: 0.88394 | Val Loss: 0.85549\n\n learning rate 0.001\nEpoch 008: | Train Loss: 0.84205 | Val Loss: 0.80709\n\n learning rate 0.001\nEpoch 009: | Train Loss: 0.85977 | Val Loss: 0.79069\n\n learning rate 0.001\nEpoch 010: | Train Loss: 0.82688 | Val Loss: 0.83141\n\n learning rate 0.001\nEpoch 011: | Train Loss: 0.91728 | Val Loss: 0.78703\n\n learning rate 0.001\nEpoch 012: | Train Loss: 0.86400 | Val Loss: 0.79910\n\n learning rate 0.001\nEpoch 013: | Train Loss: 0.86151 | Val Loss: 0.82129\n\n learning rate 0.001\nEpoch 014: | Train Loss: 0.83624 | Val Loss: 0.79338\n\n learning rate 0.001\nEpoch 015: | Train Loss: 0.85667 | Val Loss: 0.77446\n\n learning rate 0.001\nEpoch 016: | Train Loss: 0.82160 | Val Loss: 0.78596\n\n learning rate 0.001\nEpoch 017: | Train Loss: 0.82975 | Val Loss: 0.78676\n\n learning rate 0.001\nEpoch 018: | Train Loss: 0.79946 | Val Loss: 0.77673\n\n learning rate 0.001\nEpoch 019: | Train Loss: 0.81992 | Val Loss: 0.79001\n\n learning rate 0.001\nEpoch 020: | Train Loss: 0.79371 | Val Loss: 0.77100\n\n learning rate 0.001\nEpoch 021: | Train Loss: 0.79477 | Val Loss: 0.77201\n\n learning rate 0.001\nEpoch 022: | Train Loss: 0.80845 | Val Loss: 0.78814\n\n learning rate 0.001\nEpoch 023: | Train Loss: 0.79972 | Val Loss: 0.76355\n\n learning rate 0.001\nEpoch 024: | Train Loss: 0.82327 | Val Loss: 0.76836\n\n learning rate 0.001\nEpoch 025: | Train Loss: 0.81535 | Val Loss: 0.77287\n\n learning rate 0.001\nEpoch 026: | Train Loss: 0.78036 | Val Loss: 0.76549\n\n learning rate 0.001\nEpoch 027: | Train Loss: 0.76049 | Val Loss: 0.76483\n\n learning rate 0.001\nEpoch 028: | Train Loss: 0.78303 | Val Loss: 0.76618\n\n learning rate 0.001\nEpoch 029: | Train Loss: 0.81190 | Val Loss: 0.76643\n\n learning rate 0.001\nEpoch 030: | Train Loss: 0.77849 | Val Loss: 0.76323\n\n learning rate 0.0006\nEpoch 031: | Train Loss: 0.77244 | Val Loss: 0.77662\n\n learning rate 0.0006\nEpoch 032: | Train Loss: 0.73281 | Val Loss: 0.76853\n\n learning rate 0.0006\nEpoch 033: | Train Loss: 0.74223 | Val Loss: 0.76890\n\n learning rate 0.0006\nEpoch 034: | Train Loss: 0.74570 | Val Loss: 0.76662\n\n learning rate 0.0006\nEpoch 035: | Train Loss: 0.74716 | Val Loss: 0.77288\n\n learning rate 0.0006\nEpoch 036: | Train Loss: 0.72788 | Val Loss: 0.76822\n\n learning rate 0.0006\nEpoch 037: | Train Loss: 0.73619 | Val Loss: 0.76520\n\n learning rate 0.0006\nEpoch 038: | Train Loss: 0.74644 | Val Loss: 0.76749\n\n learning rate 0.0006\nEpoch 039: | Train Loss: 0.74781 | Val Loss: 0.76258\n\n learning rate 0.0006\nEpoch 040: | Train Loss: 0.73137 | Val Loss: 0.75878\n\n learning rate 0.0006\nEpoch 041: | Train Loss: 0.74417 | Val Loss: 0.76187\n\n learning rate 0.0006\nEpoch 042: | Train Loss: 0.74187 | Val Loss: 0.76017\n\n learning rate 0.0006\nEpoch 043: | Train Loss: 0.74234 | Val Loss: 0.76349\n\n learning rate 0.0006\nEpoch 044: | Train Loss: 0.74557 | Val Loss: 0.75980\n\n learning rate 0.0006\nEpoch 045: | Train Loss: 0.70663 | Val Loss: 0.76216\n\n learning rate 0.0006\nEpoch 046: | Train Loss: 0.72486 | Val Loss: 0.77495\n\n learning rate 0.0006\nEpoch 047: | Train Loss: 0.71233 | Val Loss: 0.75774\n\n learning rate 0.0006\nEpoch 048: | Train Loss: 0.70435 | Val Loss: 0.75945\n\n learning rate 0.0006\nEpoch 049: | Train Loss: 0.70843 | Val Loss: 0.75437\n\n learning rate 0.0006\nEpoch 050: | Train Loss: 0.72349 | Val Loss: 0.75828\n\n learning rate 0.0006\nEpoch 051: | Train Loss: 0.74871 | Val Loss: 0.76189\n\n learning rate 0.0006\nEpoch 052: | Train Loss: 0.69732 | Val Loss: 0.77540\n\n learning rate 0.0006\nEpoch 053: | Train Loss: 0.72274 | Val Loss: 0.76758\n\n learning rate 0.0006\nEpoch 054: | Train Loss: 0.70963 | Val Loss: 0.77475\n\n learning rate 0.0006\nEpoch 055: | Train Loss: 0.71171 | Val Loss: 0.75511\n\n learning rate 0.0006\nEpoch 056: | Train Loss: 0.71407 | Val Loss: 0.75811\n\n learning rate 0.0006\nEpoch 057: | Train Loss: 0.68927 | Val Loss: 0.76218\n\n learning rate 0.0006\nEpoch 058: | Train Loss: 0.70323 | Val Loss: 0.75412\n\n learning rate 0.0006\nEpoch 059: | Train Loss: 0.70405 | Val Loss: 0.75746\n\n learning rate 0.0006\nEpoch 060: | Train Loss: 0.72211 | Val Loss: 0.74606\n\n learning rate 0.00035999999999999997\nEpoch 061: | Train Loss: 0.68467 | Val Loss: 0.74706\n\n learning rate 0.00035999999999999997\nEpoch 062: | Train Loss: 0.68130 | Val Loss: 0.75319\n\n learning rate 0.00035999999999999997\nEpoch 063: | Train Loss: 0.67843 | Val Loss: 0.74970\n\n learning rate 0.00035999999999999997\nEpoch 064: | Train Loss: 0.69201 | Val Loss: 0.75504\n\n learning rate 0.00035999999999999997\nEpoch 065: | Train Loss: 0.67229 | Val Loss: 0.75234\n\n learning rate 0.00035999999999999997\nEpoch 066: | Train Loss: 0.67110 | Val Loss: 0.74857\n\n learning rate 0.00035999999999999997\nEpoch 067: | Train Loss: 0.70345 | Val Loss: 0.75137\n\n learning rate 0.00035999999999999997\nEpoch 068: | Train Loss: 0.68448 | Val Loss: 0.75447\n\n learning rate 0.00035999999999999997\nEpoch 069: | Train Loss: 0.66117 | Val Loss: 0.74661\n\n learning rate 0.00035999999999999997\nEpoch 070: | Train Loss: 0.68968 | Val Loss: 0.74989\n\n learning rate 0.00035999999999999997\nEpoch 071: | Train Loss: 0.66805 | Val Loss: 0.75032\n\n learning rate 0.00035999999999999997\nEpoch 072: | Train Loss: 0.66054 | Val Loss: 0.75091\n\n learning rate 0.00035999999999999997\nEpoch 073: | Train Loss: 0.66484 | Val Loss: 0.74506\n\n learning rate 0.00035999999999999997\nEpoch 074: | Train Loss: 0.68419 | Val Loss: 0.74593\n\n learning rate 0.00035999999999999997\nEpoch 075: | Train Loss: 0.66881 | Val Loss: 0.75153\n\n learning rate 0.00035999999999999997\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec5196494cb9aa8c6a9afc83e166a6e6ab737554
60,238
ipynb
Jupyter Notebook
Copy_of_KNN_Assignment13.ipynb
Sangee-28/TaskMongoDb
b392542ac9f0a2027ae6635f4c62ae28e4753b3d
[ "Apache-2.0" ]
null
null
null
Copy_of_KNN_Assignment13.ipynb
Sangee-28/TaskMongoDb
b392542ac9f0a2027ae6635f4c62ae28e4753b3d
[ "Apache-2.0" ]
null
null
null
Copy_of_KNN_Assignment13.ipynb
Sangee-28/TaskMongoDb
b392542ac9f0a2027ae6635f4c62ae28e4753b3d
[ "Apache-2.0" ]
null
null
null
78.028497
25,973
0.728527
[ [ [ "<a href=\"https://colab.research.google.com/github/Sangee-28/GuviTasks/blob/main/Copy_of_KNN_Assignment13.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "#Social_Networks_Ads.csv", "_____no_output_____" ] ], [ [ "**Importing the libraries**", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\n#from sklearn import datasets, neighbors\nfrom sklearn.linear_model import LogisticRegression\nfrom mlxtend.plotting import plot_decision_regions\nfrom sklearn.model_selection import cross_val_score # import all the functions reqd for cross validation\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "**Importing the dataset**", "_____no_output_____" ] ], [ [ "import io\nfrom google.colab import files\nuploaded = files.upload()\ndf = pd.read_csv(io.BytesIO(uploaded['Social_Network_Ads.csv']))", "_____no_output_____" ], [ "df.head()\ndf.isnull().sum()", "_____no_output_____" ] ], [ [ "**Splitting the dataset into the Training set and Test set**", "_____no_output_____" ] ], [ [ "X = df.iloc[:,2:4]\ny = df['Purchased']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.35, random_state=111) # split the data \nX_train", "_____no_output_____" ] ], [ [ "**Feature Scaling**", "_____no_output_____" ] ], [ [ "scaler = StandardScaler()\nscaler.fit(X_train) # compute mu and sigma\nX_train = scaler.transform(X_train)\n# wrong - never call scaler fit on test again - scaler.fit(X_test)\nX_test = scaler.transform(X_test)", "_____no_output_____" ] ], [ [ "**Fitting K-NN to the Training set**", "_____no_output_____" ] ], [ [ "from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\nfrom sklearn.metrics import roc_auc_score\nfor i in [1,2,3,4,5,6,7,8,9,10,20,50]:\n knn = KNeighborsClassifier(i) #initialising the model\n knn.fit(X_train,y_train) # training the model\n print(\"K value : \" , i, \" score : \", roc_auc_score(y_test, knn.predict_proba(X_test)[:,1])) #predicting using the model", "K value : 1 score : 0.80770887166236\nK value : 2 score : 0.8934108527131783\nK value : 3 score : 0.912575366063738\nK value : 4 score : 0.9191429801894918\nK value : 5 score : 0.9565030146425494\nK value : 6 score : 0.9667312661498708\nK value : 7 score : 0.9690999138673557\nK value : 8 score : 0.9688845822566752\nK value : 9 score : 0.9681309216192936\nK value : 10 score : 0.975452196382429\nK value : 20 score : 0.9810508182601205\nK value : 50 score : 0.9823428079242033\n" ], [ "\nfrom sklearn.model_selection import cross_val_score\ndata = pd.read_csv('Social_Network_Ads.csv')\nx = data[['Age','EstimatedSalary']].values\ny = data['Purchased'].astype(int).values\nfor k in [1,2,3,4,5,6,7,8,9,10,20,40,80]:\n clf = KNeighborsClassifier(n_neighbors=k)\n clf.fit(x,y)\n print(\"K value : \", k, \" train score : \", clf.score(x,y) , \" test score : \", cross_val_score(clf,x,y,cv = 10, scoring = 'accuracy').mean())", "K value : 1 train score : 0.995 test score : 0.8025\nK value : 2 train score : 0.9025 test score : 0.7875\nK value : 3 train score : 0.8975 test score : 0.7875000000000001\nK value : 4 train score : 0.8625 test score : 0.7925\nK value : 5 train score : 0.8725 test score : 0.7849999999999999\nK value : 6 train score : 0.8625 test score : 0.7825\nK value : 7 train score : 0.87 test score : 0.7949999999999999\nK value : 8 train score : 0.8475 test score : 0.785\nK value : 9 train score : 0.875 test score : 0.7849999999999999\nK value : 10 train score : 0.8475 test score : 0.76\nK value : 20 train score : 0.8175 test score : 0.7725\nK value : 40 train score : 0.8025 test score : 0.7775000000000001\nK value : 80 train score : 0.7725 test score : 0.7675000000000001\n" ], [ "#Input : k and data\n#Output : The graph of the decision boundary\ndef knn_comparison(data, k): #k and the data are input to the function\n x = data[['Age','EstimatedSalary']].values # independent features\n y = data['Purchased'].astype(int).values # y -> target/true labels \n clf = KNeighborsClassifier(n_neighbors=k) #it will initialise the model with @neighbours as k \n clf.fit(x, y) # train the model\n print(\"Train Accuracy : \", clf.score(x,y)) # test the model and it computes the accuracy (train data accuracy)\n print(\"Val Accuracy : \", np.mean(cross_val_score(clf, x, y, cv=10)))\n # Plotting decision region\n plot_decision_regions(x, y, clf=clf, legend=2) # it plots the decision boundary\n ##Adding axes annotations\n plt.xlabel('X') #Names the x-axis\n plt.ylabel('Y') #Names the y-axis\n plt.title('Knn with K='+ str(k)) #Names the graph\n plt.show() #Displays the graph \n\ndef knn_no_plot(data, k): #k and the data are input to the function\n x = data[['Age','EstimatedSalary']].values # independent features\n y = data['Purchased'].astype(int).values # y -> target/true labels \n clf = KNeighborsClassifier(n_neighbors=k) #it will initialise the model with @neighbours as k \n clf.fit(x, y) # train the model\n print(\"K : \", k, \" Train Accuracy : \", clf.score(x,y), \" Val Accuracy : \", np.mean(cross_val_score(clf, x, y, cv=5))) # test the model and it computes the accuracy (train data accuracy)\n # Plotting decision region\n # plot_decision_regions(x, y, clf=clf, legend=2) # it plots the decision boundary\n # # Adding axes annotations\n # plt.xlabel('X') #Names the x-axis\n # plt.ylabel('Y') #Names the y-axis\n # plt.title('Knn with K='+ str(k)) #Names the graph\n # plt.show() #Displays the graph \n\n#Same as aboe, but with logreg\ndef logistic(data, k = 0):\n x =data[['Age','EstimatedSalary']].values\n y = data['Purchased'].astype(int).values\n clf = LogisticRegression()\n clf.fit(x, y)\n print(clf.score(x,y))\n print(\"Train Accuracy : \", clf.score(x,y)) # test the model and it computes the accuracy (train data accuracy)\n print(\"Val Accuracy : \", np.mean(cross_val_score(clf, x, y, cv=5)))\n # Plotting decision region\n plot_decision_regions(x, y, clf=clf, legend=2)\n # Adding axes annotations\n plt.xlabel('X')\n plt.ylabel('Y')\n plt.title('Losgistic Regression decision boundary')\n plt.show()", "_____no_output_____" ], [ "logistic(data)", "0.6425\nTrain Accuracy : 0.6425\nVal Accuracy : 0.675\n" ] ], [ [ "**Predicting the Test set results**", "_____no_output_____" ] ], [ [ "knn.predict_proba(X_test)\nknn.predict(X_test)", "_____no_output_____" ] ], [ [ "**Making the Confusion Matrix**", "_____no_output_____" ] ], [ [ "cnf_matrix = confusion_matrix(y_test, knn.predict(X_test))\ncnf_matrix", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\nprint(accuracy_score(y_test, knn.predict(X_test)))", "0.8357142857142857\n" ], [ "from sklearn.metrics import precision_score\nprint(\"Precision: {0}\".format(precision_score(y_test, knn.predict(X_test))))", "Precision: 0.9696969696969697\n" ], [ "from sklearn.metrics import plot_roc_curve, roc_curve, roc_auc_score, confusion_matrix, f1_score\nroc_auc_score(y_test, knn.predict_proba(X_test)[:,1])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ec519f546e664828bdb92042247b176042ab10dc
67,065
ipynb
Jupyter Notebook
merge_performance.ipynb
timhunderwood/pandas-performance
fc93824ca25bc69d84c823011b3198d78432b582
[ "MIT" ]
null
null
null
merge_performance.ipynb
timhunderwood/pandas-performance
fc93824ca25bc69d84c823011b3198d78432b582
[ "MIT" ]
null
null
null
merge_performance.ipynb
timhunderwood/pandas-performance
fc93824ca25bc69d84c823011b3198d78432b582
[ "MIT" ]
null
null
null
123.736162
16,964
0.844688
[ [ [ "# Intro\nBenchmarking the performance of merges. ", "_____no_output_____" ] ], [ [ "import pandas\nimport numpy\nimport matplotlib.pyplot as plt\nimport timeit", "_____no_output_____" ], [ "pandas.__version__, numpy.__version__", "_____no_output_____" ], [ "def generate_dataframes(N:int, set_index: bool, type_def: str, duplicates:float):\n \n numpy.random.seed(11)\n if duplicates >0:\n sample = int((1-duplicates)*N)+1\n array_1 = numpy.random.choice(sample, N, replace=True)\n else:\n array_1 = numpy.arange(N)\n numpy.random.shuffle(array_1) # shuffle works in-place\n \n df_1 = pandas.DataFrame(array_1, columns=[\"A\"])\n df_1[\"B\"] = df_1[\"A\"]*2\n\n array_2 = array_1.copy()\n numpy.random.shuffle(array_2)\n df_2 = pandas.DataFrame(array_2, columns=[\"A\"])\n df_2[\"B\"] = df_2[\"A\"]*2\n \n if type_def == \"datetime\":\n df_1[\"A\"] = pandas.to_datetime(df_1[\"A\"])\n df_2[\"A\"] = pandas.to_datetime(df_2[\"A\"])\n else:\n df_1[\"A\"] =df_1[\"A\"].astype(type_def)\n df_2[\"A\"] =df_2[\"A\"].astype(type_def)\n \n if set_index:\n df_1 = df_1.set_index(\"A\")\n df_2 = df_2.set_index(\"A\")\n \n return df_1, df_2\n\ndef get_time(df_1: pandas.DataFrame, df_2: pandas.DataFrame, indexed: bool):\n if indexed:\n time_result = %timeit -o df_1.merge(df_2, how=\"left\", left_index=True, right_index=True)\n else:\n time_result = %timeit -o df_1.merge(df_2, how=\"left\", left_on=\"A\", right_on=\"A\")\n return time_result.average\n\ndef profile(df_1: pandas.DataFrame, df_2: pandas.DataFrame, indexed: bool):\n if indexed:\n df_1.merge(df_2, how=\"left\", left_index=True, right_index=True)\n else:\n df_1.merge(df_2, how=\"left\", left_on=\"A\", right_on=\"A\")", "_____no_output_____" ], [ "#1. Compare performance of merge for various sizes when joining on index vs not on index\nsizes = [1,10,100,1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000] \n\ndfs = [generate_dataframes(N, False, \"int\", duplicates=0) for N in sizes]\ntime_by_size = [get_time(df_1, df_2, False) for (df_1, df_2) in dfs]\n\ndfs_indexed = [generate_dataframes(N, True, \"int\", duplicates=0) for N in sizes]\ntime_by_size_indexed = [get_time(df_1, df_2, True) for (df_1, df_2) in dfs_indexed]", "1.78 ms ± 105 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n1.85 ms ± 139 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n1.77 ms ± 38.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n1.92 ms ± 37.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n3.07 ms ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n28.6 ms ± 420 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n504 ms ± 5.36 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n6.98 s ± 113 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n1min 28s ± 2.99 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n430 µs ± 3.94 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n534 µs ± 8.34 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n532 µs ± 3.14 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n564 µs ± 21.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n708 µs ± 35.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n2.46 ms ± 96.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n67.7 ms ± 805 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n1.01 s ± 9.88 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n16.6 s ± 150 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ], [ "# plot results\nfig, ax = plt.subplots()\nax.plot(sizes, time_by_size, 'o', label=\"not on index\")\nax.plot(sizes, time_by_size_indexed, 'o', label=\"on index\")\nax.set_xlabel(\"number of rows\")\nax.set_ylabel(\"time (s)\")\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\nax.legend()\nfig.savefig(\"merge-performance-by-size.png\")\nfig.savefig(\"merge-performance-by-size.svg\")", "_____no_output_____" ], [ "#2. Compare performance of merging on different dtypes (on index vs not on index)\ntype_defs = [\"datetime\", pandas.Int64Dtype(), \"int\", \"str\", \"category\", \"float\"]\ndfs = [generate_dataframes(1_000_000, False, type_def, duplicates=0) for type_def in type_defs]\ntime_by_type = [get_time(df_1, df_2, False) for (df_1, df_2) in dfs]\n\ndfs = [generate_dataframes(1_000_000, True, type_def, duplicates=0) for type_def in type_defs]\ntime_by_type_indexed = [get_time(df_1, df_2, True) for (df_1, df_2) in dfs]\ntype_defs = [\"datetime\", \"nullable-int\", \"int\", \"str\", \"category\", \"float\"]", "508 ms ± 4.64 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n850 ms ± 20 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n499 ms ± 3.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n1.2 s ± 24.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n652 ms ± 32 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n998 ms ± 11.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n58.2 ms ± 556 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n223 ms ± 4.34 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n70.5 ms ± 644 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n336 ms ± 2.37 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n2.28 s ± 13.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n82.8 ms ± 2.22 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ], [ "fig, ax = plt.subplots()\nax.plot(type_defs, time_by_type, 'o', label=\"not on index\")\nax.plot(type_defs, time_by_type_indexed, 'o', label=\"on index\")\nax.set_xlabel(\"dtype\")\nax.set_ylabel(\"time (s)\")\nax.set_yscale(\"log\")\nax.legend()\nfig.savefig(\"merge-performance-by-type.png\")\nfig.savefig(\"merge-performance-by-type.svg\")", "_____no_output_____" ], [ "#3. performance depending on duplicate amount (proportion)\nduplicates = [0,0.05, 0.1, 0.2,0.4,0.6, 0.8, 0.9, 0.95]\n\ndfs = [generate_dataframes(1_000_000, False, \"int\", duplicates=d) for d in duplicates]\ntime_by_duplicates = [get_time(df_1, df_2, False) for (df_1, df_2) in dfs]\n\ndfs_indexed = [generate_dataframes(1_000_000, True, \"int\", duplicates=d) for d in duplicates]\ntime_by_duplicates_indexed = [get_time(df_1, df_2, True) for (df_1, df_2) in dfs_indexed]", "514 ms ± 14.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n583 ms ± 17.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n600 ms ± 22.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n611 ms ± 15 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n583 ms ± 8.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n663 ms ± 15.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n940 ms ± 99.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n1.39 s ± 105 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n2.28 s ± 164 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n70.8 ms ± 3.63 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n965 ms ± 103 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n999 ms ± 95.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n976 ms ± 76.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n953 ms ± 43.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n789 ms ± 83.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n812 ms ± 41.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n1.01 s ± 27.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n1.47 s ± 75.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ], [ "fig, ax = plt.subplots()\nax.plot(duplicates, time_by_duplicates, 'o', label=\"not on index\")\nax.plot(duplicates, time_by_duplicates_indexed, 'o', label=\"on index\")\nax.set_xlabel(\"duplicate density\")\nax.set_ylabel(\"time (s)\")\nax.set_yscale(\"log\")\nax.legend()\nfig.savefig(\"merge-performance-by-duplicate.png\")\nfig.savefig(\"merge-performance-by-duplicate.svg\")", "_____no_output_____" ], [ "#4. Sorted vs unsorted\n# (unsorted)\ndf_1, df_2 = generate_dataframes(1_000_000, True, \"int\", duplicates=0)\nget_time(df_1, df_2, True)", "66.8 ms ± 2.06 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" ], [ "# sorted dfs merge much faster...\ndf_1, df_2 = generate_dataframes(1_000_000, True, \"int\", duplicates=0)\ndf_1 = df_1.sort_values(\"A\", ascending=True)\ndf_2 = df_2.sort_values(\"A\", ascending=True)\nget_time(df_1, df_2, True)", "7.02 ms ± 343 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" ], [ "df_1, df_2 = generate_dataframes(1_000_000, True, \"int\", duplicates=0)\ndf_1 = df_1.sort_values(\"A\", ascending=True)\nget_time(df_1, df_2, True)", "44.9 ms ± 1.73 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" ], [ "sizes = [1,10,100,1_000, 10_000, 100_000, 1_000_000, 10_000_000] \n\ndfs = [generate_dataframes(N, False, \"int\", duplicates=0) for N in sizes]\ntime_by_size = [get_time(df_1, df_2, False) for (df_1, df_2) in dfs]\n\ndfs_sorted = [(df_1.copy().sort_values(\"A\", ascending=True),\n df_2.copy().sort_values(\"A\", ascending=True)) for (df_1, df_2) in dfs]\ntime_by_size_sorted = [get_time(df_1, df_2, False) for (df_1, df_2) in dfs_sorted]\n\ndfs_indexed = [generate_dataframes(N, True, \"int\", duplicates=0) for N in sizes]\ntime_by_size_indexed = [get_time(df_1, df_2, True) for (df_1, df_2) in dfs_indexed]\n\ndfs_indexed_sorted = [(df_1.copy().sort_values(\"A\", ascending=True),\n df_2.copy().sort_values(\"A\", ascending=True)) for (df_1, df_2) in dfs_indexed]\ntime_by_size_indexed_sorted = [get_time(df_1, df_2, True) for (df_1, df_2) in dfs_indexed_sorted]", "1.83 ms ± 100 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n1.97 ms ± 141 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n1.94 ms ± 35.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n1.99 ms ± 124 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n3.22 ms ± 84.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n35.4 ms ± 8.64 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n545 ms ± 29.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n7.71 s ± 552 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n1.76 ms ± 84.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n1.78 ms ± 72.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n1.95 ms ± 197 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n2.03 ms ± 294 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n2.88 ms ± 54.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n27.8 ms ± 1.34 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n414 ms ± 22.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n4.65 s ± 56.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n434 µs ± 951 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n542 µs ± 6.17 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n556 µs ± 6.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n571 µs ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n747 µs ± 66.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n2.77 ms ± 581 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n108 ms ± 45.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n858 ms ± 10.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n436 µs ± 1.91 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n444 µs ± 6.64 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n439 µs ± 5.68 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n450 µs ± 16.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n467 µs ± 5.79 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n654 µs ± 54.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n6.84 ms ± 155 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n80.6 ms ± 14.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ], [ "fig, ax = plt.subplots()\nax.plot(sizes, time_by_size, 'o', label=\"not on index (not sorted)\")\nax.plot(sizes, time_by_size_sorted, 'o', label=\"not on index (sorted)\")\nax.plot(sizes, time_by_size_indexed, 'o', label=\"on index (not sorted)\")\nax.plot(sizes, time_by_size_indexed_sorted, 'o', label=\"on index (sorted)\")\nax.set_xlabel(\"number of rows\")\nax.set_ylabel(\"time (s)\")\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\nax.legend()\nfig.savefig(\"merge-performance-by-size-sorting.png\")\nfig.savefig(\"merge-performance-by-size-sorting.svg\")", "_____no_output_____" ], [ "# map vs merge - for small mapping tables using map is faster than join\ndf_1, df_2 = generate_dataframes(1_000_000, False, \"int\", duplicates=0.999)\ndf_3 = pandas.DataFrame([x for x in range(df_1[\"A\"].max()+1)], columns=[\"A\"])\ndf_3[\"B\"]=[x*2 for x in range(df_1[\"A\"].max()+1)]\nmapping ={x:x*2 for x in range(df_1[\"A\"].max()+1)}", "_____no_output_____" ], [ "get_time(df_1, df_3, False)", "_____no_output_____" ], [ "%timeit df_1[\"A\"].map(mapping)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec51aa3fd31f72b568e271f17d970a0f1b36ad06
3,554
ipynb
Jupyter Notebook
operations_research/Linear Programming.ipynb
chaosWsF/Financial-Mathematics
e8eebb7edd24eb71f6161fb6bf5fea4bb8a2961a
[ "Apache-2.0" ]
1
2022-03-13T11:57:56.000Z
2022-03-13T11:57:56.000Z
operations_research/Linear Programming.ipynb
chaosWsF/Financial-Mathematics
e8eebb7edd24eb71f6161fb6bf5fea4bb8a2961a
[ "Apache-2.0" ]
null
null
null
operations_research/Linear Programming.ipynb
chaosWsF/Financial-Mathematics
e8eebb7edd24eb71f6161fb6bf5fea4bb8a2961a
[ "Apache-2.0" ]
null
null
null
21.409639
99
0.498875
[ [ [ "from scipy import optimize as op", "_____no_output_____" ] ], [ [ "$\\max\\quad z=2x_1+3x_2-5x_3$\n\ns.t. $\\quad x_1+x_2+x_3=7$\n\n$\\quad\\quad 2x_1-5x_2+x_3\\geq10$\n\n$\\quad\\quad x_1+3x_2+x_3\\leq12$\n\n$\\quad\\quad x_1,x_2,x_3\\geq0$", "_____no_output_____" ] ], [ [ "op.linprog?", "_____no_output_____" ], [ "import numpy as np", "_____no_output_____" ], [ "c = np.array([2, 3, -5])\nA_ub = np.array([[-2, 5, -1],[1, 3, 1]])\nb_ub = np.array([-10, 12])\nA_eq = np.array([[1, 1, 1]]) # note one: input size is two by two\nb_eq = np.array([7])\nx1 = (0, 7)\nx2 = (0, 7)\nx3 = (0, 7)\nop.linprog(-c, A_ub, b_ub, A_eq, b_eq, bounds=(x1,x2,x3)) # note two: op is to solve minimize", "_____no_output_____" ] ], [ [ "$\\quad\\quad z_{max}=14.57$", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
ec51b46b03d84ee260acd6a70314198deec61fdb
164,308
ipynb
Jupyter Notebook
spring1617_assignment2/assignment2/ConvolutionalNetworks.ipynb
sujit25/cs231n_assignments
21a66a0768b81b1f2450bb913ff9981dab40cc8d
[ "Apache-2.0" ]
null
null
null
spring1617_assignment2/assignment2/ConvolutionalNetworks.ipynb
sujit25/cs231n_assignments
21a66a0768b81b1f2450bb913ff9981dab40cc8d
[ "Apache-2.0" ]
null
null
null
spring1617_assignment2/assignment2/ConvolutionalNetworks.ipynb
sujit25/cs231n_assignments
21a66a0768b81b1f2450bb913ff9981dab40cc8d
[ "Apache-2.0" ]
null
null
null
186.290249
127,112
0.881533
[ [ [ "# Convolutional Networks\nSo far we have worked with deep fully-connected networks, using them to explore different optimization strategies and network architectures. Fully-connected networks are a good testbed for experimentation because they are very computationally efficient, but in practice all state-of-the-art results use convolutional networks instead.\n\nFirst you will implement several layer types that are used in convolutional networks. You will then use these layers to train a convolutional network on the CIFAR-10 dataset.", "_____no_output_____" ] ], [ [ "# As usual, a bit of setup\nfrom __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cs231n.classifiers.cnn import *\nfrom cs231n.data_utils import get_CIFAR10_data\nfrom cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient\nfrom cs231n.layers import *\nfrom cs231n.fast_layers import *\nfrom cs231n.solver import Solver\n\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\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\n\ndef rel_error(x, y):\n \"\"\" returns relative error \"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))", "run the following from the cs231n directory and try again:\npython setup.py build_ext --inplace\nYou may also need to restart your iPython kernel\n" ], [ "# Load the (preprocessed) CIFAR10 data.\n\ndata = get_CIFAR10_data()\nfor k, v in data.items():\n print('%s: ' % k, v.shape)", "X_train: (49000, 3, 32, 32)\ny_train: (49000,)\nX_val: (1000, 3, 32, 32)\ny_val: (1000,)\nX_test: (1000, 3, 32, 32)\ny_test: (1000,)\n" ] ], [ [ "# Convolution: Naive forward pass\nThe core of a convolutional network is the convolution operation. In the file `cs231n/layers.py`, implement the forward pass for the convolution layer in the function `conv_forward_naive`. \n\nYou don't have to worry too much about efficiency at this point; just write the code in whatever way you find most clear.\n\nYou can test your implementation by running the following:", "_____no_output_____" ] ], [ [ "x_shape = (2, 3, 4, 4)\nw_shape = (3, 3, 4, 4)\nx = np.linspace(-0.1, 0.5, num=np.prod(x_shape)).reshape(x_shape)\nw = np.linspace(-0.2, 0.3, num=np.prod(w_shape)).reshape(w_shape)\nb = np.linspace(-0.1, 0.2, num=3)\n\nconv_param = {'stride': 2, 'pad': 1}\nout, _ = conv_forward_naive(x, w, b, conv_param)\ncorrect_out = np.array([[[[-0.08759809, -0.10987781],\n [-0.18387192, -0.2109216 ]],\n [[ 0.21027089, 0.21661097],\n [ 0.22847626, 0.23004637]],\n [[ 0.50813986, 0.54309974],\n [ 0.64082444, 0.67101435]]],\n [[[-0.98053589, -1.03143541],\n [-1.19128892, -1.24695841]],\n [[ 0.69108355, 0.66880383],\n [ 0.59480972, 0.56776003]],\n [[ 2.36270298, 2.36904306],\n [ 2.38090835, 2.38247847]]]])\n\n# Compare your output to ours; difference should be around 2e-8\nprint('Testing conv_forward_naive')\nprint('difference: ', rel_error(out, correct_out))", "Testing conv_forward_naive\ndifference: 2.2121476417505994e-08\n" ] ], [ [ "# Aside: Image processing via convolutions\n\nAs fun way to both check your implementation and gain a better understanding of the type of operation that convolutional layers can perform, we will set up an input containing two images and manually set up filters that perform common image processing operations (grayscale conversion and edge detection). The convolution forward pass will apply these operations to each of the input images. We can then visualize the results as a sanity check.", "_____no_output_____" ] ], [ [ "from scipy.misc import imread, imresize\n\nkitten, puppy = imread('kitten.jpg'), imread('puppy.jpg')\n# kitten is wide, and puppy is already square\nd = kitten.shape[1] - kitten.shape[0]\nkitten_cropped = kitten[:, d//2:-d//2, :]\n\nimg_size = 200 # Make this smaller if it runs too slow\nx = np.zeros((2, 3, img_size, img_size))\nx[0, :, :, :] = imresize(puppy, (img_size, img_size)).transpose((2, 0, 1))\nx[1, :, :, :] = imresize(kitten_cropped, (img_size, img_size)).transpose((2, 0, 1))\n\n# Set up a convolutional weights holding 2 filters, each 3x3\nw = np.zeros((2, 3, 3, 3))\n\n# The first filter converts the image to grayscale.\n# Set up the red, green, and blue channels of the filter.\nw[0, 0, :, :] = [[0, 0, 0], [0, 0.3, 0], [0, 0, 0]]\nw[0, 1, :, :] = [[0, 0, 0], [0, 0.6, 0], [0, 0, 0]]\nw[0, 2, :, :] = [[0, 0, 0], [0, 0.1, 0], [0, 0, 0]]\n\n# Second filter detects horizontal edges in the blue channel.\nw[1, 2, :, :] = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]]\n\n# Vector of biases. We don't need any bias for the grayscale\n# filter, but for the edge detection filter we want to add 128\n# to each output so that nothing is negative.\nb = np.array([0, 128])\n\n# Compute the result of convolving each input in x with each filter in w,\n# offsetting by b, and storing the results in out.\nout, _ = conv_forward_naive(x, w, b, {'stride': 1, 'pad': 1})\n\ndef imshow_noax(img, normalize=True):\n \"\"\" Tiny helper to show images as uint8 and remove axis labels \"\"\"\n if normalize:\n img_max, img_min = np.max(img), np.min(img)\n img = 255.0 * (img - img_min) / (img_max - img_min)\n plt.imshow(img.astype('uint8'))\n plt.gca().axis('off')\n\n# Show the original images and the results of the conv operation\nplt.subplot(2, 3, 1)\nimshow_noax(puppy, normalize=False)\nplt.title('Original image')\nplt.subplot(2, 3, 2)\nimshow_noax(out[0, 0])\nplt.title('Grayscale')\nplt.subplot(2, 3, 3)\nimshow_noax(out[0, 1])\nplt.title('Edges')\nplt.subplot(2, 3, 4)\nimshow_noax(kitten_cropped, normalize=False)\nplt.subplot(2, 3, 5)\nimshow_noax(out[1, 0])\nplt.subplot(2, 3, 6)\nimshow_noax(out[1, 1])\nplt.show()", "/home/sujit25/anaconda3/envs/ml_env/lib/python3.6/site-packages/ipykernel_launcher.py:3: DeprecationWarning: `imread` is deprecated!\n`imread` is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.\nUse ``imageio.imread`` instead.\n This is separate from the ipykernel package so we can avoid doing imports until\n/home/sujit25/anaconda3/envs/ml_env/lib/python3.6/site-packages/ipykernel_launcher.py:10: DeprecationWarning: `imresize` is deprecated!\n`imresize` is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.\nUse ``skimage.transform.resize`` instead.\n # Remove the CWD from sys.path while we load stuff.\n/home/sujit25/anaconda3/envs/ml_env/lib/python3.6/site-packages/ipykernel_launcher.py:11: DeprecationWarning: `imresize` is deprecated!\n`imresize` is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.\nUse ``skimage.transform.resize`` instead.\n # This is added back by InteractiveShellApp.init_path()\n" ] ], [ [ "# Convolution: Naive backward pass\nImplement the backward pass for the convolution operation in the function `conv_backward_naive` in the file `cs231n/layers.py`. Again, you don't need to worry too much about computational efficiency.\n\nWhen you are done, run the following to check your backward pass with a numeric gradient check.", "_____no_output_____" ] ], [ [ "np.random.seed(231)\nx = np.random.randn(4, 3, 5, 5)\nw = np.random.randn(2, 3, 3, 3)\nb = np.random.randn(2,)\ndout = np.random.randn(4, 2, 5, 5)\nconv_param = {'stride': 1, 'pad': 1}\n\ndx_num = eval_numerical_gradient_array(lambda x: conv_forward_naive(x, w, b, conv_param)[0], x, dout)\ndw_num = eval_numerical_gradient_array(lambda w: conv_forward_naive(x, w, b, conv_param)[0], w, dout)\ndb_num = eval_numerical_gradient_array(lambda b: conv_forward_naive(x, w, b, conv_param)[0], b, dout)\n\nout, cache = conv_forward_naive(x, w, b, conv_param)\ndx, dw, db = conv_backward_naive(dout, cache)\n\n# Your errors should be around 1e-8'\nprint('Testing conv_backward_naive function')\nprint('dx error: ', rel_error(dx, dx_num))\nprint('dw error: ', rel_error(dw, dw_num))\nprint('db error: ', rel_error(db, db_num))", "_____no_output_____" ] ], [ [ "# Max pooling: Naive forward\nImplement the forward pass for the max-pooling operation in the function `max_pool_forward_naive` in the file `cs231n/layers.py`. Again, don't worry too much about computational efficiency.\n\nCheck your implementation by running the following:", "_____no_output_____" ] ], [ [ "x_shape = (2, 3, 4, 4)\nx = np.linspace(-0.3, 0.4, num=np.prod(x_shape)).reshape(x_shape)\npool_param = {'pool_width': 2, 'pool_height': 2, 'stride': 2}\n\nout, _ = max_pool_forward_naive(x, pool_param)\n\ncorrect_out = np.array([[[[-0.26315789, -0.24842105],\n [-0.20421053, -0.18947368]],\n [[-0.14526316, -0.13052632],\n [-0.08631579, -0.07157895]],\n [[-0.02736842, -0.01263158],\n [ 0.03157895, 0.04631579]]],\n [[[ 0.09052632, 0.10526316],\n [ 0.14947368, 0.16421053]],\n [[ 0.20842105, 0.22315789],\n [ 0.26736842, 0.28210526]],\n [[ 0.32631579, 0.34105263],\n [ 0.38526316, 0.4 ]]]])\n\n# Compare your output with ours. Difference should be around 1e-8.\nprint('Testing max_pool_forward_naive function:')\nprint('difference: ', rel_error(out, correct_out))", "Testing max_pool_forward_naive function:\ndifference: 4.1666665157267834e-08\n" ] ], [ [ "# Max pooling: Naive backward\nImplement the backward pass for the max-pooling operation in the function `max_pool_backward_naive` in the file `cs231n/layers.py`. You don't need to worry about computational efficiency.\n\nCheck your implementation with numeric gradient checking by running the following:", "_____no_output_____" ] ], [ [ "np.random.seed(231)\nx = np.random.randn(3, 2, 8, 8)\ndout = np.random.randn(3, 2, 4, 4)\npool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}\n\ndx_num = eval_numerical_gradient_array(lambda x: max_pool_forward_naive(x, pool_param)[0], x, dout)\n\nout, cache = max_pool_forward_naive(x, pool_param)\ndx = max_pool_backward_naive(dout, cache)\n\n# Your error should be around 1e-12\nprint('Testing max_pool_backward_naive function:')\nprint('dx error: ', rel_error(dx, dx_num))", "_____no_output_____" ] ], [ [ "# Fast layers\nMaking convolution and pooling layers fast can be challenging. To spare you the pain, we've provided fast implementations of the forward and backward passes for convolution and pooling layers in the file `cs231n/fast_layers.py`.\n\nThe fast convolution implementation depends on a Cython extension; to compile it you need to run the following from the `cs231n` directory:\n\n```bash\npython setup.py build_ext --inplace\n```\n\nThe API for the fast versions of the convolution and pooling layers is exactly the same as the naive versions that you implemented above: the forward pass receives data, weights, and parameters and produces outputs and a cache object; the backward pass recieves upstream derivatives and the cache object and produces gradients with respect to the data and weights.\n\n**NOTE:** The fast implementation for pooling will only perform optimally if the pooling regions are non-overlapping and tile the input. If these conditions are not met then the fast pooling implementation will not be much faster than the naive implementation.\n\nYou can compare the performance of the naive and fast versions of these layers by running the following:", "_____no_output_____" ] ], [ [ "from cs231n.fast_layers import conv_forward_fast, conv_backward_fast\nfrom time import time\nnp.random.seed(231)\nx = np.random.randn(100, 3, 31, 31)\nw = np.random.randn(25, 3, 3, 3)\nb = np.random.randn(25,)\ndout = np.random.randn(100, 25, 16, 16)\nconv_param = {'stride': 2, 'pad': 1}\n\nt0 = time()\nout_naive, cache_naive = conv_forward_naive(x, w, b, conv_param)\nt1 = time()\nout_fast, cache_fast = conv_forward_fast(x, w, b, conv_param)\nt2 = time()\n\nprint('Testing conv_forward_fast:')\nprint('Naive: %fs' % (t1 - t0))\nprint('Fast: %fs' % (t2 - t1))\nprint('Speedup: %fx' % ((t1 - t0) / (t2 - t1)))\nprint('Difference: ', rel_error(out_naive, out_fast))\n\nt0 = time()\ndx_naive, dw_naive, db_naive = conv_backward_naive(dout, cache_naive)\nt1 = time()\ndx_fast, dw_fast, db_fast = conv_backward_fast(dout, cache_fast)\nt2 = time()\n\nprint('\\nTesting conv_backward_fast:')\nprint('Naive: %fs' % (t1 - t0))\nprint('Fast: %fs' % (t2 - t1))\nprint('Speedup: %fx' % ((t1 - t0) / (t2 - t1)))\nprint('dx difference: ', rel_error(dx_naive, dx_fast))\nprint('dw difference: ', rel_error(dw_naive, dw_fast))\nprint('db difference: ', rel_error(db_naive, db_fast))", "Testing conv_forward_fast:\nNaive: 4.572742s\nFast: 0.013993s\nSpeedup: 326.781640x\nDifference: 4.926407851494105e-11\n" ], [ "from cs231n.fast_layers import max_pool_forward_fast, max_pool_backward_fast\nnp.random.seed(231)\nx = np.random.randn(100, 3, 32, 32)\ndout = np.random.randn(100, 3, 16, 16)\npool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}\n\nt0 = time()\nout_naive, cache_naive = max_pool_forward_naive(x, pool_param)\nt1 = time()\nout_fast, cache_fast = max_pool_forward_fast(x, pool_param)\nt2 = time()\n\nprint('Testing pool_forward_fast:')\nprint('Naive: %fs' % (t1 - t0))\nprint('fast: %fs' % (t2 - t1))\nprint('speedup: %fx' % ((t1 - t0) / (t2 - t1)))\nprint('difference: ', rel_error(out_naive, out_fast))\n\nt0 = time()\ndx_naive = max_pool_backward_naive(dout, cache_naive)\nt1 = time()\ndx_fast = max_pool_backward_fast(dout, cache_fast)\nt2 = time()\n\nprint('\\nTesting pool_backward_fast:')\nprint('Naive: %fs' % (t1 - t0))\nprint('speedup: %fx' % ((t1 - t0) / (t2 - t1)))\nprint('dx difference: ', rel_error(dx_naive, dx_fast))", "_____no_output_____" ] ], [ [ "# Convolutional \"sandwich\" layers\nPreviously we introduced the concept of \"sandwich\" layers that combine multiple operations into commonly used patterns. In the file `cs231n/layer_utils.py` you will find sandwich layers that implement a few commonly used patterns for convolutional networks.", "_____no_output_____" ] ], [ [ "from cs231n.layer_utils import conv_relu_pool_forward, conv_relu_pool_backward\nnp.random.seed(231)\nx = np.random.randn(2, 3, 16, 16)\nw = np.random.randn(3, 3, 3, 3)\nb = np.random.randn(3,)\ndout = np.random.randn(2, 3, 8, 8)\nconv_param = {'stride': 1, 'pad': 1}\npool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}\n\nout, cache = conv_relu_pool_forward(x, w, b, conv_param, pool_param)\ndx, dw, db = conv_relu_pool_backward(dout, cache)\n\ndx_num = eval_numerical_gradient_array(lambda x: conv_relu_pool_forward(x, w, b, conv_param, pool_param)[0], x, dout)\ndw_num = eval_numerical_gradient_array(lambda w: conv_relu_pool_forward(x, w, b, conv_param, pool_param)[0], w, dout)\ndb_num = eval_numerical_gradient_array(lambda b: conv_relu_pool_forward(x, w, b, conv_param, pool_param)[0], b, dout)\n\nprint('Testing conv_relu_pool')\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dw error: ', rel_error(dw_num, dw))\nprint('db error: ', rel_error(db_num, db))", "_____no_output_____" ], [ "from cs231n.layer_utils import conv_relu_forward, conv_relu_backward\nnp.random.seed(231)\nx = np.random.randn(2, 3, 8, 8)\nw = np.random.randn(3, 3, 3, 3)\nb = np.random.randn(3,)\ndout = np.random.randn(2, 3, 8, 8)\nconv_param = {'stride': 1, 'pad': 1}\n\nout, cache = conv_relu_forward(x, w, b, conv_param)\ndx, dw, db = conv_relu_backward(dout, cache)\n\ndx_num = eval_numerical_gradient_array(lambda x: conv_relu_forward(x, w, b, conv_param)[0], x, dout)\ndw_num = eval_numerical_gradient_array(lambda w: conv_relu_forward(x, w, b, conv_param)[0], w, dout)\ndb_num = eval_numerical_gradient_array(lambda b: conv_relu_forward(x, w, b, conv_param)[0], b, dout)\n\nprint('Testing conv_relu:')\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dw error: ', rel_error(dw_num, dw))\nprint('db error: ', rel_error(db_num, db))", "_____no_output_____" ] ], [ [ "# Three-layer ConvNet\nNow that you have implemented all the necessary layers, we can put them together into a simple convolutional network.\n\nOpen the file `cs231n/classifiers/cnn.py` and complete the implementation of the `ThreeLayerConvNet` class. Run the following cells to help you debug:", "_____no_output_____" ], [ "## Sanity check loss\nAfter you build a new network, one of the first things you should do is sanity check the loss. When we use the softmax loss, we expect the loss for random weights (and no regularization) to be about `log(C)` for `C` classes. When we add regularization this should go up.", "_____no_output_____" ] ], [ [ "model = ThreeLayerConvNet()\n\nN = 50\nX = np.random.randn(N, 3, 32, 32)\ny = np.random.randint(10, size=N)\n\nloss, grads = model.loss(X, y)\nprint('Initial loss (no regularization): ', loss)\n\nmodel.reg = 0.5\nloss, grads = model.loss(X, y)\nprint('Initial loss (with regularization): ', loss)", "_____no_output_____" ] ], [ [ "## Gradient check\nAfter the loss looks reasonable, use numeric gradient checking to make sure that your backward pass is correct. When you use numeric gradient checking you should use a small amount of artifical data and a small number of neurons at each layer. Note: correct implementations may still have relative errors up to 1e-2.", "_____no_output_____" ] ], [ [ "num_inputs = 2\ninput_dim = (3, 16, 16)\nreg = 0.0\nnum_classes = 10\nnp.random.seed(231)\nX = np.random.randn(num_inputs, *input_dim)\ny = np.random.randint(num_classes, size=num_inputs)\n\nmodel = ThreeLayerConvNet(num_filters=3, filter_size=3,\n input_dim=input_dim, hidden_dim=7,\n dtype=np.float64)\nloss, grads = model.loss(X, y)\nfor param_name in sorted(grads):\n f = lambda _: model.loss(X, y)[0]\n param_grad_num = eval_numerical_gradient(f, model.params[param_name], verbose=False, h=1e-6)\n e = rel_error(param_grad_num, grads[param_name])\n print('%s max relative error: %e' % (param_name, rel_error(param_grad_num, grads[param_name])))", "_____no_output_____" ] ], [ [ "## Overfit small data\nA nice trick is to train your model with just a few training samples. You should be able to overfit small datasets, which will result in very high training accuracy and comparatively low validation accuracy.", "_____no_output_____" ] ], [ [ "np.random.seed(231)\n\nnum_train = 100\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nmodel = ThreeLayerConvNet(weight_scale=1e-2)\n\nsolver = Solver(model, small_data,\n num_epochs=15, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=1)\nsolver.train()", "_____no_output_____" ] ], [ [ "Plotting the loss, training accuracy, and validation accuracy should show clear overfitting:", "_____no_output_____" ] ], [ [ "plt.subplot(2, 1, 1)\nplt.plot(solver.loss_history, 'o')\nplt.xlabel('iteration')\nplt.ylabel('loss')\n\nplt.subplot(2, 1, 2)\nplt.plot(solver.train_acc_history, '-o')\nplt.plot(solver.val_acc_history, '-o')\nplt.legend(['train', 'val'], loc='upper left')\nplt.xlabel('epoch')\nplt.ylabel('accuracy')\nplt.show()", "_____no_output_____" ] ], [ [ "## Train the net\nBy training the three-layer convolutional network for one epoch, you should achieve greater than 40% accuracy on the training set:", "_____no_output_____" ] ], [ [ "model = ThreeLayerConvNet(weight_scale=0.001, hidden_dim=500, reg=0.001)\n\nsolver = Solver(model, data,\n num_epochs=1, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=20)\nsolver.train()", "_____no_output_____" ] ], [ [ "## Visualize Filters\nYou can visualize the first-layer convolutional filters from the trained network by running the following:", "_____no_output_____" ] ], [ [ "from cs231n.vis_utils import visualize_grid\n\ngrid = visualize_grid(model.params['W1'].transpose(0, 2, 3, 1))\nplt.imshow(grid.astype('uint8'))\nplt.axis('off')\nplt.gcf().set_size_inches(5, 5)\nplt.show()", "_____no_output_____" ] ], [ [ "# Spatial Batch Normalization\nWe already saw that batch normalization is a very useful technique for training deep fully-connected networks. Batch normalization can also be used for convolutional networks, but we need to tweak it a bit; the modification will be called \"spatial batch normalization.\"\n\nNormally batch-normalization accepts inputs of shape `(N, D)` and produces outputs of shape `(N, D)`, where we normalize across the minibatch dimension `N`. For data coming from convolutional layers, batch normalization needs to accept inputs of shape `(N, C, H, W)` and produce outputs of shape `(N, C, H, W)` where the `N` dimension gives the minibatch size and the `(H, W)` dimensions give the spatial size of the feature map.\n\nIf the feature map was produced using convolutions, then we expect the statistics of each feature channel to be relatively consistent both between different imagesand different locations within the same image. Therefore spatial batch normalization computes a mean and variance for each of the `C` feature channels by computing statistics over both the minibatch dimension `N` and the spatial dimensions `H` and `W`.", "_____no_output_____" ], [ "## Spatial batch normalization: forward\n\nIn the file `cs231n/layers.py`, implement the forward pass for spatial batch normalization in the function `spatial_batchnorm_forward`. Check your implementation by running the following:", "_____no_output_____" ] ], [ [ "np.random.seed(231)\n# Check the training-time forward pass by checking means and variances\n# of features both before and after spatial batch normalization\n\nN, C, H, W = 2, 3, 4, 5\nx = 4 * np.random.randn(N, C, H, W) + 10\n\nprint('Before spatial batch normalization:')\nprint(' Shape: ', x.shape)\nprint(' Means: ', x.mean(axis=(0, 2, 3)))\nprint(' Stds: ', x.std(axis=(0, 2, 3)))\n\n# Means should be close to zero and stds close to one\ngamma, beta = np.ones(C), np.zeros(C)\nbn_param = {'mode': 'train'}\nout, _ = spatial_batchnorm_forward(x, gamma, beta, bn_param)\nprint('After spatial batch normalization:')\nprint(' Shape: ', out.shape)\nprint(' Means: ', out.mean(axis=(0, 2, 3)))\nprint(' Stds: ', out.std(axis=(0, 2, 3)))\n\n# Means should be close to beta and stds close to gamma\ngamma, beta = np.asarray([3, 4, 5]), np.asarray([6, 7, 8])\nout, _ = spatial_batchnorm_forward(x, gamma, beta, bn_param)\nprint('After spatial batch normalization (nontrivial gamma, beta):')\nprint(' Shape: ', out.shape)\nprint(' Means: ', out.mean(axis=(0, 2, 3)))\nprint(' Stds: ', out.std(axis=(0, 2, 3)))", "_____no_output_____" ], [ "np.random.seed(231)\n# Check the test-time forward pass by running the training-time\n# forward pass many times to warm up the running averages, and then\n# checking the means and variances of activations after a test-time\n# forward pass.\nN, C, H, W = 10, 4, 11, 12\n\nbn_param = {'mode': 'train'}\ngamma = np.ones(C)\nbeta = np.zeros(C)\nfor t in range(50):\n x = 2.3 * np.random.randn(N, C, H, W) + 13\n spatial_batchnorm_forward(x, gamma, beta, bn_param)\nbn_param['mode'] = 'test'\nx = 2.3 * np.random.randn(N, C, H, W) + 13\na_norm, _ = spatial_batchnorm_forward(x, gamma, beta, bn_param)\n\n# Means should be close to zero and stds close to one, but will be\n# noisier than training-time forward passes.\nprint('After spatial batch normalization (test-time):')\nprint(' means: ', a_norm.mean(axis=(0, 2, 3)))\nprint(' stds: ', a_norm.std(axis=(0, 2, 3)))", "_____no_output_____" ] ], [ [ "## Spatial batch normalization: backward\nIn the file `cs231n/layers.py`, implement the backward pass for spatial batch normalization in the function `spatial_batchnorm_backward`. Run the following to check your implementation using a numeric gradient check:", "_____no_output_____" ] ], [ [ "np.random.seed(231)\nN, C, H, W = 2, 3, 4, 5\nx = 5 * np.random.randn(N, C, H, W) + 12\ngamma = np.random.randn(C)\nbeta = np.random.randn(C)\ndout = np.random.randn(N, C, H, W)\n\nbn_param = {'mode': 'train'}\nfx = lambda x: spatial_batchnorm_forward(x, gamma, beta, bn_param)[0]\nfg = lambda a: spatial_batchnorm_forward(x, gamma, beta, bn_param)[0]\nfb = lambda b: spatial_batchnorm_forward(x, gamma, beta, bn_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma, dout)\ndb_num = eval_numerical_gradient_array(fb, beta, dout)\n\n_, cache = spatial_batchnorm_forward(x, gamma, beta, bn_param)\ndx, dgamma, dbeta = spatial_batchnorm_backward(dout, cache)\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))", "_____no_output_____" ] ], [ [ "# Extra Credit Description\nIf you implement any additional features for extra credit, clearly describe them here with pointers to any code in this or other files if applicable.", "_____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" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec51bf2723fc2646784db7b00d30d75525674f7d
77,203
ipynb
Jupyter Notebook
09_Predictions.ipynb
billquinn/Teaching-Python
fa2a0bab19d80baa291a91fae54b50bc97eaa31d
[ "MIT" ]
null
null
null
09_Predictions.ipynb
billquinn/Teaching-Python
fa2a0bab19d80baa291a91fae54b50bc97eaa31d
[ "MIT" ]
null
null
null
09_Predictions.ipynb
billquinn/Teaching-Python
fa2a0bab19d80baa291a91fae54b50bc97eaa31d
[ "MIT" ]
null
null
null
99.232648
29,048
0.796977
[ [ [ "# Predictions & Data Modeling\n\n### Goals\n\nThe goal of this notebook is to build from previous notebooks and add a step-by-step method for predicting the classifications of textual data. That is, if you have texts that are classified in some way (like real or fake news), then you can use this notebook to train a model that can predict whether a new, unseen article is real or fake. While there are more advance methods in development, text classification and prediction continues to be one of the most reliable modes of computational text analysis.\n\nAs with previous (and any) kind of text analysis, it's important to be cautious with your results. Our goal with these notebooks is not to learn something about fake or real news, though it's fine to speculate. Rather, the goal is to learn how to write code that will allow you to pursue your own research questions.\n\n#### Brief Note about Libraries\nBelow, you'll notice that we're importing a lot of libraries and packages. Although it looks like a lot, they all come from a few of the following libraries, which you can get with a conda installation:\n\nNew Libraries in this Notebook:\n1. numpy (conda install -c anaconda numpy)\n2. scipy (conda install -c anaconda scipy)\n\nOlder Libraries:\n1. re\n2. pandas\n3. seaborn\n4. matplot\n5. sklearn\n\nAs I mentioned earlier in these notebooks, if you want to use computational methods to think through a research question, odds are the code is already somewhere online. This notebook is an example of finding and re-using code. The majority of the code here was copied and developed from Susan Li's explanation and tutorial, linked to below.", "_____no_output_____" ] ], [ [ "import re\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Import sklearn libraries for prediction/modeling.\nfrom scipy import stats\n\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\n\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.feature_selection import chi2\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.decomposition import PCA\n\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import LinearSVC\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nabs_dir = \"/Users/williamquinn/Desktop/DH/Python/Teaching/Python-Notebooks/\"", "_____no_output_____" ] ], [ [ "## Multi-class Text Classification\n\nMulti-class refers to determining the probability that a variable is one option out of a few. In this exercise, we're trying to predict the correct class from two options, real or fake news.\n\nThe following cell does the important work of declaring a class (or column) to predict, in this case 'veracity.' We're creating a variable, \"class_to_predict,\" so that we can easily change one line of code rather than searching for multiple lines. That is, if we want to try predicting a different column, we can change one string variable here that we'll call a number of times rather than changing every instance that variable is needed.", "_____no_output_____" ] ], [ [ "data = pd.read_csv(abs_dir + \"data/dataframe.csv\",\n sep = \",\")\n\n# Declare class to predict.\nclass_to_predict = \"veracity\"\n\n# Create labels.\nlabels = data[str(class_to_predict)]\n\ndata.head()", "_____no_output_____" ] ], [ [ "The following code is nearly identical to the last notebook. I've consolidated the code into a single cell here to streamline a little.", "_____no_output_____" ] ], [ [ "%%time\n\n# Clean up text field.\ndata['text'] = data['text'] \\\n .replace(r\"[A-Z/]+ \\(\\w+\\) - \", \"\", regex=True) \\\n .replace(r'\\s+', ' ', regex=True) \\\n .str.lower() \\\n .astype(str)\n\n# Instantiate a vectorizer.\ntfidf = TfidfVectorizer(sublinear_tf=True, \n min_df=0.1, \n max_df=0.9, \n stop_words='english',\n norm='l2', \n encoding='latin-1', \n ngram_range=(1, 2))\n\nfeatures = tfidf.fit_transform(data['text']).toarray()\n\n# Show data size.\nfeatures.shape", "CPU times: user 1min 37s, sys: 3.92 s, total: 1min 41s\nWall time: 1min 44s\n" ] ], [ [ "## Model Testing\n\nhttps://towardsdatascience.com/why-and-how-to-cross-validate-a-model-d6424b45261f\n\nNow that we have transformed our text to numeric representations we can begin modeling our data.\n\nFor our purposes, data modeling refers to \nExplanation/descriptions of data modeling...\n\nThere are different classifiers to chose from and they each vary in their effectiveness. This cell helps determine which model we'll want to pick. After evaluating the cross validation of each model, the cell prints a visualization and brief accuracy report.\n\nKey Terms:\n* Cross Validation: Cross validation is a method to evaluate a model.\n\nMany algorithms split a dataset into a training portion and a testing portion. An algorithm will try to learn what features distinguish one class from another within the training portion. The model, then, is meant to represent the classes it found within the dataset. With the model now trained, the testing portion will provide a sense of how accurate the model is. The model guesses the class of each observation within the testing set, making guesses on the significant features it has found. The testing set hides the correct answer from the model until it has made all its guesses and then can measure how accurate the model was.\n\nThe \"accuracy\" of a model is a reflection of the dataset itself. In our dataset, we will get a sense of how accurate these models can determine whether an article is fake or real. But, if we're being precise, we would need to add: we get a sense of how accurate these models are at guessing observations already within the dataset. Observations from another dataset might change the \"accuracy\" of the model.", "_____no_output_____" ] ], [ [ "%%time\n\n# Declare a list of models to evaluate. \n# Some models have their own arguments.\nmodels = [\n RandomForestClassifier(n_estimators=200, max_depth=3, random_state=0),\n LinearSVC(),\n MultinomialNB(),\n LogisticRegression(random_state=0),\n CalibratedClassifierCV(base_estimator = LinearSVC())\n]\n\n# Set up cross validation.\nCV = 5\n\ncv_df = pd.DataFrame(index=range(CV * len(models)))\n\n# Measure accuracy of models and create dataframe of results.\nentries = []\n\n# Iterate through list of models, measuring accuracy of each.\nfor model in models:\n model_name = model.__class__.__name__\n accuracies = cross_val_score(model, features, labels, scoring='accuracy', cv=CV)\n \n for fold_idx, accuracy in enumerate(accuracies):\n entries.append((model_name, fold_idx, accuracy))\n\n# Create a dataframe of accuracy results.\ncv_df = pd.DataFrame(entries, columns=['model_name', 'fold_idx', 'accuracy'])\n\n# Visualize model accuracy.\nsns.boxplot(x='model_name', y='accuracy', data=cv_df)\nsns.stripplot(x='model_name', y='accuracy', data=cv_df, \n size=6, jitter=True, edgecolor=\"gray\", linewidth=2)\n\n# Rotate axis labels.\nplt.xticks(rotation=30)\nplt.show()\n\n# Print accuracy report.\ncv_df.groupby('model_name').accuracy.mean()", "_____no_output_____" ] ], [ [ "### Model Evaluation\n\nIt looks like the <b>CalibratedClassifierCV</b> has the highest accuracy and would be preferable than the <b>RandomForestClassifier</b>. But, the models above behave differently. Their different functionalities might constrain how you access them and/or try to transform the data within. For example, if you use <b>LinearSVC()</b> below, you'll run into an AttributeError ('LinearSVC' object has no attribute 'predict_proba') in the subsequent cell. If the accuracy score is negligible, you might choose a model that you're more familiar with. Additionally, if you were doing scholarly research, you might choose a model for more specialized reasons.", "_____no_output_____" ] ], [ [ "%%time\n\n# Declare classifier (clf). Calibrated requires argument.\n# If you want to use another model, simply change the following line to: clf = the model you'd like to use\nclf = CalibratedClassifierCV(base_estimator = LinearSVC())\n\nX_train, X_test, y_train, y_test, indices_train, indices_test = train_test_split(features, \n labels, \n data.index, \n test_size=0.33, \n random_state=0)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\n\n\n# Print accuracy report.\nprint(metrics.classification_report(y_test, \n y_pred,\n labels = labels.unique()))\n\n# Print cross validation report.\ncross_val_svc = cross_val_score(estimator = clf, \n X = X_train, y = y_train, cv = 10, n_jobs = -1)\n\nprint(\"Cross Validation Accuracy : \", round(cross_val_svc.mean() * 100 , 2), \"%\\n\",\n '\\n', clf.predict_proba(features).shape)", " precision recall f1-score support\n\n real 0.93 0.95 0.94 7046\n fake 0.97 0.96 0.96 12057\n\n accuracy 0.96 19103\n macro avg 0.95 0.95 0.95 19103\nweighted avg 0.96 0.96 0.96 19103\n\nCross Validation Accuracy : 95.35 %\n \n (57887, 2)\nCPU times: user 4.01 s, sys: 526 ms, total: 4.54 s\nWall time: 27.8 s\n" ] ], [ [ "The report printed above indicates that are model is incredibly accurate. But, this report provides a holistic and zoomed-out view. What if we want a \n\n## Probabilities of Each Predicted Class\n\nWhile above gives us an overview of our model (and the accuracy of predicting fake and real news), we can't learn much from this report. Merging the prediction results with metadata will allows us see a breakdown of every article and to examine trends over time.", "_____no_output_____" ] ], [ [ "%%time\n\n# Print size of class probabilities.\n# Calls back features variable (tf-idf results).\nprint (clf.predict_proba(features).shape)\n\n# Return predicted class probabilities of original dataframe.\npredictions = pd.DataFrame((clf.predict_proba(features)*100),\n index = data.index,\n# I have set columns manually because of a bug I wasn't able to resolve...\n# Normally, this can be set using labels.unique()\n columns = ['fake', 'real']) \\\n .reset_index()\n\n# Merge prediction results with metadata.\nresults = pd.merge(data, predictions, \n how = \"inner\", left_index = True, right_index = True)\n\n# results = results.drop([\"text\", \"class_id\"], axis = 1)\nresults = results.drop([\"text\"], axis = 1) \n\nresults = pd.melt(results,\n id_vars = ['title', 'veracity', 'date'],\n value_vars = labels.unique(),\n var_name = 'predicted_veracity',\n value_name = 'prediction') \\\n .reset_index()\n\nresults.head()", "(57887, 2)\nCPU times: user 451 ms, sys: 46.7 ms, total: 497 ms\nWall time: 336 ms\n" ] ], [ [ "Because we have nearly 60,000 documents over a few years, we'll want to find the average and standard deviation of predictions.", "_____no_output_____" ] ], [ [ "results \\\n .groupby(['veracity', 'predicted_veracity'])['prediction'].mean()\n\nresults['date'] = pd.to_datetime(results['date'])\nresults['year'] = results['date'].dt.year\n\naverages = results \\\n .query('veracity == predicted_veracity') \\\n .groupby(['year', 'predicted_veracity'])['prediction'] \\\n .mean() \\\n .reset_index()\n\naverages.head()", "_____no_output_____" ], [ "ax = sns.lmplot(data = averages,\n x = 'year', y = 'prediction', hue = 'predicted_veracity')\n\nax.set_xticklabels(rotation=45)", "_____no_output_____" ] ], [ [ "## Conclusion\n\n\n\n#### Works Cited\n\n* Li, Susan. \"[Multi-Class Text Classification with Scikit-Learn](https://towardsdatascience.com/multi-class-text-classification-with-scikit-learn-12f1e60e0a9f).\" <i>towards data science</i>, February 19, 2018. Accessed: February 9, 2020.\n\n* ____. \"[Machine Learning with Python](https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Consumer_complaints.ipynb).\" GitHub. Accessed: February 9, 2020.\n\n* Saxena, Manoveg. \"[predicting_probabilities_with_linearSVC.ipynb](https://github.com/manoveg/ML_with_python/blob/master/predicting_probabilities_with_linearSVC.ipynb).\" GitHub. Accessed: February 9, 2020.\n\n* Z., Zahash. \"[A Simple Guide to creating Predictive Models in Python, Part-2a](https://medium.com/datadriveninvestor/a-simple-guide-to-creating-predictive-models-in-python-part-2a-aa86ece98f86).\" <i>Medium</i>, November 22, 2018. Accessed: February 9, 2020.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
ec51ccc7ae445e314e6f6c440810f10024fc8f94
96,195
ipynb
Jupyter Notebook
Project/SageMaker Project.ipynb
TeaBeard/SentimentAnalysis
94f80c6ebaa71a7b863971ed02a9628857b8e2ac
[ "MIT" ]
null
null
null
Project/SageMaker Project.ipynb
TeaBeard/SentimentAnalysis
94f80c6ebaa71a7b863971ed02a9628857b8e2ac
[ "MIT" ]
null
null
null
Project/SageMaker Project.ipynb
TeaBeard/SentimentAnalysis
94f80c6ebaa71a7b863971ed02a9628857b8e2ac
[ "MIT" ]
null
null
null
49.661848
1,157
0.6105
[ [ [ "# Creating a Sentiment Analysis Web App\n## Using PyTorch and SageMaker\n\n_Deep Learning Nanodegree Program | Deployment_\n\n---\n\nNow that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can use to enter a movie review. The web page will then send the review off to our deployed model which will predict the sentiment of the entered review.\n\n## Instructions\n\nSome template code has already been provided for you, and you will need to implement additional functionality to successfully complete this notebook. You will not need to modify the included code beyond what is requested. Sections that begin with '**TODO**' in the header indicate that you need to complete or implement some portion within them. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `# TODO: ...` comment. Please be sure to read the instructions carefully!\n\nIn addition to implementing code, there will be questions for you to answer which relate to the task and your implementation. Each section where you will answer a question is preceded by a '**Question:**' header. Carefully read each question and provide your answer below the '**Answer:**' header by editing the Markdown cell.\n\n> **Note**: Code and Markdown cells can be executed using the **Shift+Enter** keyboard shortcut. In addition, a cell can be edited by typically clicking it (double-click for Markdown cells) or by pressing **Enter** while it is highlighted.\n\n## General Outline\n\nRecall the general outline for SageMaker projects using a notebook instance.\n\n1. Download or otherwise retrieve the data.\n2. Process / Prepare the data.\n3. Upload the processed data to S3.\n4. Train a chosen model.\n5. Test the trained model (typically using a batch transform job).\n6. Deploy the trained model.\n7. Use the deployed model.\n\nFor this project, you will be following the steps in the general outline with some modifications. \n\nFirst, you will not be testing the model in its own step. You will still be testing the model, however, you will do it by deploying your model and then using the deployed model by sending the test data to it. One of the reasons for doing this is so that you can make sure that your deployed model is working correctly before moving forward.\n\nIn addition, you will deploy and use your trained model a second time. In the second iteration you will customize the way that your trained model is deployed by including some of your own code. In addition, your newly deployed model will be used in the sentiment analysis web app.", "_____no_output_____" ], [ "## Step 1: Downloading the data\n\nAs in the XGBoost in SageMaker notebook, we will be using the [IMDb dataset](http://ai.stanford.edu/~amaas/data/sentiment/)\n\n> Maas, Andrew L., et al. [Learning Word Vectors for Sentiment Analysis](http://ai.stanford.edu/~amaas/data/sentiment/). In _Proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies_. Association for Computational Linguistics, 2011.", "_____no_output_____" ] ], [ [ "%mkdir ../data\n!wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n!tar -zxf ../data/aclImdb_v1.tar.gz -C ../data", "mkdir: cannot create directory ‘../data’: File exists\n--2018-12-20 23:50:43-- http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\nResolving ai.stanford.edu (ai.stanford.edu)... 171.64.68.10\nConnecting to ai.stanford.edu (ai.stanford.edu)|171.64.68.10|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 84125825 (80M) [application/x-gzip]\nSaving to: ‘../data/aclImdb_v1.tar.gz’\n\n../data/aclImdb_v1. 100%[===================>] 80.23M 24.1MB/s in 4.6s \n\n2018-12-20 23:50:48 (17.5 MB/s) - ‘../data/aclImdb_v1.tar.gz’ saved [84125825/84125825]\n\n" ] ], [ [ "## Step 2: Preparing and Processing the data\n\nAlso, as in the XGBoost notebook, we will be doing some initial data processing. The first few steps are the same as in the XGBoost example. To begin with, we will read in each of the reviews and combine them into a single input structure. Then, we will split the dataset into a training set and a testing set.", "_____no_output_____" ] ], [ [ "import os\nimport glob\n\ndef read_imdb_data(data_dir='../data/aclImdb'):\n data = {}\n labels = {}\n \n for data_type in ['train', 'test']:\n data[data_type] = {}\n labels[data_type] = {}\n \n for sentiment in ['pos', 'neg']:\n data[data_type][sentiment] = []\n labels[data_type][sentiment] = []\n \n path = os.path.join(data_dir, data_type, sentiment, '*.txt')\n files = glob.glob(path)\n \n for f in files:\n with open(f) as review:\n data[data_type][sentiment].append(review.read())\n # Here we represent a positive review by '1' and a negative review by '0'\n labels[data_type][sentiment].append(1 if sentiment == 'pos' else 0)\n \n assert len(data[data_type][sentiment]) == len(labels[data_type][sentiment]), \\\n \"{}/{} data size does not match labels size\".format(data_type, sentiment)\n \n return data, labels", "_____no_output_____" ], [ "data, labels = read_imdb_data()\nprint(\"IMDB reviews: train = {} pos / {} neg, test = {} pos / {} neg\".format(\n len(data['train']['pos']), len(data['train']['neg']),\n len(data['test']['pos']), len(data['test']['neg'])))", "IMDB reviews: train = 12500 pos / 12500 neg, test = 12500 pos / 12500 neg\n" ] ], [ [ "Now that we've read the raw training and testing data from the downloaded dataset, we will combine the positive and negative reviews and shuffle the resulting records.", "_____no_output_____" ] ], [ [ "from sklearn.utils import shuffle\n\ndef prepare_imdb_data(data, labels):\n \"\"\"Prepare training and test sets from IMDb movie reviews.\"\"\"\n \n #Combine positive and negative reviews and labels\n data_train = data['train']['pos'] + data['train']['neg']\n data_test = data['test']['pos'] + data['test']['neg']\n labels_train = labels['train']['pos'] + labels['train']['neg']\n labels_test = labels['test']['pos'] + labels['test']['neg']\n \n #Shuffle reviews and corresponding labels within training and test sets\n data_train, labels_train = shuffle(data_train, labels_train)\n data_test, labels_test = shuffle(data_test, labels_test)\n \n # Return a unified training data, test data, training labels, test labets\n return data_train, data_test, labels_train, labels_test", "_____no_output_____" ], [ "train_X, test_X, train_y, test_y = prepare_imdb_data(data, labels)\nprint(\"IMDb reviews (combined): train = {}, test = {}\".format(len(train_X), len(test_X)))", "IMDb reviews (combined): train = 25000, test = 25000\n" ] ], [ [ "Now that we have our training and testing sets unified and prepared, we should do a quick check and see an example of the data our model will be trained on. This is generally a good idea as it allows you to see how each of the further processing steps affects the reviews and it also ensures that the data has been loaded correctly.", "_____no_output_____" ] ], [ [ "print(train_X[100])\nprint(train_y[100])", "It's a hideous little production, apt to give one nightmares as well as headaches. It's an unsightly blend of live action and ugly stop-motion animation. It's weird, but it's not the kind of fun, weird trip anyone optimistic might expect. It's the cold, inhuman, unfriendly, sickening, even creepy kind of weird. There is absolutely no reason to watch this movie. After all, Disney did a fantastic job with the same source material. And Cosgrove-Hall did far more attractive things with stop-motion.<br /><br />Interestingly, this is a French production. As such, it re-enforces the stereotype that the French have no concept of scary.\n0\n" ] ], [ [ "The first step in processing the reviews is to make sure that any html tags that appear should be removed. In addition we wish to tokenize our input, that way words such as *entertained* and *entertaining* are considered the same with regard to sentiment analysis.", "_____no_output_____" ] ], [ [ "import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import *\n\nimport re\nfrom bs4 import BeautifulSoup\n\ndef review_to_words(review):\n nltk.download(\"stopwords\", quiet=True)\n stemmer = PorterStemmer()\n \n text = BeautifulSoup(review, \"html.parser\").get_text() # Remove HTML tags\n text = re.sub(r\"[^a-zA-Z0-9]\", \" \", text.lower()) # Convert to lower case\n words = text.split() # Split string into words\n words = [w for w in words if w not in stopwords.words(\"english\")] # Remove stopwords\n words = [PorterStemmer().stem(w) for w in words] # stem\n \n return words", "_____no_output_____" ] ], [ [ "The `review_to_words` method defined above uses `BeautifulSoup` to remove any html tags that appear and uses the `nltk` package to tokenize the reviews. As a check to ensure we know how everything is working, try applying `review_to_words` to one of the reviews in the training set.", "_____no_output_____" ] ], [ [ "# TODO: Apply review_to_words to a review (train_X[100] or any other review)\nreview_to_words(train_X[100])", "_____no_output_____" ] ], [ [ "**Question:** Above we mentioned that `review_to_words` method removes html formatting and allows us to tokenize the words found in a review, for example, converting *entertained* and *entertaining* into *entertain* so that they are treated as though they are the same word. What else, if anything, does this method do to the input?", "_____no_output_____" ], [ "**Answer:**\nRemoves punctuation and converts everything to a comparable letter format, lower case. ", "_____no_output_____" ], [ "The method below applies the `review_to_words` method to each of the reviews in the training and testing datasets. In addition it caches the results. This is because performing this processing step can take a long time. This way if you are unable to complete the notebook in the current session, you can come back without needing to process the data a second time.", "_____no_output_____" ] ], [ [ "import pickle\n\ncache_dir = os.path.join(\"../cache\", \"sentiment_analysis\") # where to store cache files\nos.makedirs(cache_dir, exist_ok=True) # ensure cache directory exists\n\ndef preprocess_data(data_train, data_test, labels_train, labels_test,\n cache_dir=cache_dir, cache_file=\"preprocessed_data.pkl\"):\n \"\"\"Convert each review to words; read from cache if available.\"\"\"\n\n # If cache_file is not None, try to read from it first\n cache_data = None\n if cache_file is not None:\n try:\n with open(os.path.join(cache_dir, cache_file), \"rb\") as f:\n cache_data = pickle.load(f)\n print(\"Read preprocessed data from cache file:\", cache_file)\n except:\n pass # unable to read from cache, but that's okay\n \n # If cache is missing, then do the heavy lifting\n if cache_data is None:\n # Preprocess training and test data to obtain words for each review\n #words_train = list(map(review_to_words, data_train))\n #words_test = list(map(review_to_words, data_test))\n words_train = [review_to_words(review) for review in data_train]\n words_test = [review_to_words(review) for review in data_test]\n \n # Write to cache file for future runs\n if cache_file is not None:\n cache_data = dict(words_train=words_train, words_test=words_test,\n labels_train=labels_train, labels_test=labels_test)\n with open(os.path.join(cache_dir, cache_file), \"wb\") as f:\n pickle.dump(cache_data, f)\n print(\"Wrote preprocessed data to cache file:\", cache_file)\n else:\n # Unpack data loaded from cache file\n words_train, words_test, labels_train, labels_test = (cache_data['words_train'],\n cache_data['words_test'], cache_data['labels_train'], cache_data['labels_test'])\n \n return words_train, words_test, labels_train, labels_test", "_____no_output_____" ], [ "# Preprocess data\ntrain_X, test_X, train_y, test_y = preprocess_data(train_X, test_X, train_y, test_y)", "Read preprocessed data from cache file: preprocessed_data.pkl\n" ] ], [ [ "## Transform the data\n\nIn the XGBoost notebook we transformed the data from its word representation to a bag-of-words feature representation. For the model we are going to construct in this notebook we will construct a feature representation which is very similar. To start, we will represent each word as an integer. Of course, some of the words that appear in the reviews occur very infrequently and so likely don't contain much information for the purposes of sentiment analysis. The way we will deal with this problem is that we will fix the size of our working vocabulary and we will only include the words that appear most frequently. We will then combine all of the infrequent words into a single category and, in our case, we will label it as `1`.\n\nSince we will be using a recurrent neural network, it will be convenient if the length of each review is the same. To do this, we will fix a size for our reviews and then pad short reviews with the category 'no word' (which we will label `0`) and truncate long reviews.", "_____no_output_____" ], [ "### (TODO) Create a word dictionary\n\nTo begin with, we need to construct a way to map words that appear in the reviews to integers. Here we fix the size of our vocabulary (including the 'no word' and 'infrequent' categories) to be `5000` but you may wish to change this to see how it affects the model.\n\n> **TODO:** Complete the implementation for the `build_dict()` method below. Note that even though the vocab_size is set to `5000`, we only want to construct a mapping for the most frequently appearing `4998` words. This is because we want to reserve the special labels `0` for 'no word' and `1` for 'infrequent word'.", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom collections import Counter\nimport operator\n\ndef build_dict(data, vocab_size = 5000):\n \"\"\"Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer.\"\"\"\n \n # TODO: Determine how often each word appears in `data`. Note that `data` is a list of sentences and that a\n # sentence is a list of words.\n words = [word for sentence in data for word in sentence]\n word_counter = Counter(words)\n \n word_count = word_counter.most_common(vocab_size-2) # A dict storing the words that appear in the reviews along with how often they occur\n \n # TODO: Sort the words found in `data` so that sorted_words[0] is the most frequently appearing word and\n # sorted_words[-1] is the least frequently appearing word.\n \n sorted_word_count = sorted(word_count, reverse=True, key=lambda kv: kv[1])\n sorted_words = [word_count_itr[0] for word_count_itr in sorted_word_count]\n \n word_dict = {} # This is what we are building, a dictionary that translates words into integers\n for idx, word in enumerate(sorted_words[:vocab_size - 2]): # The -2 is so that we save room for the 'no word'\n word_dict[word] = idx + 2 # 'infrequent' labels\n \n return word_dict", "_____no_output_____" ], [ "word_dict = build_dict(train_X)", "_____no_output_____" ] ], [ [ "**Question:** What are the five most frequently appearing (tokenized) words in the training set? Does it makes sense that these words appear frequently in the training set?", "_____no_output_____" ], [ "**Answer:**\nmovie, film, one, like, time", "_____no_output_____" ] ], [ [ "# TODO: Use this space to determine the five most frequently appearing words in the training set.\nfor x in list(word_dict)[0:5]:\n print (x)", "movi\nfilm\none\nlike\ntime\n" ] ], [ [ "### Save `word_dict`\n\nLater on when we construct an endpoint which processes a submitted review we will need to make use of the `word_dict` which we have created. As such, we will save it to a file now for future use.", "_____no_output_____" ] ], [ [ "data_dir = '../data/pytorch' # The folder we will use for storing data\nif not os.path.exists(data_dir): # Make sure that the folder exists\n os.makedirs(data_dir)", "_____no_output_____" ], [ "with open(os.path.join(data_dir, 'word_dict.pkl'), \"wb\") as f:\n pickle.dump(word_dict, f)", "_____no_output_____" ] ], [ [ "### Transform the reviews\n\nNow that we have our word dictionary which allows us to transform the words appearing in the reviews into integers, it is time to make use of it and convert our reviews to their integer sequence representation, making sure to pad or truncate to a fixed length, which in our case is `500`.", "_____no_output_____" ] ], [ [ "def convert_and_pad(word_dict, sentence, pad=500):\n NOWORD = 0 # We will use 0 to represent the 'no word' category\n INFREQ = 1 # and we use 1 to represent the infrequent words, i.e., words not appearing in word_dict\n \n working_sentence = [NOWORD] * pad\n \n for word_index, word in enumerate(sentence[:pad]):\n if word in word_dict:\n working_sentence[word_index] = word_dict[word]\n else:\n working_sentence[word_index] = INFREQ\n \n return working_sentence, min(len(sentence), pad)\n\ndef convert_and_pad_data(word_dict, data, pad=500):\n result = []\n lengths = []\n \n for sentence in data:\n converted, leng = convert_and_pad(word_dict, sentence, pad)\n result.append(converted)\n lengths.append(leng)\n \n return np.array(result), np.array(lengths)", "_____no_output_____" ], [ "train_X, train_X_len = convert_and_pad_data(word_dict, train_X)\ntest_X, test_X_len = convert_and_pad_data(word_dict, test_X)", "_____no_output_____" ] ], [ [ "As a quick check to make sure that things are working as intended, check to see what one of the reviews in the training set looks like after having been processeed. Does this look reasonable? What is the length of a review in the training set?", "_____no_output_____" ] ], [ [ "# Use this cell to examine one of the processed reviews to make sure everything is working as intended.\ntrain_X[100]", "_____no_output_____" ] ], [ [ "**Question:** In the cells above we use the `preprocess_data` and `convert_and_pad_data` methods to process both the training and testing set. Why or why not might this be a problem?", "_____no_output_____" ], [ "**Answer:**\nThere should be no complications as neither sampling is mutating the word_dict state and both sets are processed independant of each other. This means that even though they run the same function, neither will impact the other.", "_____no_output_____" ], [ "## Step 3: Upload the data to S3\n\nAs in the XGBoost notebook, we will need to upload the training dataset to S3 in order for our training code to access it. For now we will save it locally and we will upload to S3 later on.\n\n### Save the processed training dataset locally\n\nIt is important to note the format of the data that we are saving as we will need to know it when we write the training code. In our case, each row of the dataset has the form `label`, `length`, `review[500]` where `review[500]` is a sequence of `500` integers representing the words in the review.", "_____no_output_____" ] ], [ [ "import pandas as pd\n \npd.concat([pd.DataFrame(train_y), pd.DataFrame(train_X_len), pd.DataFrame(train_X)], axis=1) \\\n .to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False)", "_____no_output_____" ] ], [ [ "### Uploading the training data\n\n\nNext, we need to upload the training data to the SageMaker default S3 bucket so that we can provide access to it while training our model.", "_____no_output_____" ] ], [ [ "import sagemaker\n\nsagemaker_session = sagemaker.Session()\n\nbucket = sagemaker_session.default_bucket()\nprefix = 'sagemaker/sentiment_rnn'\n\nrole = sagemaker.get_execution_role()", "_____no_output_____" ], [ "input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix)", "_____no_output_____" ] ], [ [ "**NOTE:** The cell above uploads the entire contents of our data directory. This includes the `word_dict.pkl` file. This is fortunate as we will need this later on when we create an endpoint that accepts an arbitrary review. For now, we will just take note of the fact that it resides in the data directory (and so also in the S3 training bucket) and that we will need to make sure it gets saved in the model directory.", "_____no_output_____" ], [ "## Step 4: Build and Train the PyTorch Model\n\nIn the XGBoost notebook we discussed what a model is in the SageMaker framework. In particular, a model comprises three objects\n\n - Model Artifacts,\n - Training Code, and\n - Inference Code,\n \neach of which interact with one another. In the XGBoost example we used training and inference code that was provided by Amazon. Here we will still be using containers provided by Amazon with the added benefit of being able to include our own custom code.\n\nWe will start by implementing our own neural network in PyTorch along with a training script. For the purposes of this project we have provided the necessary model object in the `model.py` file, inside of the `train` folder. You can see the provided implementation by running the cell below.", "_____no_output_____" ] ], [ [ "!pygmentize train/model.py", "\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch.nn\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnn\u001b[39;49;00m\r\n\r\n\u001b[34mclass\u001b[39;49;00m \u001b[04m\u001b[32mLSTMClassifier\u001b[39;49;00m(nn.Module):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m This is the simple RNN model we will be using to perform Sentiment Analysis.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n\r\n \u001b[34mdef\u001b[39;49;00m \u001b[32m__init__\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, embedding_dim, hidden_dim, vocab_size):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m Initialize the model by settingg up the various layers.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n \u001b[36msuper\u001b[39;49;00m(LSTMClassifier, \u001b[36mself\u001b[39;49;00m).\u001b[32m__init__\u001b[39;49;00m()\r\n\r\n \u001b[36mself\u001b[39;49;00m.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=\u001b[34m0\u001b[39;49;00m)\r\n \u001b[36mself\u001b[39;49;00m.lstm = nn.LSTM(embedding_dim, hidden_dim)\r\n \u001b[36mself\u001b[39;49;00m.dense = nn.Linear(in_features=hidden_dim, out_features=\u001b[34m1\u001b[39;49;00m)\r\n \u001b[36mself\u001b[39;49;00m.sig = nn.Sigmoid()\r\n \r\n \u001b[36mself\u001b[39;49;00m.word_dict = \u001b[36mNone\u001b[39;49;00m\r\n\r\n \u001b[34mdef\u001b[39;49;00m \u001b[32mforward\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, x):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m Perform a forward pass of our model on some input.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n x = x.t()\r\n lengths = x[\u001b[34m0\u001b[39;49;00m,:]\r\n reviews = x[\u001b[34m1\u001b[39;49;00m:,:]\r\n embeds = \u001b[36mself\u001b[39;49;00m.embedding(reviews)\r\n lstm_out, _ = \u001b[36mself\u001b[39;49;00m.lstm(embeds)\r\n out = \u001b[36mself\u001b[39;49;00m.dense(lstm_out)\r\n out = out[lengths - \u001b[34m1\u001b[39;49;00m, \u001b[36mrange\u001b[39;49;00m(\u001b[36mlen\u001b[39;49;00m(lengths))]\r\n \u001b[34mreturn\u001b[39;49;00m \u001b[36mself\u001b[39;49;00m.sig(out.squeeze())\r\n" ] ], [ [ "The important takeaway from the implementation provided is that there are three parameters that we may wish to tweak to improve the performance of our model. These are the embedding dimension, the hidden dimension and the size of the vocabulary. We will likely want to make these parameters configurable in the training script so that if we wish to modify them we do not need to modify the script itself. We will see how to do this later on. To start we will write some of the training code in the notebook so that we can more easily diagnose any issues that arise.\n\nFirst we will load a small portion of the training data set to use as a sample. It would be very time consuming to try and train the model completely in the notebook as we do not have access to a gpu and the compute instance that we are using is not particularly powerful. However, we can work on a small bit of the data to get a feel for how our training script is behaving.", "_____no_output_____" ] ], [ [ "import torch\nimport torch.utils.data\n\n# Read in only the first 250 rows\ntrain_sample = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None, names=None, nrows=250)\n\n# Turn the input pandas dataframe into tensors\ntrain_sample_y = torch.from_numpy(train_sample[[0]].values).float().squeeze()\ntrain_sample_X = torch.from_numpy(train_sample.drop([0], axis=1).values).long()\n\n# Build the dataset\ntrain_sample_ds = torch.utils.data.TensorDataset(train_sample_X, train_sample_y)\n# Build the dataloader\ntrain_sample_dl = torch.utils.data.DataLoader(train_sample_ds, batch_size=50)", "_____no_output_____" ] ], [ [ "### (TODO) Writing the training method\n\nNext we need to write the training code itself. This should be very similar to training methods that you have written before to train PyTorch models. We will leave any difficult aspects such as model saving / loading and parameter loading until a little later.", "_____no_output_____" ] ], [ [ "import datetime\nimport torch.nn as nn\n\ndef train(model, train_loader, epochs, optimizer, loss_fn, device):\n for epoch in range(1, epochs + 1):\n model.train()\n total_loss = 0\n for batch in train_loader: \n batch_X, batch_y = batch\n \n batch_X = batch_X.to(device)\n batch_y = batch_y.to(device)\n \n # TODO: Complete this train method to train the model provided.\n # forward, back prop\n\n model.zero_grad()\n # outputs from the rnn\n prediction = model.forward(batch_X)\n # perform backpropagation and optimization\n # calculate the loss\n loss = loss_fn(prediction, batch_y)\n\n # perform backprop and update weights\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), 5)\n optimizer.step()\n \n total_loss += loss.data.item()\n \n print(\"{} Epoch: {}, BCELoss: {}\".format(datetime.datetime.now(), epoch, total_loss / len(train_loader)))", "_____no_output_____" ] ], [ [ "Supposing we have the training method above, we will test that it is working by writing a bit of code in the notebook that executes our training method on the small sample training set that we loaded earlier. The reason for doing this in the notebook is so that we have an opportunity to fix any errors that arise early when they are easier to diagnose.", "_____no_output_____" ] ], [ [ "import torch.optim as optim\nfrom train.model import LSTMClassifier\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = LSTMClassifier(32, 100, 5000).to(device)\noptimizer = optim.Adam(model.parameters())\nloss_fn = torch.nn.BCELoss()\n\ntrain(model, train_sample_dl, 5, optimizer, loss_fn, device)", "2018-12-20 23:52:07.894054 Epoch: 1, BCELoss: 0.6928025007247924\n2018-12-20 23:52:13.019019 Epoch: 2, BCELoss: 0.6818889498710632\n2018-12-20 23:52:18.125433 Epoch: 3, BCELoss: 0.6714245796203613\n2018-12-20 23:52:23.241152 Epoch: 4, BCELoss: 0.6588106632232666\n2018-12-20 23:52:28.252511 Epoch: 5, BCELoss: 0.6415898561477661\n" ] ], [ [ "In order to construct a PyTorch model using SageMaker we must provide SageMaker with a training script. We may optionally include a directory which will be copied to the container and from which our training code will be run. When the training container is executed it will check the uploaded directory (if there is one) for a `requirements.txt` file and install any required Python libraries, after which the training script will be run.", "_____no_output_____" ], [ "### (TODO) Training the model\n\nWhen a PyTorch model is constructed in SageMaker, an entry point must be specified. This is the Python file which will be executed when the model is trained. Inside of the `train` directory is a file called `train.py` which has been provided and which contains most of the necessary code to train our model. The only thing that is missing is the implementation of the `train()` method which you wrote earlier in this notebook.\n\n**TODO**: Copy the `train()` method written above and paste it into the `train/train.py` file where required.\n\nThe way that SageMaker passes hyperparameters to the training script is by way of arguments. These arguments can then be parsed and used in the training script. To see how this is done take a look at the provided `train/train.py` file.", "_____no_output_____" ] ], [ [ "from sagemaker.pytorch import PyTorch\n\nestimator = PyTorch(entry_point=\"train.py\",\n source_dir=\"train\",\n role=role,\n framework_version='0.4.0',\n train_instance_count=1,\n train_instance_type='ml.p2.xlarge',\n hyperparameters={\n 'epochs': 10,\n 'hidden_dim': 200,\n })", "_____no_output_____" ], [ "estimator.fit({'training': input_data})", "INFO:sagemaker:Creating training-job with name: sagemaker-pytorch-2018-12-20-23-52-28-322\n" ] ], [ [ "## Step 5: Testing the model\n\nAs mentioned at the top of this notebook, we will be testing this model by first deploying it and then sending the testing data to the deployed endpoint. We will do this so that we can make sure that the deployed model is working correctly.\n\n## Step 6: Deploy the model for testing\n\nNow that we have trained our model, we would like to test it to see how it performs. Currently our model takes input of the form `review_length, review[500]` where `review[500]` is a sequence of `500` integers which describe the words present in the review, encoded using `word_dict`. Fortunately for us, SageMaker provides built-in inference code for models with simple inputs such as this.\n\nThere is one thing that we need to provide, however, and that is a function which loads the saved model. This function must be called `model_fn()` and takes as its only parameter a path to the directory where the model artifacts are stored. This function must also be present in the python file which we specified as the entry point. In our case the model loading function has been provided and so no changes need to be made.\n\n**NOTE**: When the built-in inference code is run it must import the `model_fn()` method from the `train.py` file. This is why the training code is wrapped in a main guard ( ie, `if __name__ == '__main__':` )\n\nSince we don't need to change anything in the code that was uploaded during training, we can simply deploy the current model as-is.\n\n**NOTE:** When deploying a model you are asking SageMaker to launch an compute instance that will wait for data to be sent to it. As a result, this compute instance will continue to run until *you* shut it down. This is important to know since the cost of a deployed endpoint depends on how long it has been running for.\n\nIn other words **If you are no longer using a deployed endpoint, shut it down!**\n\n**TODO:** Deploy the trained model.", "_____no_output_____" ] ], [ [ "# TODO: Deploy the trained model\n#https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/pytorch/README.rst\npredictor = estimator.deploy(instance_type='ml.m4.xlarge',\n initial_instance_count=1)", "INFO:sagemaker:Creating model with name: sagemaker-pytorch-2018-12-20-23-52-28-322\nINFO:sagemaker:Creating endpoint with name sagemaker-pytorch-2018-12-20-23-52-28-322\n" ] ], [ [ "## Step 7 - Use the model for testing\n\nOnce deployed, we can read in the test data and send it off to our deployed model to get some results. Once we collect all of the results we can determine how accurate our model is.", "_____no_output_____" ] ], [ [ "test_X = pd.concat([pd.DataFrame(test_X_len), pd.DataFrame(test_X)], axis=1)", "_____no_output_____" ], [ "# We split the data into chunks and send each chunk seperately, accumulating the results.\n\ndef predict(data, rows=512):\n split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))\n predictions = np.array([])\n for array in split_array:\n predictions = np.append(predictions, predictor.predict(array))\n \n return predictions", "_____no_output_____" ], [ "predictions = predict(test_X.values)\npredictions = [round(num) for num in predictions]", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(test_y, predictions)", "_____no_output_____" ] ], [ [ "**Question:** How does this model compare to the XGBoost model you created earlier? Why might these two models perform differently on this dataset? Which do *you* think is better for sentiment analysis?", "_____no_output_____" ], [ "**Answer:**\nThe XGBoost model is key to performance and speed. If the model needs to be trained quickly due to limited resources or a limited data set, XGBoost will outperform an untrained or little-trained nerual net. Normally if the proper sized data set is available and proper training can occur on the RNN, it will have a higher accuracy than the XGBoost. \n\nI would recommend the RNN for two reasons:\n1 - If we are taking the time to train a network to be used in the wild, we want it to be as accurate as possible so the investment of time is assumed.\n2 - If more data becomes available, a NN can perform further training from its current state, while a decision tree would need to be retrained from the initial data and new data.", "_____no_output_____" ], [ "### (TODO) More testing\n\nWe now have a trained model which has been deployed and which we can send processed reviews to and which returns the predicted sentiment. However, ultimately we would like to be able to send our model an unprocessed review. That is, we would like to send the review itself as a string. For example, suppose we wish to send the following review to our model.", "_____no_output_____" ] ], [ [ "test_review = 'The simplest pleasures in life are the best, and this film is one of them. Combining a rather basic storyline of love and adventure this movie transcends the usual weekend fair with wit and unmitigated charm.'", "_____no_output_____" ] ], [ [ "The question we now need to answer is, how do we send this review to our model?\n\nRecall in the first section of this notebook we did a bunch of data processing to the IMDb dataset. In particular, we did two specific things to the provided reviews.\n - Removed any html tags and stemmed the input\n - Encoded the review as a sequence of integers using `word_dict`\n \nIn order process the review we will need to repeat these two steps.\n\n**TODO**: Using the `review_to_words` and `convert_and_pad` methods from section one, convert `test_review` into a numpy array `test_data` suitable to send to our model. Remember that our model expects input of the form `review_length, review[500]`.", "_____no_output_____" ] ], [ [ "# TODO: Convert test_review into a form usable by the model and save the results in test_data\nreview_words = review_to_words(test_review)\nstandardized_phrase = convert_and_pad(word_dict, review_words)[0]\ntest_data = np.asarray([standardized_phrase])", "_____no_output_____" ] ], [ [ "Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review.", "_____no_output_____" ] ], [ [ "predictor.predict(test_data)", "_____no_output_____" ] ], [ [ "Since the return value of our model is close to `1`, we can be certain that the review we submitted is positive.", "_____no_output_____" ], [ "### Delete the endpoint\n\nOf course, just like in the XGBoost notebook, once we've deployed an endpoint it continues to run until we tell it to shut down. Since we are done using our endpoint for now, we can delete it.", "_____no_output_____" ] ], [ [ "estimator.delete_endpoint()", "INFO:sagemaker:Deleting endpoint with name: sagemaker-pytorch-2018-12-20-23-52-28-322\n" ] ], [ [ "## Step 6 (again) - Deploy the model for the web app\n\nNow that we know that our model is working, it's time to create some custom inference code so that we can send the model a review which has not been processed and have it determine the sentiment of the review.\n\nAs we saw above, by default the estimator which we created, when deployed, will use the entry script and directory which we provided when creating the model. However, since we now wish to accept a string as input and our model expects a processed review, we need to write some custom inference code.\n\nWe will store the code that we write in the `serve` directory. Provided in this directory is the `model.py` file that we used to construct our model, a `utils.py` file which contains the `review_to_words` and `convert_and_pad` pre-processing functions which we used during the initial data processing, and `predict.py`, the file which will contain our custom inference code. Note also that `requirements.txt` is present which will tell SageMaker what Python libraries are required by our custom inference code.\n\nWhen deploying a PyTorch model in SageMaker, you are expected to provide four functions which the SageMaker inference container will use.\n - `model_fn`: This function is the same function that we used in the training script and it tells SageMaker how to load our model.\n - `input_fn`: This function receives the raw serialized input that has been sent to the model's endpoint and its job is to de-serialize and make the input available for the inference code.\n - `output_fn`: This function takes the output of the inference code and its job is to serialize this output and return it to the caller of the model's endpoint.\n - `predict_fn`: The heart of the inference script, this is where the actual prediction is done and is the function which you will need to complete.\n\nFor the simple website that we are constructing during this project, the `input_fn` and `output_fn` methods are relatively straightforward. We only require being able to accept a string as input and we expect to return a single value as output. You might imagine though that in a more complex application the input or output may be image data or some other binary data which would require some effort to serialize.\n\n### (TODO) Writing inference code\n\nBefore writing our custom inference code, we will begin by taking a look at the code which has been provided.", "_____no_output_____" ] ], [ [ "!pygmentize serve/predict.py", "\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36margparse\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mjson\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mos\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mpickle\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msys\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msagemaker_containers\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mpandas\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mpd\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mnumpy\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnp\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch.nn\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnn\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch.optim\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36moptim\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch.utils.data\u001b[39;49;00m\r\n\r\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mmodel\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m LSTMClassifier\r\n\r\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mutils\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m review_to_words, convert_and_pad\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32mmodel_fn\u001b[39;49;00m(model_dir):\r\n \u001b[33m\"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\u001b[39;49;00m\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mLoading model.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n\r\n \u001b[37m# First, load the parameters used to create the model.\u001b[39;49;00m\r\n model_info = {}\r\n model_info_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mmodel_info.pth\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(model_info_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model_info = torch.load(f)\r\n\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mmodel_info: {}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(model_info))\r\n\r\n \u001b[37m# Determine the device and construct the model.\u001b[39;49;00m\r\n device = torch.device(\u001b[33m\"\u001b[39;49;00m\u001b[33mcuda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[34mif\u001b[39;49;00m torch.cuda.is_available() \u001b[34melse\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mcpu\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n model = LSTMClassifier(model_info[\u001b[33m'\u001b[39;49;00m\u001b[33membedding_dim\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m], model_info[\u001b[33m'\u001b[39;49;00m\u001b[33mhidden_dim\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m], model_info[\u001b[33m'\u001b[39;49;00m\u001b[33mvocab_size\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m])\r\n\r\n \u001b[37m# Load the store model parameters.\u001b[39;49;00m\r\n model_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mmodel.pth\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(model_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model.load_state_dict(torch.load(f))\r\n\r\n \u001b[37m# Load the saved word_dict.\u001b[39;49;00m\r\n word_dict_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mword_dict.pkl\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(word_dict_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model.word_dict = pickle.load(f)\r\n\r\n model.to(device).eval()\r\n\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mDone loading model.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m model\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32minput_fn\u001b[39;49;00m(serialized_input_data, content_type):\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mDeserializing the input data.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mif\u001b[39;49;00m content_type == \u001b[33m'\u001b[39;49;00m\u001b[33mtext/plain\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m:\r\n data = serialized_input_data.decode(\u001b[33m'\u001b[39;49;00m\u001b[33mutf-8\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m data\r\n \u001b[34mraise\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mRequested unsupported ContentType in content_type: \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m + content_type)\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32moutput_fn\u001b[39;49;00m(prediction_output, accept):\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mSerializing the generated output.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m \u001b[36mstr\u001b[39;49;00m(prediction_output)\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32mpredict_fn\u001b[39;49;00m(input_data, model):\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mInferring sentiment of input data.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n\r\n device = torch.device(\u001b[33m\"\u001b[39;49;00m\u001b[33mcuda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[34mif\u001b[39;49;00m torch.cuda.is_available() \u001b[34melse\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mcpu\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n \r\n \u001b[34mif\u001b[39;49;00m model.word_dict \u001b[35mis\u001b[39;49;00m \u001b[36mNone\u001b[39;49;00m:\r\n \u001b[34mraise\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mModel has not been loaded properly, no word_dict.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \r\n \u001b[37m# TODO: Process input_data so that it is ready to be sent to our model.\u001b[39;49;00m\r\n \u001b[37m# You should produce two variables:\u001b[39;49;00m\r\n \u001b[37m# data_X - A sequence of length 500 which represents the converted review\u001b[39;49;00m\r\n \u001b[37m# data_len - The length of the review\u001b[39;49;00m\r\n review_words = review_to_words(input_data)\r\n data_X, data_len = convert_and_pad(model.word_dict, review_words)\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mtype of input data {}\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m.format(\u001b[36mtype\u001b[39;49;00m(data_X)))\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mtype of input data shape {}\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m.format(\u001b[36mtype\u001b[39;49;00m(data_X[\u001b[34m0\u001b[39;49;00m])))\r\n \u001b[37m# Using data_X and data_len we construct an appropriate input tensor. Remember\u001b[39;49;00m\r\n \u001b[37m# that our model expects input data of the form 'len, review[500]'.\u001b[39;49;00m\r\n data_pack = np.hstack((data_len, data_X))\r\n data_pack = data_pack.reshape(\u001b[34m1\u001b[39;49;00m, -\u001b[34m1\u001b[39;49;00m)\r\n \r\n data = torch.from_numpy(data_pack)\r\n data = data.to(device)\r\n\r\n \u001b[37m# Make sure to put the model into evaluation mode\u001b[39;49;00m\r\n model.eval()\r\n\r\n \u001b[37m# TODO: Compute the result of applying the model to the input data. The variable `result` should\u001b[39;49;00m\r\n \u001b[37m# be a numpy array which contains a single integer which is either 1 or 0\u001b[39;49;00m\r\n result = model.forward(data)\r\n \r\n resu = result.item()\r\n rounded_result = \u001b[36mround\u001b[39;49;00m(resu)\r\n \r\n \u001b[34mreturn\u001b[39;49;00m rounded_result\r\n" ] ], [ [ "As mentioned earlier, the `model_fn` method is the same as the one provided in the training code and the `input_fn` and `output_fn` methods are very simple and your task will be to complete the `predict_fn` method. Make sure that you save the completed file as `predict.py` in the `serve` directory.\n\n**TODO**: Complete the `predict_fn()` method in the `serve/predict.py` file.", "_____no_output_____" ], [ "### Deploying the model\n\nNow that the custom inference code has been written, we will create and deploy our model. To begin with, we need to construct a new PyTorchModel object which points to the model artifacts created during training and also points to the inference code that we wish to use. Then we can call the deploy method to launch the deployment container.\n\n**NOTE**: The default behaviour for a deployed PyTorch model is to assume that any input passed to the predictor is a `numpy` array. In our case we want to send a string so we need to construct a simple wrapper around the `RealTimePredictor` class to accomodate simple strings. In a more complicated situation you may want to provide a serialization object, for example if you wanted to sent image data.", "_____no_output_____" ] ], [ [ "from sagemaker.predictor import RealTimePredictor\nfrom sagemaker.pytorch import PyTorchModel\n\nclass StringPredictor(RealTimePredictor):\n def __init__(self, endpoint_name, sagemaker_session):\n super(StringPredictor, self).__init__(endpoint_name, sagemaker_session, content_type='text/plain')\n\nmodel = PyTorchModel(model_data=estimator.model_data,\n role = role,\n framework_version='0.4.0',\n entry_point='predict.py',\n source_dir='serve',\n predictor_cls=StringPredictor)\npredictor = model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')", "INFO:sagemaker:Creating model with name: sagemaker-pytorch-2018-12-21-00-09-12-888\nINFO:sagemaker:Creating endpoint with name sagemaker-pytorch-2018-12-21-00-09-12-888\n" ] ], [ [ "### Testing the model\n\nNow that we have deployed our model with the custom inference code, we should test to see if everything is working. Here we test our model by loading the first `250` positive and negative reviews and send them to the endpoint, then collect the results. The reason for only sending some of the data is that the amount of time it takes for our model to process the input and then perform inference is quite long and so testing the entire data set would be prohibitive.", "_____no_output_____" ] ], [ [ "import glob\n\ndef test_reviews(data_dir='../data/aclImdb', stop=250):\n \n results = []\n ground = []\n \n # We make sure to test both positive and negative reviews \n for sentiment in ['pos', 'neg']:\n \n path = os.path.join(data_dir, 'test', sentiment, '*.txt')\n files = glob.glob(path)\n \n files_read = 0\n \n print('Starting ', sentiment, ' files')\n \n # Iterate through the files and send them to the predictor\n for f in files:\n with open(f) as review:\n # First, we store the ground truth (was the review positive or negative)\n if sentiment == 'pos':\n ground.append(1)\n else:\n ground.append(0)\n # Read in the review and convert to 'utf-8' for transmission via HTTP\n review_input = review.read()\n review_input = review_input.encode('utf-8')\n # Send the review to the predictor and store the results\n results.append(int(predictor.predict(review_input)))\n \n # Sending reviews to our endpoint one at a time takes a while so we\n # only send a small number of reviews\n files_read += 1\n if files_read == stop:\n break\n \n return ground, results", "_____no_output_____" ], [ "ground, results = test_reviews()", "Starting pos files\nStarting neg files\n" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(ground, results)", "_____no_output_____" ] ], [ [ "As an additional test, we can try sending the `test_review` that we looked at earlier.", "_____no_output_____" ] ], [ [ "predictor.predict(test_review)", "_____no_output_____" ] ], [ [ "Now that we know our endpoint is working as expected, we can set up the web page that will interact with it. If you don't have time to finish the project now, make sure to skip down to the end of this notebook and shut down your endpoint. You can deploy it again when you come back.", "_____no_output_____" ], [ "## Step 7 (again): Use the model for the web app\n\n> **TODO:** This entire section and the next contain tasks for you to complete, mostly using the AWS console.\n\nSo far we have been accessing our model endpoint by constructing a predictor object which uses the endpoint and then just using the predictor object to perform inference. What if we wanted to create a web app which accessed our model? The way things are set up currently makes that not possible since in order to access a SageMaker endpoint the app would first have to authenticate with AWS using an IAM role which included access to SageMaker endpoints. However, there is an easier way! We just need to use some additional AWS services.\n\n<img src=\"Web App Diagram.svg\">\n\nThe diagram above gives an overview of how the various services will work together. On the far right is the model which we trained above and which is deployed using SageMaker. On the far left is our web app that collects a user's movie review, sends it off and expects a positive or negative sentiment in return.\n\nIn the middle is where some of the magic happens. We will construct a Lambda function, which you can think of as a straightforward Python function that can be executed whenever a specified event occurs. We will give this function permission to send and recieve data from a SageMaker endpoint.\n\nLastly, the method we will use to execute the Lambda function is a new endpoint that we will create using API Gateway. This endpoint will be a url that listens for data to be sent to it. Once it gets some data it will pass that data on to the Lambda function and then return whatever the Lambda function returns. Essentially it will act as an interface that lets our web app communicate with the Lambda function.\n\n### Setting up a Lambda function\n\nThe first thing we are going to do is set up a Lambda function. This Lambda function will be executed whenever our public API has data sent to it. When it is executed it will receive the data, perform any sort of processing that is required, send the data (the review) to the SageMaker endpoint we've created and then return the result.\n\n#### Part A: Create an IAM Role for the Lambda function\n\nSince we want the Lambda function to call a SageMaker endpoint, we need to make sure that it has permission to do so. To do this, we will construct a role that we can later give the Lambda function.\n\nUsing the AWS Console, navigate to the **IAM** page and click on **Roles**. Then, click on **Create role**. Make sure that the **AWS service** is the type of trusted entity selected and choose **Lambda** as the service that will use this role, then click **Next: Permissions**.\n\nIn the search box type `sagemaker` and select the check box next to the **AmazonSageMakerFullAccess** policy. Then, click on **Next: Review**.\n\nLastly, give this role a name. Make sure you use a name that you will remember later on, for example `LambdaSageMakerRole`. Then, click on **Create role**.\n\n#### Part B: Create a Lambda function\n\nNow it is time to actually create the Lambda function.\n\nUsing the AWS Console, navigate to the AWS Lambda page and click on **Create a function**. When you get to the next page, make sure that **Author from scratch** is selected. Now, name your Lambda function, using a name that you will remember later on, for example `sentiment_analysis_func`. Make sure that the **Python 3.6** runtime is selected and then choose the role that you created in the previous part. Then, click on **Create Function**.\n\nOn the next page you will see some information about the Lambda function you've just created. If you scroll down you should see an editor in which you can write the code that will be executed when your Lambda function is triggered. In our example, we will use the code below. \n\n```python\n# We need to use the low-level library to interact with SageMaker since the SageMaker API\n# is not available natively through Lambda.\nimport boto3\n\ndef lambda_handler(event, context):\n\n # The SageMaker runtime is what allows us to invoke the endpoint that we've created.\n runtime = boto3.Session().client('sagemaker-runtime')\n\n # Now we use the SageMaker runtime to invoke our endpoint, sending the review we were given\n response = runtime.invoke_endpoint(EndpointName = '**ENDPOINT NAME HERE**', # The name of the endpoint we created\n ContentType = 'text/plain', # The data format that is expected\n Body = event['body']) # The actual review\n\n # The response is an HTTP response whose body contains the result of our inference\n result = response['Body'].read().decode('utf-8')\n\n return {\n 'statusCode' : 200,\n 'headers' : { 'Content-Type' : 'text/plain', 'Access-Control-Allow-Origin' : '*' },\n 'body' : result\n }\n```\n\nOnce you have copy and pasted the code above into the Lambda code editor, replace the `**ENDPOINT NAME HERE**` portion with the name of the endpoint that we deployed earlier. You can determine the name of the endpoint using the code cell below.", "_____no_output_____" ] ], [ [ "predictor.endpoint", "_____no_output_____" ] ], [ [ "Once you have added the endpoint name to the Lambda function, click on **Save**. Your Lambda function is now up and running. Next we need to create a way for our web app to execute the Lambda function.\n\n### Setting up API Gateway\n\nNow that our Lambda function is set up, it is time to create a new API using API Gateway that will trigger the Lambda function we have just created.\n\nUsing AWS Console, navigate to **Amazon API Gateway** and then click on **Get started**.\n\nOn the next page, make sure that **New API** is selected and give the new api a name, for example, `sentiment_analysis_api`. Then, click on **Create API**.\n\nNow we have created an API, however it doesn't currently do anything. What we want it to do is to trigger the Lambda function that we created earlier.\n\nSelect the **Actions** dropdown menu and click **Create Method**. A new blank method will be created, select its dropdown menu and select **POST**, then click on the check mark beside it.\n\nFor the integration point, make sure that **Lambda Function** is selected and click on the **Use Lambda Proxy integration**. This option makes sure that the data that is sent to the API is then sent directly to the Lambda function with no processing. It also means that the return value must be a proper response object as it will also not be processed by API Gateway.\n\nType the name of the Lambda function you created earlier into the **Lambda Function** text entry box and then click on **Save**. Click on **OK** in the pop-up box that then appears, giving permission to API Gateway to invoke the Lambda function you created.\n\nThe last step in creating the API Gateway is to select the **Actions** dropdown and click on **Deploy API**. You will need to create a new Deployment stage and name it anything you like, for example `prod`.\n\nYou have now successfully set up a public API to access your SageMaker model. Make sure to copy or write down the URL provided to invoke your newly created public API as this will be needed in the next step. This URL can be found at the top of the page, highlighted in blue next to the text **Invoke URL**.", "_____no_output_____" ], [ "## Step 4: Deploying our web app\n\nNow that we have a publicly available API, we can start using it in a web app. For our purposes, we have provided a simple static html file which can make use of the public api you created earlier.\n\nIn the `website` folder there should be a file called `index.html`. Download the file to your computer and open that file up in a text editor of your choice. There should be a line which contains **\\*\\*REPLACE WITH PUBLIC API URL\\*\\***. Replace this string with the url that you wrote down in the last step and then save the file.\n\nNow, if you open `index.html` on your local computer, your browser will behave as a local web server and you can use the provided site to interact with your SageMaker model.\n\nIf you'd like to go further, you can host this html file anywhere you'd like, for example using github or hosting a static site on Amazon's S3. Once you have done this you can share the link with anyone you'd like and have them play with it too!\n\n> **Important Note** In order for the web app to communicate with the SageMaker endpoint, the endpoint has to actually be deployed and running. This means that you are paying for it. Make sure that the endpoint is running when you want to use the web app but that you shut it down when you don't need it, otherwise you will end up with a surprisingly large AWS bill.\n\n**TODO:** Make sure that you include the edited `index.html` file in your project submission.", "_____no_output_____" ], [ "Now that your web app is working, trying playing around with it and see how well it works.\n\n**Question**: Give an example of a review that you entered into your web app. What was the predicted sentiment of your example review?", "_____no_output_____" ], [ "**Answer:**\nAquaman was a movie from down under. It combined MMA fighting styles with fish. By far the best movie DC Comics could have asked for. I will likely be going again before the week is out.\n\nIt was POSITIVE", "_____no_output_____" ], [ "### Delete the endpoint\n\nRemember to always shut down your endpoint if you are no longer using it. You are charged for the length of time that the endpoint is running so if you forget and leave it on you could end up with an unexpectedly large bill.", "_____no_output_____" ] ], [ [ "predictor.delete_endpoint()", "INFO:sagemaker:Deleting endpoint with name: sagemaker-pytorch-2018-12-21-00-09-12-888\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", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
ec51d4771adf1ebcae8c618ff06287d6e4e7e1a2
21,320
ipynb
Jupyter Notebook
notebooks_archive_10112014/thesis_functions/astro.ipynb
aerosara/thesis
55bd84e8d4b4bffa8f7526bd5b94ddef80911f99
[ "MIT" ]
null
null
null
notebooks_archive_10112014/thesis_functions/astro.ipynb
aerosara/thesis
55bd84e8d4b4bffa8f7526bd5b94ddef80911f99
[ "MIT" ]
null
null
null
notebooks_archive_10112014/thesis_functions/astro.ipynb
aerosara/thesis
55bd84e8d4b4bffa8f7526bd5b94ddef80911f99
[ "MIT" ]
null
null
null
38.276481
175
0.485976
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ec51d513be966e429588feac48b8ef2327071aa7
531,757
ipynb
Jupyter Notebook
Projects/USA housing price prediction/Linear Regression - Project .ipynb
Satyam-Bhalla/Machine-Learning-Practice
0ae4b8ae9501fb0a22b236dbc508fe6b32e21f42
[ "MIT" ]
null
null
null
Projects/USA housing price prediction/Linear Regression - Project .ipynb
Satyam-Bhalla/Machine-Learning-Practice
0ae4b8ae9501fb0a22b236dbc508fe6b32e21f42
[ "MIT" ]
null
null
null
Projects/USA housing price prediction/Linear Regression - Project .ipynb
Satyam-Bhalla/Machine-Learning-Practice
0ae4b8ae9501fb0a22b236dbc508fe6b32e21f42
[ "MIT" ]
2
2019-03-28T12:31:48.000Z
2019-10-31T05:40:08.000Z
542.056065
308,058
0.931264
[ [ [ "\n___\n# Linear Regression - Project Exercise\n\nCongratulations! You just got some contract work with an Ecommerce company based in New York City that sells clothing online but they also have in-store style and clothing advice sessions. Customers come in to the store, have sessions/meetings with a personal stylist, then they can go home and order either on a mobile app or website for the clothes they want.\n\nThe company is trying to decide whether to focus their efforts on their mobile app experience or their website. They've hired you on contract to help them figure it out! Let's get started!\n\nJust follow the steps below to analyze the customer data (it's fake, don't worry I didn't give you real credit card numbers or emails).", "_____no_output_____" ], [ "## Imports\n** Import pandas, numpy, matplotlib,and seaborn. Then set %matplotlib inline \n(You'll import sklearn as you need it.)**", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Get the Data\n\nWe'll work with the Ecommerce Customers csv file from the company. It has Customer info, suchas Email, Address, and their color Avatar. Then it also has numerical value columns:\n\n* Avg. Session Length: Average session of in-store style advice sessions.\n* Time on App: Average time spent on App in minutes\n* Time on Website: Average time spent on Website in minutes\n* Length of Membership: How many years the customer has been a member. \n\n** Read in the Ecommerce Customers csv file as a DataFrame called customers.**", "_____no_output_____" ] ], [ [ "customers = pd.read_csv(\"Ecommerce Customers\")", "_____no_output_____" ] ], [ [ "**Check the head of customers, and check out its info() and describe() methods.**", "_____no_output_____" ] ], [ [ "customers.head()", "_____no_output_____" ], [ "customers.describe()", "_____no_output_____" ], [ "customers.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 500 entries, 0 to 499\nData columns (total 8 columns):\nEmail 500 non-null object\nAddress 500 non-null object\nAvatar 500 non-null object\nAvg. Session Length 500 non-null float64\nTime on App 500 non-null float64\nTime on Website 500 non-null float64\nLength of Membership 500 non-null float64\nYearly Amount Spent 500 non-null float64\ndtypes: float64(5), object(3)\nmemory usage: 31.3+ KB\n" ] ], [ [ "## Exploratory Data Analysis\n\n**Let's explore the data!**\n\nFor the rest of the exercise we'll only be using the numerical data of the csv file.\n___\n**Use seaborn to create a jointplot to compare the Time on Website and Yearly Amount Spent columns. Does the correlation make sense?**", "_____no_output_____" ] ], [ [ "sns.set_palette(\"GnBu_d\")\nsns.set_style('whitegrid')", "_____no_output_____" ], [ "# More time on site, more money spent.\nsns.jointplot(x='Time on Website',y='Yearly Amount Spent',data=customers)", "_____no_output_____" ] ], [ [ "** Do the same but with the Time on App column instead. **", "_____no_output_____" ] ], [ [ "sns.jointplot(x='Time on App',y='Yearly Amount Spent',data=customers)", "_____no_output_____" ] ], [ [ "** Use jointplot to create a 2D hex bin plot comparing Time on App and Length of Membership.**", "_____no_output_____" ] ], [ [ "sns.jointplot(x='Time on App',y='Length of Membership',kind='hex',data=customers)", "_____no_output_____" ] ], [ [ "**Let's explore these types of relationships across the entire data set. Use [pairplot](https://stanford.edu/~mwaskom/software/seaborn/tutorial/axis_grids.html#plotting-pairwise-relationships-with-pairgrid-and-pairplot) to recreate the plot below.(Don't worry about the the colors)**", "_____no_output_____" ] ], [ [ "sns.pairplot(customers)", "_____no_output_____" ] ], [ [ "**Based off this plot what looks to be the most correlated feature with Yearly Amount Spent?**", "_____no_output_____" ] ], [ [ "# Length of Membership ", "_____no_output_____" ] ], [ [ "**Create a linear model plot (using seaborn's lmplot) of Yearly Amount Spent vs. Length of Membership. **", "_____no_output_____" ] ], [ [ "sns.lmplot(x='Length of Membership',y='Yearly Amount Spent',data=customers)", "_____no_output_____" ] ], [ [ "## Training and Testing Data\n\nNow that we've explored the data a bit, let's go ahead and split the data into training and testing sets.\n** Set a variable X equal to the numerical features of the customers and a variable y equal to the \"Yearly Amount Spent\" column. **", "_____no_output_____" ] ], [ [ "y = customers['Yearly Amount Spent']", "_____no_output_____" ], [ "X = customers[['Avg. Session Length', 'Time on App','Time on Website', 'Length of Membership']]", "_____no_output_____" ] ], [ [ "** Use model_selection.train_test_split from sklearn to split the data into training and testing sets. Set test_size=0.3 and random_state=101**", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)", "_____no_output_____" ] ], [ [ "## Training the Model\n\nNow its time to train our model on our training data!\n\n** Import LinearRegression from sklearn.linear_model **", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LinearRegression", "_____no_output_____" ] ], [ [ "**Create an instance of a LinearRegression() model named lm.**", "_____no_output_____" ] ], [ [ "lm = LinearRegression()", "_____no_output_____" ] ], [ [ "** Train/fit lm on the training data.**", "_____no_output_____" ] ], [ [ "lm.fit(X_train,y_train)", "_____no_output_____" ] ], [ [ "**Print out the coefficients of the model**", "_____no_output_____" ] ], [ [ "# The coefficients\nprint('Coefficients: \\n', lm.coef_)", "Coefficients: \n [ 25.98154972 38.59015875 0.19040528 61.27909654]\n" ] ], [ [ "## Predicting Test Data\nNow that we have fit our model, let's evaluate its performance by predicting off the test values!\n\n** Use lm.predict() to predict off the X_test set of the data.**", "_____no_output_____" ] ], [ [ "predictions = lm.predict( X_test)", "_____no_output_____" ] ], [ [ "** Create a scatterplot of the real test values versus the predicted values. **", "_____no_output_____" ] ], [ [ "plt.scatter(y_test,predictions)\nplt.xlabel('Y Test')\nplt.ylabel('Predicted Y')", "_____no_output_____" ] ], [ [ "## Evaluating the Model\n\nLet's evaluate our model performance by calculating the residual sum of squares and the explained variance score (R^2).\n\n** Calculate the Mean Absolute Error, Mean Squared Error, and the Root Mean Squared Error. Refer to the lecture or to Wikipedia for the formulas**", "_____no_output_____" ] ], [ [ "# calculate these metrics by hand!\nfrom sklearn import metrics\n\nprint('MAE:', metrics.mean_absolute_error(y_test, predictions))\nprint('MSE:', metrics.mean_squared_error(y_test, predictions))\nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))", "MAE: 7.22814865343\nMSE: 79.813051651\nRMSE: 8.93381506698\n" ] ], [ [ "## Residuals\n\nYou should have gotten a very good model with a good fit. Let's quickly explore the residuals to make sure everything was okay with our data. \n\n**Plot a histogram of the residuals and make sure it looks normally distributed. Use either seaborn distplot, or just plt.hist().**", "_____no_output_____" ] ], [ [ "sns.distplot((y_test-predictions),bins=50);", "_____no_output_____" ] ], [ [ "## Conclusion\nWe still want to figure out the answer to the original question, do we focus our efforst on mobile app or website development? Or maybe that doesn't even really matter, and Membership Time is what is really important. Let's see if we can interpret the coefficients at all to get an idea.\n\n** Recreate the dataframe below. **", "_____no_output_____" ] ], [ [ "coeffecients = pd.DataFrame(lm.coef_,X.columns)\ncoeffecients.columns = ['Coeffecient']\ncoeffecients", "_____no_output_____" ] ], [ [ "** How can you interpret these coefficients? **", "_____no_output_____" ], [ "Interpreting the coefficients:\n\n- Holding all other features fixed, a 1 unit increase in **Avg. Session Length** is associated with an **increase of 25.98 total dollars spent**.\n- Holding all other features fixed, a 1 unit increase in **Time on App** is associated with an **increase of 38.59 total dollars spent**.\n- Holding all other features fixed, a 1 unit increase in **Time on Website** is associated with an **increase of 0.19 total dollars spent**.\n- Holding all other features fixed, a 1 unit increase in **Length of Membership** is associated with an **increase of 61.27 total dollars spent**.", "_____no_output_____" ], [ "**Do you think the company should focus more on their mobile app or on their website?**", "_____no_output_____" ], [ "\nThis is tricky, there are two ways to think about this: Develop the Website to catch up to the performance of the mobile app, or develop the app more since that is what is working better. This sort of answer really depends on the other factors going on at the company, you would probably want to explore the relationship between Length of Membership and the App or the Website before coming to a conclusion!\n", "_____no_output_____" ], [ "## Great Job!\n\nCongrats on your contract work! The company loved the insights! Let's move on.", "_____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" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
ec51fb36a41a93b21837722578b29e164b88a202
903,366
ipynb
Jupyter Notebook
CIFAR10_Project.ipynb
chufangao/cifar10_classification
1f9afb4a441a2d93fcb479ef9dc4e71e715cf837
[ "MIT" ]
1
2022-03-13T17:36:44.000Z
2022-03-13T17:36:44.000Z
CIFAR10_Project.ipynb
chufangao/cifar10_classification
1f9afb4a441a2d93fcb479ef9dc4e71e715cf837
[ "MIT" ]
null
null
null
CIFAR10_Project.ipynb
chufangao/cifar10_classification
1f9afb4a441a2d93fcb479ef9dc4e71e715cf837
[ "MIT" ]
null
null
null
648.503948
450,445
0.937053
[ [ [ "# CIFAR 10 Image Classification\n\n![image](https://miro.medium.com/max/1400/1*OSvbuPLy0PSM2nZ62SbtlQ.png)\n\nTo build high performance self-driving system, one must first develop a successful machine learning pipeline to recognize objects. In this project, you will be using CIFAR 10 dataset. CIFAR is an acronym that stands for the Canadian Institute For Advanced Research and the CIFAR-10 dataset was developed along with the CIFAR-100 dataset by researchers at the CIFAR institute (this project uses CIFAR-10). The dataset is comprised of 60,000 32×32 pixel color photographs of objects from 10 classes, such as frogs, birds, cats, ships, etc. The class labels and their standard associated integer values are listed below: \n\nClass Index | Class label\n--- | ---\n`**0**` | **airplane**\n`**1**` | **automobile**\n`**2**` | **bird**\n`**3**` | **cat**\n`**4**` | **deer**\n`**5**` | **dog**\n`**6**` | **frog**\n`**7**` | **horse**\n`**8**` | **ship**\n`**9**` | **truck**\n\nThese are very small images, much smaller than a typical photograph, and the dataset was intended for computer vision research.\n\n- Algorithms: Deep Convolutional Neural Network, Deep Recurrent Neural Network\n\n- Difficulty: Challenging. The dataset can be used directly. In addition, if teams have other demands, more complex data processing procedure can be developed to produce high accuracy\n\n## Captone Project Link\n\nLinks to Capstone Project slides: [here](https://docs.google.com/presentation/d/1iEMLMUSAA-lEe4EzC0sCbiu405Bow7-4zGIj3SKN-1c/edit#slide=id.g107242abc6f_0_12)\n\n## Motivation\n\nImage classification using deep learning has become very popular, and seems to be one of the best methods. Images with more features (and higher resolution) require more sophisticated networks that are able to consider the translation invariance of features, and other important aspects of image classification.\n\nThis project was meant to give an insight and understanding of how convolutional neural networks work, different methods for improving a model (batch normalization, data augmentation etc.) and the evaluation of complex models.\n\n", "_____no_output_____" ], [ "## Load Data", "_____no_output_____" ] ], [ [ "# example of loading the cifar10 dataset\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom keras.datasets import cifar10", "_____no_output_____" ], [ "# load dataset\n(trainX, trainy), (testX, testy) = cifar10.load_data()\n\n", "Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n170500096/170498071 [==============================] - 3s 0us/step\n170508288/170498071 [==============================] - 3s 0us/step\n" ], [ "label_dict = {0: \"airplane\",\n 1: \"automobile\",\n 2: \"bird\",\n 3: \"cat\",\n 4: \"deer\",\n 5: \"dog\",\n 6: \"frog\",\n 7: \"horse\",\n 8: \"ship\",\n 9: \"truck\",}", "_____no_output_____" ] ], [ [ "## Define Research Question", "_____no_output_____" ] ], [ [ "# split training, validation and test\nrandom_index = np.random.permutation(trainX.shape[0])\ntrain_proportion = .85\ntrain_end_index = int(trainX.shape[0] * train_proportion)\n\ntraining_X = trainX[random_index[:train_end_index]]\ntraining_y = trainy[random_index[:train_end_index]]\n\nvalidation_X = trainX[random_index[train_end_index:]]\nvalidation_y = trainy[random_index[train_end_index:]]\n\nprint(training_X.shape, training_y.shape)\nprint(validation_X.shape, validation_y.shape)\n\nfrom sklearn.model_selection import train_test_split\n# train and validate\ntrain_proportion = .90\ntraining_X, validation_X, training_y, validation_y = train_test_split(trainX, trainy, train_size=train_proportion)\nprint(training_X.shape, training_y.shape)\nprint(validation_X.shape, validation_y.shape)", "(42500, 32, 32, 3) (42500, 1)\n(7500, 32, 32, 3) (7500, 1)\n(45000, 32, 32, 3) (45000, 1)\n(5000, 32, 32, 3) (5000, 1)\n" ] ], [ [ "## Exploratory Data Analysis\n\nExploratory Data Analysis (EDA) is an approach of analyzing data sets to summarize their main characteristics, often using statistical graphics and other data visualization methods. A statistical model can be used or not, but primarily EDA is for seeing what the data can tell us beyond the formal modeling or hypothesis testing task.\n\nExamples:\n\n- You can count the number of classes in this data. \n- You examine the images according to class labels. \n- You can plot the averages of pixel-level values across all images in a particular class. In addition, you can also span the visualization for all classes.\n\nYou can refer to more resources here in this [code](https://colab.research.google.com/drive/1KkG1V7RsnKjCRd0zx0h434nqiXwOf-fG?authuser=1).", "_____no_output_____" ] ], [ [ "for i in range(10):\n print(label_dict[i], training_X[(training_y.flatten() == i), :, :].shape)", "airplane (4496, 32, 32, 3)\nautomobile (4523, 32, 32, 3)\nbird (4494, 32, 32, 3)\ncat (4463, 32, 32, 3)\ndeer (4512, 32, 32, 3)\ndog (4470, 32, 32, 3)\nfrog (4527, 32, 32, 3)\nhorse (4500, 32, 32, 3)\nship (4522, 32, 32, 3)\ntruck (4493, 32, 32, 3)\n" ], [ "import numpy as np\nimport matplotlib.pyplot as plt\n\nfor i in range(10):\n subset = training_X[training_y.flatten()==i]\n mean_img = np.mean(subset, axis=0)\n mean_img = mean_img / 255\n plt.imshow(mean_img)\n plt.title(label_dict[i])\n plt.show()", "_____no_output_____" ], [ "for i in range(10):\n print(label_dict[i], training_X[(training_y.flatten() == i), :, :].shape)", "airplane (4496, 32, 32, 3)\nautomobile (4523, 32, 32, 3)\nbird (4494, 32, 32, 3)\ncat (4463, 32, 32, 3)\ndeer (4512, 32, 32, 3)\ndog (4470, 32, 32, 3)\nfrog (4527, 32, 32, 3)\nhorse (4500, 32, 32, 3)\nship (4522, 32, 32, 3)\ntruck (4493, 32, 32, 3)\n" ], [ "for i in range(10):\n subset = training_X[training_y.flatten()==i]\n std_img = np.var(subset, axis=0)\n print(std_img.shape)\n print(std_img.min())\n print(std_img.max())\n\n std_img = std_img - std_img.min()\n print(std_img.min())\n print(std_img.max())\n\n std_img = std_img / std_img.max()\n print(std_img.min())\n print(std_img.max())\n\n plt.imshow(std_img)\n plt.show()", "(32, 32, 3)\n3278.1900284930957\n5220.418108257147\n0.0\n1942.228079764051\n0.0\n1.0\n" ], [ "plt.figure(figsize=(10, 10))\nfor i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.imshow(trainX[i], cmap=plt.cm.binary)\n plt.xlabel(label_dict[trainy[i][0]])\nplt.show()", "_____no_output_____" ], [ "# include examples for each class\n# include scaled variance plots from carlos\n# include mean plots ", "_____no_output_____" ] ], [ [ "## Baseline Model\n\nFundamentally, a baseline is a model that is both simple to set up and has a reasonable chance of providing decent results. Experimenting with them is usually quick and low cost, since implementations are widely available in popular packages.\n\n# To do:\n\n1) Separate training and testing sets\n\n2) Create a traditional neural network model for classification. Code examples are [here](https://colab.research.google.com/drive/1OGxD35fQxXdWNDwYGYpZcES5zgo6UvdO?authuser=1) for reference.\n\n3) Plot your training and testing accuracy across epochs\n\n\n## Challenge:\n\n- Create another neural net with a different layer configuration. Does it improve performance?", "_____no_output_____" ] ], [ [ "n = len(training_X)\nprint(training_X.shape)\nprint(training_X.reshape((n, -1)).shape)\n\nprint(training_y.shape)", "(45000, 32, 32, 3)\n(45000, 3072)\n(45000, 1)\n" ], [ "import sklearn\nimport sklearn.linear_model\nfrom sklearn.metrics import classification_report # tested with 0.21.2l\n\n\nmodel = sklearn.linear_model.LogisticRegression(random_state=0)\n\nmodel.fit(\n training_X.reshape((len(training_X), -1)), \n training_y.flatten()\n )\n\ntest_predictions = model.predict(\n testX.reshape((len(testX), -1))\n )\ntrain_predictions = model.predict(\n training_X.reshape((len(training_X), -1))\n )\n\n# print(classification_report(train_predictions, training_y.flatten()))\n# print(classification_report(test_predictions, testy.flatten()))\n# sklearn.metrics.confusion_matrix(y_true=testy, y_pred=predictions)\nprint('train acc', np.mean(train_predictions==training_y.flatten()))\nprint('test acc', np.mean(test_predictions==testy.flatten()))\n", "/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_logistic.py:818: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG,\n" ], [ "print('train acc', np.mean(train_predictions==training_y.flatten()))\nprint('test acc', np.mean(test_predictions==testy.flatten()))\n", "train acc 0.4288888888888889\ntest acc 0.4033\n" ], [ "training_X = training_X / 255\nvalidation_X = validation_X / 255\ntestX = testX / 255 \n", "_____no_output_____" ], [ "import tensorflow as tf\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(), # this function converts image from (28, 28) to 1D array 28^2 = 784\n tf.keras.layers.Dense(128, activation=tf.nn.relu), # 128 is a choice # ReLU(x) = max(x, 0)\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n ]) \nmodel.compile(optimizer = \"adam\", # recall: gradient descent, stochastic gradient descent, RmsProp, ADAM\n loss = 'sparse_categorical_crossentropy', # loss: mean_square_error, mean_absolute_error, cross_entropy, binary_cross_entropy\n metrics=['accuracy'])\n\nhistory = model.fit(training_X, training_y, epochs=10,\n validation_data=[validation_X, validation_y])\n\nprint(model.summary())\ntf.keras.utils.plot_model(model, to_file='simple_nn_model.png', show_shapes=True, show_layer_names=True)\n", "Epoch 1/10\n1407/1407 [==============================] - 8s 4ms/step - loss: 1.9125 - accuracy: 0.3136 - val_loss: 1.8507 - val_accuracy: 0.3352\nEpoch 2/10\n1407/1407 [==============================] - 5s 4ms/step - loss: 1.7644 - accuracy: 0.3700 - val_loss: 1.7441 - val_accuracy: 0.3826\nEpoch 3/10\n1407/1407 [==============================] - 5s 4ms/step - loss: 1.7029 - accuracy: 0.3948 - val_loss: 1.6829 - val_accuracy: 0.4008\nEpoch 4/10\n1407/1407 [==============================] - 5s 4ms/step - loss: 1.6660 - accuracy: 0.4086 - val_loss: 1.7242 - val_accuracy: 0.3926\nEpoch 5/10\n1407/1407 [==============================] - 5s 4ms/step - loss: 1.6437 - accuracy: 0.4134 - val_loss: 1.6799 - val_accuracy: 0.3832\nEpoch 6/10\n1407/1407 [==============================] - 5s 4ms/step - loss: 1.6288 - accuracy: 0.4204 - val_loss: 1.6601 - val_accuracy: 0.4122\nEpoch 7/10\n1407/1407 [==============================] - 5s 4ms/step - loss: 1.6126 - accuracy: 0.4259 - val_loss: 1.6459 - val_accuracy: 0.4094\nEpoch 8/10\n1407/1407 [==============================] - 5s 4ms/step - loss: 1.6023 - accuracy: 0.4275 - val_loss: 1.6897 - val_accuracy: 0.3964\nEpoch 9/10\n1407/1407 [==============================] - 5s 4ms/step - loss: 1.5962 - accuracy: 0.4315 - val_loss: 1.6825 - val_accuracy: 0.4110\nEpoch 10/10\n1407/1407 [==============================] - 5s 4ms/step - loss: 1.5891 - accuracy: 0.4348 - val_loss: 1.6100 - val_accuracy: 0.4336\nModel: \"sequential\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n flatten (Flatten) (None, 3072) 0 \n \n dense (Dense) (None, 128) 393344 \n \n dense_1 (Dense) (None, 10) 1290 \n \n=================================================================\nTotal params: 394,634\nTrainable params: 394,634\nNon-trainable params: 0\n_________________________________________________________________\nNone\n" ], [ "# define plot_graphs function\n# do not edit\ndef plot_graphs(history, metric):\n plt.plot(history.history[metric])\n plt.plot(history.history['val_'+metric], '')\n plt.xlabel(\"Epochs\")\n plt.ylabel(metric)\n plt.legend([metric, 'val_'+metric])\n\nplt.figure(figsize=(16, 6))\nplt.subplot(1, 2, 1)\nplot_graphs(history, 'accuracy')\nplt.ylim(None, 1)\nplt.subplot(1, 2, 2)\nplot_graphs(history, 'loss')\nplt.ylim(0, None) ", "_____no_output_____" ], [ "from sklearn.metrics import classification_report # tested with 0.21.2l\n\ntest_predictions = model.predict(testX).argmax(axis=1)\ntrain_predictions = model.predict(training_X).argmax(axis=1)\n\nprint(classification_report(train_predictions, training_y.flatten()))\nprint(classification_report(test_predictions, testy.flatten()))\n# sklearn.metrics.confusion_matrix(y_true=testy, y_pred=predictions)\n# print('test acc', np.mean(testy.flatten()==predictions))", " precision recall f1-score support\n\n 0 0.46 0.50 0.48 4115\n 1 0.50 0.62 0.55 3645\n 2 0.23 0.33 0.27 3158\n 3 0.27 0.30 0.29 4037\n 4 0.34 0.40 0.37 3775\n 5 0.32 0.40 0.35 3561\n 6 0.65 0.37 0.47 7919\n 7 0.49 0.56 0.52 3891\n 8 0.70 0.52 0.60 6064\n 9 0.53 0.49 0.51 4835\n\n accuracy 0.45 45000\n macro avg 0.45 0.45 0.44 45000\nweighted avg 0.48 0.45 0.46 45000\n\n precision recall f1-score support\n\n 0 0.45 0.49 0.47 913\n 1 0.46 0.59 0.52 770\n 2 0.20 0.29 0.24 716\n 3 0.24 0.27 0.25 906\n 4 0.32 0.40 0.36 803\n 5 0.31 0.38 0.34 809\n 6 0.66 0.37 0.47 1776\n 7 0.46 0.53 0.49 864\n 8 0.67 0.47 0.55 1402\n 9 0.49 0.47 0.48 1041\n\n accuracy 0.43 10000\n macro avg 0.43 0.43 0.42 10000\nweighted avg 0.46 0.43 0.43 10000\n\n" ] ], [ [ "## Advanced Model\n\nWith the knowledge from the baseline model, your team and the instructor can work together to develop advanced models. Advanced models can have the following impact:\n\n- higher accuracy (we usually refer to test set performance and advanced models should have higher performance in the test set than baseline models)\n- auto-tune (some advanced model can be due to more automatic tuning procedure, this means the advanced model is a function instead of a fixed model)\n\nExamples: \n- Build a model that is more complex or can improve upon your predictions for classification.", "_____no_output_____" ] ], [ [ "from keras.backend import learning_phase\nimport tensorflow as tf\n\n\ninput_shape = training_X.shape[1:] # (32, 32, 3)\nclass_num = 10\n\ncnn_model = tf.keras.models.Sequential([\n tf.keras.layers.Conv2D(filters=32, kernel_size=3, padding='same', input_shape=input_shape, activation='relu'),\n tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu'),\n tf.keras.layers.MaxPooling2D(),\n tf.keras.layers.Dropout(0.3),\n\n tf.keras.layers.Conv2D(filters=64, kernel_size=3, padding='same', activation='relu'),\n tf.keras.layers.Conv2D(filters=64, kernel_size=3, activation='relu'),\n tf.keras.layers.MaxPooling2D(),\n tf.keras.layers.Dropout(0.3),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation='relu'),\n tf.keras.layers.Dropout(0.4),\n tf.keras.layers.Dense(class_num, activation='softmax'),\n])\n\n# Build the model\ncnn_model.compile(\n loss=tf.keras.losses.sparse_categorical_crossentropy, # loss function\n optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3), # optimizer function\n metrics=['accuracy'] # reporting metric\n)\n\n# Display a summary of the models structure\nprint(cnn_model.summary())\ntf.keras.utils.plot_model(cnn_model, to_file='complex_nn_model.png', show_shapes=True, show_layer_names=True)\n", "Model: \"sequential_1\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n conv2d (Conv2D) (None, 32, 32, 32) 896 \n \n conv2d_1 (Conv2D) (None, 30, 30, 32) 9248 \n \n max_pooling2d (MaxPooling2D (None, 15, 15, 32) 0 \n ) \n \n dropout (Dropout) (None, 15, 15, 32) 0 \n \n conv2d_2 (Conv2D) (None, 15, 15, 64) 18496 \n \n conv2d_3 (Conv2D) (None, 13, 13, 64) 36928 \n \n max_pooling2d_1 (MaxPooling (None, 6, 6, 64) 0 \n 2D) \n \n dropout_1 (Dropout) (None, 6, 6, 64) 0 \n \n flatten_1 (Flatten) (None, 2304) 0 \n \n dense_2 (Dense) (None, 512) 1180160 \n \n dropout_2 (Dropout) (None, 512) 0 \n \n dense_3 (Dense) (None, 10) 5130 \n \n=================================================================\nTotal params: 1,250,858\nTrainable params: 1,250,858\nNon-trainable params: 0\n_________________________________________________________________\nNone\n" ], [ "history = cnn_model.fit(training_X, training_y, epochs=20, batch_size=32,\n validation_data=[validation_X, validation_y])\n\n", "Epoch 1/20\n1407/1407 [==============================] - 34s 18ms/step - loss: 1.5629 - accuracy: 0.4288 - val_loss: 1.2013 - val_accuracy: 0.5744\nEpoch 2/20\n1407/1407 [==============================] - 21s 15ms/step - loss: 1.2095 - accuracy: 0.5691 - val_loss: 1.0164 - val_accuracy: 0.6402\nEpoch 3/20\n1407/1407 [==============================] - 21s 15ms/step - loss: 1.0586 - accuracy: 0.6255 - val_loss: 0.9554 - val_accuracy: 0.6660\nEpoch 4/20\n1407/1407 [==============================] - 21s 15ms/step - loss: 0.9669 - accuracy: 0.6604 - val_loss: 0.8598 - val_accuracy: 0.6988\nEpoch 5/20\n1407/1407 [==============================] - 20s 15ms/step - loss: 0.9044 - accuracy: 0.6820 - val_loss: 0.8256 - val_accuracy: 0.7104\nEpoch 6/20\n1407/1407 [==============================] - 20s 14ms/step - loss: 0.8546 - accuracy: 0.6993 - val_loss: 0.8099 - val_accuracy: 0.7196\nEpoch 7/20\n1407/1407 [==============================] - 21s 15ms/step - loss: 0.8157 - accuracy: 0.7132 - val_loss: 0.7385 - val_accuracy: 0.7384\nEpoch 8/20\n1407/1407 [==============================] - 21s 15ms/step - loss: 0.7788 - accuracy: 0.7279 - val_loss: 0.7536 - val_accuracy: 0.7342\nEpoch 9/20\n1407/1407 [==============================] - 20s 14ms/step - loss: 0.7607 - accuracy: 0.7349 - val_loss: 0.7051 - val_accuracy: 0.7522\nEpoch 10/20\n1407/1407 [==============================] - 20s 14ms/step - loss: 0.7300 - accuracy: 0.7457 - val_loss: 0.6818 - val_accuracy: 0.7580\nEpoch 11/20\n1407/1407 [==============================] - 20s 15ms/step - loss: 0.7085 - accuracy: 0.7525 - val_loss: 0.6915 - val_accuracy: 0.7626\nEpoch 12/20\n1407/1407 [==============================] - 21s 15ms/step - loss: 0.6848 - accuracy: 0.7583 - val_loss: 0.6877 - val_accuracy: 0.7556\nEpoch 13/20\n1407/1407 [==============================] - 24s 17ms/step - loss: 0.6809 - accuracy: 0.7604 - val_loss: 0.6971 - val_accuracy: 0.7560\nEpoch 14/20\n1407/1407 [==============================] - 25s 17ms/step - loss: 0.6631 - accuracy: 0.7654 - val_loss: 0.6703 - val_accuracy: 0.7706\nEpoch 15/20\n1407/1407 [==============================] - 23s 16ms/step - loss: 0.6435 - accuracy: 0.7704 - val_loss: 0.6623 - val_accuracy: 0.7720\nEpoch 16/20\n1407/1407 [==============================] - 22s 16ms/step - loss: 0.6365 - accuracy: 0.7764 - val_loss: 0.6540 - val_accuracy: 0.7700\nEpoch 17/20\n1407/1407 [==============================] - 21s 15ms/step - loss: 0.6172 - accuracy: 0.7810 - val_loss: 0.6606 - val_accuracy: 0.7702\nEpoch 18/20\n1407/1407 [==============================] - 20s 14ms/step - loss: 0.6101 - accuracy: 0.7853 - val_loss: 0.6524 - val_accuracy: 0.7772\nEpoch 19/20\n1407/1407 [==============================] - 21s 15ms/step - loss: 0.6023 - accuracy: 0.7866 - val_loss: 0.6653 - val_accuracy: 0.7674\nEpoch 20/20\n1407/1407 [==============================] - 21s 15ms/step - loss: 0.5902 - accuracy: 0.7916 - val_loss: 0.6634 - val_accuracy: 0.7722\n" ], [ "plt.figure(figsize=(16, 6))\nplt.subplot(1, 2, 1)\nplot_graphs(history, 'accuracy')\nplt.ylim(None, 1)\nplt.subplot(1, 2, 2)\nplot_graphs(history, 'loss')\nplt.ylim(0, None) ", "_____no_output_____" ], [ "test_predictions = cnn_model.predict(testX).argmax(axis=1)\ntrain_predictions = cnn_model.predict(training_X).argmax(axis=1)\n\nprint(classification_report(train_predictions, training_y.flatten()))\nprint(classification_report(test_predictions, testy.flatten()))\n", " precision recall f1-score support\n\n 0 0.92 0.95 0.93 4346\n 1 0.98 0.95 0.97 4685\n 2 0.87 0.89 0.88 4396\n 3 0.74 0.84 0.79 3930\n 4 0.91 0.86 0.89 4794\n 5 0.81 0.84 0.83 4282\n 6 0.96 0.85 0.90 5087\n 7 0.93 0.95 0.94 4422\n 8 0.96 0.95 0.95 4592\n 9 0.95 0.96 0.96 4466\n\n accuracy 0.90 45000\n macro avg 0.90 0.90 0.90 45000\nweighted avg 0.91 0.90 0.91 45000\n\n precision recall f1-score support\n\n 0 0.78 0.82 0.80 950\n 1 0.93 0.84 0.89 1108\n 2 0.68 0.70 0.69 973\n 3 0.54 0.63 0.58 851\n 4 0.77 0.72 0.74 1065\n 5 0.66 0.70 0.68 937\n 6 0.89 0.76 0.82 1180\n 7 0.80 0.84 0.82 953\n 8 0.87 0.87 0.87 997\n 9 0.85 0.86 0.86 986\n\n accuracy 0.78 10000\n macro avg 0.78 0.77 0.77 10000\nweighted avg 0.78 0.78 0.78 10000\n\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ec520127506b521822665a561d789df415aab602
52,985
ipynb
Jupyter Notebook
nlp-tf/3-embeddings.ipynb
MicrosoftDocs/tensorflowfundamentals
ccc0fa119dce1122529c2400d395542fbd7cf3b6
[ "CC-BY-4.0", "MIT" ]
null
null
null
nlp-tf/3-embeddings.ipynb
MicrosoftDocs/tensorflowfundamentals
ccc0fa119dce1122529c2400d395542fbd7cf3b6
[ "CC-BY-4.0", "MIT" ]
null
null
null
nlp-tf/3-embeddings.ipynb
MicrosoftDocs/tensorflowfundamentals
ccc0fa119dce1122529c2400d395542fbd7cf3b6
[ "CC-BY-4.0", "MIT" ]
2
2021-11-02T13:08:31.000Z
2022-03-14T00:51:45.000Z
48.168182
1,294
0.566255
[ [ [ "## Embeddings\n\nIn our previous example, we operated on high-dimensional bag-of-words vectors with length `vocab_size`, and we explicitly converted low-dimensional positional representation vectors into sparse one-hot representation. This one-hot representation is not memory-efficient. In addition, each word is treated independently from each other, so one-hot encoded vectors don't express semantic similarities between words.\n\nIn this unit, we will continue exploring the **News AG** dataset. To begin, let's load the data and get some definitions from the previous unit.", "_____no_output_____" ] ], [ [ "import sys\n!{sys.executable} -m pip install --quiet tensorflow_datasets==4.4.0\n!cd ~ && wget -q -O - https://mslearntensorflowlp.blob.core.windows.net/data/tfds-ag-news.tgz | tar xz", "_____no_output_____" ], [ "import tensorflow as tf\nfrom tensorflow import keras\nimport tensorflow_datasets as tfds\nimport numpy as np\n\n# In this tutorial, we will be training a lot of models. In order to use GPU memory cautiously,\n# we will set tensorflow option to grow GPU memory allocation when required.\nphysical_devices = tf.config.list_physical_devices('GPU') \nif len(physical_devices)>0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n\nds_train, ds_test = tfds.load('ag_news_subset').values()", "_____no_output_____" ] ], [ [ "\n### What's an embedding?\n\nThe idea of **embedding** is to represent words using lower-dimensional dense vectors that reflect the semantic meaning of the word. We will later discuss how to build meaningful word embeddings, but for now let's just think of embeddings as a way to reduce the dimensionality of a word vector. \n\nSo, an embedding layer takes a word as input, and produces an output vector of specified `embedding_size`. In a sense, it is very similar to a `Dense` layer, but instead of taking a one-hot encoded vector as input, it's able to take a word number.\n\nBy using an embedding layer as the first layer in our network, we can switch from bag-or-words to an **embedding bag** model, where we first convert each word in our text into the corresponding embedding, and then compute some aggregate function over all those embeddings, such as `sum`, `average` or `max`. \n\n![Image showing an embedding classifier for five sequence words.](images/embedding-classifier-example.png)\n\nOur classifier neural network consists of the following layers:\n\n* `TextVectorization` layer, which takes a string as input, and produces a tensor of token numbers. We will specify some reasonable vocabulary size `vocab_size`, and ignore less-frequently used words. The input shape will be 1, and the output shape will be $n$, since we'll get $n$ tokens as a result, each of them containing numbers from 0 to `vocab_size`.\n* `Embedding` layer, which takes $n$ numbers, and reduces each number to a dense vector of a given length (100 in our example). Thus, the input tensor of shape $n$ will be transformed into an $n\\times 100$ tensor. \n* Aggregation layer, which takes the average of this tensor along the first axis, i.e. it will compute the average of all $n$ input tensors corresponding to different words. To implement this layer, we will use a `Lambda` layer, and pass into it the function to compute the average. The output will have shape of 100, and it will be the numeric representation of the whole input sequence.\n* Final `Dense` linear classifier.", "_____no_output_____" ] ], [ [ "vocab_size = 30000\nbatch_size = 128\n\nvectorizer = keras.layers.experimental.preprocessing.TextVectorization(max_tokens=vocab_size,input_shape=(1,))\n\nmodel = keras.models.Sequential([\n vectorizer, \n keras.layers.Embedding(vocab_size,100),\n keras.layers.Lambda(lambda x: tf.reduce_mean(x,axis=1)),\n keras.layers.Dense(4, activation='softmax')\n])\nmodel.summary()", "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ntext_vectorization_1 (TextVe (None, None) 0 \n_________________________________________________________________\nembedding_1 (Embedding) (None, None, 100) 3000000 \n_________________________________________________________________\nlambda_1 (Lambda) (None, 100) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 4) 404 \n=================================================================\nTotal params: 3,000,404\nTrainable params: 3,000,404\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "In the `summary` printout, in the **output shape** column, the first tensor dimension `None` corresponds to the minibatch size, and the second corresponds to the length of the token sequence. All token sequences in the minibatch have different lengths. We'll discuss how to deal with it in the next section.\n\nNow let's train the network:", "_____no_output_____" ] ], [ [ "def extract_text(x):\n return x['title']+' '+x['description']\n\ndef tupelize(x):\n return (extract_text(x),x['label'])\n\nprint(\"Training vectorizer\")\nvectorizer.adapt(ds_train.take(500).map(extract_text))\n\nmodel.compile(loss='sparse_categorical_crossentropy',metrics=['acc'])\nmodel.fit(ds_train.map(tupelize).batch(batch_size),validation_data=ds_test.map(tupelize).batch(batch_size))", "Training vectorizer\n938/938 [==============================] - 12s 13ms/step - loss: 0.7953 - acc: 0.8113 - val_loss: 0.4496 - val_acc: 0.8657\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n" ] ], [ [ "> **Note** that we are building vectorizer based on a subset of the data. This is done in order to speed up the process, and it might result in a situation when not all tokens from our text is present in the vocabulary. In this case, those tokens would be ignored, which may result in slightly lower accuracy. However, in real life a subset of text often gives a good vocabulary estimation.", "_____no_output_____" ], [ "### Dealing with variable sequence sizes\n\nLet's understand how training happens in minibatches. In the example above, the input tensor has dimension 1, and we use 128-long minibatches, so that actual size of the tensor is $128 \\times 1$. However, the number of tokens in each sentence is different. If we apply the `TextVectorization` layer to a single input, the number of tokens returned is different, depending on how the text is tokenized:", "_____no_output_____" ] ], [ [ "print(vectorizer('Hello, world!'))\nprint(vectorizer('I am glad to meet you!'))", "tf.Tensor([ 1 45], shape=(2,), dtype=int64)\ntf.Tensor([ 112 1271 1 3 1747 158], shape=(6,), dtype=int64)\n" ] ], [ [ "However, when we apply the vectorizer to several sequences, it has to produce a tensor of rectangular shape, so it fills unused elements with the PAD token (which in our case is zero):", "_____no_output_____" ] ], [ [ "vectorizer(['Hello, world!','I am glad to meet you!'])", "_____no_output_____" ] ], [ [ "Here we can see the embeddings:", "_____no_output_____" ] ], [ [ "model.layers[1](vectorizer(['Hello, world!','I am glad to meet you!'])).numpy()", "_____no_output_____" ] ], [ [ "> **Note**: To minimize the amount of padding, in some cases it makes sense to sort all sequences in the dataset in the order of increasing length (or, more precisely, number of tokens). This will ensure that each minibatch contains sequences of similar length.", "_____no_output_____" ], [ "\n## Semantic embeddings: Word2Vec\n\nIn our previous example, the embedding layer learned to map words to vector representations, however, these representations did not have semantic meaning. It would be nice to learn a vector representation such that similar words or synonyms correspond to vectors that are close to each other in terms of some vector distance (for example euclidian distance).\n\nTo do that, we need to pretrain our embedding model on a large collection of text using a technique such as [Word2Vec](https://en.wikipedia.org/wiki/Word2vec). It's based on two main architectures that are used to produce a distributed representation of words:\n\n - **Continuous bag-of-words** (CBoW), where we train the model to predict a word from the surrounding context. Given the ngram $(W_{-2},W_{-1},W_0,W_1,W_2)$, the goal of the model is to predict $W_0$ from $(W_{-2},W_{-1},W_1,W_2)$.\n - **Continuous skip-gram** is opposite to CBoW. The model uses the surrounding window of context words to predict the current word.\n\nCBoW is faster, and while skip-gram is slower, it does a better job of representing infrequent words.\n\n![Image showing both CBoW and Skip-Gram algorithms to convert words to vectors.](images/example-algorithms-for-converting-words-to-vectors.png)\n\nTo experiment with the Word2Vec embedding pretrained on Google News dataset, we can use the **gensim** library. Below we find the words most similar to 'neural'.\n\n> **Note:** When you first create word vectors, downloading them can take some time!", "_____no_output_____" ] ], [ [ "import gensim.downloader as api\nw2v = api.load('word2vec-google-news-300')", "[==================================================] 100.0% 1662.8/1662.8MB downloaded\n" ], [ "for w,p in w2v.most_similar('neural'):\n print(f\"{w} -> {p}\")", "neuronal -> 0.7804799675941467\nneurons -> 0.7326500415802002\nneural_circuits -> 0.7252851724624634\nneuron -> 0.7174385190010071\ncortical -> 0.6941086649894714\nbrain_circuitry -> 0.6923246383666992\nsynaptic -> 0.6699118614196777\nneural_circuitry -> 0.6638563275337219\nneurochemical -> 0.6555314064025879\nneuronal_activity -> 0.6531826257705688\n" ] ], [ [ "We can also extract the vector embedding from the word, to be used in training the classification model. The embedding has 300 components, but here we only show the first 20 components of the vector for clarity:", "_____no_output_____" ] ], [ [ "w2v['play'][:20]", "_____no_output_____" ] ], [ [ "The great thing about semantic embeddings is that you can manipulate the vector encoding based on semantics. For example, we can ask to find a word whose vector representation is as close as possible to the words *king* and *woman*, and as far as possible from the word *man*:", "_____no_output_____" ] ], [ [ "w2v.most_similar(positive=['king','woman'],negative=['man'])[0]", "_____no_output_____" ] ], [ [ "An example above uses some internal GenSym magic, but the underlying logic is actually quite simple. An interesting thing about embeddings is that you can perform normal vector operations on embedding vectors, and that would reflect operations on word **meanings**. The example above can be expressed in terms of vector operations: we calculate the vector corresponding to **KING-MAN+WOMAN** (operations `+` and `-` are performed on vector representations of corresponding words), and then find the closest word in the dictionary to that vector:", "_____no_output_____" ] ], [ [ "# get the vector corresponding to kind-man+woman\nqvec = w2v['king']-1.7*w2v['man']+1.7*w2v['woman']\n# find the index of the closest embedding vector \nd = np.sum((w2v.vectors-qvec)**2,axis=1)\nmin_idx = np.argmin(d)\n# find the corresponding word\nw2v.index2word[min_idx]", "_____no_output_____" ] ], [ [ "> **NOTE**: We had to add a small coefficients to *man* and *woman* vectors - try removing them to see what happens.\n\nTo find the closest vector, we use TensorFlow machinery to compute a vector of distances between our vector and all vectors in the vocabulary, and then find the index of minimal word using `argmin`.", "_____no_output_____" ], [ "While Word2Vec seems like a great way to express word semantics, it has many disadvantages, including the following:\n\n* Both CBoW and skip-gram models are **predictive embeddings**, and they only take local context into account. Word2Vec does not take advantage of global context.\n* Word2Vec does not take into account word **morphology**, i.e. the fact that the meaning of the word can depend on different parts of the word, such as the root. \n\n**FastText** tries to overcome the second limitation, and builds on Word2Vec by learning vector representations for each word and the charachter n-grams found within each word. The values of the representations are then averaged into one vector at each training step. While this adds a lot of additional computation to pretraining, it enables word embeddings to encode sub-word information.\n\nAnother method, **GloVe**, uses a different approach to word embeddings, based on the factorization of the word-context matrix. First, it builds a large matrix that counts the number of word occurences in different contexts, and then it tries to represent this matrix in lower dimensions in a way that minimizes reconstruction loss.\n\nThe gensim library supports those word embeddings, and you can experiment with them by changing the model loading code above.", "_____no_output_____" ], [ "## Using pretrained embeddings in Keras\n\nWe can modify the example above to prepopulate the matrix in our embedding layer with semantic embeddings, such as Word2Vec. The vocabularies of the pretrained embedding and the text corpus will likely not match, so we need to choose one. Here we explore the two possible options: using the tokenizer vocabulary, and using the vocabulary from Word2Vec embeddings.\n\n### Using tokenizer vocabulary\n\nWhen using the tokenizer vocabulary, some of the words from the vocabulary will have corresponding Word2Vec embeddings, and some will be missing. Given that our vocabulary size is `vocab_size`, and the Word2Vec embedding vector length is `embed_size`, the embedding layer will be repesented by a weight matrix of shape `vocab_size`$\\times$`embed_size`. We will populate this matrix by going through the vocabulary:", "_____no_output_____" ] ], [ [ "embed_size = len(w2v.get_vector('hello'))\nprint(f'Embedding size: {embed_size}')\n\nvocab = vectorizer.get_vocabulary()\nW = np.zeros((vocab_size,embed_size))\nprint('Populating matrix, this will take some time...',end='')\nfound, not_found = 0,0\nfor i,w in enumerate(vocab):\n try:\n W[i] = w2v.get_vector(w)\n found+=1\n except:\n # W[i] = np.random.normal(0.0,0.3,size=(embed_size,))\n not_found+=1\n\nprint(f\"Done, found {found} words, {not_found} words missing\")", "Embedding size: 300\nPopulating matrix, this will take some time...Done, found 4551 words, 784 words missing\n" ] ], [ [ "For words that are not present in the Word2Vec vocabulary, we can either leave them as zeroes, or generate a random vector.\n\nNow we can define an embedding layer with pretrained weights:", "_____no_output_____" ] ], [ [ "emb = keras.layers.Embedding(vocab_size,embed_size,weights=[W],trainable=False)\nmodel = keras.models.Sequential([\n vectorizer, emb,\n keras.layers.Lambda(lambda x: tf.reduce_mean(x,axis=1)),\n keras.layers.Dense(4, activation='softmax')\n])", "_____no_output_____" ] ], [ [ "Now let's train our model. ", "_____no_output_____" ] ], [ [ "model.compile(loss='sparse_categorical_crossentropy',metrics=['acc'])\nmodel.fit(ds_train.map(tupelize).batch(batch_size),\n validation_data=ds_test.map(tupelize).batch(batch_size))", "938/938 [==============================] - 6s 7ms/step - loss: 1.1098 - acc: 0.7849 - val_loss: 0.9145 - val_acc: 0.8159\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n" ] ], [ [ "> **Note**: Notice that we set `trainable=False` when creating the `Embedding`, which means that we're not retraining the Embedding layer. This may cause accuracy to be slightly lower, but it speeds up the training.\n\n### Using embedding vocabulary\n\nOne issue with the previous approach is that the vocabularies used in the TextVectorization and Embedding are different. To overcome this problem, we can use one of the following solutions:\n* Re-train the Word2Vec model on our vocabulary.\n* Load our dataset with the vocabulary from the pretrained Word2Vec model. Vocabularies used to load the dataset can be specified during loading.\n\nThe latter approach seems easier, so let's implement it. First of all, we will create a `TextVectorization` layer with the specified vocabulary, taken from the Word2Vec embeddings:", "_____no_output_____" ] ], [ [ "vocab = list(w2v.vocab.keys())\nvectorizer = keras.layers.experimental.preprocessing.TextVectorization(input_shape=(1,))\nvectorizer.set_vocabulary(vocab)", "_____no_output_____" ] ], [ [ "The gensim word embeddings library contains a convenient function, `get_keras_embeddings`, which will automatically create the corresponding Keras embeddings layer for you.", "_____no_output_____" ] ], [ [ "model = keras.models.Sequential([\n vectorizer, \n w2v.get_keras_embedding(train_embeddings=False),\n keras.layers.Lambda(lambda x: tf.reduce_mean(x,axis=1)),\n keras.layers.Dense(4, activation='softmax')\n])\nmodel.compile(loss='sparse_categorical_crossentropy',metrics=['acc'])\nmodel.fit(ds_train.map(tupelize).batch(128),validation_data=ds_test.map(tupelize).batch(128),epochs=5)", "Epoch 1/5\n938/938 [==============================] - 7s 7ms/step - loss: 1.3381 - acc: 0.4961 - val_loss: 1.2996 - val_acc: 0.5682\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 2/5\n938/938 [==============================] - 7s 7ms/step - loss: 1.2591 - acc: 0.5714 - val_loss: 1.2340 - val_acc: 0.5839\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 3/5\n938/938 [==============================] - 7s 7ms/step - loss: 1.1983 - acc: 0.5883 - val_loss: 1.1827 - val_acc: 0.5951\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 4/5\n938/938 [==============================] - 7s 7ms/step - loss: 1.1505 - acc: 0.6001 - val_loss: 1.1417 - val_acc: 0.6021\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 5/5\n938/938 [==============================] - 7s 7ms/step - loss: 1.1122 - acc: 0.6093 - val_loss: 1.1084 - val_acc: 0.6103\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n" ] ], [ [ "One of the reasons we're not seeing higher accuracy is because some words from our dataset are missing in the pretrained GloVe vocabulary, and thus they are essentially ignored. To overcome this, we can train our own embeddings based on our dataset. \n\n\n## Training your own embeddings\n\nIn our examples, we have been using pretrained semantic embeddings, but it is interesting to see how those embeddings can be trained using either CBoW, or skip-gram architectures. This exercise goes beyond this module, but those interested might want to check out this [official TensorFlow tutorial on training Word2Vec model](https://www.tensorflow.org/tutorials/text/word2vec). Also, the **gensim** framework can be used to train the most commonly used embeddings in a few lines of code, as described [in the official documentation](https://radimrehurek.com/gensim/auto_examples/tutorials/run_word2vec.html#training-your-own-model).", "_____no_output_____" ], [ "## Contextual embeddings\n\nOne key limitation of traditional pretrained embedding representations such as Word2Vec is the fact that, even though they can capture some meaning of a word, they can't differentiate between different meanings. This can cause problems in downstream models.\n\nFor example the word 'play' has different meaning in these two different sentences:\n- I went to a **play** at the theater.\n- John wants to **play** with his friends.\n\nThe pretrained embeddings we talked about represent both meanings of the word 'play' in the same embedding. To overcome this limitation, we need to build embeddings based on the **language model**, which is trained on a large corpus of text, and *knows* how words can be put together in different contexts. Discussing contextual embeddings is out of scope for this tutorial, but we will come back to them when talking about language models in the next unit.\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" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec52065d7c8e1cfaf4b9610f941ec0c0a7a5bbd8
59,811
ipynb
Jupyter Notebook
devlog/07-TF2.ipynb
pzharrington/WeatherBench
244b8452c928d825af388ba62e0c3c21affb32d3
[ "MIT" ]
2
2020-10-20T09:38:55.000Z
2021-02-16T04:53:47.000Z
devlog/07-TF2.ipynb
pzharrington/WeatherBench
244b8452c928d825af388ba62e0c3c21affb32d3
[ "MIT" ]
8
2020-04-28T08:21:21.000Z
2020-12-08T06:07:52.000Z
devlog/07-TF2.ipynb
sagar-garg/WeatherBench
fdf208d9af6a896ccb012146dfef268722380a0d
[ "MIT" ]
4
2020-03-10T08:34:47.000Z
2022-01-31T12:39:37.000Z
87.957353
1,628
0.664376
[ [ [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "from src.score import *\nfrom src.data_generator import *\nfrom src.networks import *\nfrom src.utils import *\nimport os\nimport ast, re\nimport numpy as np\nimport xarray as xr\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom configargparse import ArgParser\nimport pickle\nimport pdb", "_____no_output_____" ], [ "exp_id = '31-resnet_multi'\ndatadir = '/data/WeatherBench/5.625deg/'\nmodel_save_dir = '/home/stephan/data/myWeatherBench/predictions/saved_models/'\npred_save_dir = '/home/stephan/data/myWeatherBench/predictions/'\nvar_dict = {'geopotential': ('z', [200, 500, 850]), 'temperature': ('t', [200, 500, 850]), 'u_component_of_wind': ('u', [200, 500, 850]), 'v_component_of_wind': ('v', [200, 500, 850]), 'constants': ['lsm','orography','lat2d']}\noutput_vars = ['z_500', 't_850']\nfilters = [128, 128, 128, 128, 128, 128, 128, 128, 2]\nkernels = [7, 3, 3, 3, 3, 3, 3, 3, 3]\nlead_time = 72\nlr = 0.5e-4\nearly_stopping_patience = 5\ndata_subsample = 2\nnorm_subsample = 30000\nepochs = 150\nnetwork_type = 'resnet'\nactivation = 'relu'\nbn_position = 'post'\nbatch_size = 4", "_____no_output_____" ], [ "limit_mem()", "_____no_output_____" ], [ "var_dict = {\n 'geopotential': ('z', [500]),\n 'temperature': ('t', [850]),\n 'constants': ['lat2d', 'orography', 'lsm']\n}", "_____no_output_____" ], [ "ds = xr.merge([xr.open_mfdataset(f'{datadir}/{var}/*.nc', combine='by_coords') for var in var_dict.keys()])", "_____no_output_____" ], [ "ds_train = ds.sel(time=slice('2000', '2015'))\nds_valid = ds.sel(time=slice('2016', '2016'))\nds_test = ds.sel(time=slice('2017', '2018'))", "_____no_output_____" ], [ "dg_train = DataGenerator(\n ds_train, var_dict, lead_time, batch_size=batch_size, output_vars=output_vars,\n data_subsample=data_subsample, norm_subsample=norm_subsample\n)\ndg_valid = DataGenerator(\n ds_valid, var_dict, lead_time, batch_size=batch_size, mean=dg_train.mean, std=dg_train.std,\n shuffle=False, output_vars=output_vars\n)\ndg_test = DataGenerator(\n ds_test, var_dict, lead_time, batch_size=batch_size, mean=dg_train.mean, std=dg_train.std,\n shuffle=False, output_vars=output_vars\n)", "DG start 17:13:14.877780\nDG normalize 17:13:14.892840\nDG load 17:13:29.254796\nLoading data into RAM\nDG done 17:14:47.016230\nDG start 17:14:47.020809\nDG normalize 17:14:47.080753\nDG load 17:14:47.099299\nLoading data into RAM\nDG done 17:14:51.985847\nDG start 17:14:51.986091\nDG normalize 17:14:51.999516\nDG load 17:14:52.005391\nLoading data into RAM\nDG done 17:15:01.576044\n" ], [ "X, y = dg_train[0]\nX.shape", "_____no_output_____" ], [ "model = build_resnet(\n filters, kernels, input_shape=(32, 64, 5),\n bn_position=bn_position, use_bias=True, l2=1e-4, skip=True,\n dropout=0.1\n)", "_____no_output_____" ], [ "model.compile(keras.optimizers.Adam(lr), 'mse')", "_____no_output_____" ], [ "model.summary()", "Model: \"model\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) [(None, 32, 64, 5)] 0 \n__________________________________________________________________________________________________\nperiodic_conv2d (PeriodicConv2D (None, 32, 64, 128) 31488 input_1[0][0] \n__________________________________________________________________________________________________\nre_lu (ReLU) (None, 32, 64, 128) 0 periodic_conv2d[0][0] \n__________________________________________________________________________________________________\nbatch_normalization (BatchNorma (None, 32, 64, 128) 512 re_lu[0][0] \n__________________________________________________________________________________________________\ndropout (Dropout) (None, 32, 64, 128) 0 batch_normalization[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_1 (PeriodicConv (None, 32, 64, 128) 147584 dropout[0][0] \n__________________________________________________________________________________________________\nre_lu_1 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_1 (BatchNor (None, 32, 64, 128) 512 re_lu_1[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 32, 64, 128) 0 batch_normalization_1[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_2 (PeriodicConv (None, 32, 64, 128) 147584 dropout_1[0][0] \n__________________________________________________________________________________________________\nre_lu_2 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_2 (BatchNor (None, 32, 64, 128) 512 re_lu_2[0][0] \n__________________________________________________________________________________________________\ndropout_2 (Dropout) (None, 32, 64, 128) 0 batch_normalization_2[0][0] \n__________________________________________________________________________________________________\nadd (Add) (None, 32, 64, 128) 0 dropout[0][0] \n dropout_2[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_3 (PeriodicConv (None, 32, 64, 128) 147584 add[0][0] \n__________________________________________________________________________________________________\nre_lu_3 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_3 (BatchNor (None, 32, 64, 128) 512 re_lu_3[0][0] \n__________________________________________________________________________________________________\ndropout_3 (Dropout) (None, 32, 64, 128) 0 batch_normalization_3[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_4 (PeriodicConv (None, 32, 64, 128) 147584 dropout_3[0][0] \n__________________________________________________________________________________________________\nre_lu_4 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_4 (BatchNor (None, 32, 64, 128) 512 re_lu_4[0][0] \n__________________________________________________________________________________________________\ndropout_4 (Dropout) (None, 32, 64, 128) 0 batch_normalization_4[0][0] \n__________________________________________________________________________________________________\nadd_1 (Add) (None, 32, 64, 128) 0 add[0][0] \n dropout_4[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_5 (PeriodicConv (None, 32, 64, 128) 147584 add_1[0][0] \n__________________________________________________________________________________________________\nre_lu_5 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_5 (BatchNor (None, 32, 64, 128) 512 re_lu_5[0][0] \n__________________________________________________________________________________________________\ndropout_5 (Dropout) (None, 32, 64, 128) 0 batch_normalization_5[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_6 (PeriodicConv (None, 32, 64, 128) 147584 dropout_5[0][0] \n__________________________________________________________________________________________________\nre_lu_6 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_6[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_6 (BatchNor (None, 32, 64, 128) 512 re_lu_6[0][0] \n__________________________________________________________________________________________________\ndropout_6 (Dropout) (None, 32, 64, 128) 0 batch_normalization_6[0][0] \n__________________________________________________________________________________________________\nadd_2 (Add) (None, 32, 64, 128) 0 add_1[0][0] \n dropout_6[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_7 (PeriodicConv (None, 32, 64, 128) 147584 add_2[0][0] \n__________________________________________________________________________________________________\nre_lu_7 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_7 (BatchNor (None, 32, 64, 128) 512 re_lu_7[0][0] \n__________________________________________________________________________________________________\ndropout_7 (Dropout) (None, 32, 64, 128) 0 batch_normalization_7[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_8 (PeriodicConv (None, 32, 64, 128) 147584 dropout_7[0][0] \n__________________________________________________________________________________________________\nre_lu_8 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_8 (BatchNor (None, 32, 64, 128) 512 re_lu_8[0][0] \n__________________________________________________________________________________________________\ndropout_8 (Dropout) (None, 32, 64, 128) 0 batch_normalization_8[0][0] \n__________________________________________________________________________________________________\nadd_3 (Add) (None, 32, 64, 128) 0 add_2[0][0] \n dropout_8[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_9 (PeriodicConv (None, 32, 64, 128) 147584 add_3[0][0] \n__________________________________________________________________________________________________\nre_lu_9 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_9 (BatchNor (None, 32, 64, 128) 512 re_lu_9[0][0] \n__________________________________________________________________________________________________\ndropout_9 (Dropout) (None, 32, 64, 128) 0 batch_normalization_9[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_10 (PeriodicCon (None, 32, 64, 128) 147584 dropout_9[0][0] \n__________________________________________________________________________________________________\nre_lu_10 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_10[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_10 (BatchNo (None, 32, 64, 128) 512 re_lu_10[0][0] \n__________________________________________________________________________________________________\ndropout_10 (Dropout) (None, 32, 64, 128) 0 batch_normalization_10[0][0] \n__________________________________________________________________________________________________\nadd_4 (Add) (None, 32, 64, 128) 0 add_3[0][0] \n dropout_10[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_11 (PeriodicCon (None, 32, 64, 128) 147584 add_4[0][0] \n__________________________________________________________________________________________________\nre_lu_11 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_11[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_11 (BatchNo (None, 32, 64, 128) 512 re_lu_11[0][0] \n__________________________________________________________________________________________________\ndropout_11 (Dropout) (None, 32, 64, 128) 0 batch_normalization_11[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_12 (PeriodicCon (None, 32, 64, 128) 147584 dropout_11[0][0] \n__________________________________________________________________________________________________\nre_lu_12 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_12[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_12 (BatchNo (None, 32, 64, 128) 512 re_lu_12[0][0] \n__________________________________________________________________________________________________\ndropout_12 (Dropout) (None, 32, 64, 128) 0 batch_normalization_12[0][0] \n__________________________________________________________________________________________________\nadd_5 (Add) (None, 32, 64, 128) 0 add_4[0][0] \n dropout_12[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_13 (PeriodicCon (None, 32, 64, 128) 147584 add_5[0][0] \n__________________________________________________________________________________________________\nre_lu_13 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_13[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_13 (BatchNo (None, 32, 64, 128) 512 re_lu_13[0][0] \n__________________________________________________________________________________________________\ndropout_13 (Dropout) (None, 32, 64, 128) 0 batch_normalization_13[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_14 (PeriodicCon (None, 32, 64, 128) 147584 dropout_13[0][0] \n__________________________________________________________________________________________________\nre_lu_14 (ReLU) (None, 32, 64, 128) 0 periodic_conv2d_14[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_14 (BatchNo (None, 32, 64, 128) 512 re_lu_14[0][0] \n__________________________________________________________________________________________________\ndropout_14 (Dropout) (None, 32, 64, 128) 0 batch_normalization_14[0][0] \n__________________________________________________________________________________________________\nadd_6 (Add) (None, 32, 64, 128) 0 add_5[0][0] \n dropout_14[0][0] \n__________________________________________________________________________________________________\nperiodic_conv2d_15 (PeriodicCon (None, 32, 64, 2) 2306 add_6[0][0] \n==================================================================================================\nTotal params: 2,107,650\nTrainable params: 2,103,810\nNon-trainable params: 3,840\n__________________________________________________________________________________________________\n" ], [ "X.dtype", "_____no_output_____" ], [ "p1 = model(X)", "_____no_output_____" ], [ "p1[0,0,0]", "_____no_output_____" ], [ "model.save('./test.h5')", "_____no_output_____" ], [ "a = keras.models.load_model('./test.h5', custom_objects={'PeriodicConv2D': PeriodicConv2D})", "_____no_output_____" ], [ "a(X)[0,0,0]", "_____no_output_____" ], [ "callbacks = []\ncallbacks.append(tf.keras.callbacks.EarlyStopping(\n monitor='val_loss',\n min_delta=0,\n patience=early_stopping_patience,\n verbose=1,\n mode='auto',\n restore_best_weights=True\n ))", "_____no_output_____" ], [ "history = model.fit_generator(dg_train, epochs=1, validation_data=dg_valid,\n callbacks=callbacks\n )", " 798/17523 [>.............................] - ETA: 33:26 - loss: 2.3522" ], [ "p1 = model(X)", "_____no_output_____" ], [ "p1[0,0,0]", "_____no_output_____" ], [ "model.save('./test.h5')", "_____no_output_____" ], [ "a = keras.models.load_model('./test.h5', custom_objects={'PeriodicConv2D': PeriodicConv2D})", "_____no_output_____" ], [ "a(X)[0,0,0]", "_____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" ] ]
ec5206ccbb6b27a31985d07e74c1f17d7b78c231
32,208
ipynb
Jupyter Notebook
notebooks/Matching.ipynb
florpi/GaHaCo
5e42511877ee7cf3de3935f57ebea6ca86cf4ea5
[ "MIT" ]
null
null
null
notebooks/Matching.ipynb
florpi/GaHaCo
5e42511877ee7cf3de3935f57ebea6ca86cf4ea5
[ "MIT" ]
12
2019-09-27T07:33:27.000Z
2019-11-29T16:48:02.000Z
notebooks/Matching.ipynb
florpi/GaHaCo
5e42511877ee7cf3de3935f57ebea6ca86cf4ea5
[ "MIT" ]
null
null
null
133.643154
26,028
0.882017
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "DATA_DIR = '/cosma7/data/dp004/dc-cues1/tng_dataframes/'\nHALO_MASS_CUT = 1.e11", "_____no_output_____" ], [ "merge_df = pd.read_hdf(DATA_DIR + 'TNG300Dark_Hydro_MergerTree.hdf5')\ndark_df = pd.read_hdf(DATA_DIR + 'TNG300dark_subfind.hdf5')\nhdyro_df = pd.read_hdf(DATA_DIR + 'TNG300hydro_subfind.hdf5')", "_____no_output_____" ], [ "merge_df = merge_df.loc[merge_df['M200_HYDRO'] > HALO_MASS_CUT]", "_____no_output_____" ], [ "matched_df = pd.merge(merge_df, dark_df, on = ['ID_DMO'], how = 'inner')", "_____no_output_____" ], [ "full_df = pd.merge(matched_df, hdyro_df, on = ['ID_HYDRO'], how = 'inner',suffixes=('_dmo', '_hydro'))", "_____no_output_____" ], [ "def periodic_distance(df, boxsize: float) -> np.array:\n a = np.array([df['x_dmo'], df['y_dmo'], df['z_dmo']])\n b = np.array([df['x_hydro'], df['y_hydro'], df['z_hydro']])\ns\n bounds = boxsize * np.ones(3)\n min_dists = np.min(np.dstack(((a - b) % bounds, (b - a) % bounds)), axis=2)\n dists = np.sqrt(np.sum(min_dists ** 2, axis=1))\n return dists[0]", "_____no_output_____" ], [ "full_df['displacement'] = full_df.apply(lambda x: periodic_distance(x, 300.), axis=1)\n", "_____no_output_____" ], [ "one2one = full_df.drop_duplicates(subset='ID_DMO')\n", "_____no_output_____" ], [ "len(one2one)", "_____no_output_____" ], [ "plt.hist(full_df['displacement'], log=True,alpha=0.3, label='1-Many')\nplt.hist(one2one['displacement'], log=True, alpha=0.3, label='1-1')\nplt.xlabel('Displacement DMO to HYDRO')\nplt.ylabel('Number of halos')\nplt.legend()", "_____no_output_____" ] ], [ [ "# Stellar Mass after thresholding", "_____no_output_____" ] ], [ [ "df_1 = pd.read_hdf(DATA_DIR + 'merged_dataframe_v2_threshold_1.h5')\ndf_4 = pd.read_hdf(DATA_DIR + 'merged_dataframe_v2_threshold_4.h5')\n", "_____no_output_____" ], [ "df_1.columns", "_____no_output_____" ], [ "#.loglog(full_df.M200_DMO, full_df.M_stars_central,\n# linestyle='', marker='o', markersize=2)\nplt.loglog(df_1.M200_DMO, df_1.M_stars_central,\n linestyle='', marker='o', markersize=2,\n alpha=0.2, label = 'd<1')\nplt.loglog(df_4.M200_DMO, df_4.M_stars_central,\n linestyle='', marker='o', markersize=2, \n alpha=0.4, label='d < 4')\nplt.legend()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ec520782e770d721ef99407297ec92984cc024aa
55,072
ipynb
Jupyter Notebook
notebooks/02.04-Getting-Spatial-Features-from-Pose.ipynb
wrbl96/pyRosetta
63dccca0c7d84a04068f0d981cc0b00b138a7b9b
[ "MIT" ]
226
2019-08-05T17:36:59.000Z
2022-03-27T09:30:21.000Z
notebooks/02.04-Getting-Spatial-Features-from-Pose.ipynb
wrbl96/pyRosetta
63dccca0c7d84a04068f0d981cc0b00b138a7b9b
[ "MIT" ]
44
2019-08-21T15:47:53.000Z
2022-03-18T03:45:07.000Z
notebooks/02.04-Getting-Spatial-Features-from-Pose.ipynb
wrbl96/pyRosetta
63dccca0c7d84a04068f0d981cc0b00b138a7b9b
[ "MIT" ]
86
2019-12-23T07:18:27.000Z
2022-03-31T08:33:12.000Z
140.489796
44,076
0.893394
[ [ [ "<!--NOTEBOOK_HEADER-->\n*This notebook contains material from [PyRosetta](https://RosettaCommons.github.io/PyRosetta.notebooks);\ncontent is available [on Github](https://github.com/RosettaCommons/PyRosetta.notebooks.git).*", "_____no_output_____" ], [ "<!--NAVIGATION-->\n< [Accessing PyRosetta Documentation](http://nbviewer.jupyter.org/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.03-Accessing-PyRosetta-Documentation.ipynb) | [Contents](toc.ipynb) | [Index](index.ipynb) | [Protein Geometry](http://nbviewer.jupyter.org/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.05-Protein-Geometry.ipynb) ><p><a href=\"https://colab.research.google.com/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.04-Getting-Spatial-Features-from-Pose.ipynb\"><img align=\"left\" src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Colab\" title=\"Open in Google Colaboratory\"></a>", "_____no_output_____" ], [ "# Getting spatial features from a Pose\nKeywords: conformation(), bond_length(), AtomID, atom_index()", "_____no_output_____" ] ], [ [ "# Notebook setup\nimport sys\nif 'google.colab' in sys.modules:\n !pip install pyrosettacolabsetup\n import pyrosettacolabsetup\n pyrosettacolabsetup.mount_pyrosetta_install()\n print (\"Notebook is set for PyRosetta use in Colab. Have fun!\")", "_____no_output_____" ], [ "from pyrosetta import *\ninit()", "_____no_output_____" ] ], [ [ "**From previous section:**\nMake sure you are in the directory with the pdb files:\n\n`cd google_drive/My\\ Drive/student-notebooks/`", "_____no_output_____" ] ], [ [ "pose = pose_from_pdb(\"inputs/5tj3.pdb\")", "_____no_output_____" ], [ "from IPython.display import Image\nImage('./Media/dihedral-final.png',width='500')", "_____no_output_____" ] ], [ [ "`Pose` objects make it easy to access angles, distances, and torsions for analysis. Lets take a look at how to get backbone torsions first.", "_____no_output_____" ] ], [ [ "#resid = \"get the pose residue number for chain A:res 28 using the pdb2pose function\"\n### BEGIN SOLUTION\nresid = pose.pdb_info().pdb2pose('A', 28)\n### END SOLUTION", "_____no_output_____" ], [ "print(\"phi:\", pose.phi(resid))\nprint(\"psi:\", pose.psi(resid))\nprint(\"chi1:\", pose.chi(1, resid))", "phi: -149.17513487055064\npsi: 151.30037995499168\nchi1: -82.850785668982\n" ] ], [ [ "Say we want to find the length of the $N$-$C_\\alpha$ and $C_\\alpha$-$C$ bonds for residue A:28 from the PDB file. We can use a couple approaches. The first involves using the bond length in the `Conformation` class, which stores some info on protein geometry. Take a look at some of the methods in the `Conformation` class using tab completion.", "_____no_output_____" ] ], [ [ "conformation = pose.conformation()\n# do some tab completion here to explore the Conformation class methods\n#conformation.", "_____no_output_____" ] ], [ [ "Look at the documentation for the method `conformation.bond_length` below. Remember using the `?`", "_____no_output_____" ] ], [ [ "### BEGIN SOLUTION\n# ?conformation.bond_length\n### END SOLUTION", "Object `conformation.bond_length` not found.\n" ] ], [ [ "To use the bond_length method in the `Conformation` class, it looks like we'll need to make `AtomID` objects. We can do this using an atom index and residue ID as follows:", "_____no_output_____" ] ], [ [ "# Double Check: does resid contain the Pose numbering or PDB numbering?\nres_28 = pose.residue(resid)\nN28 = AtomID(res_28.atom_index(\"N\"), resid)\nCA28 = AtomID(res_28.atom_index(\"CA\"), resid)\nC28 = AtomID(res_28.atom_index(\"C\"), resid)\n\n# try printing out an AtomID object!", "_____no_output_____" ], [ "### BEGIN SOLUTION\nprint(N28)\n### END SOLUTION", " atomno= 1 rsd= 5 \n" ] ], [ [ "As usual, if you did not know how to construct an `AtomID`, you could check the documentation using `?AtomID`.\n\nNow we can compute the bond lengths:", "_____no_output_____" ] ], [ [ "print(pose.conformation().bond_length(N28, CA28))\nprint(pose.conformation().bond_length(CA28, C28))", "1.456100614655453\n1.5184027792387658\n" ] ], [ [ "Alternatively, we can compute bond lengths ourselves starting from the xyz coordinates of the atoms. \n\nThe method `xyz` of `Residue` returns a `Vector` class. The `Vector` class has various useful builtin methods including computing dot products, cross products, and norms. Through operator overloading in the `Vector` class, you can just subtract and add vector objects and they will manipulate the corresponding vectors appropriately.", "_____no_output_____" ] ], [ [ "N_xyz = res_28.xyz(\"N\")\nCA_xyz = res_28.xyz(\"CA\")\nC_xyz = res_28.xyz(\"C\")\nN_CA_vector = CA_xyz - N_xyz\nCA_C_vector = CA_xyz - C_xyz\nprint(N_CA_vector.norm())\nprint(CA_C_vector.norm())", "1.456100614655453\n1.5184027792387658\n" ] ], [ [ "Thankfully, the two approaches for computing distances check out!\n\n**Note**: Not all bond lengths, angles, and torsions will be accessible using the `Conformation` object. That is because the `Conformation` object stores only the subset it needs to generate xyz locations for the atoms in the pose. The most stable way to get this information is to compute it using the xyz Cartesian coordinate vectors as a starting point.", "_____no_output_____" ], [ "## References\nThis notebook includes some concepts and exercises from:\n\n\"Workshop #2: PyRosetta\" in the PyRosetta workbook: https://graylab.jhu.edu/pyrosetta/downloads/documentation/pyrosetta4_online_format/PyRosetta4_Workshop2_PyRosetta.pdf\n\n\"Workshop #4.1: PyMOL_Mover\" in the PyRosetta workbook: \nhttp://www.pyrosetta.org/pymol_mover-tutorial", "_____no_output_____" ], [ "<!--NAVIGATION-->\n< [Accessing PyRosetta Documentation](http://nbviewer.jupyter.org/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.03-Accessing-PyRosetta-Documentation.ipynb) | [Contents](toc.ipynb) | [Index](index.ipynb) | [Protein Geometry](http://nbviewer.jupyter.org/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.05-Protein-Geometry.ipynb) ><p><a href=\"https://colab.research.google.com/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.04-Getting-Spatial-Features-from-Pose.ipynb\"><img align=\"left\" src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Colab\" title=\"Open in Google Colaboratory\"></a>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
ec521e216e8f6e986c69c8ff751da7d1cfeac4f1
2,056
ipynb
Jupyter Notebook
artificial-intelligence-with-python-ja-master/Chapter 13/frame_diff.ipynb
tryoutlab/python-ai-oreilly
111a0db4a9d5bf7ec4c07b1e9e357ed4fa225f28
[ "Unlicense" ]
null
null
null
artificial-intelligence-with-python-ja-master/Chapter 13/frame_diff.ipynb
tryoutlab/python-ai-oreilly
111a0db4a9d5bf7ec4c07b1e9e357ed4fa225f28
[ "Unlicense" ]
null
null
null
artificial-intelligence-with-python-ja-master/Chapter 13/frame_diff.ipynb
tryoutlab/python-ai-oreilly
111a0db4a9d5bf7ec4c07b1e9e357ed4fa225f28
[ "Unlicense" ]
null
null
null
25.7
69
0.546693
[ [ [ "%run ipython_show_image.ipynb\nimport cv2\n\ndef get_gray_frame(cap, scaling_factor):\n frame = get_frame(cap, scaling_factor)\n if frame is None: return None\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) \n return gray\n \ndef frame_diff(prev_frame, cur_frame, next_frame): \n diff_frames_1 = cv2.absdiff(next_frame, cur_frame) \n diff_frames_2 = cv2.absdiff(cur_frame, prev_frame) \n return cv2.bitwise_and(diff_frames_1, diff_frames_2) \n \ncap = cv2.VideoCapture('bbb.mp4') \nscaling_factor = 1 \n\nprev_frame = get_gray_frame(cap, scaling_factor) \ncur_frame = get_gray_frame(cap, scaling_factor) \nnext_frame = get_gray_frame(cap, scaling_factor) \n\ntry:\n while True:\n diff = frame_diff(prev_frame, cur_frame, next_frame)\n show_image(diff)\n\n prev_frame = cur_frame \n cur_frame = next_frame \n next_frame = get_gray_frame(cap, scaling_factor) \n if next_frame is None: break\n \nexcept KeyboardInterrupt:\n print('Interrupted')\n\ncap.release()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
ec5228d0111704e09660be0c976b30669bdfa0f3
511,613
ipynb
Jupyter Notebook
Model backlog/EfficientNet/EfficientNetB5/226 - EfficientNetB5-Reg-Img224 0,5data No TTA.ipynb
ThinkBricks/APTOS2019BlindnessDetection
e524fd69f83a1252710076c78b6a5236849cd885
[ "MIT" ]
23
2019-09-08T17:19:16.000Z
2022-02-02T16:20:09.000Z
Model backlog/EfficientNet/EfficientNetB5/226 - EfficientNetB5-Reg-Img224 0,5data No TTA.ipynb
ThinkBricks/APTOS2019BlindnessDetection
e524fd69f83a1252710076c78b6a5236849cd885
[ "MIT" ]
1
2020-03-10T18:42:12.000Z
2020-09-18T22:02:38.000Z
Model backlog/EfficientNet/EfficientNetB5/226 - EfficientNetB5-Reg-Img224 0,5data No TTA.ipynb
ThinkBricks/APTOS2019BlindnessDetection
e524fd69f83a1252710076c78b6a5236849cd885
[ "MIT" ]
16
2019-09-21T12:29:59.000Z
2022-03-21T00:42:26.000Z
135.706366
83,432
0.745251
[ [ [ "## Dependencies", "_____no_output_____" ] ], [ [ "import os\nimport sys\nimport cv2\nimport shutil\nimport random\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport multiprocessing as mp\nimport matplotlib.pyplot as plt\nfrom tensorflow import set_random_seed\nfrom sklearn.utils import class_weight\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, cohen_kappa_score\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.utils import to_categorical\nfrom keras import optimizers, applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Dense, Dropout, GlobalAveragePooling2D, Input\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, Callback, LearningRateScheduler\n\ndef seed_everything(seed=0):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n set_random_seed(0)\n\nseed = 0\nseed_everything(seed)\n%matplotlib inline\nsns.set(style=\"whitegrid\")\nwarnings.filterwarnings(\"ignore\")\nsys.path.append(os.path.abspath('../input/efficientnet/efficientnet-master/efficientnet-master/'))\nfrom efficientnet import *", "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n/opt/conda/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\nUsing TensorFlow backend.\n" ] ], [ [ "## Load data", "_____no_output_____" ] ], [ [ "hold_out_set = pd.read_csv('../input/aptos-split-oldnew/hold-out_5.csv')\nX_train = hold_out_set[hold_out_set['set'] == 'train']\nX_val = hold_out_set[hold_out_set['set'] == 'validation']\ntest = pd.read_csv('../input/aptos2019-blindness-detection/test.csv')\n\ntest[\"id_code\"] = test[\"id_code\"].apply(lambda x: x + \".png\")\n\nprint('Number of train samples: ', X_train.shape[0])\nprint('Number of validation samples: ', X_val.shape[0])\nprint('Number of test samples: ', test.shape[0])\ndisplay(X_train.head())", "Number of train samples: 17599\nNumber of validation samples: 1831\nNumber of test samples: 1928\n" ] ], [ [ "# Model parameters", "_____no_output_____" ] ], [ [ "# Model parameters\nFACTOR = 4\nBATCH_SIZE = 8 * FACTOR\nEPOCHS = 20\nWARMUP_EPOCHS = 5\nLEARNING_RATE = 1e-4 * FACTOR\nWARMUP_LEARNING_RATE = 1e-3 * FACTOR\nHEIGHT = 224\nWIDTH = 224\nCHANNELS = 3\nES_PATIENCE = 5\nRLROP_PATIENCE = 3\nDECAY_DROP = 0.5\nLR_WARMUP_EPOCHS_1st = 2\nLR_WARMUP_EPOCHS_2nd = 5\nSTEP_SIZE = len(X_train) // BATCH_SIZE\nTOTAL_STEPS_1st = WARMUP_EPOCHS * STEP_SIZE\nTOTAL_STEPS_2nd = EPOCHS * STEP_SIZE\nWARMUP_STEPS_1st = LR_WARMUP_EPOCHS_1st * STEP_SIZE\nWARMUP_STEPS_2nd = LR_WARMUP_EPOCHS_2nd * STEP_SIZE", "_____no_output_____" ] ], [ [ "# Pre-procecess images", "_____no_output_____" ] ], [ [ "old_data_base_path = '../input/diabetic-retinopathy-resized/resized_train/resized_train/'\nnew_data_base_path = '../input/aptos2019-blindness-detection/train_images/'\ntest_base_path = '../input/aptos2019-blindness-detection/test_images/'\ntrain_dest_path = 'base_dir/train_images/'\nvalidation_dest_path = 'base_dir/validation_images/'\ntest_dest_path = 'base_dir/test_images/'\n\n# Making sure directories don't exist\nif os.path.exists(train_dest_path):\n shutil.rmtree(train_dest_path)\nif os.path.exists(validation_dest_path):\n shutil.rmtree(validation_dest_path)\nif os.path.exists(test_dest_path):\n shutil.rmtree(test_dest_path)\n \n# Creating train, validation and test directories\nos.makedirs(train_dest_path)\nos.makedirs(validation_dest_path)\nos.makedirs(test_dest_path)\n\ndef crop_image(img, tol=7):\n if img.ndim ==2:\n mask = img>tol\n return img[np.ix_(mask.any(1),mask.any(0))]\n elif img.ndim==3:\n gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n mask = gray_img>tol\n check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n if (check_shape == 0): # image is too dark so that we crop out everything,\n return img # return original image\n else:\n img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n img = np.stack([img1,img2,img3],axis=-1)\n \n return img\n\ndef circle_crop(img):\n img = crop_image(img)\n\n height, width, depth = img.shape\n largest_side = np.max((height, width))\n img = cv2.resize(img, (largest_side, largest_side))\n\n height, width, depth = img.shape\n\n x = width//2\n y = height//2\n r = np.amin((x, y))\n\n circle_img = np.zeros((height, width), np.uint8)\n cv2.circle(circle_img, (x, y), int(r), 1, thickness=-1)\n img = cv2.bitwise_and(img, img, mask=circle_img)\n img = crop_image(img)\n\n return img\n \ndef preprocess_image(image_id, base_path, save_path, HEIGHT=HEIGHT, WIDTH=WIDTH, sigmaX=10):\n image = cv2.imread(base_path + image_id)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = circle_crop(image)\n image = cv2.resize(image, (HEIGHT, WIDTH))\n# image = cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0,0), sigmaX), -4 , 128)\n cv2.imwrite(save_path + image_id, image)\n \ndef preprocess_data(df, HEIGHT=HEIGHT, WIDTH=WIDTH, sigmaX=10):\n df = df.reset_index()\n for i in range(df.shape[0]):\n item = df.iloc[i]\n image_id = item['id_code']\n item_set = item['set']\n item_data = item['data']\n if item_set == 'train':\n if item_data == 'new':\n preprocess_image(image_id, new_data_base_path, train_dest_path)\n if item_data == 'old':\n preprocess_image(image_id, old_data_base_path, train_dest_path)\n if item_set == 'validation':\n if item_data == 'new':\n preprocess_image(image_id, new_data_base_path, validation_dest_path)\n if item_data == 'old':\n preprocess_image(image_id, old_data_base_path, validation_dest_path)\n \ndef preprocess_test(df, base_path=test_base_path, save_path=test_dest_path, HEIGHT=HEIGHT, WIDTH=WIDTH, sigmaX=10):\n df = df.reset_index()\n for i in range(df.shape[0]):\n image_id = df.iloc[i]['id_code']\n preprocess_image(image_id, base_path, save_path)\n\nn_cpu = mp.cpu_count()\ntrain_n_cnt = X_train.shape[0] // n_cpu\nval_n_cnt = X_val.shape[0] // n_cpu\ntest_n_cnt = test.shape[0] // n_cpu\n\n# Pre-procecss old data train set\npool = mp.Pool(n_cpu)\ndfs = [X_train.iloc[train_n_cnt*i:train_n_cnt*(i+1)] for i in range(n_cpu)]\ndfs[-1] = X_train.iloc[train_n_cnt*(n_cpu-1):]\nres = pool.map(preprocess_data, [x_df for x_df in dfs])\npool.close()\n\n# Pre-procecss validation set\npool = mp.Pool(n_cpu)\ndfs = [X_val.iloc[val_n_cnt*i:val_n_cnt*(i+1)] for i in range(n_cpu)]\ndfs[-1] = X_val.iloc[val_n_cnt*(n_cpu-1):] \nres = pool.map(preprocess_data, [x_df for x_df in dfs])\npool.close()\n\n# Pre-procecss test set\npool = mp.Pool(n_cpu)\ndfs = [test.iloc[test_n_cnt*i:test_n_cnt*(i+1)] for i in range(n_cpu)]\ndfs[-1] = test.iloc[test_n_cnt*(n_cpu-1):] \nres = pool.map(preprocess_test, [x_df for x_df in dfs])\npool.close()", "_____no_output_____" ] ], [ [ "# Data generator", "_____no_output_____" ] ], [ [ "datagen=ImageDataGenerator(rescale=1./255, \n rotation_range=360,\n horizontal_flip=True,\n vertical_flip=True)\n\ntest_datagen=ImageDataGenerator(rescale=1./255)\n\ntrain_generator=datagen.flow_from_dataframe(\n dataframe=X_train,\n directory=train_dest_path,\n x_col=\"id_code\",\n y_col=\"diagnosis\",\n class_mode=\"raw\",\n batch_size=BATCH_SIZE,\n target_size=(HEIGHT, WIDTH),\n seed=seed)\n\nvalid_generator=datagen.flow_from_dataframe(\n dataframe=X_val,\n directory=validation_dest_path,\n x_col=\"id_code\",\n y_col=\"diagnosis\",\n class_mode=\"raw\",\n batch_size=BATCH_SIZE,\n target_size=(HEIGHT, WIDTH),\n seed=seed)\n\ntest_generator=test_datagen.flow_from_dataframe( \n dataframe=test,\n directory=test_dest_path,\n x_col=\"id_code\",\n batch_size=1,\n class_mode=None,\n shuffle=False,\n target_size=(HEIGHT, WIDTH),\n seed=seed)", "Found 17599 validated image filenames.\nFound 1831 validated image filenames.\nFound 1928 validated image filenames.\n" ], [ "def cosine_decay_with_warmup(global_step,\n learning_rate_base,\n total_steps,\n warmup_learning_rate=0.0,\n warmup_steps=0,\n hold_base_rate_steps=0):\n \"\"\"\n Cosine decay schedule with warm up period.\n In this schedule, the learning rate grows linearly from warmup_learning_rate\n to learning_rate_base for warmup_steps, then transitions to a cosine decay\n schedule.\n :param global_step {int}: global step.\n :param learning_rate_base {float}: base learning rate.\n :param total_steps {int}: total number of training steps.\n :param warmup_learning_rate {float}: initial learning rate for warm up. (default: {0.0}).\n :param warmup_steps {int}: number of warmup steps. (default: {0}).\n :param hold_base_rate_steps {int}: Optional number of steps to hold base learning rate before decaying. (default: {0}).\n :param global_step {int}: global step.\n :Returns : a float representing learning rate.\n :Raises ValueError: if warmup_learning_rate is larger than learning_rate_base, or if warmup_steps is larger than total_steps.\n \"\"\"\n\n if total_steps < warmup_steps:\n raise ValueError('total_steps must be larger or equal to warmup_steps.')\n learning_rate = 0.5 * learning_rate_base * (1 + np.cos(\n np.pi *\n (global_step - warmup_steps - hold_base_rate_steps\n ) / float(total_steps - warmup_steps - hold_base_rate_steps)))\n if hold_base_rate_steps > 0:\n learning_rate = np.where(global_step > warmup_steps + hold_base_rate_steps,\n learning_rate, learning_rate_base)\n if warmup_steps > 0:\n if learning_rate_base < warmup_learning_rate:\n raise ValueError('learning_rate_base must be larger or equal to warmup_learning_rate.')\n slope = (learning_rate_base - warmup_learning_rate) / warmup_steps\n warmup_rate = slope * global_step + warmup_learning_rate\n learning_rate = np.where(global_step < warmup_steps, warmup_rate,\n learning_rate)\n return np.where(global_step > total_steps, 0.0, learning_rate)\n\n\nclass WarmUpCosineDecayScheduler(Callback):\n \"\"\"Cosine decay with warmup learning rate scheduler\"\"\"\n\n def __init__(self,\n learning_rate_base,\n total_steps,\n global_step_init=0,\n warmup_learning_rate=0.0,\n warmup_steps=0,\n hold_base_rate_steps=0,\n verbose=0):\n \"\"\"\n Constructor for cosine decay with warmup learning rate scheduler.\n :param learning_rate_base {float}: base learning rate.\n :param total_steps {int}: total number of training steps.\n :param global_step_init {int}: initial global step, e.g. from previous checkpoint.\n :param warmup_learning_rate {float}: initial learning rate for warm up. (default: {0.0}).\n :param warmup_steps {int}: number of warmup steps. (default: {0}).\n :param hold_base_rate_steps {int}: Optional number of steps to hold base learning rate before decaying. (default: {0}).\n :param verbose {int}: quiet, 1: update messages. (default: {0}).\n \"\"\"\n\n super(WarmUpCosineDecayScheduler, self).__init__()\n self.learning_rate_base = learning_rate_base\n self.total_steps = total_steps\n self.global_step = global_step_init\n self.warmup_learning_rate = warmup_learning_rate\n self.warmup_steps = warmup_steps\n self.hold_base_rate_steps = hold_base_rate_steps\n self.verbose = verbose\n self.learning_rates = []\n\n def on_batch_end(self, batch, logs=None):\n self.global_step = self.global_step + 1\n lr = K.get_value(self.model.optimizer.lr)\n self.learning_rates.append(lr)\n\n def on_batch_begin(self, batch, logs=None):\n lr = cosine_decay_with_warmup(global_step=self.global_step,\n learning_rate_base=self.learning_rate_base,\n total_steps=self.total_steps,\n warmup_learning_rate=self.warmup_learning_rate,\n warmup_steps=self.warmup_steps,\n hold_base_rate_steps=self.hold_base_rate_steps)\n K.set_value(self.model.optimizer.lr, lr)\n if self.verbose > 0:\n print('\\nBatch %02d: setting learning rate to %s.' % (self.global_step + 1, lr))", "_____no_output_____" ] ], [ [ "# Model", "_____no_output_____" ] ], [ [ "def create_model(input_shape):\n input_tensor = Input(shape=input_shape)\n base_model = EfficientNetB5(weights=None, \n include_top=False,\n input_tensor=input_tensor)\n base_model.load_weights('../input/efficientnet-keras-weights-b0b5/efficientnet-b5_imagenet_1000_notop.h5')\n\n x = GlobalAveragePooling2D()(base_model.output)\n final_output = Dense(1, activation='linear', name='final_output')(x)\n model = Model(input_tensor, final_output)\n \n return model", "_____no_output_____" ] ], [ [ "# Train top layers", "_____no_output_____" ] ], [ [ "model = create_model(input_shape=(HEIGHT, WIDTH, CHANNELS))\n\nfor layer in model.layers:\n layer.trainable = False\n\nfor i in range(-2, 0):\n model.layers[i].trainable = True\n\ncosine_lr_1st = WarmUpCosineDecayScheduler(learning_rate_base=WARMUP_LEARNING_RATE,\n total_steps=TOTAL_STEPS_1st,\n warmup_learning_rate=0.0,\n warmup_steps=WARMUP_STEPS_1st,\n hold_base_rate_steps=(2 * STEP_SIZE))\n\nmetric_list = [\"accuracy\"]\ncallback_list = [cosine_lr_1st]\noptimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE)\nmodel.compile(optimizer=optimizer, loss='mean_squared_error', metrics=metric_list)\nmodel.summary()", "__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, 224, 224, 3) 0 \n__________________________________________________________________________________________________\nconv2d_1 (Conv2D) (None, 112, 112, 48) 1296 input_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_1 (BatchNor (None, 112, 112, 48) 192 conv2d_1[0][0] \n__________________________________________________________________________________________________\nswish_1 (Swish) (None, 112, 112, 48) 0 batch_normalization_1[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_1 (DepthwiseCo (None, 112, 112, 48) 432 swish_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_2 (BatchNor (None, 112, 112, 48) 192 depthwise_conv2d_1[0][0] \n__________________________________________________________________________________________________\nswish_2 (Swish) (None, 112, 112, 48) 0 batch_normalization_2[0][0] \n__________________________________________________________________________________________________\nlambda_1 (Lambda) (None, 1, 1, 48) 0 swish_2[0][0] \n__________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 1, 1, 12) 588 lambda_1[0][0] \n__________________________________________________________________________________________________\nswish_3 (Swish) (None, 1, 1, 12) 0 conv2d_2[0][0] \n__________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 1, 1, 48) 624 swish_3[0][0] \n__________________________________________________________________________________________________\nactivation_1 (Activation) (None, 1, 1, 48) 0 conv2d_3[0][0] \n__________________________________________________________________________________________________\nmultiply_1 (Multiply) (None, 112, 112, 48) 0 activation_1[0][0] \n swish_2[0][0] \n__________________________________________________________________________________________________\nconv2d_4 (Conv2D) (None, 112, 112, 24) 1152 multiply_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_3 (BatchNor (None, 112, 112, 24) 96 conv2d_4[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_2 (DepthwiseCo (None, 112, 112, 24) 216 batch_normalization_3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_4 (BatchNor (None, 112, 112, 24) 96 depthwise_conv2d_2[0][0] \n__________________________________________________________________________________________________\nswish_4 (Swish) (None, 112, 112, 24) 0 batch_normalization_4[0][0] \n__________________________________________________________________________________________________\nlambda_2 (Lambda) (None, 1, 1, 24) 0 swish_4[0][0] \n__________________________________________________________________________________________________\nconv2d_5 (Conv2D) (None, 1, 1, 6) 150 lambda_2[0][0] \n__________________________________________________________________________________________________\nswish_5 (Swish) (None, 1, 1, 6) 0 conv2d_5[0][0] \n__________________________________________________________________________________________________\nconv2d_6 (Conv2D) (None, 1, 1, 24) 168 swish_5[0][0] \n__________________________________________________________________________________________________\nactivation_2 (Activation) (None, 1, 1, 24) 0 conv2d_6[0][0] \n__________________________________________________________________________________________________\nmultiply_2 (Multiply) (None, 112, 112, 24) 0 activation_2[0][0] \n swish_4[0][0] \n__________________________________________________________________________________________________\nconv2d_7 (Conv2D) (None, 112, 112, 24) 576 multiply_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_5 (BatchNor (None, 112, 112, 24) 96 conv2d_7[0][0] \n__________________________________________________________________________________________________\ndrop_connect_1 (DropConnect) (None, 112, 112, 24) 0 batch_normalization_5[0][0] \n__________________________________________________________________________________________________\nadd_1 (Add) (None, 112, 112, 24) 0 drop_connect_1[0][0] \n batch_normalization_3[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_3 (DepthwiseCo (None, 112, 112, 24) 216 add_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_6 (BatchNor (None, 112, 112, 24) 96 depthwise_conv2d_3[0][0] \n__________________________________________________________________________________________________\nswish_6 (Swish) (None, 112, 112, 24) 0 batch_normalization_6[0][0] \n__________________________________________________________________________________________________\nlambda_3 (Lambda) (None, 1, 1, 24) 0 swish_6[0][0] \n__________________________________________________________________________________________________\nconv2d_8 (Conv2D) (None, 1, 1, 6) 150 lambda_3[0][0] \n__________________________________________________________________________________________________\nswish_7 (Swish) (None, 1, 1, 6) 0 conv2d_8[0][0] \n__________________________________________________________________________________________________\nconv2d_9 (Conv2D) (None, 1, 1, 24) 168 swish_7[0][0] \n__________________________________________________________________________________________________\nactivation_3 (Activation) (None, 1, 1, 24) 0 conv2d_9[0][0] \n__________________________________________________________________________________________________\nmultiply_3 (Multiply) (None, 112, 112, 24) 0 activation_3[0][0] \n swish_6[0][0] \n__________________________________________________________________________________________________\nconv2d_10 (Conv2D) (None, 112, 112, 24) 576 multiply_3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_7 (BatchNor (None, 112, 112, 24) 96 conv2d_10[0][0] \n__________________________________________________________________________________________________\ndrop_connect_2 (DropConnect) (None, 112, 112, 24) 0 batch_normalization_7[0][0] \n__________________________________________________________________________________________________\nadd_2 (Add) (None, 112, 112, 24) 0 drop_connect_2[0][0] \n add_1[0][0] \n__________________________________________________________________________________________________\nconv2d_11 (Conv2D) (None, 112, 112, 144 3456 add_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_8 (BatchNor (None, 112, 112, 144 576 conv2d_11[0][0] \n__________________________________________________________________________________________________\nswish_8 (Swish) (None, 112, 112, 144 0 batch_normalization_8[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_4 (DepthwiseCo (None, 56, 56, 144) 1296 swish_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_9 (BatchNor (None, 56, 56, 144) 576 depthwise_conv2d_4[0][0] \n__________________________________________________________________________________________________\nswish_9 (Swish) (None, 56, 56, 144) 0 batch_normalization_9[0][0] \n__________________________________________________________________________________________________\nlambda_4 (Lambda) (None, 1, 1, 144) 0 swish_9[0][0] \n__________________________________________________________________________________________________\nconv2d_12 (Conv2D) (None, 1, 1, 6) 870 lambda_4[0][0] \n__________________________________________________________________________________________________\nswish_10 (Swish) (None, 1, 1, 6) 0 conv2d_12[0][0] \n__________________________________________________________________________________________________\nconv2d_13 (Conv2D) (None, 1, 1, 144) 1008 swish_10[0][0] \n__________________________________________________________________________________________________\nactivation_4 (Activation) (None, 1, 1, 144) 0 conv2d_13[0][0] \n__________________________________________________________________________________________________\nmultiply_4 (Multiply) (None, 56, 56, 144) 0 activation_4[0][0] \n swish_9[0][0] \n__________________________________________________________________________________________________\nconv2d_14 (Conv2D) (None, 56, 56, 40) 5760 multiply_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_10 (BatchNo (None, 56, 56, 40) 160 conv2d_14[0][0] \n__________________________________________________________________________________________________\nconv2d_15 (Conv2D) (None, 56, 56, 240) 9600 batch_normalization_10[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_11 (BatchNo (None, 56, 56, 240) 960 conv2d_15[0][0] \n__________________________________________________________________________________________________\nswish_11 (Swish) (None, 56, 56, 240) 0 batch_normalization_11[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_5 (DepthwiseCo (None, 56, 56, 240) 2160 swish_11[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_12 (BatchNo (None, 56, 56, 240) 960 depthwise_conv2d_5[0][0] \n__________________________________________________________________________________________________\nswish_12 (Swish) (None, 56, 56, 240) 0 batch_normalization_12[0][0] \n__________________________________________________________________________________________________\nlambda_5 (Lambda) (None, 1, 1, 240) 0 swish_12[0][0] \n__________________________________________________________________________________________________\nconv2d_16 (Conv2D) (None, 1, 1, 10) 2410 lambda_5[0][0] \n__________________________________________________________________________________________________\nswish_13 (Swish) (None, 1, 1, 10) 0 conv2d_16[0][0] \n__________________________________________________________________________________________________\nconv2d_17 (Conv2D) (None, 1, 1, 240) 2640 swish_13[0][0] \n__________________________________________________________________________________________________\nactivation_5 (Activation) (None, 1, 1, 240) 0 conv2d_17[0][0] \n__________________________________________________________________________________________________\nmultiply_5 (Multiply) (None, 56, 56, 240) 0 activation_5[0][0] \n swish_12[0][0] \n__________________________________________________________________________________________________\nconv2d_18 (Conv2D) (None, 56, 56, 40) 9600 multiply_5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_13 (BatchNo (None, 56, 56, 40) 160 conv2d_18[0][0] \n__________________________________________________________________________________________________\ndrop_connect_3 (DropConnect) (None, 56, 56, 40) 0 batch_normalization_13[0][0] \n__________________________________________________________________________________________________\nadd_3 (Add) (None, 56, 56, 40) 0 drop_connect_3[0][0] \n batch_normalization_10[0][0] \n__________________________________________________________________________________________________\nconv2d_19 (Conv2D) (None, 56, 56, 240) 9600 add_3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_14 (BatchNo (None, 56, 56, 240) 960 conv2d_19[0][0] \n__________________________________________________________________________________________________\nswish_14 (Swish) (None, 56, 56, 240) 0 batch_normalization_14[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_6 (DepthwiseCo (None, 56, 56, 240) 2160 swish_14[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_15 (BatchNo (None, 56, 56, 240) 960 depthwise_conv2d_6[0][0] \n__________________________________________________________________________________________________\nswish_15 (Swish) (None, 56, 56, 240) 0 batch_normalization_15[0][0] \n__________________________________________________________________________________________________\nlambda_6 (Lambda) (None, 1, 1, 240) 0 swish_15[0][0] \n__________________________________________________________________________________________________\nconv2d_20 (Conv2D) (None, 1, 1, 10) 2410 lambda_6[0][0] \n__________________________________________________________________________________________________\nswish_16 (Swish) (None, 1, 1, 10) 0 conv2d_20[0][0] \n__________________________________________________________________________________________________\nconv2d_21 (Conv2D) (None, 1, 1, 240) 2640 swish_16[0][0] \n__________________________________________________________________________________________________\nactivation_6 (Activation) (None, 1, 1, 240) 0 conv2d_21[0][0] \n__________________________________________________________________________________________________\nmultiply_6 (Multiply) (None, 56, 56, 240) 0 activation_6[0][0] \n swish_15[0][0] \n__________________________________________________________________________________________________\nconv2d_22 (Conv2D) (None, 56, 56, 40) 9600 multiply_6[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_16 (BatchNo (None, 56, 56, 40) 160 conv2d_22[0][0] \n__________________________________________________________________________________________________\ndrop_connect_4 (DropConnect) (None, 56, 56, 40) 0 batch_normalization_16[0][0] \n__________________________________________________________________________________________________\nadd_4 (Add) (None, 56, 56, 40) 0 drop_connect_4[0][0] \n add_3[0][0] \n__________________________________________________________________________________________________\nconv2d_23 (Conv2D) (None, 56, 56, 240) 9600 add_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_17 (BatchNo (None, 56, 56, 240) 960 conv2d_23[0][0] \n__________________________________________________________________________________________________\nswish_17 (Swish) (None, 56, 56, 240) 0 batch_normalization_17[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_7 (DepthwiseCo (None, 56, 56, 240) 2160 swish_17[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_18 (BatchNo (None, 56, 56, 240) 960 depthwise_conv2d_7[0][0] \n__________________________________________________________________________________________________\nswish_18 (Swish) (None, 56, 56, 240) 0 batch_normalization_18[0][0] \n__________________________________________________________________________________________________\nlambda_7 (Lambda) (None, 1, 1, 240) 0 swish_18[0][0] \n__________________________________________________________________________________________________\nconv2d_24 (Conv2D) (None, 1, 1, 10) 2410 lambda_7[0][0] \n__________________________________________________________________________________________________\nswish_19 (Swish) (None, 1, 1, 10) 0 conv2d_24[0][0] \n__________________________________________________________________________________________________\nconv2d_25 (Conv2D) (None, 1, 1, 240) 2640 swish_19[0][0] \n__________________________________________________________________________________________________\nactivation_7 (Activation) (None, 1, 1, 240) 0 conv2d_25[0][0] \n__________________________________________________________________________________________________\nmultiply_7 (Multiply) (None, 56, 56, 240) 0 activation_7[0][0] \n swish_18[0][0] \n__________________________________________________________________________________________________\nconv2d_26 (Conv2D) (None, 56, 56, 40) 9600 multiply_7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_19 (BatchNo (None, 56, 56, 40) 160 conv2d_26[0][0] \n__________________________________________________________________________________________________\ndrop_connect_5 (DropConnect) (None, 56, 56, 40) 0 batch_normalization_19[0][0] \n__________________________________________________________________________________________________\nadd_5 (Add) (None, 56, 56, 40) 0 drop_connect_5[0][0] \n add_4[0][0] \n__________________________________________________________________________________________________\nconv2d_27 (Conv2D) (None, 56, 56, 240) 9600 add_5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_20 (BatchNo (None, 56, 56, 240) 960 conv2d_27[0][0] \n__________________________________________________________________________________________________\nswish_20 (Swish) (None, 56, 56, 240) 0 batch_normalization_20[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_8 (DepthwiseCo (None, 56, 56, 240) 2160 swish_20[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_21 (BatchNo (None, 56, 56, 240) 960 depthwise_conv2d_8[0][0] \n__________________________________________________________________________________________________\nswish_21 (Swish) (None, 56, 56, 240) 0 batch_normalization_21[0][0] \n__________________________________________________________________________________________________\nlambda_8 (Lambda) (None, 1, 1, 240) 0 swish_21[0][0] \n__________________________________________________________________________________________________\nconv2d_28 (Conv2D) (None, 1, 1, 10) 2410 lambda_8[0][0] \n__________________________________________________________________________________________________\nswish_22 (Swish) (None, 1, 1, 10) 0 conv2d_28[0][0] \n__________________________________________________________________________________________________\nconv2d_29 (Conv2D) (None, 1, 1, 240) 2640 swish_22[0][0] \n__________________________________________________________________________________________________\nactivation_8 (Activation) (None, 1, 1, 240) 0 conv2d_29[0][0] \n__________________________________________________________________________________________________\nmultiply_8 (Multiply) (None, 56, 56, 240) 0 activation_8[0][0] \n swish_21[0][0] \n__________________________________________________________________________________________________\nconv2d_30 (Conv2D) (None, 56, 56, 40) 9600 multiply_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_22 (BatchNo (None, 56, 56, 40) 160 conv2d_30[0][0] \n__________________________________________________________________________________________________\ndrop_connect_6 (DropConnect) (None, 56, 56, 40) 0 batch_normalization_22[0][0] \n__________________________________________________________________________________________________\nadd_6 (Add) (None, 56, 56, 40) 0 drop_connect_6[0][0] \n add_5[0][0] \n__________________________________________________________________________________________________\nconv2d_31 (Conv2D) (None, 56, 56, 240) 9600 add_6[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_23 (BatchNo (None, 56, 56, 240) 960 conv2d_31[0][0] \n__________________________________________________________________________________________________\nswish_23 (Swish) (None, 56, 56, 240) 0 batch_normalization_23[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_9 (DepthwiseCo (None, 28, 28, 240) 6000 swish_23[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_24 (BatchNo (None, 28, 28, 240) 960 depthwise_conv2d_9[0][0] \n__________________________________________________________________________________________________\nswish_24 (Swish) (None, 28, 28, 240) 0 batch_normalization_24[0][0] \n__________________________________________________________________________________________________\nlambda_9 (Lambda) (None, 1, 1, 240) 0 swish_24[0][0] \n__________________________________________________________________________________________________\nconv2d_32 (Conv2D) (None, 1, 1, 10) 2410 lambda_9[0][0] \n__________________________________________________________________________________________________\nswish_25 (Swish) (None, 1, 1, 10) 0 conv2d_32[0][0] \n__________________________________________________________________________________________________\nconv2d_33 (Conv2D) (None, 1, 1, 240) 2640 swish_25[0][0] \n__________________________________________________________________________________________________\nactivation_9 (Activation) (None, 1, 1, 240) 0 conv2d_33[0][0] \n__________________________________________________________________________________________________\nmultiply_9 (Multiply) (None, 28, 28, 240) 0 activation_9[0][0] \n swish_24[0][0] \n__________________________________________________________________________________________________\nconv2d_34 (Conv2D) (None, 28, 28, 64) 15360 multiply_9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_25 (BatchNo (None, 28, 28, 64) 256 conv2d_34[0][0] \n__________________________________________________________________________________________________\nconv2d_35 (Conv2D) (None, 28, 28, 384) 24576 batch_normalization_25[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_26 (BatchNo (None, 28, 28, 384) 1536 conv2d_35[0][0] \n__________________________________________________________________________________________________\nswish_26 (Swish) (None, 28, 28, 384) 0 batch_normalization_26[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_10 (DepthwiseC (None, 28, 28, 384) 9600 swish_26[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_27 (BatchNo (None, 28, 28, 384) 1536 depthwise_conv2d_10[0][0] \n__________________________________________________________________________________________________\nswish_27 (Swish) (None, 28, 28, 384) 0 batch_normalization_27[0][0] \n__________________________________________________________________________________________________\nlambda_10 (Lambda) (None, 1, 1, 384) 0 swish_27[0][0] \n__________________________________________________________________________________________________\nconv2d_36 (Conv2D) (None, 1, 1, 16) 6160 lambda_10[0][0] \n__________________________________________________________________________________________________\nswish_28 (Swish) (None, 1, 1, 16) 0 conv2d_36[0][0] \n__________________________________________________________________________________________________\nconv2d_37 (Conv2D) (None, 1, 1, 384) 6528 swish_28[0][0] \n__________________________________________________________________________________________________\nactivation_10 (Activation) (None, 1, 1, 384) 0 conv2d_37[0][0] \n__________________________________________________________________________________________________\nmultiply_10 (Multiply) (None, 28, 28, 384) 0 activation_10[0][0] \n swish_27[0][0] \n__________________________________________________________________________________________________\nconv2d_38 (Conv2D) (None, 28, 28, 64) 24576 multiply_10[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_28 (BatchNo (None, 28, 28, 64) 256 conv2d_38[0][0] \n__________________________________________________________________________________________________\ndrop_connect_7 (DropConnect) (None, 28, 28, 64) 0 batch_normalization_28[0][0] \n__________________________________________________________________________________________________\nadd_7 (Add) (None, 28, 28, 64) 0 drop_connect_7[0][0] \n batch_normalization_25[0][0] \n__________________________________________________________________________________________________\nconv2d_39 (Conv2D) (None, 28, 28, 384) 24576 add_7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_29 (BatchNo (None, 28, 28, 384) 1536 conv2d_39[0][0] \n__________________________________________________________________________________________________\nswish_29 (Swish) (None, 28, 28, 384) 0 batch_normalization_29[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_11 (DepthwiseC (None, 28, 28, 384) 9600 swish_29[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_30 (BatchNo (None, 28, 28, 384) 1536 depthwise_conv2d_11[0][0] \n__________________________________________________________________________________________________\nswish_30 (Swish) (None, 28, 28, 384) 0 batch_normalization_30[0][0] \n__________________________________________________________________________________________________\nlambda_11 (Lambda) (None, 1, 1, 384) 0 swish_30[0][0] \n__________________________________________________________________________________________________\nconv2d_40 (Conv2D) (None, 1, 1, 16) 6160 lambda_11[0][0] \n__________________________________________________________________________________________________\nswish_31 (Swish) (None, 1, 1, 16) 0 conv2d_40[0][0] \n__________________________________________________________________________________________________\nconv2d_41 (Conv2D) (None, 1, 1, 384) 6528 swish_31[0][0] \n__________________________________________________________________________________________________\nactivation_11 (Activation) (None, 1, 1, 384) 0 conv2d_41[0][0] \n__________________________________________________________________________________________________\nmultiply_11 (Multiply) (None, 28, 28, 384) 0 activation_11[0][0] \n swish_30[0][0] \n__________________________________________________________________________________________________\nconv2d_42 (Conv2D) (None, 28, 28, 64) 24576 multiply_11[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_31 (BatchNo (None, 28, 28, 64) 256 conv2d_42[0][0] \n__________________________________________________________________________________________________\ndrop_connect_8 (DropConnect) (None, 28, 28, 64) 0 batch_normalization_31[0][0] \n__________________________________________________________________________________________________\nadd_8 (Add) (None, 28, 28, 64) 0 drop_connect_8[0][0] \n add_7[0][0] \n__________________________________________________________________________________________________\nconv2d_43 (Conv2D) (None, 28, 28, 384) 24576 add_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_32 (BatchNo (None, 28, 28, 384) 1536 conv2d_43[0][0] \n__________________________________________________________________________________________________\nswish_32 (Swish) (None, 28, 28, 384) 0 batch_normalization_32[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_12 (DepthwiseC (None, 28, 28, 384) 9600 swish_32[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_33 (BatchNo (None, 28, 28, 384) 1536 depthwise_conv2d_12[0][0] \n__________________________________________________________________________________________________\nswish_33 (Swish) (None, 28, 28, 384) 0 batch_normalization_33[0][0] \n__________________________________________________________________________________________________\nlambda_12 (Lambda) (None, 1, 1, 384) 0 swish_33[0][0] \n__________________________________________________________________________________________________\nconv2d_44 (Conv2D) (None, 1, 1, 16) 6160 lambda_12[0][0] \n__________________________________________________________________________________________________\nswish_34 (Swish) (None, 1, 1, 16) 0 conv2d_44[0][0] \n__________________________________________________________________________________________________\nconv2d_45 (Conv2D) (None, 1, 1, 384) 6528 swish_34[0][0] \n__________________________________________________________________________________________________\nactivation_12 (Activation) (None, 1, 1, 384) 0 conv2d_45[0][0] \n__________________________________________________________________________________________________\nmultiply_12 (Multiply) (None, 28, 28, 384) 0 activation_12[0][0] \n swish_33[0][0] \n__________________________________________________________________________________________________\nconv2d_46 (Conv2D) (None, 28, 28, 64) 24576 multiply_12[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_34 (BatchNo (None, 28, 28, 64) 256 conv2d_46[0][0] \n__________________________________________________________________________________________________\ndrop_connect_9 (DropConnect) (None, 28, 28, 64) 0 batch_normalization_34[0][0] \n__________________________________________________________________________________________________\nadd_9 (Add) (None, 28, 28, 64) 0 drop_connect_9[0][0] \n add_8[0][0] \n__________________________________________________________________________________________________\nconv2d_47 (Conv2D) (None, 28, 28, 384) 24576 add_9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_35 (BatchNo (None, 28, 28, 384) 1536 conv2d_47[0][0] \n__________________________________________________________________________________________________\nswish_35 (Swish) (None, 28, 28, 384) 0 batch_normalization_35[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_13 (DepthwiseC (None, 28, 28, 384) 9600 swish_35[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_36 (BatchNo (None, 28, 28, 384) 1536 depthwise_conv2d_13[0][0] \n__________________________________________________________________________________________________\nswish_36 (Swish) (None, 28, 28, 384) 0 batch_normalization_36[0][0] \n__________________________________________________________________________________________________\nlambda_13 (Lambda) (None, 1, 1, 384) 0 swish_36[0][0] \n__________________________________________________________________________________________________\nconv2d_48 (Conv2D) (None, 1, 1, 16) 6160 lambda_13[0][0] \n__________________________________________________________________________________________________\nswish_37 (Swish) (None, 1, 1, 16) 0 conv2d_48[0][0] \n__________________________________________________________________________________________________\nconv2d_49 (Conv2D) (None, 1, 1, 384) 6528 swish_37[0][0] \n__________________________________________________________________________________________________\nactivation_13 (Activation) (None, 1, 1, 384) 0 conv2d_49[0][0] \n__________________________________________________________________________________________________\nmultiply_13 (Multiply) (None, 28, 28, 384) 0 activation_13[0][0] \n swish_36[0][0] \n__________________________________________________________________________________________________\nconv2d_50 (Conv2D) (None, 28, 28, 64) 24576 multiply_13[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_37 (BatchNo (None, 28, 28, 64) 256 conv2d_50[0][0] \n__________________________________________________________________________________________________\ndrop_connect_10 (DropConnect) (None, 28, 28, 64) 0 batch_normalization_37[0][0] \n__________________________________________________________________________________________________\nadd_10 (Add) (None, 28, 28, 64) 0 drop_connect_10[0][0] \n add_9[0][0] \n__________________________________________________________________________________________________\nconv2d_51 (Conv2D) (None, 28, 28, 384) 24576 add_10[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_38 (BatchNo (None, 28, 28, 384) 1536 conv2d_51[0][0] \n__________________________________________________________________________________________________\nswish_38 (Swish) (None, 28, 28, 384) 0 batch_normalization_38[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_14 (DepthwiseC (None, 14, 14, 384) 3456 swish_38[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_39 (BatchNo (None, 14, 14, 384) 1536 depthwise_conv2d_14[0][0] \n__________________________________________________________________________________________________\nswish_39 (Swish) (None, 14, 14, 384) 0 batch_normalization_39[0][0] \n__________________________________________________________________________________________________\nlambda_14 (Lambda) (None, 1, 1, 384) 0 swish_39[0][0] \n__________________________________________________________________________________________________\nconv2d_52 (Conv2D) (None, 1, 1, 16) 6160 lambda_14[0][0] \n__________________________________________________________________________________________________\nswish_40 (Swish) (None, 1, 1, 16) 0 conv2d_52[0][0] \n__________________________________________________________________________________________________\nconv2d_53 (Conv2D) (None, 1, 1, 384) 6528 swish_40[0][0] \n__________________________________________________________________________________________________\nactivation_14 (Activation) (None, 1, 1, 384) 0 conv2d_53[0][0] \n__________________________________________________________________________________________________\nmultiply_14 (Multiply) (None, 14, 14, 384) 0 activation_14[0][0] \n swish_39[0][0] \n__________________________________________________________________________________________________\nconv2d_54 (Conv2D) (None, 14, 14, 128) 49152 multiply_14[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_40 (BatchNo (None, 14, 14, 128) 512 conv2d_54[0][0] \n__________________________________________________________________________________________________\nconv2d_55 (Conv2D) (None, 14, 14, 768) 98304 batch_normalization_40[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_41 (BatchNo (None, 14, 14, 768) 3072 conv2d_55[0][0] \n__________________________________________________________________________________________________\nswish_41 (Swish) (None, 14, 14, 768) 0 batch_normalization_41[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_15 (DepthwiseC (None, 14, 14, 768) 6912 swish_41[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_42 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_15[0][0] \n__________________________________________________________________________________________________\nswish_42 (Swish) (None, 14, 14, 768) 0 batch_normalization_42[0][0] \n__________________________________________________________________________________________________\nlambda_15 (Lambda) (None, 1, 1, 768) 0 swish_42[0][0] \n__________________________________________________________________________________________________\nconv2d_56 (Conv2D) (None, 1, 1, 32) 24608 lambda_15[0][0] \n__________________________________________________________________________________________________\nswish_43 (Swish) (None, 1, 1, 32) 0 conv2d_56[0][0] \n__________________________________________________________________________________________________\nconv2d_57 (Conv2D) (None, 1, 1, 768) 25344 swish_43[0][0] \n__________________________________________________________________________________________________\nactivation_15 (Activation) (None, 1, 1, 768) 0 conv2d_57[0][0] \n__________________________________________________________________________________________________\nmultiply_15 (Multiply) (None, 14, 14, 768) 0 activation_15[0][0] \n swish_42[0][0] \n__________________________________________________________________________________________________\nconv2d_58 (Conv2D) (None, 14, 14, 128) 98304 multiply_15[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_43 (BatchNo (None, 14, 14, 128) 512 conv2d_58[0][0] \n__________________________________________________________________________________________________\ndrop_connect_11 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_43[0][0] \n__________________________________________________________________________________________________\nadd_11 (Add) (None, 14, 14, 128) 0 drop_connect_11[0][0] \n batch_normalization_40[0][0] \n__________________________________________________________________________________________________\nconv2d_59 (Conv2D) (None, 14, 14, 768) 98304 add_11[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_44 (BatchNo (None, 14, 14, 768) 3072 conv2d_59[0][0] \n__________________________________________________________________________________________________\nswish_44 (Swish) (None, 14, 14, 768) 0 batch_normalization_44[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_16 (DepthwiseC (None, 14, 14, 768) 6912 swish_44[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_45 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_16[0][0] \n__________________________________________________________________________________________________\nswish_45 (Swish) (None, 14, 14, 768) 0 batch_normalization_45[0][0] \n__________________________________________________________________________________________________\nlambda_16 (Lambda) (None, 1, 1, 768) 0 swish_45[0][0] \n__________________________________________________________________________________________________\nconv2d_60 (Conv2D) (None, 1, 1, 32) 24608 lambda_16[0][0] \n__________________________________________________________________________________________________\nswish_46 (Swish) (None, 1, 1, 32) 0 conv2d_60[0][0] \n__________________________________________________________________________________________________\nconv2d_61 (Conv2D) (None, 1, 1, 768) 25344 swish_46[0][0] \n__________________________________________________________________________________________________\nactivation_16 (Activation) (None, 1, 1, 768) 0 conv2d_61[0][0] \n__________________________________________________________________________________________________\nmultiply_16 (Multiply) (None, 14, 14, 768) 0 activation_16[0][0] \n swish_45[0][0] \n__________________________________________________________________________________________________\nconv2d_62 (Conv2D) (None, 14, 14, 128) 98304 multiply_16[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_46 (BatchNo (None, 14, 14, 128) 512 conv2d_62[0][0] \n__________________________________________________________________________________________________\ndrop_connect_12 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_46[0][0] \n__________________________________________________________________________________________________\nadd_12 (Add) (None, 14, 14, 128) 0 drop_connect_12[0][0] \n add_11[0][0] \n__________________________________________________________________________________________________\nconv2d_63 (Conv2D) (None, 14, 14, 768) 98304 add_12[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_47 (BatchNo (None, 14, 14, 768) 3072 conv2d_63[0][0] \n__________________________________________________________________________________________________\nswish_47 (Swish) (None, 14, 14, 768) 0 batch_normalization_47[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_17 (DepthwiseC (None, 14, 14, 768) 6912 swish_47[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_48 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_17[0][0] \n__________________________________________________________________________________________________\nswish_48 (Swish) (None, 14, 14, 768) 0 batch_normalization_48[0][0] \n__________________________________________________________________________________________________\nlambda_17 (Lambda) (None, 1, 1, 768) 0 swish_48[0][0] \n__________________________________________________________________________________________________\nconv2d_64 (Conv2D) (None, 1, 1, 32) 24608 lambda_17[0][0] \n__________________________________________________________________________________________________\nswish_49 (Swish) (None, 1, 1, 32) 0 conv2d_64[0][0] \n__________________________________________________________________________________________________\nconv2d_65 (Conv2D) (None, 1, 1, 768) 25344 swish_49[0][0] \n__________________________________________________________________________________________________\nactivation_17 (Activation) (None, 1, 1, 768) 0 conv2d_65[0][0] \n__________________________________________________________________________________________________\nmultiply_17 (Multiply) (None, 14, 14, 768) 0 activation_17[0][0] \n swish_48[0][0] \n__________________________________________________________________________________________________\nconv2d_66 (Conv2D) (None, 14, 14, 128) 98304 multiply_17[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_49 (BatchNo (None, 14, 14, 128) 512 conv2d_66[0][0] \n__________________________________________________________________________________________________\ndrop_connect_13 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_49[0][0] \n__________________________________________________________________________________________________\nadd_13 (Add) (None, 14, 14, 128) 0 drop_connect_13[0][0] \n add_12[0][0] \n__________________________________________________________________________________________________\nconv2d_67 (Conv2D) (None, 14, 14, 768) 98304 add_13[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_50 (BatchNo (None, 14, 14, 768) 3072 conv2d_67[0][0] \n__________________________________________________________________________________________________\nswish_50 (Swish) (None, 14, 14, 768) 0 batch_normalization_50[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_18 (DepthwiseC (None, 14, 14, 768) 6912 swish_50[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_51 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_18[0][0] \n__________________________________________________________________________________________________\nswish_51 (Swish) (None, 14, 14, 768) 0 batch_normalization_51[0][0] \n__________________________________________________________________________________________________\nlambda_18 (Lambda) (None, 1, 1, 768) 0 swish_51[0][0] \n__________________________________________________________________________________________________\nconv2d_68 (Conv2D) (None, 1, 1, 32) 24608 lambda_18[0][0] \n__________________________________________________________________________________________________\nswish_52 (Swish) (None, 1, 1, 32) 0 conv2d_68[0][0] \n__________________________________________________________________________________________________\nconv2d_69 (Conv2D) (None, 1, 1, 768) 25344 swish_52[0][0] \n__________________________________________________________________________________________________\nactivation_18 (Activation) (None, 1, 1, 768) 0 conv2d_69[0][0] \n__________________________________________________________________________________________________\nmultiply_18 (Multiply) (None, 14, 14, 768) 0 activation_18[0][0] \n swish_51[0][0] \n__________________________________________________________________________________________________\nconv2d_70 (Conv2D) (None, 14, 14, 128) 98304 multiply_18[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_52 (BatchNo (None, 14, 14, 128) 512 conv2d_70[0][0] \n__________________________________________________________________________________________________\ndrop_connect_14 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_52[0][0] \n__________________________________________________________________________________________________\nadd_14 (Add) (None, 14, 14, 128) 0 drop_connect_14[0][0] \n add_13[0][0] \n__________________________________________________________________________________________________\nconv2d_71 (Conv2D) (None, 14, 14, 768) 98304 add_14[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_53 (BatchNo (None, 14, 14, 768) 3072 conv2d_71[0][0] \n__________________________________________________________________________________________________\nswish_53 (Swish) (None, 14, 14, 768) 0 batch_normalization_53[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_19 (DepthwiseC (None, 14, 14, 768) 6912 swish_53[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_54 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_19[0][0] \n__________________________________________________________________________________________________\nswish_54 (Swish) (None, 14, 14, 768) 0 batch_normalization_54[0][0] \n__________________________________________________________________________________________________\nlambda_19 (Lambda) (None, 1, 1, 768) 0 swish_54[0][0] \n__________________________________________________________________________________________________\nconv2d_72 (Conv2D) (None, 1, 1, 32) 24608 lambda_19[0][0] \n__________________________________________________________________________________________________\nswish_55 (Swish) (None, 1, 1, 32) 0 conv2d_72[0][0] \n__________________________________________________________________________________________________\nconv2d_73 (Conv2D) (None, 1, 1, 768) 25344 swish_55[0][0] \n__________________________________________________________________________________________________\nactivation_19 (Activation) (None, 1, 1, 768) 0 conv2d_73[0][0] \n__________________________________________________________________________________________________\nmultiply_19 (Multiply) (None, 14, 14, 768) 0 activation_19[0][0] \n swish_54[0][0] \n__________________________________________________________________________________________________\nconv2d_74 (Conv2D) (None, 14, 14, 128) 98304 multiply_19[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_55 (BatchNo (None, 14, 14, 128) 512 conv2d_74[0][0] \n__________________________________________________________________________________________________\ndrop_connect_15 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_55[0][0] \n__________________________________________________________________________________________________\nadd_15 (Add) (None, 14, 14, 128) 0 drop_connect_15[0][0] \n add_14[0][0] \n__________________________________________________________________________________________________\nconv2d_75 (Conv2D) (None, 14, 14, 768) 98304 add_15[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_56 (BatchNo (None, 14, 14, 768) 3072 conv2d_75[0][0] \n__________________________________________________________________________________________________\nswish_56 (Swish) (None, 14, 14, 768) 0 batch_normalization_56[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_20 (DepthwiseC (None, 14, 14, 768) 6912 swish_56[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_57 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_20[0][0] \n__________________________________________________________________________________________________\nswish_57 (Swish) (None, 14, 14, 768) 0 batch_normalization_57[0][0] \n__________________________________________________________________________________________________\nlambda_20 (Lambda) (None, 1, 1, 768) 0 swish_57[0][0] \n__________________________________________________________________________________________________\nconv2d_76 (Conv2D) (None, 1, 1, 32) 24608 lambda_20[0][0] \n__________________________________________________________________________________________________\nswish_58 (Swish) (None, 1, 1, 32) 0 conv2d_76[0][0] \n__________________________________________________________________________________________________\nconv2d_77 (Conv2D) (None, 1, 1, 768) 25344 swish_58[0][0] \n__________________________________________________________________________________________________\nactivation_20 (Activation) (None, 1, 1, 768) 0 conv2d_77[0][0] \n__________________________________________________________________________________________________\nmultiply_20 (Multiply) (None, 14, 14, 768) 0 activation_20[0][0] \n swish_57[0][0] \n__________________________________________________________________________________________________\nconv2d_78 (Conv2D) (None, 14, 14, 128) 98304 multiply_20[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_58 (BatchNo (None, 14, 14, 128) 512 conv2d_78[0][0] \n__________________________________________________________________________________________________\ndrop_connect_16 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_58[0][0] \n__________________________________________________________________________________________________\nadd_16 (Add) (None, 14, 14, 128) 0 drop_connect_16[0][0] \n add_15[0][0] \n__________________________________________________________________________________________________\nconv2d_79 (Conv2D) (None, 14, 14, 768) 98304 add_16[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_59 (BatchNo (None, 14, 14, 768) 3072 conv2d_79[0][0] \n__________________________________________________________________________________________________\nswish_59 (Swish) (None, 14, 14, 768) 0 batch_normalization_59[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_21 (DepthwiseC (None, 14, 14, 768) 19200 swish_59[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_60 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_21[0][0] \n__________________________________________________________________________________________________\nswish_60 (Swish) (None, 14, 14, 768) 0 batch_normalization_60[0][0] \n__________________________________________________________________________________________________\nlambda_21 (Lambda) (None, 1, 1, 768) 0 swish_60[0][0] \n__________________________________________________________________________________________________\nconv2d_80 (Conv2D) (None, 1, 1, 32) 24608 lambda_21[0][0] \n__________________________________________________________________________________________________\nswish_61 (Swish) (None, 1, 1, 32) 0 conv2d_80[0][0] \n__________________________________________________________________________________________________\nconv2d_81 (Conv2D) (None, 1, 1, 768) 25344 swish_61[0][0] \n__________________________________________________________________________________________________\nactivation_21 (Activation) (None, 1, 1, 768) 0 conv2d_81[0][0] \n__________________________________________________________________________________________________\nmultiply_21 (Multiply) (None, 14, 14, 768) 0 activation_21[0][0] \n swish_60[0][0] \n__________________________________________________________________________________________________\nconv2d_82 (Conv2D) (None, 14, 14, 176) 135168 multiply_21[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_61 (BatchNo (None, 14, 14, 176) 704 conv2d_82[0][0] \n__________________________________________________________________________________________________\nconv2d_83 (Conv2D) (None, 14, 14, 1056) 185856 batch_normalization_61[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_62 (BatchNo (None, 14, 14, 1056) 4224 conv2d_83[0][0] \n__________________________________________________________________________________________________\nswish_62 (Swish) (None, 14, 14, 1056) 0 batch_normalization_62[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_22 (DepthwiseC (None, 14, 14, 1056) 26400 swish_62[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_63 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_22[0][0] \n__________________________________________________________________________________________________\nswish_63 (Swish) (None, 14, 14, 1056) 0 batch_normalization_63[0][0] \n__________________________________________________________________________________________________\nlambda_22 (Lambda) (None, 1, 1, 1056) 0 swish_63[0][0] \n__________________________________________________________________________________________________\nconv2d_84 (Conv2D) (None, 1, 1, 44) 46508 lambda_22[0][0] \n__________________________________________________________________________________________________\nswish_64 (Swish) (None, 1, 1, 44) 0 conv2d_84[0][0] \n__________________________________________________________________________________________________\nconv2d_85 (Conv2D) (None, 1, 1, 1056) 47520 swish_64[0][0] \n__________________________________________________________________________________________________\nactivation_22 (Activation) (None, 1, 1, 1056) 0 conv2d_85[0][0] \n__________________________________________________________________________________________________\nmultiply_22 (Multiply) (None, 14, 14, 1056) 0 activation_22[0][0] \n swish_63[0][0] \n__________________________________________________________________________________________________\nconv2d_86 (Conv2D) (None, 14, 14, 176) 185856 multiply_22[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_64 (BatchNo (None, 14, 14, 176) 704 conv2d_86[0][0] \n__________________________________________________________________________________________________\ndrop_connect_17 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_64[0][0] \n__________________________________________________________________________________________________\nadd_17 (Add) (None, 14, 14, 176) 0 drop_connect_17[0][0] \n batch_normalization_61[0][0] \n__________________________________________________________________________________________________\nconv2d_87 (Conv2D) (None, 14, 14, 1056) 185856 add_17[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_65 (BatchNo (None, 14, 14, 1056) 4224 conv2d_87[0][0] \n__________________________________________________________________________________________________\nswish_65 (Swish) (None, 14, 14, 1056) 0 batch_normalization_65[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_23 (DepthwiseC (None, 14, 14, 1056) 26400 swish_65[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_66 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_23[0][0] \n__________________________________________________________________________________________________\nswish_66 (Swish) (None, 14, 14, 1056) 0 batch_normalization_66[0][0] \n__________________________________________________________________________________________________\nlambda_23 (Lambda) (None, 1, 1, 1056) 0 swish_66[0][0] \n__________________________________________________________________________________________________\nconv2d_88 (Conv2D) (None, 1, 1, 44) 46508 lambda_23[0][0] \n__________________________________________________________________________________________________\nswish_67 (Swish) (None, 1, 1, 44) 0 conv2d_88[0][0] \n__________________________________________________________________________________________________\nconv2d_89 (Conv2D) (None, 1, 1, 1056) 47520 swish_67[0][0] \n__________________________________________________________________________________________________\nactivation_23 (Activation) (None, 1, 1, 1056) 0 conv2d_89[0][0] \n__________________________________________________________________________________________________\nmultiply_23 (Multiply) (None, 14, 14, 1056) 0 activation_23[0][0] \n swish_66[0][0] \n__________________________________________________________________________________________________\nconv2d_90 (Conv2D) (None, 14, 14, 176) 185856 multiply_23[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_67 (BatchNo (None, 14, 14, 176) 704 conv2d_90[0][0] \n__________________________________________________________________________________________________\ndrop_connect_18 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_67[0][0] \n__________________________________________________________________________________________________\nadd_18 (Add) (None, 14, 14, 176) 0 drop_connect_18[0][0] \n add_17[0][0] \n__________________________________________________________________________________________________\nconv2d_91 (Conv2D) (None, 14, 14, 1056) 185856 add_18[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_68 (BatchNo (None, 14, 14, 1056) 4224 conv2d_91[0][0] \n__________________________________________________________________________________________________\nswish_68 (Swish) (None, 14, 14, 1056) 0 batch_normalization_68[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_24 (DepthwiseC (None, 14, 14, 1056) 26400 swish_68[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_69 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_24[0][0] \n__________________________________________________________________________________________________\nswish_69 (Swish) (None, 14, 14, 1056) 0 batch_normalization_69[0][0] \n__________________________________________________________________________________________________\nlambda_24 (Lambda) (None, 1, 1, 1056) 0 swish_69[0][0] \n__________________________________________________________________________________________________\nconv2d_92 (Conv2D) (None, 1, 1, 44) 46508 lambda_24[0][0] \n__________________________________________________________________________________________________\nswish_70 (Swish) (None, 1, 1, 44) 0 conv2d_92[0][0] \n__________________________________________________________________________________________________\nconv2d_93 (Conv2D) (None, 1, 1, 1056) 47520 swish_70[0][0] \n__________________________________________________________________________________________________\nactivation_24 (Activation) (None, 1, 1, 1056) 0 conv2d_93[0][0] \n__________________________________________________________________________________________________\nmultiply_24 (Multiply) (None, 14, 14, 1056) 0 activation_24[0][0] \n swish_69[0][0] \n__________________________________________________________________________________________________\nconv2d_94 (Conv2D) (None, 14, 14, 176) 185856 multiply_24[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_70 (BatchNo (None, 14, 14, 176) 704 conv2d_94[0][0] \n__________________________________________________________________________________________________\ndrop_connect_19 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_70[0][0] \n__________________________________________________________________________________________________\nadd_19 (Add) (None, 14, 14, 176) 0 drop_connect_19[0][0] \n add_18[0][0] \n__________________________________________________________________________________________________\nconv2d_95 (Conv2D) (None, 14, 14, 1056) 185856 add_19[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_71 (BatchNo (None, 14, 14, 1056) 4224 conv2d_95[0][0] \n__________________________________________________________________________________________________\nswish_71 (Swish) (None, 14, 14, 1056) 0 batch_normalization_71[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_25 (DepthwiseC (None, 14, 14, 1056) 26400 swish_71[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_72 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_25[0][0] \n__________________________________________________________________________________________________\nswish_72 (Swish) (None, 14, 14, 1056) 0 batch_normalization_72[0][0] \n__________________________________________________________________________________________________\nlambda_25 (Lambda) (None, 1, 1, 1056) 0 swish_72[0][0] \n__________________________________________________________________________________________________\nconv2d_96 (Conv2D) (None, 1, 1, 44) 46508 lambda_25[0][0] \n__________________________________________________________________________________________________\nswish_73 (Swish) (None, 1, 1, 44) 0 conv2d_96[0][0] \n__________________________________________________________________________________________________\nconv2d_97 (Conv2D) (None, 1, 1, 1056) 47520 swish_73[0][0] \n__________________________________________________________________________________________________\nactivation_25 (Activation) (None, 1, 1, 1056) 0 conv2d_97[0][0] \n__________________________________________________________________________________________________\nmultiply_25 (Multiply) (None, 14, 14, 1056) 0 activation_25[0][0] \n swish_72[0][0] \n__________________________________________________________________________________________________\nconv2d_98 (Conv2D) (None, 14, 14, 176) 185856 multiply_25[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_73 (BatchNo (None, 14, 14, 176) 704 conv2d_98[0][0] \n__________________________________________________________________________________________________\ndrop_connect_20 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_73[0][0] \n__________________________________________________________________________________________________\nadd_20 (Add) (None, 14, 14, 176) 0 drop_connect_20[0][0] \n add_19[0][0] \n__________________________________________________________________________________________________\nconv2d_99 (Conv2D) (None, 14, 14, 1056) 185856 add_20[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_74 (BatchNo (None, 14, 14, 1056) 4224 conv2d_99[0][0] \n__________________________________________________________________________________________________\nswish_74 (Swish) (None, 14, 14, 1056) 0 batch_normalization_74[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_26 (DepthwiseC (None, 14, 14, 1056) 26400 swish_74[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_75 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_26[0][0] \n__________________________________________________________________________________________________\nswish_75 (Swish) (None, 14, 14, 1056) 0 batch_normalization_75[0][0] \n__________________________________________________________________________________________________\nlambda_26 (Lambda) (None, 1, 1, 1056) 0 swish_75[0][0] \n__________________________________________________________________________________________________\nconv2d_100 (Conv2D) (None, 1, 1, 44) 46508 lambda_26[0][0] \n__________________________________________________________________________________________________\nswish_76 (Swish) (None, 1, 1, 44) 0 conv2d_100[0][0] \n__________________________________________________________________________________________________\nconv2d_101 (Conv2D) (None, 1, 1, 1056) 47520 swish_76[0][0] \n__________________________________________________________________________________________________\nactivation_26 (Activation) (None, 1, 1, 1056) 0 conv2d_101[0][0] \n__________________________________________________________________________________________________\nmultiply_26 (Multiply) (None, 14, 14, 1056) 0 activation_26[0][0] \n swish_75[0][0] \n__________________________________________________________________________________________________\nconv2d_102 (Conv2D) (None, 14, 14, 176) 185856 multiply_26[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_76 (BatchNo (None, 14, 14, 176) 704 conv2d_102[0][0] \n__________________________________________________________________________________________________\ndrop_connect_21 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_76[0][0] \n__________________________________________________________________________________________________\nadd_21 (Add) (None, 14, 14, 176) 0 drop_connect_21[0][0] \n add_20[0][0] \n__________________________________________________________________________________________________\nconv2d_103 (Conv2D) (None, 14, 14, 1056) 185856 add_21[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_77 (BatchNo (None, 14, 14, 1056) 4224 conv2d_103[0][0] \n__________________________________________________________________________________________________\nswish_77 (Swish) (None, 14, 14, 1056) 0 batch_normalization_77[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_27 (DepthwiseC (None, 14, 14, 1056) 26400 swish_77[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_78 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_27[0][0] \n__________________________________________________________________________________________________\nswish_78 (Swish) (None, 14, 14, 1056) 0 batch_normalization_78[0][0] \n__________________________________________________________________________________________________\nlambda_27 (Lambda) (None, 1, 1, 1056) 0 swish_78[0][0] \n__________________________________________________________________________________________________\nconv2d_104 (Conv2D) (None, 1, 1, 44) 46508 lambda_27[0][0] \n__________________________________________________________________________________________________\nswish_79 (Swish) (None, 1, 1, 44) 0 conv2d_104[0][0] \n__________________________________________________________________________________________________\nconv2d_105 (Conv2D) (None, 1, 1, 1056) 47520 swish_79[0][0] \n__________________________________________________________________________________________________\nactivation_27 (Activation) (None, 1, 1, 1056) 0 conv2d_105[0][0] \n__________________________________________________________________________________________________\nmultiply_27 (Multiply) (None, 14, 14, 1056) 0 activation_27[0][0] \n swish_78[0][0] \n__________________________________________________________________________________________________\nconv2d_106 (Conv2D) (None, 14, 14, 176) 185856 multiply_27[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_79 (BatchNo (None, 14, 14, 176) 704 conv2d_106[0][0] \n__________________________________________________________________________________________________\ndrop_connect_22 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_79[0][0] \n__________________________________________________________________________________________________\nadd_22 (Add) (None, 14, 14, 176) 0 drop_connect_22[0][0] \n add_21[0][0] \n__________________________________________________________________________________________________\nconv2d_107 (Conv2D) (None, 14, 14, 1056) 185856 add_22[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_80 (BatchNo (None, 14, 14, 1056) 4224 conv2d_107[0][0] \n__________________________________________________________________________________________________\nswish_80 (Swish) (None, 14, 14, 1056) 0 batch_normalization_80[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_28 (DepthwiseC (None, 7, 7, 1056) 26400 swish_80[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_81 (BatchNo (None, 7, 7, 1056) 4224 depthwise_conv2d_28[0][0] \n__________________________________________________________________________________________________\nswish_81 (Swish) (None, 7, 7, 1056) 0 batch_normalization_81[0][0] \n__________________________________________________________________________________________________\nlambda_28 (Lambda) (None, 1, 1, 1056) 0 swish_81[0][0] \n__________________________________________________________________________________________________\nconv2d_108 (Conv2D) (None, 1, 1, 44) 46508 lambda_28[0][0] \n__________________________________________________________________________________________________\nswish_82 (Swish) (None, 1, 1, 44) 0 conv2d_108[0][0] \n__________________________________________________________________________________________________\nconv2d_109 (Conv2D) (None, 1, 1, 1056) 47520 swish_82[0][0] \n__________________________________________________________________________________________________\nactivation_28 (Activation) (None, 1, 1, 1056) 0 conv2d_109[0][0] \n__________________________________________________________________________________________________\nmultiply_28 (Multiply) (None, 7, 7, 1056) 0 activation_28[0][0] \n swish_81[0][0] \n__________________________________________________________________________________________________\nconv2d_110 (Conv2D) (None, 7, 7, 304) 321024 multiply_28[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_82 (BatchNo (None, 7, 7, 304) 1216 conv2d_110[0][0] \n__________________________________________________________________________________________________\nconv2d_111 (Conv2D) (None, 7, 7, 1824) 554496 batch_normalization_82[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_83 (BatchNo (None, 7, 7, 1824) 7296 conv2d_111[0][0] \n__________________________________________________________________________________________________\nswish_83 (Swish) (None, 7, 7, 1824) 0 batch_normalization_83[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_29 (DepthwiseC (None, 7, 7, 1824) 45600 swish_83[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_84 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_29[0][0] \n__________________________________________________________________________________________________\nswish_84 (Swish) (None, 7, 7, 1824) 0 batch_normalization_84[0][0] \n__________________________________________________________________________________________________\nlambda_29 (Lambda) (None, 1, 1, 1824) 0 swish_84[0][0] \n__________________________________________________________________________________________________\nconv2d_112 (Conv2D) (None, 1, 1, 76) 138700 lambda_29[0][0] \n__________________________________________________________________________________________________\nswish_85 (Swish) (None, 1, 1, 76) 0 conv2d_112[0][0] \n__________________________________________________________________________________________________\nconv2d_113 (Conv2D) (None, 1, 1, 1824) 140448 swish_85[0][0] \n__________________________________________________________________________________________________\nactivation_29 (Activation) (None, 1, 1, 1824) 0 conv2d_113[0][0] \n__________________________________________________________________________________________________\nmultiply_29 (Multiply) (None, 7, 7, 1824) 0 activation_29[0][0] \n swish_84[0][0] \n__________________________________________________________________________________________________\nconv2d_114 (Conv2D) (None, 7, 7, 304) 554496 multiply_29[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_85 (BatchNo (None, 7, 7, 304) 1216 conv2d_114[0][0] \n__________________________________________________________________________________________________\ndrop_connect_23 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_85[0][0] \n__________________________________________________________________________________________________\nadd_23 (Add) (None, 7, 7, 304) 0 drop_connect_23[0][0] \n batch_normalization_82[0][0] \n__________________________________________________________________________________________________\nconv2d_115 (Conv2D) (None, 7, 7, 1824) 554496 add_23[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_86 (BatchNo (None, 7, 7, 1824) 7296 conv2d_115[0][0] \n__________________________________________________________________________________________________\nswish_86 (Swish) (None, 7, 7, 1824) 0 batch_normalization_86[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_30 (DepthwiseC (None, 7, 7, 1824) 45600 swish_86[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_87 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_30[0][0] \n__________________________________________________________________________________________________\nswish_87 (Swish) (None, 7, 7, 1824) 0 batch_normalization_87[0][0] \n__________________________________________________________________________________________________\nlambda_30 (Lambda) (None, 1, 1, 1824) 0 swish_87[0][0] \n__________________________________________________________________________________________________\nconv2d_116 (Conv2D) (None, 1, 1, 76) 138700 lambda_30[0][0] \n__________________________________________________________________________________________________\nswish_88 (Swish) (None, 1, 1, 76) 0 conv2d_116[0][0] \n__________________________________________________________________________________________________\nconv2d_117 (Conv2D) (None, 1, 1, 1824) 140448 swish_88[0][0] \n__________________________________________________________________________________________________\nactivation_30 (Activation) (None, 1, 1, 1824) 0 conv2d_117[0][0] \n__________________________________________________________________________________________________\nmultiply_30 (Multiply) (None, 7, 7, 1824) 0 activation_30[0][0] \n swish_87[0][0] \n__________________________________________________________________________________________________\nconv2d_118 (Conv2D) (None, 7, 7, 304) 554496 multiply_30[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_88 (BatchNo (None, 7, 7, 304) 1216 conv2d_118[0][0] \n__________________________________________________________________________________________________\ndrop_connect_24 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_88[0][0] \n__________________________________________________________________________________________________\nadd_24 (Add) (None, 7, 7, 304) 0 drop_connect_24[0][0] \n add_23[0][0] \n__________________________________________________________________________________________________\nconv2d_119 (Conv2D) (None, 7, 7, 1824) 554496 add_24[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_89 (BatchNo (None, 7, 7, 1824) 7296 conv2d_119[0][0] \n__________________________________________________________________________________________________\nswish_89 (Swish) (None, 7, 7, 1824) 0 batch_normalization_89[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_31 (DepthwiseC (None, 7, 7, 1824) 45600 swish_89[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_90 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_31[0][0] \n__________________________________________________________________________________________________\nswish_90 (Swish) (None, 7, 7, 1824) 0 batch_normalization_90[0][0] \n__________________________________________________________________________________________________\nlambda_31 (Lambda) (None, 1, 1, 1824) 0 swish_90[0][0] \n__________________________________________________________________________________________________\nconv2d_120 (Conv2D) (None, 1, 1, 76) 138700 lambda_31[0][0] \n__________________________________________________________________________________________________\nswish_91 (Swish) (None, 1, 1, 76) 0 conv2d_120[0][0] \n__________________________________________________________________________________________________\nconv2d_121 (Conv2D) (None, 1, 1, 1824) 140448 swish_91[0][0] \n__________________________________________________________________________________________________\nactivation_31 (Activation) (None, 1, 1, 1824) 0 conv2d_121[0][0] \n__________________________________________________________________________________________________\nmultiply_31 (Multiply) (None, 7, 7, 1824) 0 activation_31[0][0] \n swish_90[0][0] \n__________________________________________________________________________________________________\nconv2d_122 (Conv2D) (None, 7, 7, 304) 554496 multiply_31[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_91 (BatchNo (None, 7, 7, 304) 1216 conv2d_122[0][0] \n__________________________________________________________________________________________________\ndrop_connect_25 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_91[0][0] \n__________________________________________________________________________________________________\nadd_25 (Add) (None, 7, 7, 304) 0 drop_connect_25[0][0] \n add_24[0][0] \n__________________________________________________________________________________________________\nconv2d_123 (Conv2D) (None, 7, 7, 1824) 554496 add_25[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_92 (BatchNo (None, 7, 7, 1824) 7296 conv2d_123[0][0] \n__________________________________________________________________________________________________\nswish_92 (Swish) (None, 7, 7, 1824) 0 batch_normalization_92[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_32 (DepthwiseC (None, 7, 7, 1824) 45600 swish_92[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_93 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_32[0][0] \n__________________________________________________________________________________________________\nswish_93 (Swish) (None, 7, 7, 1824) 0 batch_normalization_93[0][0] \n__________________________________________________________________________________________________\nlambda_32 (Lambda) (None, 1, 1, 1824) 0 swish_93[0][0] \n__________________________________________________________________________________________________\nconv2d_124 (Conv2D) (None, 1, 1, 76) 138700 lambda_32[0][0] \n__________________________________________________________________________________________________\nswish_94 (Swish) (None, 1, 1, 76) 0 conv2d_124[0][0] \n__________________________________________________________________________________________________\nconv2d_125 (Conv2D) (None, 1, 1, 1824) 140448 swish_94[0][0] \n__________________________________________________________________________________________________\nactivation_32 (Activation) (None, 1, 1, 1824) 0 conv2d_125[0][0] \n__________________________________________________________________________________________________\nmultiply_32 (Multiply) (None, 7, 7, 1824) 0 activation_32[0][0] \n swish_93[0][0] \n__________________________________________________________________________________________________\nconv2d_126 (Conv2D) (None, 7, 7, 304) 554496 multiply_32[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_94 (BatchNo (None, 7, 7, 304) 1216 conv2d_126[0][0] \n__________________________________________________________________________________________________\ndrop_connect_26 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_94[0][0] \n__________________________________________________________________________________________________\nadd_26 (Add) (None, 7, 7, 304) 0 drop_connect_26[0][0] \n add_25[0][0] \n__________________________________________________________________________________________________\nconv2d_127 (Conv2D) (None, 7, 7, 1824) 554496 add_26[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_95 (BatchNo (None, 7, 7, 1824) 7296 conv2d_127[0][0] \n__________________________________________________________________________________________________\nswish_95 (Swish) (None, 7, 7, 1824) 0 batch_normalization_95[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_33 (DepthwiseC (None, 7, 7, 1824) 45600 swish_95[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_96 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_33[0][0] \n__________________________________________________________________________________________________\nswish_96 (Swish) (None, 7, 7, 1824) 0 batch_normalization_96[0][0] \n__________________________________________________________________________________________________\nlambda_33 (Lambda) (None, 1, 1, 1824) 0 swish_96[0][0] \n__________________________________________________________________________________________________\nconv2d_128 (Conv2D) (None, 1, 1, 76) 138700 lambda_33[0][0] \n__________________________________________________________________________________________________\nswish_97 (Swish) (None, 1, 1, 76) 0 conv2d_128[0][0] \n__________________________________________________________________________________________________\nconv2d_129 (Conv2D) (None, 1, 1, 1824) 140448 swish_97[0][0] \n__________________________________________________________________________________________________\nactivation_33 (Activation) (None, 1, 1, 1824) 0 conv2d_129[0][0] \n__________________________________________________________________________________________________\nmultiply_33 (Multiply) (None, 7, 7, 1824) 0 activation_33[0][0] \n swish_96[0][0] \n__________________________________________________________________________________________________\nconv2d_130 (Conv2D) (None, 7, 7, 304) 554496 multiply_33[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_97 (BatchNo (None, 7, 7, 304) 1216 conv2d_130[0][0] \n__________________________________________________________________________________________________\ndrop_connect_27 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_97[0][0] \n__________________________________________________________________________________________________\nadd_27 (Add) (None, 7, 7, 304) 0 drop_connect_27[0][0] \n add_26[0][0] \n__________________________________________________________________________________________________\nconv2d_131 (Conv2D) (None, 7, 7, 1824) 554496 add_27[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_98 (BatchNo (None, 7, 7, 1824) 7296 conv2d_131[0][0] \n__________________________________________________________________________________________________\nswish_98 (Swish) (None, 7, 7, 1824) 0 batch_normalization_98[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_34 (DepthwiseC (None, 7, 7, 1824) 45600 swish_98[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_99 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_34[0][0] \n__________________________________________________________________________________________________\nswish_99 (Swish) (None, 7, 7, 1824) 0 batch_normalization_99[0][0] \n__________________________________________________________________________________________________\nlambda_34 (Lambda) (None, 1, 1, 1824) 0 swish_99[0][0] \n__________________________________________________________________________________________________\nconv2d_132 (Conv2D) (None, 1, 1, 76) 138700 lambda_34[0][0] \n__________________________________________________________________________________________________\nswish_100 (Swish) (None, 1, 1, 76) 0 conv2d_132[0][0] \n__________________________________________________________________________________________________\nconv2d_133 (Conv2D) (None, 1, 1, 1824) 140448 swish_100[0][0] \n__________________________________________________________________________________________________\nactivation_34 (Activation) (None, 1, 1, 1824) 0 conv2d_133[0][0] \n__________________________________________________________________________________________________\nmultiply_34 (Multiply) (None, 7, 7, 1824) 0 activation_34[0][0] \n swish_99[0][0] \n__________________________________________________________________________________________________\nconv2d_134 (Conv2D) (None, 7, 7, 304) 554496 multiply_34[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_100 (BatchN (None, 7, 7, 304) 1216 conv2d_134[0][0] \n__________________________________________________________________________________________________\ndrop_connect_28 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_100[0][0] \n__________________________________________________________________________________________________\nadd_28 (Add) (None, 7, 7, 304) 0 drop_connect_28[0][0] \n add_27[0][0] \n__________________________________________________________________________________________________\nconv2d_135 (Conv2D) (None, 7, 7, 1824) 554496 add_28[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_101 (BatchN (None, 7, 7, 1824) 7296 conv2d_135[0][0] \n__________________________________________________________________________________________________\nswish_101 (Swish) (None, 7, 7, 1824) 0 batch_normalization_101[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_35 (DepthwiseC (None, 7, 7, 1824) 45600 swish_101[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_102 (BatchN (None, 7, 7, 1824) 7296 depthwise_conv2d_35[0][0] \n__________________________________________________________________________________________________\nswish_102 (Swish) (None, 7, 7, 1824) 0 batch_normalization_102[0][0] \n__________________________________________________________________________________________________\nlambda_35 (Lambda) (None, 1, 1, 1824) 0 swish_102[0][0] \n__________________________________________________________________________________________________\nconv2d_136 (Conv2D) (None, 1, 1, 76) 138700 lambda_35[0][0] \n__________________________________________________________________________________________________\nswish_103 (Swish) (None, 1, 1, 76) 0 conv2d_136[0][0] \n__________________________________________________________________________________________________\nconv2d_137 (Conv2D) (None, 1, 1, 1824) 140448 swish_103[0][0] \n__________________________________________________________________________________________________\nactivation_35 (Activation) (None, 1, 1, 1824) 0 conv2d_137[0][0] \n__________________________________________________________________________________________________\nmultiply_35 (Multiply) (None, 7, 7, 1824) 0 activation_35[0][0] \n swish_102[0][0] \n__________________________________________________________________________________________________\nconv2d_138 (Conv2D) (None, 7, 7, 304) 554496 multiply_35[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_103 (BatchN (None, 7, 7, 304) 1216 conv2d_138[0][0] \n__________________________________________________________________________________________________\ndrop_connect_29 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_103[0][0] \n__________________________________________________________________________________________________\nadd_29 (Add) (None, 7, 7, 304) 0 drop_connect_29[0][0] \n add_28[0][0] \n__________________________________________________________________________________________________\nconv2d_139 (Conv2D) (None, 7, 7, 1824) 554496 add_29[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_104 (BatchN (None, 7, 7, 1824) 7296 conv2d_139[0][0] \n__________________________________________________________________________________________________\nswish_104 (Swish) (None, 7, 7, 1824) 0 batch_normalization_104[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_36 (DepthwiseC (None, 7, 7, 1824) 45600 swish_104[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_105 (BatchN (None, 7, 7, 1824) 7296 depthwise_conv2d_36[0][0] \n__________________________________________________________________________________________________\nswish_105 (Swish) (None, 7, 7, 1824) 0 batch_normalization_105[0][0] \n__________________________________________________________________________________________________\nlambda_36 (Lambda) (None, 1, 1, 1824) 0 swish_105[0][0] \n__________________________________________________________________________________________________\nconv2d_140 (Conv2D) (None, 1, 1, 76) 138700 lambda_36[0][0] \n__________________________________________________________________________________________________\nswish_106 (Swish) (None, 1, 1, 76) 0 conv2d_140[0][0] \n__________________________________________________________________________________________________\nconv2d_141 (Conv2D) (None, 1, 1, 1824) 140448 swish_106[0][0] \n__________________________________________________________________________________________________\nactivation_36 (Activation) (None, 1, 1, 1824) 0 conv2d_141[0][0] \n__________________________________________________________________________________________________\nmultiply_36 (Multiply) (None, 7, 7, 1824) 0 activation_36[0][0] \n swish_105[0][0] \n__________________________________________________________________________________________________\nconv2d_142 (Conv2D) (None, 7, 7, 304) 554496 multiply_36[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_106 (BatchN (None, 7, 7, 304) 1216 conv2d_142[0][0] \n__________________________________________________________________________________________________\ndrop_connect_30 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_106[0][0] \n__________________________________________________________________________________________________\nadd_30 (Add) (None, 7, 7, 304) 0 drop_connect_30[0][0] \n add_29[0][0] \n__________________________________________________________________________________________________\nconv2d_143 (Conv2D) (None, 7, 7, 1824) 554496 add_30[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_107 (BatchN (None, 7, 7, 1824) 7296 conv2d_143[0][0] \n__________________________________________________________________________________________________\nswish_107 (Swish) (None, 7, 7, 1824) 0 batch_normalization_107[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_37 (DepthwiseC (None, 7, 7, 1824) 16416 swish_107[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_108 (BatchN (None, 7, 7, 1824) 7296 depthwise_conv2d_37[0][0] \n__________________________________________________________________________________________________\nswish_108 (Swish) (None, 7, 7, 1824) 0 batch_normalization_108[0][0] \n__________________________________________________________________________________________________\nlambda_37 (Lambda) (None, 1, 1, 1824) 0 swish_108[0][0] \n__________________________________________________________________________________________________\nconv2d_144 (Conv2D) (None, 1, 1, 76) 138700 lambda_37[0][0] \n__________________________________________________________________________________________________\nswish_109 (Swish) (None, 1, 1, 76) 0 conv2d_144[0][0] \n__________________________________________________________________________________________________\nconv2d_145 (Conv2D) (None, 1, 1, 1824) 140448 swish_109[0][0] \n__________________________________________________________________________________________________\nactivation_37 (Activation) (None, 1, 1, 1824) 0 conv2d_145[0][0] \n__________________________________________________________________________________________________\nmultiply_37 (Multiply) (None, 7, 7, 1824) 0 activation_37[0][0] \n swish_108[0][0] \n__________________________________________________________________________________________________\nconv2d_146 (Conv2D) (None, 7, 7, 512) 933888 multiply_37[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_109 (BatchN (None, 7, 7, 512) 2048 conv2d_146[0][0] \n__________________________________________________________________________________________________\nconv2d_147 (Conv2D) (None, 7, 7, 3072) 1572864 batch_normalization_109[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_110 (BatchN (None, 7, 7, 3072) 12288 conv2d_147[0][0] \n__________________________________________________________________________________________________\nswish_110 (Swish) (None, 7, 7, 3072) 0 batch_normalization_110[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_38 (DepthwiseC (None, 7, 7, 3072) 27648 swish_110[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_111 (BatchN (None, 7, 7, 3072) 12288 depthwise_conv2d_38[0][0] \n__________________________________________________________________________________________________\nswish_111 (Swish) (None, 7, 7, 3072) 0 batch_normalization_111[0][0] \n__________________________________________________________________________________________________\nlambda_38 (Lambda) (None, 1, 1, 3072) 0 swish_111[0][0] \n__________________________________________________________________________________________________\nconv2d_148 (Conv2D) (None, 1, 1, 128) 393344 lambda_38[0][0] \n__________________________________________________________________________________________________\nswish_112 (Swish) (None, 1, 1, 128) 0 conv2d_148[0][0] \n__________________________________________________________________________________________________\nconv2d_149 (Conv2D) (None, 1, 1, 3072) 396288 swish_112[0][0] \n__________________________________________________________________________________________________\nactivation_38 (Activation) (None, 1, 1, 3072) 0 conv2d_149[0][0] \n__________________________________________________________________________________________________\nmultiply_38 (Multiply) (None, 7, 7, 3072) 0 activation_38[0][0] \n swish_111[0][0] \n__________________________________________________________________________________________________\nconv2d_150 (Conv2D) (None, 7, 7, 512) 1572864 multiply_38[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_112 (BatchN (None, 7, 7, 512) 2048 conv2d_150[0][0] \n__________________________________________________________________________________________________\ndrop_connect_31 (DropConnect) (None, 7, 7, 512) 0 batch_normalization_112[0][0] \n__________________________________________________________________________________________________\nadd_31 (Add) (None, 7, 7, 512) 0 drop_connect_31[0][0] \n batch_normalization_109[0][0] \n__________________________________________________________________________________________________\nconv2d_151 (Conv2D) (None, 7, 7, 3072) 1572864 add_31[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_113 (BatchN (None, 7, 7, 3072) 12288 conv2d_151[0][0] \n__________________________________________________________________________________________________\nswish_113 (Swish) (None, 7, 7, 3072) 0 batch_normalization_113[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_39 (DepthwiseC (None, 7, 7, 3072) 27648 swish_113[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_114 (BatchN (None, 7, 7, 3072) 12288 depthwise_conv2d_39[0][0] \n__________________________________________________________________________________________________\nswish_114 (Swish) (None, 7, 7, 3072) 0 batch_normalization_114[0][0] \n__________________________________________________________________________________________________\nlambda_39 (Lambda) (None, 1, 1, 3072) 0 swish_114[0][0] \n__________________________________________________________________________________________________\nconv2d_152 (Conv2D) (None, 1, 1, 128) 393344 lambda_39[0][0] \n__________________________________________________________________________________________________\nswish_115 (Swish) (None, 1, 1, 128) 0 conv2d_152[0][0] \n__________________________________________________________________________________________________\nconv2d_153 (Conv2D) (None, 1, 1, 3072) 396288 swish_115[0][0] \n__________________________________________________________________________________________________\nactivation_39 (Activation) (None, 1, 1, 3072) 0 conv2d_153[0][0] \n__________________________________________________________________________________________________\nmultiply_39 (Multiply) (None, 7, 7, 3072) 0 activation_39[0][0] \n swish_114[0][0] \n__________________________________________________________________________________________________\nconv2d_154 (Conv2D) (None, 7, 7, 512) 1572864 multiply_39[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_115 (BatchN (None, 7, 7, 512) 2048 conv2d_154[0][0] \n__________________________________________________________________________________________________\ndrop_connect_32 (DropConnect) (None, 7, 7, 512) 0 batch_normalization_115[0][0] \n__________________________________________________________________________________________________\nadd_32 (Add) (None, 7, 7, 512) 0 drop_connect_32[0][0] \n add_31[0][0] \n__________________________________________________________________________________________________\nconv2d_155 (Conv2D) (None, 7, 7, 2048) 1048576 add_32[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_116 (BatchN (None, 7, 7, 2048) 8192 conv2d_155[0][0] \n__________________________________________________________________________________________________\nswish_116 (Swish) (None, 7, 7, 2048) 0 batch_normalization_116[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling2d_1 (Glo (None, 2048) 0 swish_116[0][0] \n__________________________________________________________________________________________________\nfinal_output (Dense) (None, 1) 2049 global_average_pooling2d_1[0][0] \n==================================================================================================\nTotal params: 28,515,569\nTrainable params: 2,049\nNon-trainable params: 28,513,520\n__________________________________________________________________________________________________\n" ], [ "STEP_SIZE_TRAIN = train_generator.n//train_generator.batch_size\nSTEP_SIZE_VALID = valid_generator.n//valid_generator.batch_size\n\nhistory_warmup = model.fit_generator(generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=valid_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=WARMUP_EPOCHS,\n callbacks=callback_list,\n verbose=2).history", "Epoch 1/5\n - 233s - loss: 1.7629 - acc: 0.3119 - val_loss: 1.6802 - val_acc: 0.1963\nEpoch 2/5\n - 222s - loss: 1.2568 - acc: 0.2917 - val_loss: 2.1269 - val_acc: 0.3430\nEpoch 3/5\n - 221s - loss: 1.2324 - acc: 0.3040 - val_loss: 3.2224 - val_acc: 0.3130\nEpoch 4/5\n - 221s - loss: 1.2268 - acc: 0.3022 - val_loss: 3.3881 - val_acc: 0.2729\nEpoch 5/5\n - 220s - loss: 1.1654 - acc: 0.3039 - val_loss: 1.8564 - val_acc: 0.3296\n" ] ], [ [ "# Fine-tune the complete model", "_____no_output_____" ] ], [ [ "for layer in model.layers:\n layer.trainable = True\n\nes = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, restore_best_weights=True, verbose=1)\ncosine_lr_2nd = WarmUpCosineDecayScheduler(learning_rate_base=LEARNING_RATE,\n total_steps=TOTAL_STEPS_2nd,\n warmup_learning_rate=0.0,\n warmup_steps=WARMUP_STEPS_2nd,\n hold_base_rate_steps=(3 * STEP_SIZE))\n\ncallback_list = [es, cosine_lr_2nd]\noptimizer = optimizers.Adam(lr=LEARNING_RATE)\nmodel.compile(optimizer=optimizer, loss='mean_squared_error', metrics=metric_list)\nmodel.summary()", "__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, 224, 224, 3) 0 \n__________________________________________________________________________________________________\nconv2d_1 (Conv2D) (None, 112, 112, 48) 1296 input_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_1 (BatchNor (None, 112, 112, 48) 192 conv2d_1[0][0] \n__________________________________________________________________________________________________\nswish_1 (Swish) (None, 112, 112, 48) 0 batch_normalization_1[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_1 (DepthwiseCo (None, 112, 112, 48) 432 swish_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_2 (BatchNor (None, 112, 112, 48) 192 depthwise_conv2d_1[0][0] \n__________________________________________________________________________________________________\nswish_2 (Swish) (None, 112, 112, 48) 0 batch_normalization_2[0][0] \n__________________________________________________________________________________________________\nlambda_1 (Lambda) (None, 1, 1, 48) 0 swish_2[0][0] \n__________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 1, 1, 12) 588 lambda_1[0][0] \n__________________________________________________________________________________________________\nswish_3 (Swish) (None, 1, 1, 12) 0 conv2d_2[0][0] \n__________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 1, 1, 48) 624 swish_3[0][0] \n__________________________________________________________________________________________________\nactivation_1 (Activation) (None, 1, 1, 48) 0 conv2d_3[0][0] \n__________________________________________________________________________________________________\nmultiply_1 (Multiply) (None, 112, 112, 48) 0 activation_1[0][0] \n swish_2[0][0] \n__________________________________________________________________________________________________\nconv2d_4 (Conv2D) (None, 112, 112, 24) 1152 multiply_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_3 (BatchNor (None, 112, 112, 24) 96 conv2d_4[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_2 (DepthwiseCo (None, 112, 112, 24) 216 batch_normalization_3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_4 (BatchNor (None, 112, 112, 24) 96 depthwise_conv2d_2[0][0] \n__________________________________________________________________________________________________\nswish_4 (Swish) (None, 112, 112, 24) 0 batch_normalization_4[0][0] \n__________________________________________________________________________________________________\nlambda_2 (Lambda) (None, 1, 1, 24) 0 swish_4[0][0] \n__________________________________________________________________________________________________\nconv2d_5 (Conv2D) (None, 1, 1, 6) 150 lambda_2[0][0] \n__________________________________________________________________________________________________\nswish_5 (Swish) (None, 1, 1, 6) 0 conv2d_5[0][0] \n__________________________________________________________________________________________________\nconv2d_6 (Conv2D) (None, 1, 1, 24) 168 swish_5[0][0] \n__________________________________________________________________________________________________\nactivation_2 (Activation) (None, 1, 1, 24) 0 conv2d_6[0][0] \n__________________________________________________________________________________________________\nmultiply_2 (Multiply) (None, 112, 112, 24) 0 activation_2[0][0] \n swish_4[0][0] \n__________________________________________________________________________________________________\nconv2d_7 (Conv2D) (None, 112, 112, 24) 576 multiply_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_5 (BatchNor (None, 112, 112, 24) 96 conv2d_7[0][0] \n__________________________________________________________________________________________________\ndrop_connect_1 (DropConnect) (None, 112, 112, 24) 0 batch_normalization_5[0][0] \n__________________________________________________________________________________________________\nadd_1 (Add) (None, 112, 112, 24) 0 drop_connect_1[0][0] \n batch_normalization_3[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_3 (DepthwiseCo (None, 112, 112, 24) 216 add_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_6 (BatchNor (None, 112, 112, 24) 96 depthwise_conv2d_3[0][0] \n__________________________________________________________________________________________________\nswish_6 (Swish) (None, 112, 112, 24) 0 batch_normalization_6[0][0] \n__________________________________________________________________________________________________\nlambda_3 (Lambda) (None, 1, 1, 24) 0 swish_6[0][0] \n__________________________________________________________________________________________________\nconv2d_8 (Conv2D) (None, 1, 1, 6) 150 lambda_3[0][0] \n__________________________________________________________________________________________________\nswish_7 (Swish) (None, 1, 1, 6) 0 conv2d_8[0][0] \n__________________________________________________________________________________________________\nconv2d_9 (Conv2D) (None, 1, 1, 24) 168 swish_7[0][0] \n__________________________________________________________________________________________________\nactivation_3 (Activation) (None, 1, 1, 24) 0 conv2d_9[0][0] \n__________________________________________________________________________________________________\nmultiply_3 (Multiply) (None, 112, 112, 24) 0 activation_3[0][0] \n swish_6[0][0] \n__________________________________________________________________________________________________\nconv2d_10 (Conv2D) (None, 112, 112, 24) 576 multiply_3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_7 (BatchNor (None, 112, 112, 24) 96 conv2d_10[0][0] \n__________________________________________________________________________________________________\ndrop_connect_2 (DropConnect) (None, 112, 112, 24) 0 batch_normalization_7[0][0] \n__________________________________________________________________________________________________\nadd_2 (Add) (None, 112, 112, 24) 0 drop_connect_2[0][0] \n add_1[0][0] \n__________________________________________________________________________________________________\nconv2d_11 (Conv2D) (None, 112, 112, 144 3456 add_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_8 (BatchNor (None, 112, 112, 144 576 conv2d_11[0][0] \n__________________________________________________________________________________________________\nswish_8 (Swish) (None, 112, 112, 144 0 batch_normalization_8[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_4 (DepthwiseCo (None, 56, 56, 144) 1296 swish_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_9 (BatchNor (None, 56, 56, 144) 576 depthwise_conv2d_4[0][0] \n__________________________________________________________________________________________________\nswish_9 (Swish) (None, 56, 56, 144) 0 batch_normalization_9[0][0] \n__________________________________________________________________________________________________\nlambda_4 (Lambda) (None, 1, 1, 144) 0 swish_9[0][0] \n__________________________________________________________________________________________________\nconv2d_12 (Conv2D) (None, 1, 1, 6) 870 lambda_4[0][0] \n__________________________________________________________________________________________________\nswish_10 (Swish) (None, 1, 1, 6) 0 conv2d_12[0][0] \n__________________________________________________________________________________________________\nconv2d_13 (Conv2D) (None, 1, 1, 144) 1008 swish_10[0][0] \n__________________________________________________________________________________________________\nactivation_4 (Activation) (None, 1, 1, 144) 0 conv2d_13[0][0] \n__________________________________________________________________________________________________\nmultiply_4 (Multiply) (None, 56, 56, 144) 0 activation_4[0][0] \n swish_9[0][0] \n__________________________________________________________________________________________________\nconv2d_14 (Conv2D) (None, 56, 56, 40) 5760 multiply_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_10 (BatchNo (None, 56, 56, 40) 160 conv2d_14[0][0] \n__________________________________________________________________________________________________\nconv2d_15 (Conv2D) (None, 56, 56, 240) 9600 batch_normalization_10[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_11 (BatchNo (None, 56, 56, 240) 960 conv2d_15[0][0] \n__________________________________________________________________________________________________\nswish_11 (Swish) (None, 56, 56, 240) 0 batch_normalization_11[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_5 (DepthwiseCo (None, 56, 56, 240) 2160 swish_11[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_12 (BatchNo (None, 56, 56, 240) 960 depthwise_conv2d_5[0][0] \n__________________________________________________________________________________________________\nswish_12 (Swish) (None, 56, 56, 240) 0 batch_normalization_12[0][0] \n__________________________________________________________________________________________________\nlambda_5 (Lambda) (None, 1, 1, 240) 0 swish_12[0][0] \n__________________________________________________________________________________________________\nconv2d_16 (Conv2D) (None, 1, 1, 10) 2410 lambda_5[0][0] \n__________________________________________________________________________________________________\nswish_13 (Swish) (None, 1, 1, 10) 0 conv2d_16[0][0] \n__________________________________________________________________________________________________\nconv2d_17 (Conv2D) (None, 1, 1, 240) 2640 swish_13[0][0] \n__________________________________________________________________________________________________\nactivation_5 (Activation) (None, 1, 1, 240) 0 conv2d_17[0][0] \n__________________________________________________________________________________________________\nmultiply_5 (Multiply) (None, 56, 56, 240) 0 activation_5[0][0] \n swish_12[0][0] \n__________________________________________________________________________________________________\nconv2d_18 (Conv2D) (None, 56, 56, 40) 9600 multiply_5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_13 (BatchNo (None, 56, 56, 40) 160 conv2d_18[0][0] \n__________________________________________________________________________________________________\ndrop_connect_3 (DropConnect) (None, 56, 56, 40) 0 batch_normalization_13[0][0] \n__________________________________________________________________________________________________\nadd_3 (Add) (None, 56, 56, 40) 0 drop_connect_3[0][0] \n batch_normalization_10[0][0] \n__________________________________________________________________________________________________\nconv2d_19 (Conv2D) (None, 56, 56, 240) 9600 add_3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_14 (BatchNo (None, 56, 56, 240) 960 conv2d_19[0][0] \n__________________________________________________________________________________________________\nswish_14 (Swish) (None, 56, 56, 240) 0 batch_normalization_14[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_6 (DepthwiseCo (None, 56, 56, 240) 2160 swish_14[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_15 (BatchNo (None, 56, 56, 240) 960 depthwise_conv2d_6[0][0] \n__________________________________________________________________________________________________\nswish_15 (Swish) (None, 56, 56, 240) 0 batch_normalization_15[0][0] \n__________________________________________________________________________________________________\nlambda_6 (Lambda) (None, 1, 1, 240) 0 swish_15[0][0] \n__________________________________________________________________________________________________\nconv2d_20 (Conv2D) (None, 1, 1, 10) 2410 lambda_6[0][0] \n__________________________________________________________________________________________________\nswish_16 (Swish) (None, 1, 1, 10) 0 conv2d_20[0][0] \n__________________________________________________________________________________________________\nconv2d_21 (Conv2D) (None, 1, 1, 240) 2640 swish_16[0][0] \n__________________________________________________________________________________________________\nactivation_6 (Activation) (None, 1, 1, 240) 0 conv2d_21[0][0] \n__________________________________________________________________________________________________\nmultiply_6 (Multiply) (None, 56, 56, 240) 0 activation_6[0][0] \n swish_15[0][0] \n__________________________________________________________________________________________________\nconv2d_22 (Conv2D) (None, 56, 56, 40) 9600 multiply_6[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_16 (BatchNo (None, 56, 56, 40) 160 conv2d_22[0][0] \n__________________________________________________________________________________________________\ndrop_connect_4 (DropConnect) (None, 56, 56, 40) 0 batch_normalization_16[0][0] \n__________________________________________________________________________________________________\nadd_4 (Add) (None, 56, 56, 40) 0 drop_connect_4[0][0] \n add_3[0][0] \n__________________________________________________________________________________________________\nconv2d_23 (Conv2D) (None, 56, 56, 240) 9600 add_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_17 (BatchNo (None, 56, 56, 240) 960 conv2d_23[0][0] \n__________________________________________________________________________________________________\nswish_17 (Swish) (None, 56, 56, 240) 0 batch_normalization_17[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_7 (DepthwiseCo (None, 56, 56, 240) 2160 swish_17[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_18 (BatchNo (None, 56, 56, 240) 960 depthwise_conv2d_7[0][0] \n__________________________________________________________________________________________________\nswish_18 (Swish) (None, 56, 56, 240) 0 batch_normalization_18[0][0] \n__________________________________________________________________________________________________\nlambda_7 (Lambda) (None, 1, 1, 240) 0 swish_18[0][0] \n__________________________________________________________________________________________________\nconv2d_24 (Conv2D) (None, 1, 1, 10) 2410 lambda_7[0][0] \n__________________________________________________________________________________________________\nswish_19 (Swish) (None, 1, 1, 10) 0 conv2d_24[0][0] \n__________________________________________________________________________________________________\nconv2d_25 (Conv2D) (None, 1, 1, 240) 2640 swish_19[0][0] \n__________________________________________________________________________________________________\nactivation_7 (Activation) (None, 1, 1, 240) 0 conv2d_25[0][0] \n__________________________________________________________________________________________________\nmultiply_7 (Multiply) (None, 56, 56, 240) 0 activation_7[0][0] \n swish_18[0][0] \n__________________________________________________________________________________________________\nconv2d_26 (Conv2D) (None, 56, 56, 40) 9600 multiply_7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_19 (BatchNo (None, 56, 56, 40) 160 conv2d_26[0][0] \n__________________________________________________________________________________________________\ndrop_connect_5 (DropConnect) (None, 56, 56, 40) 0 batch_normalization_19[0][0] \n__________________________________________________________________________________________________\nadd_5 (Add) (None, 56, 56, 40) 0 drop_connect_5[0][0] \n add_4[0][0] \n__________________________________________________________________________________________________\nconv2d_27 (Conv2D) (None, 56, 56, 240) 9600 add_5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_20 (BatchNo (None, 56, 56, 240) 960 conv2d_27[0][0] \n__________________________________________________________________________________________________\nswish_20 (Swish) (None, 56, 56, 240) 0 batch_normalization_20[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_8 (DepthwiseCo (None, 56, 56, 240) 2160 swish_20[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_21 (BatchNo (None, 56, 56, 240) 960 depthwise_conv2d_8[0][0] \n__________________________________________________________________________________________________\nswish_21 (Swish) (None, 56, 56, 240) 0 batch_normalization_21[0][0] \n__________________________________________________________________________________________________\nlambda_8 (Lambda) (None, 1, 1, 240) 0 swish_21[0][0] \n__________________________________________________________________________________________________\nconv2d_28 (Conv2D) (None, 1, 1, 10) 2410 lambda_8[0][0] \n__________________________________________________________________________________________________\nswish_22 (Swish) (None, 1, 1, 10) 0 conv2d_28[0][0] \n__________________________________________________________________________________________________\nconv2d_29 (Conv2D) (None, 1, 1, 240) 2640 swish_22[0][0] \n__________________________________________________________________________________________________\nactivation_8 (Activation) (None, 1, 1, 240) 0 conv2d_29[0][0] \n__________________________________________________________________________________________________\nmultiply_8 (Multiply) (None, 56, 56, 240) 0 activation_8[0][0] \n swish_21[0][0] \n__________________________________________________________________________________________________\nconv2d_30 (Conv2D) (None, 56, 56, 40) 9600 multiply_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_22 (BatchNo (None, 56, 56, 40) 160 conv2d_30[0][0] \n__________________________________________________________________________________________________\ndrop_connect_6 (DropConnect) (None, 56, 56, 40) 0 batch_normalization_22[0][0] \n__________________________________________________________________________________________________\nadd_6 (Add) (None, 56, 56, 40) 0 drop_connect_6[0][0] \n add_5[0][0] \n__________________________________________________________________________________________________\nconv2d_31 (Conv2D) (None, 56, 56, 240) 9600 add_6[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_23 (BatchNo (None, 56, 56, 240) 960 conv2d_31[0][0] \n__________________________________________________________________________________________________\nswish_23 (Swish) (None, 56, 56, 240) 0 batch_normalization_23[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_9 (DepthwiseCo (None, 28, 28, 240) 6000 swish_23[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_24 (BatchNo (None, 28, 28, 240) 960 depthwise_conv2d_9[0][0] \n__________________________________________________________________________________________________\nswish_24 (Swish) (None, 28, 28, 240) 0 batch_normalization_24[0][0] \n__________________________________________________________________________________________________\nlambda_9 (Lambda) (None, 1, 1, 240) 0 swish_24[0][0] \n__________________________________________________________________________________________________\nconv2d_32 (Conv2D) (None, 1, 1, 10) 2410 lambda_9[0][0] \n__________________________________________________________________________________________________\nswish_25 (Swish) (None, 1, 1, 10) 0 conv2d_32[0][0] \n__________________________________________________________________________________________________\nconv2d_33 (Conv2D) (None, 1, 1, 240) 2640 swish_25[0][0] \n__________________________________________________________________________________________________\nactivation_9 (Activation) (None, 1, 1, 240) 0 conv2d_33[0][0] \n__________________________________________________________________________________________________\nmultiply_9 (Multiply) (None, 28, 28, 240) 0 activation_9[0][0] \n swish_24[0][0] \n__________________________________________________________________________________________________\nconv2d_34 (Conv2D) (None, 28, 28, 64) 15360 multiply_9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_25 (BatchNo (None, 28, 28, 64) 256 conv2d_34[0][0] \n__________________________________________________________________________________________________\nconv2d_35 (Conv2D) (None, 28, 28, 384) 24576 batch_normalization_25[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_26 (BatchNo (None, 28, 28, 384) 1536 conv2d_35[0][0] \n__________________________________________________________________________________________________\nswish_26 (Swish) (None, 28, 28, 384) 0 batch_normalization_26[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_10 (DepthwiseC (None, 28, 28, 384) 9600 swish_26[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_27 (BatchNo (None, 28, 28, 384) 1536 depthwise_conv2d_10[0][0] \n__________________________________________________________________________________________________\nswish_27 (Swish) (None, 28, 28, 384) 0 batch_normalization_27[0][0] \n__________________________________________________________________________________________________\nlambda_10 (Lambda) (None, 1, 1, 384) 0 swish_27[0][0] \n__________________________________________________________________________________________________\nconv2d_36 (Conv2D) (None, 1, 1, 16) 6160 lambda_10[0][0] \n__________________________________________________________________________________________________\nswish_28 (Swish) (None, 1, 1, 16) 0 conv2d_36[0][0] \n__________________________________________________________________________________________________\nconv2d_37 (Conv2D) (None, 1, 1, 384) 6528 swish_28[0][0] \n__________________________________________________________________________________________________\nactivation_10 (Activation) (None, 1, 1, 384) 0 conv2d_37[0][0] \n__________________________________________________________________________________________________\nmultiply_10 (Multiply) (None, 28, 28, 384) 0 activation_10[0][0] \n swish_27[0][0] \n__________________________________________________________________________________________________\nconv2d_38 (Conv2D) (None, 28, 28, 64) 24576 multiply_10[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_28 (BatchNo (None, 28, 28, 64) 256 conv2d_38[0][0] \n__________________________________________________________________________________________________\ndrop_connect_7 (DropConnect) (None, 28, 28, 64) 0 batch_normalization_28[0][0] \n__________________________________________________________________________________________________\nadd_7 (Add) (None, 28, 28, 64) 0 drop_connect_7[0][0] \n batch_normalization_25[0][0] \n__________________________________________________________________________________________________\nconv2d_39 (Conv2D) (None, 28, 28, 384) 24576 add_7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_29 (BatchNo (None, 28, 28, 384) 1536 conv2d_39[0][0] \n__________________________________________________________________________________________________\nswish_29 (Swish) (None, 28, 28, 384) 0 batch_normalization_29[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_11 (DepthwiseC (None, 28, 28, 384) 9600 swish_29[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_30 (BatchNo (None, 28, 28, 384) 1536 depthwise_conv2d_11[0][0] \n__________________________________________________________________________________________________\nswish_30 (Swish) (None, 28, 28, 384) 0 batch_normalization_30[0][0] \n__________________________________________________________________________________________________\nlambda_11 (Lambda) (None, 1, 1, 384) 0 swish_30[0][0] \n__________________________________________________________________________________________________\nconv2d_40 (Conv2D) (None, 1, 1, 16) 6160 lambda_11[0][0] \n__________________________________________________________________________________________________\nswish_31 (Swish) (None, 1, 1, 16) 0 conv2d_40[0][0] \n__________________________________________________________________________________________________\nconv2d_41 (Conv2D) (None, 1, 1, 384) 6528 swish_31[0][0] \n__________________________________________________________________________________________________\nactivation_11 (Activation) (None, 1, 1, 384) 0 conv2d_41[0][0] \n__________________________________________________________________________________________________\nmultiply_11 (Multiply) (None, 28, 28, 384) 0 activation_11[0][0] \n swish_30[0][0] \n__________________________________________________________________________________________________\nconv2d_42 (Conv2D) (None, 28, 28, 64) 24576 multiply_11[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_31 (BatchNo (None, 28, 28, 64) 256 conv2d_42[0][0] \n__________________________________________________________________________________________________\ndrop_connect_8 (DropConnect) (None, 28, 28, 64) 0 batch_normalization_31[0][0] \n__________________________________________________________________________________________________\nadd_8 (Add) (None, 28, 28, 64) 0 drop_connect_8[0][0] \n add_7[0][0] \n__________________________________________________________________________________________________\nconv2d_43 (Conv2D) (None, 28, 28, 384) 24576 add_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_32 (BatchNo (None, 28, 28, 384) 1536 conv2d_43[0][0] \n__________________________________________________________________________________________________\nswish_32 (Swish) (None, 28, 28, 384) 0 batch_normalization_32[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_12 (DepthwiseC (None, 28, 28, 384) 9600 swish_32[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_33 (BatchNo (None, 28, 28, 384) 1536 depthwise_conv2d_12[0][0] \n__________________________________________________________________________________________________\nswish_33 (Swish) (None, 28, 28, 384) 0 batch_normalization_33[0][0] \n__________________________________________________________________________________________________\nlambda_12 (Lambda) (None, 1, 1, 384) 0 swish_33[0][0] \n__________________________________________________________________________________________________\nconv2d_44 (Conv2D) (None, 1, 1, 16) 6160 lambda_12[0][0] \n__________________________________________________________________________________________________\nswish_34 (Swish) (None, 1, 1, 16) 0 conv2d_44[0][0] \n__________________________________________________________________________________________________\nconv2d_45 (Conv2D) (None, 1, 1, 384) 6528 swish_34[0][0] \n__________________________________________________________________________________________________\nactivation_12 (Activation) (None, 1, 1, 384) 0 conv2d_45[0][0] \n__________________________________________________________________________________________________\nmultiply_12 (Multiply) (None, 28, 28, 384) 0 activation_12[0][0] \n swish_33[0][0] \n__________________________________________________________________________________________________\nconv2d_46 (Conv2D) (None, 28, 28, 64) 24576 multiply_12[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_34 (BatchNo (None, 28, 28, 64) 256 conv2d_46[0][0] \n__________________________________________________________________________________________________\ndrop_connect_9 (DropConnect) (None, 28, 28, 64) 0 batch_normalization_34[0][0] \n__________________________________________________________________________________________________\nadd_9 (Add) (None, 28, 28, 64) 0 drop_connect_9[0][0] \n add_8[0][0] \n__________________________________________________________________________________________________\nconv2d_47 (Conv2D) (None, 28, 28, 384) 24576 add_9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_35 (BatchNo (None, 28, 28, 384) 1536 conv2d_47[0][0] \n__________________________________________________________________________________________________\nswish_35 (Swish) (None, 28, 28, 384) 0 batch_normalization_35[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_13 (DepthwiseC (None, 28, 28, 384) 9600 swish_35[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_36 (BatchNo (None, 28, 28, 384) 1536 depthwise_conv2d_13[0][0] \n__________________________________________________________________________________________________\nswish_36 (Swish) (None, 28, 28, 384) 0 batch_normalization_36[0][0] \n__________________________________________________________________________________________________\nlambda_13 (Lambda) (None, 1, 1, 384) 0 swish_36[0][0] \n__________________________________________________________________________________________________\nconv2d_48 (Conv2D) (None, 1, 1, 16) 6160 lambda_13[0][0] \n__________________________________________________________________________________________________\nswish_37 (Swish) (None, 1, 1, 16) 0 conv2d_48[0][0] \n__________________________________________________________________________________________________\nconv2d_49 (Conv2D) (None, 1, 1, 384) 6528 swish_37[0][0] \n__________________________________________________________________________________________________\nactivation_13 (Activation) (None, 1, 1, 384) 0 conv2d_49[0][0] \n__________________________________________________________________________________________________\nmultiply_13 (Multiply) (None, 28, 28, 384) 0 activation_13[0][0] \n swish_36[0][0] \n__________________________________________________________________________________________________\nconv2d_50 (Conv2D) (None, 28, 28, 64) 24576 multiply_13[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_37 (BatchNo (None, 28, 28, 64) 256 conv2d_50[0][0] \n__________________________________________________________________________________________________\ndrop_connect_10 (DropConnect) (None, 28, 28, 64) 0 batch_normalization_37[0][0] \n__________________________________________________________________________________________________\nadd_10 (Add) (None, 28, 28, 64) 0 drop_connect_10[0][0] \n add_9[0][0] \n__________________________________________________________________________________________________\nconv2d_51 (Conv2D) (None, 28, 28, 384) 24576 add_10[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_38 (BatchNo (None, 28, 28, 384) 1536 conv2d_51[0][0] \n__________________________________________________________________________________________________\nswish_38 (Swish) (None, 28, 28, 384) 0 batch_normalization_38[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_14 (DepthwiseC (None, 14, 14, 384) 3456 swish_38[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_39 (BatchNo (None, 14, 14, 384) 1536 depthwise_conv2d_14[0][0] \n__________________________________________________________________________________________________\nswish_39 (Swish) (None, 14, 14, 384) 0 batch_normalization_39[0][0] \n__________________________________________________________________________________________________\nlambda_14 (Lambda) (None, 1, 1, 384) 0 swish_39[0][0] \n__________________________________________________________________________________________________\nconv2d_52 (Conv2D) (None, 1, 1, 16) 6160 lambda_14[0][0] \n__________________________________________________________________________________________________\nswish_40 (Swish) (None, 1, 1, 16) 0 conv2d_52[0][0] \n__________________________________________________________________________________________________\nconv2d_53 (Conv2D) (None, 1, 1, 384) 6528 swish_40[0][0] \n__________________________________________________________________________________________________\nactivation_14 (Activation) (None, 1, 1, 384) 0 conv2d_53[0][0] \n__________________________________________________________________________________________________\nmultiply_14 (Multiply) (None, 14, 14, 384) 0 activation_14[0][0] \n swish_39[0][0] \n__________________________________________________________________________________________________\nconv2d_54 (Conv2D) (None, 14, 14, 128) 49152 multiply_14[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_40 (BatchNo (None, 14, 14, 128) 512 conv2d_54[0][0] \n__________________________________________________________________________________________________\nconv2d_55 (Conv2D) (None, 14, 14, 768) 98304 batch_normalization_40[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_41 (BatchNo (None, 14, 14, 768) 3072 conv2d_55[0][0] \n__________________________________________________________________________________________________\nswish_41 (Swish) (None, 14, 14, 768) 0 batch_normalization_41[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_15 (DepthwiseC (None, 14, 14, 768) 6912 swish_41[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_42 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_15[0][0] \n__________________________________________________________________________________________________\nswish_42 (Swish) (None, 14, 14, 768) 0 batch_normalization_42[0][0] \n__________________________________________________________________________________________________\nlambda_15 (Lambda) (None, 1, 1, 768) 0 swish_42[0][0] \n__________________________________________________________________________________________________\nconv2d_56 (Conv2D) (None, 1, 1, 32) 24608 lambda_15[0][0] \n__________________________________________________________________________________________________\nswish_43 (Swish) (None, 1, 1, 32) 0 conv2d_56[0][0] \n__________________________________________________________________________________________________\nconv2d_57 (Conv2D) (None, 1, 1, 768) 25344 swish_43[0][0] \n__________________________________________________________________________________________________\nactivation_15 (Activation) (None, 1, 1, 768) 0 conv2d_57[0][0] \n__________________________________________________________________________________________________\nmultiply_15 (Multiply) (None, 14, 14, 768) 0 activation_15[0][0] \n swish_42[0][0] \n__________________________________________________________________________________________________\nconv2d_58 (Conv2D) (None, 14, 14, 128) 98304 multiply_15[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_43 (BatchNo (None, 14, 14, 128) 512 conv2d_58[0][0] \n__________________________________________________________________________________________________\ndrop_connect_11 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_43[0][0] \n__________________________________________________________________________________________________\nadd_11 (Add) (None, 14, 14, 128) 0 drop_connect_11[0][0] \n batch_normalization_40[0][0] \n__________________________________________________________________________________________________\nconv2d_59 (Conv2D) (None, 14, 14, 768) 98304 add_11[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_44 (BatchNo (None, 14, 14, 768) 3072 conv2d_59[0][0] \n__________________________________________________________________________________________________\nswish_44 (Swish) (None, 14, 14, 768) 0 batch_normalization_44[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_16 (DepthwiseC (None, 14, 14, 768) 6912 swish_44[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_45 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_16[0][0] \n__________________________________________________________________________________________________\nswish_45 (Swish) (None, 14, 14, 768) 0 batch_normalization_45[0][0] \n__________________________________________________________________________________________________\nlambda_16 (Lambda) (None, 1, 1, 768) 0 swish_45[0][0] \n__________________________________________________________________________________________________\nconv2d_60 (Conv2D) (None, 1, 1, 32) 24608 lambda_16[0][0] \n__________________________________________________________________________________________________\nswish_46 (Swish) (None, 1, 1, 32) 0 conv2d_60[0][0] \n__________________________________________________________________________________________________\nconv2d_61 (Conv2D) (None, 1, 1, 768) 25344 swish_46[0][0] \n__________________________________________________________________________________________________\nactivation_16 (Activation) (None, 1, 1, 768) 0 conv2d_61[0][0] \n__________________________________________________________________________________________________\nmultiply_16 (Multiply) (None, 14, 14, 768) 0 activation_16[0][0] \n swish_45[0][0] \n__________________________________________________________________________________________________\nconv2d_62 (Conv2D) (None, 14, 14, 128) 98304 multiply_16[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_46 (BatchNo (None, 14, 14, 128) 512 conv2d_62[0][0] \n__________________________________________________________________________________________________\ndrop_connect_12 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_46[0][0] \n__________________________________________________________________________________________________\nadd_12 (Add) (None, 14, 14, 128) 0 drop_connect_12[0][0] \n add_11[0][0] \n__________________________________________________________________________________________________\nconv2d_63 (Conv2D) (None, 14, 14, 768) 98304 add_12[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_47 (BatchNo (None, 14, 14, 768) 3072 conv2d_63[0][0] \n__________________________________________________________________________________________________\nswish_47 (Swish) (None, 14, 14, 768) 0 batch_normalization_47[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_17 (DepthwiseC (None, 14, 14, 768) 6912 swish_47[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_48 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_17[0][0] \n__________________________________________________________________________________________________\nswish_48 (Swish) (None, 14, 14, 768) 0 batch_normalization_48[0][0] \n__________________________________________________________________________________________________\nlambda_17 (Lambda) (None, 1, 1, 768) 0 swish_48[0][0] \n__________________________________________________________________________________________________\nconv2d_64 (Conv2D) (None, 1, 1, 32) 24608 lambda_17[0][0] \n__________________________________________________________________________________________________\nswish_49 (Swish) (None, 1, 1, 32) 0 conv2d_64[0][0] \n__________________________________________________________________________________________________\nconv2d_65 (Conv2D) (None, 1, 1, 768) 25344 swish_49[0][0] \n__________________________________________________________________________________________________\nactivation_17 (Activation) (None, 1, 1, 768) 0 conv2d_65[0][0] \n__________________________________________________________________________________________________\nmultiply_17 (Multiply) (None, 14, 14, 768) 0 activation_17[0][0] \n swish_48[0][0] \n__________________________________________________________________________________________________\nconv2d_66 (Conv2D) (None, 14, 14, 128) 98304 multiply_17[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_49 (BatchNo (None, 14, 14, 128) 512 conv2d_66[0][0] \n__________________________________________________________________________________________________\ndrop_connect_13 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_49[0][0] \n__________________________________________________________________________________________________\nadd_13 (Add) (None, 14, 14, 128) 0 drop_connect_13[0][0] \n add_12[0][0] \n__________________________________________________________________________________________________\nconv2d_67 (Conv2D) (None, 14, 14, 768) 98304 add_13[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_50 (BatchNo (None, 14, 14, 768) 3072 conv2d_67[0][0] \n__________________________________________________________________________________________________\nswish_50 (Swish) (None, 14, 14, 768) 0 batch_normalization_50[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_18 (DepthwiseC (None, 14, 14, 768) 6912 swish_50[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_51 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_18[0][0] \n__________________________________________________________________________________________________\nswish_51 (Swish) (None, 14, 14, 768) 0 batch_normalization_51[0][0] \n__________________________________________________________________________________________________\nlambda_18 (Lambda) (None, 1, 1, 768) 0 swish_51[0][0] \n__________________________________________________________________________________________________\nconv2d_68 (Conv2D) (None, 1, 1, 32) 24608 lambda_18[0][0] \n__________________________________________________________________________________________________\nswish_52 (Swish) (None, 1, 1, 32) 0 conv2d_68[0][0] \n__________________________________________________________________________________________________\nconv2d_69 (Conv2D) (None, 1, 1, 768) 25344 swish_52[0][0] \n__________________________________________________________________________________________________\nactivation_18 (Activation) (None, 1, 1, 768) 0 conv2d_69[0][0] \n__________________________________________________________________________________________________\nmultiply_18 (Multiply) (None, 14, 14, 768) 0 activation_18[0][0] \n swish_51[0][0] \n__________________________________________________________________________________________________\nconv2d_70 (Conv2D) (None, 14, 14, 128) 98304 multiply_18[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_52 (BatchNo (None, 14, 14, 128) 512 conv2d_70[0][0] \n__________________________________________________________________________________________________\ndrop_connect_14 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_52[0][0] \n__________________________________________________________________________________________________\nadd_14 (Add) (None, 14, 14, 128) 0 drop_connect_14[0][0] \n add_13[0][0] \n__________________________________________________________________________________________________\nconv2d_71 (Conv2D) (None, 14, 14, 768) 98304 add_14[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_53 (BatchNo (None, 14, 14, 768) 3072 conv2d_71[0][0] \n__________________________________________________________________________________________________\nswish_53 (Swish) (None, 14, 14, 768) 0 batch_normalization_53[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_19 (DepthwiseC (None, 14, 14, 768) 6912 swish_53[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_54 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_19[0][0] \n__________________________________________________________________________________________________\nswish_54 (Swish) (None, 14, 14, 768) 0 batch_normalization_54[0][0] \n__________________________________________________________________________________________________\nlambda_19 (Lambda) (None, 1, 1, 768) 0 swish_54[0][0] \n__________________________________________________________________________________________________\nconv2d_72 (Conv2D) (None, 1, 1, 32) 24608 lambda_19[0][0] \n__________________________________________________________________________________________________\nswish_55 (Swish) (None, 1, 1, 32) 0 conv2d_72[0][0] \n__________________________________________________________________________________________________\nconv2d_73 (Conv2D) (None, 1, 1, 768) 25344 swish_55[0][0] \n__________________________________________________________________________________________________\nactivation_19 (Activation) (None, 1, 1, 768) 0 conv2d_73[0][0] \n__________________________________________________________________________________________________\nmultiply_19 (Multiply) (None, 14, 14, 768) 0 activation_19[0][0] \n swish_54[0][0] \n__________________________________________________________________________________________________\nconv2d_74 (Conv2D) (None, 14, 14, 128) 98304 multiply_19[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_55 (BatchNo (None, 14, 14, 128) 512 conv2d_74[0][0] \n__________________________________________________________________________________________________\ndrop_connect_15 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_55[0][0] \n__________________________________________________________________________________________________\nadd_15 (Add) (None, 14, 14, 128) 0 drop_connect_15[0][0] \n add_14[0][0] \n__________________________________________________________________________________________________\nconv2d_75 (Conv2D) (None, 14, 14, 768) 98304 add_15[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_56 (BatchNo (None, 14, 14, 768) 3072 conv2d_75[0][0] \n__________________________________________________________________________________________________\nswish_56 (Swish) (None, 14, 14, 768) 0 batch_normalization_56[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_20 (DepthwiseC (None, 14, 14, 768) 6912 swish_56[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_57 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_20[0][0] \n__________________________________________________________________________________________________\nswish_57 (Swish) (None, 14, 14, 768) 0 batch_normalization_57[0][0] \n__________________________________________________________________________________________________\nlambda_20 (Lambda) (None, 1, 1, 768) 0 swish_57[0][0] \n__________________________________________________________________________________________________\nconv2d_76 (Conv2D) (None, 1, 1, 32) 24608 lambda_20[0][0] \n__________________________________________________________________________________________________\nswish_58 (Swish) (None, 1, 1, 32) 0 conv2d_76[0][0] \n__________________________________________________________________________________________________\nconv2d_77 (Conv2D) (None, 1, 1, 768) 25344 swish_58[0][0] \n__________________________________________________________________________________________________\nactivation_20 (Activation) (None, 1, 1, 768) 0 conv2d_77[0][0] \n__________________________________________________________________________________________________\nmultiply_20 (Multiply) (None, 14, 14, 768) 0 activation_20[0][0] \n swish_57[0][0] \n__________________________________________________________________________________________________\nconv2d_78 (Conv2D) (None, 14, 14, 128) 98304 multiply_20[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_58 (BatchNo (None, 14, 14, 128) 512 conv2d_78[0][0] \n__________________________________________________________________________________________________\ndrop_connect_16 (DropConnect) (None, 14, 14, 128) 0 batch_normalization_58[0][0] \n__________________________________________________________________________________________________\nadd_16 (Add) (None, 14, 14, 128) 0 drop_connect_16[0][0] \n add_15[0][0] \n__________________________________________________________________________________________________\nconv2d_79 (Conv2D) (None, 14, 14, 768) 98304 add_16[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_59 (BatchNo (None, 14, 14, 768) 3072 conv2d_79[0][0] \n__________________________________________________________________________________________________\nswish_59 (Swish) (None, 14, 14, 768) 0 batch_normalization_59[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_21 (DepthwiseC (None, 14, 14, 768) 19200 swish_59[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_60 (BatchNo (None, 14, 14, 768) 3072 depthwise_conv2d_21[0][0] \n__________________________________________________________________________________________________\nswish_60 (Swish) (None, 14, 14, 768) 0 batch_normalization_60[0][0] \n__________________________________________________________________________________________________\nlambda_21 (Lambda) (None, 1, 1, 768) 0 swish_60[0][0] \n__________________________________________________________________________________________________\nconv2d_80 (Conv2D) (None, 1, 1, 32) 24608 lambda_21[0][0] \n__________________________________________________________________________________________________\nswish_61 (Swish) (None, 1, 1, 32) 0 conv2d_80[0][0] \n__________________________________________________________________________________________________\nconv2d_81 (Conv2D) (None, 1, 1, 768) 25344 swish_61[0][0] \n__________________________________________________________________________________________________\nactivation_21 (Activation) (None, 1, 1, 768) 0 conv2d_81[0][0] \n__________________________________________________________________________________________________\nmultiply_21 (Multiply) (None, 14, 14, 768) 0 activation_21[0][0] \n swish_60[0][0] \n__________________________________________________________________________________________________\nconv2d_82 (Conv2D) (None, 14, 14, 176) 135168 multiply_21[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_61 (BatchNo (None, 14, 14, 176) 704 conv2d_82[0][0] \n__________________________________________________________________________________________________\nconv2d_83 (Conv2D) (None, 14, 14, 1056) 185856 batch_normalization_61[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_62 (BatchNo (None, 14, 14, 1056) 4224 conv2d_83[0][0] \n__________________________________________________________________________________________________\nswish_62 (Swish) (None, 14, 14, 1056) 0 batch_normalization_62[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_22 (DepthwiseC (None, 14, 14, 1056) 26400 swish_62[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_63 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_22[0][0] \n__________________________________________________________________________________________________\nswish_63 (Swish) (None, 14, 14, 1056) 0 batch_normalization_63[0][0] \n__________________________________________________________________________________________________\nlambda_22 (Lambda) (None, 1, 1, 1056) 0 swish_63[0][0] \n__________________________________________________________________________________________________\nconv2d_84 (Conv2D) (None, 1, 1, 44) 46508 lambda_22[0][0] \n__________________________________________________________________________________________________\nswish_64 (Swish) (None, 1, 1, 44) 0 conv2d_84[0][0] \n__________________________________________________________________________________________________\nconv2d_85 (Conv2D) (None, 1, 1, 1056) 47520 swish_64[0][0] \n__________________________________________________________________________________________________\nactivation_22 (Activation) (None, 1, 1, 1056) 0 conv2d_85[0][0] \n__________________________________________________________________________________________________\nmultiply_22 (Multiply) (None, 14, 14, 1056) 0 activation_22[0][0] \n swish_63[0][0] \n__________________________________________________________________________________________________\nconv2d_86 (Conv2D) (None, 14, 14, 176) 185856 multiply_22[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_64 (BatchNo (None, 14, 14, 176) 704 conv2d_86[0][0] \n__________________________________________________________________________________________________\ndrop_connect_17 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_64[0][0] \n__________________________________________________________________________________________________\nadd_17 (Add) (None, 14, 14, 176) 0 drop_connect_17[0][0] \n batch_normalization_61[0][0] \n__________________________________________________________________________________________________\nconv2d_87 (Conv2D) (None, 14, 14, 1056) 185856 add_17[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_65 (BatchNo (None, 14, 14, 1056) 4224 conv2d_87[0][0] \n__________________________________________________________________________________________________\nswish_65 (Swish) (None, 14, 14, 1056) 0 batch_normalization_65[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_23 (DepthwiseC (None, 14, 14, 1056) 26400 swish_65[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_66 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_23[0][0] \n__________________________________________________________________________________________________\nswish_66 (Swish) (None, 14, 14, 1056) 0 batch_normalization_66[0][0] \n__________________________________________________________________________________________________\nlambda_23 (Lambda) (None, 1, 1, 1056) 0 swish_66[0][0] \n__________________________________________________________________________________________________\nconv2d_88 (Conv2D) (None, 1, 1, 44) 46508 lambda_23[0][0] \n__________________________________________________________________________________________________\nswish_67 (Swish) (None, 1, 1, 44) 0 conv2d_88[0][0] \n__________________________________________________________________________________________________\nconv2d_89 (Conv2D) (None, 1, 1, 1056) 47520 swish_67[0][0] \n__________________________________________________________________________________________________\nactivation_23 (Activation) (None, 1, 1, 1056) 0 conv2d_89[0][0] \n__________________________________________________________________________________________________\nmultiply_23 (Multiply) (None, 14, 14, 1056) 0 activation_23[0][0] \n swish_66[0][0] \n__________________________________________________________________________________________________\nconv2d_90 (Conv2D) (None, 14, 14, 176) 185856 multiply_23[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_67 (BatchNo (None, 14, 14, 176) 704 conv2d_90[0][0] \n__________________________________________________________________________________________________\ndrop_connect_18 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_67[0][0] \n__________________________________________________________________________________________________\nadd_18 (Add) (None, 14, 14, 176) 0 drop_connect_18[0][0] \n add_17[0][0] \n__________________________________________________________________________________________________\nconv2d_91 (Conv2D) (None, 14, 14, 1056) 185856 add_18[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_68 (BatchNo (None, 14, 14, 1056) 4224 conv2d_91[0][0] \n__________________________________________________________________________________________________\nswish_68 (Swish) (None, 14, 14, 1056) 0 batch_normalization_68[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_24 (DepthwiseC (None, 14, 14, 1056) 26400 swish_68[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_69 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_24[0][0] \n__________________________________________________________________________________________________\nswish_69 (Swish) (None, 14, 14, 1056) 0 batch_normalization_69[0][0] \n__________________________________________________________________________________________________\nlambda_24 (Lambda) (None, 1, 1, 1056) 0 swish_69[0][0] \n__________________________________________________________________________________________________\nconv2d_92 (Conv2D) (None, 1, 1, 44) 46508 lambda_24[0][0] \n__________________________________________________________________________________________________\nswish_70 (Swish) (None, 1, 1, 44) 0 conv2d_92[0][0] \n__________________________________________________________________________________________________\nconv2d_93 (Conv2D) (None, 1, 1, 1056) 47520 swish_70[0][0] \n__________________________________________________________________________________________________\nactivation_24 (Activation) (None, 1, 1, 1056) 0 conv2d_93[0][0] \n__________________________________________________________________________________________________\nmultiply_24 (Multiply) (None, 14, 14, 1056) 0 activation_24[0][0] \n swish_69[0][0] \n__________________________________________________________________________________________________\nconv2d_94 (Conv2D) (None, 14, 14, 176) 185856 multiply_24[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_70 (BatchNo (None, 14, 14, 176) 704 conv2d_94[0][0] \n__________________________________________________________________________________________________\ndrop_connect_19 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_70[0][0] \n__________________________________________________________________________________________________\nadd_19 (Add) (None, 14, 14, 176) 0 drop_connect_19[0][0] \n add_18[0][0] \n__________________________________________________________________________________________________\nconv2d_95 (Conv2D) (None, 14, 14, 1056) 185856 add_19[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_71 (BatchNo (None, 14, 14, 1056) 4224 conv2d_95[0][0] \n__________________________________________________________________________________________________\nswish_71 (Swish) (None, 14, 14, 1056) 0 batch_normalization_71[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_25 (DepthwiseC (None, 14, 14, 1056) 26400 swish_71[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_72 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_25[0][0] \n__________________________________________________________________________________________________\nswish_72 (Swish) (None, 14, 14, 1056) 0 batch_normalization_72[0][0] \n__________________________________________________________________________________________________\nlambda_25 (Lambda) (None, 1, 1, 1056) 0 swish_72[0][0] \n__________________________________________________________________________________________________\nconv2d_96 (Conv2D) (None, 1, 1, 44) 46508 lambda_25[0][0] \n__________________________________________________________________________________________________\nswish_73 (Swish) (None, 1, 1, 44) 0 conv2d_96[0][0] \n__________________________________________________________________________________________________\nconv2d_97 (Conv2D) (None, 1, 1, 1056) 47520 swish_73[0][0] \n__________________________________________________________________________________________________\nactivation_25 (Activation) (None, 1, 1, 1056) 0 conv2d_97[0][0] \n__________________________________________________________________________________________________\nmultiply_25 (Multiply) (None, 14, 14, 1056) 0 activation_25[0][0] \n swish_72[0][0] \n__________________________________________________________________________________________________\nconv2d_98 (Conv2D) (None, 14, 14, 176) 185856 multiply_25[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_73 (BatchNo (None, 14, 14, 176) 704 conv2d_98[0][0] \n__________________________________________________________________________________________________\ndrop_connect_20 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_73[0][0] \n__________________________________________________________________________________________________\nadd_20 (Add) (None, 14, 14, 176) 0 drop_connect_20[0][0] \n add_19[0][0] \n__________________________________________________________________________________________________\nconv2d_99 (Conv2D) (None, 14, 14, 1056) 185856 add_20[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_74 (BatchNo (None, 14, 14, 1056) 4224 conv2d_99[0][0] \n__________________________________________________________________________________________________\nswish_74 (Swish) (None, 14, 14, 1056) 0 batch_normalization_74[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_26 (DepthwiseC (None, 14, 14, 1056) 26400 swish_74[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_75 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_26[0][0] \n__________________________________________________________________________________________________\nswish_75 (Swish) (None, 14, 14, 1056) 0 batch_normalization_75[0][0] \n__________________________________________________________________________________________________\nlambda_26 (Lambda) (None, 1, 1, 1056) 0 swish_75[0][0] \n__________________________________________________________________________________________________\nconv2d_100 (Conv2D) (None, 1, 1, 44) 46508 lambda_26[0][0] \n__________________________________________________________________________________________________\nswish_76 (Swish) (None, 1, 1, 44) 0 conv2d_100[0][0] \n__________________________________________________________________________________________________\nconv2d_101 (Conv2D) (None, 1, 1, 1056) 47520 swish_76[0][0] \n__________________________________________________________________________________________________\nactivation_26 (Activation) (None, 1, 1, 1056) 0 conv2d_101[0][0] \n__________________________________________________________________________________________________\nmultiply_26 (Multiply) (None, 14, 14, 1056) 0 activation_26[0][0] \n swish_75[0][0] \n__________________________________________________________________________________________________\nconv2d_102 (Conv2D) (None, 14, 14, 176) 185856 multiply_26[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_76 (BatchNo (None, 14, 14, 176) 704 conv2d_102[0][0] \n__________________________________________________________________________________________________\ndrop_connect_21 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_76[0][0] \n__________________________________________________________________________________________________\nadd_21 (Add) (None, 14, 14, 176) 0 drop_connect_21[0][0] \n add_20[0][0] \n__________________________________________________________________________________________________\nconv2d_103 (Conv2D) (None, 14, 14, 1056) 185856 add_21[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_77 (BatchNo (None, 14, 14, 1056) 4224 conv2d_103[0][0] \n__________________________________________________________________________________________________\nswish_77 (Swish) (None, 14, 14, 1056) 0 batch_normalization_77[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_27 (DepthwiseC (None, 14, 14, 1056) 26400 swish_77[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_78 (BatchNo (None, 14, 14, 1056) 4224 depthwise_conv2d_27[0][0] \n__________________________________________________________________________________________________\nswish_78 (Swish) (None, 14, 14, 1056) 0 batch_normalization_78[0][0] \n__________________________________________________________________________________________________\nlambda_27 (Lambda) (None, 1, 1, 1056) 0 swish_78[0][0] \n__________________________________________________________________________________________________\nconv2d_104 (Conv2D) (None, 1, 1, 44) 46508 lambda_27[0][0] \n__________________________________________________________________________________________________\nswish_79 (Swish) (None, 1, 1, 44) 0 conv2d_104[0][0] \n__________________________________________________________________________________________________\nconv2d_105 (Conv2D) (None, 1, 1, 1056) 47520 swish_79[0][0] \n__________________________________________________________________________________________________\nactivation_27 (Activation) (None, 1, 1, 1056) 0 conv2d_105[0][0] \n__________________________________________________________________________________________________\nmultiply_27 (Multiply) (None, 14, 14, 1056) 0 activation_27[0][0] \n swish_78[0][0] \n__________________________________________________________________________________________________\nconv2d_106 (Conv2D) (None, 14, 14, 176) 185856 multiply_27[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_79 (BatchNo (None, 14, 14, 176) 704 conv2d_106[0][0] \n__________________________________________________________________________________________________\ndrop_connect_22 (DropConnect) (None, 14, 14, 176) 0 batch_normalization_79[0][0] \n__________________________________________________________________________________________________\nadd_22 (Add) (None, 14, 14, 176) 0 drop_connect_22[0][0] \n add_21[0][0] \n__________________________________________________________________________________________________\nconv2d_107 (Conv2D) (None, 14, 14, 1056) 185856 add_22[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_80 (BatchNo (None, 14, 14, 1056) 4224 conv2d_107[0][0] \n__________________________________________________________________________________________________\nswish_80 (Swish) (None, 14, 14, 1056) 0 batch_normalization_80[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_28 (DepthwiseC (None, 7, 7, 1056) 26400 swish_80[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_81 (BatchNo (None, 7, 7, 1056) 4224 depthwise_conv2d_28[0][0] \n__________________________________________________________________________________________________\nswish_81 (Swish) (None, 7, 7, 1056) 0 batch_normalization_81[0][0] \n__________________________________________________________________________________________________\nlambda_28 (Lambda) (None, 1, 1, 1056) 0 swish_81[0][0] \n__________________________________________________________________________________________________\nconv2d_108 (Conv2D) (None, 1, 1, 44) 46508 lambda_28[0][0] \n__________________________________________________________________________________________________\nswish_82 (Swish) (None, 1, 1, 44) 0 conv2d_108[0][0] \n__________________________________________________________________________________________________\nconv2d_109 (Conv2D) (None, 1, 1, 1056) 47520 swish_82[0][0] \n__________________________________________________________________________________________________\nactivation_28 (Activation) (None, 1, 1, 1056) 0 conv2d_109[0][0] \n__________________________________________________________________________________________________\nmultiply_28 (Multiply) (None, 7, 7, 1056) 0 activation_28[0][0] \n swish_81[0][0] \n__________________________________________________________________________________________________\nconv2d_110 (Conv2D) (None, 7, 7, 304) 321024 multiply_28[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_82 (BatchNo (None, 7, 7, 304) 1216 conv2d_110[0][0] \n__________________________________________________________________________________________________\nconv2d_111 (Conv2D) (None, 7, 7, 1824) 554496 batch_normalization_82[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_83 (BatchNo (None, 7, 7, 1824) 7296 conv2d_111[0][0] \n__________________________________________________________________________________________________\nswish_83 (Swish) (None, 7, 7, 1824) 0 batch_normalization_83[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_29 (DepthwiseC (None, 7, 7, 1824) 45600 swish_83[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_84 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_29[0][0] \n__________________________________________________________________________________________________\nswish_84 (Swish) (None, 7, 7, 1824) 0 batch_normalization_84[0][0] \n__________________________________________________________________________________________________\nlambda_29 (Lambda) (None, 1, 1, 1824) 0 swish_84[0][0] \n__________________________________________________________________________________________________\nconv2d_112 (Conv2D) (None, 1, 1, 76) 138700 lambda_29[0][0] \n__________________________________________________________________________________________________\nswish_85 (Swish) (None, 1, 1, 76) 0 conv2d_112[0][0] \n__________________________________________________________________________________________________\nconv2d_113 (Conv2D) (None, 1, 1, 1824) 140448 swish_85[0][0] \n__________________________________________________________________________________________________\nactivation_29 (Activation) (None, 1, 1, 1824) 0 conv2d_113[0][0] \n__________________________________________________________________________________________________\nmultiply_29 (Multiply) (None, 7, 7, 1824) 0 activation_29[0][0] \n swish_84[0][0] \n__________________________________________________________________________________________________\nconv2d_114 (Conv2D) (None, 7, 7, 304) 554496 multiply_29[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_85 (BatchNo (None, 7, 7, 304) 1216 conv2d_114[0][0] \n__________________________________________________________________________________________________\ndrop_connect_23 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_85[0][0] \n__________________________________________________________________________________________________\nadd_23 (Add) (None, 7, 7, 304) 0 drop_connect_23[0][0] \n batch_normalization_82[0][0] \n__________________________________________________________________________________________________\nconv2d_115 (Conv2D) (None, 7, 7, 1824) 554496 add_23[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_86 (BatchNo (None, 7, 7, 1824) 7296 conv2d_115[0][0] \n__________________________________________________________________________________________________\nswish_86 (Swish) (None, 7, 7, 1824) 0 batch_normalization_86[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_30 (DepthwiseC (None, 7, 7, 1824) 45600 swish_86[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_87 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_30[0][0] \n__________________________________________________________________________________________________\nswish_87 (Swish) (None, 7, 7, 1824) 0 batch_normalization_87[0][0] \n__________________________________________________________________________________________________\nlambda_30 (Lambda) (None, 1, 1, 1824) 0 swish_87[0][0] \n__________________________________________________________________________________________________\nconv2d_116 (Conv2D) (None, 1, 1, 76) 138700 lambda_30[0][0] \n__________________________________________________________________________________________________\nswish_88 (Swish) (None, 1, 1, 76) 0 conv2d_116[0][0] \n__________________________________________________________________________________________________\nconv2d_117 (Conv2D) (None, 1, 1, 1824) 140448 swish_88[0][0] \n__________________________________________________________________________________________________\nactivation_30 (Activation) (None, 1, 1, 1824) 0 conv2d_117[0][0] \n__________________________________________________________________________________________________\nmultiply_30 (Multiply) (None, 7, 7, 1824) 0 activation_30[0][0] \n swish_87[0][0] \n__________________________________________________________________________________________________\nconv2d_118 (Conv2D) (None, 7, 7, 304) 554496 multiply_30[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_88 (BatchNo (None, 7, 7, 304) 1216 conv2d_118[0][0] \n__________________________________________________________________________________________________\ndrop_connect_24 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_88[0][0] \n__________________________________________________________________________________________________\nadd_24 (Add) (None, 7, 7, 304) 0 drop_connect_24[0][0] \n add_23[0][0] \n__________________________________________________________________________________________________\nconv2d_119 (Conv2D) (None, 7, 7, 1824) 554496 add_24[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_89 (BatchNo (None, 7, 7, 1824) 7296 conv2d_119[0][0] \n__________________________________________________________________________________________________\nswish_89 (Swish) (None, 7, 7, 1824) 0 batch_normalization_89[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_31 (DepthwiseC (None, 7, 7, 1824) 45600 swish_89[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_90 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_31[0][0] \n__________________________________________________________________________________________________\nswish_90 (Swish) (None, 7, 7, 1824) 0 batch_normalization_90[0][0] \n__________________________________________________________________________________________________\nlambda_31 (Lambda) (None, 1, 1, 1824) 0 swish_90[0][0] \n__________________________________________________________________________________________________\nconv2d_120 (Conv2D) (None, 1, 1, 76) 138700 lambda_31[0][0] \n__________________________________________________________________________________________________\nswish_91 (Swish) (None, 1, 1, 76) 0 conv2d_120[0][0] \n__________________________________________________________________________________________________\nconv2d_121 (Conv2D) (None, 1, 1, 1824) 140448 swish_91[0][0] \n__________________________________________________________________________________________________\nactivation_31 (Activation) (None, 1, 1, 1824) 0 conv2d_121[0][0] \n__________________________________________________________________________________________________\nmultiply_31 (Multiply) (None, 7, 7, 1824) 0 activation_31[0][0] \n swish_90[0][0] \n__________________________________________________________________________________________________\nconv2d_122 (Conv2D) (None, 7, 7, 304) 554496 multiply_31[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_91 (BatchNo (None, 7, 7, 304) 1216 conv2d_122[0][0] \n__________________________________________________________________________________________________\ndrop_connect_25 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_91[0][0] \n__________________________________________________________________________________________________\nadd_25 (Add) (None, 7, 7, 304) 0 drop_connect_25[0][0] \n add_24[0][0] \n__________________________________________________________________________________________________\nconv2d_123 (Conv2D) (None, 7, 7, 1824) 554496 add_25[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_92 (BatchNo (None, 7, 7, 1824) 7296 conv2d_123[0][0] \n__________________________________________________________________________________________________\nswish_92 (Swish) (None, 7, 7, 1824) 0 batch_normalization_92[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_32 (DepthwiseC (None, 7, 7, 1824) 45600 swish_92[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_93 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_32[0][0] \n__________________________________________________________________________________________________\nswish_93 (Swish) (None, 7, 7, 1824) 0 batch_normalization_93[0][0] \n__________________________________________________________________________________________________\nlambda_32 (Lambda) (None, 1, 1, 1824) 0 swish_93[0][0] \n__________________________________________________________________________________________________\nconv2d_124 (Conv2D) (None, 1, 1, 76) 138700 lambda_32[0][0] \n__________________________________________________________________________________________________\nswish_94 (Swish) (None, 1, 1, 76) 0 conv2d_124[0][0] \n__________________________________________________________________________________________________\nconv2d_125 (Conv2D) (None, 1, 1, 1824) 140448 swish_94[0][0] \n__________________________________________________________________________________________________\nactivation_32 (Activation) (None, 1, 1, 1824) 0 conv2d_125[0][0] \n__________________________________________________________________________________________________\nmultiply_32 (Multiply) (None, 7, 7, 1824) 0 activation_32[0][0] \n swish_93[0][0] \n__________________________________________________________________________________________________\nconv2d_126 (Conv2D) (None, 7, 7, 304) 554496 multiply_32[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_94 (BatchNo (None, 7, 7, 304) 1216 conv2d_126[0][0] \n__________________________________________________________________________________________________\ndrop_connect_26 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_94[0][0] \n__________________________________________________________________________________________________\nadd_26 (Add) (None, 7, 7, 304) 0 drop_connect_26[0][0] \n add_25[0][0] \n__________________________________________________________________________________________________\nconv2d_127 (Conv2D) (None, 7, 7, 1824) 554496 add_26[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_95 (BatchNo (None, 7, 7, 1824) 7296 conv2d_127[0][0] \n__________________________________________________________________________________________________\nswish_95 (Swish) (None, 7, 7, 1824) 0 batch_normalization_95[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_33 (DepthwiseC (None, 7, 7, 1824) 45600 swish_95[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_96 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_33[0][0] \n__________________________________________________________________________________________________\nswish_96 (Swish) (None, 7, 7, 1824) 0 batch_normalization_96[0][0] \n__________________________________________________________________________________________________\nlambda_33 (Lambda) (None, 1, 1, 1824) 0 swish_96[0][0] \n__________________________________________________________________________________________________\nconv2d_128 (Conv2D) (None, 1, 1, 76) 138700 lambda_33[0][0] \n__________________________________________________________________________________________________\nswish_97 (Swish) (None, 1, 1, 76) 0 conv2d_128[0][0] \n__________________________________________________________________________________________________\nconv2d_129 (Conv2D) (None, 1, 1, 1824) 140448 swish_97[0][0] \n__________________________________________________________________________________________________\nactivation_33 (Activation) (None, 1, 1, 1824) 0 conv2d_129[0][0] \n__________________________________________________________________________________________________\nmultiply_33 (Multiply) (None, 7, 7, 1824) 0 activation_33[0][0] \n swish_96[0][0] \n__________________________________________________________________________________________________\nconv2d_130 (Conv2D) (None, 7, 7, 304) 554496 multiply_33[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_97 (BatchNo (None, 7, 7, 304) 1216 conv2d_130[0][0] \n__________________________________________________________________________________________________\ndrop_connect_27 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_97[0][0] \n__________________________________________________________________________________________________\nadd_27 (Add) (None, 7, 7, 304) 0 drop_connect_27[0][0] \n add_26[0][0] \n__________________________________________________________________________________________________\nconv2d_131 (Conv2D) (None, 7, 7, 1824) 554496 add_27[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_98 (BatchNo (None, 7, 7, 1824) 7296 conv2d_131[0][0] \n__________________________________________________________________________________________________\nswish_98 (Swish) (None, 7, 7, 1824) 0 batch_normalization_98[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_34 (DepthwiseC (None, 7, 7, 1824) 45600 swish_98[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_99 (BatchNo (None, 7, 7, 1824) 7296 depthwise_conv2d_34[0][0] \n__________________________________________________________________________________________________\nswish_99 (Swish) (None, 7, 7, 1824) 0 batch_normalization_99[0][0] \n__________________________________________________________________________________________________\nlambda_34 (Lambda) (None, 1, 1, 1824) 0 swish_99[0][0] \n__________________________________________________________________________________________________\nconv2d_132 (Conv2D) (None, 1, 1, 76) 138700 lambda_34[0][0] \n__________________________________________________________________________________________________\nswish_100 (Swish) (None, 1, 1, 76) 0 conv2d_132[0][0] \n__________________________________________________________________________________________________\nconv2d_133 (Conv2D) (None, 1, 1, 1824) 140448 swish_100[0][0] \n__________________________________________________________________________________________________\nactivation_34 (Activation) (None, 1, 1, 1824) 0 conv2d_133[0][0] \n__________________________________________________________________________________________________\nmultiply_34 (Multiply) (None, 7, 7, 1824) 0 activation_34[0][0] \n swish_99[0][0] \n__________________________________________________________________________________________________\nconv2d_134 (Conv2D) (None, 7, 7, 304) 554496 multiply_34[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_100 (BatchN (None, 7, 7, 304) 1216 conv2d_134[0][0] \n__________________________________________________________________________________________________\ndrop_connect_28 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_100[0][0] \n__________________________________________________________________________________________________\nadd_28 (Add) (None, 7, 7, 304) 0 drop_connect_28[0][0] \n add_27[0][0] \n__________________________________________________________________________________________________\nconv2d_135 (Conv2D) (None, 7, 7, 1824) 554496 add_28[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_101 (BatchN (None, 7, 7, 1824) 7296 conv2d_135[0][0] \n__________________________________________________________________________________________________\nswish_101 (Swish) (None, 7, 7, 1824) 0 batch_normalization_101[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_35 (DepthwiseC (None, 7, 7, 1824) 45600 swish_101[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_102 (BatchN (None, 7, 7, 1824) 7296 depthwise_conv2d_35[0][0] \n__________________________________________________________________________________________________\nswish_102 (Swish) (None, 7, 7, 1824) 0 batch_normalization_102[0][0] \n__________________________________________________________________________________________________\nlambda_35 (Lambda) (None, 1, 1, 1824) 0 swish_102[0][0] \n__________________________________________________________________________________________________\nconv2d_136 (Conv2D) (None, 1, 1, 76) 138700 lambda_35[0][0] \n__________________________________________________________________________________________________\nswish_103 (Swish) (None, 1, 1, 76) 0 conv2d_136[0][0] \n__________________________________________________________________________________________________\nconv2d_137 (Conv2D) (None, 1, 1, 1824) 140448 swish_103[0][0] \n__________________________________________________________________________________________________\nactivation_35 (Activation) (None, 1, 1, 1824) 0 conv2d_137[0][0] \n__________________________________________________________________________________________________\nmultiply_35 (Multiply) (None, 7, 7, 1824) 0 activation_35[0][0] \n swish_102[0][0] \n__________________________________________________________________________________________________\nconv2d_138 (Conv2D) (None, 7, 7, 304) 554496 multiply_35[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_103 (BatchN (None, 7, 7, 304) 1216 conv2d_138[0][0] \n__________________________________________________________________________________________________\ndrop_connect_29 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_103[0][0] \n__________________________________________________________________________________________________\nadd_29 (Add) (None, 7, 7, 304) 0 drop_connect_29[0][0] \n add_28[0][0] \n__________________________________________________________________________________________________\nconv2d_139 (Conv2D) (None, 7, 7, 1824) 554496 add_29[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_104 (BatchN (None, 7, 7, 1824) 7296 conv2d_139[0][0] \n__________________________________________________________________________________________________\nswish_104 (Swish) (None, 7, 7, 1824) 0 batch_normalization_104[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_36 (DepthwiseC (None, 7, 7, 1824) 45600 swish_104[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_105 (BatchN (None, 7, 7, 1824) 7296 depthwise_conv2d_36[0][0] \n__________________________________________________________________________________________________\nswish_105 (Swish) (None, 7, 7, 1824) 0 batch_normalization_105[0][0] \n__________________________________________________________________________________________________\nlambda_36 (Lambda) (None, 1, 1, 1824) 0 swish_105[0][0] \n__________________________________________________________________________________________________\nconv2d_140 (Conv2D) (None, 1, 1, 76) 138700 lambda_36[0][0] \n__________________________________________________________________________________________________\nswish_106 (Swish) (None, 1, 1, 76) 0 conv2d_140[0][0] \n__________________________________________________________________________________________________\nconv2d_141 (Conv2D) (None, 1, 1, 1824) 140448 swish_106[0][0] \n__________________________________________________________________________________________________\nactivation_36 (Activation) (None, 1, 1, 1824) 0 conv2d_141[0][0] \n__________________________________________________________________________________________________\nmultiply_36 (Multiply) (None, 7, 7, 1824) 0 activation_36[0][0] \n swish_105[0][0] \n__________________________________________________________________________________________________\nconv2d_142 (Conv2D) (None, 7, 7, 304) 554496 multiply_36[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_106 (BatchN (None, 7, 7, 304) 1216 conv2d_142[0][0] \n__________________________________________________________________________________________________\ndrop_connect_30 (DropConnect) (None, 7, 7, 304) 0 batch_normalization_106[0][0] \n__________________________________________________________________________________________________\nadd_30 (Add) (None, 7, 7, 304) 0 drop_connect_30[0][0] \n add_29[0][0] \n__________________________________________________________________________________________________\nconv2d_143 (Conv2D) (None, 7, 7, 1824) 554496 add_30[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_107 (BatchN (None, 7, 7, 1824) 7296 conv2d_143[0][0] \n__________________________________________________________________________________________________\nswish_107 (Swish) (None, 7, 7, 1824) 0 batch_normalization_107[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_37 (DepthwiseC (None, 7, 7, 1824) 16416 swish_107[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_108 (BatchN (None, 7, 7, 1824) 7296 depthwise_conv2d_37[0][0] \n__________________________________________________________________________________________________\nswish_108 (Swish) (None, 7, 7, 1824) 0 batch_normalization_108[0][0] \n__________________________________________________________________________________________________\nlambda_37 (Lambda) (None, 1, 1, 1824) 0 swish_108[0][0] \n__________________________________________________________________________________________________\nconv2d_144 (Conv2D) (None, 1, 1, 76) 138700 lambda_37[0][0] \n__________________________________________________________________________________________________\nswish_109 (Swish) (None, 1, 1, 76) 0 conv2d_144[0][0] \n__________________________________________________________________________________________________\nconv2d_145 (Conv2D) (None, 1, 1, 1824) 140448 swish_109[0][0] \n__________________________________________________________________________________________________\nactivation_37 (Activation) (None, 1, 1, 1824) 0 conv2d_145[0][0] \n__________________________________________________________________________________________________\nmultiply_37 (Multiply) (None, 7, 7, 1824) 0 activation_37[0][0] \n swish_108[0][0] \n__________________________________________________________________________________________________\nconv2d_146 (Conv2D) (None, 7, 7, 512) 933888 multiply_37[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_109 (BatchN (None, 7, 7, 512) 2048 conv2d_146[0][0] \n__________________________________________________________________________________________________\nconv2d_147 (Conv2D) (None, 7, 7, 3072) 1572864 batch_normalization_109[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_110 (BatchN (None, 7, 7, 3072) 12288 conv2d_147[0][0] \n__________________________________________________________________________________________________\nswish_110 (Swish) (None, 7, 7, 3072) 0 batch_normalization_110[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_38 (DepthwiseC (None, 7, 7, 3072) 27648 swish_110[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_111 (BatchN (None, 7, 7, 3072) 12288 depthwise_conv2d_38[0][0] \n__________________________________________________________________________________________________\nswish_111 (Swish) (None, 7, 7, 3072) 0 batch_normalization_111[0][0] \n__________________________________________________________________________________________________\nlambda_38 (Lambda) (None, 1, 1, 3072) 0 swish_111[0][0] \n__________________________________________________________________________________________________\nconv2d_148 (Conv2D) (None, 1, 1, 128) 393344 lambda_38[0][0] \n__________________________________________________________________________________________________\nswish_112 (Swish) (None, 1, 1, 128) 0 conv2d_148[0][0] \n__________________________________________________________________________________________________\nconv2d_149 (Conv2D) (None, 1, 1, 3072) 396288 swish_112[0][0] \n__________________________________________________________________________________________________\nactivation_38 (Activation) (None, 1, 1, 3072) 0 conv2d_149[0][0] \n__________________________________________________________________________________________________\nmultiply_38 (Multiply) (None, 7, 7, 3072) 0 activation_38[0][0] \n swish_111[0][0] \n__________________________________________________________________________________________________\nconv2d_150 (Conv2D) (None, 7, 7, 512) 1572864 multiply_38[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_112 (BatchN (None, 7, 7, 512) 2048 conv2d_150[0][0] \n__________________________________________________________________________________________________\ndrop_connect_31 (DropConnect) (None, 7, 7, 512) 0 batch_normalization_112[0][0] \n__________________________________________________________________________________________________\nadd_31 (Add) (None, 7, 7, 512) 0 drop_connect_31[0][0] \n batch_normalization_109[0][0] \n__________________________________________________________________________________________________\nconv2d_151 (Conv2D) (None, 7, 7, 3072) 1572864 add_31[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_113 (BatchN (None, 7, 7, 3072) 12288 conv2d_151[0][0] \n__________________________________________________________________________________________________\nswish_113 (Swish) (None, 7, 7, 3072) 0 batch_normalization_113[0][0] \n__________________________________________________________________________________________________\ndepthwise_conv2d_39 (DepthwiseC (None, 7, 7, 3072) 27648 swish_113[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_114 (BatchN (None, 7, 7, 3072) 12288 depthwise_conv2d_39[0][0] \n__________________________________________________________________________________________________\nswish_114 (Swish) (None, 7, 7, 3072) 0 batch_normalization_114[0][0] \n__________________________________________________________________________________________________\nlambda_39 (Lambda) (None, 1, 1, 3072) 0 swish_114[0][0] \n__________________________________________________________________________________________________\nconv2d_152 (Conv2D) (None, 1, 1, 128) 393344 lambda_39[0][0] \n__________________________________________________________________________________________________\nswish_115 (Swish) (None, 1, 1, 128) 0 conv2d_152[0][0] \n__________________________________________________________________________________________________\nconv2d_153 (Conv2D) (None, 1, 1, 3072) 396288 swish_115[0][0] \n__________________________________________________________________________________________________\nactivation_39 (Activation) (None, 1, 1, 3072) 0 conv2d_153[0][0] \n__________________________________________________________________________________________________\nmultiply_39 (Multiply) (None, 7, 7, 3072) 0 activation_39[0][0] \n swish_114[0][0] \n__________________________________________________________________________________________________\nconv2d_154 (Conv2D) (None, 7, 7, 512) 1572864 multiply_39[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_115 (BatchN (None, 7, 7, 512) 2048 conv2d_154[0][0] \n__________________________________________________________________________________________________\ndrop_connect_32 (DropConnect) (None, 7, 7, 512) 0 batch_normalization_115[0][0] \n__________________________________________________________________________________________________\nadd_32 (Add) (None, 7, 7, 512) 0 drop_connect_32[0][0] \n add_31[0][0] \n__________________________________________________________________________________________________\nconv2d_155 (Conv2D) (None, 7, 7, 2048) 1048576 add_32[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_116 (BatchN (None, 7, 7, 2048) 8192 conv2d_155[0][0] \n__________________________________________________________________________________________________\nswish_116 (Swish) (None, 7, 7, 2048) 0 batch_normalization_116[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling2d_1 (Glo (None, 2048) 0 swish_116[0][0] \n__________________________________________________________________________________________________\nfinal_output (Dense) (None, 1) 2049 global_average_pooling2d_1[0][0] \n==================================================================================================\nTotal params: 28,515,569\nTrainable params: 28,342,833\nNon-trainable params: 172,736\n__________________________________________________________________________________________________\n" ], [ "history = model.fit_generator(generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=valid_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=EPOCHS,\n callbacks=callback_list,\n verbose=2).history", "Epoch 1/20\n - 511s - loss: 1.0456 - acc: 0.3303 - val_loss: 0.5170 - val_acc: 0.5931\nEpoch 2/20\n - 466s - loss: 0.8683 - acc: 0.3688 - val_loss: 0.4086 - val_acc: 0.6937\nEpoch 3/20\n - 466s - loss: 0.7548 - acc: 0.4039 - val_loss: 0.3718 - val_acc: 0.7115\nEpoch 4/20\n - 465s - loss: 0.6858 - acc: 0.4392 - val_loss: 0.3637 - val_acc: 0.7093\nEpoch 5/20\n - 466s - loss: 0.6526 - acc: 0.4569 - val_loss: 0.3312 - val_acc: 0.7560\nEpoch 6/20\n - 466s - loss: 0.6265 - acc: 0.4845 - val_loss: 0.3525 - val_acc: 0.7076\nEpoch 7/20\n - 464s - loss: 0.5909 - acc: 0.5026 - val_loss: 0.3599 - val_acc: 0.7248\nEpoch 8/20\n - 464s - loss: 0.5667 - acc: 0.5165 - val_loss: 0.4651 - val_acc: 0.7487\nEpoch 9/20\n - 466s - loss: 0.5560 - acc: 0.5280 - val_loss: 0.2760 - val_acc: 0.7899\nEpoch 10/20\n - 466s - loss: 0.5347 - acc: 0.5363 - val_loss: 0.3465 - val_acc: 0.7710\nEpoch 11/20\n - 465s - loss: 0.5085 - acc: 0.5582 - val_loss: 0.3280 - val_acc: 0.7310\nEpoch 12/20\n - 466s - loss: 0.4908 - acc: 0.5673 - val_loss: 0.3140 - val_acc: 0.7476\nEpoch 13/20\n - 466s - loss: 0.4536 - acc: 0.5923 - val_loss: 0.2864 - val_acc: 0.7560\nEpoch 14/20\n - 464s - loss: 0.4248 - acc: 0.6150 - val_loss: 0.2438 - val_acc: 0.8121\nEpoch 15/20\n - 465s - loss: 0.3909 - acc: 0.6391 - val_loss: 0.2576 - val_acc: 0.8054\nEpoch 16/20\n - 465s - loss: 0.3525 - acc: 0.6666 - val_loss: 0.2448 - val_acc: 0.8021\nEpoch 17/20\n - 465s - loss: 0.3253 - acc: 0.6795 - val_loss: 0.2485 - val_acc: 0.8110\nEpoch 18/20\n - 466s - loss: 0.2979 - acc: 0.7022 - val_loss: 0.2513 - val_acc: 0.7921\nEpoch 19/20\n - 465s - loss: 0.2836 - acc: 0.7111 - val_loss: 0.2599 - val_acc: 0.8016\nRestoring model weights from the end of the best epoch\nEpoch 00019: early stopping\n" ], [ "fig, (ax1, ax2) = plt.subplots(2, 1, sharex='col', figsize=(20, 6))\n\nax1.plot(cosine_lr_1st.learning_rates)\nax1.set_title('Warm up learning rates')\n\nax2.plot(cosine_lr_2nd.learning_rates)\nax2.set_title('Fine-tune learning rates')\n\nplt.xlabel('Steps')\nplt.ylabel('Learning rate')\nsns.despine()\nplt.show()", "_____no_output_____" ] ], [ [ "# Model loss graph ", "_____no_output_____" ] ], [ [ "fig, (ax1, ax2) = plt.subplots(2, 1, sharex='col', figsize=(20, 14))\n\nax1.plot(history['loss'], label='Train loss')\nax1.plot(history['val_loss'], label='Validation loss')\nax1.legend(loc='best')\nax1.set_title('Loss')\n\nax2.plot(history['acc'], label='Train accuracy')\nax2.plot(history['val_acc'], label='Validation accuracy')\nax2.legend(loc='best')\nax2.set_title('Accuracy')\n\nplt.xlabel('Epochs')\nsns.despine()\nplt.show()", "_____no_output_____" ], [ "# Create empty arays to keep the predictions and labels\ndf_preds = pd.DataFrame(columns=['label', 'pred', 'set'])\ntrain_generator.reset()\nvalid_generator.reset()\n\n# Add train predictions and labels\nfor i in range(STEP_SIZE_TRAIN + 1):\n im, lbl = next(train_generator)\n preds = model.predict(im, batch_size=train_generator.batch_size)\n for index in range(len(preds)):\n df_preds.loc[len(df_preds)] = [lbl[index], preds[index][0], 'train']\n\n# Add validation predictions and labels\nfor i in range(STEP_SIZE_VALID + 1):\n im, lbl = next(valid_generator)\n preds = model.predict(im, batch_size=valid_generator.batch_size)\n for index in range(len(preds)):\n df_preds.loc[len(df_preds)] = [lbl[index], preds[index][0], 'validation']\n\ndf_preds['label'] = df_preds['label'].astype('int')", "_____no_output_____" ], [ "def classify(x):\n if x < 0.5:\n return 0\n elif x < 1.5:\n return 1\n elif x < 2.5:\n return 2\n elif x < 3.5:\n return 3\n return 4\n\n# Classify predictions\ndf_preds['predictions'] = df_preds['pred'].apply(lambda x: classify(x))\n\ntrain_preds = df_preds[df_preds['set'] == 'train']\nvalidation_preds = df_preds[df_preds['set'] == 'validation']", "_____no_output_____" ] ], [ [ "# Model Evaluation", "_____no_output_____" ], [ "## Confusion Matrix\n\n### Original thresholds", "_____no_output_____" ] ], [ [ "labels = ['0 - No DR', '1 - Mild', '2 - Moderate', '3 - Severe', '4 - Proliferative DR']\ndef plot_confusion_matrix(train, validation, labels=labels):\n train_labels, train_preds = train\n validation_labels, validation_preds = validation\n fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', figsize=(24, 7))\n train_cnf_matrix = confusion_matrix(train_labels, train_preds)\n validation_cnf_matrix = confusion_matrix(validation_labels, validation_preds)\n\n train_cnf_matrix_norm = train_cnf_matrix.astype('float') / train_cnf_matrix.sum(axis=1)[:, np.newaxis]\n validation_cnf_matrix_norm = validation_cnf_matrix.astype('float') / validation_cnf_matrix.sum(axis=1)[:, np.newaxis]\n\n train_df_cm = pd.DataFrame(train_cnf_matrix_norm, index=labels, columns=labels)\n validation_df_cm = pd.DataFrame(validation_cnf_matrix_norm, index=labels, columns=labels)\n\n sns.heatmap(train_df_cm, annot=True, fmt='.2f', cmap=\"Blues\",ax=ax1).set_title('Train')\n sns.heatmap(validation_df_cm, annot=True, fmt='.2f', cmap=sns.cubehelix_palette(8),ax=ax2).set_title('Validation')\n plt.show()\n\nplot_confusion_matrix((train_preds['label'], train_preds['predictions']), (validation_preds['label'], validation_preds['predictions']))", "_____no_output_____" ] ], [ [ "## Quadratic Weighted Kappa", "_____no_output_____" ] ], [ [ "def evaluate_model(train, validation):\n train_labels, train_preds = train\n validation_labels, validation_preds = validation\n print(\"Train Cohen Kappa score: %.3f\" % cohen_kappa_score(train_preds, train_labels, weights='quadratic'))\n print(\"Validation Cohen Kappa score: %.3f\" % cohen_kappa_score(validation_preds, validation_labels, weights='quadratic'))\n print(\"Complete set Cohen Kappa score: %.3f\" % cohen_kappa_score(np.append(train_preds, validation_preds), np.append(train_labels, validation_labels), weights='quadratic'))\n \nevaluate_model((train_preds['label'], train_preds['predictions']), (validation_preds['label'], validation_preds['predictions']))", "Train Cohen Kappa score: 0.847\nValidation Cohen Kappa score: 0.910\nComplete set Cohen Kappa score: 0.854\n" ] ], [ [ "## Apply model to test set and output predictions", "_____no_output_____" ] ], [ [ "step_size = test_generator.n//test_generator.batch_size\ntest_generator.reset()\npreds = model.predict_generator(test_generator, steps=step_size)\npredictions = [classify(x) for x in preds]\n\nresults = pd.DataFrame({'id_code':test['id_code'], 'diagnosis':predictions})\nresults['id_code'] = results['id_code'].map(lambda x: str(x)[:-4])", "_____no_output_____" ], [ "# Cleaning created directories\nif os.path.exists(train_dest_path):\n shutil.rmtree(train_dest_path)\nif os.path.exists(validation_dest_path):\n shutil.rmtree(validation_dest_path)\nif os.path.exists(test_dest_path):\n shutil.rmtree(test_dest_path)", "_____no_output_____" ] ], [ [ "# Predictions class distribution", "_____no_output_____" ] ], [ [ "fig = plt.subplots(sharex='col', figsize=(24, 8.7))\nsns.countplot(x=\"diagnosis\", data=results, palette=\"GnBu_d\").set_title('Test')\nsns.despine()\nplt.show()", "_____no_output_____" ], [ "results.to_csv('submission.csv', index=False)\ndisplay(results.head())", "_____no_output_____" ] ], [ [ "## Save model", "_____no_output_____" ] ], [ [ "model.save_weights('../working/effNetB5_img224.h5')", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
ec522b05a33563eab860c423df1c416ec35b4394
26,983
ipynb
Jupyter Notebook
20-Chapter-20/Chapter_20.ipynb
DiegoMerino28/Practical-Data-Science-with-Python
b05cffac6fe46c2a3cc77b556af262b1a5b7f8a0
[ "MIT" ]
2
2022-01-11T09:49:13.000Z
2022-02-20T15:30:12.000Z
20-Chapter-20/Chapter_20.ipynb
Hardik1809-coder/Practical-Data-Science-with-Python
4eb557492974c7c3e587338102b5897b532564e6
[ "MIT" ]
1
2021-12-28T21:57:57.000Z
2021-12-28T21:57:57.000Z
20-Chapter-20/Chapter_20.ipynb
MathMachado/Practical-Data-Science-with-Python
4eb557492974c7c3e587338102b5897b532564e6
[ "MIT" ]
null
null
null
29.6191
121
0.301264
[ [ [ "import pandas as pd\n\ndf = pd.read_excel('data/HIV_results.xlsx')\ndf", "_____no_output_____" ], [ "df.drop('Name', axis=1, inplace=True)\ndf.loc[(df['Age'] >= 20) & (df['Age'] < 30), 'Age'] = 20\ndf.loc[(df['Age'] >= 30) & (df['Age'] < 40), 'Age'] = 30\ndf.loc[(df['Age'] >= 40) & (df['Age'] < 50), 'Age'] = 40\ndf['Age'] = df['Age'].apply(lambda x: str(x) + 's')\ndf['Zipcode'] = df['Zipcode'].apply(lambda x: str(x)[:3] + '**')", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df['equiv_class'] = [0, 1, 0, 2, 1, 2]", "_____no_output_____" ], [ "df.sort_values(by='equiv_class')", "_____no_output_____" ] ], [ [ "Another example of use pandas to do some generalization and measure k-anonymity. The data here is only 1-anonymous.", "_____no_output_____" ] ], [ [ "df = pd.read_excel('data/default of credit card clients.xls', index_col='ID', skiprows=1)", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df['AGE'].astype('str')", "_____no_output_____" ], [ "df['qi_tuple'] = df[['SEX', 'EDUCATION', 'MARRIAGE', 'AGE']].astype(str).agg('_'.join, axis=1)", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df['qi_tuple'].value_counts()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
ec5234db814a672aae74e59127e2f92d26a94ccf
47,805
ipynb
Jupyter Notebook
site/en/tutorials/estimators/linear.ipynb
kyleabeauchamp/docs
a5952bc17d89ed11a39e1124b362382f9064af65
[ "Apache-2.0" ]
2
2021-01-27T08:34:26.000Z
2021-04-06T00:07:55.000Z
site/en/tutorials/estimators/linear.ipynb
1272857430/docs
e785a902c34cf20fd47901dc07bac403d2df5c8e
[ "Apache-2.0" ]
1
2019-04-24T12:17:40.000Z
2019-04-24T12:17:40.000Z
site/en/tutorials/estimators/linear.ipynb
1272857430/docs
e785a902c34cf20fd47901dc07bac403d2df5c8e
[ "Apache-2.0" ]
2
2019-04-24T09:49:54.000Z
2019-04-24T11:37:47.000Z
34.073414
546
0.547119
[ [ [ "##### 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_____" ] ], [ [ "# Build a linear model with Estimators", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/estimators/linear\"><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/estimators/linear.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/estimators/linear.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n</table>", "_____no_output_____" ], [ "This tutorial uses the `tf.estimator` API in TensorFlow to solve a benchmark binary classification problem. Estimators are TensorFlow's most scalable and production-oriented model type. For more information see the [Estimator guide](https://www.tensorflow.org/guide/estimators).\n\n## Overview\n\nUsing census data which contains data a person's age, education, marital status, and occupation (the *features*), we will try to predict whether or not the person earns more than 50,000 dollars a year (the target *label*). We will train a *logistic regression* model that, given an individual's information, outputs a number between 0 and 1—this can be interpreted as the probability that the individual has an annual income of over 50,000 dollars.\n\nKey Point: As a modeler and developer, think about how this data is used and the potential benefits and harm a model's predictions can cause. A model like this could reinforce societal biases and disparities. Is each feature relevant to the problem you want to solve or will it introduce bias? For more information, read about [ML fairness](https://developers.google.com/machine-learning/fairness-overview/).\n\n## Setup\n\nImport TensorFlow, feature column support, and supporting modules:", "_____no_output_____" ] ], [ [ "from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\nimport tensorflow.feature_column as fc\n\nimport os\nimport sys\n\nimport matplotlib.pyplot as plt\nfrom IPython.display import clear_output", "_____no_output_____" ] ], [ [ "And let's enable [eager execution](https://www.tensorflow.org/guide/eager) to inspect this program as we run it:", "_____no_output_____" ] ], [ [ "tf.enable_eager_execution()", "_____no_output_____" ] ], [ [ "## Download the official implementation\n\nWe'll use the [wide and deep model](https://github.com/tensorflow/models/tree/master/official/wide_deep/) available in TensorFlow's [model repository](https://github.com/tensorflow/models/). Download the code, add the root directory to your Python path, and jump to the `wide_deep` directory:", "_____no_output_____" ] ], [ [ "! pip install requests\n! git clone --depth 1 https://github.com/tensorflow/models", "_____no_output_____" ] ], [ [ "Add the root directory of the repository to your Python path:", "_____no_output_____" ] ], [ [ "models_path = os.path.join(os.getcwd(), 'models')\n\nsys.path.append(models_path)", "_____no_output_____" ] ], [ [ "Download the dataset:", "_____no_output_____" ] ], [ [ "from official.wide_deep import census_dataset\nfrom official.wide_deep import census_main\n\ncensus_dataset.download(\"/tmp/census_data/\")", "_____no_output_____" ] ], [ [ "### Command line usage\n\nThe repo includes a complete program for experimenting with this type of model.\n\nTo execute the tutorial code from the command line first add the path to tensorflow/models to your `PYTHONPATH`.", "_____no_output_____" ] ], [ [ "#export PYTHONPATH=${PYTHONPATH}:\"$(pwd)/models\"\n#running from python you need to set the `os.environ` or the subprocess will not see the directory.\n\nif \"PYTHONPATH\" in os.environ:\n os.environ['PYTHONPATH'] += os.pathsep + models_path\nelse:\n os.environ['PYTHONPATH'] = models_path", "_____no_output_____" ] ], [ [ "Use `--help` to see what command line options are available:", "_____no_output_____" ] ], [ [ "!python -m official.wide_deep.census_main --help", "_____no_output_____" ] ], [ [ "Now run the model:\n", "_____no_output_____" ] ], [ [ "!python -m official.wide_deep.census_main --model_type=wide --train_epochs=2", "_____no_output_____" ] ], [ [ "## Read the U.S. Census data\n\nThis example uses the [U.S Census Income Dataset](https://archive.ics.uci.edu/ml/datasets/Census+Income) from 1994 and 1995. We have provided the [census_dataset.py](https://github.com/tensorflow/models/tree/master/official/wide_deep/census_dataset.py) script to download the data and perform a little cleanup.\n\nSince the task is a *binary classification problem*, we'll construct a label column named \"label\" whose value is 1 if the income is over 50K, and 0 otherwise. For reference, see the `input_fn` in [census_main.py](https://github.com/tensorflow/models/tree/master/official/wide_deep/census_main.py).\n\nLet's look at the data to see which columns we can use to predict the target label:", "_____no_output_____" ] ], [ [ "!ls /tmp/census_data/", "_____no_output_____" ], [ "train_file = \"/tmp/census_data/adult.data\"\ntest_file = \"/tmp/census_data/adult.test\"", "_____no_output_____" ] ], [ [ "[pandas](https://pandas.pydata.org/) provides some convenient utilities for data analysis. Here's a list of columns available in the Census Income dataset:", "_____no_output_____" ] ], [ [ "import pandas\n\ntrain_df = pandas.read_csv(train_file, header = None, names = census_dataset._CSV_COLUMNS)\ntest_df = pandas.read_csv(test_file, header = None, names = census_dataset._CSV_COLUMNS)\n\ntrain_df.head()", "_____no_output_____" ] ], [ [ "The columns are grouped into two types: *categorical* and *continuous* columns:\n\n* A column is called *categorical* if its value can only be one of the categories in a finite set. For example, the relationship status of a person (wife, husband, unmarried, etc.) or the education level (high school, college, etc.) are categorical columns.\n* A column is called *continuous* if its value can be any numerical value in a continuous range. For example, the capital gain of a person (e.g. $14,084) is a continuous column.\n\n## Converting Data into Tensors\n\nWhen building a `tf.estimator` model, the input data is specified by using an *input function* (or `input_fn`). This builder function returns a `tf.data.Dataset` of batches of `(features-dict, label)` pairs. It is not called until it is passed to `tf.estimator.Estimator` methods such as `train` and `evaluate`.\n\nThe input builder function returns the following pair:\n\n1. `features`: A dict from feature names to `Tensors` or `SparseTensors` containing batches of features.\n2. `labels`: A `Tensor` containing batches of labels.\n\nThe keys of the `features` are used to configure the model's input layer.\n\nNote: The input function is called while constructing the TensorFlow graph, *not* while running the graph. It is returning a representation of the input data as a sequence of TensorFlow graph operations.\n\nFor small problems like this, it's easy to make a `tf.data.Dataset` by slicing the `pandas.DataFrame`:", "_____no_output_____" ] ], [ [ "def easy_input_function(df, label_key, num_epochs, shuffle, batch_size):\n label = df[label_key]\n ds = tf.data.Dataset.from_tensor_slices((dict(df),label))\n\n if shuffle:\n ds = ds.shuffle(10000)\n\n ds = ds.batch(batch_size).repeat(num_epochs)\n\n return ds", "_____no_output_____" ] ], [ [ "Since we have eager execution enabled, it's easy to inspect the resulting dataset:", "_____no_output_____" ] ], [ [ "ds = easy_input_function(train_df, label_key='income_bracket', num_epochs=5, shuffle=True, batch_size=10)\n\nfor feature_batch, label_batch in ds.take(1):\n print('Some feature keys:', list(feature_batch.keys())[:5])\n print()\n print('A batch of Ages :', feature_batch['age'])\n print()\n print('A batch of Labels:', label_batch )", "_____no_output_____" ] ], [ [ "But this approach has severly-limited scalability. Larger datasets should be streamed from disk. The `census_dataset.input_fn` provides an example of how to do this using `tf.decode_csv` and `tf.data.TextLineDataset`:\n\n<!-- TODO(markdaoust): This `input_fn` should use `tf.contrib.data.make_csv_dataset` -->", "_____no_output_____" ] ], [ [ "import inspect\nprint(inspect.getsource(census_dataset.input_fn))", "_____no_output_____" ] ], [ [ "This `input_fn` returns equivalent output:", "_____no_output_____" ] ], [ [ "ds = census_dataset.input_fn(train_file, num_epochs=5, shuffle=True, batch_size=10)\n\nfor feature_batch, label_batch in ds.take(1):\n print('Feature keys:', list(feature_batch.keys())[:5])\n print()\n print('Age batch :', feature_batch['age'])\n print()\n print('Label batch :', label_batch )", "_____no_output_____" ] ], [ [ "Because `Estimators` expect an `input_fn` that takes no arguments, we typically wrap configurable input function into an obejct with the expected signature. For this notebook configure the `train_inpf` to iterate over the data twice:", "_____no_output_____" ] ], [ [ "import functools\n\ntrain_inpf = functools.partial(census_dataset.input_fn, train_file, num_epochs=2, shuffle=True, batch_size=64)\ntest_inpf = functools.partial(census_dataset.input_fn, test_file, num_epochs=1, shuffle=False, batch_size=64)", "_____no_output_____" ] ], [ [ "## Selecting and Engineering Features for the Model\n\nEstimators use a system called [feature columns](https://www.tensorflow.org/guide/feature_columns) to describe how the model should interpret each of the raw input features. An Estimator expects a vector of numeric inputs, and feature columns describe how the model should convert each feature.\n\nSelecting and crafting the right set of feature columns is key to learning an effective model. A *feature column* can be either one of the raw inputs in the original features `dict` (a *base feature column*), or any new columns created using transformations defined over one or multiple base columns (a *derived feature columns*).\n\nA feature column is an abstract concept of any raw or derived variable that can be used to predict the target label.", "_____no_output_____" ], [ "### Base Feature Columns", "_____no_output_____" ], [ "#### Numeric columns\n\nThe simplest `feature_column` is `numeric_column`. This indicates that a feature is a numeric value that should be input to the model directly. For example:", "_____no_output_____" ] ], [ [ "age = fc.numeric_column('age')", "_____no_output_____" ] ], [ [ "The model will use the `feature_column` definitions to build the model input. You can inspect the resulting output using the `input_layer` function:", "_____no_output_____" ] ], [ [ "fc.input_layer(feature_batch, [age]).numpy()", "_____no_output_____" ] ], [ [ "The following will train and evaluate a model using only the `age` feature:", "_____no_output_____" ] ], [ [ "classifier = tf.estimator.LinearClassifier(feature_columns=[age])\nclassifier.train(train_inpf)\nresult = classifier.evaluate(test_inpf)\n\nclear_output() # used for display in notebook\nprint(result)", "_____no_output_____" ] ], [ [ "Similarly, we can define a `NumericColumn` for each continuous feature column\nthat we want to use in the model:", "_____no_output_____" ] ], [ [ "education_num = tf.feature_column.numeric_column('education_num')\ncapital_gain = tf.feature_column.numeric_column('capital_gain')\ncapital_loss = tf.feature_column.numeric_column('capital_loss')\nhours_per_week = tf.feature_column.numeric_column('hours_per_week')\n\nmy_numeric_columns = [age,education_num, capital_gain, capital_loss, hours_per_week]\n\nfc.input_layer(feature_batch, my_numeric_columns).numpy()", "_____no_output_____" ] ], [ [ "You could retrain a model on these features by changing the `feature_columns` argument to the constructor:", "_____no_output_____" ] ], [ [ "classifier = tf.estimator.LinearClassifier(feature_columns=my_numeric_columns)\nclassifier.train(train_inpf)\n\nresult = classifier.evaluate(test_inpf)\n\nclear_output()\n\nfor key,value in sorted(result.items()):\n print('%s: %s' % (key, value))", "_____no_output_____" ] ], [ [ "#### Categorical columns\n\nTo define a feature column for a categorical feature, create a `CategoricalColumn` using one of the `tf.feature_column.categorical_column*` functions.\n\nIf you know the set of all possible feature values of a column—and there are only a few of them—use `categorical_column_with_vocabulary_list`. Each key in the list is assigned an auto-incremented ID starting from 0. For example, for the `relationship` column we can assign the feature string `Husband` to an integer ID of 0 and \"Not-in-family\" to 1, etc.", "_____no_output_____" ] ], [ [ "relationship = fc.categorical_column_with_vocabulary_list(\n 'relationship',\n ['Husband', 'Not-in-family', 'Wife', 'Own-child', 'Unmarried', 'Other-relative'])", "_____no_output_____" ] ], [ [ "This creates a sparse one-hot vector from the raw input feature.\n\nThe `input_layer` function we're using is designed for DNN models and expects dense inputs. To demonstrate the categorical column we must wrap it in a `tf.feature_column.indicator_column` to create the dense one-hot output (Linear `Estimators` can often skip this dense-step).\n\nNote: the other sparse-to-dense option is `tf.feature_column.embedding_column`.\n\nRun the input layer, configured with both the `age` and `relationship` columns:", "_____no_output_____" ] ], [ [ "fc.input_layer(feature_batch, [age, fc.indicator_column(relationship)])", "_____no_output_____" ] ], [ [ "If we don't know the set of possible values in advance, use the `categorical_column_with_hash_bucket` instead:", "_____no_output_____" ] ], [ [ "occupation = tf.feature_column.categorical_column_with_hash_bucket(\n 'occupation', hash_bucket_size=1000)", "_____no_output_____" ] ], [ [ "Here, each possible value in the feature column `occupation` is hashed to an integer ID as we encounter them in training. The example batch has a few different occupations:", "_____no_output_____" ] ], [ [ "for item in feature_batch['occupation'].numpy():\n print(item.decode())", "_____no_output_____" ] ], [ [ "If we run `input_layer` with the hashed column, we see that the output shape is `(batch_size, hash_bucket_size)`:", "_____no_output_____" ] ], [ [ "occupation_result = fc.input_layer(feature_batch, [fc.indicator_column(occupation)])\n\noccupation_result.numpy().shape", "_____no_output_____" ] ], [ [ "It's easier to see the actual results if we take the `tf.argmax` over the `hash_bucket_size` dimension. Notice how any duplicate occupations are mapped to the same pseudo-random index:", "_____no_output_____" ] ], [ [ "tf.argmax(occupation_result, axis=1).numpy()", "_____no_output_____" ] ], [ [ "Note: Hash collisions are unavoidable, but often have minimal impact on model quiality. The effect may be noticable if the hash buckets are being used to compress the input space. See [this notebook](https://colab.research.google.com/github/tensorflow/models/blob/master/samples/outreach/blogs/housing_prices.ipynb) for a more visual example of the effect of these hash collisions.\n\nNo matter how we choose to define a `SparseColumn`, each feature string is mapped into an integer ID by looking up a fixed mapping or by hashing. Under the hood, the `LinearModel` class is responsible for managing the mapping and creating `tf.Variable` to store the model parameters (model *weights*) for each feature ID. The model parameters are learned through the model training process described later.\n\nLet's do the similar trick to define the other categorical features:", "_____no_output_____" ] ], [ [ "education = tf.feature_column.categorical_column_with_vocabulary_list(\n 'education', [\n 'Bachelors', 'HS-grad', '11th', 'Masters', '9th', 'Some-college',\n 'Assoc-acdm', 'Assoc-voc', '7th-8th', 'Doctorate', 'Prof-school',\n '5th-6th', '10th', '1st-4th', 'Preschool', '12th'])\n\nmarital_status = tf.feature_column.categorical_column_with_vocabulary_list(\n 'marital_status', [\n 'Married-civ-spouse', 'Divorced', 'Married-spouse-absent',\n 'Never-married', 'Separated', 'Married-AF-spouse', 'Widowed'])\n\nworkclass = tf.feature_column.categorical_column_with_vocabulary_list(\n 'workclass', [\n 'Self-emp-not-inc', 'Private', 'State-gov', 'Federal-gov',\n 'Local-gov', '?', 'Self-emp-inc', 'Without-pay', 'Never-worked'])\n\n\nmy_categorical_columns = [relationship, occupation, education, marital_status, workclass]", "_____no_output_____" ] ], [ [ "It's easy to use both sets of columns to configure a model that uses all these features:", "_____no_output_____" ] ], [ [ "classifier = tf.estimator.LinearClassifier(feature_columns=my_numeric_columns+my_categorical_columns)\nclassifier.train(train_inpf)\nresult = classifier.evaluate(test_inpf)\n\nclear_output()\n\nfor key,value in sorted(result.items()):\n print('%s: %s' % (key, value))", "_____no_output_____" ] ], [ [ "### Derived feature columns", "_____no_output_____" ], [ "#### Make Continuous Features Categorical through Bucketization\n\nSometimes the relationship between a continuous feature and the label is not linear. For example, *age* and *income*—a person's income may grow in the early stage of their career, then the growth may slow at some point, and finally, the income decreases after retirement. In this scenario, using the raw `age` as a real-valued feature column might not be a good choice because the model can only learn one of the three cases:\n\n1. Income always increases at some rate as age grows (positive correlation),\n2. Income always decreases at some rate as age grows (negative correlation), or\n3. Income stays the same no matter at what age (no correlation).\n\nIf we want to learn the fine-grained correlation between income and each age group separately, we can leverage *bucketization*. Bucketization is a process of dividing the entire range of a continuous feature into a set of consecutive buckets, and then converting the original numerical feature into a bucket ID (as a categorical feature) depending on which bucket that value falls into. So, we can define a `bucketized_column` over `age` as:", "_____no_output_____" ] ], [ [ "age_buckets = tf.feature_column.bucketized_column(\n age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65])", "_____no_output_____" ] ], [ [ "`boundaries` is a list of bucket boundaries. In this case, there are 10 boundaries, resulting in 11 age group buckets (from age 17 and below, 18-24, 25-29, ..., to 65 and over).\n\nWith bucketing, the model sees each bucket as a one-hot feature:", "_____no_output_____" ] ], [ [ "fc.input_layer(feature_batch, [age, age_buckets]).numpy()", "_____no_output_____" ] ], [ [ "#### Learn complex relationships with crossed column\n\nUsing each base feature column separately may not be enough to explain the data. For example, the correlation between education and the label (earning > 50,000 dollars) may be different for different occupations. Therefore, if we only learn a single model weight for `education=\"Bachelors\"` and `education=\"Masters\"`, we won't capture every education-occupation combination (e.g. distinguishing between `education=\"Bachelors\"` AND `occupation=\"Exec-managerial\"` AND `education=\"Bachelors\" AND occupation=\"Craft-repair\"`).\n\nTo learn the differences between different feature combinations, we can add *crossed feature columns* to the model:", "_____no_output_____" ] ], [ [ "education_x_occupation = tf.feature_column.crossed_column(\n ['education', 'occupation'], hash_bucket_size=1000)", "_____no_output_____" ] ], [ [ "We can also create a `crossed_column` over more than two columns. Each constituent column can be either a base feature column that is categorical (`SparseColumn`), a bucketized real-valued feature column, or even another `CrossColumn`. For example:", "_____no_output_____" ] ], [ [ "age_buckets_x_education_x_occupation = tf.feature_column.crossed_column(\n [age_buckets, 'education', 'occupation'], hash_bucket_size=1000)", "_____no_output_____" ] ], [ [ "These crossed columns always use hash buckets to avoid the exponential explosion in the number of categories, and put the control over number of model weights in the hands of the user.\n\nFor a visual example the effect of hash-buckets with crossed columns see [this notebook](https://colab.research.google.com/github/tensorflow/models/blob/master/samples/outreach/blogs/housing_prices.ipynb)\n", "_____no_output_____" ], [ "## Define the logistic regression model\n\nAfter processing the input data and defining all the feature columns, we can put them together and build a *logistic regression* model. The previous section showed several types of base and derived feature columns, including:\n\n* `CategoricalColumn`\n* `NumericColumn`\n* `BucketizedColumn`\n* `CrossedColumn`\n\nAll of these are subclasses of the abstract `FeatureColumn` class and can be added to the `feature_columns` field of a model:", "_____no_output_____" ] ], [ [ "import tempfile\n\nbase_columns = [\n education, marital_status, relationship, workclass, occupation,\n age_buckets,\n]\n\ncrossed_columns = [\n tf.feature_column.crossed_column(\n ['education', 'occupation'], hash_bucket_size=1000),\n tf.feature_column.crossed_column(\n [age_buckets, 'education', 'occupation'], hash_bucket_size=1000),\n]\n\nmodel = tf.estimator.LinearClassifier(\n model_dir=tempfile.mkdtemp(),\n feature_columns=base_columns + crossed_columns,\n optimizer=tf.train.FtrlOptimizer(learning_rate=0.1))", "_____no_output_____" ] ], [ [ "The model automatically learns a bias term, which controls the prediction made without observing any features. The learned model files are stored in `model_dir`.\n\n## Train and evaluate the model\n\nAfter adding all the features to the model, let's train the model. Training a model is just a single command using the `tf.estimator` API:", "_____no_output_____" ] ], [ [ "train_inpf = functools.partial(census_dataset.input_fn, train_file,\n num_epochs=40, shuffle=True, batch_size=64)\n\nmodel.train(train_inpf)\n\nclear_output() # used for notebook display", "_____no_output_____" ] ], [ [ "After the model is trained, evaluate the accuracy of the model by predicting the labels of the holdout data:", "_____no_output_____" ] ], [ [ "results = model.evaluate(test_inpf)\n\nclear_output()\n\nfor key,value in sorted(results.items()):\n print('%s: %0.2f' % (key, value))", "_____no_output_____" ] ], [ [ "The first line of the output should display something like: `accuracy: 0.84`, which means the accuracy is 84%. You can try using more features and transformations to see if you can do better!\n\nAfter the model is evaluated, we can use it to predict whether an individual has an annual income of over 50,000 dollars given an individual's information input.\n\nLet's look in more detail how the model performed:", "_____no_output_____" ] ], [ [ "import numpy as np\n\npredict_df = test_df[:20].copy()\n\npred_iter = model.predict(\n lambda:easy_input_function(predict_df, label_key='income_bracket',\n num_epochs=1, shuffle=False, batch_size=10))\n\nclasses = np.array(['<=50K', '>50K'])\npred_class_id = []\n\nfor pred_dict in pred_iter:\n pred_class_id.append(pred_dict['class_ids'])\n\npredict_df['predicted_class'] = classes[np.array(pred_class_id)]\npredict_df['correct'] = predict_df['predicted_class'] == predict_df['income_bracket']\n\nclear_output()\n\npredict_df[['income_bracket','predicted_class', 'correct']]", "_____no_output_____" ] ], [ [ "For a working end-to-end example, download our [example code](https://github.com/tensorflow/models/tree/master/official/wide_deep/census_main.py) and set the `model_type` flag to `wide`.", "_____no_output_____" ], [ "## Adding Regularization to Prevent Overfitting\n\nRegularization is a technique used to avoid overfitting. Overfitting happens when a model performs well on the data it is trained on, but worse on test data that the model has not seen before. Overfitting can occur when a model is excessively complex, such as having too many parameters relative to the number of observed training data. Regularization allows you to control the model's complexity and make the model more generalizable to unseen data.\n\nYou can add L1 and L2 regularizations to the model with the following code:", "_____no_output_____" ] ], [ [ "model_l1 = tf.estimator.LinearClassifier(\n feature_columns=base_columns + crossed_columns,\n optimizer=tf.train.FtrlOptimizer(\n learning_rate=0.1,\n l1_regularization_strength=10.0,\n l2_regularization_strength=0.0))\n\nmodel_l1.train(train_inpf)\n\nresults = model_l1.evaluate(test_inpf)\nclear_output()\nfor key in sorted(results):\n print('%s: %0.2f' % (key, results[key]))", "_____no_output_____" ], [ "model_l2 = tf.estimator.LinearClassifier(\n feature_columns=base_columns + crossed_columns,\n optimizer=tf.train.FtrlOptimizer(\n learning_rate=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=10.0))\n\nmodel_l2.train(train_inpf)\n\nresults = model_l2.evaluate(test_inpf)\nclear_output()\nfor key in sorted(results):\n print('%s: %0.2f' % (key, results[key]))", "_____no_output_____" ] ], [ [ "These regularized models don't perform much better than the base model. Let's look at the model's weight distributions to better see the effect of the regularization:", "_____no_output_____" ] ], [ [ "def get_flat_weights(model):\n weight_names = [\n name for name in model.get_variable_names()\n if \"linear_model\" in name and \"Ftrl\" not in name]\n\n weight_values = [model.get_variable_value(name) for name in weight_names]\n\n weights_flat = np.concatenate([item.flatten() for item in weight_values], axis=0)\n\n return weights_flat\n\nweights_flat = get_flat_weights(model)\nweights_flat_l1 = get_flat_weights(model_l1)\nweights_flat_l2 = get_flat_weights(model_l2)", "_____no_output_____" ] ], [ [ "The models have many zero-valued weights caused by unused hash bins (there are many more hash bins than categories in some columns). We can mask these weights when viewing the weight distributions:", "_____no_output_____" ] ], [ [ "weight_mask = weights_flat != 0\n\nweights_base = weights_flat[weight_mask]\nweights_l1 = weights_flat_l1[weight_mask]\nweights_l2 = weights_flat_l2[weight_mask]", "_____no_output_____" ] ], [ [ "Now plot the distributions:", "_____no_output_____" ] ], [ [ "plt.figure()\n_ = plt.hist(weights_base, bins=np.linspace(-3,3,30))\nplt.title('Base Model')\nplt.ylim([0,500])\n\nplt.figure()\n_ = plt.hist(weights_l1, bins=np.linspace(-3,3,30))\nplt.title('L1 - Regularization')\nplt.ylim([0,500])\n\nplt.figure()\n_ = plt.hist(weights_l2, bins=np.linspace(-3,3,30))\nplt.title('L2 - Regularization')\n_=plt.ylim([0,500])\n\n", "_____no_output_____" ] ], [ [ "Both types of regularization squeeze the distribution of weights towards zero. L2 regularization has a greater effect in the tails of the distribution eliminating extreme weights. L1 regularization produces more exactly-zero values, in this case it sets ~200 to zero.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "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", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec52386b0306738efb64ba34babee4c5ccb49fb0
16,897
ipynb
Jupyter Notebook
nbs/21c-preprocessing-categorization.ipynb
gnoparus/bualabs
8a0fe910f2acf349a720137e1858edfcd5e92de7
[ "MIT" ]
7
2019-12-12T22:59:28.000Z
2022-03-25T09:49:36.000Z
nbs/21c-preprocessing-categorization.ipynb
gnoparus/bualabs
8a0fe910f2acf349a720137e1858edfcd5e92de7
[ "MIT" ]
1
2020-06-24T04:40:13.000Z
2020-06-24T04:40:13.000Z
nbs/21c-preprocessing-categorization.ipynb
gnoparus/bualabs
8a0fe910f2acf349a720137e1858edfcd5e92de7
[ "MIT" ]
29
2020-01-17T19:33:25.000Z
2022-03-22T04:52:32.000Z
31.117864
126
0.29236
[ [ [ "# 0. Magic", "_____no_output_____" ] ], [ [ "%reload_ext autoreload\n%autoreload 2\n%matplotlib inline", "_____no_output_____" ] ], [ [ "# 1. Import", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "# 2. Data", "_____no_output_____" ], [ "เราจะสมมติข้อมูล ผู้บรรยายงานสัมมนา ขึ้นมา สังเกตว่ามีค่า Null / None ด้วย", "_____no_output_____" ] ], [ [ "df = pd.DataFrame({'Name': [\"Mister A\", \"Mister B\", \"Mister C\", \"Mister D\", \"Mister E\", \"Mister F\"], \n 'Age': [22, 33, 30, 31, 42, 51], \n 'Degree': [\"Bachelor\", \"Master\", \"Master\", \"Bachelor\", \"Doctor\", None], \n 'Shirt': [\"Red\", \"Blue\", \"Green\", \"Blue\", None, \"Blue\"], \n })\ndf", "_____no_output_____" ] ], [ [ "# 3. Preprocessing", "_____no_output_____" ], [ "## 3.1 One-Hot Encoding", "_____no_output_____" ], [ "เราจะสร้าง Dummy Column ใหม่ ขึ้นมาจาก ค่าต่าง ๆ ของ Shirt รวมถึง None/NA/Null", "_____no_output_____" ] ], [ [ "df = pd.get_dummies(df, columns=['Shirt'], dummy_na=True)\ndf\n", "_____no_output_____" ] ], [ [ "## 3.2 Map to Int", "_____no_output_____" ], [ "เราจะ Map ค่าต่าง ๆ ของ Degree เป็นตัวเลขที่เรากำหนด", "_____no_output_____" ] ], [ [ "df[\"Degree\"] = df[\"Degree\"].map({'Bachelor': 0, 'Master': 1, \"Doctor\": 2})\ndf", "_____no_output_____" ] ], [ [ "# 4. สรุป", "_____no_output_____" ], [ "1. เราจะเลือกวิธี Categorize ข้อมูลอย่างไร ขึ้นกับความหมายของ Feature นั้น ๆ \n1. การมีความรู้ความเข้าใจในข้อมูล ทำให้เราเลือกวิธี Preprocessing ได้ดีขึ้น\n1. โค้ดตัวอย่างใช้ Pandas DataFrame เป็นเครื่องมือจัดการข้อมูล แต่สำหรับภาษาอื่น ๆ ก็ใช้หลักการเดียวกัน", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
ec52386ccce8e3e689725680d9be84a0c5c1ecc0
16,782
ipynb
Jupyter Notebook
tutorials/W1D2_ModelingPractice/W1D2_Tutorial1.ipynb
vasudev-sharma/course-content
46fb9be49da52acb5df252dda43f11b6d1fe827f
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
tutorials/W1D2_ModelingPractice/W1D2_Tutorial1.ipynb
vasudev-sharma/course-content
46fb9be49da52acb5df252dda43f11b6d1fe827f
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
tutorials/W1D2_ModelingPractice/W1D2_Tutorial1.ipynb
vasudev-sharma/course-content
46fb9be49da52acb5df252dda43f11b6d1fe827f
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
43.931937
424
0.649029
[ [ [ "<a href=\"https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W1D2_ModelingPractice/W1D2_Tutorial1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Tutorial: Framing the Question\n**Week 1, Day 2: Modeling Practice**\n\n**By Neuromatch Academy**\n\n__Content creators:__ Marius 't Hart, Megan Peters, Paul Schrater, Gunnar Blohm", "_____no_output_____" ], [ "---\n# Tutorial objectives\nYesterday you gained some understanding of what models can buy us in neuroscience. But how do you build a model? Today, we will try to clarify the process of computational modeling, by thinking through the logic of modeling based on your project ideas.\n\nWe assume that you have a general idea of a project in mind, i.e. a preliminary question, and/or phenomenon you would like to understand. You should have started developing a project idea yesterday with [this brainstorming demo](https://youtu.be/H6rSlZzlrgQ). Maybe you have a goal in mind. We will now work through the 4 first steps of modeling ([Blohm et al., 2019](https://doi.org/10.1523/ENEURO.0352-19.2019)): \n\n**Framing the question**\n\n1. finding a phenomenon and a question to ask about it\n2. understanding the state of the art\n3. determining the basic ingredients\n4. formulating specific, mathematically defined hypotheses\n\nThe remaining steps 5-10 will be covered in a second notebook that you can consult throughout the modeling process when you work on your projects.\n\n**Importantly**, we will guide you through Steps 1-4 today. After you do more work on projects, you likely have to revite some or all of these steps *before* you should move on the the remaining steps of modeling. \n\n**Note**: there will be no coding today. It's important that you think through the different steps of this how-to-model tutorial to maximize your chance of succeeding in your group projects.\n\n**Think! Sections**: All activities you should perform are labeled with **Think!**. These are discussion based exercises and can be found in the Table of Content on the left side of the notebook. Make sure you complete all within a section before moving on!\n\nEnjoy!\n", "_____no_output_____" ], [ "----\n#Step 1: Finding a phenomenon and a question to ask about it\n", "_____no_output_____" ] ], [ [ "#@title Video 1: Asking a question\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id=\"Prf_Tc9UNp0\", width=854, height=480, fs=1)\nprint(\"Video available at https://youtu.be/\" + video.id)\nvideo", "_____no_output_____" ] ], [ [ "## Think! 1: Asking your own question\nYou should already have a project idea from your brainstorming yesterday. **Write down the phenomenon, question and goal(s) if you have them.** \n\nAs a reminder, here is what you should discuss and write down:\n\n* What exact aspect of data needs to be modelled?\n * Answer this question clearly and precisely!\nOtherwise you will get lost (almost guaranteed)\n * Write everything down!\n * Also identify aspects of data that you do not want to address (yet)\n* Define the model evaluation method!\n * How will you know your model is good?\n * E.g. comparison to specific data (quantitative method of comparison?)\n* Think of an experiment that could test your model\n * You essentially want your model to interface with this experiment, i.e. you want to simulate this experiment\n\nYou can find interesting questions by looking for phenomena that differ from your expectations. In *what* way does it differ? *How* could that be explained (starting to think about mechanistic questions and structural hypotheses)? *Why* could it be the way it is? What experiment could you design to investigate this phenomenon? What kind of data would you need?\n\n>### Avoid these common pitfalls\n* Question is too general\n * Remember: science advances one small step at the time. Get the small step right…\n* Precise aspect of phenomenon you want to model is unclear\n * You fail to ask a meaningful question\n* You have already chosen a toolkit\n * This will prevent you from thinking deeply about the best way to answer your scientific question\n* You don’t have a clear goal\n * What do you want to get out the model?\n* You don’t have a potential experiment in mind\n * This will help concretize your objectives and think through the logic behind your goal\n\n**This should take no more than 30 minutes.**", "_____no_output_____" ], [ "----\n#Step 2: Understanding the state of the art\n", "_____no_output_____" ], [ "Here you will do a literature review (**to be done AFTER this tutorial!**). For the projects, do not spend too much time on this. A thorough literature review should take weeks or months depending on your prior knowledge of the field...\n\nThe important thing for your project here is not to exhaustively survey the literatire but rather to learn the process of modeling. 1-2 days of digging into the literature should be enough!\n\n**Here is what you should get out of it**:\n* Survey the literature\n * What’s known?\n * What has already been done?\n * Previous models as a starting point?\n * What hypotheses have been emitted in the field?\n * Are there any alternative / complementary models?\n* What skill sets are required?\n * Do I need learn something before I can start?\n * Ensures that no important aspect is missed\n* Provides specific data sets / alternative models for comparison\n\n**Do this AFTER the tutorial**\n", "_____no_output_____" ], [ "----\n#Step 3: Determining the basic ingredients\n", "_____no_output_____" ] ], [ [ "#@title Video 2: Determining basic ingredients\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id=\"hfntEL8TVvY\", width=854, height=480, fs=1)\nprint(\"Video available at https://youtu.be/\" + video.id)\nvideo", "_____no_output_____" ] ], [ [ "## Think! 3: Determine your basic ingredients.\n\nDetermine the basic ingredients. This will allow you to think deeper about what your model will need. It's a crucial step before you can formulate hypotheses because you first need to understand what the model will need to contain. There are 2 aspects you want to think about:\n\n1. What parameters / variables are needed in the model?\n * Constants?\n * Do they change over space, time, conditions…?\n * What details can be omitted?\n * Constraints, initial conditions?\n * Model inputs / outputs?\n2. Variables needed to describe the process to be modelled?\n * Brainstorming!\n * What can be observed / measured? latent variables? \n * Where do these variables come from?\n * Do any abstract concepts need to be instantiated as variables?\n * E.g. value, utility, uncertainty, cost, salience, goals, strategy, plant, dynamics\n * Instantiate them so that they relate to potential measurements! \n\nThis is a step where your prior knowledge and intuition is tested. You want to end up with an inventory of *specific* concepts and/or interactions that need to be instantiated. \n\n>### Make sure to avoid the following pitfalls\n* I’m experienced, I don’t need to think about ingredients anymore\n * Or so you think…\n* I can’t think of any ingredients\n * Think about the potential experiment. What are your stimuli? What parameters? What would you control? What do you measure?\n* I have all inputs and outputs\n * Good! But what will link them? Thinking about that will start shaping your model and hypotheses\n* I can’t think of any links (= mechanisms)\n * You will acquire a library of potential mechanisms as you keep modeling and learning\n * But the literature will often give you hints through hypotheses\n * If you still can't think of links, then maybe you're missing ingredients?\n\nThe hardest part is Step 1. Once that is properly set up, all other should be easier. **BUT**: often you think that Step 1 is done only to figure out in later steps (anywhere really) that you were not as clear on your question and goal than you thought. Revisiting Step 1 is frequent necessity. Don't feel bad about it. You can revisit Step 1 later; for now, let's move on to the nest step.\n\n**This should take approximately 30 min.**", "_____no_output_____" ], [ "----\n#Step 4: Formulating specific, mathematically defined hypotheses\n\n", "_____no_output_____" ] ], [ [ "#@title Video 3: Formulating a hypothesis\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id=\"Vc3g1XajLlc\", width=854, height=480, fs=1)\nprint(\"Video available at https://youtu.be/\" + video.id)\nvideo", "_____no_output_____" ] ], [ [ "## Think! 4: Formulating your hypothesis\n\nOnce you have your question and goal lines up, you have done a literature review (let's assume for now) and you have thought about ingredients needed for your model, you're now ready to start thinking about *specific* hypotheses.\n\nFormulating hypotheses really consists of two consecutive steps:\n1. You think about the hypotheses in words by relating ingredients identified in Step 3\n * What is the model mechanism expected to do? \n * How are different parameters expected to influence model results?\n\n2. You then express these hypotheses in mathematical language by giving the ingredients identified in Step 3 specific variable names. \n * Be explicit, e.g. y(t)=f(x(t),k) but z(t) doesn’t influence y\n\n\nThere are also \"structural hypotheses\" that make assumptions on what model components you hypothesize will be crucial to capture the phenomenon at hand. \n\n**Important**: Formulating the hypotheses is the last step before starting to model. This step determines the model approach and ingredients. It provides a more detailed description of the question / goal from Step 1. The more precise the hypotheses, the easier the model will be to justify. \n\n>### To succeed here, avoid the following pitfalls\n* I don’t need hypotheses, I will just play around with the model\n * Hypotheses help determine and specify goals. You can (and should) still play…\n* My hypotheses don’t match my question (or vice versa)\n * This is a normal part of the process!\n * You need to loop back to Step 1 and revisit your question / phenomenon / goals\n* I can’t write down a math hypothesis\n * Often that means you lack ingredients and/or clarity on the hypothesis\n * OR: you have a “structural” hypothesis, i.e. you expect a certain model component to be crucial in explaining the phenomenon / answering the question\n\n**This step should take about 30 min**.\n", "_____no_output_____" ], [ "\n\n\n\n**We now have everything we need to actually start modelling!**\n\n", "_____no_output_____" ] ], [ [ "#@title Video 4: Next step!\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id=\"bDqwjCYhyAg\", width=854, height=480, fs=1)\nprint(\"Video available at https://youtu.be/\" + video.id)\nvideo", "_____no_output_____" ] ], [ [ "----\n#Summary\n\nIn this tutorial, we worked through some steps of the process of modeling. \n\n- We defined a phenomenon and formulated a question (step 1)\n- We collected information the state-of-the-art about the topic (step 2)\n- We determined the basic ingredients (step 3), and used these to formulate a specific mathematically defined hypothesis (step 4)\n\nYou are now in a position that you could start modeling without getting lost. But remember: you might have to work through steps 1-4 again after doing a literature review and/or if there were other pitfalls you identified along the way (which is totally normal).\n\n[In the next tutorial](https://colab.research.google.com/drive/10689_o9Aea0PImoVhZ26IVxfK9sRHRuM?usp=sharing) we will continue with the steps 5-10 to guide you through the implementation and completion stages of the projects. ", "_____no_output_____" ], [ "----\n#Reading\nBlohm G, Kording KP, Schrater PR (2020). _A How-to-Model Guide for Neuroscience_. eNeuro, 7(1) ENEURO.0352-19.2019. https://doi.org/10.1523/ENEURO.0352-19.2019 \n\nKording KP, Blohm G, Schrater P, Kay K (2020). _Appreciating the variety of goals in computational neuroscience_. Neurons, Behavior, Data Analysis, and Theory 3(6). https://nbdt.scholasticahq.com/article/16723-appreciating-the-variety-of-goals-in-computational-neuroscience\n\nSchrater PR, Peters MK, Kording KP, Blohm G (2019). _Modeling in Neuroscience as a Decision Process_. OSF pre-print. https://osf.io/w56vt/", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec5243b16bde81d780334f3af41ef4cee02a04bf
155,052
ipynb
Jupyter Notebook
Tensorflow in Practice specialization/Course 4 - Sequences, Time series, Prediction/week 3 - RNN for time series/Lesson_2_LSTM.ipynb
veb-101/Tensorflow-Specialization
adafa8ba0f9cee5989943568938f189c6a5793db
[ "Unlicense" ]
5
2020-06-08T11:25:07.000Z
2021-04-21T09:47:13.000Z
Tensorflow in Practice specialization/Course 4 - Sequences, Time series, Prediction/week 3 - RNN for time series/Lesson_2_LSTM.ipynb
rahul263-stack/Tensorflow-Specialization
adafa8ba0f9cee5989943568938f189c6a5793db
[ "Unlicense" ]
null
null
null
Tensorflow in Practice specialization/Course 4 - Sequences, Time series, Prediction/week 3 - RNN for time series/Lesson_2_LSTM.ipynb
rahul263-stack/Tensorflow-Specialization
adafa8ba0f9cee5989943568938f189c6a5793db
[ "Unlicense" ]
4
2020-04-27T02:58:44.000Z
2022-03-19T17:34:30.000Z
219.931915
69,046
0.848773
[ [ [ "# links\n\n1. [How to Prepare Univariate Time Series Data for Long Short-Term Memory Networks](https://machinelearningmastery.com/reshape-input-data-long-short-term-memory-networks-keras/)\n2. [https://github.com/MohammadFneish7/Keras_LSTM_Diagram](Keras_LSTM_Diagram)\n3. [How to Develop LSTM Models for Time Series Forecasting](https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/)", "_____no_output_____" ] ], [ [ "# %tensorflow_version 2.xs", "TensorFlow 2.x selected.\n" ], [ "import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nprint(tf.__version__)", "_____no_output_____" ], [ "def plot_series(time, series, format=\"-\", start=0, end=None):\n plt.plot(time[start:end], series[start:end], format)\n plt.xlabel(\"Time\")\n plt.ylabel(\"Value\")\n plt.grid(True)\n\ndef trend(time, slope=0):\n return slope * time\n\ndef seasonal_pattern(season_time):\n \"\"\"Just an arbitrary pattern, you can change it if you wish\"\"\"\n return np.where(season_time < 0.4,\n np.cos(season_time * 2 * np.pi),\n 1 / np.exp(3 * season_time))\n\ndef seasonality(time, period, amplitude=1, phase=0):\n \"\"\"Repeats the same pattern at each period\"\"\"\n season_time = ((time + phase) % period) / period\n return amplitude * seasonal_pattern(season_time)\n\ndef noise(time, noise_level=1, seed=None):\n rnd = np.random.RandomState(seed)\n return rnd.randn(len(time)) * noise_level\n\ntime = np.arange(4 * 365 + 1, dtype=\"float32\")\nbaseline = 10\nseries = trend(time, 0.1) \nbaseline = 10\namplitude = 40\nslope = 0.05\nnoise_level = 5\n\n# Create the series\nseries = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)\n# Update with noise\nseries += noise(time, noise_level, seed=42)\n\nsplit_time = 1000\ntime_train = time[:split_time]\nx_train = series[:split_time]\ntime_valid = time[split_time:]\nx_valid = series[split_time:]\n\nwindow_size = 20\nbatch_size = 32\nshuffle_buffer_size = 1000", "_____no_output_____" ], [ "def windowed_dataset(series, window_size, batch_size, shuffle_buffer):\n dataset = tf.data.Dataset.from_tensor_slices(series)\n dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)\n dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))\n dataset = dataset.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1]))\n dataset = dataset.batch(batch_size).prefetch(1)\n return dataset", "_____no_output_____" ], [ "tf.keras.backend.clear_session()\ntf.random.set_seed(51)\nnp.random.seed(51)\n\ntf.keras.backend.clear_session()\ndataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)\n\nmodel = tf.keras.models.Sequential([\n # we have a dataset of shape(batch_size, timesteps)\n # rnn takes a 3-d input of shape(batch_size, timesteps, dimenstionality)\n # so as to increase the dimension we can use a lambda layer which is a part of the\n # network to do so, lambda layers gives us greater control over the network\n # link - https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda?version=stable\n \n tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),\n input_shape=[None]), # so as to intake arbitrary time steps \n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Dense(1),\n tf.keras.layers.Lambda(lambda x: x * 100.0)\n])\n\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(\n lambda epoch: 1e-8 * 10**(epoch / 20))\noptimizer = tf.keras.optimizers.SGD(lr=1e-8, momentum=0.9)\nmodel.compile(loss=tf.keras.losses.Huber(),\n optimizer=optimizer,\n metrics=[\"mae\"])\nhistory = model.fit(dataset, epochs=100, callbacks=[lr_schedule])", "Epoch 1/100\n31/31 [==============================] - 9s 303ms/step - loss: 21.4956 - mae: 22.0115\nEpoch 2/100\n31/31 [==============================] - 0s 12ms/step - loss: 21.1128 - mae: 21.6440\nEpoch 3/100\n31/31 [==============================] - 0s 13ms/step - loss: 20.7468 - mae: 21.2278\nEpoch 4/100\n31/31 [==============================] - 0s 12ms/step - loss: 20.3564 - mae: 20.7739\nEpoch 5/100\n31/31 [==============================] - 0s 12ms/step - loss: 19.7907 - mae: 20.2843\nEpoch 6/100\n31/31 [==============================] - 0s 12ms/step - loss: 19.1428 - mae: 19.6776\nEpoch 7/100\n31/31 [==============================] - 0s 11ms/step - loss: 18.2205 - mae: 18.7308\nEpoch 8/100\n31/31 [==============================] - 0s 12ms/step - loss: 17.5280 - mae: 17.9757\nEpoch 9/100\n31/31 [==============================] - 0s 12ms/step - loss: 17.1315 - mae: 17.6581\nEpoch 10/100\n31/31 [==============================] - 0s 12ms/step - loss: 16.8294 - mae: 17.3457\nEpoch 11/100\n31/31 [==============================] - 0s 12ms/step - loss: 16.5175 - mae: 17.0459\nEpoch 12/100\n31/31 [==============================] - 0s 12ms/step - loss: 16.2835 - mae: 16.7529\nEpoch 13/100\n31/31 [==============================] - 0s 12ms/step - loss: 15.9576 - mae: 16.4573\nEpoch 14/100\n31/31 [==============================] - 0s 12ms/step - loss: 15.6444 - mae: 16.1587\nEpoch 15/100\n31/31 [==============================] - 0s 12ms/step - loss: 15.3548 - mae: 15.8571\nEpoch 16/100\n31/31 [==============================] - 0s 12ms/step - loss: 15.0615 - mae: 15.5765\nEpoch 17/100\n31/31 [==============================] - 0s 12ms/step - loss: 14.8060 - mae: 15.2950\nEpoch 18/100\n31/31 [==============================] - 0s 12ms/step - loss: 14.5474 - mae: 15.0164\nEpoch 19/100\n31/31 [==============================] - 0s 13ms/step - loss: 14.2308 - mae: 14.7612\nEpoch 20/100\n31/31 [==============================] - 0s 13ms/step - loss: 14.0179 - mae: 14.5354\nEpoch 21/100\n31/31 [==============================] - 0s 12ms/step - loss: 13.8130 - mae: 14.3081\nEpoch 22/100\n31/31 [==============================] - 0s 12ms/step - loss: 13.5935 - mae: 14.1062\nEpoch 23/100\n31/31 [==============================] - 0s 13ms/step - loss: 13.3985 - mae: 13.8858\nEpoch 24/100\n31/31 [==============================] - 0s 12ms/step - loss: 13.2187 - mae: 13.7037\nEpoch 25/100\n31/31 [==============================] - 0s 12ms/step - loss: 12.9267 - mae: 13.4526\nEpoch 26/100\n31/31 [==============================] - 0s 13ms/step - loss: 12.7290 - mae: 13.2327\nEpoch 27/100\n31/31 [==============================] - 0s 12ms/step - loss: 12.4543 - mae: 12.9716\nEpoch 28/100\n31/31 [==============================] - 0s 12ms/step - loss: 12.2231 - mae: 12.7095\nEpoch 29/100\n31/31 [==============================] - 0s 13ms/step - loss: 12.3309 - mae: 12.8460\nEpoch 30/100\n31/31 [==============================] - 0s 12ms/step - loss: 11.8069 - mae: 12.3121\nEpoch 31/100\n31/31 [==============================] - 0s 12ms/step - loss: 11.3216 - mae: 11.8148\nEpoch 32/100\n31/31 [==============================] - 0s 13ms/step - loss: 11.0173 - mae: 11.4830\nEpoch 33/100\n31/31 [==============================] - 0s 12ms/step - loss: 10.6577 - mae: 11.1361\nEpoch 34/100\n31/31 [==============================] - 0s 13ms/step - loss: 10.8242 - mae: 11.3007\nEpoch 35/100\n31/31 [==============================] - 0s 12ms/step - loss: 10.9697 - mae: 11.4607\nEpoch 36/100\n31/31 [==============================] - 0s 11ms/step - loss: 10.4873 - mae: 10.9636\nEpoch 37/100\n31/31 [==============================] - 0s 13ms/step - loss: 10.0051 - mae: 10.4892\nEpoch 38/100\n31/31 [==============================] - 0s 12ms/step - loss: 9.5181 - mae: 10.0283\nEpoch 39/100\n31/31 [==============================] - 0s 13ms/step - loss: 9.0591 - mae: 9.5461\nEpoch 40/100\n31/31 [==============================] - 0s 12ms/step - loss: 8.6498 - mae: 9.1358\nEpoch 41/100\n31/31 [==============================] - 0s 11ms/step - loss: 8.2329 - mae: 8.7356\nEpoch 42/100\n31/31 [==============================] - 0s 13ms/step - loss: 7.9299 - mae: 8.4081\nEpoch 43/100\n31/31 [==============================] - 0s 12ms/step - loss: 7.6007 - mae: 8.1137\nEpoch 44/100\n31/31 [==============================] - 0s 11ms/step - loss: 7.3032 - mae: 7.8033\nEpoch 45/100\n31/31 [==============================] - 0s 12ms/step - loss: 7.0877 - mae: 7.5770\nEpoch 46/100\n31/31 [==============================] - 0s 12ms/step - loss: 6.8843 - mae: 7.3933\nEpoch 47/100\n31/31 [==============================] - 0s 12ms/step - loss: 6.6226 - mae: 7.0771\nEpoch 48/100\n31/31 [==============================] - 0s 13ms/step - loss: 6.4349 - mae: 6.9074\nEpoch 49/100\n31/31 [==============================] - 0s 12ms/step - loss: 6.3954 - mae: 6.8757\nEpoch 50/100\n31/31 [==============================] - 0s 12ms/step - loss: 6.0277 - mae: 6.5164\nEpoch 51/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.8894 - mae: 6.3634\nEpoch 52/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.7521 - mae: 6.2421\nEpoch 53/100\n31/31 [==============================] - 0s 13ms/step - loss: 5.6553 - mae: 6.1419\nEpoch 54/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.4473 - mae: 5.9468\nEpoch 55/100\n31/31 [==============================] - 0s 11ms/step - loss: 5.4122 - mae: 5.9006\nEpoch 56/100\n31/31 [==============================] - 0s 13ms/step - loss: 5.2623 - mae: 5.7471\nEpoch 57/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.3106 - mae: 5.7881\nEpoch 58/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.1929 - mae: 5.6591\nEpoch 59/100\n31/31 [==============================] - 0s 13ms/step - loss: 5.2541 - mae: 5.7545\nEpoch 60/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.1063 - mae: 5.5567\nEpoch 61/100\n31/31 [==============================] - 0s 12ms/step - loss: 4.9472 - mae: 5.4250\nEpoch 62/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.0917 - mae: 5.5808\nEpoch 63/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.1680 - mae: 5.6630\nEpoch 64/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.0575 - mae: 5.5312\nEpoch 65/100\n31/31 [==============================] - 0s 12ms/step - loss: 4.9006 - mae: 5.3900\nEpoch 66/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.2746 - mae: 5.7638\nEpoch 67/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.2607 - mae: 5.7446\nEpoch 68/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.2218 - mae: 5.7233\nEpoch 69/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.3456 - mae: 5.8346\nEpoch 70/100\n31/31 [==============================] - 0s 12ms/step - loss: 6.1691 - mae: 6.6382\nEpoch 71/100\n31/31 [==============================] - 0s 11ms/step - loss: 4.9526 - mae: 5.4137\nEpoch 72/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.5657 - mae: 6.0633\nEpoch 73/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.3436 - mae: 5.8209\nEpoch 74/100\n31/31 [==============================] - 0s 12ms/step - loss: 6.7311 - mae: 7.1983\nEpoch 75/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.7492 - mae: 6.2193\nEpoch 76/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.2818 - mae: 5.7818\nEpoch 77/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.6425 - mae: 6.0995\nEpoch 78/100\n31/31 [==============================] - 0s 13ms/step - loss: 7.3175 - mae: 7.8347\nEpoch 79/100\n31/31 [==============================] - 0s 13ms/step - loss: 7.1590 - mae: 7.6353\nEpoch 80/100\n31/31 [==============================] - 0s 13ms/step - loss: 5.2885 - mae: 5.7796\nEpoch 81/100\n31/31 [==============================] - 0s 12ms/step - loss: 5.4822 - mae: 5.9677\nEpoch 82/100\n31/31 [==============================] - 0s 13ms/step - loss: 6.7601 - mae: 7.2446\nEpoch 83/100\n31/31 [==============================] - 0s 11ms/step - loss: 6.2718 - mae: 6.7460\nEpoch 84/100\n31/31 [==============================] - 0s 12ms/step - loss: 7.5164 - mae: 8.0019\nEpoch 85/100\n31/31 [==============================] - 0s 12ms/step - loss: 8.5435 - mae: 9.0290\nEpoch 86/100\n31/31 [==============================] - 0s 12ms/step - loss: 6.3990 - mae: 6.8505\nEpoch 87/100\n31/31 [==============================] - 0s 13ms/step - loss: 6.8739 - mae: 7.3729\nEpoch 88/100\n31/31 [==============================] - 0s 12ms/step - loss: 6.9440 - mae: 7.4645\nEpoch 89/100\n31/31 [==============================] - 0s 13ms/step - loss: 5.7347 - mae: 6.2071\nEpoch 90/100\n31/31 [==============================] - 0s 12ms/step - loss: 6.5328 - mae: 7.0147\nEpoch 91/100\n31/31 [==============================] - 0s 12ms/step - loss: 9.1667 - mae: 9.6334\nEpoch 92/100\n31/31 [==============================] - 0s 12ms/step - loss: 9.1487 - mae: 9.6960\nEpoch 93/100\n31/31 [==============================] - 0s 12ms/step - loss: 9.1058 - mae: 9.6064\nEpoch 94/100\n31/31 [==============================] - 0s 12ms/step - loss: 8.6748 - mae: 9.1999\nEpoch 95/100\n31/31 [==============================] - 0s 12ms/step - loss: 8.4982 - mae: 8.9723\nEpoch 96/100\n31/31 [==============================] - 0s 12ms/step - loss: 7.1676 - mae: 7.6561\nEpoch 97/100\n31/31 [==============================] - 0s 13ms/step - loss: 9.4725 - mae: 9.9320\nEpoch 98/100\n31/31 [==============================] - 0s 13ms/step - loss: 9.3080 - mae: 9.8532\nEpoch 99/100\n31/31 [==============================] - 0s 12ms/step - loss: 12.4675 - mae: 13.0500\nEpoch 100/100\n31/31 [==============================] - 0s 12ms/step - loss: 13.9109 - mae: 14.4005\n" ], [ "plt.semilogx(history.history[\"lr\"], history.history[\"loss\"])\nplt.axis([1e-8, 1e-4, 0, 30])", "_____no_output_____" ], [ "tf.keras.backend.clear_session()\ntf.random.set_seed(51)\nnp.random.seed(51)\n\ntf.keras.backend.clear_session()\ndataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),\n input_shape=[None]),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Dense(1),\n tf.keras.layers.Lambda(lambda x: x * 100.0)\n])\n\n\nmodel.compile(loss=\"mse\", optimizer=tf.keras.optimizers.SGD(lr=1e-5, momentum=0.9),metrics=[\"mae\"])\nhistory = model.fit(dataset,epochs=500,verbose=0)", "_____no_output_____" ], [ "forecast = []\nfor time in range(len(series) - window_size):\n forecast.append(model.predict(series[time:time + window_size][np.newaxis]))\n\nforecast = forecast[split_time-window_size:]\nresults = np.array(forecast)[:, 0, 0]\n\n\nplt.figure(figsize=(10, 6))\n\nplot_series(time_valid, x_valid)\nplot_series(time_valid, results)", "_____no_output_____" ], [ "tf.keras.metrics.mean_absolute_error(x_valid, results).numpy()", "_____no_output_____" ], [ "import matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\n#-----------------------------------------------------------\n# Retrieve a list of list results on training and test data\n# sets for each training epoch\n#-----------------------------------------------------------\nmae=history.history['mae']\nloss=history.history['loss']\n\nepochs=range(len(loss)) # Get number of epochs\n\n#------------------------------------------------\n# Plot MAE and Loss\n#------------------------------------------------\nplt.plot(epochs, mae, 'r')\nplt.plot(epochs, loss, 'b')\nplt.title('MAE and Loss')\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend([\"MAE\", \"Loss\"])\n\nplt.figure()\n\nepochs_zoom = epochs[200:]\nmae_zoom = mae[200:]\nloss_zoom = loss[200:]\n\n#------------------------------------------------\n# Plot Zoomed MAE and Loss\n#------------------------------------------------\nplt.plot(epochs_zoom, mae_zoom, 'r')\nplt.plot(epochs_zoom, loss_zoom, 'b')\nplt.title('MAE and Loss')\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend([\"MAE\", \"Loss\"])\n\nplt.figure()", "_____no_output_____" ], [ "tf.keras.backend.clear_session()\ndataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),\n input_shape=[None]),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Dense(1),\n tf.keras.layers.Lambda(lambda x: x * 100.0)\n])\n\n\nmodel.compile(loss=\"mse\", optimizer=tf.keras.optimizers.SGD(lr=1e-6, momentum=0.9))\nmodel.fit(dataset,epochs=100, verbose=0)", "_____no_output_____" ], [ "tf.keras.backend.clear_session()\ndataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),\n input_shape=[None]),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Dense(1),\n tf.keras.layers.Lambda(lambda x: x * 100.0)\n])\n\n\nmodel.compile(loss=\"mse\", optimizer=tf.keras.optimizers.SGD(lr=1e-6, momentum=0.9))\nmodel.fit(dataset,epochs=100)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec52514ecd49de96822000081375b2e2eaa7b21f
3,214
ipynb
Jupyter Notebook
Python_Classes_and_Objects.ipynb
FranzLouiseGloriani/OOP-1-1
8350a23019b6ad925f3f00d2fb61e661475e7654
[ "Apache-2.0" ]
null
null
null
Python_Classes_and_Objects.ipynb
FranzLouiseGloriani/OOP-1-1
8350a23019b6ad925f3f00d2fb61e661475e7654
[ "Apache-2.0" ]
null
null
null
Python_Classes_and_Objects.ipynb
FranzLouiseGloriani/OOP-1-1
8350a23019b6ad925f3f00d2fb61e661475e7654
[ "Apache-2.0" ]
null
null
null
25.712
250
0.448351
[ [ [ "<a href=\"https://colab.research.google.com/github/FranzLouiseGloriani/OOP-1-1/blob/main/Python_Classes_and_Objects.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "Class", "_____no_output_____" ] ], [ [ "class MyClass: #name of class\n pass #create a class without variable and methods", "_____no_output_____" ], [ "class MyClass:\n def __init__(self, name, age):\n self.name = name #create a class with attributes\n self.age = age\n\n def display(self):\n print(self.name, self.age)\n \nperson = MyClass(\"Franz Louise B. Gloriani\", 19) #create an object name\n\nprint(person.name)\nprint(person.age)\n\nperson.display()", "Franz Louise B. Gloriani\n19\nFranz Louise B. Gloriani 19\n" ], [ "#Application 1 - Write a Python program that computes for an area of rectangle: A = l x w\n\nclass Rectangle:\n def __init__(self,l,w):\n self.l = l #attribute names\n self.w = w\n\n def Area(self):\n print(self.l * self.w)\n\nrect = Rectangle(7,3)\nrect.Area()", "21\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
ec525c4e057d138f93a1bae62def9229c627b288
11,309
ipynb
Jupyter Notebook
site/ko/tutorials/images/cnn.ipynb
ilyaspiridonov/docs-l10n
a061a44e40d25028d0a4458094e48ab717d3565c
[ "Apache-2.0" ]
1
2021-09-23T09:56:29.000Z
2021-09-23T09:56:29.000Z
site/ko/tutorials/images/cnn.ipynb
ilyaspiridonov/docs-l10n
a061a44e40d25028d0a4458094e48ab717d3565c
[ "Apache-2.0" ]
null
null
null
site/ko/tutorials/images/cnn.ipynb
ilyaspiridonov/docs-l10n
a061a44e40d25028d0a4458094e48ab717d3565c
[ "Apache-2.0" ]
1
2020-06-23T07:43:49.000Z
2020-06-23T07:43:49.000Z
29.374026
338
0.497745
[ [ [ "##### Copyright 2019 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_____" ] ], [ [ "# 합성곱 신경망", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/images/cnn\">\n <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n TensorFlow.org에서 보기</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/tutorials/images/cnn.ipynb\">\n <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n 구글 코랩(Colab)에서 실행하기</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/ko/tutorials/images/cnn.ipynb\">\n <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n 깃허브(GitHub) 소스 보기</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ko/tutorials/images/cnn.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>", "_____no_output_____" ], [ "Note: 이 문서는 텐서플로 커뮤니티에서 번역했습니다. 커뮤니티 번역 활동의 특성상 정확한 번역과 최신 내용을 반영하기 위해 노력함에도\n불구하고 [공식 영문 문서](https://www.tensorflow.org/?hl=en)의 내용과 일치하지 않을 수 있습니다.\n이 번역에 개선할 부분이 있다면\n[tensorflow/docs-l10n](https://github.com/tensorflow/docs-l10n/) 깃헙 저장소로 풀 리퀘스트를 보내주시기 바랍니다.\n문서 번역이나 리뷰에 참여하려면\n[[email protected]](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ko)로\n메일을 보내주시기 바랍니다.", "_____no_output_____" ], [ "이 튜토리얼은 MNIST 숫자를 분류하기 위해 간단한 [합성곱 신경망](https://developers.google.com/machine-learning/glossary/#convolutional_neural_network)(Convolutional Neural Network, CNN)을 훈련합니다. 간단한 이 네트워크는 MNIST 테스트 세트에서 99% 정확도를 달성할 것입니다. 이 튜토리얼은 [케라스 Sequential API](https://www.tensorflow.org/guide/keras)를 사용하기 때문에 몇 줄의 코드만으로 모델을 만들고 훈련할 수 있습니다.\n\n노트: GPU를 사용하여 CNN의 훈련 속도를 높일 수 있습니다. 코랩에서 이 노트북을 실행한다면 * 수정 -> 노트 설정 -> 하드웨어 가속기* 에서 GPU를 선택하세요.", "_____no_output_____" ], [ "### 텐서플로 임포트하기", "_____no_output_____" ] ], [ [ "!pip install tensorflow-gpu==2.0.0-rc1\nimport tensorflow as tf\n\nfrom tensorflow.keras import datasets, layers, models", "_____no_output_____" ] ], [ [ "### MNIST 데이터셋 다운로드하고 준비하기", "_____no_output_____" ] ], [ [ "(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()\n\ntrain_images = train_images.reshape((60000, 28, 28, 1))\ntest_images = test_images.reshape((10000, 28, 28, 1))\n\n# 픽셀 값을 0~1 사이로 정규화합니다.\ntrain_images, test_images = train_images / 255.0, test_images / 255.0", "_____no_output_____" ] ], [ [ "### 합성곱 층 만들기", "_____no_output_____" ], [ "아래 6줄의 코드에서 [Conv2D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D)와 [MaxPooling2D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D) 층을 쌓는 일반적인 패턴으로 합성곱 층을 정의합니다.\n\nCNN은 배치(batch) 크기를 제외하고 (이미지 높이, 이미지 너비, 컬러 채널) 크기의 텐서(tensor)를 입력으로 받습니다. MNIST 데이터는 (흑백 이미지이기 때문에) 컬러 채널(channel)이 하나지만 컬러 이미지는 (R,G,B) 세 개의 채널을 가집니다. 이 예에서는 MNIST 이미지 포맷인 (28, 28, 1) 크기의 입력을 처리하는 CNN을 정의하겠습니다. 이 값을 첫 번째 층의 `input_shape` 매개변수로 전달합니다.", "_____no_output_____" ] ], [ [ "model = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))", "_____no_output_____" ] ], [ [ "지금까지 모델의 구조를 출력해 보죠.", "_____no_output_____" ] ], [ [ "model.summary()", "_____no_output_____" ] ], [ [ "위에서 Conv2D와 MaxPooling2D 층의 출력은 (높이, 너비, 채널) 크기의 3D 텐서입니다. 높이와 너비 차원은 네트워크가 깊어질수록 감소하는 경향을 가집니다. Conv2D 층에서 출력 채널의 수는 첫 번째 매개변수에 의해 결정됩니다(예를 들면, 32 또는 64). 일반적으로 높이와 너비가 줄어듦에 따라 (계산 비용 측면에서) Conv2D 층의 출력 채널을 늘릴 수 있습니다.", "_____no_output_____" ], [ "### 마지막에 Dense 층 추가하기\n\n모델을 완성하려면 마지막 합성곱 층의 출력 텐서(크기 (3, 3, 64))를 하나 이상의 Dense 층에 주입하여 분류를 수행합니다. Dense 층은 벡터(1D)를 입력으로 받는데 현재 출력은 3D 텐서입니다. 먼저 3D 출력을 1D로 펼치겠습니다. 그다음 하나 이상의 Dense 층을 그 위에 추가하겠습니다. MNIST 데이터는 10개의 클래스가 있으므로 마지막에 Dense 층에 10개의 출력과 소프트맥스 활성화 함수를 사용합니다.", "_____no_output_____" ] ], [ [ "model.add(layers.Flatten())\nmodel.add(layers.Dense(64, activation='relu'))\nmodel.add(layers.Dense(10, activation='softmax'))", "_____no_output_____" ] ], [ [ "최종 모델의 구조를 확인해 보죠.", "_____no_output_____" ] ], [ [ "model.summary()", "_____no_output_____" ] ], [ [ "여기에서 볼 수 있듯이 두 개의 Dense 층을 통과하기 전에 (3, 3, 64) 출력을 (576) 크기의 벡터로 펼쳤습니다.", "_____no_output_____" ], [ "### 모델 컴파일과 훈련하기", "_____no_output_____" ] ], [ [ "model.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(train_images, train_labels, epochs=5)", "_____no_output_____" ] ], [ [ "### 모델 평가", "_____no_output_____" ] ], [ [ "test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)", "_____no_output_____" ], [ "print(test_acc)", "_____no_output_____" ] ], [ [ "결과에서 보듯이 간단한 CNN 모델이 99%의 테스트 정확도를 달성합니다. 몇 라인의 코드치고 나쁘지 않네요! (케라스의 서브클래싱 API와 GradientTape를 사용하여) CNN을 만드는 또 다른 방법은 [여기](https://github.com/tensorflow/docs-l10n/blob/master/site/ko/tutorials/quickstart/advanced.ipynb)를 참고하세요.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
ec525d85d7a289a14179f81dab531b4f8dce5319
16,755
ipynb
Jupyter Notebook
Recommender-Source-Code/JupyterNotebook/notebooks/Sampling_Data.ipynb
Xiyao-Cheng/OnTimeEvidence
22e5ebfff2544bd5a1424c73367969bb450d2f9a
[ "MIT" ]
null
null
null
Recommender-Source-Code/JupyterNotebook/notebooks/Sampling_Data.ipynb
Xiyao-Cheng/OnTimeEvidence
22e5ebfff2544bd5a1424c73367969bb450d2f9a
[ "MIT" ]
5
2020-07-16T22:58:15.000Z
2022-02-17T21:58:23.000Z
Recommender-Source-Code/JupyterNotebook/notebooks/Sampling_Data.ipynb
Xiyao-Cheng/OnTimeEvidence
22e5ebfff2544bd5a1424c73367969bb450d2f9a
[ "MIT" ]
1
2019-05-01T05:30:04.000Z
2019-05-01T05:30:04.000Z
34.689441
729
0.620054
[ [ [ "As explained in the [Composing Data](Composing_Data.ipynb) and [Containers](Containers.ipynb) tutorials, HoloViews allows you to build up hierarchical containers that express the natural relationships between your data items, in whatever multidimensional space best characterizes your application domain. Once your data is in such containers, individual visualizations are then made by choosing subregions of this multidimensional space, either smaller numeric ranges (as in cropping of photographic images), or lower-dimensional subsets (as in selecting frames from a movie, or a specific movie from a large library), or both (as in selecting a cropped version of a frame from a specific movie from a large library). \n\nIn this tutorial, we show how to specify such selections, using four different (but related) operations that can act on an element ``e``:\n\n| Operation | Example syntax | Description |\n|:---------------|:----------------:|:-------------|\n| **indexing** | e[5.5], e[3,5.5] | Selecting a single data value, returning one actual numerical value from the existing data\n| **slice** | e[3:5.5], e[3:5.5,0:1] | Selecting a contiguous portion from an Element, returning the same type of Element\n| **sample** | e.sample(y=5.5),<br>e.sample((3,3)) | Selecting one or more regularly spaced data values, returning a new type of Element\n| **select** | e.select(y=5.5),<br>e.select(y=(3,5.5)) | More verbose notation covering all supporting slice and index operations by dimension name.\n\nThese operations are all concerned with selecting some subset of your data values, without combining across data values (e.g. averaging) or otherwise transforming your actual data. In the [Columnar Data](Columnar_Data.ipynb) tutorial we will look at other operations on the data that reduce, summarize, or transform the data in other ways, rather than selections as covered here.\n\nWe'll be going through each operation in detail and provide a visual illustration to help make the semantics of each operation clear. This Tutorial assumes that you are familiar with continuous and discrete coordinate systems, so please review our [Continuous Coordinates Tutorial](Continuous_Coordinates.ipynb) if you have not done so already.", "_____no_output_____" ], [ "# Indexing and slicing Elements", "_____no_output_____" ], [ "In the [Exploring Data Tutorial](Exploring_Data.ipynb) we saw examples of how to select individual elements embedded in a multi-dimensional space. We also briefly introduced \"deep slicing\" of the ``RGB`` elements to select a subregion of the images. The [Continuous Coordinates Tutorial](Continuous_Coordinates.ipynb) covered slicing and indexing in Elements representing continuous coordinate coordinate systems such as ``Image`` types. Here we'll be going through each operation in full detail, providing a visual illustration to help make the semantics of each operation clear.\n\nHow the Element may be indexed depends on the key dimensions (or ``kdims``) of the Element. It is thus important to consider the nature and dimensionality of your data when choosing the Element type for it.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport holoviews as hv\nhv.notebook_extension()\n%opts Layout [fig_size=125] Points [size_index=None] (s=50) Scatter3D [size_index=None]\n%opts Bounds (linewidth=2 color='k') {+axiswise} Text (fontsize=16 color='k') Image (cmap='Reds')", "_____no_output_____" ] ], [ [ "## 1D Elements: Slicing and indexing", "_____no_output_____" ], [ "Certain Chart elements support both single-dimensional indexing and slicing: ``Scatter``, ``Curve``, ``Histogram``, and ``ErrorBars``. Here we'll look at how we can easily slice a ``Histogram`` to select a subregion of it:", "_____no_output_____" ] ], [ [ "np.random.seed(42)\nedges, data = np.histogram(np.random.randn(100))\nhist = hv.Histogram(edges, data)\nsubregion = hist[0:1]\nhist * subregion", "_____no_output_____" ] ], [ [ "The two bins in a different color show the selected region, overlaid on top of the full histogram. We can also access the value for a specific bin in the ``Histogram``. A continuous-valued index that falls inside a particular bin will return the corresponding value or frequency.", "_____no_output_____" ] ], [ [ "hist[0.25], hist[0.5], hist[0.55]", "_____no_output_____" ] ], [ [ "We can slice a ``Curve`` the same way:", "_____no_output_____" ] ], [ [ "xs = np.linspace(0, np.pi*2, 21)\ncurve = hv.Curve((xs, np.sin(xs)))\nsubregion = curve[np.pi/2:np.pi*1.5]\ncurve * subregion * hv.Scatter(curve)", "_____no_output_____" ] ], [ [ "Here again the region in a different color is the specified subregion, and we've also marked each discrete point with a dot using the ``Scatter`` ``Element``. As before we can also get the value for a specific sample point; whatever x-index is provided will snap to the closest sample point and return the dependent value:", "_____no_output_____" ] ], [ [ "curve[4.05], curve[4.1], curve[4.17], curve[4.3]", "_____no_output_____" ] ], [ [ "It is important to note that an index (or a list of indices, as for the 2D and 3D cases below) will always return the raw indexed (dependent) value, i.e. a number. A slice (indicated with `:`), on the other hand, will retain the Element type even in cases where the plot might not be useful, such as having only a single value, two values, or no value at all in that range:", "_____no_output_____" ] ], [ [ "curve[4:4.5]", "_____no_output_____" ] ], [ [ "## 2D and 3D Elements: slicing", "_____no_output_____" ], [ "For data defined in a 2D space, there are 2D equivalents of the 1D Curve and Scatter types. A ``Points``, for example, can be thought of as a number of points in a 2D space.", "_____no_output_____" ] ], [ [ "r = np.arange(0, 1, 0.005)\nxs, ys = (r * fn(85*np.pi*r) for fn in (np.cos, np.sin))\npaths = hv.Points((xs, ys))\npaths + paths[0:1, 0:1]", "_____no_output_____" ] ], [ [ "However, indexing is not supported in this space, because there could be many possible points near a given set of coordinates, and finding the nearest one would require a search across potentially incommensurable dimensions, which is poorly defined and difficult to support.\n\nSlicing in 3D works much like slicing in 2D, but indexing is not supported for the same reason as in 2D:", "_____no_output_____" ] ], [ [ "xs = np.linspace(0, np.pi*8, 201)\nscatter = hv.Scatter3D((xs, np.sin(xs), np.cos(xs)))\nscatter + scatter[5:10, :, 0:]", "_____no_output_____" ] ], [ [ "## 2D Raster and Image: slicing and indexing\n\nRaster and the various other image-like objects (Images, RGB, HSV, etc.) can all sliced and indexed, as can Surface, because they all have an underlying regular grid of key dimension values:", "_____no_output_____" ] ], [ [ "%opts Image (cmap='Blues') Bounds (color='red')", "_____no_output_____" ], [ "np.random.seed(0)\nextents = (0, 0, 10, 10)\nimg = hv.Image(np.random.rand(10, 10), bounds=extents)\nimg_slice = img[1:9,4:5]\nbox = hv.Bounds((1,4,9,5))\nimg*box + img_slice", "_____no_output_____" ], [ "img[4.2,4.2], img[4.3,4.2], img[5.0,4.2]", "_____no_output_____" ] ], [ [ "# Sampling\n\nSampling is essentially a process of indexing an Element at multiple index locations, and collecting the results. Thus any Element that can be indexed can also be sampled. Compared to regular indexing, sampling is different in that multiple indices may be supplied at the same time. Also, indexing will only return the value at that location, whereas the return type from a sampling operation is another ``Element`` type, usually either a ``Table`` or a ``Curve``, to allow both key and value dimensions to be returned.\n\n### Sampling Elements\n\nSampling can use either an explicit list of samples, or or by passing the samples for each dimension keyword arguments.\n\nWe'll start by taking a single sample of an Image object, to make it clear how sampling and indexing are similar operations yet different in their results:", "_____no_output_____" ] ], [ [ "img_coords = hv.Points(img.table(), extents=extents)\nlabeled_img = img * img_coords * hv.Points([img.closest([(5.1,4.9)])])(style=dict(color='r'))\nimg + labeled_img + img.sample([(5.1,4.9)])", "_____no_output_____" ], [ "img[5.1,4.9]", "_____no_output_____" ] ], [ [ "Here, the output of the indexing operation is the value (0.1965823616800535) from the location closest to the specified , whereas ``.sample()`` returns a Table that lists both the coordinates *and* the value, and slicing (in previous section) returns an Element of the same type, not a Table.\n\n\nNext we can try sampling along only one Dimension on our 2D Image, leaving us with a 1D Element (in this case a ``Curve``):", "_____no_output_____" ] ], [ [ "sampled = img.sample(y=5)\nlabeled_img = img * img_coords * hv.Points(zip(sampled['x'], [img.closest(y=5)]*10))\nimg + labeled_img + sampled", "_____no_output_____" ] ], [ [ "Sampling works on any regularly sampled Element type. For example, we can select multiple samples along the x-axis of a Curve.", "_____no_output_____" ] ], [ [ "xs = np.arange(10)\nsamples = [2, 4, 6, 8]\ncurve = hv.Curve(zip(xs, np.sin(xs)))\ncurve_samples = hv.Scatter(zip(xs, [0] * 10)) * hv.Scatter(zip(samples, [0]*len(samples))) \ncurve + curve_samples + curve.sample(samples)", "_____no_output_____" ] ], [ [ "### Sampling HoloMaps\n\nSampling is often useful when you have more data than you wish to visualize or analyze at one time. First, let's create a HoloMap containing a number of observations of some noisy data.", "_____no_output_____" ] ], [ [ "obs_hmap = hv.HoloMap({i: hv.Image(np.random.randn(10, 10), bounds=extents)\n for i in range(3)}, key_dimensions=['Observation'])", "_____no_output_____" ] ], [ [ "HoloMaps also provide additional functionality to perform regular sampling on your data. In this case we'll take 3x3 subsamples of each of the Images.", "_____no_output_____" ] ], [ [ "sample_style = dict(edgecolors='k', alpha=1)\nall_samples = obs_hmap.table().to.scatter3d()(style=dict(alpha=0.15))\nsampled = obs_hmap.sample((3,3))\nsubsamples = sampled.to.scatter3d()(style=sample_style)\nall_samples * subsamples + sampled", "_____no_output_____" ] ], [ [ "By supplying bounds in as a (left, bottom, right, top) tuple we can also sample a subregion of our images:", "_____no_output_____" ] ], [ [ "sampled = obs_hmap.sample((3,3), bounds=(2,5,5,10))\nsubsamples = sampled.to.scatter3d()(style=sample_style)\nall_samples * subsamples + sampled", "_____no_output_____" ] ], [ [ "Since this kind of sampling is only well supported for continuous coordinate systems, we can only apply this kind of sampling to Image types for now.\n\n### Sampling Charts\n\nSampling Chart-type Elements like Curve, Scatter, Histogram is only supported by providing an explicit list of samples, since those Elements have no underlying regular grid.", "_____no_output_____" ] ], [ [ "xs = np.arange(10)\nextents = (0, 0, 2, 10)\ncurve = hv.HoloMap({(i) : hv.Curve(zip(xs, np.sin(xs)*i))\n for i in np.linspace(0.5, 1.5, 3)},\n key_dimensions=['Observation'])\nall_samples = curve.table().to.points()\nsampled = curve.sample([0, 2, 4, 6, 8])\nsampling = all_samples * sampled.to.points(extents=extents)(style=dict(color='r'))\nsampling + sampled", "_____no_output_____" ] ], [ [ "Alternatively, you can always deconstruct your data into a Table (see the [Columnar Data](Columnar_Data.ipynb) tutorial) and perform ``select`` operations instead. This is also the easiest way to sample ``NdElement`` types like Bars. Individual samples should be supplied as a set, while ranges can be specified as a two-tuple.", "_____no_output_____" ] ], [ [ "sampled = curve.table().select(Observation=(0, 1.1), x={0, 2, 4, 6, 8})\nsampling = all_samples * sampled.to.points(extents=extents)(style=dict(color='r'))\nsampling + sampled", "_____no_output_____" ] ], [ [ "These tools should help you index, slice, sample, and select your data with ease. The [Columnar Data](Columnar_Data.ipynb) tutorial) explains how to do other types of operations, such as averaging and other reduction operations.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec526f51c3833ac8730743ee72f375e1e3f35e38
26,467
ipynb
Jupyter Notebook
machine-learning-intermediate/pipelines.ipynb
acisel-fr/python-certification
51d04d0570064096e70dcfa19c9c276953731315
[ "Apache-2.0" ]
null
null
null
machine-learning-intermediate/pipelines.ipynb
acisel-fr/python-certification
51d04d0570064096e70dcfa19c9c276953731315
[ "Apache-2.0" ]
null
null
null
machine-learning-intermediate/pipelines.ipynb
acisel-fr/python-certification
51d04d0570064096e70dcfa19c9c276953731315
[ "Apache-2.0" ]
null
null
null
26,467
26,467
0.619828
[ [ [ "<a href=\"https://www.kaggle.com/chasset/intermediate-machine-learning-pipelines?scriptVersionId=89398601\" target=\"_blank\"><img align=\"left\" alt=\"Kaggle\" title=\"Open in Kaggle\" src=\"https://kaggle.com/static/images/open-in-kaggle.svg\"></a>", "_____no_output_____" ], [ "**This notebook is an exercise in the [Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/pipelines).**\n\n---\n", "_____no_output_____" ], [ "In this exercise, you will use **pipelines** to improve the efficiency of your machine learning code.\n\n# Setup\n\nThe questions below will give you feedback on your work. Run the following cell to set up the feedback system.", "_____no_output_____" ] ], [ [ "# Set up code checking\nimport os\nif not os.path.exists(\"../input/train.csv\"):\n os.symlink(\"../input/home-data-for-ml-course/train.csv\", \"../input/train.csv\") \n os.symlink(\"../input/home-data-for-ml-course/test.csv\", \"../input/test.csv\") \nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.ml_intermediate.ex4 import *\nprint(\"Setup Complete\")", "Setup Complete\n" ] ], [ [ "You will work with data from the [Housing Prices Competition for Kaggle Learn Users](https://www.kaggle.com/c/home-data-for-ml-course). \n\n![Ames Housing dataset image](https://i.imgur.com/lTJVG4e.png)\n\nRun the next code cell without changes to load the training and validation sets in `X_train`, `X_valid`, `y_train`, and `y_valid`. The test set is loaded in `X_test`.", "_____no_output_____" ] ], [ [ "import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n# Read the data\nX_full = pd.read_csv('../input/train.csv', index_col='Id')\nX_test_full = pd.read_csv('../input/test.csv', index_col='Id')\n\n# Remove rows with missing target, separate target from predictors\nX_full.dropna(axis=0, subset=['SalePrice'], inplace=True)\ny = X_full.SalePrice\nX_full.drop(['SalePrice'], axis=1, inplace=True)\n\n# Break off validation set from training data\nX_train_full, X_valid_full, y_train, y_valid = train_test_split(X_full, y, \n train_size=0.8, test_size=0.2,\n random_state=0)\n\n# \"Cardinality\" means the number of unique values in a column\n# Select categorical columns with relatively low cardinality (convenient but arbitrary)\ncategorical_cols = [cname for cname in X_train_full.columns if\n X_train_full[cname].nunique() < 10 and \n X_train_full[cname].dtype == \"object\"]\n\n# Select numerical columns\nnumerical_cols = [cname for cname in X_train_full.columns if \n X_train_full[cname].dtype in ['int64', 'float64']]\n\n# Keep selected columns only\nmy_cols = categorical_cols + numerical_cols\nX_train = X_train_full[my_cols].copy()\nX_valid = X_valid_full[my_cols].copy()\nX_test = X_test_full[my_cols].copy()", "_____no_output_____" ], [ "X_train.head()", "_____no_output_____" ] ], [ [ "The next code cell uses code from the tutorial to preprocess the data and train a model. Run this code without changes.", "_____no_output_____" ] ], [ [ "from sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error\n\n# Preprocessing for numerical data\nnumerical_transformer = SimpleImputer(strategy='constant')\n\n# Preprocessing for categorical data\ncategorical_transformer = Pipeline(steps=[\n ('imputer', SimpleImputer(strategy='most_frequent')),\n ('onehot', OneHotEncoder(handle_unknown='ignore'))\n])\n\n# Bundle preprocessing for numerical and categorical data\npreprocessor = ColumnTransformer(\n transformers=[\n ('num', numerical_transformer, numerical_cols),\n ('cat', categorical_transformer, categorical_cols)\n ])\n\n# Define model\nmodel = RandomForestRegressor(n_estimators=100, random_state=0)\n\n# Bundle preprocessing and modeling code in a pipeline\nclf = Pipeline(steps=[('preprocessor', preprocessor),\n ('model', model)\n ])\n\n# Preprocessing of training data, fit model \nclf.fit(X_train, y_train)\n\n# Preprocessing of validation data, get predictions\npreds = clf.predict(X_valid)\n\nprint('MAE:', mean_absolute_error(y_valid, preds))", "MAE: 17861.780102739725\n" ] ], [ [ "The code yields a value around 17862 for the mean absolute error (MAE). In the next step, you will amend the code to do better.\n\n# Step 1: Improve the performance\n\n### Part A\n\nNow, it's your turn! In the code cell below, define your own preprocessing steps and random forest model. Fill in values for the following variables:\n- `numerical_transformer`\n- `categorical_transformer`\n- `model`\n\nTo pass this part of the exercise, you need only define valid preprocessing steps and a random forest model.", "_____no_output_____" ] ], [ [ "# Preprocessing for numerical data\nnumerical_transformer = SimpleImputer(strategy='mean')\n\n# Preprocessing for categorical data\nfrom sklearn.preprocessing import OrdinalEncoder\ncategorical_transformer = Pipeline(steps = [\n ('imputer', SimpleImputer(strategy='most_frequent')),\n ('ordinal', OneHotEncoder(handle_unknown='ignore'))\n])\n\n# Bundle preprocessing for numerical and categorical data\npreprocessor = ColumnTransformer(\n transformers=[\n ('num', numerical_transformer, numerical_cols),\n ('cat', categorical_transformer, categorical_cols)\n ])\n\n# Define model\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)\n\n# Check your answer\nstep_1.a.check()", "_____no_output_____" ], [ "# Lines below will give you a hint or solution code\n#step_1.a.hint()\n#step_1.a.solution()", "_____no_output_____" ] ], [ [ "### Part B\n\nRun the code cell below without changes.\n\nTo pass this step, you need to have defined a pipeline in **Part A** that achieves lower MAE than the code above. You're encouraged to take your time here and try out many different approaches, to see how low you can get the MAE! (_If your code does not pass, please amend the preprocessing steps and model in Part A._)", "_____no_output_____" ] ], [ [ "# Bundle preprocessing and modeling code in a pipeline\nmy_pipeline = Pipeline(steps=[('preprocessor', preprocessor),\n ('model', model)\n ])\n\n# Preprocessing of training data, fit model \nmy_pipeline.fit(X_train, y_train)\n\n# Preprocessing of validation data, get predictions\npreds = my_pipeline.predict(X_valid)\n\n# Evaluate the model\nscore = mean_absolute_error(y_valid, preds)\nprint('MAE:', score)\n\n# Check your answer\nstep_1.b.check()", "MAE: 17418.883253424658\n" ], [ "# Line below will give you a hint\n#step_1.b.hint()", "_____no_output_____" ] ], [ [ "# Step 2: Generate test predictions\n\nNow, you'll use your trained model to generate predictions with the test data.", "_____no_output_____" ] ], [ [ "# Preprocessing of test data, fit model\npreds_test = my_pipeline.predict(X_test)\n\n# Check your answer\nstep_2.check()", "_____no_output_____" ], [ "# Lines below will give you a hint or solution code\n#step_2.hint()\n#step_2.solution()", "_____no_output_____" ] ], [ [ "Run the next code cell without changes to save your results to a CSV file that can be submitted directly to the competition.", "_____no_output_____" ] ], [ [ "# Save test predictions to file\noutput = pd.DataFrame({'Id': X_test.index,\n 'SalePrice': preds_test})\noutput.to_csv('submission.csv', index=False)", "_____no_output_____" ] ], [ [ "# Submit your results\n\nOnce you have successfully completed Step 2, you're ready to submit your results to the leaderboard! If you choose to do so, make sure that you have already joined the competition by clicking on the **Join Competition** button at [this link](https://www.kaggle.com/c/home-data-for-ml-course). \n1. Begin by clicking on the **Save Version** button in the top right corner of the window. This will generate a pop-up window. \n2. Ensure that the **Save and Run All** option is selected, and then click on the **Save** button.\n3. This generates a window in the bottom left corner of the notebook. After it has finished running, click on the number to the right of the **Save Version** button. This pulls up a list of versions on the right of the screen. Click on the ellipsis **(...)** to the right of the most recent version, and select **Open in Viewer**. This brings you into view mode of the same page. You will need to scroll down to get back to these instructions.\n4. Click on the **Output** tab on the right of the screen. Then, click on the file you would like to submit, and click on the **Submit** button to submit your results to the leaderboard.\n\nYou have now successfully submitted to the competition!\n\nIf you want to keep working to improve your performance, select the **Edit** button in the top right of the screen. Then you can change your code and repeat the process. There's a lot of room to improve, and you will climb up the leaderboard as you work.\n\n\n# Keep going\n\nMove on to learn about [**cross-validation**](https://www.kaggle.com/alexisbcook/cross-validation), a technique you can use to obtain more accurate estimates of model performance!", "_____no_output_____" ], [ "---\n\n\n\n\n*Have questions or comments? Visit the [course discussion forum](https://www.kaggle.com/learn/intermediate-machine-learning/discussion) to chat with other learners.*", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec5277cf71cebba3643b1a9564ce694dbf4680a1
5,276
ipynb
Jupyter Notebook
09_Time_Series/Getting_Financial_Data/Exercises.ipynb
BrownianNotion/pandas_exercises
b8cdb7164b231988a1815fbb54f186f5361f1467
[ "BSD-3-Clause" ]
null
null
null
09_Time_Series/Getting_Financial_Data/Exercises.ipynb
BrownianNotion/pandas_exercises
b8cdb7164b231988a1815fbb54f186f5361f1467
[ "BSD-3-Clause" ]
null
null
null
09_Time_Series/Getting_Financial_Data/Exercises.ipynb
BrownianNotion/pandas_exercises
b8cdb7164b231988a1815fbb54f186f5361f1467
[ "BSD-3-Clause" ]
null
null
null
24.769953
256
0.540751
[ [ [ "# Getting Financial Data - Pandas Datareader", "_____no_output_____" ], [ "### Introduction:\n\nThis time you will get data from a website.\n\n\n### Step 1. Import the necessary libraries", "_____no_output_____" ] ], [ [ "import pandas as pd", "_____no_output_____" ] ], [ [ "### Step 2. Create your time range (start and end variables). The start date should be 01/01/2015 and the end should today (whatever your today is).", "_____no_output_____" ] ], [ [ "date_range = pd.date_range(start='01/01/2015', end='01/26/2022')\ndate_range", "_____no_output_____" ] ], [ [ "### Step 3. Get an API key for one of the APIs that are supported by Pandas Datareader, preferably for AlphaVantage.\n\nIf you do not have an API key for any of the supported APIs, it is easiest to get one for [AlphaVantage](https://www.alphavantage.co/support/#api-key). (Note that the API key is shown directly after the signup. You do *not* receive it via e-mail.)\n\n(For a full list of the APIs that are supported by Pandas Datareader, [see here](https://pydata.github.io/pandas-datareader/readers/index.html). As the APIs are provided by third parties, this list may change.)", "_____no_output_____" ], [ "### Step 4. Use Pandas Datarader to read the daily time series for the Apple stock (ticker symbol AAPL) between 01/01/2015 and today, assign it to df_apple and print it.", "_____no_output_____" ], [ "### Step 5. Add a new column \"stock\" to the dataframe and add the ticker symbol", "_____no_output_____" ], [ "### Step 6. Repeat the two previous steps for a few other stocks, always creating a new dataframe: Tesla, IBM and Microsoft. (Ticker symbols TSLA, IBM and MSFT.)", "_____no_output_____" ], [ "### Step 7. Combine the four separate dataFrames into one combined dataFrame df that holds the information for all four stocks", "_____no_output_____" ], [ "### Step 8. Shift the stock column into the index (making it a multi-level index consisting of the ticker symbol and the date).", "_____no_output_____" ], [ "### Step 7. Create a dataFrame called vol, with the volume values.", "_____no_output_____" ], [ "### Step 8. Aggregate the data of volume to weekly.\nHint: Be careful to not sum data from the same week of 2015 and other years.", "_____no_output_____" ], [ "### Step 9. Find all the volume traded in the year of 2015", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
ec52826f50836fc06210c30f671634a9c62b4d12
111,844
ipynb
Jupyter Notebook
Sequence Models/Week 3/Neural_machine_translation_with_attention_v4a.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
ea2c69a818ae830ee6b62ae5674f08ab4b1cb4ea
[ "Apache-2.0" ]
null
null
null
Sequence Models/Week 3/Neural_machine_translation_with_attention_v4a.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
ea2c69a818ae830ee6b62ae5674f08ab4b1cb4ea
[ "Apache-2.0" ]
null
null
null
Sequence Models/Week 3/Neural_machine_translation_with_attention_v4a.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
ea2c69a818ae830ee6b62ae5674f08ab4b1cb4ea
[ "Apache-2.0" ]
null
null
null
60.950409
22,000
0.544884
[ [ [ "# Neural Machine Translation\n\nWelcome to your first programming assignment for this week! \n\n* You will build a Neural Machine Translation (NMT) model to translate human-readable dates (\"25th of June, 2009\") into machine-readable dates (\"2009-06-25\"). \n* You will do this using an attention model, one of the most sophisticated sequence-to-sequence models. \n\nThis notebook was produced together with NVIDIA's Deep Learning Institute. ", "_____no_output_____" ], [ "## Table of Contents\n\n- [Packages](#0)\n- [1 - Translating Human Readable Dates Into Machine Readable Dates](#1)\n - [1.1 - Dataset](#1-1)\n- [2 - Neural Machine Translation with Attention](#2)\n - [2.1 - Attention Mechanism](#2-1)\n - [Exercise 1 - one_step_attention](#ex-1)\n - [Exercise 2 - modelf](#ex-2)\n - [Exercise 3 - Compile the Model](#ex-3)\n- [3 - Visualizing Attention (Optional / Ungraded)](#3)\n - [3.1 - Getting the Attention Weights From the Network](#3-1)", "_____no_output_____" ], [ "<a name='0'></a>\n## Packages", "_____no_output_____" ] ], [ [ "from tensorflow.keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply\nfrom tensorflow.keras.layers import RepeatVector, Dense, Activation, Lambda\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import load_model, Model\nimport tensorflow.keras.backend as K\nimport tensorflow as tf\nimport numpy as np\n\nfrom faker import Faker\nimport random\nfrom tqdm import tqdm\nfrom babel.dates import format_date\nfrom nmt_utils import *\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ] ], [ [ "<a name='1'></a>\n## 1 - Translating Human Readable Dates Into Machine Readable Dates\n\n* The model you will build here could be used to translate from one language to another, such as translating from English to Hindi. \n* However, language translation requires massive datasets and usually takes days of training on GPUs. \n* To give you a place to experiment with these models without using massive datasets, we will perform a simpler \"date translation\" task. \n* The network will input a date written in a variety of possible formats (*e.g. \"the 29th of August 1958\", \"03/30/1968\", \"24 JUNE 1987\"*) \n* The network will translate them into standardized, machine readable dates (*e.g. \"1958-08-29\", \"1968-03-30\", \"1987-06-24\"*). \n* We will have the network learn to output dates in the common machine-readable format YYYY-MM-DD. \n\n<!-- \nTake a look at [nmt_utils.py](./nmt_utils.py) to see all the formatting. Count and figure out how the formats work, you will need this knowledge later. !--> ", "_____no_output_____" ], [ "<a name='1-1'></a>\n### 1.1 - Dataset\n\nWe will train the model on a dataset of 10,000 human readable dates and their equivalent, standardized, machine readable dates. Let's run the following cells to load the dataset and print some examples. ", "_____no_output_____" ] ], [ [ "m = 10000\ndataset, human_vocab, machine_vocab, inv_machine_vocab = load_dataset(m)", "100%|██████████| 10000/10000 [00:00<00:00, 22696.19it/s]\n" ], [ "dataset[:10]", "_____no_output_____" ] ], [ [ "You've loaded:\n- `dataset`: a list of tuples of (human readable date, machine readable date).\n- `human_vocab`: a python dictionary mapping all characters used in the human readable dates to an integer-valued index.\n- `machine_vocab`: a python dictionary mapping all characters used in machine readable dates to an integer-valued index. \n - **Note**: These indices are not necessarily consistent with `human_vocab`. \n- `inv_machine_vocab`: the inverse dictionary of `machine_vocab`, mapping from indices back to characters. \n\nLet's preprocess the data and map the raw text data into the index values. \n- We will set Tx=30 \n - We assume Tx is the maximum length of the human readable date.\n - If we get a longer input, we would have to truncate it.\n- We will set Ty=10\n - \"YYYY-MM-DD\" is 10 characters long.", "_____no_output_____" ] ], [ [ "Tx = 30\nTy = 10\nX, Y, Xoh, Yoh = preprocess_data(dataset, human_vocab, machine_vocab, Tx, Ty)\n\nprint(\"X.shape:\", X.shape)\nprint(\"Y.shape:\", Y.shape)\nprint(\"Xoh.shape:\", Xoh.shape)\nprint(\"Yoh.shape:\", Yoh.shape)", "X.shape: (10000, 30)\nY.shape: (10000, 10)\nXoh.shape: (10000, 30, 37)\nYoh.shape: (10000, 10, 11)\n" ] ], [ [ "You now have:\n- `X`: a processed version of the human readable dates in the training set.\n - Each character in X is replaced by an index (integer) mapped to the character using `human_vocab`. \n - Each date is padded to ensure a length of $T_x$ using a special character (< pad >). \n - `X.shape = (m, Tx)` where m is the number of training examples in a batch.\n- `Y`: a processed version of the machine readable dates in the training set.\n - Each character is replaced by the index (integer) it is mapped to in `machine_vocab`. \n - `Y.shape = (m, Ty)`. \n- `Xoh`: one-hot version of `X`\n - Each index in `X` is converted to the one-hot representation (if the index is 2, the one-hot version has the index position 2 set to 1, and the remaining positions are 0.\n - `Xoh.shape = (m, Tx, len(human_vocab))`\n- `Yoh`: one-hot version of `Y`\n - Each index in `Y` is converted to the one-hot representation. \n - `Yoh.shape = (m, Ty, len(machine_vocab))`. \n - `len(machine_vocab) = 11` since there are 10 numeric digits (0 to 9) and the `-` symbol.", "_____no_output_____" ], [ "* Let's also look at some examples of preprocessed training examples. \n* Feel free to play with `index` in the cell below to navigate the dataset and see how source/target dates are preprocessed. ", "_____no_output_____" ] ], [ [ "index = 0\nprint(\"Source date:\", dataset[index][0])\nprint(\"Target date:\", dataset[index][1])\nprint()\nprint(\"Source after preprocessing (indices):\", X[index])\nprint(\"Target after preprocessing (indices):\", Y[index])\nprint()\nprint(\"Source after preprocessing (one-hot):\", Xoh[index])\nprint(\"Target after preprocessing (one-hot):\", Yoh[index])", "Source date: 9 may 1998\nTarget date: 1998-05-09\n\nSource after preprocessing (indices): [12 0 24 13 34 0 4 12 12 11 36 36 36 36 36 36 36 36 36 36 36 36 36 36\n 36 36 36 36 36 36]\nTarget after preprocessing (indices): [ 2 10 10 9 0 1 6 0 1 10]\n\nSource after preprocessing (one-hot): [[0. 0. 0. ... 0. 0. 0.]\n [1. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n ...\n [0. 0. 0. ... 0. 0. 1.]\n [0. 0. 0. ... 0. 0. 1.]\n [0. 0. 0. ... 0. 0. 1.]]\nTarget after preprocessing (one-hot): [[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]\n [1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]\n [1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]\n" ] ], [ [ "<a name='2'></a>\n## 2 - Neural Machine Translation with Attention\n\n* If you had to translate a book's paragraph from French to English, you would not read the whole paragraph, then close the book and translate. \n* Even during the translation process, you would read/re-read and focus on the parts of the French paragraph corresponding to the parts of the English you are writing down. \n* The attention mechanism tells a Neural Machine Translation model where it should pay attention to at any step. \n\n<a name='2-1'></a>\n### 2.1 - Attention Mechanism\n\nIn this part, you will implement the attention mechanism presented in the lecture videos. \n* Here is a figure to remind you how the model works. \n * The diagram on the left shows the attention model. \n * The diagram on the right shows what one \"attention\" step does to calculate the attention variables $\\alpha^{\\langle t, t' \\rangle}$.\n * The attention variables $\\alpha^{\\langle t, t' \\rangle}$ are used to compute the context variable $context^{\\langle t \\rangle}$ for each timestep in the output ($t=1, \\ldots, T_y$). \n\n<table>\n<td> \n<img src=\"images/attn_model.png\" style=\"width:500;height:500px;\"> <br>\n</td> \n<td> \n<img src=\"images/attn_mechanism.png\" style=\"width:500;height:500px;\"> <br>\n</td> \n</table>\n<caption><center> **Figure 1**: Neural machine translation with attention</center></caption>\n", "_____no_output_____" ], [ "Here are some properties of the model that you may notice: \n\n#### Pre-attention and Post-attention LSTMs on both sides of the attention mechanism\n- There are two separate LSTMs in this model (see diagram on the left): pre-attention and post-attention LSTMs.\n- *Pre-attention* Bi-LSTM is the one at the bottom of the picture is a Bi-directional LSTM and comes *before* the attention mechanism.\n - The attention mechanism is shown in the middle of the left-hand diagram.\n - The pre-attention Bi-LSTM goes through $T_x$ time steps\n- *Post-attention* LSTM: at the top of the diagram comes *after* the attention mechanism. \n - The post-attention LSTM goes through $T_y$ time steps. \n\n- The post-attention LSTM passes the hidden state $s^{\\langle t \\rangle}$ and cell state $c^{\\langle t \\rangle}$ from one time step to the next. ", "_____no_output_____" ], [ "#### An LSTM has both a hidden state and cell state\n* In the lecture videos, we were using only a basic RNN for the post-attention sequence model\n * This means that the state captured by the RNN was outputting only the hidden state $s^{\\langle t\\rangle}$. \n* In this assignment, we are using an LSTM instead of a basic RNN.\n * So the LSTM has both the hidden state $s^{\\langle t\\rangle}$ and the cell state $c^{\\langle t\\rangle}$. ", "_____no_output_____" ], [ "#### Each time step does not use predictions from the previous time step\n* Unlike previous text generation examples earlier in the course, in this model, the post-attention LSTM at time $t$ does not take the previous time step's prediction $y^{\\langle t-1 \\rangle}$ as input.\n* The post-attention LSTM at time 't' only takes the hidden state $s^{\\langle t\\rangle}$ and cell state $c^{\\langle t\\rangle}$ as input. \n* We have designed the model this way because unlike language generation (where adjacent characters are highly correlated) there isn't as strong a dependency between the previous character and the next character in a YYYY-MM-DD date.", "_____no_output_____" ], [ "#### Concatenation of hidden states from the forward and backward pre-attention LSTMs\n- $\\overrightarrow{a}^{\\langle t \\rangle}$: hidden state of the forward-direction, pre-attention LSTM.\n- $\\overleftarrow{a}^{\\langle t \\rangle}$: hidden state of the backward-direction, pre-attention LSTM.\n- $a^{\\langle t \\rangle} = [\\overrightarrow{a}^{\\langle t \\rangle}, \\overleftarrow{a}^{\\langle t \\rangle}]$: the concatenation of the activations of both the forward-direction $\\overrightarrow{a}^{\\langle t \\rangle}$ and backward-directions $\\overleftarrow{a}^{\\langle t \\rangle}$ of the pre-attention Bi-LSTM. ", "_____no_output_____" ], [ "#### Computing \"energies\" $e^{\\langle t, t' \\rangle}$ as a function of $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t' \\rangle}$\n- Recall in the lesson videos \"Attention Model\", at time 6:45 to 8:16, the definition of \"e\" as a function of $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t \\rangle}$.\n - \"e\" is called the \"energies\" variable.\n - $s^{\\langle t-1 \\rangle}$ is the hidden state of the post-attention LSTM\n - $a^{\\langle t' \\rangle}$ is the hidden state of the pre-attention LSTM.\n - $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t \\rangle}$ are fed into a simple neural network, which learns the function to output $e^{\\langle t, t' \\rangle}$.\n - $e^{\\langle t, t' \\rangle}$ is then used when computing the attention $a^{\\langle t, t' \\rangle}$ that $y^{\\langle t \\rangle}$ should pay to $a^{\\langle t' \\rangle}$.", "_____no_output_____" ], [ "- The diagram on the right of figure 1 uses a `RepeatVector` node to copy $s^{\\langle t-1 \\rangle}$'s value $T_x$ times.\n- Then it uses `Concatenation` to concatenate $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t \\rangle}$.\n- The concatenation of $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t \\rangle}$ is fed into a \"Dense\" layer, which computes $e^{\\langle t, t' \\rangle}$. \n- $e^{\\langle t, t' \\rangle}$ is then passed through a softmax to compute $\\alpha^{\\langle t, t' \\rangle}$.\n- Note that the diagram doesn't explicitly show variable $e^{\\langle t, t' \\rangle}$, but $e^{\\langle t, t' \\rangle}$ is above the Dense layer and below the Softmax layer in the diagram in the right half of figure 1.\n- We'll explain how to use `RepeatVector` and `Concatenation` in Keras below. ", "_____no_output_____" ], [ "#### Implementation Details\n \nLet's implement this neural translator. You will start by implementing two functions: `one_step_attention()` and `model()`.\n\n#### one_step_attention\n* The inputs to the one_step_attention at time step $t$ are:\n - $[a^{<1>},a^{<2>}, ..., a^{<T_x>}]$: all hidden states of the pre-attention Bi-LSTM.\n - $s^{<t-1>}$: the previous hidden state of the post-attention LSTM \n* one_step_attention computes:\n - $[\\alpha^{<t,1>},\\alpha^{<t,2>}, ..., \\alpha^{<t,T_x>}]$: the attention weights\n - $context^{ \\langle t \\rangle }$: the context vector:\n \n$$context^{<t>} = \\sum_{t' = 1}^{T_x} \\alpha^{<t,t'>}a^{<t'>}\\tag{1}$$ \n\n##### Clarifying 'context' and 'c'\n- In the lecture videos, the context was denoted $c^{\\langle t \\rangle}$\n- In the assignment, we are calling the context $context^{\\langle t \\rangle}$.\n - This is to avoid confusion with the post-attention LSTM's internal memory cell variable, which is also denoted $c^{\\langle t \\rangle}$.", "_____no_output_____" ], [ "<a name='ex-1'></a>\n### Exercise 1 - one_step_attention \n\nImplement `one_step_attention()`. \n\n* The function `model()` will call the layers in `one_step_attention()` $T_y$ times using a for-loop.\n* It is important that all $T_y$ copies have the same weights. \n * It should not reinitialize the weights every time. \n * In other words, all $T_y$ steps should have shared weights. \n* Here's how you can implement layers with shareable weights in Keras:\n 1. Define the layer objects in a variable scope that is outside of the `one_step_attention` function. For example, defining the objects as global variables would work.\n - Note that defining these variables inside the scope of the function `model` would technically work, since `model` will then call the `one_step_attention` function. For the purposes of making grading and troubleshooting easier, we are defining these as global variables. Note that the automatic grader will expect these to be global variables as well.\n 2. Call these objects when propagating the input.\n* We have defined the layers you need as global variables. \n * Please run the following cells to create them. \n * Please note that the automatic grader expects these global variables with the given variable names. For grading purposes, please do not rename the global variables.\n* Please check the Keras documentation to learn more about these layers. The layers are functions. Below are examples of how to call these functions.\n * [RepeatVector()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/RepeatVector)\n```Python\nvar_repeated = repeat_layer(var1)\n```\n * [Concatenate()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Concatenate) \n```Python\nconcatenated_vars = concatenate_layer([var1,var2,var3])\n```\n * [Dense()](https://keras.io/layers/core/#dense) \n```Python\nvar_out = dense_layer(var_in)\n```\n * [Activation()](https://keras.io/layers/core/#activation) \n```Python\nactivation = activation_layer(var_in) \n```\n * [Dot()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dot) \n```Python\ndot_product = dot_layer([var1,var2])\n```", "_____no_output_____" ] ], [ [ "# Defined shared layers as global variables\nrepeator = RepeatVector(Tx)\nconcatenator = Concatenate(axis=-1)\ndensor1 = Dense(10, activation = \"tanh\")\ndensor2 = Dense(1, activation = \"relu\")\nactivator = Activation(softmax, name='attention_weights') # We are using a custom softmax(axis = 1) loaded in this notebook\ndotor = Dot(axes = 1)", "_____no_output_____" ], [ "# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: one_step_attention\n\ndef one_step_attention(a, s_prev):\n \"\"\"\n Performs one step of attention: Outputs a context vector computed as a dot product of the attention weights\n \"alphas\" and the hidden states \"a\" of the Bi-LSTM.\n \n Arguments:\n a -- hidden state output of the Bi-LSTM, numpy-array of shape (m, Tx, 2*n_a)\n s_prev -- previous hidden state of the (post-attention) LSTM, numpy-array of shape (m, n_s)\n \n Returns:\n context -- context vector, input of the next (post-attention) LSTM cell\n \"\"\"\n \n ### START CODE HERE ###\n # Use repeator to repeat s_prev to be of shape (m, Tx, n_s) so that you can concatenate it with all hidden states \"a\" (≈ 1 line)\n s_prev = repeator(s_prev)\n # Use concatenator to concatenate a and s_prev on the last axis (≈ 1 line)\n # For grading purposes, please list 'a' first and 's_prev' second, in this order.\n concat = concatenator([a,s_prev])\n # Use densor1 to propagate concat through a small fully-connected neural network to compute the \"intermediate energies\" variable e. (≈1 lines)\n e = densor1(concat)\n # Use densor2 to propagate e through a small fully-connected neural network to compute the \"energies\" variable energies. (≈1 lines)\n energies = densor2(e)\n # Use \"activator\" on \"energies\" to compute the attention weights \"alphas\" (≈ 1 line)\n alphas = activator(energies)\n # Use dotor together with \"alphas\" and \"a\", in this order, to compute the context vector to be given to the next (post-attention) LSTM-cell (≈ 1 line)\n context = dotor([alphas,a])\n ### END CODE HERE ###\n \n return context", "_____no_output_____" ], [ "# UNIT TEST\ndef one_step_attention_test(target):\n\n m = 10\n Tx = 30\n n_a = 32\n n_s = 64\n #np.random.seed(10)\n a = np.random.uniform(1, 0, (m, Tx, 2 * n_a)).astype(np.float32)\n s_prev =np.random.uniform(1, 0, (m, n_s)).astype(np.float32) * 1\n context = target(a, s_prev)\n \n assert type(context) == tf.python.framework.ops.EagerTensor, \"Unexpected type. It should be a Tensor\"\n assert tuple(context.shape) == (m, 1, n_s), \"Unexpected output shape\"\n assert np.all(context.numpy() > 0), \"All output values must be > 0 in this example\"\n assert np.all(context.numpy() < 1), \"All output values must be < 1 in this example\"\n\n #assert np.allclose(context[0][0][0:5].numpy(), [0.50877404, 0.57160693, 0.45448175, 0.50074816, 0.53651875]), \"Unexpected values in the result\"\n print(\"\\033[92mAll tests passed!\")\n \none_step_attention_test(one_step_attention)", "\u001b[92mAll tests passed!\n" ] ], [ [ "<a name='ex-2'></a>\n### Exercise 2 - modelf\n\nImplement `modelf()` as explained in figure 1 and the instructions:\n\n* `modelf` first runs the input through a Bi-LSTM to get $[a^{<1>},a^{<2>}, ..., a^{<T_x>}]$. \n* Then, `modelf` calls `one_step_attention()` $T_y$ times using a `for` loop. At each iteration of this loop:\n - It gives the computed context vector $context^{<t>}$ to the post-attention LSTM.\n - It runs the output of the post-attention LSTM through a dense layer with softmax activation.\n - The softmax generates a prediction $\\hat{y}^{<t>}$.\n \nAgain, we have defined global layers that will share weights to be used in `modelf()`.", "_____no_output_____" ] ], [ [ "n_a = 32 # number of units for the pre-attention, bi-directional LSTM's hidden state 'a'\nn_s = 64 # number of units for the post-attention LSTM's hidden state \"s\"\n\n# Please note, this is the post attention LSTM cell. \npost_activation_LSTM_cell = LSTM(n_s, return_state = True) # Please do not modify this global variable.\noutput_layer = Dense(len(machine_vocab), activation=softmax)", "_____no_output_____" ] ], [ [ "Now you can use these layers $T_y$ times in a `for` loop to generate the outputs, and their parameters will not be reinitialized. You will have to carry out the following steps: \n\n1. Propagate the input `X` into a bi-directional LSTM.\n * [Bidirectional](https://keras.io/layers/wrappers/#bidirectional) \n * [LSTM](https://keras.io/layers/recurrent/#lstm)\n * Remember that we want the LSTM to return a full sequence instead of just the last hidden state. \n \nSample code:\n\n```Python\nsequence_of_hidden_states = Bidirectional(LSTM(units=..., return_sequences=...))(the_input_X)\n```\n \n2. Iterate for $t = 0, \\cdots, T_y-1$: \n 1. Call `one_step_attention()`, passing in the sequence of hidden states $[a^{\\langle 1 \\rangle},a^{\\langle 2 \\rangle}, ..., a^{ \\langle T_x \\rangle}]$ from the pre-attention bi-directional LSTM, and the previous hidden state $s^{<t-1>}$ from the post-attention LSTM to calculate the context vector $context^{<t>}$.\n 2. Give $context^{<t>}$ to the post-attention LSTM cell. \n - Remember to pass in the previous hidden-state $s^{\\langle t-1\\rangle}$ and cell-states $c^{\\langle t-1\\rangle}$ of this LSTM \n * This outputs the new hidden state $s^{<t>}$ and the new cell state $c^{<t>}$. \n\n Sample code:\n ```Python\n next_hidden_state, _ , next_cell_state = \n post_activation_LSTM_cell(inputs=..., initial_state=[prev_hidden_state, prev_cell_state])\n ``` \n Please note that the layer is actually the \"post attention LSTM cell\". For the purposes of passing the automatic grader, please do not modify the naming of this global variable. This will be fixed when we deploy updates to the automatic grader.\n 3. Apply a dense, softmax layer to $s^{<t>}$, get the output. \n Sample code:\n ```Python\n output = output_layer(inputs=...)\n ```\n 4. Save the output by adding it to the list of outputs.\n\n3. Create your Keras model instance.\n * It should have three inputs:\n * `X`, the one-hot encoded inputs to the model, of shape ($T_{x}, humanVocabSize)$\n * $s^{\\langle 0 \\rangle}$, the initial hidden state of the post-attention LSTM\n * $c^{\\langle 0 \\rangle}$, the initial cell state of the post-attention LSTM\n * The output is the list of outputs. \n Sample code\n ```Python\n model = Model(inputs=[...,...,...], outputs=...)\n ```", "_____no_output_____" ] ], [ [ "# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: model\n\ndef modelf(Tx, Ty, n_a, n_s, human_vocab_size, machine_vocab_size):\n \"\"\"\n Arguments:\n Tx -- length of the input sequence\n Ty -- length of the output sequence\n n_a -- hidden state size of the Bi-LSTM\n n_s -- hidden state size of the post-attention LSTM\n human_vocab_size -- size of the python dictionary \"human_vocab\"\n machine_vocab_size -- size of the python dictionary \"machine_vocab\"\n\n Returns:\n model -- Keras model instance\n \"\"\"\n \n # Define the inputs of your model with a shape (Tx,)\n # Define s0 (initial hidden state) and c0 (initial cell state)\n # for the decoder LSTM with shape (n_s,)\n X = Input(shape=(Tx, human_vocab_size))\n s0 = Input(shape=(n_s,), name='s0')\n c0 = Input(shape=(n_s,), name='c0')\n s = s0\n c = c0\n \n # Initialize empty list of outputs\n outputs = []\n \n ### START CODE HERE ###\n \n # Step 1: Define your pre-attention Bi-LSTM. (≈ 1 line)\n a = Bidirectional(LSTM(n_a, return_sequences=True))(X) \n \n # Step 2: Iterate for Ty steps\n for t in range(Ty):\n \n # Step 2.A: Perform one step of the attention mechanism to get back the context vector at step t (≈ 1 line)\n context = one_step_attention(a, s)\n \n # Step 2.B: Apply the post-attention LSTM cell to the \"context\" vector.\n # Don't forget to pass: initial_state = [hidden state, cell state] (≈ 1 line)\n s, _, c = post_activation_LSTM_cell(context, initial_state=[s,c])\n \n # Step 2.C: Apply Dense layer to the hidden state output of the post-attention LSTM (≈ 1 line)\n out = output_layer(s)\n \n # Step 2.D: Append \"out\" to the \"outputs\" list (≈ 1 line)\n outputs.append(out)\n \n # Step 3: Create model instance taking three inputs and returning the list of outputs. (≈ 1 line)\n model = Model(inputs=[X,s0,c0], outputs=outputs)\n \n ### END CODE HERE ###\n \n return model", "_____no_output_____" ], [ "# UNIT TEST\nfrom test_utils import *\n\ndef modelf_test(target):\n m = 10\n Tx = 30\n n_a = 32\n n_s = 64\n len_human_vocab = 37\n len_machine_vocab = 11\n \n \n model = target(Tx, Ty, n_a, n_s, len_human_vocab, len_machine_vocab)\n \n print(summary(model))\n\n \n expected_summary = [['InputLayer', [(None, 30, 37)], 0],\n ['InputLayer', [(None, 64)], 0],\n ['Bidirectional', (None, 30, 64), 17920],\n ['RepeatVector', (None, 30, 64), 0, 30],\n ['Concatenate', (None, 30, 128), 0],\n ['Dense', (None, 30, 10), 1290, 'tanh'],\n ['Dense', (None, 30, 1), 11, 'relu'],\n ['Activation', (None, 30, 1), 0],\n ['Dot', (None, 1, 64), 0],\n ['InputLayer', [(None, 64)], 0],\n ['LSTM',[(None, 64), (None, 64), (None, 64)], 33024,[(None, 1, 64), (None, 64), (None, 64)],'tanh'],\n ['Dense', (None, 11), 715, 'softmax']]\n\n assert len(model.outputs) == 10, f\"Wrong output shape. Expected 10 != {len(model.outputs)}\"\n\n comparator(summary(model), expected_summary)\n \n\nmodelf_test(modelf)", "[['InputLayer', [(None, 30, 37)], 0], ['InputLayer', [(None, 64)], 0], ['Bidirectional', (None, 30, 64), 17920], ['RepeatVector', (None, 30, 64), 0, 30], ['Concatenate', (None, 30, 128), 0], ['Dense', (None, 30, 10), 1290, 'tanh'], ['Dense', (None, 30, 1), 11, 'relu'], ['Activation', (None, 30, 1), 0], ['Dot', (None, 1, 64), 0], ['InputLayer', [(None, 64)], 0], ['LSTM', [(None, 64), (None, 64), (None, 64)], 33024, [(None, 1, 64), (None, 64), (None, 64)], 'tanh'], ['Dense', (None, 11), 715, 'softmax']]\n\u001b[32mAll tests passed!\u001b[0m\n" ] ], [ [ "Run the following cell to create your model.", "_____no_output_____" ] ], [ [ "model = modelf(Tx, Ty, n_a, n_s, len(human_vocab), len(machine_vocab))", "_____no_output_____" ] ], [ [ "#### Troubleshooting Note\n* If you are getting repeated errors after an initially incorrect implementation of \"model\", but believe that you have corrected the error, you may still see error messages when building your model. \n* A solution is to save and restart your kernel (or shutdown then restart your notebook), and re-run the cells.", "_____no_output_____" ], [ "Let's get a summary of the model to check if it matches the expected output.", "_____no_output_____" ] ], [ [ "model.summary()", "Model: \"functional_3\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_2 (InputLayer) [(None, 30, 37)] 0 \n__________________________________________________________________________________________________\ns0 (InputLayer) [(None, 64)] 0 \n__________________________________________________________________________________________________\nbidirectional_1 (Bidirectional) (None, 30, 64) 17920 input_2[0][0] \n__________________________________________________________________________________________________\nrepeat_vector (RepeatVector) (None, 30, 64) 0 s0[0][0] \n lstm[10][0] \n lstm[11][0] \n lstm[12][0] \n lstm[13][0] \n lstm[14][0] \n lstm[15][0] \n lstm[16][0] \n lstm[17][0] \n lstm[18][0] \n__________________________________________________________________________________________________\nconcatenate (Concatenate) (None, 30, 128) 0 bidirectional_1[0][0] \n repeat_vector[10][0] \n bidirectional_1[0][0] \n repeat_vector[11][0] \n bidirectional_1[0][0] \n repeat_vector[12][0] \n bidirectional_1[0][0] \n repeat_vector[13][0] \n bidirectional_1[0][0] \n repeat_vector[14][0] \n bidirectional_1[0][0] \n repeat_vector[15][0] \n bidirectional_1[0][0] \n repeat_vector[16][0] \n bidirectional_1[0][0] \n repeat_vector[17][0] \n bidirectional_1[0][0] \n repeat_vector[18][0] \n bidirectional_1[0][0] \n repeat_vector[19][0] \n__________________________________________________________________________________________________\ndense (Dense) (None, 30, 10) 1290 concatenate[10][0] \n concatenate[11][0] \n concatenate[12][0] \n concatenate[13][0] \n concatenate[14][0] \n concatenate[15][0] \n concatenate[16][0] \n concatenate[17][0] \n concatenate[18][0] \n concatenate[19][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 30, 1) 11 dense[10][0] \n dense[11][0] \n dense[12][0] \n dense[13][0] \n dense[14][0] \n dense[15][0] \n dense[16][0] \n dense[17][0] \n dense[18][0] \n dense[19][0] \n__________________________________________________________________________________________________\nattention_weights (Activation) (None, 30, 1) 0 dense_1[10][0] \n dense_1[11][0] \n dense_1[12][0] \n dense_1[13][0] \n dense_1[14][0] \n dense_1[15][0] \n dense_1[16][0] \n dense_1[17][0] \n dense_1[18][0] \n dense_1[19][0] \n__________________________________________________________________________________________________\ndot (Dot) (None, 1, 64) 0 attention_weights[10][0] \n bidirectional_1[0][0] \n attention_weights[11][0] \n bidirectional_1[0][0] \n attention_weights[12][0] \n bidirectional_1[0][0] \n attention_weights[13][0] \n bidirectional_1[0][0] \n attention_weights[14][0] \n bidirectional_1[0][0] \n attention_weights[15][0] \n bidirectional_1[0][0] \n attention_weights[16][0] \n bidirectional_1[0][0] \n attention_weights[17][0] \n bidirectional_1[0][0] \n attention_weights[18][0] \n bidirectional_1[0][0] \n attention_weights[19][0] \n bidirectional_1[0][0] \n__________________________________________________________________________________________________\nc0 (InputLayer) [(None, 64)] 0 \n__________________________________________________________________________________________________\nlstm (LSTM) [(None, 64), (None, 33024 dot[10][0] \n s0[0][0] \n c0[0][0] \n dot[11][0] \n lstm[10][0] \n lstm[10][2] \n dot[12][0] \n lstm[11][0] \n lstm[11][2] \n dot[13][0] \n lstm[12][0] \n lstm[12][2] \n dot[14][0] \n lstm[13][0] \n lstm[13][2] \n dot[15][0] \n lstm[14][0] \n lstm[14][2] \n dot[16][0] \n lstm[15][0] \n lstm[15][2] \n dot[17][0] \n lstm[16][0] \n lstm[16][2] \n dot[18][0] \n lstm[17][0] \n lstm[17][2] \n dot[19][0] \n lstm[18][0] \n lstm[18][2] \n__________________________________________________________________________________________________\ndense_2 (Dense) (None, 11) 715 lstm[10][0] \n lstm[11][0] \n lstm[12][0] \n lstm[13][0] \n lstm[14][0] \n lstm[15][0] \n lstm[16][0] \n lstm[17][0] \n lstm[18][0] \n lstm[19][0] \n==================================================================================================\nTotal params: 52,960\nTrainable params: 52,960\nNon-trainable params: 0\n__________________________________________________________________________________________________\n" ] ], [ [ "**Expected Output**:\n\nHere is the summary you should see\n<table>\n <tr>\n <td>\n **Total params:**\n </td>\n <td>\n 52,960\n </td>\n </tr>\n <tr>\n <td>\n **Trainable params:**\n </td>\n <td>\n 52,960\n </td>\n </tr>\n <tr>\n <td>\n **Non-trainable params:**\n </td>\n <td>\n 0\n </td>\n </tr>\n <tr>\n <td>\n **bidirectional_1's output shape **\n </td>\n <td>\n (None, 30, 64) \n </td>\n </tr>\n <tr>\n <td>\n **repeat_vector_1's output shape **\n </td>\n <td>\n (None, 30, 64) \n </td>\n </tr>\n <tr>\n <td>\n **concatenate_1's output shape **\n </td>\n <td>\n (None, 30, 128) \n </td>\n </tr>\n <tr>\n <td>\n **attention_weights's output shape **\n </td>\n <td>\n (None, 30, 1) \n </td>\n </tr>\n <tr>\n <td>\n **dot_1's output shape **\n </td>\n <td>\n (None, 1, 64)\n </td>\n </tr>\n <tr>\n <td>\n **dense_3's output shape **\n </td>\n <td>\n (None, 11) \n </td>\n </tr>\n</table>\n", "_____no_output_____" ], [ "<a name='ex-3'></a>\n### Exercise 3 - Compile the Model\n\n* After creating your model in Keras, you need to compile it and define the loss function, optimizer and metrics you want to use. \n * Loss function: 'categorical_crossentropy'.\n * Optimizer: [Adam](https://keras.io/optimizers/#adam) [optimizer](https://keras.io/optimizers/#usage-of-optimizers)\n - learning rate = 0.005 \n - $\\beta_1 = 0.9$\n - $\\beta_2 = 0.999$\n - decay = 0.01 \n * metric: 'accuracy'\n \nSample code\n```Python\noptimizer = Adam(lr=..., beta_1=..., beta_2=..., decay=...)\nmodel.compile(optimizer=..., loss=..., metrics=[...])\n```", "_____no_output_____" ] ], [ [ "### START CODE HERE ### (≈2 lines)\nopt = Adam(lr = 0.005, beta_1 = 0.9, beta_2 = 0.999, decay = 0.01) # Adam(...) \nmodel.compile(loss = 'categorical_crossentropy', optimizer = opt, metrics = ['accuracy'])\n### END CODE HERE ###", "_____no_output_____" ], [ "# UNIT TESTS\nassert opt.lr == 0.005, \"Set the lr parameter to 0.005\"\nassert opt.beta_1 == 0.9, \"Set the beta_1 parameter to 0.9\"\nassert opt.beta_2 == 0.999, \"Set the beta_2 parameter to 0.999\"\nassert opt.decay == 0.01, \"Set the decay parameter to 0.01\"\nassert model.loss == \"categorical_crossentropy\", \"Wrong loss. Use 'categorical_crossentropy'\"\nassert model.optimizer == opt, \"Use the optimizer that you have instantiated\"\nassert model.compiled_metrics._user_metrics[0] == 'accuracy', \"set metrics to ['accuracy']\"\n\nprint(\"\\033[92mAll tests passed!\")", "\u001b[92mAll tests passed!\n" ] ], [ [ "#### Define inputs and outputs, and fit the model\nThe last step is to define all your inputs and outputs to fit the model:\n- You have input `Xoh` of shape $(m = 10000, T_x = 30, human\\_vocab=37)$ containing the training examples.\n- You need to create `s0` and `c0` to initialize your `post_attention_LSTM_cell` with zeros.\n- Given the `model()` you coded, you need the \"outputs\" to be a list of 10 elements of shape (m, T_y). \n - The list `outputs[i][0], ..., outputs[i][Ty]` represents the true labels (characters) corresponding to the $i^{th}$ training example (`Xoh[i]`). \n - `outputs[i][j]` is the true label of the $j^{th}$ character in the $i^{th}$ training example.", "_____no_output_____" ] ], [ [ "s0 = np.zeros((m, n_s))\nc0 = np.zeros((m, n_s))\noutputs = list(Yoh.swapaxes(0,1))", "_____no_output_____" ] ], [ [ "Let's now fit the model and run it for one epoch.", "_____no_output_____" ] ], [ [ "model.fit([Xoh, s0, c0], outputs, epochs=1, batch_size=100)", "100/100 [==============================] - 12s 121ms/step - loss: 16.5964 - dense_2_loss: 1.2297 - dense_2_1_loss: 1.0620 - dense_2_2_loss: 1.8013 - dense_2_3_loss: 2.6791 - dense_2_4_loss: 0.7472 - dense_2_5_loss: 1.2728 - dense_2_6_loss: 2.6736 - dense_2_7_loss: 0.8648 - dense_2_8_loss: 1.6747 - dense_2_9_loss: 2.5912 - dense_2_accuracy: 0.5137 - dense_2_1_accuracy: 0.6880 - dense_2_2_accuracy: 0.3048 - dense_2_3_accuracy: 0.0857 - dense_2_4_accuracy: 0.9580 - dense_2_5_accuracy: 0.3436 - dense_2_6_accuracy: 0.0539 - dense_2_7_accuracy: 0.9422 - dense_2_8_accuracy: 0.2493 - dense_2_9_accuracy: 0.1002\n" ] ], [ [ "While training you can see the loss as well as the accuracy on each of the 10 positions of the output. The table below gives you an example of what the accuracies could be if the batch had 2 examples: \n\n<img src=\"images/table.png\" style=\"width:700;height:200px;\"> <br>\n<caption><center>Thus, `dense_2_acc_8: 0.89` means that you are predicting the 7th character of the output correctly 89% of the time in the current batch of data. </center></caption>\n\n\nWe have run this model for longer, and saved the weights. Run the next cell to load our weights. (By training a model for several minutes, you should be able to obtain a model of similar accuracy, but loading our model will save you time.) ", "_____no_output_____" ] ], [ [ "model.load_weights('models/model.h5')", "_____no_output_____" ] ], [ [ "You can now see the results on new examples.", "_____no_output_____" ] ], [ [ "EXAMPLES = ['3 May 1979', '5 April 09', '21th of August 2016', 'Tue 10 Jul 2007', 'Saturday May 9 2018', 'March 3 2001', 'March 3rd 2001', '1 March 2001']\ns00 = np.zeros((1, n_s))\nc00 = np.zeros((1, n_s))\nfor example in EXAMPLES:\n source = string_to_int(example, Tx, human_vocab)\n #print(source)\n source = np.array(list(map(lambda x: to_categorical(x, num_classes=len(human_vocab)), source))).swapaxes(0,1)\n source = np.swapaxes(source, 0, 1)\n source = np.expand_dims(source, axis=0)\n prediction = model.predict([source, s00, c00])\n prediction = np.argmax(prediction, axis = -1)\n output = [inv_machine_vocab[int(i)] for i in prediction]\n print(\"source:\", example)\n print(\"output:\", ''.join(output),\"\\n\")", "source: 3 May 1979\noutput: 1979-05-33 \n\nsource: 5 April 09\noutput: 2009-04-05 \n\nsource: 21th of August 2016\noutput: 2016-08-20 \n\nsource: Tue 10 Jul 2007\noutput: 2007-07-10 \n\nsource: Saturday May 9 2018\noutput: 2018-05-09 \n\nsource: March 3 2001\noutput: 2001-03-03 \n\nsource: March 3rd 2001\noutput: 2001-03-03 \n\nsource: 1 March 2001\noutput: 2001-03-01 \n\n" ] ], [ [ "You can also change these examples to test with your own examples. The next part will give you a better sense of what the attention mechanism is doing--i.e., what part of the input the network is paying attention to when generating a particular output character. ", "_____no_output_____" ], [ "<a name='3'></a>\n## 3 - Visualizing Attention (Optional / Ungraded)\n\nSince the problem has a fixed output length of 10, it is also possible to carry out this task using 10 different softmax units to generate the 10 characters of the output. But one advantage of the attention model is that each part of the output (such as the month) knows it needs to depend only on a small part of the input (the characters in the input giving the month). We can visualize what each part of the output is looking at which part of the input.\n\nConsider the task of translating \"Saturday 9 May 2018\" to \"2018-05-09\". If we visualize the computed $\\alpha^{\\langle t, t' \\rangle}$ we get this: \n\n<img src=\"images/date_attention.png\" style=\"width:600;height:300px;\"> <br>\n<caption><center> **Figure 8**: Full Attention Map</center></caption>\n\nNotice how the output ignores the \"Saturday\" portion of the input. None of the output timesteps are paying much attention to that portion of the input. We also see that 9 has been translated as 09 and May has been correctly translated into 05, with the output paying attention to the parts of the input it needs to to make the translation. The year mostly requires it to pay attention to the input's \"18\" in order to generate \"2018.\" ", "_____no_output_____" ], [ "<a name='3-1'></a>\n### 3.1 - Getting the Attention Weights From the Network\n\nLets now visualize the attention values in your network. We'll propagate an example through the network, then visualize the values of $\\alpha^{\\langle t, t' \\rangle}$. \n\nTo figure out where the attention values are located, let's start by printing a summary of the model .", "_____no_output_____" ] ], [ [ "model.summary()", "Model: \"functional_3\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_2 (InputLayer) [(None, 30, 37)] 0 \n__________________________________________________________________________________________________\ns0 (InputLayer) [(None, 64)] 0 \n__________________________________________________________________________________________________\nbidirectional_1 (Bidirectional) (None, 30, 64) 17920 input_2[0][0] \n__________________________________________________________________________________________________\nrepeat_vector (RepeatVector) (None, 30, 64) 0 s0[0][0] \n lstm[10][0] \n lstm[11][0] \n lstm[12][0] \n lstm[13][0] \n lstm[14][0] \n lstm[15][0] \n lstm[16][0] \n lstm[17][0] \n lstm[18][0] \n__________________________________________________________________________________________________\nconcatenate (Concatenate) (None, 30, 128) 0 bidirectional_1[0][0] \n repeat_vector[10][0] \n bidirectional_1[0][0] \n repeat_vector[11][0] \n bidirectional_1[0][0] \n repeat_vector[12][0] \n bidirectional_1[0][0] \n repeat_vector[13][0] \n bidirectional_1[0][0] \n repeat_vector[14][0] \n bidirectional_1[0][0] \n repeat_vector[15][0] \n bidirectional_1[0][0] \n repeat_vector[16][0] \n bidirectional_1[0][0] \n repeat_vector[17][0] \n bidirectional_1[0][0] \n repeat_vector[18][0] \n bidirectional_1[0][0] \n repeat_vector[19][0] \n__________________________________________________________________________________________________\ndense (Dense) (None, 30, 10) 1290 concatenate[10][0] \n concatenate[11][0] \n concatenate[12][0] \n concatenate[13][0] \n concatenate[14][0] \n concatenate[15][0] \n concatenate[16][0] \n concatenate[17][0] \n concatenate[18][0] \n concatenate[19][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 30, 1) 11 dense[10][0] \n dense[11][0] \n dense[12][0] \n dense[13][0] \n dense[14][0] \n dense[15][0] \n dense[16][0] \n dense[17][0] \n dense[18][0] \n dense[19][0] \n__________________________________________________________________________________________________\nattention_weights (Activation) (None, 30, 1) 0 dense_1[10][0] \n dense_1[11][0] \n dense_1[12][0] \n dense_1[13][0] \n dense_1[14][0] \n dense_1[15][0] \n dense_1[16][0] \n dense_1[17][0] \n dense_1[18][0] \n dense_1[19][0] \n__________________________________________________________________________________________________\ndot (Dot) (None, 1, 64) 0 attention_weights[10][0] \n bidirectional_1[0][0] \n attention_weights[11][0] \n bidirectional_1[0][0] \n attention_weights[12][0] \n bidirectional_1[0][0] \n attention_weights[13][0] \n bidirectional_1[0][0] \n attention_weights[14][0] \n bidirectional_1[0][0] \n attention_weights[15][0] \n bidirectional_1[0][0] \n attention_weights[16][0] \n bidirectional_1[0][0] \n attention_weights[17][0] \n bidirectional_1[0][0] \n attention_weights[18][0] \n bidirectional_1[0][0] \n attention_weights[19][0] \n bidirectional_1[0][0] \n__________________________________________________________________________________________________\nc0 (InputLayer) [(None, 64)] 0 \n__________________________________________________________________________________________________\nlstm (LSTM) [(None, 64), (None, 33024 dot[10][0] \n s0[0][0] \n c0[0][0] \n dot[11][0] \n lstm[10][0] \n lstm[10][2] \n dot[12][0] \n lstm[11][0] \n lstm[11][2] \n dot[13][0] \n lstm[12][0] \n lstm[12][2] \n dot[14][0] \n lstm[13][0] \n lstm[13][2] \n dot[15][0] \n lstm[14][0] \n lstm[14][2] \n dot[16][0] \n lstm[15][0] \n lstm[15][2] \n dot[17][0] \n lstm[16][0] \n lstm[16][2] \n dot[18][0] \n lstm[17][0] \n lstm[17][2] \n dot[19][0] \n lstm[18][0] \n lstm[18][2] \n__________________________________________________________________________________________________\ndense_2 (Dense) (None, 11) 715 lstm[10][0] \n lstm[11][0] \n lstm[12][0] \n lstm[13][0] \n lstm[14][0] \n lstm[15][0] \n lstm[16][0] \n lstm[17][0] \n lstm[18][0] \n lstm[19][0] \n==================================================================================================\nTotal params: 52,960\nTrainable params: 52,960\nNon-trainable params: 0\n__________________________________________________________________________________________________\n" ] ], [ [ "Navigate through the output of `model.summary()` above. You can see that the layer named `attention_weights` outputs the `alphas` of shape (m, 30, 1) before `dot_2` computes the context vector for every time step $t = 0, \\ldots, T_y-1$. Let's get the attention weights from this layer.\n\nThe function `attention_map()` pulls out the attention values from your model and plots them.\n\n**Note**: We are aware that you might run into an error running the cell below despite a valid implementation for Exercise 2 - `modelf` above. If you get the error kindly report it on this [Topic](https://discourse.deeplearning.ai/t/error-in-optional-ungraded-part-of-neural-machine-translation-w3a1/1096) on [Discourse](https://discourse.deeplearning.ai) as it'll help us improve our content. \n\nIf you haven’t joined our Discourse community you can do so by clicking on the link: http://bit.ly/dls-discourse\n\nAnd don’t worry about the error, it will not affect the grading for this assignment.", "_____no_output_____" ] ], [ [ "attention_map = plot_attention_map(model, human_vocab, inv_machine_vocab, \"Tuesday 09 Oct 1993\", num = 7, n_s = 64);", "_____no_output_____" ] ], [ [ "On the generated plot you can observe the values of the attention weights for each character of the predicted output. Examine this plot and check that the places where the network is paying attention makes sense to you.\n\nIn the date translation application, you will observe that most of the time attention helps predict the year, and doesn't have much impact on predicting the day or month.", "_____no_output_____" ], [ "### Congratulations!\n\n\nYou have come to the end of this assignment \n\n#### Here's what you should remember\n\n- Machine translation models can be used to map from one sequence to another. They are useful not just for translating human languages (like French->English) but also for tasks like date format translation. \n- An attention mechanism allows a network to focus on the most relevant parts of the input when producing a specific part of the output. \n- A network using an attention mechanism can translate from inputs of length $T_x$ to outputs of length $T_y$, where $T_x$ and $T_y$ can be different. \n- You can visualize attention weights $\\alpha^{\\langle t,t' \\rangle}$ to see what the network is paying attention to while generating each output.", "_____no_output_____" ], [ "Congratulations on finishing this assignment! You are now able to implement an attention model and use it to learn complex mappings from one sequence to another. ", "_____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" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
ec52897ac9596eba4c2bc7fac17713026dca7c4d
384,679
ipynb
Jupyter Notebook
Tutorials/Boston Housing - Updating an Endpoint.ipynb
Marius1311/udacity_deployment
58f59f3c3bd417e3efda47a761ec41bba7120f43
[ "MIT" ]
null
null
null
Tutorials/Boston Housing - Updating an Endpoint.ipynb
Marius1311/udacity_deployment
58f59f3c3bd417e3efda47a761ec41bba7120f43
[ "MIT" ]
null
null
null
Tutorials/Boston Housing - Updating an Endpoint.ipynb
Marius1311/udacity_deployment
58f59f3c3bd417e3efda47a761ec41bba7120f43
[ "MIT" ]
null
null
null
117.891204
1,493
0.593955
[ [ [ "# Predicting Boston Housing Prices\n\n## Updating a model using SageMaker\n\n_Deep Learning Nanodegree Program | Deployment_\n\n---\n\nIn this notebook, we will continue working with the [Boston Housing Dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html). Our goal in this notebook will be to train two different models and to use SageMaker to switch a deployed endpoint from using one model to the other. One of the benefits of using SageMaker to do this is that we can make the change without interrupting service. What this means is that we can continue sending data to the endpoint and at no point will that endpoint disappear.\n\n## General Outline\n\nTypically, when using a notebook instance with SageMaker, you will proceed through the following steps. Of course, not every step will need to be done with each project. Also, there is quite a lot of room for variation in many of the steps, as you will see throughout these lessons.\n\n1. Download or otherwise retrieve the data.\n2. Process / Prepare the data.\n3. Upload the processed data to S3.\n4. Train a chosen model.\n5. Test the trained model (typically using a batch transform job).\n6. Deploy the trained model.\n7. Use the deployed model.\n\nIn this notebook we will be skipping step 5, testing the model. In addition, we will perform steps 4, 6 and 7 multiple times with different models.", "_____no_output_____" ], [ "## Step 0: Setting up the notebook\n\nWe begin by setting up all of the necessary bits required to run our notebook. To start that means loading all of the Python modules we will need.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport os\n\nimport numpy as np\nimport pandas as pd\n\nfrom pprint import pprint\nimport matplotlib.pyplot as plt\nfrom time import gmtime, strftime\n\nfrom sklearn.datasets import load_boston\nimport sklearn.model_selection", "_____no_output_____" ] ], [ [ "In addition to the modules above, we need to import the various bits of SageMaker that we will be using. ", "_____no_output_____" ] ], [ [ "import sagemaker\nfrom sagemaker import get_execution_role\nfrom sagemaker.amazon.amazon_estimator import get_image_uri\nfrom sagemaker.predictor import csv_serializer\n\n# This is an object that represents the SageMaker session that we are currently operating in. This\n# object contains some useful information that we will need to access later such as our region.\nsession = sagemaker.Session()\n\n# This is an object that represents the IAM role that we are currently assigned. When we construct\n# and launch the training job later we will need to tell it what IAM role it should have. Since our\n# use case is relatively simple we will simply assign the training job the role we currently have.\nrole = get_execution_role()", "_____no_output_____" ] ], [ [ "## Step 1: Downloading the data\n\nFortunately, this dataset can be retrieved using sklearn and so this step is relatively straightforward.", "_____no_output_____" ] ], [ [ "boston = load_boston()", "_____no_output_____" ] ], [ [ "## Step 2: Preparing and splitting the data\n\nGiven that this is clean tabular data, we don't need to do any processing. However, we do need to split the rows in the dataset up into train, test and validation sets.", "_____no_output_____" ] ], [ [ "# First we package up the input data and the target variable (the median value) as pandas dataframes. This\n# will make saving the data to a file a little easier later on.\n\nX_bos_pd = pd.DataFrame(boston.data, columns=boston.feature_names)\nY_bos_pd = pd.DataFrame(boston.target)\n\n# We split the dataset into 2/3 training and 1/3 testing sets.\nX_train, X_test, Y_train, Y_test = sklearn.model_selection.train_test_split(X_bos_pd, Y_bos_pd, test_size=0.33)\n\n# Then we split the training set further into 2/3 training and 1/3 validation sets.\nX_train, X_val, Y_train, Y_val = sklearn.model_selection.train_test_split(X_train, Y_train, test_size=0.33)", "_____no_output_____" ] ], [ [ "## Step 3: Uploading the training and validation files to S3\n\nWhen a training job is constructed using SageMaker, a container is executed which performs the training operation. This container is given access to data that is stored in S3. This means that we need to upload the data we want to use for training to S3. We can use the SageMaker API to do this and hide some of the details.\n\n### Save the data locally\n\nFirst we need to create the train and validation csv files which we will then upload to S3.", "_____no_output_____" ] ], [ [ "# This is our local data directory. We need to make sure that it exists.\ndata_dir = '../data/boston'\nif not os.path.exists(data_dir):\n os.makedirs(data_dir)", "_____no_output_____" ], [ "# We use pandas to save our train and validation data to csv files. Note that we make sure not to include header\n# information or an index as this is required by the built in algorithms provided by Amazon. Also, it is assumed\n# that the first entry in each row is the target variable.\n\npd.concat([Y_val, X_val], axis=1).to_csv(os.path.join(data_dir, 'validation.csv'), header=False, index=False)\npd.concat([Y_train, X_train], axis=1).to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False)", "_____no_output_____" ] ], [ [ "### Upload to S3\n\nSince we are currently running inside of a SageMaker session, we can use the object which represents this session to upload our data to the 'default' S3 bucket. Note that it is good practice to provide a custom prefix (essentially an S3 folder) to make sure that you don't accidentally interfere with data uploaded from some other notebook or project.", "_____no_output_____" ] ], [ [ "prefix = 'boston-update-endpoints'\n\nval_location = session.upload_data(os.path.join(data_dir, 'validation.csv'), key_prefix=prefix)\ntrain_location = session.upload_data(os.path.join(data_dir, 'train.csv'), key_prefix=prefix)", "_____no_output_____" ] ], [ [ "## Step 4 (A): Train the XGBoost model\n\nNow that we have the training and validation data uploaded to S3, we can construct our XGBoost model and train it. We will be making use of the high level SageMaker API to do this which will make the resulting code a little easier to read at the cost of some flexibility.\n\nTo construct an estimator, the object which we wish to train, we need to provide the location of a container which contains the training code. Since we are using a built in algorithm this container is provided by Amazon. However, the full name of the container is a bit lengthy and depends on the region that we are operating in. Fortunately, SageMaker provides a useful utility method called `get_image_uri` that constructs the image name for us.\n\nTo use the `get_image_uri` method we need to provide it with our current region, which can be obtained from the session object, and the name of the algorithm we wish to use. In this notebook we will be using XGBoost however you could try another algorithm if you wish. The list of built in algorithms can be found in the list of [Common Parameters](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html).", "_____no_output_____" ] ], [ [ "# As stated above, we use this utility method to construct the image name for the training container.\nxgb_container = get_image_uri(session.boto_region_name, 'xgboost')\n\n# Now that we know which container to use, we can construct the estimator object.\nxgb = sagemaker.estimator.Estimator(xgb_container, # The name of the training container\n role, # The IAM role to use (our current role in this case)\n train_instance_count=1, # The number of instances to use for training\n train_instance_type='ml.m4.xlarge', # The type of instance ot use for training\n output_path='s3://{}/{}/output'.format(session.default_bucket(), prefix),\n # Where to save the output (the model artifacts)\n sagemaker_session=session) # The current SageMaker session", "_____no_output_____" ] ], [ [ "Before asking SageMaker to begin the training job, we should probably set any model specific hyperparameters. There are quite a few that can be set when using the XGBoost algorithm, below are just a few of them. If you would like to change the hyperparameters below or modify additional ones you can find additional information on the [XGBoost hyperparameter page](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost_hyperparameters.html)", "_____no_output_____" ] ], [ [ "xgb.set_hyperparameters(max_depth=5,\n eta=0.2,\n gamma=4,\n min_child_weight=6,\n subsample=0.8,\n objective='reg:linear',\n early_stopping_rounds=10,\n num_round=200)", "_____no_output_____" ] ], [ [ "Now that we have our estimator object completely set up, it is time to train it. To do this we make sure that SageMaker knows our input data is in csv format and then execute the `fit` method.", "_____no_output_____" ] ], [ [ "# This is a wrapper around the location of our train and validation data, to make sure that SageMaker\n# knows our data is in csv format.\ns3_input_train = sagemaker.s3_input(s3_data=train_location, content_type='text/csv')\ns3_input_validation = sagemaker.s3_input(s3_data=val_location, content_type='text/csv')\n\nxgb.fit({'train': s3_input_train, 'validation': s3_input_validation})", "INFO:sagemaker:Creating training-job with name: xgboost-2019-04-06-13-13-15-076\n" ] ], [ [ "## Step 5: Test the trained model\n\nWe will be skipping this step for now.\n\n\n## Step 6 (A): Deploy the trained model\n\nEven though we used the high level approach to construct and train the XGBoost model, we will be using the lower level approach to deploy it. One of the reasons for this is so that we have additional control over how the endpoint is constructed. This will be a little more clear later on when construct more advanced endpoints.\n\n### Build the model\n\nOf course, before we can deploy the model, we need to first create it. The `fit` method that we used earlier created some model artifacts and we can use these to construct a model object.", "_____no_output_____" ] ], [ [ "# Remember that a model needs to have a unique name\nxgb_model_name = \"boston-update-xgboost-model\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\n# We also need to tell SageMaker which container should be used for inference and where it should\n# retrieve the model artifacts from. In our case, the xgboost container that we used for training\n# can also be used for inference and the model artifacts come from the previous call to fit.\nxgb_primary_container = {\n \"Image\": xgb_container,\n \"ModelDataUrl\": xgb.model_data\n}\n\n# And lastly we construct the SageMaker model\nxgb_model_info = session.sagemaker_client.create_model(\n ModelName = xgb_model_name,\n ExecutionRoleArn = role,\n PrimaryContainer = xgb_primary_container)", "_____no_output_____" ] ], [ [ "### Create the endpoint configuration\n\nOnce we have a model we can start putting together the endpoint. Recall that to do this we need to first create an endpoint configuration, essentially the blueprint that SageMaker will use to build the endpoint itself.", "_____no_output_____" ] ], [ [ "# As before, we need to give our endpoint configuration a name which should be unique\nxgb_endpoint_config_name = \"boston-update-xgboost-endpoint-config-\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\n# And then we ask SageMaker to construct the endpoint configuration\nxgb_endpoint_config_info = session.sagemaker_client.create_endpoint_config(\n EndpointConfigName = xgb_endpoint_config_name,\n ProductionVariants = [{\n \"InstanceType\": \"ml.m4.xlarge\",\n \"InitialVariantWeight\": 1,\n \"InitialInstanceCount\": 1,\n \"ModelName\": xgb_model_name,\n \"VariantName\": \"XGB-Model\"\n }])", "_____no_output_____" ] ], [ [ "### Deploy the endpoint\n\nNow that the endpoint configuration has been created, we can ask SageMaker to build our endpoint.\n\n**Note:** This is a friendly (repeated) reminder that you are about to deploy an endpoint. Make sure that you shut it down once you've finished with it!", "_____no_output_____" ] ], [ [ "# Again, we need a unique name for our endpoint\nendpoint_name = \"boston-update-endpoint-\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\n# we pass over the configurations we created above by passing xgb_endpoint_config_name\n\n# And then we can deploy our endpoint\nendpoint_info = session.sagemaker_client.create_endpoint(\n EndpointName = endpoint_name,\n EndpointConfigName = xgb_endpoint_config_name)", "_____no_output_____" ], [ "endpoint_dec = session.wait_for_endpoint(endpoint_name)", "--------------------------------------------------------------!" ] ], [ [ "## Step 7 (A): Use the model\n\nNow that our model is trained and deployed we can send some test data to it and evaluate the results.", "_____no_output_____" ] ], [ [ "# that is the first sample in this dataframe\nX_test.values[0]", "_____no_output_____" ], [ "# the following command serializes this first row of the dataframe\n', '.join(map(str, X_test.values[0]))", "_____no_output_____" ], [ "response = session.sagemaker_runtime_client.invoke_endpoint(\n EndpointName = endpoint_name,\n ContentType = 'text/csv',\n Body = ','.join(map(str, X_test.values[0])))", "_____no_output_____" ], [ "pprint(response)", "{'Body': <botocore.response.StreamingBody object at 0x7fc8752d8898>,\n 'ContentType': 'text/csv; charset=utf-8',\n 'InvokedProductionVariant': 'XGB-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '13',\n 'content-type': 'text/csv; charset=utf-8',\n 'date': 'Sat, 6 Apr 2019 13:22:24 GMT',\n 'x-amzn-invoked-production-variant': 'XGB-Model',\n 'x-amzn-requestid': 'f7fc23ea-70b3-4e53-a08d-2156252b9b92'},\n 'HTTPStatusCode': 200,\n 'RequestId': 'f7fc23ea-70b3-4e53-a08d-2156252b9b92',\n 'RetryAttempts': 0}}\n" ], [ "result = response['Body'].read().decode(\"utf-8\")", "_____no_output_____" ], [ "pprint(result)", "'15.4057502747'\n" ], [ "Y_test.values[0]", "_____no_output_____" ] ], [ [ "## Shut down the endpoint\n\nNow that we know that the XGBoost endpoint works, we can shut it down. We will make use of it again later.", "_____no_output_____" ] ], [ [ "session.sagemaker_client.delete_endpoint(EndpointName = endpoint_name)", "_____no_output_____" ] ], [ [ "## Step 4 (B): Train the Linear model\n\nSuppose we are working in an environment where the XGBoost model that we trained earlier is becoming too costly. Perhaps the number of calls to our endpoint has increased and the length of time it takes to perform inference with the XGBoost model is becoming problematic.\n\nA possible solution might be to train a simpler model to see if it performs nearly as well. In our case, we will construct a linear model. The process of doing this is the same as for creating the XGBoost model that we created earlier, although there are different hyperparameters that we need to set.", "_____no_output_____" ] ], [ [ "linear_container = get_image_uri(session.boto_region_name, 'linear-learner')", "_____no_output_____" ], [ "linear_container", "_____no_output_____" ], [ "linear = sagemaker.estimator.Estimator(linear_container,\n role,\n train_instance_count=1,\n train_instance_type='ml.m4.xlarge',\n output_path='s3://{}/{}/output'.format(session.default_bucket(), prefix),\n sagemaker_session=session)", "_____no_output_____" ], [ "# Similar to the XGBoost model, we will use the utility method to construct the image name for the training container.\nlinear_container = get_image_uri(session.boto_region_name, 'linear-learner')\n\n# Now that we know which container to use, we can construct the estimator object.\nlinear = sagemaker.estimator.Estimator(linear_container, # The name of the training container\n role, # The IAM role to use (our current role in this case)\n train_instance_count=1, # The number of instances to use for training\n train_instance_type='ml.m4.xlarge', # The type of instance ot use for training\n output_path='s3://{}/{}/output'.format(session.default_bucket(), prefix),\n # Where to save the output (the model artifacts)\n sagemaker_session=session) # The current SageMaker session", "_____no_output_____" ] ], [ [ "Before asking SageMaker to train our model, we need to set some hyperparameters. In this case we will be using a linear model so the number of hyperparameters we need to set is much fewer. For more details see the [Linear model hyperparameter page](https://docs.aws.amazon.com/sagemaker/latest/dg/ll_hyperparameters.html)", "_____no_output_____" ] ], [ [ "linear.set_hyperparameters(feature_dim=13, # Our data has 13 feature columns\n predictor_type='regressor', # We wish to create a regression model\n mini_batch_size=200) # Here we set how many samples to look at in each iteration", "_____no_output_____" ] ], [ [ "Now that the hyperparameters have been set, we can ask SageMaker to fit the linear model to our data.", "_____no_output_____" ] ], [ [ "linear.fit({'train': s3_input_train, 'validation': s3_input_validation})", "INFO:sagemaker:Creating training-job with name: linear-learner-2019-04-06-13-29-09-733\n" ] ], [ [ "## Step 6 (B): Deploy the trained model\n\nSimilar to the XGBoost model, now that we've fit the model we need to deploy it. Also like the XGBoost model, we will use the lower level approach so that we have more control over the endpoint that gets created.\n\n### Build the model\n\nOf course, before we can deploy the model, we need to first create it. The `fit` method that we used earlier created some model artifacts and we can use these to construct a model object.", "_____no_output_____" ] ], [ [ "linear_model_name = \"boston-upadte-linear-model\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())", "_____no_output_____" ], [ "linear_primary_container = {\n \"Image\": linear_container,\n \"ModelDataUrl\": linear.model_data\n}", "_____no_output_____" ], [ "linear_model_info = session.sagemaker_client.create_model(\nModelName = linear_model_name,\nExecutionRoleArn = role,\nPrimaryContainer = linear_primary_container)", "_____no_output_____" ], [ "# First, we create a unique model name\nlinear_model_name = \"boston-update-linear-model\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\n# We also need to tell SageMaker which container should be used for inference and where it should\n# retrieve the model artifacts from. In our case, the linear-learner container that we used for training\n# can also be used for inference.\nlinear_primary_container = {\n \"Image\": linear_container,\n \"ModelDataUrl\": linear.model_data\n}\n\n# And lastly we construct the SageMaker model\nlinear_model_info = session.sagemaker_client.create_model(\n ModelName = linear_model_name,\n ExecutionRoleArn = role,\n PrimaryContainer = linear_primary_container)", "_____no_output_____" ] ], [ [ "### Create the endpoint configuration\n\nOnce we have the model we can start putting together the endpoint by creating an endpoint configuration.", "_____no_output_____" ] ], [ [ "# As before, we need to give our endpoint configuration a name which should be unique\nlinear_endpoint_config_name = \"boston-linear-endpoint-config-\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\n# And then we ask SageMaker to construct the endpoint configuration\nlinear_endpoint_config_info = session.sagemaker_client.create_endpoint_config(\n EndpointConfigName = linear_endpoint_config_name,\n ProductionVariants = [{\n \"InstanceType\": \"ml.m4.xlarge\",\n \"InitialVariantWeight\": 1,\n \"InitialInstanceCount\": 1,\n \"ModelName\": linear_model_name,\n \"VariantName\": \"Linear-Model\"\n }])", "_____no_output_____" ] ], [ [ "### Deploy the endpoint\n\nNow that the endpoint configuration has been created, we can ask SageMaker to build our endpoint.\n\n**Note:** This is a friendly (repeated) reminder that you are about to deploy an endpoint. Make sure that you shut it down once you've finished with it!", "_____no_output_____" ] ], [ [ "# Again, we need a unique name for our endpoint\nendpoint_name = \"boston-update-endpoint-\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\n# And then we can deploy our endpoint\nendpoint_info = session.sagemaker_client.create_endpoint(\n EndpointName = endpoint_name,\n EndpointConfigName = linear_endpoint_config_name)", "_____no_output_____" ], [ "endpoint_dec = session.wait_for_endpoint(endpoint_name)", "--------------------------------------------------------------------------!" ] ], [ [ "## Step 7 (B): Use the model\n\nJust like with the XGBoost model, we will send some data to our endpoint to make sure that it is working properly. An important note is that the output format for the linear model is different from the XGBoost model.", "_____no_output_____" ] ], [ [ "response = session.sagemaker_runtime_client.invoke_endpoint(\n EndpointName = endpoint_name,\n ContentType = 'text/csv',\n Body = ','.join(map(str, X_test.values[0])))", "_____no_output_____" ], [ "pprint(response)", "{'Body': <botocore.response.StreamingBody object at 0x7fc8747f1550>,\n 'ContentType': 'application/json',\n 'InvokedProductionVariant': 'Linear-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '48',\n 'content-type': 'application/json',\n 'date': 'Sat, 6 Apr 2019 13:39:12 GMT',\n 'x-amzn-invoked-production-variant': 'Linear-Model',\n 'x-amzn-requestid': '6a699c4c-2f0a-4737-83d2-2bf02374dceb'},\n 'HTTPStatusCode': 200,\n 'RequestId': '6a699c4c-2f0a-4737-83d2-2bf02374dceb',\n 'RetryAttempts': 0}}\n" ], [ "result = response['Body'].read().decode(\"utf-8\")", "_____no_output_____" ], [ "pprint(result)", "'{\"predictions\": [{\"score\": 16.032089233398438}]}'\n" ], [ "Y_test.values[0]", "_____no_output_____" ] ], [ [ "## Shut down the endpoint\n\nNow that we know that the Linear model's endpoint works, we can shut it down.", "_____no_output_____" ] ], [ [ "session.sagemaker_client.delete_endpoint(EndpointName = endpoint_name)", "_____no_output_____" ] ], [ [ "## Step 6 (C): Deploy a combined model\n\nSo far we've constructed two separate models which we could deploy and use. Before we talk about how we can change a deployed endpoint from one configuration to another, let's consider a slightly different situation. Suppose that before we switch from using only the XGBoost model to only the Linear model, we first want to do something like an A-B test, where we send some of the incoming data to the XGBoost model and some of the data to the Linear model.\n\nFortunately, SageMaker provides this functionality. And to actually get SageMaker to do this for us is not too different from deploying a model in the way that we've already done. The only difference is that we need to list more than one model in the production variants parameter of the endpoint configuration.\n\nA reasonable question to ask is, how much data is sent to each of the models that I list in the production variants parameter? The answer is that it depends on the weight set for each model.\n\nSuppose that we have $k$ models listed in the production variants and that each model $i$ is assigned the weight $w_i$. Then each model $i$ will receive $w_i / W$ of the traffic where $W = \\sum_{i} w_i$.\n\nIn our case, since we have two models, the linear model and the XGBoost model, and each model has weight 1, we see that each model will get 1 / (1 + 1) = 1/2 of the data sent to the endpoint.", "_____no_output_____" ] ], [ [ "combined_endpoint_config_name = \"boston-combined-endpoint-config\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())", "_____no_output_____" ], [ "combined_endpoint_config_info = session.sagemaker_client.create_endpoint_config(\nEndpointConfigName = combined_endpoint_config_name,\nProductionVariants=[\n {# First the linear model\n \"InstanceType\": \"ml.m4.xlarge\",\n \"InitialVariantWeight\":1,\n \"InitialInstanceCount\":1,\n \"ModelName\": linear_model_name,\n \"VariantName\": \"Linear-Model\"\n }, {\n # include the xgb model\n \"InstanceType\": \"ml.m4.xlarge\",\n \"InitialVariantWeight\": 1,\n \"InitialInstanceCount\": 1,\n \"ModelName\": xgb_model_name,\n \"VariantName\": \"XGB-Model\"\n }\n])", "_____no_output_____" ], [ "# As before, we need to give our endpoint configuration a name which should be unique\ncombined_endpoint_config_name = \"boston-combined-endpoint-config-\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\n# And then we ask SageMaker to construct the endpoint configuration\ncombined_endpoint_config_info = session.sagemaker_client.create_endpoint_config(\n EndpointConfigName = combined_endpoint_config_name,\n ProductionVariants = [\n { # First we include the linear model\n \"InstanceType\": \"ml.m4.xlarge\",\n \"InitialVariantWeight\": 1,\n \"InitialInstanceCount\": 1,\n \"ModelName\": linear_model_name,\n \"VariantName\": \"Linear-Model\"\n }, { # And next we include the xgb model\n \"InstanceType\": \"ml.m4.xlarge\",\n \"InitialVariantWeight\": 1,\n \"InitialInstanceCount\": 1,\n \"ModelName\": xgb_model_name,\n \"VariantName\": \"XGB-Model\"\n }])", "_____no_output_____" ] ], [ [ "Now that we've created the endpoint configuration, we can ask SageMaker to construct the endpoint.\n\n**Note:** This is a friendly (repeated) reminder that you are about to deploy an endpoint. Make sure that you shut it down once you've finished with it!", "_____no_output_____" ] ], [ [ "# Again, we need a unique name for our endpoint\nendpoint_name = \"boston-update-endpoint-\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\n# And then we can deploy our endpoint\nendpoint_info = session.sagemaker_client.create_endpoint(\n EndpointName = endpoint_name,\n EndpointConfigName = combined_endpoint_config_name)", "_____no_output_____" ], [ "endpoint_dec = session.wait_for_endpoint(endpoint_name)", "---------------------------------------------------------------------------!" ] ], [ [ "## Step 7 (C): Use the model\n\nNow that we've constructed an endpoint which sends data to both the XGBoost model and the linear model we can send some data to the endpoint and see what sort of results we get back.", "_____no_output_____" ] ], [ [ "response = session.sagemaker_runtime_client.invoke_endpoint(\n EndpointName = endpoint_name,\n ContentType = 'text/csv',\n Body = ','.join(map(str, X_test.values[0])))\npprint(response)", "{'Body': <botocore.response.StreamingBody object at 0x7fc874735438>,\n 'ContentType': 'text/csv; charset=utf-8',\n 'InvokedProductionVariant': 'XGB-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '13',\n 'content-type': 'text/csv; charset=utf-8',\n 'date': 'Sat, 6 Apr 2019 13:46:30 GMT',\n 'x-amzn-invoked-production-variant': 'XGB-Model',\n 'x-amzn-requestid': 'b083002c-35c1-4edb-898e-559c5c0738f5'},\n 'HTTPStatusCode': 200,\n 'RequestId': 'b083002c-35c1-4edb-898e-559c5c0738f5',\n 'RetryAttempts': 0}}\n" ] ], [ [ "Since looking at a single response doesn't give us a clear look at what is happening, we can instead take a look at a few different responses to our endpoint", "_____no_output_____" ] ], [ [ "for rec in range(10):\n response = session.sagemaker_runtime_client.invoke_endpoint(\n EndpointName = endpoint_name,\n ContentType = 'text/csv',\n Body = ','.join(map(str, X_test.values[rec])))\n pprint(response)\n result = response['Body'].read().decode(\"utf-8\")\n print(result)\n print(Y_test.values[rec])", "{'Body': <botocore.response.StreamingBody object at 0x7fc874735c88>,\n 'ContentType': 'application/json',\n 'InvokedProductionVariant': 'Linear-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '48',\n 'content-type': 'application/json',\n 'date': 'Sat, 6 Apr 2019 13:46:43 GMT',\n 'x-amzn-invoked-production-variant': 'Linear-Model',\n 'x-amzn-requestid': 'b201476e-992e-41a0-a199-61225aa1973a'},\n 'HTTPStatusCode': 200,\n 'RequestId': 'b201476e-992e-41a0-a199-61225aa1973a',\n 'RetryAttempts': 0}}\n{\"predictions\": [{\"score\": 16.032089233398438}]}\n[13.4]\n{'Body': <botocore.response.StreamingBody object at 0x7fc874735dd8>,\n 'ContentType': 'text/csv; charset=utf-8',\n 'InvokedProductionVariant': 'XGB-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '11',\n 'content-type': 'text/csv; charset=utf-8',\n 'date': 'Sat, 6 Apr 2019 13:46:44 GMT',\n 'x-amzn-invoked-production-variant': 'XGB-Model',\n 'x-amzn-requestid': '83ee1eff-7b86-4f7d-bad4-ed063136d4d8'},\n 'HTTPStatusCode': 200,\n 'RequestId': '83ee1eff-7b86-4f7d-bad4-ed063136d4d8',\n 'RetryAttempts': 0}}\n18.48802948\n[17.6]\n{'Body': <botocore.response.StreamingBody object at 0x7fc87473c048>,\n 'ContentType': 'text/csv; charset=utf-8',\n 'InvokedProductionVariant': 'XGB-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '13',\n 'content-type': 'text/csv; charset=utf-8',\n 'date': 'Sat, 6 Apr 2019 13:46:44 GMT',\n 'x-amzn-invoked-production-variant': 'XGB-Model',\n 'x-amzn-requestid': '1c5668ed-962d-4911-9536-200707d34e79'},\n 'HTTPStatusCode': 200,\n 'RequestId': '1c5668ed-962d-4911-9536-200707d34e79',\n 'RetryAttempts': 0}}\n49.2618789673\n[50.]\n{'Body': <botocore.response.StreamingBody object at 0x7fc87473c278>,\n 'ContentType': 'application/json',\n 'InvokedProductionVariant': 'Linear-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '48',\n 'content-type': 'application/json',\n 'date': 'Sat, 6 Apr 2019 13:46:44 GMT',\n 'x-amzn-invoked-production-variant': 'Linear-Model',\n 'x-amzn-requestid': '623ad249-938f-48b5-8a4f-f945898eb304'},\n 'HTTPStatusCode': 200,\n 'RequestId': '623ad249-938f-48b5-8a4f-f945898eb304',\n 'RetryAttempts': 0}}\n{\"predictions\": [{\"score\": 15.197037696838379}]}\n[14.]\n{'Body': <botocore.response.StreamingBody object at 0x7fc87473c4a8>,\n 'ContentType': 'application/json',\n 'InvokedProductionVariant': 'Linear-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '48',\n 'content-type': 'application/json',\n 'date': 'Sat, 6 Apr 2019 13:46:44 GMT',\n 'x-amzn-invoked-production-variant': 'Linear-Model',\n 'x-amzn-requestid': '1dd3bcda-3fc4-4641-bb16-63dc1c534d02'},\n 'HTTPStatusCode': 200,\n 'RequestId': '1dd3bcda-3fc4-4641-bb16-63dc1c534d02',\n 'RetryAttempts': 0}}\n{\"predictions\": [{\"score\": 18.265228271484375}]}\n[19.6]\n{'Body': <botocore.response.StreamingBody object at 0x7fc87473c6d8>,\n 'ContentType': 'application/json',\n 'InvokedProductionVariant': 'Linear-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '48',\n 'content-type': 'application/json',\n 'date': 'Sat, 6 Apr 2019 13:46:44 GMT',\n 'x-amzn-invoked-production-variant': 'Linear-Model',\n 'x-amzn-requestid': '81d1719d-aec7-442a-aef8-7eaaa795d1ce'},\n 'HTTPStatusCode': 200,\n 'RequestId': '81d1719d-aec7-442a-aef8-7eaaa795d1ce',\n 'RetryAttempts': 0}}\n{\"predictions\": [{\"score\": 20.137454986572266}]}\n[19.2]\n{'Body': <botocore.response.StreamingBody object at 0x7fc87473c908>,\n 'ContentType': 'text/csv; charset=utf-8',\n 'InvokedProductionVariant': 'XGB-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '13',\n 'content-type': 'text/csv; charset=utf-8',\n 'date': 'Sat, 6 Apr 2019 13:46:44 GMT',\n 'x-amzn-invoked-production-variant': 'XGB-Model',\n 'x-amzn-requestid': '0baf6df8-0e9b-432f-b860-a777682ffda4'},\n 'HTTPStatusCode': 200,\n 'RequestId': '0baf6df8-0e9b-432f-b860-a777682ffda4',\n 'RetryAttempts': 0}}\n8.63937950134\n[8.3]\n{'Body': <botocore.response.StreamingBody object at 0x7fc87473cb38>,\n 'ContentType': 'text/csv; charset=utf-8',\n 'InvokedProductionVariant': 'XGB-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '12',\n 'content-type': 'text/csv; charset=utf-8',\n 'date': 'Sat, 6 Apr 2019 13:46:44 GMT',\n 'x-amzn-invoked-production-variant': 'XGB-Model',\n 'x-amzn-requestid': '6c33ffb5-a436-4b6b-bbe7-2312f902afaf'},\n 'HTTPStatusCode': 200,\n 'RequestId': '6c33ffb5-a436-4b6b-bbe7-2312f902afaf',\n 'RetryAttempts': 0}}\n15.225894928\n[13.1]\n{'Body': <botocore.response.StreamingBody object at 0x7fc87473cd68>,\n 'ContentType': 'text/csv; charset=utf-8',\n 'InvokedProductionVariant': 'XGB-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '13',\n 'content-type': 'text/csv; charset=utf-8',\n 'date': 'Sat, 6 Apr 2019 13:46:44 GMT',\n 'x-amzn-invoked-production-variant': 'XGB-Model',\n 'x-amzn-requestid': 'a31fbb18-a635-4c5f-8311-716e003a787b'},\n 'HTTPStatusCode': 200,\n 'RequestId': 'a31fbb18-a635-4c5f-8311-716e003a787b',\n 'RetryAttempts': 0}}\n16.6175460815\n[16.4]\n{'Body': <botocore.response.StreamingBody object at 0x7fc87473cf98>,\n 'ContentType': 'text/csv; charset=utf-8',\n 'InvokedProductionVariant': 'XGB-Model',\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '13',\n 'content-type': 'text/csv; charset=utf-8',\n 'date': 'Sat, 6 Apr 2019 13:46:44 GMT',\n 'x-amzn-invoked-production-variant': 'XGB-Model',\n 'x-amzn-requestid': '45a0889e-2e35-4c8a-afc8-b9e1f9c12ac2'},\n 'HTTPStatusCode': 200,\n 'RequestId': '45a0889e-2e35-4c8a-afc8-b9e1f9c12ac2',\n 'RetryAttempts': 0}}\n28.3570671082\n[30.8]\n" ] ], [ [ "If at some point we aren't sure about the properties of a deployed endpoint, we can use the `describe_endpoint` function to get SageMaker to return a description of the deployed endpoint.", "_____no_output_____" ] ], [ [ "pprint(session.sagemaker_client.describe_endpoint(EndpointName=endpoint_name))", "{'CreationTime': datetime.datetime(2019, 4, 6, 13, 39, 42, 114000, tzinfo=tzlocal()),\n 'EndpointArn': 'arn:aws:sagemaker:eu-west-1:288115630859:endpoint/boston-update-endpoint-2019-04-06-13-39-42',\n 'EndpointConfigName': 'boston-combined-endpoint-config2019-04-06-13-39-22',\n 'EndpointName': 'boston-update-endpoint-2019-04-06-13-39-42',\n 'EndpointStatus': 'InService',\n 'LastModifiedTime': datetime.datetime(2019, 4, 6, 13, 45, 57, 99000, tzinfo=tzlocal()),\n 'ProductionVariants': [{'CurrentInstanceCount': 1,\n 'CurrentWeight': 1.0,\n 'DeployedImages': [{'ResolutionTime': datetime.datetime(2019, 4, 6, 13, 39, 44, 153000, tzinfo=tzlocal()),\n 'ResolvedImage': '438346466558.dkr.ecr.eu-west-1.amazonaws.com/linear-learner@sha256:ae84ef3af074a245f82d03f3b2e1a1310f4a4246d1bf03001a9900fd012aec05',\n 'SpecifiedImage': '438346466558.dkr.ecr.eu-west-1.amazonaws.com/linear-learner:1'}],\n 'DesiredInstanceCount': 1,\n 'DesiredWeight': 1.0,\n 'VariantName': 'Linear-Model'},\n {'CurrentInstanceCount': 1,\n 'CurrentWeight': 1.0,\n 'DeployedImages': [{'ResolutionTime': datetime.datetime(2019, 4, 6, 13, 39, 44, 206000, tzinfo=tzlocal()),\n 'ResolvedImage': '685385470294.dkr.ecr.eu-west-1.amazonaws.com/xgboost@sha256:f4035605aa6947463e77da9512337296c96173f34117f475cea9869bbdc0a799',\n 'SpecifiedImage': '685385470294.dkr.ecr.eu-west-1.amazonaws.com/xgboost:1'}],\n 'DesiredInstanceCount': 1,\n 'DesiredWeight': 1.0,\n 'VariantName': 'XGB-Model'}],\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '1161',\n 'content-type': 'application/x-amz-json-1.1',\n 'date': 'Sat, 06 Apr 2019 13:46:55 GMT',\n 'x-amzn-requestid': '22cc1c2b-4299-419b-b7aa-c90c937037e1'},\n 'HTTPStatusCode': 200,\n 'RequestId': '22cc1c2b-4299-419b-b7aa-c90c937037e1',\n 'RetryAttempts': 0}}\n" ] ], [ [ "## Updating an Endpoint\n\nNow suppose that we've done our A-B test and the new linear model is working well enough. What we'd like to do now is to switch our endpoint from sending data to both the XGBoost model and the linear model to sending data only to the linear model.\n\nOf course, we don't really want to shut down the endpoint to do this as doing so would interrupt service to whoever depends on our endpoint. Instead, we can ask SageMaker to **update** an endpoint to a new endpoint configuration.\n\nWhat is actually happening is that SageMaker will set up a new endpoint with the new characteristics. Once this new endpoint is running, SageMaker will switch the old endpoint so that it now points at the newly deployed model, making sure that this happens seamlessly in the background.", "_____no_output_____" ] ], [ [ "session.sagemaker_client.update_endpoint(EndpointName=endpoint_name, EndpointConfigName=linear_endpoint_config_name)", "_____no_output_____" ] ], [ [ "To get a glimpse at what is going on, we can ask SageMaker to describe our in-use endpoint now, before the update process has completed. When we do so, we can see that the in-use endpoint still has the same characteristics it had before.", "_____no_output_____" ] ], [ [ "pprint(session.sagemaker_client.describe_endpoint(EndpointName=endpoint_name))", "{'CreationTime': datetime.datetime(2019, 4, 6, 13, 39, 42, 114000, tzinfo=tzlocal()),\n 'EndpointArn': 'arn:aws:sagemaker:eu-west-1:288115630859:endpoint/boston-update-endpoint-2019-04-06-13-39-42',\n 'EndpointConfigName': 'boston-combined-endpoint-config2019-04-06-13-39-22',\n 'EndpointName': 'boston-update-endpoint-2019-04-06-13-39-42',\n 'EndpointStatus': 'Updating',\n 'LastModifiedTime': datetime.datetime(2019, 4, 6, 13, 47, 37, 455000, tzinfo=tzlocal()),\n 'ProductionVariants': [{'CurrentInstanceCount': 1,\n 'CurrentWeight': 1.0,\n 'DeployedImages': [{'ResolutionTime': datetime.datetime(2019, 4, 6, 13, 39, 44, 153000, tzinfo=tzlocal()),\n 'ResolvedImage': '438346466558.dkr.ecr.eu-west-1.amazonaws.com/linear-learner@sha256:ae84ef3af074a245f82d03f3b2e1a1310f4a4246d1bf03001a9900fd012aec05',\n 'SpecifiedImage': '438346466558.dkr.ecr.eu-west-1.amazonaws.com/linear-learner:1'}],\n 'DesiredInstanceCount': 1,\n 'DesiredWeight': 1.0,\n 'VariantName': 'Linear-Model'},\n {'CurrentInstanceCount': 1,\n 'CurrentWeight': 1.0,\n 'DeployedImages': [{'ResolutionTime': datetime.datetime(2019, 4, 6, 13, 39, 44, 206000, tzinfo=tzlocal()),\n 'ResolvedImage': '685385470294.dkr.ecr.eu-west-1.amazonaws.com/xgboost@sha256:f4035605aa6947463e77da9512337296c96173f34117f475cea9869bbdc0a799',\n 'SpecifiedImage': '685385470294.dkr.ecr.eu-west-1.amazonaws.com/xgboost:1'}],\n 'DesiredInstanceCount': 1,\n 'DesiredWeight': 1.0,\n 'VariantName': 'XGB-Model'}],\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '1160',\n 'content-type': 'application/x-amz-json-1.1',\n 'date': 'Sat, 06 Apr 2019 13:47:49 GMT',\n 'x-amzn-requestid': '2dfe038e-36fb-41ec-9a9a-28d6a4278d97'},\n 'HTTPStatusCode': 200,\n 'RequestId': '2dfe038e-36fb-41ec-9a9a-28d6a4278d97',\n 'RetryAttempts': 0}}\n" ] ], [ [ "If we now wait for the update process to complete, and then ask SageMaker to describe the endpoint, it will return the characteristics of the new endpoint configuration.", "_____no_output_____" ] ], [ [ "endpoint_dec = session.wait_for_endpoint(endpoint_name)", "-----------------------------------------------------------------------!" ], [ "pprint(session.sagemaker_client.describe_endpoint(EndpointName=endpoint_name))", "{'CreationTime': datetime.datetime(2019, 4, 6, 13, 39, 42, 114000, tzinfo=tzlocal()),\n 'EndpointArn': 'arn:aws:sagemaker:eu-west-1:288115630859:endpoint/boston-update-endpoint-2019-04-06-13-39-42',\n 'EndpointConfigName': 'boston-linear-endpoint-config-2019-04-06-13-32-43',\n 'EndpointName': 'boston-update-endpoint-2019-04-06-13-39-42',\n 'EndpointStatus': 'InService',\n 'LastModifiedTime': datetime.datetime(2019, 4, 6, 13, 53, 54, 108000, tzinfo=tzlocal()),\n 'ProductionVariants': [{'CurrentInstanceCount': 1,\n 'CurrentWeight': 1.0,\n 'DeployedImages': [{'ResolutionTime': datetime.datetime(2019, 4, 6, 13, 47, 39, 504000, tzinfo=tzlocal()),\n 'ResolvedImage': '438346466558.dkr.ecr.eu-west-1.amazonaws.com/linear-learner@sha256:ae84ef3af074a245f82d03f3b2e1a1310f4a4246d1bf03001a9900fd012aec05',\n 'SpecifiedImage': '438346466558.dkr.ecr.eu-west-1.amazonaws.com/linear-learner:1'}],\n 'DesiredInstanceCount': 1,\n 'DesiredWeight': 1.0,\n 'VariantName': 'Linear-Model'}],\n 'ResponseMetadata': {'HTTPHeaders': {'content-length': '770',\n 'content-type': 'application/x-amz-json-1.1',\n 'date': 'Sat, 06 Apr 2019 13:55:04 GMT',\n 'x-amzn-requestid': '31d5c5ba-8221-45bd-9708-7fac40ae71f9'},\n 'HTTPStatusCode': 200,\n 'RequestId': '31d5c5ba-8221-45bd-9708-7fac40ae71f9',\n 'RetryAttempts': 0}}\n" ] ], [ [ "## Shut down the endpoint\n\nNow that we've finished, we need to make sure to shut down the endpoint.", "_____no_output_____" ] ], [ [ "session.sagemaker_client.delete_endpoint(EndpointName = endpoint_name)", "_____no_output_____" ] ], [ [ "## Optional: Clean up\n\nThe default notebook instance on SageMaker doesn't have a lot of excess disk space available. As you continue to complete and execute notebooks you will eventually fill up this disk space, leading to errors which can be difficult to diagnose. Once you are completely finished using a notebook it is a good idea to remove the files that you created along the way. Of course, you can do this from the terminal or from the notebook hub if you would like. The cell below contains some commands to clean up the created files from within the notebook.", "_____no_output_____" ] ], [ [ "# First we will remove all of the files contained in the data_dir directory\n!rm $data_dir/*\n\n# And then we delete the directory itself\n!rmdir $data_dir", "_____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", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec528d9fb0a93e0ee8223e84d60cd00c2ee7ce28
407,286
ipynb
Jupyter Notebook
GB/arousal_classificationGB.ipynb
bandarads/video_emotion_prediction
65c4c6bfd9ee81375f1b26d62e59e64f736aae48
[ "MIT" ]
null
null
null
GB/arousal_classificationGB.ipynb
bandarads/video_emotion_prediction
65c4c6bfd9ee81375f1b26d62e59e64f736aae48
[ "MIT" ]
null
null
null
GB/arousal_classificationGB.ipynb
bandarads/video_emotion_prediction
65c4c6bfd9ee81375f1b26d62e59e64f736aae48
[ "MIT" ]
1
2020-11-12T22:10:30.000Z
2020-11-12T22:10:30.000Z
1,153.784703
199,741
0.939767
[ [ [ "import numpy as np\nimport os\nimport PIL\nimport PIL.Image\nimport tensorflow as tf\nimport seaborn as sns\nprint(tf.__version__)\nbatch_size = 32\nimg_height = 180\nimg_width = 180\ndata_root=\"\\\\Users\\\\George\\\\Documents\\\\Python\\\\ADS CapStone\\\\aff_wild_annotations_bboxes_landmarks_new\\\\dataset_arousal\\\\\"", "2.4.1\n" ], [ "\ntrain_ds = tf.keras.preprocessing.image_dataset_from_directory(\n data_root+'train',\n validation_split=0.2,\n subset=\"training\",\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)\nval_ds = tf.keras.preprocessing.image_dataset_from_directory(\n data_root+'train',\n validation_split=0.2,\n subset=\"validation\",\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)\ntest_ds = tf.keras.preprocessing.image_dataset_from_directory(\n data_root+'train',\n seed=123,\n image_size=(img_height, img_width),\n batch_size = 200\n)", "Found 1435229 files belonging to 3 classes.\nUsing 1148184 files for training.\nFound 1435229 files belonging to 3 classes.\nUsing 287045 files for validation.\nFound 1435229 files belonging to 3 classes.\n" ], [ "\nclass_names = train_ds.class_names\nprint(class_names)\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(10, 10))\nfor images, labels in train_ds.take(1):\n for i in range(9):\n ax = plt.subplot(3, 3, i + 1)\n plt.imshow(images[i].numpy().astype(\"uint8\"))\n plt.title(class_names[labels[i]])\n plt.axis(\"off\")", "['high', 'low', 'neutral']\n" ], [ "\nfor image_batch, labels_batch in train_ds:\n print(image_batch.shape)\n print(labels_batch.shape)\n break", "(32, 180, 180, 3)\n(32,)\n" ], [ "from tensorflow.keras import layers\n\nnormalization_layer = tf.keras.layers.experimental.preprocessing.Rescaling(1./255)\nnormalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))\nimage_batch, labels_batch = next(iter(normalized_ds))\nfirst_image = image_batch[0]", "_____no_output_____" ], [ "\nmodel = tf.keras.Sequential([\n layers.experimental.preprocessing.Rescaling(1./255),\n layers.Conv2D(32, 3, activation='relu'),\n layers.MaxPooling2D(),\n layers.Conv2D(32, 3, activation='relu'),\n layers.MaxPooling2D(),\n layers.Conv2D(32, 3, activation='relu'),\n layers.MaxPooling2D(),\n layers.Flatten(),\n layers.Dense(128, activation='relu'),\n layers.Dense(3)\n])", "_____no_output_____" ], [ "model.compile(\n optimizer='adam',\n loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\nmodel.fit(\n train_ds,\n validation_data=val_ds,\n epochs=5\n)", "Epoch 1/5\n35881/35881 [==============================] - 47188s 1s/step - loss: 0.3445 - accuracy: 0.8653 - val_loss: 0.1643 - val_accuracy: 0.9377\nEpoch 2/5\n35881/35881 [==============================] - 45786s 1s/step - loss: 0.1370 - accuracy: 0.9482 - val_loss: 0.1197 - val_accuracy: 0.9571\nEpoch 3/5\n35881/35881 [==============================] - 44625s 1s/step - loss: 0.0856 - accuracy: 0.9692 - val_loss: 0.1035 - val_accuracy: 0.9660\nEpoch 4/5\n35881/35881 [==============================] - 43951s 1s/step - loss: 0.0631 - accuracy: 0.9780 - val_loss: 0.0979 - val_accuracy: 0.9706\nEpoch 5/5\n35881/35881 [==============================] - 41739s 1s/step - loss: 0.0512 - accuracy: 0.9825 - val_loss: 0.0992 - val_accuracy: 0.9724\n" ], [ "\n#result = model.evaluate(test_ds)\n#dict(zip(model.metrics_names, result))\n\ntest_images = []\ntest_labels = []\npredictions = []\n\nfor image, label in test_ds.take(3):\n test_images.append(image.numpy())\n test_labels.append(label.numpy())\n predictions.append(np.argmax(model.predict(test_images), axis=1))\n\ntest_labels = np.array(test_labels)\npredictions = np.array(predictions)\n\ny_true = test_labels\n\ntest_acc = sum(predictions[0] == y_true[0]) / len(y_true[0])\nprint(f'Test set accuracy: {test_acc:.0%}')", "WARNING:tensorflow:Layers in a Sequential model should only have a single input tensor, but we receive a <class 'tuple'> input: (<tf.Tensor 'IteratorGetNext:0' shape=(None, 180, 180, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, 180, 180, 3) dtype=float32>)\nConsider rewriting this model with the Functional API.\nWARNING:tensorflow:Layers in a Sequential model should only have a single input tensor, but we receive a <class 'tuple'> input: (<tf.Tensor 'IteratorGetNext:0' shape=(None, 180, 180, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, 180, 180, 3) dtype=float32>)\nConsider rewriting this model with the Functional API.\nWARNING:tensorflow:Layers in a Sequential model should only have a single input tensor, but we receive a <class 'tuple'> input: (<tf.Tensor 'IteratorGetNext:0' shape=(None, 180, 180, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, 180, 180, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:2' shape=(None, 180, 180, 3) dtype=float32>)\nConsider rewriting this model with the Functional API.\nWARNING:tensorflow:Layers in a Sequential model should only have a single input tensor, but we receive a <class 'tuple'> input: (<tf.Tensor 'IteratorGetNext:0' shape=(None, 180, 180, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, 180, 180, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:2' shape=(None, 180, 180, 3) dtype=float32>)\nConsider rewriting this model with the Functional API.\nTest set accuracy: 98%\n" ], [ "\nprint(class_names)\nconfusion_mtx = tf.math.confusion_matrix(y_true[0], predictions[0]) \nplt.figure(figsize=(10, 8))\nsns.heatmap(confusion_mtx, yticklabels = class_names, xticklabels = class_names,annot=True, fmt='g')\nplt.xlabel('Prediction')\nplt.ylabel('Label')\nplt.show()", "_____no_output_____" ], [ "\nfilepath = '\\\\Users\\\\George\\\\Documents\\\\Python\\\\ADS CapStone\\\\models'\nmodel.save(filepath)\n", "INFO:tensorflow:Assets written to: \\Users\\George\\Documents\\Python\\ADS CapStone\\models\\assets\nINFO:tensorflow:Assets written to: \\Users\\George\\Documents\\Python\\ADS CapStone\\models\\assets\n" ], [ "x = tuple(val_ds)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec5292fd861ef93f57ea2ff7df991b259e164320
236,953
ipynb
Jupyter Notebook
tf_light_clf/simulator_traffic_light_clf_dt.ipynb
Karthikeya108/sdc-pipeline-project
7d41ad27a661cf44179b01b54095e15a657a3273
[ "MIT" ]
null
null
null
tf_light_clf/simulator_traffic_light_clf_dt.ipynb
Karthikeya108/sdc-pipeline-project
7d41ad27a661cf44179b01b54095e15a657a3273
[ "MIT" ]
null
null
null
tf_light_clf/simulator_traffic_light_clf_dt.ipynb
Karthikeya108/sdc-pipeline-project
7d41ad27a661cf44179b01b54095e15a657a3273
[ "MIT" ]
null
null
null
649.186301
91,862
0.939313
[ [ [ "### Download simulator dataset from \nhttps://drive.google.com/file/d/0B-Eiyn-CUQtxdUZWMkFfQzdObUE/view\n\nRef: https://github.com/coldKnight/TrafficLight_Detection-TensorFlowAPI#get-the-dataset", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\nimport glob\nimport yaml\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nimport seaborn as sns", "_____no_output_____" ], [ "with open(\"sim_data_annotations.yaml\", 'r') as stream:\n try:\n txt = yaml.load(stream)\n except yaml.YAMLError as exc:\n print(exc)", "_____no_output_____" ], [ "data = []\nlabel = []\nfor i in xrange(len(txt)):\n fname = txt[i]['filename']\n if txt[i]['annotations']:\n class_name = txt[i]['annotations'][0]['class']\n else:\n class_name = 'other'\n image = np.array(ndimage.imread(fname, flatten=False))\n data.append(image.flatten())\n label.append(class_name)", "_____no_output_____" ], [ "X_train, X_test, y_train, y_test = train_test_split(data, label, random_state=42, test_size=0.1)", "_____no_output_____" ], [ "from sklearn.tree import DecisionTreeClassifier", "_____no_output_____" ], [ "clf = DecisionTreeClassifier()", "_____no_output_____" ], [ "clf.fit(X_train, y_train)", "_____no_output_____" ], [ "predictions = clf.predict(X_test)", "_____no_output_____" ], [ "classes = ['red','green','yellow','other']", "_____no_output_____" ], [ "conf_mat = confusion_matrix(y_test, predictions)\nfig, ax = plt.subplots(figsize=(10,10))\nsns.heatmap(conf_mat, annot=True, fmt='d',\n xticklabels=classes, yticklabels=classes)\nplt.ylabel('Actual')\nplt.xlabel('Predicted')\nplt.show()", "_____no_output_____" ], [ "print(\"Accuracy: \",accuracy_score(y_test, predictions))", "('Accuracy: ', 0.8571428571428571)\n" ], [ "test_image = np.array(ndimage.imread('sim_data_capture/left0053.jpg', flatten=False))\nplt.imshow(test_image)", "_____no_output_____" ], [ "clf.predict([test_image.flatten()])", "_____no_output_____" ], [ "test_image = np.array(ndimage.imread('sim_data_capture/left0969.jpg', flatten=False))\nplt.imshow(test_image)", "_____no_output_____" ], [ "clf.predict([test_image.flatten()])", "_____no_output_____" ], [ "test_image = np.array(ndimage.imread('sim_data_capture/left1112.jpg', flatten=False))\nplt.imshow(test_image)", "_____no_output_____" ], [ "clf.predict([test_image.flatten()])", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec52a5a2231775d8f33d8fe2499eb20a369d6cd2
2,091
ipynb
Jupyter Notebook
Aula_AVD_Evoney_19_04.ipynb
Evoney/AVD---UFAM
97c039301d8f46c3171f880c018e26c95c295da8
[ "MIT" ]
1
2021-05-06T00:51:21.000Z
2021-05-06T00:51:21.000Z
Aula_AVD_Evoney_19_04.ipynb
Evoney/AVD-UFAM
97c039301d8f46c3171f880c018e26c95c295da8
[ "MIT" ]
null
null
null
Aula_AVD_Evoney_19_04.ipynb
Evoney/AVD-UFAM
97c039301d8f46c3171f880c018e26c95c295da8
[ "MIT" ]
null
null
null
2,091
2,091
0.656624
[ [ [ "# Teste de hipótese\n\nx <- c(6.2, 6.6, 7.1, 7.4, 7.6, 7.9, 8.0, 8.3, 8.4, 8.5, 8.6, 8.8,\n8.8, 9.1, 9.2, 9.4, 9.4, 9.7, 9.9, 10.2, 10.4, 10.8, 11.3, 11.9)", "_____no_output_____" ], [ "# teste de normalidade para alpha = 0.05\nshapiro.test(x)", "_____no_output_____" ], [ "# t teste\nt.test(x, mu=9, alternative=\"two.sided\", conf.level=0.95)", "_____no_output_____" ], [ "depois = c(38.9, 61.2, 73.3, 21.8, 63.4, 64.6, 48.4, 48.8, 48.5)\nantes = c(67.8, 60, 63.4, 76, 89.4, 73.3, 67.3, 61.3, 62.4)", "_____no_output_____" ], [ "# Computar o t-test\nres <- t.test(depois, antes, var.equal = TRUE)\nres", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
ec52a7821d165f1095f034e0481eb61d4401b300
137,892
ipynb
Jupyter Notebook
p1_navigation/Navigation.ipynb
salviosage/Deep_R_Learning
be10c90f551ae812435549196fc09e948ac50691
[ "MIT" ]
1
2021-07-01T17:12:20.000Z
2021-07-01T17:12:20.000Z
p1_navigation/Navigation.ipynb
salviosage/Deep_R_Learning
be10c90f551ae812435549196fc09e948ac50691
[ "MIT" ]
null
null
null
p1_navigation/Navigation.ipynb
salviosage/Deep_R_Learning
be10c90f551ae812435549196fc09e948ac50691
[ "MIT" ]
null
null
null
348.212121
124,924
0.927269
[ [ [ "# Navigation\n\n---\n\nIn this notebook, you will learn how to use the Unity ML-Agents environment for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893).\n\n### 1. Start the Environment\n\nWe begin by importing some necessary packages. If the code cell below returns an error, please revisit the project instructions to double-check that you have installed [Unity ML-Agents](https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Installation.md) and [NumPy](http://www.numpy.org/).", "_____no_output_____" ] ], [ [ "from unityagents import UnityEnvironment\nimport numpy as np\nfrom collections import deque\nimport random\nimport os\nimport torch\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "from dqn_agent import Agent", "_____no_output_____" ] ], [ [ "Next, we will start the environment! **_Before running the code cell below_**, change the `file_name` parameter to match the location of the Unity environment that you downloaded.\n\n- **Mac**: `\"path/to/Banana.app\"`\n- **Windows** (x86): `\"path/to/Banana_Windows_x86/Banana.exe\"`\n- **Windows** (x86_64): `\"path/to/Banana_Windows_x86_64/Banana.exe\"`\n- **Linux** (x86): `\"path/to/Banana_Linux/Banana.x86\"`\n- **Linux** (x86_64): `\"path/to/Banana_Linux/Banana.x86_64\"`\n- **Linux** (x86, headless): `\"path/to/Banana_Linux_NoVis/Banana.x86\"`\n- **Linux** (x86_64, headless): `\"path/to/Banana_Linux_NoVis/Banana.x86_64\"`\n\nFor instance, if you are using a Mac, then you downloaded `Banana.app`. If this file is in the same folder as the notebook, then the line below should appear as follows:\n```\nenv = UnityEnvironment(file_name=\"Banana.app\")\n```", "_____no_output_____" ] ], [ [ "env = UnityEnvironment(file_name=\"Banana.app\")", "INFO:unityagents:\n'Academy' started successfully!\nUnity Academy name: Academy\n Number of Brains: 1\n Number of External Brains : 1\n Lesson number : 0\n Reset Parameters :\n\t\t\nUnity brain name: BananaBrain\n Number of Visual Observations (per agent): 0\n Vector Observation space type: continuous\n Vector Observation space size (per agent): 37\n Number of stacked Vector Observation: 1\n Vector Action space type: discrete\n Vector Action space size (per agent): 4\n Vector Action descriptions: , , , \n" ] ], [ [ "Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python.", "_____no_output_____" ] ], [ [ "# get the default brain\nbrain_name = env.brain_names[0]\nbrain = env.brains[brain_name]", "_____no_output_____" ] ], [ [ "### 2. Examine the State and Action Spaces\n\nThe simulation contains a single agent that navigates a large environment. At each time step, it has four actions at its disposal:\n- `0` - walk forward \n- `1` - walk backward\n- `2` - turn left\n- `3` - turn right\n\nThe state space has `37` dimensions and contains the agent's velocity, along with ray-based perception of objects around agent's forward direction. A reward of `+1` is provided for collecting a yellow banana, and a reward of `-1` is provided for collecting a blue banana. \n\nRun the code cell below to print some information about the environment.", "_____no_output_____" ] ], [ [ "# reset the environment\nenv_info = env.reset(train_mode=True)[brain_name]\n\n# number of agents in the environment\nprint('Number of agents:', len(env_info.agents))\n\n# number of actions\naction_size = brain.vector_action_space_size\nprint('Number of actions:', action_size)\n\n# examine the state space \nstate = env_info.vector_observations[0]\nprint('States look like:', state)\nstate_size = len(state)\nprint('States have length:', state_size)", "Number of agents: 1\nNumber of actions: 4\nStates look like: [1. 0. 0. 0. 0.84408134 0.\n 0. 1. 0. 0.0748472 0. 1.\n 0. 0. 0.25755 1. 0. 0.\n 0. 0.74177343 0. 1. 0. 0.\n 0.25854847 0. 0. 1. 0. 0.09355672\n 0. 1. 0. 0. 0.31969345 0.\n 0. ]\nStates have length: 37\n" ] ], [ [ "### 3. Take Random Actions in the Environment\n\nIn the next code cell, you will learn how to use the Python API to control the agent and receive feedback from the environment.\n\nOnce this cell is executed, you will watch the agent's performance, if it selects an action (uniformly) at random with each time step. A window should pop up that allows you to observe the agent, as it moves through the environment. \n\nOf course, as part of the project, you'll have to change the code so that the agent is able to use its experience to gradually choose better actions when interacting with the environment!", "_____no_output_____" ] ], [ [ "env_info = env.reset(train_mode=False)[brain_name] # reset the environment\nstate = env_info.vector_observations[0] # get the current state\nscore = 0 # initialize the score\nwhile True:\n action = np.random.randint(action_size) # select an action\n env_info = env.step(action)[brain_name] # send the action to the environment\n next_state = env_info.vector_observations[0] # get the next state\n reward = env_info.rewards[0] # get the reward\n done = env_info.local_done[0] # see if episode has finished\n score += reward # update the score\n state = next_state # roll over the state to next time step\n if done: # exit loop if episode finished\n break\n \nprint(\"Score: {}\".format(score))", "Score: 1.0\n" ] ], [ [ "### TRAIN THE AGENT USING DEEP Q NET ", "_____no_output_____" ] ], [ [ "agent = Agent(state_size=37, action_size=4, seed=32, fc1_units=128, fc2_units=64)", "_____no_output_____" ], [ "save_path = 'checkpoint.pth'\nepisode_num = 1\ndef save_model(model, episode_num):\n if model is not None:\n checkpoint = {\n 'episode_num': episode_num,\n 'state_dict': model.state_dict()\n }\n torch.save(checkpoint, save_path)\n print('\\r\\tsave episode' + str(episode_num), end='')\n\ndef load_model(model):\n if os.path.exists(save_path) and model is not None:\n checkpoint = torch.load(save_path)\n episode_num = checkpoint['episode_num']\n model.load_state_dict(checkpoint['state_dict'])\n print('Loaded episode number: ', episode_num)\n return episode_num\n return 1\n\nepisode_num = load_model(agent.qnetwork_local)\nprint(episode_num)", "1\n" ], [ "def dqn(n_episodes=2000, max_t=100000, eps_start=1., eps_end=.01, eps_decay=.995):\n scores = []\n scores_window = deque(maxlen=100)\n eps = eps_start\n \n for i_episode in range(n_episodes):\n env_info = env.reset(train_mode=True)[brain_name]\n state = env_info.vector_observations[0]\n score = 0\n for t in range(max_t):\n action = (int)(agent.act(state, eps))\n env_info = env.step(action)[brain_name]\n next_state = env_info.vector_observations[0]\n reward = env_info.rewards[0]\n done = env_info.local_done[0]\n agent.step(state, action, reward, next_state, done)\n state = next_state\n score+=reward\n if done: break\n scores_window.append(score)\n scores.append(score)\n eps = max(eps_end, eps_decay * eps)\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end='')\n if i_episode % 100 == 0:\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end='')\n save_model(agent.qnetwork_local, i_episode)\n if np.mean(scores_window) >= 15.:\n print('\\nEnvironment solved in {:d} episodes!\\tAverage Score: {:.2f}'.format(i_episode - 100,\n np.mean(scores_window)))\n torch.save(agent.qnetwork_local.state_dict(), 'model.pth')\n break\n return scores", "_____no_output_____" ], [ "scores = dqn()", "Episode 823\tAverage Score: 15.02\nEnvironment solved in 723 episodes!\tAverage Score: 15.02\n" ], [ "fig = plt.figure(figsize=(13, 10))\nax = fig.add_subplot(111)\nplt.plot(np.arange(len(scores)), scores)\nplt.ylabel('Score')\nplt.xlabel('Episodes')\nplt.show()", "_____no_output_____" ] ], [ [ "When finished, you can close the environment.", "_____no_output_____" ] ], [ [ "env.close()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
ec52bd7942eefef6fd6ab5e5a1a342139dac79e2
34,613
ipynb
Jupyter Notebook
src/test/datascience/sub/test.ipynb
PeterJCLaw/vscode-python
e7136b1448d27e9a607ca0d8242d4272b48aabdb
[ "MIT" ]
28
2020-05-21T19:17:43.000Z
2021-12-14T06:54:41.000Z
src/test/datascience/sub/test.ipynb
PeterJCLaw/vscode-python
e7136b1448d27e9a607ca0d8242d4272b48aabdb
[ "MIT" ]
66
2020-09-01T20:09:30.000Z
2022-03-31T10:03:15.000Z
src/test/datascience/sub/test.ipynb
PeterJCLaw/vscode-python
e7136b1448d27e9a607ca0d8242d4272b48aabdb
[ "MIT" ]
9
2020-06-06T16:41:24.000Z
2021-11-03T12:10:58.000Z
17,306.5
34,612
0.952677
[ [ [ "# Change directory to VSCode workspace root so that relative path loads work correctly. Turn this addition off with the DataScience.changeDirOnImportExport setting\r\n# ms-python.python added\r\nimport os\r\ntry:\r\n\tz(os.path.join(os.getcwd(), '..'))\r\n\tprint(os.getcwd())\r\nexcept:\r\n\tpass\r\n", "_____no_output_____" ], [ "print('hello')\n\nimport os\nos.getcwd()\n", "hello\n" ], [ "import matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\nimport pandas as pd\n\nx = np.linspace(0, 20, 100)\nfig, ax = plt.subplots(figsize=(5,10))\nplt.plot(x, np.sin(x))\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
ec52cd9c8fd24d2c751cbe45bb2b4092aeedda30
481,999
ipynb
Jupyter Notebook
notes/01c_interpolation_error.ipynb
matteoalberti/P1.4_seed
9eeb14238cdd76365b6dde3dd95c91e1a64db545
[ "CC-BY-4.0" ]
null
null
null
notes/01c_interpolation_error.ipynb
matteoalberti/P1.4_seed
9eeb14238cdd76365b6dde3dd95c91e1a64db545
[ "CC-BY-4.0" ]
null
null
null
notes/01c_interpolation_error.ipynb
matteoalberti/P1.4_seed
9eeb14238cdd76365b6dde3dd95c91e1a64db545
[ "CC-BY-4.0" ]
null
null
null
729.196672
73,260
0.941201
[ [ [ "# Task for today:\n\n- compute the error between Lagrange interpolation for equispaced points (in \"approximate Linfty\") and a given function when the degree increases\n- compute the error between Lagrange interpolation for Chebyshev (in \"approximate Linfty\") and a given function when the degree increases\n- compute the error between Bernstein approximation (in \"approximate Linfty\") and a given function when the degree increases\n- compute the L2 projection and compute the error (\"in approximate Linfty\") norm and compare with previous results\n", "_____no_output_____" ] ], [ [ "%pylab inline", "Populating the interactive namespace from numpy and matplotlib\n" ], [ "import scipy.special\n\ndef lagrange(i, q, x):\n return product([(x-qj)/(q[i]-qj) for qj in q if qj != q[i]], axis=0)\n\ndef bernstein(i, q, x):\n n = len(q)-1\n return scipy.special.binom(n,i)*(1-x)**(n-i)*x**i\n\ndef cheb(n):\n return numpy.polynomial.chebyshev.chebgauss(n)[0]*.5+.5", "_____no_output_____" ], [ "x = linspace(0,1,1025)\nq = linspace(0,1,10)\ny = array([lagrange(i,q,x) for i in range(len(q))])\n_ = plot(x, y.T)", "_____no_output_____" ], [ "q = cheb(10)\ny = array([lagrange(i,q,x) for i in range(len(q))])\n_ = plot(x, y.T)", "_____no_output_____" ], [ "q = linspace(0,1,10)\ny = array([bernstein(i,q,x) for i in range(len(q))])\n_ = plot(x, y.T)", "_____no_output_____" ], [ "def myfun(x):\n return 1/(1+100*(x-.5)**2)\n\ndef myfun(x):\n return sin(3*numpy.pi*x)\n\n\nplot(x, myfun(x))", "_____no_output_____" ], [ "p = y.T.dot(myfun(q))\nf = myfun(x)\n\nplot(x,p)\nplot(x,f)\nplot(q,myfun(q), 'or')", "_____no_output_____" ], [ "linfty = max(abs(f-p))\nlinfty", "_____no_output_____" ], [ "def error(q, myfun, interpolation=lagrange) : \n y = array([interpolation(i,q,x) for i in range(len(q))])\n p = y.T.dot(myfun(q))\n f = myfun(x)\n return (max(abs(f-p)))", "_____no_output_____" ], [ "N = range(3, 30)\nerror_equispaced = []\nerror_cheb = []\nerror_bernstein = []\nfor n in N:\n error_cheb.append(error(cheb(n), myfun))\n error_equispaced.append(error(linspace(0,1,n), myfun))\n error_bernstein.append(error(linspace(0,1,n), myfun, bernstein))\n", "_____no_output_____" ], [ "semilogy(N, error_equispaced)\nsemilogy(N, error_cheb)\nsemilogy(N, error_bernstein)\n_ = legend(['Equispaced','Chebishev','Bernstein'])", "_____no_output_____" ], [ "q = linspace(0,1,20)\ny = array([bernstein(i,q,x) for i in range(len(q))])\n_ = plot(x, y.T)", "_____no_output_____" ], [ "N = range(5,400,5)\nplot(x,myfun(x))\n\nfor n in N:\n q = linspace(0,1,n)\n y = array([bernstein(i,q,x) for i in range(len(q))])\n p = y.T.dot(myfun(q))\n _ = plot(x, p, '--')\n", "_____no_output_____" ], [ "def myfun(x):\n return abs(x-.5)\n\nimport scipy\nfrom scipy.integrate import quad as integrate\n\nN = range(1,15)\n\nfor n in N:\n M = zeros((n,n))\n\n for i in range(n):\n for j in range(n):\n M[i,j] = 1.0/(i+j+1)\n\n F = array([integrate(lambda x: myfun(x)*x**i, 0,1)[0] for i in range(n)])\n pi = linalg.solve(M, F)\n p = sum([x**i*pi[i] for i in range(n)], axis=0)\n plot(x,p)\nplot(x,myfun(x))", "_____no_output_____" ], [ "plot(x,p)\nplot(x,myfun(x))", "_____no_output_____" ], [ "max(abs(p-myfun(x)))", "_____no_output_____" ] ], [ [ "Why do we get these errors in the L2 projection? The matrix M is not well conditioned...", "_____no_output_____" ] ], [ [ "linalg.cond(M)", "_____no_output_____" ] ], [ [ "Let's turn to numerical quadrature, and Legendre polynomials (for which M is the identity by construction...)", "_____no_output_____" ] ], [ [ "from numpy.polynomial.legendre import leggauss\nfrom numpy.polynomial.legendre import legval\nfrom numpy.polynomial.legendre import Legendre", "_____no_output_____" ], [ "n = 10\nN = n+5\n\n\nq,w = leggauss(N)\nw *= .5\nq +=1\nq /=2", "_____no_output_____" ], [ "v = array([Legendre.basis(i, domain=[0,1])(x) for i in range(n)])\nvq = array([Legendre.basis(i, domain=[0,1])(q) for i in range(n)])\n_ = plot(x,v.T)\n_ = plot(q, vq.T, 'o')", "_____no_output_____" ] ], [ [ "Check that we get a diagonal matrix as M:", "_____no_output_____" ] ], [ [ "vq.shape", "_____no_output_____" ], [ "M = einsum('iq, jq, q', vq, vq, w)", "_____no_output_____" ], [ "diag = array([M[i,i] for i in range(n)])", "_____no_output_____" ], [ "diag", "_____no_output_____" ] ], [ [ "Now perform the integral", "_____no_output_____" ] ], [ [ "pi = sum(vq*myfun(q)*w, axis=1)", "_____no_output_____" ] ], [ [ "And plot the function, and its interpolation", "_____no_output_____" ] ], [ [ "p = (pi/diag).dot(v)", "_____no_output_____" ], [ "plot(x, p)\n_ = plot(x, myfun(x))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
ec52d03cbc513e7c72c96e38a1e9757595cb0500
150,716
ipynb
Jupyter Notebook
demo/vae_recon_error_demo.ipynb
yizi0511/vae_from_scratch
e847a0353ceab990b47351cf2d26d0b140c082ca
[ "MIT" ]
1
2020-04-24T18:02:54.000Z
2020-04-24T18:02:54.000Z
demo/vae_recon_error_demo.ipynb
yizi0511/vae_from_scratch
e847a0353ceab990b47351cf2d26d0b140c082ca
[ "MIT" ]
null
null
null
demo/vae_recon_error_demo.ipynb
yizi0511/vae_from_scratch
e847a0353ceab990b47351cf2d26d0b140c082ca
[ "MIT" ]
1
2020-04-08T02:42:26.000Z
2020-04-08T02:42:26.000Z
243.090323
99,620
0.900263
[ [ [ "import numpy as np\nimport mnist\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n#import tensorflow as tf\nimport tensorflow.compat.v1 as tf\ntf.disable_eager_execution()", "_____no_output_____" ], [ "def xavier_init(channel_in, channel_out, constant = 1): \n \"\"\"\n Xavier initialization of network weights\n \"\"\"\n \n low = -constant * np.sqrt(6.0 / (channel_in + channel_out)) \n high = constant * np.sqrt(6.0 / (channel_in + channel_out))\n return tf.random_uniform((channel_in, channel_out), minval = low, maxval = high, dtype=tf.float32)", "_____no_output_____" ] ], [ [ "### Define Model", "_____no_output_____" ] ], [ [ "class VAE(object):\n \n def __init__(self, network_architecture, learning_rate=0.001, batch_size=100):\n \"\"\"\n Set up the VAE model.\n \"\"\"\n \n # Set model parameters\n self.network_architecture = network_architecture\n self.lr = learning_rate\n self.batch_size = batch_size\n \n self.x = tf.placeholder(tf.float32, [None, network_architecture[\"n_input\"]])\n \n # Forward pass\n self.forward()\n \n # Backward pass\n self.backward()\n\n # Initialize the variables and launch the session\n self.sess = tf.InteractiveSession()\n self.sess.run(tf.global_variables_initializer())\n \n def initialize_weights(self, n_hidden_enc_1, n_hidden_enc_2, \n n_hidden_dec_1, n_hidden_dec_2, n_input, n_z):\n \"\"\"\n Initialize weights of the network layers.\n \"\"\"\n \n network_weights = dict()\n network_weights['encoder_weights'] = {\n 'W1': tf.Variable(xavier_init(n_input, n_hidden_enc_1)),\n 'W2': tf.Variable(xavier_init(n_hidden_enc_1, n_hidden_enc_2)),\n 'W_mu': tf.Variable(xavier_init(n_hidden_enc_2, n_z)),\n 'W_logvar': tf.Variable(xavier_init(n_hidden_enc_2, n_z))}\n network_weights['encoder_bias'] = {\n 'b1': tf.Variable(tf.zeros([n_hidden_enc_1], dtype=tf.float32)),\n 'b2': tf.Variable(tf.zeros([n_hidden_enc_2], dtype=tf.float32)),\n 'b_mu': tf.Variable(tf.zeros([n_z], dtype=tf.float32)),\n 'b_logvar': tf.Variable(tf.zeros([n_z], dtype=tf.float32))}\n network_weights['decoder_weights'] = {\n 'W1': tf.Variable(xavier_init(n_z, n_hidden_dec_1)),\n 'W2': tf.Variable(xavier_init(n_hidden_dec_1, n_hidden_dec_2)),\n 'W_out': tf.Variable(xavier_init(n_hidden_dec_2, n_input))}\n network_weights['decoder_bias'] = {\n 'b1': tf.Variable(tf.zeros([n_hidden_dec_1], dtype=tf.float32)),\n 'b2': tf.Variable(tf.zeros([n_hidden_dec_2], dtype=tf.float32)),\n 'b_out': tf.Variable(tf.zeros([n_input], dtype=tf.float32))}\n return network_weights\n \n\n def encode(self, weights, bias):\n \"\"\"\n Use the encoder model to map the input data to the latent space.\n \"\"\"\n \n hidden_1 = tf.nn.relu(tf.add(tf.matmul(self.x, weights['W1']), bias['b1'])) \n hidden_2 = tf.nn.relu(tf.add(tf.matmul(hidden_1, weights['W2']), bias['b2'])) \n mu = tf.add(tf.matmul(hidden_2, weights['W_mu']), bias['b_mu'])\n logvar = tf.add(tf.matmul(hidden_2, weights['W_logvar']), bias['b_logvar'])\n return (mu, logvar)\n\n def decode(self, weights, bias):\n \"\"\"\n Use the decoder model to reconstruct the input data.\n \"\"\"\n \n hidden_1 = tf.nn.leaky_relu(tf.add(tf.matmul(self.z, weights['W1']), bias['b1'])) \n hidden_2 = tf.nn.leaky_relu(tf.add(tf.matmul(hidden_1, weights['W2']), bias['b2'])) \n recon_x = tf.nn.sigmoid(tf.add(tf.matmul(hidden_2, weights['W_out']), bias['b_out']))\n return recon_x\n \n \n def forward(self):\n \"\"\"\n Build the VAE network.\n \"\"\"\n \n # Initialize weights and bias\n network_weights = self.initialize_weights(**self.network_architecture)\n\n # Use encoder model to obtain latent z\n self.mu, self.logvar = self.encode(network_weights[\"encoder_weights\"], \n network_weights[\"encoder_bias\"])\n\n # Draw sample z from Gaussian using reparametrization trick\n n_z = self.network_architecture[\"n_z\"]\n eps = tf.random_normal((self.batch_size, n_z), 0, 1, dtype=tf.float32)\n self.z = tf.add(self.mu, tf.multiply(tf.sqrt(tf.exp(self.logvar)), eps))\n\n # Use decoder model to obtain the reconstructed input\n self.recon_x = self.decode(network_weights[\"decoder_weights\"],\n network_weights[\"decoder_bias\"])\n \n \n def backward(self):\n \"\"\"\n Calculate gradients using backpropagation and update weights using Adam optimizer.\n \"\"\"\n \n rec_loss = - tf.reduce_sum(self.x * tf.log(1e-8 + self.recon_x)\n + (1 - self.x) * tf.log(1e-8 + 1 - self.recon_x), 1)\n \n kl = -0.5 * tf.reduce_sum(1 + self.logvar - tf.square(self.mu) - tf.exp(self.logvar), 1)\n \n self.loss = tf.reduce_mean(rec_loss + kl) \n \n self.optimizer = tf.train.AdamOptimizer(learning_rate = self.lr).minimize(self.loss)\n \n def train(self, X):\n \"\"\"\n Train model based on mini-batch of input data.\n Return loss of mini-batch.\n \"\"\"\n \n opt, loss = self.sess.run((self.optimizer, self.loss), \n feed_dict={self.x: X})\n return loss\n \n def transform(self, X):\n \"\"\"\n Transform data by mapping it into the latent space.\n \"\"\"\n # Note: This maps to mean of distribution, we could alternatively sample from Gaussian distribution\n return self.sess.run((self.mu, self.logvar), feed_dict={self.x: X})\n \n def generate(self, mu = None):\n \"\"\" \n Generate data by sampling from the latent space. \n \"\"\"\n if mu is None:\n # Data is alternatively generated from the prior in the latent space\n mu = np.random.normal(size = self.network_architecture[\"n_z\"])\n\n return self.sess.run(self.recon_x, feed_dict={self.z: mu})\n \n def reconstruct(self, X):\n \"\"\" \n Reconstruct the given input data. \n \"\"\"\n \n return self.sess.run(self.recon_x, feed_dict={self.x: X})", "_____no_output_____" ] ], [ [ "### Training", "_____no_output_____" ] ], [ [ "def train_mnist(network_architecture, images,\n learning_rate=0.001, batch_size=100, n_epoch=10):\n \"\"\"\n Train the VAE model on the MNIST data set.\n \"\"\"\n \n vae = VAE(network_architecture, learning_rate=learning_rate, batch_size=batch_size)\n \n train_size = len(images)\n train_data = images.reshape((train_size, 784)) / 255 # normalize to [0,1]\n \n for epoch in range(n_epoch):\n \n avg_loss = 0.\n n_batch = int(train_size / batch_size) \n\n for idx in range(n_batch):\n train_batch = train_data[idx * batch_size:idx * batch_size + batch_size]\n loss = vae.train(train_batch)\n avg_loss += loss / train_size * batch_size\n\n print(\"Epoch:\", \"%d/%d\" % (epoch+1, n_epoch), \n \"Loss =\", \"{:.4f}\".format(avg_loss))\n \n return vae", "_____no_output_____" ], [ "network_architecture = dict(n_hidden_enc_1=500, \n n_hidden_enc_2=500, \n n_hidden_dec_1=500, \n n_hidden_dec_2=500, \n n_input=784, \n n_z=100) \n\nvae = train_mnist(network_architecture, mnist.train_images(), n_epoch = 200)", "WARNING:tensorflow:From /Users/yizizhang/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1635: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\nInstructions for updating:\nIf using Keras pass *_constraint arguments to layers.\nEpoch: 1/200 Loss = 164.6328\nEpoch: 2/200 Loss = 124.9651\nEpoch: 3/200 Loss = 116.9161\nEpoch: 4/200 Loss = 113.0834\nEpoch: 5/200 Loss = 110.4787\nEpoch: 6/200 Loss = 108.6359\nEpoch: 7/200 Loss = 107.4994\nEpoch: 8/200 Loss = 106.4819\nEpoch: 9/200 Loss = 105.6952\nEpoch: 10/200 Loss = 105.1213\nEpoch: 11/200 Loss = 104.5814\nEpoch: 12/200 Loss = 103.9522\nEpoch: 13/200 Loss = 103.5108\nEpoch: 14/200 Loss = 103.0897\nEpoch: 15/200 Loss = 102.8289\nEpoch: 16/200 Loss = 102.4243\nEpoch: 17/200 Loss = 102.1996\nEpoch: 18/200 Loss = 101.9845\nEpoch: 19/200 Loss = 101.7286\nEpoch: 20/200 Loss = 101.5520\nEpoch: 21/200 Loss = 101.2993\nEpoch: 22/200 Loss = 101.1506\nEpoch: 23/200 Loss = 101.0281\nEpoch: 24/200 Loss = 100.8513\nEpoch: 25/200 Loss = 100.7082\nEpoch: 26/200 Loss = 100.5033\nEpoch: 27/200 Loss = 100.4141\nEpoch: 28/200 Loss = 100.2769\nEpoch: 29/200 Loss = 100.2472\nEpoch: 30/200 Loss = 100.0456\nEpoch: 31/200 Loss = 99.9535\nEpoch: 32/200 Loss = 99.8187\nEpoch: 33/200 Loss = 99.7406\nEpoch: 34/200 Loss = 99.7417\nEpoch: 35/200 Loss = 99.6276\nEpoch: 36/200 Loss = 99.4998\nEpoch: 37/200 Loss = 99.4626\nEpoch: 38/200 Loss = 99.3407\nEpoch: 39/200 Loss = 99.3076\nEpoch: 40/200 Loss = 99.2432\nEpoch: 41/200 Loss = 99.1769\nEpoch: 42/200 Loss = 99.0505\nEpoch: 43/200 Loss = 99.0406\nEpoch: 44/200 Loss = 98.9437\nEpoch: 45/200 Loss = 98.9414\nEpoch: 46/200 Loss = 98.8360\nEpoch: 47/200 Loss = 98.7691\nEpoch: 48/200 Loss = 98.7484\nEpoch: 49/200 Loss = 98.6769\nEpoch: 50/200 Loss = 98.6287\nEpoch: 51/200 Loss = 98.6063\nEpoch: 52/200 Loss = 98.5440\nEpoch: 53/200 Loss = 98.4687\nEpoch: 54/200 Loss = 98.4670\nEpoch: 55/200 Loss = 98.4235\nEpoch: 56/200 Loss = 98.4135\nEpoch: 57/200 Loss = 98.3035\nEpoch: 58/200 Loss = 98.2675\nEpoch: 59/200 Loss = 98.2657\nEpoch: 60/200 Loss = 98.2544\nEpoch: 61/200 Loss = 98.1224\nEpoch: 62/200 Loss = 98.1701\nEpoch: 63/200 Loss = 98.1391\nEpoch: 64/200 Loss = 98.0348\nEpoch: 65/200 Loss = 98.0479\nEpoch: 66/200 Loss = 97.9778\nEpoch: 67/200 Loss = 98.0378\nEpoch: 68/200 Loss = 97.9582\nEpoch: 69/200 Loss = 97.9439\nEpoch: 70/200 Loss = 97.8425\nEpoch: 71/200 Loss = 97.8831\nEpoch: 72/200 Loss = 97.8256\nEpoch: 73/200 Loss = 97.8256\nEpoch: 74/200 Loss = 97.7716\nEpoch: 75/200 Loss = 97.7409\nEpoch: 76/200 Loss = 97.7463\nEpoch: 77/200 Loss = 97.7256\nEpoch: 78/200 Loss = 97.6734\nEpoch: 79/200 Loss = 97.6613\nEpoch: 80/200 Loss = 97.6766\nEpoch: 81/200 Loss = 97.6239\nEpoch: 82/200 Loss = 97.5782\nEpoch: 83/200 Loss = 97.5400\nEpoch: 84/200 Loss = 97.4700\nEpoch: 85/200 Loss = 97.5087\nEpoch: 86/200 Loss = 97.4725\nEpoch: 87/200 Loss = 97.4581\nEpoch: 88/200 Loss = 97.4459\nEpoch: 89/200 Loss = 97.4104\nEpoch: 90/200 Loss = 97.4056\nEpoch: 91/200 Loss = 97.4112\nEpoch: 92/200 Loss = 97.3119\nEpoch: 93/200 Loss = 97.3651\nEpoch: 94/200 Loss = 97.2944\nEpoch: 95/200 Loss = 97.2695\nEpoch: 96/200 Loss = 97.2637\nEpoch: 97/200 Loss = 97.2705\nEpoch: 98/200 Loss = 97.2644\nEpoch: 99/200 Loss = 97.2139\nEpoch: 100/200 Loss = 97.1710\nEpoch: 101/200 Loss = 97.1928\nEpoch: 102/200 Loss = 97.2216\nEpoch: 103/200 Loss = 97.1760\nEpoch: 104/200 Loss = 97.1240\nEpoch: 105/200 Loss = 97.0905\nEpoch: 106/200 Loss = 97.0727\nEpoch: 107/200 Loss = 97.0714\nEpoch: 108/200 Loss = 97.0643\nEpoch: 109/200 Loss = 97.0575\nEpoch: 110/200 Loss = 97.0672\nEpoch: 111/200 Loss = 97.0411\nEpoch: 112/200 Loss = 96.9512\nEpoch: 113/200 Loss = 97.0397\nEpoch: 114/200 Loss = 96.9908\nEpoch: 115/200 Loss = 96.9195\nEpoch: 116/200 Loss = 96.9990\nEpoch: 117/200 Loss = 97.0020\nEpoch: 118/200 Loss = 96.9331\nEpoch: 119/200 Loss = 96.8749\nEpoch: 120/200 Loss = 96.8790\nEpoch: 121/200 Loss = 96.8633\nEpoch: 122/200 Loss = 96.8646\nEpoch: 123/200 Loss = 96.8810\nEpoch: 124/200 Loss = 96.8239\nEpoch: 125/200 Loss = 96.8477\nEpoch: 126/200 Loss = 96.8337\nEpoch: 127/200 Loss = 96.7957\nEpoch: 128/200 Loss = 96.8003\nEpoch: 129/200 Loss = 96.7664\nEpoch: 130/200 Loss = 96.7734\nEpoch: 131/200 Loss = 96.7910\nEpoch: 132/200 Loss = 96.7213\nEpoch: 133/200 Loss = 96.7535\nEpoch: 134/200 Loss = 96.7178\nEpoch: 135/200 Loss = 96.7226\nEpoch: 136/200 Loss = 96.6707\nEpoch: 137/200 Loss = 96.6849\nEpoch: 138/200 Loss = 96.7209\nEpoch: 139/200 Loss = 96.6708\nEpoch: 140/200 Loss = 96.6604\nEpoch: 141/200 Loss = 96.6925\nEpoch: 142/200 Loss = 96.5891\nEpoch: 143/200 Loss = 96.6038\nEpoch: 144/200 Loss = 96.5512\nEpoch: 145/200 Loss = 96.6179\nEpoch: 146/200 Loss = 96.5759\nEpoch: 147/200 Loss = 96.5613\nEpoch: 148/200 Loss = 96.5751\nEpoch: 149/200 Loss = 96.5531\nEpoch: 150/200 Loss = 96.5387\nEpoch: 151/200 Loss = 96.4977\nEpoch: 152/200 Loss = 96.5127\nEpoch: 153/200 Loss = 96.5193\nEpoch: 154/200 Loss = 96.5473\nEpoch: 155/200 Loss = 96.5189\nEpoch: 156/200 Loss = 96.4527\nEpoch: 157/200 Loss = 96.4391\nEpoch: 158/200 Loss = 96.4253\nEpoch: 159/200 Loss = 96.4974\nEpoch: 160/200 Loss = 96.4892\nEpoch: 161/200 Loss = 96.4772\nEpoch: 162/200 Loss = 96.4622\nEpoch: 163/200 Loss = 96.3716\nEpoch: 164/200 Loss = 96.4016\nEpoch: 165/200 Loss = 96.4281\nEpoch: 166/200 Loss = 96.4031\nEpoch: 167/200 Loss = 96.3680\nEpoch: 168/200 Loss = 96.4136\nEpoch: 169/200 Loss = 96.3590\nEpoch: 170/200 Loss = 96.3781\nEpoch: 171/200 Loss = 96.3825\nEpoch: 172/200 Loss = 96.3825\nEpoch: 173/200 Loss = 96.3342\nEpoch: 174/200 Loss = 96.3072\nEpoch: 175/200 Loss = 96.3239\nEpoch: 176/200 Loss = 96.3009\nEpoch: 177/200 Loss = 96.3403\nEpoch: 178/200 Loss = 96.3657\nEpoch: 179/200 Loss = 96.2983\nEpoch: 180/200 Loss = 96.2790\nEpoch: 181/200 Loss = 96.2835\nEpoch: 182/200 Loss = 96.3006\nEpoch: 183/200 Loss = 96.2236\nEpoch: 184/200 Loss = 96.2678\nEpoch: 185/200 Loss = 96.2229\nEpoch: 186/200 Loss = 96.2614\nEpoch: 187/200 Loss = 96.2136\nEpoch: 188/200 Loss = 96.2116\nEpoch: 189/200 Loss = 96.2289\nEpoch: 190/200 Loss = 96.2133\nEpoch: 191/200 Loss = 96.2229\nEpoch: 192/200 Loss = 96.2163\nEpoch: 193/200 Loss = 96.1386\nEpoch: 194/200 Loss = 96.2145\nEpoch: 195/200 Loss = 96.1407\nEpoch: 196/200 Loss = 96.1786\nEpoch: 197/200 Loss = 96.2176\nEpoch: 198/200 Loss = 96.1421\nEpoch: 199/200 Loss = 96.1413\nEpoch: 200/200 Loss = 96.2259\n" ] ], [ [ "### Image Reconstruction", "_____no_output_____" ] ], [ [ "images = mnist.train_images()\nx_sample = (images.reshape((60000, 784)) / 255)[:100,]\nrecon_x = vae.reconstruct(x_sample)\n\nplt.figure(figsize=(4, 6))\nfor i in range(5):\n\n plt.subplot(5, 2, 2*i + 1)\n plt.imshow(x_sample[i].reshape(28, 28), vmin=0, vmax=1, cmap=\"gray\")\n plt.title(\"Input\")\n plt.colorbar()\n plt.subplot(5, 2, 2*i + 2)\n plt.imshow(recon_x[i].reshape(28, 28), vmin=0, vmax=1, cmap=\"gray\")\n plt.title(\"Reconstruction\")\n plt.colorbar()\n \nplt.tight_layout()", "_____no_output_____" ], [ "def gen_mnist_image(X):\n return np.rollaxis(np.rollaxis(X[0:200].reshape(20, -1, 28, 28), 0, 2), 1, 3).reshape(-1, 20 * 28)", "_____no_output_____" ], [ "plt.figure(figsize=(10,20))\nplt.imshow(gen_mnist_image(recon_x))", "_____no_output_____" ] ], [ [ "#### Compute Reconstruction Error", "_____no_output_____" ] ], [ [ "def calculate_recon_error(X, recon_X):\n \"\"\"\n Compute the reconstruction error.\n \"\"\"\n rec_loss = - np.sum(X * np.log(1e-8 + recon_X)\n + (1 - X) * np.log(1e-8 + 1 - recon_X), 1)\n return np.mean(rec_loss)", "_____no_output_____" ], [ "calculate_recon_error(x_sample, recon_x)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ec52daed82dfd8428ef6e09deb3346e07cdffd83
490,260
ipynb
Jupyter Notebook
HOMEWORK 1.ipynb
Farshid123/Old-Win-7
74296e56fc5d89f908e58858fd1c0e8208a5cbf3
[ "MIT" ]
null
null
null
HOMEWORK 1.ipynb
Farshid123/Old-Win-7
74296e56fc5d89f908e58858fd1c0e8208a5cbf3
[ "MIT" ]
null
null
null
HOMEWORK 1.ipynb
Farshid123/Old-Win-7
74296e56fc5d89f908e58858fd1c0e8208a5cbf3
[ "MIT" ]
null
null
null
61.000373
577
0.655344
[ [ [ "# Part 1", "_____no_output_____" ] ], [ [ "noun=['human','bird','tiger','pen','paper','book','Farshid']", "_____no_output_____" ], [ "adjective=['beautiful','ugly','fantastic','fabioulus','interesting','dirty']", "_____no_output_____" ], [ "import random", "_____no_output_____" ], [ "random.choice(noun)", "_____no_output_____" ], [ "random.choice(adjective)", "_____no_output_____" ], [ "print(\"all \\\"\"+random.choice(noun)+\"s\\\" are \\\"\" +random.choice(adjective)+\"\\\"!\")", "all \"humans\" are \"dirty\"!\n" ] ], [ [ "# Part two ", "_____no_output_____" ] ], [ [ "TheBigText=\"The advent of massive quantity of born-digital sources, and increasing amount of digitalized and web-based information has necessitated rethinking about a new collection’s toolkit. What Moretti called it distant reading is to distantly read large amount of information, which can be mediated through algorithms and computer interfaces.\"", "_____no_output_____" ], [ "TheBigText", "_____no_output_____" ], [ "theWords=TheBigText.split()", "_____no_output_____" ], [ "theWords[:]", "_____no_output_____" ], [ "theLowerBig=TheBigText.lower()", "_____no_output_____" ], [ "theLowerWords=theLowerBig.split()", "_____no_output_____" ], [ "theLowerWords", "_____no_output_____" ], [ "len(theLowerWords)", "_____no_output_____" ], [ "TheSorted=sorted(theLowerWords)", "_____no_output_____" ], [ "TheSorted", "_____no_output_____" ], [ "import collections", "_____no_output_____" ], [ "collections", "_____no_output_____" ], [ "from collections import Counter", "_____no_output_____" ], [ "theCounts=Counter(TheSorted)", "_____no_output_____" ], [ "print(theCounts)", "Counter({'of': 4, 'and': 3, 'amount': 2, 'a': 1, 'about': 1, 'advent': 1, 'algorithms': 1, 'be': 1, 'born-digital': 1, 'called': 1, 'can': 1, 'collection’s': 1, 'computer': 1, 'digitalized': 1, 'distant': 1, 'distantly': 1, 'has': 1, 'increasing': 1, 'information': 1, 'information,': 1, 'interfaces.': 1, 'is': 1, 'it': 1, 'large': 1, 'massive': 1, 'mediated': 1, 'moretti': 1, 'necessitated': 1, 'new': 1, 'quantity': 1, 'read': 1, 'reading': 1, 'rethinking': 1, 'sources,': 1, 'the': 1, 'through': 1, 'to': 1, 'toolkit.': 1, 'web-based': 1, 'what': 1, 'which': 1})\n" ], [ "TopTen=theCounts.most_common(10)", "_____no_output_____" ], [ "print(TopTen)", "[('of', 4), ('and', 3), ('amount', 2), ('a', 1), ('about', 1), ('advent', 1), ('algorithms', 1), ('be', 1), ('born-digital', 1), ('called', 1)]\n" ] ], [ [ "# Sept. 25 class", "_____no_output_____" ] ], [ [ "%ls", " Volume in drive C has no label.\n Volume Serial Number is 5682-6DAE\n\n Directory of C:\\Users\\Papar\n\n25/09/2017 02:26 PM <DIR> .\n25/09/2017 02:26 PM <DIR> ..\n15/09/2017 09:27 PM <DIR> .anaconda\n27/06/2017 01:01 PM <DIR> .cisco\n25/09/2017 02:58 PM <DIR> .conda\n25/09/2017 12:57 PM 43 .condarc\n24/09/2017 09:27 PM <DIR> .ipynb_checkpoints\n18/09/2017 03:59 PM <DIR> .ipython\n22/09/2017 12:25 PM <DIR> .jupyter\n22/05/2017 11:00 AM <DIR> .spss\n15/09/2017 09:19 PM <DIR> Anaconda3\n24/09/2017 08:34 PM <DIR> AnacondaProjects\n13/05/2017 10:30 AM <DIR> Contacts\n25/09/2017 11:23 AM <DIR> Desktop\n15/09/2017 09:19 PM <DIR> Documents\n25/09/2017 11:27 AM <DIR> Downloads\n13/05/2017 10:30 AM <DIR> Favorites\n25/09/2017 02:26 PM 11,850 HOMEWORK 1.ipynb\n13/05/2017 10:30 AM <DIR> Links\n13/05/2017 10:30 AM <DIR> Music\n13/05/2017 10:30 AM <DIR> Pictures\n13/05/2017 12:45 PM 473 rarreg.key\n13/05/2017 10:30 AM <DIR> Saved Games\n13/05/2017 10:30 AM <DIR> Searches\n18/09/2017 05:47 PM 12,315 Untitled.ipynb\n24/09/2017 09:26 PM 398 Untitled1.py\n13/05/2017 10:30 AM <DIR> Videos\n 5 File(s) 25,079 bytes\n 22 Dir(s) 19,717,160,960 bytes free\n" ], [ "%cd HOMEWORK 1", "[WinError 2] The system cannot find the file specified: 'HOMEWORK 1'\nC:\\Users\\Papar\n" ], [ "%ls", " Volume in drive C has no label.\n Volume Serial Number is 5682-6DAE\n\n Directory of C:\\Users\\Papar\n\n25/09/2017 03:08 PM <DIR> .\n25/09/2017 03:08 PM <DIR> ..\n15/09/2017 09:27 PM <DIR> .anaconda\n27/06/2017 01:01 PM <DIR> .cisco\n25/09/2017 03:09 PM <DIR> .conda\n25/09/2017 12:57 PM 43 .condarc\n24/09/2017 09:27 PM <DIR> .ipynb_checkpoints\n18/09/2017 03:59 PM <DIR> .ipython\n22/09/2017 12:25 PM <DIR> .jupyter\n22/05/2017 11:00 AM <DIR> .spss\n15/09/2017 09:19 PM <DIR> Anaconda3\n24/09/2017 08:34 PM <DIR> AnacondaProjects\n13/05/2017 10:30 AM <DIR> Contacts\n25/09/2017 11:23 AM <DIR> Desktop\n15/09/2017 09:19 PM <DIR> Documents\n25/09/2017 11:27 AM <DIR> Downloads\n13/05/2017 10:30 AM <DIR> Favorites\n25/09/2017 03:08 PM 19,466 HOMEWORK 1.ipynb\n13/05/2017 10:30 AM <DIR> Links\n13/05/2017 10:30 AM <DIR> Music\n13/05/2017 10:30 AM <DIR> Pictures\n13/05/2017 12:45 PM 473 rarreg.key\n13/05/2017 10:30 AM <DIR> Saved Games\n13/05/2017 10:30 AM <DIR> Searches\n25/09/2017 03:01 PM 620 story.txt\n18/09/2017 05:47 PM 12,315 Untitled.ipynb\n24/09/2017 09:26 PM 398 Untitled1.py\n13/05/2017 10:30 AM <DIR> Videos\n 6 File(s) 33,315 bytes\n 22 Dir(s) 19,715,407,872 bytes free\n" ], [ "with open(\"story.txt\", \"r\") as file:\n theStory=file.read()", "_____no_output_____" ], [ "file2Open = open('story.txt', \"r\")\ntheStory = file2Open.read()\nfile2Open.close()\ntheStory[:100]", "_____no_output_____" ], [ "import urllib.request", "_____no_output_____" ], [ "path = 'http://www.gutenberg.org/cache/epub/1636/pg1636.txt'", "_____no_output_____" ], [ "with urllib.request.urlopen(path) as response:\n fullDialogue = response.read().decode('utf-8')", "_____no_output_____" ], [ "print(fullDialogue[:100])", "The Project Gutenberg EBook of Phaedrus, by Plato\r\n\r\nThis eBook is for the use of anyone anywhere a\n" ], [ "print(fullDialogue)", "The Project Gutenberg EBook of Phaedrus, by Plato\r\n\r\nThis eBook is for the use of anyone anywhere at no cost and with\r\nalmost no restrictions whatsoever. You may copy it, give it away or\r\nre-use it under the terms of the Project Gutenberg License included\r\nwith this eBook or online at www.gutenberg.org\r\n\r\n\r\nTitle: Phaedrus\r\n\r\nAuthor: Plato\r\n\r\nTranslator: B. Jowett\r\n\r\nPosting Date: October 30, 2008 [EBook #1636]\r\nRelease Date: February 1999\r\n\r\nLanguage: English\r\n\r\n\r\n*** START OF THIS PROJECT GUTENBERG EBOOK PHAEDRUS ***\r\n\r\n\r\n\r\n\r\nProduced by Sue Asscher\r\n\r\n\r\n\r\n\r\n\r\nPHAEDRUS\r\n\r\nBy Plato\r\n\r\n\r\nTranslated by Benjamin Jowett\r\n\r\n\r\n\r\n\r\nINTRODUCTION.\r\n\r\nThe Phaedrus is closely connected with the Symposium, and may be\r\nregarded either as introducing or following it. The two Dialogues\r\ntogether contain the whole philosophy of Plato on the nature of love,\r\nwhich in the Republic and in the later writings of Plato is only\r\nintroduced playfully or as a figure of speech. But in the Phaedrus and\r\nSymposium love and philosophy join hands, and one is an aspect of the\r\nother. The spiritual and emotional part is elevated into the ideal, to\r\nwhich in the Symposium mankind are described as looking forward, and\r\nwhich in the Phaedrus, as well as in the Phaedo, they are seeking to\r\nrecover from a former state of existence. Whether the subject of the\r\nDialogue is love or rhetoric, or the union of the two, or the relation\r\nof philosophy to love and to art in general, and to the human soul, will\r\nbe hereafter considered. And perhaps we may arrive at some conclusion\r\nsuch as the following--that the dialogue is not strictly confined to a\r\nsingle subject, but passes from one to another with the natural freedom\r\nof conversation.\r\n\r\nPhaedrus has been spending the morning with Lysias, the celebrated\r\nrhetorician, and is going to refresh himself by taking a walk outside\r\nthe wall, when he is met by Socrates, who professes that he will not\r\nleave him until he has delivered up the speech with which Lysias\r\nhas regaled him, and which he is carrying about in his mind, or more\r\nprobably in a book hidden under his cloak, and is intending to study\r\nas he walks. The imputation is not denied, and the two agree to direct\r\ntheir steps out of the public way along the stream of the Ilissus\r\ntowards a plane-tree which is seen in the distance. There, lying down\r\namidst pleasant sounds and scents, they will read the speech of Lysias.\r\nThe country is a novelty to Socrates, who never goes out of the town;\r\nand hence he is full of admiration for the beauties of nature, which he\r\nseems to be drinking in for the first time.\r\n\r\nAs they are on their way, Phaedrus asks the opinion of Socrates\r\nrespecting the local tradition of Boreas and Oreithyia. Socrates, after\r\na satirical allusion to the 'rationalizers' of his day, replies that he\r\nhas no time for these 'nice' interpretations of mythology, and he pities\r\nanyone who has. When you once begin there is no end of them, and they\r\nspring from an uncritical philosophy after all. 'The proper study of\r\nmankind is man;' and he is a far more complex and wonderful being than\r\nthe serpent Typho. Socrates as yet does not know himself; and why should\r\nhe care to know about unearthly monsters? Engaged in such conversation,\r\nthey arrive at the plane-tree; when they have found a convenient\r\nresting-place, Phaedrus pulls out the speech and reads:--\r\n\r\nThe speech consists of a foolish paradox which is to the effect that the\r\nnon-lover ought to be accepted rather than the lover--because he is more\r\nrational, more agreeable, more enduring, less suspicious, less hurtful,\r\nless boastful, less engrossing, and because there are more of them, and\r\nfor a great many other reasons which are equally unmeaning. Phaedrus is\r\ncaptivated with the beauty of the periods, and wants to make Socrates\r\nsay that nothing was or ever could be written better. Socrates does not\r\nthink much of the matter, but then he has only attended to the form, and\r\nin that he has detected several repetitions and other marks of haste. He\r\ncannot agree with Phaedrus in the extreme value which he sets upon this\r\nperformance, because he is afraid of doing injustice to Anacreon and\r\nSappho and other great writers, and is almost inclined to think that he\r\nhimself, or rather some power residing within him, could make a speech\r\nbetter than that of Lysias on the same theme, and also different from\r\nhis, if he may be allowed the use of a few commonplaces which all\r\nspeakers must equally employ.\r\n\r\nPhaedrus is delighted at the prospect of having another speech, and\r\npromises that he will set up a golden statue of Socrates at Delphi,\r\nif he keeps his word. Some raillery ensues, and at length Socrates,\r\nconquered by the threat that he shall never again hear a speech of\r\nLysias unless he fulfils his promise, veils his face and begins.\r\n\r\nFirst, invoking the Muses and assuming ironically the person of the\r\nnon-lover (who is a lover all the same), he will enquire into the nature\r\nand power of love. For this is a necessary preliminary to the other\r\nquestion--How is the non-lover to be distinguished from the lover? In\r\nall of us there are two principles--a better and a worse--reason and\r\ndesire, which are generally at war with one another; and the victory\r\nof the rational is called temperance, and the victory of the irrational\r\nintemperance or excess. The latter takes many forms and has many bad\r\nnames--gluttony, drunkenness, and the like. But of all the irrational\r\ndesires or excesses the greatest is that which is led away by desires\r\nof a kindred nature to the enjoyment of personal beauty. And this is the\r\nmaster power of love.\r\n\r\nHere Socrates fancies that he detects in himself an unusual flow\r\nof eloquence--this newly-found gift he can only attribute to the\r\ninspiration of the place, which appears to be dedicated to the nymphs.\r\nStarting again from the philosophical basis which has been laid down, he\r\nproceeds to show how many advantages the non-lover has over the lover.\r\nThe one encourages softness and effeminacy and exclusiveness; he cannot\r\nendure any superiority in his beloved; he will train him in luxury, he\r\nwill keep him out of society, he will deprive him of parents, friends,\r\nmoney, knowledge, and of every other good, that he may have him all to\r\nhimself. Then again his ways are not ways of pleasantness; he is mighty\r\ndisagreeable; 'crabbed age and youth cannot live together.' At every\r\nhour of the night and day he is intruding upon him; there is the\r\nsame old withered face and the remainder to match--and he is always\r\nrepeating, in season or out of season, the praises or dispraises of his\r\nbeloved, which are bad enough when he is sober, and published all over\r\nthe world when he is drunk. At length his love ceases; he is converted\r\ninto an enemy, and the spectacle may be seen of the lover running away\r\nfrom the beloved, who pursues him with vain reproaches, and demands\r\nhis reward which the other refuses to pay. Too late the beloved learns,\r\nafter all his pains and disagreeables, that 'As wolves love lambs so\r\nlovers love their loves.' (Compare Char.) Here is the end; the 'other'\r\nor 'non-lover' part of the speech had better be understood, for if in\r\nthe censure of the lover Socrates has broken out in verse, what will\r\nhe not do in his praise of the non-lover? He has said his say and is\r\npreparing to go away.\r\n\r\nPhaedrus begs him to remain, at any rate until the heat of noon has\r\npassed; he would like to have a little more conversation before they go.\r\nSocrates, who has risen, recognizes the oracular sign which forbids him\r\nto depart until he has done penance. His conscious has been awakened,\r\nand like Stesichorus when he had reviled the lovely Helen he will sing\r\na palinode for having blasphemed the majesty of love. His palinode takes\r\nthe form of a myth.\r\n\r\nSocrates begins his tale with a glorification of madness, which he\r\ndivides into four kinds: first, there is the art of divination or\r\nprophecy--this, in a vein similar to that pervading the Cratylus and\r\nIo, he connects with madness by an etymological explanation (mantike,\r\nmanike--compare oionoistike, oionistike, ''tis all one reckoning, save\r\nthe phrase is a little variations'); secondly, there is the art of\r\npurification by mysteries; thirdly, poetry or the inspiration of the\r\nMuses (compare Ion), without which no man can enter their temple. All\r\nthis shows that madness is one of heaven's blessings, and may sometimes\r\nbe a great deal better than sense. There is also a fourth kind of\r\nmadness--that of love--which cannot be explained without enquiring into\r\nthe nature of the soul.\r\n\r\nAll soul is immortal, for she is the source of all motion both in\r\nherself and in others. Her form may be described in a figure as a\r\ncomposite nature made up of a charioteer and a pair of winged steeds.\r\nThe steeds of the gods are immortal, but ours are one mortal and the\r\nother immortal. The immortal soul soars upwards into the heavens, but\r\nthe mortal drops her plumes and settles upon the earth.\r\n\r\nNow the use of the wing is to rise and carry the downward element into\r\nthe upper world--there to behold beauty, wisdom, goodness, and the other\r\nthings of God by which the soul is nourished. On a certain day Zeus the\r\nlord of heaven goes forth in a winged chariot; and an array of gods\r\nand demi-gods and of human souls in their train, follows him. There are\r\nglorious and blessed sights in the interior of heaven, and he who will\r\nmay freely behold them. The great vision of all is seen at the feast of\r\nthe gods, when they ascend the heights of the empyrean--all but Hestia,\r\nwho is left at home to keep house. The chariots of the gods glide\r\nreadily upwards and stand upon the outside; the revolution of the\r\nspheres carries them round, and they have a vision of the world beyond.\r\nBut the others labour in vain; for the mortal steed, if he has not been\r\nproperly trained, keeps them down and sinks them towards the earth. Of\r\nthe world which is beyond the heavens, who can tell? There is an essence\r\nformless, colourless, intangible, perceived by the mind only, dwelling\r\nin the region of true knowledge. The divine mind in her revolution\r\nenjoys this fair prospect, and beholds justice, temperance, and\r\nknowledge in their everlasting essence. When fulfilled with the sight\r\nof them she returns home, and the charioteer puts up the horses in their\r\nstable, and gives them ambrosia to eat and nectar to drink. This is the\r\nlife of the gods; the human soul tries to reach the same heights, but\r\nhardly succeeds; and sometimes the head of the charioteer rises above,\r\nand sometimes sinks below, the fair vision, and he is at last obliged,\r\nafter much contention, to turn away and leave the plain of truth. But if\r\nthe soul has followed in the train of her god and once beheld truth she\r\nis preserved from harm, and is carried round in the next revolution of\r\nthe spheres; and if always following, and always seeing the truth, is\r\nthen for ever unharmed. If, however, she drops her wings and falls to\r\nthe earth, then she takes the form of man, and the soul which has seen\r\nmost of the truth passes into a philosopher or lover; that which has\r\nseen truth in the second degree, into a king or warrior; the third, into\r\na householder or money-maker; the fourth, into a gymnast; the fifth,\r\ninto a prophet or mystic; the sixth, into a poet or imitator; the\r\nseventh, into a husbandman or craftsman; the eighth, into a sophist or\r\ndemagogue; the ninth, into a tyrant. All these are states of probation,\r\nwherein he who lives righteously is improved, and he who lives\r\nunrighteously deteriorates. After death comes the judgment; the bad\r\ndepart to houses of correction under the earth, the good to places\r\nof joy in heaven. When a thousand years have elapsed the souls meet\r\ntogether and choose the lives which they will lead for another period of\r\nexistence. The soul which three times in succession has chosen the life\r\nof a philosopher or of a lover who is not without philosophy receives\r\nher wings at the close of the third millennium; the remainder have to\r\ncomplete a cycle of ten thousand years before their wings are restored\r\nto them. Each time there is full liberty of choice. The soul of a man\r\nmay descend into a beast, and return again into the form of man. But the\r\nform of man will only be taken by the soul which has once seen truth and\r\nacquired some conception of the universal:--this is the recollection of\r\nthe knowledge which she attained when in the company of the Gods. And\r\nmen in general recall only with difficulty the things of another world,\r\nbut the mind of the philosopher has a better remembrance of them. For\r\nwhen he beholds the visible beauty of earth his enraptured soul passes\r\nin thought to those glorious sights of justice and wisdom and temperance\r\nand truth which she once gazed upon in heaven. Then she celebrated holy\r\nmysteries and beheld blessed apparitions shining in pure light, herself\r\npure, and not as yet entombed in the body. And still, like a bird eager\r\nto quit its cage, she flutters and looks upwards, and is therefore\r\ndeemed mad. Such a recollection of past days she receives through sight,\r\nthe keenest of our senses, because beauty, alone of the ideas, has any\r\nrepresentation on earth: wisdom is invisible to mortal eyes. But the\r\ncorrupted nature, blindly excited by this vision of beauty, rushes on\r\nto enjoy, and would fain wallow like a brute beast in sensual pleasures.\r\nWhereas the true mystic, who has seen the many sights of bliss, when he\r\nbeholds a god-like form or face is amazed with delight, and if he were\r\nnot afraid of being thought mad he would fall down and worship. Then\r\nthe stiffened wing begins to relax and grow again; desire which has\r\nbeen imprisoned pours over the soul of the lover; the germ of the wing\r\nunfolds, and stings, and pangs of birth, like the cutting of teeth, are\r\neverywhere felt. (Compare Symp.) Father and mother, and goods and laws\r\nand proprieties are nothing to him; his beloved is his physician, who\r\ncan alone cure his pain. An apocryphal sacred writer says that the power\r\nwhich thus works in him is by mortals called love, but the immortals\r\ncall him dove, or the winged one, in order to represent the force of\r\nhis wings--such at any rate is his nature. Now the characters of lovers\r\ndepend upon the god whom they followed in the other world; and they\r\nchoose their loves in this world accordingly. The followers of Ares\r\nare fierce and violent; those of Zeus seek out some philosophical and\r\nimperial nature; the attendants of Here find a royal love; and in like\r\nmanner the followers of every god seek a love who is like their god; and\r\nto him they communicate the nature which they have received from their\r\ngod. The manner in which they take their love is as follows:--\r\n\r\nI told you about the charioteer and his two steeds, the one a noble\r\nanimal who is guided by word and admonition only, the other an\r\nill-looking villain who will hardly yield to blow or spur. Together all\r\nthree, who are a figure of the soul, approach the vision of love. And\r\nnow a fierce conflict begins. The ill-conditioned steed rushes on to\r\nenjoy, but the charioteer, who beholds the beloved with awe, falls back\r\nin adoration, and forces both the steeds on their haunches; again the\r\nevil steed rushes forwards and pulls shamelessly. The conflict grows\r\nmore and more severe; and at last the charioteer, throwing himself\r\nbackwards, forces the bit out of the clenched teeth of the brute, and\r\npulling harder than ever at the reins, covers his tongue and jaws with\r\nblood, and forces him to rest his legs and haunches with pain upon the\r\nground. When this has happened several times, the villain is tamed and\r\nhumbled, and from that time forward the soul of the lover follows the\r\nbeloved in modesty and holy fear. And now their bliss is consummated;\r\nthe same image of love dwells in the breast of either, and if they have\r\nself-control, they pass their lives in the greatest happiness which is\r\nattainable by man--they continue masters of themselves, and conquer in\r\none of the three heavenly victories. But if they choose the lower\r\nlife of ambition they may still have a happy destiny, though inferior,\r\nbecause they have not the approval of the whole soul. At last they leave\r\nthe body and proceed on their pilgrim's progress, and those who have\r\nonce begun can never go back. When the time comes they receive their\r\nwings and fly away, and the lovers have the same wings.\r\n\r\nSocrates concludes:--\r\n\r\nThese are the blessings of love, and thus have I made my recantation in\r\nfiner language than before: I did so in order to please Phaedrus. If I\r\nsaid what was wrong at first, please to attribute my error to Lysias,\r\nwho ought to study philosophy instead of rhetoric, and then he will not\r\nmislead his disciple Phaedrus.\r\n\r\nPhaedrus is afraid that he will lose conceit of Lysias, and that Lysias\r\nwill be out of conceit with himself, and leave off making speeches,\r\nfor the politicians have been deriding him. Socrates is of opinion that\r\nthere is small danger of this; the politicians are themselves the\r\ngreat rhetoricians of the age, who desire to attain immortality by the\r\nauthorship of laws. And therefore there is nothing with which they can\r\nreproach Lysias in being a writer; but there may be disgrace in being a\r\nbad one.\r\n\r\nAnd what is good or bad writing or speaking? While the sun is hot in the\r\nsky above us, let us ask that question: since by rational conversation\r\nman lives, and not by the indulgence of bodily pleasures. And the\r\ngrasshoppers who are chirruping around may carry our words to the\r\nMuses, who are their patronesses; for the grasshoppers were human beings\r\nthemselves in a world before the Muses, and when the Muses came they\r\ndied of hunger for the love of song. And they carry to them in heaven\r\nthe report of those who honour them on earth.\r\n\r\nThe first rule of good speaking is to know and speak the truth; as a\r\nSpartan proverb says, 'true art is truth'; whereas rhetoric is an art of\r\nenchantment, which makes things appear good and evil, like and unlike,\r\nas the speaker pleases. Its use is not confined, as people commonly\r\nsuppose, to arguments in the law courts and speeches in the assembly;\r\nit is rather a part of the art of disputation, under which are included\r\nboth the rules of Gorgias and the eristic of Zeno. But it is not wholly\r\ndevoid of truth. Superior knowledge enables us to deceive another by the\r\nhelp of resemblances, and to escape from such a deception when employed\r\nagainst ourselves. We see therefore that even in rhetoric an element of\r\ntruth is required. For if we do not know the truth, we can neither make\r\nthe gradual departures from truth by which men are most easily deceived,\r\nnor guard ourselves against deception.\r\n\r\nSocrates then proposes that they shall use the two speeches as\r\nillustrations of the art of rhetoric; first distinguishing between the\r\ndebatable and undisputed class of subjects. In the debatable class there\r\nought to be a definition of all disputed matters. But there was no such\r\ndefinition in the speech of Lysias; nor is there any order or connection\r\nin his words any more than in a nursery rhyme. With this he compares the\r\nregular divisions of the other speech, which was his own (and yet not\r\nhis own, for the local deities must have inspired him). Although only a\r\nplayful composition, it will be found to embody two principles: first,\r\nthat of synthesis or the comprehension of parts in a whole; secondly,\r\nanalysis, or the resolution of the whole into parts. These are the\r\nprocesses of division and generalization which are so dear to the\r\ndialectician, that king of men. They are effected by dialectic, and\r\nnot by rhetoric, of which the remains are but scanty after order and\r\narrangement have been subtracted. There is nothing left but a heap\r\nof 'ologies' and other technical terms invented by Polus, Theodorus,\r\nEvenus, Tisias, Gorgias, and others, who have rules for everything, and\r\nwho teach how to be short or long at pleasure. Prodicus showed his good\r\nsense when he said that there was a better thing than either to be short\r\nor long, which was to be of convenient length.\r\n\r\nStill, notwithstanding the absurdities of Polus and others, rhetoric has\r\ngreat power in public assemblies. This power, however, is not given by\r\nany technical rules, but is the gift of genius. The real art is always\r\nbeing confused by rhetoricians with the preliminaries of the art. The\r\nperfection of oratory is like the perfection of anything else; natural\r\npower must be aided by art. But the art is not that which is taught in\r\nthe schools of rhetoric; it is nearer akin to philosophy. Pericles, for\r\ninstance, who was the most accomplished of all speakers, derived his\r\neloquence not from rhetoric but from the philosophy of nature which\r\nhe learnt of Anaxagoras. True rhetoric is like medicine, and the\r\nrhetorician has to consider the natures of men's souls as the physician\r\nconsiders the natures of their bodies. Such and such persons are to be\r\naffected in this way, such and such others in that; and he must know the\r\ntimes and the seasons for saying this or that. This is not an easy task,\r\nand this, if there be such an art, is the art of rhetoric.\r\n\r\nI know that there are some professors of the art who maintain\r\nprobability to be stronger than truth. But we maintain that probability\r\nis engendered by likeness of the truth which can only be attained by\r\nthe knowledge of it, and that the aim of the good man should not be to\r\nplease or persuade his fellow-servants, but to please his good masters\r\nwho are the gods. Rhetoric has a fair beginning in this.\r\n\r\nEnough of the art of speaking; let us now proceed to consider the true\r\nuse of writing. There is an old Egyptian tale of Theuth, the inventor of\r\nwriting, showing his invention to the god Thamus, who told him that he\r\nwould only spoil men's memories and take away their understandings. From\r\nthis tale, of which young Athens will probably make fun, may be gathered\r\nthe lesson that writing is inferior to speech. For it is like a picture,\r\nwhich can give no answer to a question, and has only a deceitful\r\nlikeness of a living creature. It has no power of adaptation, but uses\r\nthe same words for all. It is not a legitimate son of knowledge, but a\r\nbastard, and when an attack is made upon this bastard neither parent\r\nnor anyone else is there to defend it. The husbandman will not seriously\r\nincline to sow his seed in such a hot-bed or garden of Adonis; he will\r\nrather sow in the natural soil of the human soul which has depth of\r\nearth; and he will anticipate the inner growth of the mind, by writing\r\nonly, if at all, as a remedy against old age. The natural process will\r\nbe far nobler, and will bring forth fruit in the minds of others as well\r\nas in his own.\r\n\r\nThe conclusion of the whole matter is just this,--that until a man knows\r\nthe truth, and the manner of adapting the truth to the natures of other\r\nmen, he cannot be a good orator; also, that the living is better than\r\nthe written word, and that the principles of justice and truth when\r\ndelivered by word of mouth are the legitimate offspring of a man's own\r\nbosom, and their lawful descendants take up their abode in others.\r\nSuch an orator as he is who is possessed of them, you and I would fain\r\nbecome. And to all composers in the world, poets, orators, legislators,\r\nwe hereby announce that if their compositions are based upon these\r\nprinciples, then they are not only poets, orators, legislators, but\r\nphilosophers. All others are mere flatterers and putters together of\r\nwords. This is the message which Phaedrus undertakes to carry to Lysias\r\nfrom the local deities, and Socrates himself will carry a similar\r\nmessage to his favourite Isocrates, whose future distinction as a great\r\nrhetorician he prophesies. The heat of the day has passed, and after\r\noffering up a prayer to Pan and the nymphs, Socrates and Phaedrus\r\ndepart.\r\n\r\nThere are two principal controversies which have been raised about the\r\nPhaedrus; the first relates to the subject, the second to the date of\r\nthe Dialogue.\r\n\r\nThere seems to be a notion that the work of a great artist like Plato\r\ncannot fail in unity, and that the unity of a dialogue requires a single\r\nsubject. But the conception of unity really applies in very different\r\ndegrees and ways to different kinds of art; to a statue, for example,\r\nfar more than to any kind of literary composition, and to some species\r\nof literature far more than to others. Nor does the dialogue appear\r\nto be a style of composition in which the requirement of unity is most\r\nstringent; nor should the idea of unity derived from one sort of art\r\nbe hastily transferred to another. The double titles of several of the\r\nPlatonic Dialogues are a further proof that the severer rule was not\r\nobserved by Plato. The Republic is divided between the search after\r\njustice and the construction of the ideal state; the Parmenides between\r\nthe criticism of the Platonic ideas and of the Eleatic one or being;\r\nthe Gorgias between the art of speaking and the nature of the good;\r\nthe Sophist between the detection of the Sophist and the correlation\r\nof ideas. The Theaetetus, the Politicus, and the Philebus have also\r\ndigressions which are but remotely connected with the main subject.\r\n\r\nThus the comparison of Plato's other writings, as well as the reason of\r\nthe thing, lead us to the conclusion that we must not expect to find one\r\nidea pervading a whole work, but one, two, or more, as the invention\r\nof the writer may suggest, or his fancy wander. If each dialogue were\r\nconfined to the development of a single idea, this would appear on the\r\nface of the dialogue, nor could any controversy be raised as to whether\r\nthe Phaedrus treated of love or rhetoric. But the truth is that Plato\r\nsubjects himself to no rule of this sort. Like every great artist he\r\ngives unity of form to the different and apparently distracting topics\r\nwhich he brings together. He works freely and is not to be supposed to\r\nhave arranged every part of the dialogue before he begins to write.\r\nHe fastens or weaves together the frame of his discourse loosely and\r\nimperfectly, and which is the warp and which is the woof cannot always\r\nbe determined.\r\n\r\nThe subjects of the Phaedrus (exclusive of the short introductory\r\npassage about mythology which is suggested by the local tradition) are\r\nfirst the false or conventional art of rhetoric; secondly, love or the\r\ninspiration of beauty and knowledge, which is described as madness;\r\nthirdly, dialectic or the art of composition and division; fourthly, the\r\ntrue rhetoric, which is based upon dialectic, and is neither the art of\r\npersuasion nor knowledge of the truth alone, but the art of persuasion\r\nfounded on knowledge of truth and knowledge of character; fifthly, the\r\nsuperiority of the spoken over the written word. The continuous thread\r\nwhich appears and reappears throughout is rhetoric; this is the ground\r\ninto which the rest of the Dialogue is worked, in parts embroidered with\r\nfine words which are not in Socrates' manner, as he says, 'in order to\r\nplease Phaedrus.' The speech of Lysias which has thrown Phaedrus into an\r\necstacy is adduced as an example of the false rhetoric; the first speech\r\nof Socrates, though an improvement, partakes of the same character; his\r\nsecond speech, which is full of that higher element said to have been\r\nlearned of Anaxagoras by Pericles, and which in the midst of poetry does\r\nnot forget order, is an illustration of the higher or true rhetoric.\r\nThis higher rhetoric is based upon dialectic, and dialectic is a sort\r\nof inspiration akin to love (compare Symp.); in these two aspects of\r\nphilosophy the technicalities of rhetoric are absorbed. And so the\r\nexample becomes also the deeper theme of discourse. The true knowledge\r\nof things in heaven and earth is based upon enthusiasm or love of\r\nthe ideas going before us and ever present to us in this world and in\r\nanother; and the true order of speech or writing proceeds accordingly.\r\nLove, again, has three degrees: first, of interested love corresponding\r\nto the conventionalities of rhetoric; secondly, of disinterested or\r\nmad love, fixed on objects of sense, and answering, perhaps, to poetry;\r\nthirdly, of disinterested love directed towards the unseen, answering\r\nto dialectic or the science of the ideas. Lastly, the art of rhetoric\r\nin the lower sense is found to rest on a knowledge of the natures and\r\ncharacters of men, which Socrates at the commencement of the Dialogue\r\nhas described as his own peculiar study.\r\n\r\nThus amid discord a harmony begins to appear; there are many links of\r\nconnection which are not visible at first sight. At the same time the\r\nPhaedrus, although one of the most beautiful of the Platonic Dialogues,\r\nis also more irregular than any other. For insight into the world, for\r\nsustained irony, for depth of thought, there is no Dialogue superior,\r\nor perhaps equal to it. Nevertheless the form of the work has tended to\r\nobscure some of Plato's higher aims.\r\n\r\nThe first speech is composed 'in that balanced style in which the wise\r\nlove to talk' (Symp.). The characteristics of rhetoric are insipidity,\r\nmannerism, and monotonous parallelism of clauses. There is more rhythm\r\nthan reason; the creative power of imagination is wanting.\r\n\r\n''Tis Greece, but living Greece no more.'\r\n\r\nPlato has seized by anticipation the spirit which hung over Greek\r\nliterature for a thousand years afterwards. Yet doubtless there were\r\nsome who, like Phaedrus, felt a delight in the harmonious cadence and\r\nthe pedantic reasoning of the rhetoricians newly imported from Sicily,\r\nwhich had ceased to be awakened in them by really great works, such as\r\nthe odes of Anacreon or Sappho or the orations of Pericles. That the\r\nfirst speech was really written by Lysias is improbable. Like the poem\r\nof Solon, or the story of Thamus and Theuth, or the funeral oration of\r\nAspasia (if genuine), or the pretence of Socrates in the Cratylus that\r\nhis knowledge of philology is derived from Euthyphro, the invention\r\nis really due to the imagination of Plato, and may be compared to the\r\nparodies of the Sophists in the Protagoras. Numerous fictions of this\r\nsort occur in the Dialogues, and the gravity of Plato has sometimes\r\nimposed upon his commentators. The introduction of a considerable\r\nwriting of another would seem not to be in keeping with a great work of\r\nart, and has no parallel elsewhere.\r\n\r\nIn the second speech Socrates is exhibited as beating the rhetoricians\r\nat their own weapons; he 'an unpractised man and they masters of the\r\nart.' True to his character, he must, however, profess that the speech\r\nwhich he makes is not his own, for he knows nothing of himself. (Compare\r\nSymp.) Regarded as a rhetorical exercise, the superiority of his speech\r\nseems to consist chiefly in a better arrangement of the topics; he\r\nbegins with a definition of love, and he gives weight to his words by\r\ngoing back to general maxims; a lesser merit is the greater liveliness\r\nof Socrates, which hurries him into verse and relieves the monotony of\r\nthe style.\r\n\r\nBut Plato had doubtless a higher purpose than to exhibit Socrates as the\r\nrival or superior of the Athenian rhetoricians. Even in the speech of\r\nLysias there is a germ of truth, and this is further developed in the\r\nparallel oration of Socrates. First, passionate love is overthrown by\r\nthe sophistical or interested, and then both yield to that higher view\r\nof love which is afterwards revealed to us. The extreme of commonplace\r\nis contrasted with the most ideal and imaginative of speculations.\r\nSocrates, half in jest and to satisfy his own wild humour, takes the\r\ndisguise of Lysias, but he is also in profound earnest and in a deeper\r\nvein of irony than usual. Having improvised his own speech, which is\r\nbased upon the model of the preceding, he condemns them both. Yet the\r\ncondemnation is not to be taken seriously, for he is evidently trying\r\nto express an aspect of the truth. To understand him, we must make\r\nabstraction of morality and of the Greek manner of regarding the\r\nrelation of the sexes. In this, as in his other discussions about love,\r\nwhat Plato says of the loves of men must be transferred to the loves\r\nof women before we can attach any serious meaning to his words. Had he\r\nlived in our times he would have made the transposition himself. But\r\nseeing in his own age the impossibility of woman being the intellectual\r\nhelpmate or friend of man (except in the rare instances of a Diotima\r\nor an Aspasia), seeing that, even as to personal beauty, her place was\r\ntaken by young mankind instead of womankind, he tries to work out the\r\nproblem of love without regard to the distinctions of nature. And full\r\nof the evils which he recognized as flowing from the spurious form of\r\nlove, he proceeds with a deep meaning, though partly in joke, to show\r\nthat the 'non-lover's' love is better than the 'lover's.'\r\n\r\nWe may raise the same question in another form: Is marriage preferable\r\nwith or without love? 'Among ourselves,' as we may say, a little\r\nparodying the words of Pausanias in the Symposium, 'there would be\r\none answer to this question: the practice and feeling of some foreign\r\ncountries appears to be more doubtful.' Suppose a modern Socrates,\r\nin defiance of the received notions of society and the sentimental\r\nliterature of the day, alone against all the writers and readers of\r\nnovels, to suggest this enquiry, would not the younger 'part of the\r\nworld be ready to take off its coat and run at him might and main?'\r\n(Republic.) Yet, if like Peisthetaerus in Aristophanes, he could\r\npersuade the 'birds' to hear him, retiring a little behind a rampart,\r\nnot of pots and dishes, but of unreadable books, he might have something\r\nto say for himself. Might he not argue, 'that a rational being should\r\nnot follow the dictates of passion in the most important act of his or\r\nher life'? Who would willingly enter into a contract at first sight,\r\nalmost without thought, against the advice and opinion of his friends,\r\nat a time when he acknowledges that he is not in his right mind? And yet\r\nthey are praised by the authors of romances, who reject the warnings of\r\ntheir friends or parents, rather than those who listen to them in such\r\nmatters. Two inexperienced persons, ignorant of the world and of one\r\nanother, how can they be said to choose?--they draw lots, whence also\r\nthe saying, 'marriage is a lottery.' Then he would describe their way of\r\nlife after marriage; how they monopolize one another's affections to\r\nthe exclusion of friends and relations: how they pass their days in\r\nunmeaning fondness or trivial conversation; how the inferior of the\r\ntwo drags the other down to his or her level; how the cares of a family\r\n'breed meanness in their souls.' In the fulfilment of military or public\r\nduties, they are not helpers but hinderers of one another: they cannot\r\nundertake any noble enterprise, such as makes the names of men and women\r\nfamous, from domestic considerations. Too late their eyes are opened;\r\nthey were taken unawares and desire to part company. Better, he would\r\nsay, a 'little love at the beginning,' for heaven might have increased\r\nit; but now their foolish fondness has changed into mutual dislike. In\r\nthe days of their honeymoon they never understood that they must provide\r\nagainst offences, that they must have interests, that they must learn\r\nthe art of living as well as loving. Our misogamist will not appeal to\r\nAnacreon or Sappho for a confirmation of his view, but to the universal\r\nexperience of mankind. How much nobler, in conclusion, he will say, is\r\nfriendship, which does not receive unmeaning praises from novelists and\r\npoets, is not exacting or exclusive, is not impaired by familiarity, is\r\nmuch less expensive, is not so likely to take offence, seldom changes,\r\nand may be dissolved from time to time without the assistance of the\r\ncourts. Besides, he will remark that there is a much greater choice of\r\nfriends than of wives--you may have more of them and they will be far\r\nmore improving to your mind. They will not keep you dawdling at home, or\r\ndancing attendance upon them; or withdraw you from the great world and\r\nstirring scenes of life and action which would make a man of you.\r\n\r\nIn such a manner, turning the seamy side outwards, a modern Socrates\r\nmight describe the evils of married and domestic life. They are evils\r\nwhich mankind in general have agreed to conceal, partly because they are\r\ncompensated by greater goods. Socrates or Archilochus would soon have\r\nto sing a palinode for the injustice done to lovely Helen, or some\r\nmisfortune worse than blindness might be fall them. Then they would take\r\nup their parable again and say:--that there were two loves, a higher and\r\na lower, holy and unholy, a love of the mind and a love of the body.\r\n\r\n 'Let me not to the marriage of true minds\r\n Admit impediments. Love is not love\r\n Which alters when it alteration finds.\r\n\r\n .....\r\n\r\n Love's not time's fool, though rosy lips and cheeks\r\n Within his bending sickle's compass come;\r\n Love alters not with his brief hours and weeks,\r\n But bears it out even to the edge of doom.'\r\n\r\nBut this true love of the mind cannot exist between two souls, until\r\nthey are purified from the grossness of earthly passion: they must pass\r\nthrough a time of trial and conflict first; in the language of religion\r\nthey must be converted or born again. Then they would see the world\r\ntransformed into a scene of heavenly beauty; a divine idea would\r\naccompany them in all their thoughts and actions. Something too of the\r\nrecollections of childhood might float about them still; they might\r\nregain that old simplicity which had been theirs in other days at their\r\nfirst entrance on life. And although their love of one another was ever\r\npresent to them, they would acknowledge also a higher love of duty and\r\nof God, which united them. And their happiness would depend upon their\r\npreserving in them this principle--not losing the ideals of justice and\r\nholiness and truth, but renewing them at the fountain of light. When\r\nthey have attained to this exalted state, let them marry (something too\r\nmay be conceded to the animal nature of man): or live together in holy\r\nand innocent friendship. The poet might describe in eloquent words\r\nthe nature of such a union; how after many struggles the true love was\r\nfound: how the two passed their lives together in the service of God and\r\nman; how their characters were reflected upon one another, and seemed\r\nto grow more like year by year; how they read in one another's eyes the\r\nthoughts, wishes, actions of the other; how they saw each other in God;\r\nhow in a figure they grew wings like doves, and were 'ready to fly away\r\ntogether and be at rest.' And lastly, he might tell how, after a time\r\nat no long intervals, first one and then the other fell asleep, and\r\n'appeared to the unwise' to die, but were reunited in another state of\r\nbeing, in which they saw justice and holiness and truth, not according\r\nto the imperfect copies of them which are found in this world, but\r\njustice absolute in existence absolute, and so of the rest. And they\r\nwould hold converse not only with each other, but with blessed souls\r\neverywhere; and would be employed in the service of God, every soul\r\nfulfilling his own nature and character, and would see into the wonders\r\nof earth and heaven, and trace the works of creation to their author.\r\n\r\nSo, partly in jest but also 'with a certain degree of seriousness,'\r\nwe may appropriate to ourselves the words of Plato. The use of such a\r\nparody, though very imperfect, is to transfer his thoughts to our sphere\r\nof religion and feeling, to bring him nearer to us and us to him. Like\r\nthe Scriptures, Plato admits of endless applications, if we allow for\r\nthe difference of times and manners; and we lose the better half of\r\nhim when we regard his Dialogues merely as literary compositions. Any\r\nancient work which is worth reading has a practical and speculative as\r\nwell as a literary interest. And in Plato, more than in any other Greek\r\nwriter, the local and transitory is inextricably blended with what is\r\nspiritual and eternal. Socrates is necessarily ironical; for he has to\r\nwithdraw from the received opinions and beliefs of mankind. We cannot\r\nseparate the transitory from the permanent; nor can we translate the\r\nlanguage of irony into that of plain reflection and common sense. But we\r\ncan imagine the mind of Socrates in another age and country; and we can\r\ninterpret him by analogy with reference to the errors and prejudices\r\nwhich prevail among ourselves. To return to the Phaedrus:--\r\n\r\nBoth speeches are strongly condemned by Socrates as sinful and\r\nblasphemous towards the god Love, and as worthy only of some haunt of\r\nsailors to which good manners were unknown. The meaning of this and\r\nother wild language to the same effect, which is introduced by way of\r\ncontrast to the formality of the two speeches (Socrates has a sense of\r\nrelief when he has escaped from the trammels of rhetoric), seems to\r\nbe that the two speeches proceed upon the supposition that love is\r\nand ought to be interested, and that no such thing as a real or\r\ndisinterested passion, which would be at the same time lasting, could\r\nbe conceived. 'But did I call this \"love\"? O God, forgive my blasphemy.\r\nThis is not love. Rather it is the love of the world. But there is\r\nanother kingdom of love, a kingdom not of this world, divine, eternal.\r\nAnd this other love I will now show you in a mystery.'\r\n\r\nThen follows the famous myth, which is a sort of parable, and like other\r\nparables ought not to receive too minute an interpretation. In all such\r\nallegories there is a great deal which is merely ornamental, and the\r\ninterpreter has to separate the important from the unimportant. Socrates\r\nhimself has given the right clue when, in using his own discourse\r\nafterwards as the text for his examination of rhetoric, he characterizes\r\nit as a 'partly true and tolerably credible mythus,' in which amid\r\npoetical figures, order and arrangement were not forgotten.\r\n\r\nThe soul is described in magnificent language as the self-moved and the\r\nsource of motion in all other things. This is the philosophical theme or\r\nproem of the whole. But ideas must be given through something, and under\r\nthe pretext that to realize the true nature of the soul would be not\r\nonly tedious but impossible, we at once pass on to describe the souls\r\nof gods as well as men under the figure of two winged steeds and a\r\ncharioteer. No connection is traced between the soul as the great motive\r\npower and the triple soul which is thus imaged. There is no difficulty\r\nin seeing that the charioteer represents the reason, or that the black\r\nhorse is the symbol of the sensual or concupiscent element of human\r\nnature. The white horse also represents rational impulse, but the\r\ndescription, 'a lover of honour and modesty and temperance, and a\r\nfollower of true glory,' though similar, does not at once recall the\r\n'spirit' (thumos) of the Republic. The two steeds really correspond in a\r\nfigure more nearly to the appetitive and moral or semi-rational soul\r\nof Aristotle. And thus, for the first time perhaps in the history\r\nof philosophy, we have represented to us the threefold division of\r\npsychology. The image of the charioteer and the steeds has been compared\r\nwith a similar image which occurs in the verses of Parmenides; but it\r\nis important to remark that the horses of Parmenides have no allegorical\r\nmeaning, and that the poet is only describing his own approach in a\r\nchariot to the regions of light and the house of the goddess of truth.\r\n\r\nThe triple soul has had a previous existence, in which following in\r\nthe train of some god, from whom she derived her character, she beheld\r\npartially and imperfectly the vision of absolute truth. All her\r\nafter existence, passed in many forms of men and animals, is spent in\r\nregaining this. The stages of the conflict are many and various; and\r\nshe is sorely let and hindered by the animal desires of the inferior or\r\nconcupiscent steed. Again and again she beholds the flashing beauty of\r\nthe beloved. But before that vision can be finally enjoyed the animal\r\ndesires must be subjected.\r\n\r\nThe moral or spiritual element in man is represented by the immortal\r\nsteed which, like thumos in the Republic, always sides with the reason.\r\nBoth are dragged out of their course by the furious impulses of desire.\r\nIn the end something is conceded to the desires, after they have been\r\nfinally humbled and overpowered. And yet the way of philosophy, or\r\nperfect love of the unseen, is total abstinence from bodily delights.\r\n'But all men cannot receive this saying': in the lower life of ambition\r\nthey may be taken off their guard and stoop to folly unawares, and then,\r\nalthough they do not attain to the highest bliss, yet if they have once\r\nconquered they may be happy enough.\r\n\r\nThe language of the Meno and the Phaedo as well as of the Phaedrus\r\nseems to show that at one time of his life Plato was quite serious in\r\nmaintaining a former state of existence. His mission was to realize the\r\nabstract; in that, all good and truth, all the hopes of this and another\r\nlife seemed to centre. To him abstractions, as we call them, were\r\nanother kind of knowledge--an inner and unseen world, which seemed\r\nto exist far more truly than the fleeting objects of sense which were\r\nwithout him. When we are once able to imagine the intense power which\r\nabstract ideas exercised over the mind of Plato, we see that there was\r\nno more difficulty to him in realizing the eternal existence of them\r\nand of the human minds which were associated with them, in the past and\r\nfuture than in the present. The difficulty was not how they could exist,\r\nbut how they could fail to exist. In the attempt to regain this 'saving'\r\nknowledge of the ideas, the sense was found to be as great an enemy as\r\nthe desires; and hence two things which to us seem quite distinct are\r\ninextricably blended in the representation of Plato.\r\n\r\nThus far we may believe that Plato was serious in his conception of the\r\nsoul as a motive power, in his reminiscence of a former state of being,\r\nin his elevation of the reason over sense and passion, and perhaps in\r\nhis doctrine of transmigration. Was he equally serious in the rest? For\r\nexample, are we to attribute his tripartite division of the soul to the\r\ngods? Or is this merely assigned to them by way of parallelism with men?\r\nThe latter is the more probable; for the horses of the gods are both\r\nwhite, i.e. their every impulse is in harmony with reason; their\r\ndualism, on the other hand, only carries out the figure of the chariot.\r\nIs he serious, again, in regarding love as 'a madness'? That seems to\r\narise out of the antithesis to the former conception of love. At the\r\nsame time he appears to intimate here, as in the Ion, Apology, Meno,\r\nand elsewhere, that there is a faculty in man, whether to be termed in\r\nmodern language genius, or inspiration, or imagination, or idealism,\r\nor communion with God, which cannot be reduced to rule and measure.\r\nPerhaps, too, he is ironically repeating the common language of mankind\r\nabout philosophy, and is turning their jest into a sort of earnest.\r\n(Compare Phaedo, Symp.) Or is he serious in holding that each soul bears\r\nthe character of a god? He may have had no other account to give of\r\nthe differences of human characters to which he afterwards refers. Or,\r\nagain, in his absurd derivation of mantike and oionistike and imeros\r\n(compare Cratylus)? It is characteristic of the irony of Socrates to\r\nmix up sense and nonsense in such a way that no exact line can be drawn\r\nbetween them. And allegory helps to increase this sort of confusion.\r\n\r\nAs is often the case in the parables and prophecies of Scripture, the\r\nmeaning is allowed to break through the figure, and the details are not\r\nalways consistent. When the charioteers and their steeds stand upon the\r\ndome of heaven they behold the intangible invisible essences which\r\nare not objects of sight. This is because the force of language can\r\nno further go. Nor can we dwell much on the circumstance, that at the\r\ncompletion of ten thousand years all are to return to the place from\r\nwhence they came; because he represents their return as dependent on\r\ntheir own good conduct in the successive stages of existence. Nor again\r\ncan we attribute anything to the accidental inference which would also\r\nfollow, that even a tyrant may live righteously in the condition of life\r\nto which fate has called him ('he aiblins might, I dinna ken'). But\r\nto suppose this would be at variance with Plato himself and with Greek\r\nnotions generally. He is much more serious in distinguishing men from\r\nanimals by their recognition of the universal which they have known in\r\na former state, and in denying that this gift of reason can ever be\r\nobliterated or lost. In the language of some modern theologians he might\r\nbe said to maintain the 'final perseverance' of those who have entered\r\non their pilgrim's progress. Other intimations of a 'metaphysic' or\r\n'theology' of the future may also be discerned in him: (1) The moderate\r\npredestinarianism which here, as in the Republic, acknowledges the\r\nelement of chance in human life, and yet asserts the freedom and\r\nresponsibility of man; (2) The recognition of a moral as well as an\r\nintellectual principle in man under the image of an immortal steed; (3)\r\nThe notion that the divine nature exists by the contemplation of\r\nideas of virtue and justice--or, in other words, the assertion of the\r\nessentially moral nature of God; (4) Again, there is the hint that human\r\nlife is a life of aspiration only, and that the true ideal is not to\r\nbe found in art; (5) There occurs the first trace of the distinction\r\nbetween necessary and contingent matter; (6) The conception of the soul\r\nitself as the motive power and reason of the universe.\r\n\r\nThe conception of the philosopher, or the philosopher and lover in one,\r\nas a sort of madman, may be compared with the Republic and Theaetetus,\r\nin both of which the philosopher is regarded as a stranger and monster\r\nupon the earth. The whole myth, like the other myths of Plato, describes\r\nin a figure things which are beyond the range of human faculties, or\r\ninaccessible to the knowledge of the age. That philosophy should be\r\nrepresented as the inspiration of love is a conception that has already\r\nbecome familiar to us in the Symposium, and is the expression partly of\r\nPlato's enthusiasm for the idea, and is also an indication of the real\r\npower exercised by the passion of friendship over the mind of the Greek.\r\nThe master in the art of love knew that there was a mystery in these\r\nfeelings and their associations, and especially in the contrast of\r\nthe sensible and permanent which is afforded by them; and he sought\r\nto explain this, as he explained universal ideas, by a reference to a\r\nformer state of existence. The capriciousness of love is also derived\r\nby him from an attachment to some god in a former world. The singular\r\nremark that the beloved is more affected than the lover at the final\r\nconsummation of their love, seems likewise to hint at a psychological\r\ntruth.\r\n\r\nIt is difficult to exhaust the meanings of a work like the Phaedrus,\r\nwhich indicates so much more than it expresses; and is full of\r\ninconsistencies and ambiguities which were not perceived by Plato\r\nhimself. For example, when he is speaking of the soul does he mean the\r\nhuman or the divine soul? and are they both equally self-moving and\r\nconstructed on the same threefold principle? We should certainly be\r\ndisposed to reply that the self-motive is to be attributed to God only;\r\nand on the other hand that the appetitive and passionate elements have\r\nno place in His nature. So we should infer from the reason of the thing,\r\nbut there is no indication in Plato's own writings that this was his\r\nmeaning. Or, again, when he explains the different characters of men\r\nby referring them back to the nature of the God whom they served in a\r\nformer state of existence, we are inclined to ask whether he is serious:\r\nIs he not rather using a mythological figure, here as elsewhere, to draw\r\na veil over things which are beyond the limits of mortal knowledge? Once\r\nmore, in speaking of beauty is he really thinking of some external form\r\nsuch as might have been expressed in the works of Phidias or Praxiteles;\r\nand not rather of an imaginary beauty, of a sort which extinguishes\r\nrather than stimulates vulgar love,--a heavenly beauty like that which\r\nflashed from time to time before the eyes of Dante or Bunyan? Surely\r\nthe latter. But it would be idle to reconcile all the details of the\r\npassage: it is a picture, not a system, and a picture which is for the\r\ngreater part an allegory, and an allegory which allows the meaning to\r\ncome through. The image of the charioteer and his steeds is placed side\r\nby side with the absolute forms of justice, temperance, and the like,\r\nwhich are abstract ideas only, and which are seen with the eye of the\r\nsoul in her heavenly journey. The first impression of such a passage, in\r\nwhich no attempt is made to separate the substance from the form, is far\r\ntruer than an elaborate philosophical analysis.\r\n\r\nIt is too often forgotten that the whole of the second discourse of\r\nSocrates is only an allegory, or figure of speech. For this reason, it\r\nis unnecessary to enquire whether the love of which Plato speaks is\r\nthe love of men or of women. It is really a general idea which includes\r\nboth, and in which the sensual element, though not wholly eradicated, is\r\nreduced to order and measure. We must not attribute a meaning to\r\nevery fanciful detail. Nor is there any need to call up revolting\r\nassociations, which as a matter of good taste should be banished, and\r\nwhich were far enough away from the mind of Plato. These and similar\r\npassages should be interpreted by the Laws. Nor is there anything in the\r\nSymposium, or in the Charmides, in reality inconsistent with the sterner\r\nrule which Plato lays down in the Laws. At the same time it is not to be\r\ndenied that love and philosophy are described by Socrates in figures\r\nof speech which would not be used in Christian times; or that nameless\r\nvices were prevalent at Athens and in other Greek cities; or that\r\nfriendships between men were a more sacred tie, and had a more important\r\nsocial and educational influence than among ourselves. (See note on\r\nSymposium.)\r\n\r\nIn the Phaedrus, as well as in the Symposium, there are two kinds of\r\nlove, a lower and a higher, the one answering to the natural wants of\r\nthe animal, the other rising above them and contemplating with religious\r\nawe the forms of justice, temperance, holiness, yet finding them\r\nalso 'too dazzling bright for mortal eye,' and shrinking from them\r\nin amazement. The opposition between these two kinds of love may be\r\ncompared to the opposition between the flesh and the spirit in the\r\nEpistles of St. Paul. It would be unmeaning to suppose that Plato, in\r\ndescribing the spiritual combat, in which the rational soul is\r\nfinally victor and master of both the steeds, condescends to allow any\r\nindulgence of unnatural lusts.\r\n\r\nTwo other thoughts about love are suggested by this passage. First of\r\nall, love is represented here, as in the Symposium, as one of the great\r\npowers of nature, which takes many forms and two principal ones, having\r\na predominant influence over the lives of men. And these two, though\r\nopposed, are not absolutely separated the one from the other. Plato,\r\nwith his great knowledge of human nature, was well aware how easily\r\none is transformed into the other, or how soon the noble but fleeting\r\naspiration may return into the nature of the animal, while the\r\nlower instinct which is latent always remains. The intermediate\r\nsentimentalism, which has exercised so great an influence on the\r\nliterature of modern Europe, had no place in the classical times of\r\nHellas; the higher love, of which Plato speaks, is the subject, not of\r\npoetry or fiction, but of philosophy.\r\n\r\nSecondly, there seems to be indicated a natural yearning of the human\r\nmind that the great ideas of justice, temperance, wisdom, should be\r\nexpressed in some form of visible beauty, like the absolute purity and\r\ngoodness which Christian art has sought to realize in the person of\r\nthe Madonna. But although human nature has often attempted to represent\r\noutwardly what can be only 'spiritually discerned,' men feel that in\r\npictures and images, whether painted or carved, or described in words\r\nonly, we have not the substance but the shadow of the truth which is in\r\nheaven. There is no reason to suppose that in the fairest works of Greek\r\nart, Plato ever conceived himself to behold an image, however faint, of\r\nideal truths. 'Not in that way was wisdom seen.'\r\n\r\nWe may now pass on to the second part of the Dialogue, which is a\r\ncriticism on the first. Rhetoric is assailed on various grounds: first,\r\nas desiring to persuade, without a knowledge of the truth; and secondly,\r\nas ignoring the distinction between certain and probable matter. The\r\nthree speeches are then passed in review: the first of them has no\r\ndefinition of the nature of love, and no order in the topics (being in\r\nthese respects far inferior to the second); while the third of them is\r\nfound (though a fancy of the hour) to be framed upon real dialectical\r\nprinciples. But dialectic is not rhetoric; nothing on that subject is to\r\nbe found in the endless treatises of rhetoric, however prolific in hard\r\nnames. When Plato has sufficiently put them to the test of ridicule he\r\ntouches, as with the point of a needle, the real error, which is the\r\nconfusion of preliminary knowledge with creative power. No attainments\r\nwill provide the speaker with genius; and the sort of attainments which\r\ncan alone be of any value are the higher philosophy and the power of\r\npsychological analysis, which is given by dialectic, but not by the\r\nrules of the rhetoricians.\r\n\r\nIn this latter portion of the Dialogue there are many texts which may\r\nhelp us to speak and to think. The names dialectic and rhetoric are\r\npassing out of use; we hardly examine seriously into their nature and\r\nlimits, and probably the arts both of speaking and of conversation have\r\nbeen unduly neglected by us. But the mind of Socrates pierces through\r\nthe differences of times and countries into the essential nature of man;\r\nand his words apply equally to the modern world and to the Athenians of\r\nold. Would he not have asked of us, or rather is he not asking of us,\r\nWhether we have ceased to prefer appearances to reality? Let us take\r\na survey of the professions to which he refers and try them by his\r\nstandard. Is not all literature passing into criticism, just as Athenian\r\nliterature in the age of Plato was degenerating into sophistry and\r\nrhetoric? We can discourse and write about poems and paintings, but we\r\nseem to have lost the gift of creating them. Can we wonder that few\r\nof them 'come sweetly from nature,' while ten thousand reviewers (mala\r\nmurioi) are engaged in dissecting them? Young men, like Phaedrus, are\r\nenamoured of their own literary clique and have but a feeble sympathy\r\nwith the master-minds of former ages. They recognize 'a POETICAL\r\nnecessity in the writings of their favourite author, even when he boldly\r\nwrote off just what came in his head.' They are beginning to think that\r\nArt is enough, just at the time when Art is about to disappear from the\r\nworld. And would not a great painter, such as Michael Angelo, or a great\r\npoet, such as Shakespeare, returning to earth, 'courteously rebuke'\r\nus--would he not say that we are putting 'in the place of Art the\r\npreliminaries of Art,' confusing Art the expression of mind and truth\r\nwith Art the composition of colours and forms; and perhaps he might\r\nmore severely chastise some of us for trying to invent 'a new shudder'\r\ninstead of bringing to the birth living and healthy creations? These he\r\nwould regard as the signs of an age wanting in original power.\r\n\r\nTurning from literature and the arts to law and politics, again we fall\r\nunder the lash of Socrates. For do we not often make 'the worse appear\r\nthe better cause;' and do not 'both parties sometimes agree to tell\r\nlies'? Is not pleading 'an art of speaking unconnected with the truth'?\r\nThere is another text of Socrates which must not be forgotten in\r\nrelation to this subject. In the endless maze of English law is there\r\nany 'dividing the whole into parts or reuniting the parts into a\r\nwhole'--any semblance of an organized being 'having hands and feet and\r\nother members'? Instead of a system there is the Chaos of Anaxagoras\r\n(omou panta chremata) and no Mind or Order. Then again in the noble\r\nart of politics, who thinks of first principles and of true ideas?\r\nWe avowedly follow not the truth but the will of the many (compare\r\nRepublic). Is not legislation too a sort of literary effort, and might\r\nnot statesmanship be described as the 'art of enchanting' the house?\r\nWhile there are some politicians who have no knowledge of the truth, but\r\nonly of what is likely to be approved by 'the many who sit in judgment,'\r\nthere are others who can give no form to their ideal, neither having\r\nlearned 'the art of persuasion,' nor having any insight into the\r\n'characters of men.' Once more, has not medical science become a\r\nprofessional routine, which many 'practise without being able to say\r\nwho were their instructors'--the application of a few drugs taken from\r\na book instead of a life-long study of the natures and constitutions of\r\nhuman beings? Do we see as clearly as Hippocrates 'that the nature of\r\nthe body can only be understood as a whole'? (Compare Charm.) And are\r\nnot they held to be the wisest physicians who have the greatest distrust\r\nof their art? What would Socrates think of our newspapers, of our\r\ntheology? Perhaps he would be afraid to speak of them;--the one vox\r\npopuli, the other vox Dei, he might hesitate to attack them; or he might\r\ntrace a fanciful connexion between them, and ask doubtfully, whether\r\nthey are not equally inspired? He would remark that we are always\r\nsearching for a belief and deploring our unbelief, seeming to prefer\r\npopular opinions unverified and contradictory to unpopular truths which\r\nare assured to us by the most certain proofs: that our preachers are\r\nin the habit of praising God 'without regard to truth and falsehood,\r\nattributing to Him every species of greatness and glory, saying that He\r\nis all this and the cause of all that, in order that we may exhibit Him\r\nas the fairest and best of all' (Symp.) without any consideration of\r\nHis real nature and character or of the laws by which He governs the\r\nworld--seeking for a 'private judgment' and not for the truth or 'God's\r\njudgment.' What would he say of the Church, which we praise in like\r\nmanner, 'meaning ourselves,' without regard to history or experience?\r\nMight he not ask, whether we 'care more for the truth of religion, or\r\nfor the speaker and the country from which the truth comes'? or, whether\r\nthe 'select wise' are not 'the many' after all? (Symp.) So we may fill\r\nup the sketch of Socrates, lest, as Phaedrus says, the argument should\r\nbe too 'abstract and barren of illustrations.' (Compare Symp., Apol.,\r\nEuthyphro.)\r\n\r\nHe next proceeds with enthusiasm to define the royal art of dialectic as\r\nthe power of dividing a whole into parts, and of uniting the parts in a\r\nwhole, and which may also be regarded (compare Soph.) as the process of\r\nthe mind talking with herself. The latter view has probably led Plato\r\nto the paradox that speech is superior to writing, in which he may seem\r\nalso to be doing an injustice to himself. For the two cannot be fairly\r\ncompared in the manner which Plato suggests. The contrast of the living\r\nand dead word, and the example of Socrates, which he has represented\r\nin the form of the Dialogue, seem to have misled him. For speech and\r\nwriting have really different functions; the one is more transitory,\r\nmore diffuse, more elastic and capable of adaptation to moods and times;\r\nthe other is more permanent, more concentrated, and is uttered not to\r\nthis or that person or audience, but to all the world. In the Politicus\r\nthe paradox is carried further; the mind or will of the king is\r\npreferred to the written law; he is supposed to be the Law personified,\r\nthe ideal made Life.\r\n\r\nYet in both these statements there is also contained a truth; they may\r\nbe compared with one another, and also with the other famous paradox,\r\nthat 'knowledge cannot be taught.' Socrates means to say, that what is\r\ntruly written is written in the soul, just as what is truly taught grows\r\nup in the soul from within and is not forced upon it from without. When\r\nplanted in a congenial soil the little seed becomes a tree, and 'the\r\nbirds of the air build their nests in the branches.' There is an echo\r\nof this in the prayer at the end of the Dialogue, 'Give me beauty in\r\nthe inward soul, and may the inward and outward man be at one.' We may\r\nfurther compare the words of St. Paul, 'Written not on tables of stone,\r\nbut on fleshly tables of the heart;' and again, 'Ye are my epistles\r\nknown and read of all men.' There may be a use in writing as a\r\npreservative against the forgetfulness of old age, but to live is higher\r\nfar, to be ourselves the book, or the epistle, the truth embodied in a\r\nperson, the Word made flesh. Something like this we may believe to have\r\npassed before Plato's mind when he affirmed that speech was superior to\r\nwriting. So in other ages, weary of literature and criticism, of making\r\nmany books, of writing articles in reviews, some have desired to live\r\nmore closely in communion with their fellow-men, to speak heart to\r\nheart, to speak and act only, and not to write, following the example of\r\nSocrates and of Christ...\r\n\r\nSome other touches of inimitable grace and art and of the deepest wisdom\r\nmay be also noted; such as the prayer or 'collect' which has just been\r\ncited, 'Give me beauty,' etc.; or 'the great name which belongs to God\r\nalone;' or 'the saying of wiser men than ourselves that a man of sense\r\nshould try to please not his fellow-servants, but his good and noble\r\nmasters,' like St. Paul again; or the description of the 'heavenly\r\noriginals'...\r\n\r\nThe chief criteria for determining the date of the Dialogue are (1) the\r\nages of Lysias and Isocrates; (2) the character of the work.\r\n\r\nLysias was born in the year 458; Isocrates in the year 436, about seven\r\nyears before the birth of Plato. The first of the two great rhetoricians\r\nis described as in the zenith of his fame; the second is still young and\r\nfull of promise. Now it is argued that this must have been written in\r\nthe youth of Isocrates, when the promise was not yet fulfilled. And thus\r\nwe should have to assign the Dialogue to a year not later than 406,\r\nwhen Isocrates was thirty and Plato twenty-three years of age, and while\r\nSocrates himself was still alive.\r\n\r\nThose who argue in this way seem not to reflect how easily Plato\r\ncan 'invent Egyptians or anything else,' and how careless he is of\r\nhistorical truth or probability. Who would suspect that the wise\r\nCritias, the virtuous Charmides, had ended their lives among the\r\nthirty tyrants? Who would imagine that Lysias, who is here assailed\r\nby Socrates, is the son of his old friend Cephalus? Or that Isocrates\r\nhimself is the enemy of Plato and his school? No arguments can be drawn\r\nfrom the appropriateness or inappropriateness of the characters of\r\nPlato. (Else, perhaps, it might be further argued that, judging from\r\ntheir extant remains, insipid rhetoric is far more characteristic of\r\nIsocrates than of Lysias.) But Plato makes use of names which have\r\noften hardly any connection with the historical characters to whom they\r\nbelong. In this instance the comparative favour shown to Isocrates may\r\npossibly be accounted for by the circumstance of his belonging to the\r\naristocratical, as Lysias to the democratical party.\r\n\r\nFew persons will be inclined to suppose, in the superficial manner\r\nof some ancient critics, that a dialogue which treats of love must\r\nnecessarily have been written in youth. As little weight can be attached\r\nto the argument that Plato must have visited Egypt before he wrote the\r\nstory of Theuth and Thamus. For there is no real proof that he ever went\r\nto Egypt; and even if he did, he might have known or invented Egyptian\r\ntraditions before he went there. The late date of the Phaedrus will have\r\nto be established by other arguments than these: the maturity of the\r\nthought, the perfection of the style, the insight, the relation to the\r\nother Platonic Dialogues, seem to contradict the notion that it could\r\nhave been the work of a youth of twenty or twenty-three years of age.\r\nThe cosmological notion of the mind as the primum mobile, and the\r\nadmission of impulse into the immortal nature, also afford grounds for\r\nassigning a later date. (Compare Tim., Soph., Laws.) Add to this that\r\nthe picture of Socrates, though in some lesser particulars,--e.g. his\r\ngoing without sandals, his habit of remaining within the walls,\r\nhis emphatic declaration that his study is human nature,--an exact\r\nresemblance, is in the main the Platonic and not the real Socrates. Can\r\nwe suppose 'the young man to have told such lies' about his master\r\nwhile he was still alive? Moreover, when two Dialogues are so closely\r\nconnected as the Phaedrus and Symposium, there is great improbability in\r\nsupposing that one of them was written at least twenty years after the\r\nother. The conclusion seems to be, that the Dialogue was written at\r\nsome comparatively late but unknown period of Plato's life, after he had\r\ndeserted the purely Socratic point of view, but before he had entered\r\non the more abstract speculations of the Sophist or the Philebus. Taking\r\ninto account the divisions of the soul, the doctrine of transmigration,\r\nthe contemplative nature of the philosophic life, and the character\r\nof the style, we shall not be far wrong in placing the Phaedrus in the\r\nneighbourhood of the Republic; remarking only that allowance must be\r\nmade for the poetical element in the Phaedrus, which, while falling\r\nshort of the Republic in definite philosophic results, seems to have\r\nglimpses of a truth beyond.\r\n\r\nTwo short passages, which are unconnected with the main subject of the\r\nDialogue, may seem to merit a more particular notice: (1) the locus\r\nclassicus about mythology; (2) the tale of the grasshoppers.\r\n\r\nThe first passage is remarkable as showing that Plato was entirely\r\nfree from what may be termed the Euhemerism of his age. For there were\r\nEuhemerists in Hellas long before Euhemerus. Early philosophers, like\r\nAnaxagoras and Metrodorus, had found in Homer and mythology hidden\r\nmeanings. Plato, with a truer instinct, rejects these attractive\r\ninterpretations; he regards the inventor of them as 'unfortunate;' and\r\nthey draw a man off from the knowledge of himself. There is a latent\r\ncriticism, and also a poetical sense in Plato, which enable him to\r\ndiscard them, and yet in another way to make use of poetry and mythology\r\nas a vehicle of thought and feeling. What would he have said of the\r\ndiscovery of Christian doctrines in these old Greek legends? While\r\nacknowledging that such interpretations are 'very nice,' would he not\r\nhave remarked that they are found in all sacred literatures? They cannot\r\nbe tested by any criterion of truth, or used to establish any truth;\r\nthey add nothing to the sum of human knowledge; they are--what we\r\nplease, and if employed as 'peacemakers' between the new and old are\r\nliable to serious misconstruction, as he elsewhere remarks (Republic).\r\nAnd therefore he would have 'bid Farewell to them; the study of them\r\nwould take up too much of his time; and he has not as yet learned the\r\ntrue nature of religion.' The 'sophistical' interest of Phaedrus, the\r\nlittle touch about the two versions of the story, the ironical manner in\r\nwhich these explanations are set aside--'the common opinion about them\r\nis enough for me'--the allusion to the serpent Typho may be noted in\r\npassing; also the general agreement between the tone of this speech and\r\nthe remark of Socrates which follows afterwards, 'I am a diviner, but a\r\npoor one.'\r\n\r\nThe tale of the grasshoppers is naturally suggested by the surrounding\r\nscene. They are also the representatives of the Athenians as children\r\nof the soil. Under the image of the lively chirruping grasshoppers who\r\ninform the Muses in heaven about those who honour them on earth, Plato\r\nintends to represent an Athenian audience (tettigessin eoikotes). The\r\nstory is introduced, apparently, to mark a change of subject, and also,\r\nlike several other allusions which occur in the course of the Dialogue,\r\nin order to preserve the scene in the recollection of the reader.\r\n\r\n*****\r\n\r\nNo one can duly appreciate the dialogues of Plato, especially the\r\nPhaedrus, Symposium, and portions of the Republic, who has not a\r\nsympathy with mysticism. To the uninitiated, as he would himself\r\nhave acknowledged, they will appear to be the dreams of a poet who\r\nis disguised as a philosopher. There is a twofold difficulty in\r\napprehending this aspect of the Platonic writings. First, we do not\r\nimmediately realize that under the marble exterior of Greek literature\r\nwas concealed a soul thrilling with spiritual emotion. Secondly, the\r\nforms or figures which the Platonic philosophy assumes, are not like the\r\nimages of the prophet Isaiah, or of the Apocalypse, familiar to us in\r\nthe days of our youth. By mysticism we mean, not the extravagance of\r\nan erring fancy, but the concentration of reason in feeling, the\r\nenthusiastic love of the good, the true, the one, the sense of the\r\ninfinity of knowledge and of the marvel of the human faculties. When\r\nfeeding upon such thoughts the 'wing of the soul' is renewed and\r\ngains strength; she is raised above 'the manikins of earth' and their\r\nopinions, waiting in wonder to know, and working with reverence to find\r\nout what God in this or in another life may reveal to her.\r\n\r\n\r\nON THE DECLINE OF GREEK LITERATURE.\r\n\r\nOne of the main purposes of Plato in the Phaedrus is to satirize\r\nRhetoric, or rather the Professors of Rhetoric who swarmed at Athens in\r\nthe fourth century before Christ. As in the opening of the Dialogue he\r\nridicules the interpreters of mythology; as in the Protagoras he mocks\r\nat the Sophists; as in the Euthydemus he makes fun of the word-splitting\r\nEristics; as in the Cratylus he ridicules the fancies of Etymologers;\r\nas in the Meno and Gorgias and some other dialogues he makes reflections\r\nand casts sly imputation upon the higher classes at Athens; so in\r\nthe Phaedrus, chiefly in the latter part, he aims his shafts at the\r\nrhetoricians. The profession of rhetoric was the greatest and most\r\npopular in Athens, necessary 'to a man's salvation,' or at any rate to\r\nhis attainment of wealth or power; but Plato finds nothing wholesome\r\nor genuine in the purpose of it. It is a veritable 'sham,' having no\r\nrelation to fact, or to truth of any kind. It is antipathetic to him not\r\nonly as a philosopher, but also as a great writer. He cannot abide the\r\ntricks of the rhetoricians, or the pedantries and mannerisms which they\r\nintroduce into speech and writing. He sees clearly how far removed they\r\nare from the ways of simplicity and truth, and how ignorant of the very\r\nelements of the art which they are professing to teach. The thing which\r\nis most necessary of all, the knowledge of human nature, is hardly if\r\nat all considered by them. The true rules of composition, which are\r\nvery few, are not to be found in their voluminous systems. Their\r\npretentiousness, their omniscience, their large fortunes, their\r\nimpatience of argument, their indifference to first principles, their\r\nstupidity, their progresses through Hellas accompanied by a troop\r\nof their disciples--these things were very distasteful to Plato, who\r\nesteemed genius far above art, and was quite sensible of the interval\r\nwhich separated them (Phaedrus). It is the interval which separates\r\nSophists and rhetoricians from ancient famous men and women such as\r\nHomer and Hesiod, Anacreon and Sappho, Aeschylus and Sophocles; and the\r\nPlatonic Socrates is afraid that, if he approves the former, he will be\r\ndisowned by the latter. The spirit of rhetoric was soon to overspread\r\nall Hellas; and Plato with prophetic insight may have seen, from afar,\r\nthe great literary waste or dead level, or interminable marsh, in which\r\nGreek literature was soon to disappear. A similar vision of the decline\r\nof the Greek drama and of the contrast of the old literature and the\r\nnew was present to the mind of Aristophanes after the death of the three\r\ngreat tragedians (Frogs). After about a hundred, or at most two hundred\r\nyears if we exclude Homer, the genius of Hellas had ceased to flower or\r\nblossom. The dreary waste which follows, beginning with the Alexandrian\r\nwriters and even before them in the platitudes of Isocrates and his\r\nschool, spreads over much more than a thousand years. And from this\r\ndecline the Greek language and literature, unlike the Latin, which has\r\ncome to life in new forms and been developed into the great European\r\nlanguages, never recovered.\r\n\r\nThis monotony of literature, without merit, without genius and without\r\ncharacter, is a phenomenon which deserves more attention than it has\r\nhitherto received; it is a phenomenon unique in the literary history\r\nof the world. How could there have been so much cultivation, so much\r\ndiligence in writing, and so little mind or real creative power? Why\r\ndid a thousand years invent nothing better than Sibylline books,\r\nOrphic poems, Byzantine imitations of classical histories, Christian\r\nreproductions of Greek plays, novels like the silly and obscene romances\r\nof Longus and Heliodorus, innumerable forged epistles, a great many\r\nepigrams, biographies of the meanest and most meagre description, a sham\r\nphilosophy which was the bastard progeny of the union between Hellas\r\nand the East? Only in Plutarch, in Lucian, in Longinus, in the Roman\r\nemperors Marcus Aurelius and Julian, in some of the Christian fathers\r\nare there any traces of good sense or originality, or any power of\r\narousing the interest of later ages. And when new books ceased to be\r\nwritten, why did hosts of grammarians and interpreters flock in, who\r\nnever attain to any sound notion either of grammar or interpretation?\r\nWhy did the physical sciences never arrive at any true knowledge or make\r\nany real progress? Why did poetry droop and languish? Why did history\r\ndegenerate into fable? Why did words lose their power of expression?\r\nWhy were ages of external greatness and magnificence attended by all the\r\nsigns of decay in the human mind which are possible?\r\n\r\nTo these questions many answers may be given, which if not the true\r\ncauses, are at least to be reckoned among the symptoms of the decline.\r\nThere is the want of method in physical science, the want of criticism\r\nin history, the want of simplicity or delicacy in poetry, the want of\r\npolitical freedom, which is the true atmosphere of public speaking, in\r\noratory. The ways of life were luxurious and commonplace. Philosophy had\r\nbecome extravagant, eclectic, abstract, devoid of any real content. At\r\nlength it ceased to exist. It had spread words like plaster over the\r\nwhole field of knowledge. It had grown ascetic on one side, mystical\r\non the other. Neither of these tendencies was favourable to literature.\r\nThere was no sense of beauty either in language or in art. The Greek\r\nworld became vacant, barbaric, oriental. No one had anything new to say,\r\nor any conviction of truth. The age had no remembrance of the past, no\r\npower of understanding what other ages thought and felt. The Catholic\r\nfaith had degenerated into dogma and controversy. For more than\r\na thousand years not a single writer of first-rate, or even of\r\nsecond-rate, reputation has a place in the innumerable rolls of Greek\r\nliterature.\r\n\r\nIf we seek to go deeper, we can still only describe the outward nature\r\nof the clouds or darkness which were spread over the heavens during so\r\nmany ages without relief or light. We may say that this, like several\r\nother long periods in the history of the human race, was destitute,\r\nor deprived of the moral qualities which are the root of literary\r\nexcellence. It had no life or aspiration, no national or political\r\nforce, no desire for consistency, no love of knowledge for its own sake.\r\nIt did not attempt to pierce the mists which surrounded it. It did not\r\npropose to itself to go forward and scale the heights of knowledge, but\r\nto go backwards and seek at the beginning what can only be found towards\r\nthe end. It was lost in doubt and ignorance. It rested upon tradition\r\nand authority. It had none of the higher play of fancy which creates\r\npoetry; and where there is no true poetry, neither can there be any\r\ngood prose. It had no great characters, and therefore it had no great\r\nwriters. It was incapable of distinguishing between words and things. It\r\nwas so hopelessly below the ancient standard of classical Greek art and\r\nliterature that it had no power of understanding or of valuing them. It\r\nis doubtful whether any Greek author was justly appreciated in antiquity\r\nexcept by his own contemporaries; and this neglect of the great authors\r\nof the past led to the disappearance of the larger part of them, while\r\nthe Greek fathers were mostly preserved. There is no reason to suppose\r\nthat, in the century before the taking of Constantinople, much more was\r\nin existence than the scholars of the Renaissance carried away with them\r\nto Italy.\r\n\r\nThe character of Greek literature sank lower as time went on. It\r\nconsisted more and more of compilations, of scholia, of extracts, of\r\ncommentaries, forgeries, imitations. The commentator or interpreter had\r\nno conception of his author as a whole, and very little of the context\r\nof any passage which he was explaining. The least things were preferred\r\nby him to the greatest. The question of a reading, or a grammatical\r\nform, or an accent, or the uses of a word, took the place of the aim or\r\nsubject of the book. He had no sense of the beauties of an author, and\r\nvery little light is thrown by him on real difficulties. He interprets\r\npast ages by his own. The greatest classical writers are the least\r\nappreciated by him. This seems to be the reason why so many of them have\r\nperished, why the lyric poets have almost wholly disappeared; why, out\r\nof the eighty or ninety tragedies of Aeschylus and Sophocles, only seven\r\nof each had been preserved.\r\n\r\nSuch an age of sciolism and scholasticism may possibly once more get\r\nthe better of the literary world. There are those who prophesy that the\r\nsigns of such a day are again appearing among us, and that at the end\r\nof the present century no writer of the first class will be still alive.\r\nThey think that the Muse of Literature may transfer herself to other\r\ncountries less dried up or worn out than our own. They seem to see the\r\nwithering effect of criticism on original genius. No one can doubt that\r\nsuch a decay or decline of literature and of art seriously affects\r\nthe manners and character of a nation. It takes away half the joys and\r\nrefinements of life; it increases its dulness and grossness. Hence it\r\nbecomes a matter of great interest to consider how, if at all, such a\r\ndegeneracy may be averted. Is there any elixir which can restore life\r\nand youth to the literature of a nation, or at any rate which can\r\nprevent it becoming unmanned and enfeebled?\r\n\r\nFirst there is the progress of education. It is possible, and even\r\nprobable, that the extension of the means of knowledge over a wider\r\narea and to persons living under new conditions may lead to many new\r\ncombinations of thought and language. But, as yet, experience does\r\nnot favour the realization of such a hope or promise. It may be truly\r\nanswered that at present the training of teachers and the methods of\r\neducation are very imperfect, and therefore that we cannot judge of the\r\nfuture by the present. When more of our youth are trained in the best\r\nliteratures, and in the best parts of them, their minds may be expected\r\nto have a larger growth. They will have more interests, more thoughts,\r\nmore material for conversation; they will have a higher standard and\r\nbegin to think for themselves. The number of persons who will have the\r\nopportunity of receiving the highest education through the cheap press,\r\nand by the help of high schools and colleges, may increase tenfold. It\r\nis likely that in every thousand persons there is at least one who is\r\nfar above the average in natural capacity, but the seed which is in him\r\ndies for want of cultivation. It has never had any stimulus to grow,\r\nor any field in which to blossom and produce fruit. Here is a great\r\nreservoir or treasure-house of human intelligence out of which new\r\nwaters may flow and cover the earth. If at any time the great men of\r\nthe world should die out, and originality or genius appear to suffer\r\na partial eclipse, there is a boundless hope in the multitude of\r\nintelligences for future generations. They may bring gifts to men such\r\nas the world has never received before. They may begin at a higher point\r\nand yet take with them all the results of the past. The co-operation of\r\nmany may have effects not less striking, though different in character\r\nfrom those which the creative genius of a single man, such as Bacon or\r\nNewton, formerly produced. There is also great hope to be derived, not\r\nmerely from the extension of education over a wider area, but from the\r\ncontinuance of it during many generations. Educated parents will have\r\nchildren fit to receive education; and these again will grow up under\r\ncircumstances far more favourable to the growth of intelligence than any\r\nwhich have hitherto existed in our own or in former ages.\r\n\r\nEven if we were to suppose no more men of genius to be produced, the\r\ngreat writers of ancient or of modern times will remain to furnish\r\nabundant materials of education to the coming generation. Now that\r\nevery nation holds communication with every other, we may truly say in\r\na fuller sense than formerly that 'the thoughts of men are widened\r\nwith the process of the suns.' They will not be 'cribbed, cabined, and\r\nconfined' within a province or an island. The East will provide elements\r\nof culture to the West as well as the West to the East. The religions\r\nand literatures of the world will be open books, which he who wills may\r\nread. The human race may not be always ground down by bodily toil, but\r\nmay have greater leisure for the improvement of the mind. The increasing\r\nsense of the greatness and infinity of nature will tend to awaken in men\r\nlarger and more liberal thoughts. The love of mankind may be the source\r\nof a greater development of literature than nationality has ever been.\r\nThere may be a greater freedom from prejudice and party; we may better\r\nunderstand the whereabouts of truth, and therefore there may be more\r\nsuccess and fewer failures in the search for it. Lastly, in the coming\r\nages we shall carry with us the recollection of the past, in which\r\nare necessarily contained many seeds of revival and renaissance in the\r\nfuture. So far is the world from becoming exhausted, so groundless is\r\nthe fear that literature will ever die out.\r\n\r\n\r\n\r\n\r\nPHAEDRUS\r\n\r\n\r\nPERSONS OF THE DIALOGUE: Socrates, Phaedrus.\r\n\r\nSCENE: Under a plane-tree, by the banks of the Ilissus.\r\n\r\n\r\nSOCRATES: My dear Phaedrus, whence come you, and whither are you going?\r\n\r\nPHAEDRUS: I come from Lysias the son of Cephalus, and I am going to\r\ntake a walk outside the wall, for I have been sitting with him the whole\r\nmorning; and our common friend Acumenus tells me that it is much more\r\nrefreshing to walk in the open air than to be shut up in a cloister.\r\n\r\nSOCRATES: There he is right. Lysias then, I suppose, was in the town?\r\n\r\nPHAEDRUS: Yes, he was staying with Epicrates, here at the house of\r\nMorychus; that house which is near the temple of Olympian Zeus.\r\n\r\nSOCRATES: And how did he entertain you? Can I be wrong in supposing that\r\nLysias gave you a feast of discourse?\r\n\r\nPHAEDRUS: You shall hear, if you can spare time to accompany me.\r\n\r\nSOCRATES: And should I not deem the conversation of you and Lysias 'a\r\nthing of higher import,' as I may say in the words of Pindar, 'than any\r\nbusiness'?\r\n\r\nPHAEDRUS: Will you go on?\r\n\r\nSOCRATES: And will you go on with the narration?\r\n\r\nPHAEDRUS: My tale, Socrates, is one of your sort, for love was the theme\r\nwhich occupied us--love after a fashion: Lysias has been writing about\r\na fair youth who was being tempted, but not by a lover; and this was\r\nthe point: he ingeniously proved that the non-lover should be accepted\r\nrather than the lover.\r\n\r\nSOCRATES: O that is noble of him! I wish that he would say the poor man\r\nrather than the rich, and the old man rather than the young one;--then\r\nhe would meet the case of me and of many a man; his words would be quite\r\nrefreshing, and he would be a public benefactor. For my part, I do so\r\nlong to hear his speech, that if you walk all the way to Megara, and\r\nwhen you have reached the wall come back, as Herodicus recommends,\r\nwithout going in, I will keep you company.\r\n\r\nPHAEDRUS: What do you mean, my good Socrates? How can you imagine that\r\nmy unpractised memory can do justice to an elaborate work, which the\r\ngreatest rhetorician of the age spent a long time in composing. Indeed,\r\nI cannot; I would give a great deal if I could.\r\n\r\nSOCRATES: I believe that I know Phaedrus about as well as I know myself,\r\nand I am very sure that the speech of Lysias was repeated to him, not\r\nonce only, but again and again;--he insisted on hearing it many times\r\nover and Lysias was very willing to gratify him; at last, when nothing\r\nelse would do, he got hold of the book, and looked at what he most\r\nwanted to see,--this occupied him during the whole morning;--and then\r\nwhen he was tired with sitting, he went out to take a walk, not until,\r\nby the dog, as I believe, he had simply learned by heart the entire\r\ndiscourse, unless it was unusually long, and he went to a place outside\r\nthe wall that he might practise his lesson. There he saw a certain\r\nlover of discourse who had a similar weakness;--he saw and rejoiced; now\r\nthought he, 'I shall have a partner in my revels.' And he invited him to\r\ncome and walk with him. But when the lover of discourse begged that he\r\nwould repeat the tale, he gave himself airs and said, 'No I cannot,'\r\nas if he were indisposed; although, if the hearer had refused, he would\r\nsooner or later have been compelled by him to listen whether he would or\r\nno. Therefore, Phaedrus, bid him do at once what he will soon do whether\r\nbidden or not.\r\n\r\nPHAEDRUS: I see that you will not let me off until I speak in some\r\nfashion or other; verily therefore my best plan is to speak as I best\r\ncan.\r\n\r\nSOCRATES: A very true remark, that of yours.\r\n\r\nPHAEDRUS: I will do as I say; but believe me, Socrates, I did not learn\r\nthe very words--O no; nevertheless I have a general notion of what\r\nhe said, and will give you a summary of the points in which the lover\r\ndiffered from the non-lover. Let me begin at the beginning.\r\n\r\nSOCRATES: Yes, my sweet one; but you must first of all show what you\r\nhave in your left hand under your cloak, for that roll, as I suspect,\r\nis the actual discourse. Now, much as I love you, I would not have you\r\nsuppose that I am going to have your memory exercised at my expense, if\r\nyou have Lysias himself here.\r\n\r\nPHAEDRUS: Enough; I see that I have no hope of practising my art upon\r\nyou. But if I am to read, where would you please to sit?\r\n\r\nSOCRATES: Let us turn aside and go by the Ilissus; we will sit down at\r\nsome quiet spot.\r\n\r\nPHAEDRUS: I am fortunate in not having my sandals, and as you never have\r\nany, I think that we may go along the brook and cool our feet in the\r\nwater; this will be the easiest way, and at midday and in the summer is\r\nfar from being unpleasant.\r\n\r\nSOCRATES: Lead on, and look out for a place in which we can sit down.\r\n\r\nPHAEDRUS: Do you see the tallest plane-tree in the distance?\r\n\r\nSOCRATES: Yes.\r\n\r\nPHAEDRUS: There are shade and gentle breezes, and grass on which we may\r\neither sit or lie down.\r\n\r\nSOCRATES: Move forward.\r\n\r\nPHAEDRUS: I should like to know, Socrates, whether the place is not\r\nsomewhere here at which Boreas is said to have carried off Orithyia from\r\nthe banks of the Ilissus?\r\n\r\nSOCRATES: Such is the tradition.\r\n\r\nPHAEDRUS: And is this the exact spot? The little stream is delightfully\r\nclear and bright; I can fancy that there might be maidens playing near.\r\n\r\nSOCRATES: I believe that the spot is not exactly here, but about a\r\nquarter of a mile lower down, where you cross to the temple of Artemis,\r\nand there is, I think, some sort of an altar of Boreas at the place.\r\n\r\nPHAEDRUS: I have never noticed it; but I beseech you to tell me,\r\nSocrates, do you believe this tale?\r\n\r\nSOCRATES: The wise are doubtful, and I should not be singular if, like\r\nthem, I too doubted. I might have a rational explanation that Orithyia\r\nwas playing with Pharmacia, when a northern gust carried her over the\r\nneighbouring rocks; and this being the manner of her death, she was said\r\nto have been carried away by Boreas. There is a discrepancy, however,\r\nabout the locality; according to another version of the story she was\r\ntaken from Areopagus, and not from this place. Now I quite acknowledge\r\nthat these allegories are very nice, but he is not to be envied who has\r\nto invent them; much labour and ingenuity will be required of him; and\r\nwhen he has once begun, he must go on and rehabilitate Hippocentaurs and\r\nchimeras dire. Gorgons and winged steeds flow in apace, and numberless\r\nother inconceivable and portentous natures. And if he is sceptical\r\nabout them, and would fain reduce them one after another to the rules of\r\nprobability, this sort of crude philosophy will take up a great deal of\r\ntime. Now I have no leisure for such enquiries; shall I tell you why? I\r\nmust first know myself, as the Delphian inscription says; to be curious\r\nabout that which is not my concern, while I am still in ignorance of my\r\nown self, would be ridiculous. And therefore I bid farewell to all this;\r\nthe common opinion is enough for me. For, as I was saying, I want to\r\nknow not about this, but about myself: am I a monster more complicated\r\nand swollen with passion than the serpent Typho, or a creature of a\r\ngentler and simpler sort, to whom Nature has given a diviner and lowlier\r\ndestiny? But let me ask you, friend: have we not reached the plane-tree\r\nto which you were conducting us?\r\n\r\nPHAEDRUS: Yes, this is the tree.\r\n\r\nSOCRATES: By Here, a fair resting-place, full of summer sounds and\r\nscents. Here is this lofty and spreading plane-tree, and the agnus\r\ncastus high and clustering, in the fullest blossom and the greatest\r\nfragrance; and the stream which flows beneath the plane-tree is\r\ndeliciously cold to the feet. Judging from the ornaments and images,\r\nthis must be a spot sacred to Achelous and the Nymphs. How delightful is\r\nthe breeze:--so very sweet; and there is a sound in the air shrill and\r\nsummerlike which makes answer to the chorus of the cicadae. But the\r\ngreatest charm of all is the grass, like a pillow gently sloping to the\r\nhead. My dear Phaedrus, you have been an admirable guide.\r\n\r\nPHAEDRUS: What an incomprehensible being you are, Socrates: when you are\r\nin the country, as you say, you really are like some stranger who is led\r\nabout by a guide. Do you ever cross the border? I rather think that you\r\nnever venture even outside the gates.\r\n\r\nSOCRATES: Very true, my good friend; and I hope that you will excuse me\r\nwhen you hear the reason, which is, that I am a lover of knowledge, and\r\nthe men who dwell in the city are my teachers, and not the trees or the\r\ncountry. Though I do indeed believe that you have found a spell with\r\nwhich to draw me out of the city into the country, like a hungry cow\r\nbefore whom a bough or a bunch of fruit is waved. For only hold up\r\nbefore me in like manner a book, and you may lead me all round Attica,\r\nand over the wide world. And now having arrived, I intend to lie down,\r\nand do you choose any posture in which you can read best. Begin.\r\n\r\nPHAEDRUS: Listen. You know how matters stand with me; and how, as I\r\nconceive, this affair may be arranged for the advantage of both of us.\r\nAnd I maintain that I ought not to fail in my suit, because I am not\r\nyour lover: for lovers repent of the kindnesses which they have shown\r\nwhen their passion ceases, but to the non-lovers who are free and not\r\nunder any compulsion, no time of repentance ever comes; for they confer\r\ntheir benefits according to the measure of their ability, in the way\r\nwhich is most conducive to their own interest. Then again, lovers\r\nconsider how by reason of their love they have neglected their own\r\nconcerns and rendered service to others: and when to these benefits\r\nconferred they add on the troubles which they have endured, they think\r\nthat they have long ago made to the beloved a very ample return. But the\r\nnon-lover has no such tormenting recollections; he has never neglected\r\nhis affairs or quarrelled with his relations; he has no troubles to\r\nadd up or excuses to invent; and being well rid of all these evils, why\r\nshould he not freely do what will gratify the beloved? If you say that\r\nthe lover is more to be esteemed, because his love is thought to be\r\ngreater; for he is willing to say and do what is hateful to other men,\r\nin order to please his beloved;--that, if true, is only a proof that he\r\nwill prefer any future love to his present, and will injure his old\r\nlove at the pleasure of the new. And how, in a matter of such infinite\r\nimportance, can a man be right in trusting himself to one who is\r\nafflicted with a malady which no experienced person would attempt to\r\ncure, for the patient himself admits that he is not in his right mind,\r\nand acknowledges that he is wrong in his mind, but says that he is\r\nunable to control himself? And if he came to his right mind, would he\r\never imagine that the desires were good which he conceived when in his\r\nwrong mind? Once more, there are many more non-lovers than lovers; and\r\nif you choose the best of the lovers, you will not have many to choose\r\nfrom; but if from the non-lovers, the choice will be larger, and you\r\nwill be far more likely to find among them a person who is worthy of\r\nyour friendship. If public opinion be your dread, and you would avoid\r\nreproach, in all probability the lover, who is always thinking that\r\nother men are as emulous of him as he is of them, will boast to some\r\none of his successes, and make a show of them openly in the pride of his\r\nheart;--he wants others to know that his labour has not been lost; but\r\nthe non-lover is more his own master, and is desirous of solid good, and\r\nnot of the opinion of mankind. Again, the lover may be generally noted\r\nor seen following the beloved (this is his regular occupation), and\r\nwhenever they are observed to exchange two words they are supposed to\r\nmeet about some affair of love either past or in contemplation; but when\r\nnon-lovers meet, no one asks the reason why, because people know that\r\ntalking to another is natural, whether friendship or mere pleasure\r\nbe the motive. Once more, if you fear the fickleness of friendship,\r\nconsider that in any other case a quarrel might be a mutual calamity;\r\nbut now, when you have given up what is most precious to you, you will\r\nbe the greater loser, and therefore, you will have more reason in\r\nbeing afraid of the lover, for his vexations are many, and he is always\r\nfancying that every one is leagued against him. Wherefore also he\r\ndebars his beloved from society; he will not have you intimate with\r\nthe wealthy, lest they should exceed him in wealth, or with men of\r\neducation, lest they should be his superiors in understanding; and he is\r\nequally afraid of anybody's influence who has any other advantage over\r\nhimself. If he can persuade you to break with them, you are left without\r\na friend in the world; or if, out of a regard to your own interest, you\r\nhave more sense than to comply with his desire, you will have to quarrel\r\nwith him. But those who are non-lovers, and whose success in love is the\r\nreward of their merit, will not be jealous of the companions of their\r\nbeloved, and will rather hate those who refuse to be his associates,\r\nthinking that their favourite is slighted by the latter and benefited by\r\nthe former; for more love than hatred may be expected to come to him out\r\nof his friendship with others. Many lovers too have loved the person of\r\na youth before they knew his character or his belongings; so that when\r\ntheir passion has passed away, there is no knowing whether they will\r\ncontinue to be his friends; whereas, in the case of non-lovers who were\r\nalways friends, the friendship is not lessened by the favours granted;\r\nbut the recollection of these remains with them, and is an earnest of\r\ngood things to come.\r\n\r\nFurther, I say that you are likely to be improved by me, whereas the\r\nlover will spoil you. For they praise your words and actions in a wrong\r\nway; partly, because they are afraid of offending you, and also, their\r\njudgment is weakened by passion. Such are the feats which love exhibits;\r\nhe makes things painful to the disappointed which give no pain to\r\nothers; he compels the successful lover to praise what ought not to\r\ngive him pleasure, and therefore the beloved is to be pitied rather\r\nthan envied. But if you listen to me, in the first place, I, in my\r\nintercourse with you, shall not merely regard present enjoyment, but\r\nalso future advantage, being not mastered by love, but my own master;\r\nnor for small causes taking violent dislikes, but even when the cause\r\nis great, slowly laying up little wrath--unintentional offences I shall\r\nforgive, and intentional ones I shall try to prevent; and these are the\r\nmarks of a friendship which will last.\r\n\r\nDo you think that a lover only can be a firm friend? reflect:--if this\r\nwere true, we should set small value on sons, or fathers, or mothers;\r\nnor should we ever have loyal friends, for our love of them arises\r\nnot from passion, but from other associations. Further, if we ought\r\nto shower favours on those who are the most eager suitors,--on that\r\nprinciple, we ought always to do good, not to the most virtuous, but to\r\nthe most needy; for they are the persons who will be most relieved,\r\nand will therefore be the most grateful; and when you make a feast you\r\nshould invite not your friend, but the beggar and the empty soul; for\r\nthey will love you, and attend you, and come about your doors, and\r\nwill be the best pleased, and the most grateful, and will invoke many a\r\nblessing on your head. Yet surely you ought not to be granting favours\r\nto those who besiege you with prayer, but to those who are best able to\r\nreward you; nor to the lover only, but to those who are worthy of love;\r\nnor to those who will enjoy the bloom of your youth, but to those who\r\nwill share their possessions with you in age; nor to those who, having\r\nsucceeded, will glory in their success to others, but to those who\r\nwill be modest and tell no tales; nor to those who care about you for a\r\nmoment only, but to those who will continue your friends through life;\r\nnor to those who, when their passion is over, will pick a quarrel with\r\nyou, but rather to those who, when the charm of youth has left you, will\r\nshow their own virtue. Remember what I have said; and consider yet this\r\nfurther point: friends admonish the lover under the idea that his way of\r\nlife is bad, but no one of his kindred ever yet censured the non-lover,\r\nor thought that he was ill-advised about his own interests.\r\n\r\n'Perhaps you will ask me whether I propose that you should indulge every\r\nnon-lover. To which I reply that not even the lover would advise you to\r\nindulge all lovers, for the indiscriminate favour is less esteemed by\r\nthe rational recipient, and less easily hidden by him who would escape\r\nthe censure of the world. Now love ought to be for the advantage of both\r\nparties, and for the injury of neither.\r\n\r\n'I believe that I have said enough; but if there is anything more which\r\nyou desire or which in your opinion needs to be supplied, ask and I will\r\nanswer.'\r\n\r\nNow, Socrates, what do you think? Is not the discourse excellent, more\r\nespecially in the matter of the language?\r\n\r\nSOCRATES: Yes, quite admirable; the effect on me was ravishing. And this\r\nI owe to you, Phaedrus, for I observed you while reading to be in an\r\necstasy, and thinking that you are more experienced in these matters\r\nthan I am, I followed your example, and, like you, my divine darling, I\r\nbecame inspired with a phrenzy.\r\n\r\nPHAEDRUS: Indeed, you are pleased to be merry.\r\n\r\nSOCRATES: Do you mean that I am not in earnest?\r\n\r\nPHAEDRUS: Now don't talk in that way, Socrates, but let me have your\r\nreal opinion; I adjure you, by Zeus, the god of friendship, to tell me\r\nwhether you think that any Hellene could have said more or spoken better\r\non the same subject.\r\n\r\nSOCRATES: Well, but are you and I expected to praise the sentiments\r\nof the author, or only the clearness, and roundness, and finish, and\r\ntournure of the language? As to the first I willingly submit to your\r\nbetter judgment, for I am not worthy to form an opinion, having only\r\nattended to the rhetorical manner; and I was doubting whether this could\r\nhave been defended even by Lysias himself; I thought, though I speak\r\nunder correction, that he repeated himself two or three times, either\r\nfrom want of words or from want of pains; and also, he appeared to me\r\nostentatiously to exult in showing how well he could say the same thing\r\nin two or three ways.\r\n\r\nPHAEDRUS: Nonsense, Socrates; what you call repetition was the especial\r\nmerit of the speech; for he omitted no topic of which the subject\r\nrightly allowed, and I do not think that any one could have spoken\r\nbetter or more exhaustively.\r\n\r\nSOCRATES: There I cannot go along with you. Ancient sages, men and\r\nwomen, who have spoken and written of these things, would rise up in\r\njudgment against me, if out of complaisance I assented to you.\r\n\r\nPHAEDRUS: Who are they, and where did you hear anything better than\r\nthis?\r\n\r\nSOCRATES: I am sure that I must have heard; but at this moment I do not\r\nremember from whom; perhaps from Sappho the fair, or Anacreon the wise;\r\nor, possibly, from a prose writer. Why do I say so? Why, because I\r\nperceive that my bosom is full, and that I could make another speech as\r\ngood as that of Lysias, and different. Now I am certain that this is\r\nnot an invention of my own, who am well aware that I know nothing, and\r\ntherefore I can only infer that I have been filled through the ears,\r\nlike a pitcher, from the waters of another, though I have actually\r\nforgotten in my stupidity who was my informant.\r\n\r\nPHAEDRUS: That is grand:--but never mind where you heard the discourse\r\nor from whom; let that be a mystery not to be divulged even at my\r\nearnest desire. Only, as you say, promise to make another and better\r\noration, equal in length and entirely new, on the same subject; and I,\r\nlike the nine Archons, will promise to set up a golden image at Delphi,\r\nnot only of myself, but of you, and as large as life.\r\n\r\nSOCRATES: You are a dear golden ass if you suppose me to mean that\r\nLysias has altogether missed the mark, and that I can make a speech from\r\nwhich all his arguments are to be excluded. The worst of authors will\r\nsay something which is to the point. Who, for example, could speak on\r\nthis thesis of yours without praising the discretion of the non-lover\r\nand blaming the indiscretion of the lover? These are the commonplaces of\r\nthe subject which must come in (for what else is there to be said?) and\r\nmust be allowed and excused; the only merit is in the arrangement of\r\nthem, for there can be none in the invention; but when you leave the\r\ncommonplaces, then there may be some originality.\r\n\r\nPHAEDRUS: I admit that there is reason in what you say, and I too will\r\nbe reasonable, and will allow you to start with the premiss that the\r\nlover is more disordered in his wits than the non-lover; if in what\r\nremains you make a longer and better speech than Lysias, and use other\r\narguments, then I say again, that a statue you shall have of beaten\r\ngold, and take your place by the colossal offerings of the Cypselids at\r\nOlympia.\r\n\r\nSOCRATES: How profoundly in earnest is the lover, because to tease him I\r\nlay a finger upon his love! And so, Phaedrus, you really imagine that I\r\nam going to improve upon the ingenuity of Lysias?\r\n\r\nPHAEDRUS: There I have you as you had me, and you must just speak 'as\r\nyou best can.' Do not let us exchange 'tu quoque' as in a farce, or\r\ncompel me to say to you as you said to me, 'I know Socrates as well as\r\nI know myself, and he was wanting to speak, but he gave himself airs.'\r\nRather I would have you consider that from this place we stir not until\r\nyou have unbosomed yourself of the speech; for here are we all alone,\r\nand I am stronger, remember, and younger than you:--Wherefore perpend,\r\nand do not compel me to use violence.\r\n\r\nSOCRATES: But, my sweet Phaedrus, how ridiculous it would be of me to\r\ncompete with Lysias in an extempore speech! He is a master in his art\r\nand I am an untaught man.\r\n\r\nPHAEDRUS: You see how matters stand; and therefore let there be no more\r\npretences; for, indeed, I know the word that is irresistible.\r\n\r\nSOCRATES: Then don't say it.\r\n\r\nPHAEDRUS: Yes, but I will; and my word shall be an oath. 'I say, or\r\nrather swear'--but what god will be witness of my oath?--'By this\r\nplane-tree I swear, that unless you repeat the discourse here in the\r\nface of this very plane-tree, I will never tell you another; never let\r\nyou have word of another!'\r\n\r\nSOCRATES: Villain! I am conquered; the poor lover of discourse has no\r\nmore to say.\r\n\r\nPHAEDRUS: Then why are you still at your tricks?\r\n\r\nSOCRATES: I am not going to play tricks now that you have taken the\r\noath, for I cannot allow myself to be starved.\r\n\r\nPHAEDRUS: Proceed.\r\n\r\nSOCRATES: Shall I tell you what I will do?\r\n\r\nPHAEDRUS: What?\r\n\r\nSOCRATES: I will veil my face and gallop through the discourse as fast\r\nas I can, for if I see you I shall feel ashamed and not know what to\r\nsay.\r\n\r\nPHAEDRUS: Only go on and you may do anything else which you please.\r\n\r\nSOCRATES: Come, O ye Muses, melodious, as ye are called, whether you\r\nhave received this name from the character of your strains, or because\r\nthe Melians are a musical race, help, O help me in the tale which my\r\ngood friend here desires me to rehearse, in order that his friend whom\r\nhe always deemed wise may seem to him to be wiser than ever.\r\n\r\nOnce upon a time there was a fair boy, or, more properly speaking, a\r\nyouth; he was very fair and had a great many lovers; and there was one\r\nspecial cunning one, who had persuaded the youth that he did not love\r\nhim, but he really loved him all the same; and one day when he was\r\npaying his addresses to him, he used this very argument--that he\r\nought to accept the non-lover rather than the lover; his words were as\r\nfollows:--\r\n\r\n'All good counsel begins in the same way; a man should know what he\r\nis advising about, or his counsel will all come to nought. But people\r\nimagine that they know about the nature of things, when they don't know\r\nabout them, and, not having come to an understanding at first\r\nbecause they think that they know, they end, as might be expected, in\r\ncontradicting one another and themselves. Now you and I must not be\r\nguilty of this fundamental error which we condemn in others; but as our\r\nquestion is whether the lover or non-lover is to be preferred, let us\r\nfirst of all agree in defining the nature and power of love, and then,\r\nkeeping our eyes upon the definition and to this appealing, let us\r\nfurther enquire whether love brings advantage or disadvantage.\r\n\r\n'Every one sees that love is a desire, and we know also that non-lovers\r\ndesire the beautiful and good. Now in what way is the lover to be\r\ndistinguished from the non-lover? Let us note that in every one of us\r\nthere are two guiding and ruling principles which lead us whither they\r\nwill; one is the natural desire of pleasure, the other is an acquired\r\nopinion which aspires after the best; and these two are sometimes in\r\nharmony and then again at war, and sometimes the one, sometimes the\r\nother conquers. When opinion by the help of reason leads us to the best,\r\nthe conquering principle is called temperance; but when desire, which\r\nis devoid of reason, rules in us and drags us to pleasure, that power of\r\nmisrule is called excess. Now excess has many names, and many members,\r\nand many forms, and any of these forms when very marked gives a name,\r\nneither honourable nor creditable, to the bearer of the name. The desire\r\nof eating, for example, which gets the better of the higher reason and\r\nthe other desires, is called gluttony, and he who is possessed by it\r\nis called a glutton; the tyrannical desire of drink, which inclines the\r\npossessor of the desire to drink, has a name which is only too obvious,\r\nand there can be as little doubt by what name any other appetite of the\r\nsame family would be called;--it will be the name of that which happens\r\nto be dominant. And now I think that you will perceive the drift of\r\nmy discourse; but as every spoken word is in a manner plainer than the\r\nunspoken, I had better say further that the irrational desire which\r\novercomes the tendency of opinion towards right, and is led away to the\r\nenjoyment of beauty, and especially of personal beauty, by the desires\r\nwhich are her own kindred--that supreme desire, I say, which by leading\r\nconquers and by the force of passion is reinforced, from this very\r\nforce, receiving a name, is called love (erromenos eros).'\r\n\r\nAnd now, dear Phaedrus, I shall pause for an instant to ask whether you\r\ndo not think me, as I appear to myself, inspired?\r\n\r\nPHAEDRUS: Yes, Socrates, you seem to have a very unusual flow of words.\r\n\r\nSOCRATES: Listen to me, then, in silence; for surely the place is holy;\r\nso that you must not wonder, if, as I proceed, I appear to be in a\r\ndivine fury, for already I am getting into dithyrambics.\r\n\r\nPHAEDRUS: Nothing can be truer.\r\n\r\nSOCRATES: The responsibility rests with you. But hear what follows, and\r\nperhaps the fit may be averted; all is in their hands above. I will go\r\non talking to my youth. Listen:--\r\n\r\nThus, my friend, we have declared and defined the nature of the subject.\r\nKeeping the definition in view, let us now enquire what advantage or\r\ndisadvantage is likely to ensue from the lover or the non-lover to him\r\nwho accepts their advances.\r\n\r\nHe who is the victim of his passions and the slave of pleasure will of\r\ncourse desire to make his beloved as agreeable to himself as possible.\r\nNow to him who has a mind diseased anything is agreeable which is not\r\nopposed to him, but that which is equal or superior is hateful to him,\r\nand therefore the lover will not brook any superiority or equality\r\non the part of his beloved; he is always employed in reducing him to\r\ninferiority. And the ignorant is the inferior of the wise, the coward\r\nof the brave, the slow of speech of the speaker, the dull of the\r\nclever. These, and not these only, are the mental defects of the\r\nbeloved;--defects which, when implanted by nature, are necessarily\r\na delight to the lover, and when not implanted, he must contrive to\r\nimplant them in him, if he would not be deprived of his fleeting joy.\r\nAnd therefore he cannot help being jealous, and will debar his beloved\r\nfrom the advantages of society which would make a man of him, and\r\nespecially from that society which would have given him wisdom, and\r\nthereby he cannot fail to do him great harm. That is to say, in his\r\nexcessive fear lest he should come to be despised in his eyes he will be\r\ncompelled to banish from him divine philosophy; and there is no greater\r\ninjury which he can inflict upon him than this. He will contrive that\r\nhis beloved shall be wholly ignorant, and in everything shall look\r\nto him; he is to be the delight of the lover's heart, and a curse to\r\nhimself. Verily, a lover is a profitable guardian and associate for him\r\nin all that relates to his mind.\r\n\r\nLet us next see how his master, whose law of life is pleasure and not\r\ngood, will keep and train the body of his servant. Will he not choose a\r\nbeloved who is delicate rather than sturdy and strong? One brought up\r\nin shady bowers and not in the bright sun, a stranger to manly exercises\r\nand the sweat of toil, accustomed only to a soft and luxurious diet,\r\ninstead of the hues of health having the colours of paint and ornament,\r\nand the rest of a piece?--such a life as any one can imagine and which I\r\nneed not detail at length. But I may sum up all that I have to say in a\r\nword, and pass on. Such a person in war, or in any of the great crises\r\nof life, will be the anxiety of his friends and also of his lover, and\r\ncertainly not the terror of his enemies; which nobody can deny.\r\n\r\nAnd now let us tell what advantage or disadvantage the beloved will\r\nreceive from the guardianship and society of his lover in the matter of\r\nhis property; this is the next point to be considered. The lover will be\r\nthe first to see what, indeed, will be sufficiently evident to all men,\r\nthat he desires above all things to deprive his beloved of his dearest\r\nand best and holiest possessions, father, mother, kindred, friends, of\r\nall whom he thinks may be hinderers or reprovers of their most sweet\r\nconverse; he will even cast a jealous eye upon his gold and silver or\r\nother property, because these make him a less easy prey, and when caught\r\nless manageable; hence he is of necessity displeased at his possession\r\nof them and rejoices at their loss; and he would like him to be\r\nwifeless, childless, homeless, as well; and the longer the better, for\r\nthe longer he is all this, the longer he will enjoy him.\r\n\r\nThere are some sort of animals, such as flatterers, who are dangerous\r\nand mischievous enough, and yet nature has mingled a temporary pleasure\r\nand grace in their composition. You may say that a courtesan is hurtful,\r\nand disapprove of such creatures and their practices, and yet for the\r\ntime they are very pleasant. But the lover is not only hurtful to his\r\nlove; he is also an extremely disagreeable companion. The old proverb\r\nsays that 'birds of a feather flock together'; I suppose that equality\r\nof years inclines them to the same pleasures, and similarity begets\r\nfriendship; yet you may have more than enough even of this; and verily\r\nconstraint is always said to be grievous. Now the lover is not only\r\nunlike his beloved, but he forces himself upon him. For he is old and\r\nhis love is young, and neither day nor night will he leave him if he\r\ncan help; necessity and the sting of desire drive him on, and allure\r\nhim with the pleasure which he receives from seeing, hearing, touching,\r\nperceiving him in every way. And therefore he is delighted to fasten\r\nupon him and to minister to him. But what pleasure or consolation can\r\nthe beloved be receiving all this time? Must he not feel the extremity\r\nof disgust when he looks at an old shrivelled face and the remainder to\r\nmatch, which even in a description is disagreeable, and quite detestable\r\nwhen he is forced into daily contact with his lover; moreover he is\r\njealously watched and guarded against everything and everybody, and\r\nhas to hear misplaced and exaggerated praises of himself, and censures\r\nequally inappropriate, which are intolerable when the man is sober, and,\r\nbesides being intolerable, are published all over the world in all their\r\nindelicacy and wearisomeness when he is drunk.\r\n\r\nAnd not only while his love continues is he mischievous and unpleasant,\r\nbut when his love ceases he becomes a perfidious enemy of him on whom\r\nhe showered his oaths and prayers and promises, and yet could hardly\r\nprevail upon him to tolerate the tedium of his company even from motives\r\nof interest. The hour of payment arrives, and now he is the servant of\r\nanother master; instead of love and infatuation, wisdom and temperance\r\nare his bosom's lords; but the beloved has not discovered the change\r\nwhich has taken place in him, when he asks for a return and recalls to\r\nhis recollection former sayings and doings; he believes himself to be\r\nspeaking to the same person, and the other, not having the courage to\r\nconfess the truth, and not knowing how to fulfil the oaths and promises\r\nwhich he made when under the dominion of folly, and having now grown\r\nwise and temperate, does not want to do as he did or to be as he was\r\nbefore. And so he runs away and is constrained to be a defaulter; the\r\noyster-shell (In allusion to a game in which two parties fled or pursued\r\naccording as an oyster-shell which was thrown into the air fell with\r\nthe dark or light side uppermost.) has fallen with the other side\r\nuppermost--he changes pursuit into flight, while the other is compelled\r\nto follow him with passion and imprecation, not knowing that he ought\r\nnever from the first to have accepted a demented lover instead of a\r\nsensible non-lover; and that in making such a choice he was giving\r\nhimself up to a faithless, morose, envious, disagreeable being, hurtful\r\nto his estate, hurtful to his bodily health, and still more hurtful to\r\nthe cultivation of his mind, than which there neither is nor ever will\r\nbe anything more honoured in the eyes both of gods and men. Consider\r\nthis, fair youth, and know that in the friendship of the lover there is\r\nno real kindness; he has an appetite and wants to feed upon you:\r\n\r\n'As wolves love lambs so lovers love their loves.'\r\n\r\nBut I told you so, I am speaking in verse, and therefore I had better\r\nmake an end; enough.\r\n\r\nPHAEDRUS: I thought that you were only half-way and were going to make a\r\nsimilar speech about all the advantages of accepting the non-lover. Why\r\ndo you not proceed?\r\n\r\nSOCRATES: Does not your simplicity observe that I have got out of\r\ndithyrambics into heroics, when only uttering a censure on the lover?\r\nAnd if I am to add the praises of the non-lover what will become of me?\r\nDo you not perceive that I am already overtaken by the Nymphs to whom\r\nyou have mischievously exposed me? And therefore I will only add that\r\nthe non-lover has all the advantages in which the lover is accused of\r\nbeing deficient. And now I will say no more; there has been enough of\r\nboth of them. Leaving the tale to its fate, I will cross the river and\r\nmake the best of my way home, lest a worse thing be inflicted upon me by\r\nyou.\r\n\r\nPHAEDRUS: Not yet, Socrates; not until the heat of the day has passed;\r\ndo you not see that the hour is almost noon? there is the midday sun\r\nstanding still, as people say, in the meridian. Let us rather stay and\r\ntalk over what has been said, and then return in the cool.\r\n\r\nSOCRATES: Your love of discourse, Phaedrus, is superhuman, simply\r\nmarvellous, and I do not believe that there is any one of your\r\ncontemporaries who has either made or in one way or another has\r\ncompelled others to make an equal number of speeches. I would except\r\nSimmias the Theban, but all the rest are far behind you. And now I do\r\nverily believe that you have been the cause of another.\r\n\r\nPHAEDRUS: That is good news. But what do you mean?\r\n\r\nSOCRATES: I mean to say that as I was about to cross the stream the\r\nusual sign was given to me,--that sign which always forbids, but never\r\nbids, me to do anything which I am going to do; and I thought that I\r\nheard a voice saying in my ear that I had been guilty of impiety,\r\nand that I must not go away until I had made an atonement. Now I am a\r\ndiviner, though not a very good one, but I have enough religion for my\r\nown use, as you might say of a bad writer--his writing is good enough\r\nfor him; and I am beginning to see that I was in error. O my friend, how\r\nprophetic is the human soul! At the time I had a sort of misgiving, and,\r\nlike Ibycus, 'I was troubled; I feared that I might be buying honour\r\nfrom men at the price of sinning against the gods.' Now I recognize my\r\nerror.\r\n\r\nPHAEDRUS: What error?\r\n\r\nSOCRATES: That was a dreadful speech which you brought with you, and you\r\nmade me utter one as bad.\r\n\r\nPHAEDRUS: How so?\r\n\r\nSOCRATES: It was foolish, I say,--to a certain extent, impious; can\r\nanything be more dreadful?\r\n\r\nPHAEDRUS: Nothing, if the speech was really such as you describe.\r\n\r\nSOCRATES: Well, and is not Eros the son of Aphrodite, and a god?\r\n\r\nPHAEDRUS: So men say.\r\n\r\nSOCRATES: But that was not acknowledged by Lysias in his speech, nor by\r\nyou in that other speech which you by a charm drew from my lips. For if\r\nlove be, as he surely is, a divinity, he cannot be evil. Yet this was\r\nthe error of both the speeches. There was also a simplicity about them\r\nwhich was refreshing; having no truth or honesty in them, nevertheless\r\nthey pretended to be something, hoping to succeed in deceiving the\r\nmanikins of earth and gain celebrity among them. Wherefore I must have\r\na purgation. And I bethink me of an ancient purgation of mythological\r\nerror which was devised, not by Homer, for he never had the wit to\r\ndiscover why he was blind, but by Stesichorus, who was a philosopher and\r\nknew the reason why; and therefore, when he lost his eyes, for that was\r\nthe penalty which was inflicted upon him for reviling the lovely Helen,\r\nhe at once purged himself. And the purgation was a recantation, which\r\nbegan thus,--\r\n\r\n 'False is that word of mine--the truth is that thou didst not embark in\r\n ships, nor ever go to the walls of Troy;'\r\n\r\nand when he had completed his poem, which is called 'the recantation,'\r\nimmediately his sight returned to him. Now I will be wiser than either\r\nStesichorus or Homer, in that I am going to make my recantation for\r\nreviling love before I suffer; and this I will attempt, not as before,\r\nveiled and ashamed, but with forehead bold and bare.\r\n\r\nPHAEDRUS: Nothing could be more agreeable to me than to hear you say so.\r\n\r\nSOCRATES: Only think, my good Phaedrus, what an utter want of delicacy\r\nwas shown in the two discourses; I mean, in my own and in that which you\r\nrecited out of the book. Would not any one who was himself of a noble\r\nand gentle nature, and who loved or ever had loved a nature like his\r\nown, when we tell of the petty causes of lovers' jealousies, and of\r\ntheir exceeding animosities, and of the injuries which they do to their\r\nbeloved, have imagined that our ideas of love were taken from some haunt\r\nof sailors to which good manners were unknown--he would certainly never\r\nhave admitted the justice of our censure?\r\n\r\nPHAEDRUS: I dare say not, Socrates.\r\n\r\nSOCRATES: Therefore, because I blush at the thought of this person, and\r\nalso because I am afraid of Love himself, I desire to wash the brine out\r\nof my ears with water from the spring; and I would counsel Lysias not to\r\ndelay, but to write another discourse, which shall prove that 'ceteris\r\nparibus' the lover ought to be accepted rather than the non-lover.\r\n\r\nPHAEDRUS: Be assured that he shall. You shall speak the praises of the\r\nlover, and Lysias shall be compelled by me to write another discourse on\r\nthe same theme.\r\n\r\nSOCRATES: You will be true to your nature in that, and therefore I\r\nbelieve you.\r\n\r\nPHAEDRUS: Speak, and fear not.\r\n\r\nSOCRATES: But where is the fair youth whom I was addressing before, and\r\nwho ought to listen now; lest, if he hear me not, he should accept a\r\nnon-lover before he knows what he is doing?\r\n\r\nPHAEDRUS: He is close at hand, and always at your service.\r\n\r\nSOCRATES: Know then, fair youth, that the former discourse was the word\r\nof Phaedrus, the son of Vain Man, who dwells in the city of Myrrhina\r\n(Myrrhinusius). And this which I am about to utter is the recantation of\r\nStesichorus the son of Godly Man (Euphemus), who comes from the town of\r\nDesire (Himera), and is to the following effect: 'I told a lie when I\r\nsaid' that the beloved ought to accept the non-lover when he might have\r\nthe lover, because the one is sane, and the other mad. It might be so\r\nif madness were simply an evil; but there is also a madness which is a\r\ndivine gift, and the source of the chiefest blessings granted to\r\nmen. For prophecy is a madness, and the prophetess at Delphi and the\r\npriestesses at Dodona when out of their senses have conferred great\r\nbenefits on Hellas, both in public and private life, but when in their\r\nsenses few or none. And I might also tell you how the Sibyl and other\r\ninspired persons have given to many an one many an intimation of the\r\nfuture which has saved them from falling. But it would be tedious to\r\nspeak of what every one knows.\r\n\r\nThere will be more reason in appealing to the ancient inventors of names\r\n(compare Cratylus), who would never have connected prophecy (mantike)\r\nwhich foretells the future and is the noblest of arts, with madness\r\n(manike), or called them both by the same name, if they had deemed\r\nmadness to be a disgrace or dishonour;--they must have thought that\r\nthere was an inspired madness which was a noble thing; for the two\r\nwords, mantike and manike, are really the same, and the letter tau is\r\nonly a modern and tasteless insertion. And this is confirmed by the\r\nname which was given by them to the rational investigation of futurity,\r\nwhether made by the help of birds or of other signs--this, for as much\r\nas it is an art which supplies from the reasoning faculty mind (nous)\r\nand information (istoria) to human thought (oiesis) they originally\r\ntermed oionoistike, but the word has been lately altered and made\r\nsonorous by the modern introduction of the letter Omega (oionoistike and\r\noionistike), and in proportion as prophecy (mantike) is more perfect and\r\naugust than augury, both in name and fact, in the same proportion, as\r\nthe ancients testify, is madness superior to a sane mind (sophrosune)\r\nfor the one is only of human, but the other of divine origin. Again,\r\nwhere plagues and mightiest woes have bred in certain families, owing\r\nto some ancient blood-guiltiness, there madness has entered with holy\r\nprayers and rites, and by inspired utterances found a way of deliverance\r\nfor those who are in need; and he who has part in this gift, and is\r\ntruly possessed and duly out of his mind, is by the use of purifications\r\nand mysteries made whole and exempt from evil, future as well as\r\npresent, and has a release from the calamity which was afflicting him.\r\nThe third kind is the madness of those who are possessed by the Muses;\r\nwhich taking hold of a delicate and virgin soul, and there inspiring\r\nfrenzy, awakens lyrical and all other numbers; with these adorning the\r\nmyriad actions of ancient heroes for the instruction of posterity. But\r\nhe who, having no touch of the Muses' madness in his soul, comes to the\r\ndoor and thinks that he will get into the temple by the help of art--he,\r\nI say, and his poetry are not admitted; the sane man disappears and is\r\nnowhere when he enters into rivalry with the madman.\r\n\r\nI might tell of many other noble deeds which have sprung from inspired\r\nmadness. And therefore, let no one frighten or flutter us by saying that\r\nthe temperate friend is to be chosen rather than the inspired, but let\r\nhim further show that love is not sent by the gods for any good to lover\r\nor beloved; if he can do so we will allow him to carry off the palm. And\r\nwe, on our part, will prove in answer to him that the madness of love is\r\nthe greatest of heaven's blessings, and the proof shall be one which the\r\nwise will receive, and the witling disbelieve. But first of all, let us\r\nview the affections and actions of the soul divine and human, and try\r\nto ascertain the truth about them. The beginning of our proof is as\r\nfollows:--\r\n\r\n(Translated by Cic. Tus. Quaest.) The soul through all her being is\r\nimmortal, for that which is ever in motion is immortal; but that which\r\nmoves another and is moved by another, in ceasing to move ceases also to\r\nlive. Only the self-moving, never leaving self, never ceases to move,\r\nand is the fountain and beginning of motion to all that moves besides.\r\nNow, the beginning is unbegotten, for that which is begotten has a\r\nbeginning; but the beginning is begotten of nothing, for if it were\r\nbegotten of something, then the begotten would not come from a\r\nbeginning. But if unbegotten, it must also be indestructible; for if\r\nbeginning were destroyed, there could be no beginning out of anything,\r\nnor anything out of a beginning; and all things must have a beginning.\r\nAnd therefore the self-moving is the beginning of motion; and this can\r\nneither be destroyed nor begotten, else the whole heavens and all\r\ncreation would collapse and stand still, and never again have motion or\r\nbirth. But if the self-moving is proved to be immortal, he who affirms\r\nthat self-motion is the very idea and essence of the soul will not be\r\nput to confusion. For the body which is moved from without is soulless;\r\nbut that which is moved from within has a soul, for such is the nature\r\nof the soul. But if this be true, must not the soul be the self-moving,\r\nand therefore of necessity unbegotten and immortal? Enough of the soul's\r\nimmortality.\r\n\r\nOf the nature of the soul, though her true form be ever a theme of large\r\nand more than mortal discourse, let me speak briefly, and in a\r\nfigure. And let the figure be composite--a pair of winged horses and a\r\ncharioteer. Now the winged horses and the charioteers of the gods are\r\nall of them noble and of noble descent, but those of other races are\r\nmixed; the human charioteer drives his in a pair; and one of them is\r\nnoble and of noble breed, and the other is ignoble and of ignoble breed;\r\nand the driving of them of necessity gives a great deal of trouble to\r\nhim. I will endeavour to explain to you in what way the mortal differs\r\nfrom the immortal creature. The soul in her totality has the care of\r\ninanimate being everywhere, and traverses the whole heaven in divers\r\nforms appearing--when perfect and fully winged she soars upward, and\r\norders the whole world; whereas the imperfect soul, losing her wings\r\nand drooping in her flight at last settles on the solid ground--there,\r\nfinding a home, she receives an earthly frame which appears to be\r\nself-moved, but is really moved by her power; and this composition of\r\nsoul and body is called a living and mortal creature. For immortal no\r\nsuch union can be reasonably believed to be; although fancy, not\r\nhaving seen nor surely known the nature of God, may imagine an immortal\r\ncreature having both a body and also a soul which are united throughout\r\nall time. Let that, however, be as God wills, and be spoken of\r\nacceptably to him. And now let us ask the reason why the soul loses her\r\nwings!\r\n\r\nThe wing is the corporeal element which is most akin to the divine,\r\nand which by nature tends to soar aloft and carry that which gravitates\r\ndownwards into the upper region, which is the habitation of the gods.\r\nThe divine is beauty, wisdom, goodness, and the like; and by these the\r\nwing of the soul is nourished, and grows apace; but when fed upon evil\r\nand foulness and the opposite of good, wastes and falls away. Zeus, the\r\nmighty lord, holding the reins of a winged chariot, leads the way in\r\nheaven, ordering all and taking care of all; and there follows him the\r\narray of gods and demi-gods, marshalled in eleven bands; Hestia alone\r\nabides at home in the house of heaven; of the rest they who are reckoned\r\namong the princely twelve march in their appointed order. They see many\r\nblessed sights in the inner heaven, and there are many ways to and fro,\r\nalong which the blessed gods are passing, every one doing his own\r\nwork; he may follow who will and can, for jealousy has no place in the\r\ncelestial choir. But when they go to banquet and festival, then they\r\nmove up the steep to the top of the vault of heaven. The chariots of\r\nthe gods in even poise, obeying the rein, glide rapidly; but the others\r\nlabour, for the vicious steed goes heavily, weighing down the charioteer\r\nto the earth when his steed has not been thoroughly trained:--and\r\nthis is the hour of agony and extremest conflict for the soul. For the\r\nimmortals, when they are at the end of their course, go forth and stand\r\nupon the outside of heaven, and the revolution of the spheres carries\r\nthem round, and they behold the things beyond. But of the heaven which\r\nis above the heavens, what earthly poet ever did or ever will sing\r\nworthily? It is such as I will describe; for I must dare to speak the\r\ntruth, when truth is my theme. There abides the very being with which\r\ntrue knowledge is concerned; the colourless, formless, intangible\r\nessence, visible only to mind, the pilot of the soul. The divine\r\nintelligence, being nurtured upon mind and pure knowledge, and the\r\nintelligence of every soul which is capable of receiving the food proper\r\nto it, rejoices at beholding reality, and once more gazing upon truth,\r\nis replenished and made glad, until the revolution of the worlds\r\nbrings her round again to the same place. In the revolution she beholds\r\njustice, and temperance, and knowledge absolute, not in the form of\r\ngeneration or of relation, which men call existence, but knowledge\r\nabsolute in existence absolute; and beholding the other true existences\r\nin like manner, and feasting upon them, she passes down into the\r\ninterior of the heavens and returns home; and there the charioteer\r\nputting up his horses at the stall, gives them ambrosia to eat and\r\nnectar to drink.\r\n\r\nSuch is the life of the gods; but of other souls, that which follows\r\nGod best and is likest to him lifts the head of the charioteer into the\r\nouter world, and is carried round in the revolution, troubled indeed by\r\nthe steeds, and with difficulty beholding true being; while another\r\nonly rises and falls, and sees, and again fails to see by reason of the\r\nunruliness of the steeds. The rest of the souls are also longing after\r\nthe upper world and they all follow, but not being strong enough they\r\nare carried round below the surface, plunging, treading on one another,\r\neach striving to be first; and there is confusion and perspiration and\r\nthe extremity of effort; and many of them are lamed or have their wings\r\nbroken through the ill-driving of the charioteers; and all of them after\r\na fruitless toil, not having attained to the mysteries of true being,\r\ngo away, and feed upon opinion. The reason why the souls exhibit this\r\nexceeding eagerness to behold the plain of truth is that pasturage is\r\nfound there, which is suited to the highest part of the soul; and the\r\nwing on which the soul soars is nourished with this. And there is a law\r\nof Destiny, that the soul which attains any vision of truth in company\r\nwith a god is preserved from harm until the next period, and if\r\nattaining always is always unharmed. But when she is unable to follow,\r\nand fails to behold the truth, and through some ill-hap sinks beneath\r\nthe double load of forgetfulness and vice, and her wings fall from her\r\nand she drops to the ground, then the law ordains that this soul shall\r\nat her first birth pass, not into any other animal, but only into man;\r\nand the soul which has seen most of truth shall come to the birth as a\r\nphilosopher, or artist, or some musical and loving nature; that which\r\nhas seen truth in the second degree shall be some righteous king\r\nor warrior chief; the soul which is of the third class shall be a\r\npolitician, or economist, or trader; the fourth shall be a lover of\r\ngymnastic toils, or a physician; the fifth shall lead the life of a\r\nprophet or hierophant; to the sixth the character of poet or some other\r\nimitative artist will be assigned; to the seventh the life of an artisan\r\nor husbandman; to the eighth that of a sophist or demagogue; to the\r\nninth that of a tyrant--all these are states of probation, in which\r\nhe who does righteously improves, and he who does unrighteously,\r\ndeteriorates his lot.\r\n\r\nTen thousand years must elapse before the soul of each one can return to\r\nthe place from whence she came, for she cannot grow her wings in less;\r\nonly the soul of a philosopher, guileless and true, or the soul of a\r\nlover, who is not devoid of philosophy, may acquire wings in the third\r\nof the recurring periods of a thousand years; he is distinguished from\r\nthe ordinary good man who gains wings in three thousand years:--and they\r\nwho choose this life three times in succession have wings given them,\r\nand go away at the end of three thousand years. But the others (The\r\nphilosopher alone is not subject to judgment (krisis), for he has never\r\nlost the vision of truth.) receive judgment when they have completed\r\ntheir first life, and after the judgment they go, some of them to the\r\nhouses of correction which are under the earth, and are punished; others\r\nto some place in heaven whither they are lightly borne by justice, and\r\nthere they live in a manner worthy of the life which they led here when\r\nin the form of men. And at the end of the first thousand years the good\r\nsouls and also the evil souls both come to draw lots and choose their\r\nsecond life, and they may take any which they please. The soul of a man\r\nmay pass into the life of a beast, or from the beast return again into\r\nthe man. But the soul which has never seen the truth will not pass into\r\nthe human form. For a man must have intelligence of universals, and be\r\nable to proceed from the many particulars of sense to one conception of\r\nreason;--this is the recollection of those things which our soul once\r\nsaw while following God--when regardless of that which we now call being\r\nshe raised her head up towards the true being. And therefore the mind\r\nof the philosopher alone has wings; and this is just, for he is always,\r\naccording to the measure of his abilities, clinging in recollection to\r\nthose things in which God abides, and in beholding which He is what He\r\nis. And he who employs aright these memories is ever being initiated\r\ninto perfect mysteries and alone becomes truly perfect. But, as he\r\nforgets earthly interests and is rapt in the divine, the vulgar deem him\r\nmad, and rebuke him; they do not see that he is inspired.\r\n\r\nThus far I have been speaking of the fourth and last kind of madness,\r\nwhich is imputed to him who, when he sees the beauty of earth, is\r\ntransported with the recollection of the true beauty; he would like to\r\nfly away, but he cannot; he is like a bird fluttering and looking upward\r\nand careless of the world below; and he is therefore thought to be mad.\r\nAnd I have shown this of all inspirations to be the noblest and highest\r\nand the offspring of the highest to him who has or shares in it, and\r\nthat he who loves the beautiful is called a lover because he partakes of\r\nit. For, as has been already said, every soul of man has in the way of\r\nnature beheld true being; this was the condition of her passing into the\r\nform of man. But all souls do not easily recall the things of the other\r\nworld; they may have seen them for a short time only, or they may have\r\nbeen unfortunate in their earthly lot, and, having had their hearts\r\nturned to unrighteousness through some corrupting influence, they may\r\nhave lost the memory of the holy things which once they saw. Few only\r\nretain an adequate remembrance of them; and they, when they behold\r\nhere any image of that other world, are rapt in amazement; but they\r\nare ignorant of what this rapture means, because they do not clearly\r\nperceive. For there is no light of justice or temperance or any of the\r\nhigher ideas which are precious to souls in the earthly copies of them:\r\nthey are seen through a glass dimly; and there are few who, going to the\r\nimages, behold in them the realities, and these only with difficulty.\r\nThere was a time when with the rest of the happy band they saw beauty\r\nshining in brightness,--we philosophers following in the train of Zeus,\r\nothers in company with other gods; and then we beheld the beatific\r\nvision and were initiated into a mystery which may be truly called most\r\nblessed, celebrated by us in our state of innocence, before we had\r\nany experience of evils to come, when we were admitted to the sight\r\nof apparitions innocent and simple and calm and happy, which we beheld\r\nshining in pure light, pure ourselves and not yet enshrined in that\r\nliving tomb which we carry about, now that we are imprisoned in the\r\nbody, like an oyster in his shell. Let me linger over the memory of\r\nscenes which have passed away.\r\n\r\nBut of beauty, I repeat again that we saw her there shining in company\r\nwith the celestial forms; and coming to earth we find her here too,\r\nshining in clearness through the clearest aperture of sense. For sight\r\nis the most piercing of our bodily senses; though not by that is wisdom\r\nseen; her loveliness would have been transporting if there had been\r\na visible image of her, and the other ideas, if they had visible\r\ncounterparts, would be equally lovely. But this is the privilege of\r\nbeauty, that being the loveliest she is also the most palpable to sight.\r\nNow he who is not newly initiated or who has become corrupted, does not\r\neasily rise out of this world to the sight of true beauty in the other;\r\nhe looks only at her earthly namesake, and instead of being awed at the\r\nsight of her, he is given over to pleasure, and like a brutish beast he\r\nrushes on to enjoy and beget; he consorts with wantonness, and is not\r\nafraid or ashamed of pursuing pleasure in violation of nature. But\r\nhe whose initiation is recent, and who has been the spectator of many\r\nglories in the other world, is amazed when he sees any one having a\r\ngodlike face or form, which is the expression of divine beauty; and at\r\nfirst a shudder runs through him, and again the old awe steals over him;\r\nthen looking upon the face of his beloved as of a god he reverences him,\r\nand if he were not afraid of being thought a downright madman, he would\r\nsacrifice to his beloved as to the image of a god; then while he gazes\r\non him there is a sort of reaction, and the shudder passes into an\r\nunusual heat and perspiration; for, as he receives the effluence of\r\nbeauty through the eyes, the wing moistens and he warms. And as he\r\nwarms, the parts out of which the wing grew, and which had been hitherto\r\nclosed and rigid, and had prevented the wing from shooting forth, are\r\nmelted, and as nourishment streams upon him, the lower end of the wing\r\nbegins to swell and grow from the root upwards; and the growth extends\r\nunder the whole soul--for once the whole was winged. During this process\r\nthe whole soul is all in a state of ebullition and effervescence,--which\r\nmay be compared to the irritation and uneasiness in the gums at the\r\ntime of cutting teeth,--bubbles up, and has a feeling of uneasiness and\r\ntickling; but when in like manner the soul is beginning to grow wings,\r\nthe beauty of the beloved meets her eye and she receives the sensible\r\nwarm motion of particles which flow towards her, therefore called\r\nemotion (imeros), and is refreshed and warmed by them, and then she\r\nceases from her pain with joy. But when she is parted from her beloved\r\nand her moisture fails, then the orifices of the passage out of which\r\nthe wing shoots dry up and close, and intercept the germ of the wing;\r\nwhich, being shut up with the emotion, throbbing as with the pulsations\r\nof an artery, pricks the aperture which is nearest, until at length the\r\nentire soul is pierced and maddened and pained, and at the recollection\r\nof beauty is again delighted. And from both of them together the soul is\r\noppressed at the strangeness of her condition, and is in a great strait\r\nand excitement, and in her madness can neither sleep by night nor abide\r\nin her place by day. And wherever she thinks that she will behold the\r\nbeautiful one, thither in her desire she runs. And when she has seen\r\nhim, and bathed herself in the waters of beauty, her constraint is\r\nloosened, and she is refreshed, and has no more pangs and pains; and\r\nthis is the sweetest of all pleasures at the time, and is the reason\r\nwhy the soul of the lover will never forsake his beautiful one, whom he\r\nesteems above all; he has forgotten mother and brethren and companions,\r\nand he thinks nothing of the neglect and loss of his property; the rules\r\nand proprieties of life, on which he formerly prided himself, he now\r\ndespises, and is ready to sleep like a servant, wherever he is allowed,\r\nas near as he can to his desired one, who is the object of his worship,\r\nand the physician who can alone assuage the greatness of his pain. And\r\nthis state, my dear imaginary youth to whom I am talking, is by men\r\ncalled love, and among the gods has a name at which you, in your\r\nsimplicity, may be inclined to mock; there are two lines in the\r\napocryphal writings of Homer in which the name occurs. One of them is\r\nrather outrageous, and not altogether metrical. They are as follows:\r\n\r\n'Mortals call him fluttering love, But the immortals call him winged\r\none, Because the growing of wings (Or, reading pterothoiton, 'the\r\nmovement of wings.') is a necessity to him.'\r\n\r\nYou may believe this, but not unless you like. At any rate the loves of\r\nlovers and their causes are such as I have described.\r\n\r\nNow the lover who is taken to be the attendant of Zeus is better able to\r\nbear the winged god, and can endure a heavier burden; but the attendants\r\nand companions of Ares, when under the influence of love, if they fancy\r\nthat they have been at all wronged, are ready to kill and put an end\r\nto themselves and their beloved. And he who follows in the train of any\r\nother god, while he is unspoiled and the impression lasts, honours and\r\nimitates him, as far as he is able; and after the manner of his God he\r\nbehaves in his intercourse with his beloved and with the rest of the\r\nworld during the first period of his earthly existence. Every one\r\nchooses his love from the ranks of beauty according to his character,\r\nand this he makes his god, and fashions and adorns as a sort of image\r\nwhich he is to fall down and worship. The followers of Zeus desire that\r\ntheir beloved should have a soul like him; and therefore they seek out\r\nsome one of a philosophical and imperial nature, and when they have\r\nfound him and loved him, they do all they can to confirm such a nature\r\nin him, and if they have no experience of such a disposition hitherto,\r\nthey learn of any one who can teach them, and themselves follow in the\r\nsame way. And they have the less difficulty in finding the nature of\r\ntheir own god in themselves, because they have been compelled to gaze\r\nintensely on him; their recollection clings to him, and they become\r\npossessed of him, and receive from him their character and disposition,\r\nso far as man can participate in God. The qualities of their god they\r\nattribute to the beloved, wherefore they love him all the more, and if,\r\nlike the Bacchic Nymphs, they draw inspiration from Zeus, they pour out\r\ntheir own fountain upon him, wanting to make him as like as possible\r\nto their own god. But those who are the followers of Here seek a royal\r\nlove, and when they have found him they do just the same with him; and\r\nin like manner the followers of Apollo, and of every other god walking\r\nin the ways of their god, seek a love who is to be made like him whom\r\nthey serve, and when they have found him, they themselves imitate their\r\ngod, and persuade their love to do the same, and educate him into the\r\nmanner and nature of the god as far as they each can; for no feelings of\r\nenvy or jealousy are entertained by them towards their beloved, but they\r\ndo their utmost to create in him the greatest likeness of themselves and\r\nof the god whom they honour. Thus fair and blissful to the beloved is\r\nthe desire of the inspired lover, and the initiation of which I speak\r\ninto the mysteries of true love, if he be captured by the lover and\r\ntheir purpose is effected. Now the beloved is taken captive in the\r\nfollowing manner:--\r\n\r\nAs I said at the beginning of this tale, I divided each soul into\r\nthree--two horses and a charioteer; and one of the horses was good and\r\nthe other bad: the division may remain, but I have not yet explained in\r\nwhat the goodness or badness of either consists, and to that I will\r\nnow proceed. The right-hand horse is upright and cleanly made; he has a\r\nlofty neck and an aquiline nose; his colour is white, and his eyes dark;\r\nhe is a lover of honour and modesty and temperance, and the follower\r\nof true glory; he needs no touch of the whip, but is guided by word and\r\nadmonition only. The other is a crooked lumbering animal, put together\r\nanyhow; he has a short thick neck; he is flat-faced and of a dark\r\ncolour, with grey eyes and blood-red complexion (Or with grey and\r\nblood-shot eyes.); the mate of insolence and pride, shag-eared and deaf,\r\nhardly yielding to whip and spur. Now when the charioteer beholds the\r\nvision of love, and has his whole soul warmed through sense, and is full\r\nof the prickings and ticklings of desire, the obedient steed, then\r\nas always under the government of shame, refrains from leaping on the\r\nbeloved; but the other, heedless of the pricks and of the blows of\r\nthe whip, plunges and runs away, giving all manner of trouble to his\r\ncompanion and the charioteer, whom he forces to approach the beloved and\r\nto remember the joys of love. They at first indignantly oppose him and\r\nwill not be urged on to do terrible and unlawful deeds; but at last,\r\nwhen he persists in plaguing them, they yield and agree to do as he bids\r\nthem. And now they are at the spot and behold the flashing beauty of the\r\nbeloved; which when the charioteer sees, his memory is carried to the\r\ntrue beauty, whom he beholds in company with Modesty like an image\r\nplaced upon a holy pedestal. He sees her, but he is afraid and falls\r\nbackwards in adoration, and by his fall is compelled to pull back the\r\nreins with such violence as to bring both the steeds on their haunches,\r\nthe one willing and unresisting, the unruly one very unwilling; and when\r\nthey have gone back a little, the one is overcome with shame and wonder,\r\nand his whole soul is bathed in perspiration; the other, when the\r\npain is over which the bridle and the fall had given him, having with\r\ndifficulty taken breath, is full of wrath and reproaches, which he\r\nheaps upon the charioteer and his fellow-steed, for want of courage\r\nand manhood, declaring that they have been false to their agreement and\r\nguilty of desertion. Again they refuse, and again he urges them on, and\r\nwill scarce yield to their prayer that he would wait until another time.\r\nWhen the appointed hour comes, they make as if they had forgotten, and\r\nhe reminds them, fighting and neighing and dragging them on, until at\r\nlength he on the same thoughts intent, forces them to draw near again.\r\nAnd when they are near he stoops his head and puts up his tail, and\r\ntakes the bit in his teeth and pulls shamelessly. Then the charioteer is\r\nworse off than ever; he falls back like a racer at the barrier, and with\r\na still more violent wrench drags the bit out of the teeth of the wild\r\nsteed and covers his abusive tongue and jaws with blood, and forces his\r\nlegs and haunches to the ground and punishes him sorely. And when this\r\nhas happened several times and the villain has ceased from his wanton\r\nway, he is tamed and humbled, and follows the will of the charioteer,\r\nand when he sees the beautiful one he is ready to die of fear. And from\r\nthat time forward the soul of the lover follows the beloved in modesty\r\nand holy fear.\r\n\r\nAnd so the beloved who, like a god, has received every true and loyal\r\nservice from his lover, not in pretence but in reality, being also\r\nhimself of a nature friendly to his admirer, if in former days he\r\nhas blushed to own his passion and turned away his lover, because his\r\nyouthful companions or others slanderously told him that he would be\r\ndisgraced, now as years advance, at the appointed age and time, is led\r\nto receive him into communion. For fate which has ordained that there\r\nshall be no friendship among the evil has also ordained that there shall\r\never be friendship among the good. And the beloved when he has received\r\nhim into communion and intimacy, is quite amazed at the good-will of the\r\nlover; he recognises that the inspired friend is worth all other\r\nfriends or kinsmen; they have nothing of friendship in them worthy to be\r\ncompared with his. And when this feeling continues and he is nearer\r\nto him and embraces him, in gymnastic exercises and at other times of\r\nmeeting, then the fountain of that stream, which Zeus when he was in\r\nlove with Ganymede named Desire, overflows upon the lover, and some\r\nenters into his soul, and some when he is filled flows out again; and as\r\na breeze or an echo rebounds from the smooth rocks and returns whence it\r\ncame, so does the stream of beauty, passing through the eyes which are\r\nthe windows of the soul, come back to the beautiful one; there arriving\r\nand quickening the passages of the wings, watering them and inclining\r\nthem to grow, and filling the soul of the beloved also with love. And\r\nthus he loves, but he knows not what; he does not understand and cannot\r\nexplain his own state; he appears to have caught the infection of\r\nblindness from another; the lover is his mirror in whom he is beholding\r\nhimself, but he is not aware of this. When he is with the lover, both\r\ncease from their pain, but when he is away then he longs as he is\r\nlonged for, and has love's image, love for love (Anteros) lodging in his\r\nbreast, which he calls and believes to be not love but friendship only,\r\nand his desire is as the desire of the other, but weaker; he wants\r\nto see him, touch him, kiss him, embrace him, and probably not long\r\nafterwards his desire is accomplished. When they meet, the wanton steed\r\nof the lover has a word to say to the charioteer; he would like to have\r\na little pleasure in return for many pains, but the wanton steed of\r\nthe beloved says not a word, for he is bursting with passion which he\r\nunderstands not;--he throws his arms round the lover and embraces him\r\nas his dearest friend; and, when they are side by side, he is not in a\r\nstate in which he can refuse the lover anything, if he ask him; although\r\nhis fellow-steed and the charioteer oppose him with the arguments\r\nof shame and reason. After this their happiness depends upon their\r\nself-control; if the better elements of the mind which lead to order\r\nand philosophy prevail, then they pass their life here in happiness and\r\nharmony--masters of themselves and orderly--enslaving the vicious and\r\nemancipating the virtuous elements of the soul; and when the end comes,\r\nthey are light and winged for flight, having conquered in one of the\r\nthree heavenly or truly Olympian victories; nor can human discipline or\r\ndivine inspiration confer any greater blessing on man than this. If,\r\non the other hand, they leave philosophy and lead the lower life of\r\nambition, then probably, after wine or in some other careless hour, the\r\ntwo wanton animals take the two souls when off their guard and bring\r\nthem together, and they accomplish that desire of their hearts which to\r\nthe many is bliss; and this having once enjoyed they continue to enjoy,\r\nyet rarely because they have not the approval of the whole soul. They\r\ntoo are dear, but not so dear to one another as the others, either at\r\nthe time of their love or afterwards. They consider that they have given\r\nand taken from each other the most sacred pledges, and they may not\r\nbreak them and fall into enmity. At last they pass out of the body,\r\nunwinged, but eager to soar, and thus obtain no mean reward of love and\r\nmadness. For those who have once begun the heavenward pilgrimage may not\r\ngo down again to darkness and the journey beneath the earth, but they\r\nlive in light always; happy companions in their pilgrimage, and when the\r\ntime comes at which they receive their wings they have the same plumage\r\nbecause of their love.\r\n\r\nThus great are the heavenly blessings which the friendship of a lover\r\nwill confer upon you, my youth. Whereas the attachment of the non-lover,\r\nwhich is alloyed with a worldly prudence and has worldly and niggardly\r\nways of doling out benefits, will breed in your soul those vulgar\r\nqualities which the populace applaud, will send you bowling round the\r\nearth during a period of nine thousand years, and leave you a fool in\r\nthe world below.\r\n\r\nAnd thus, dear Eros, I have made and paid my recantation, as well and as\r\nfairly as I could; more especially in the matter of the poetical figures\r\nwhich I was compelled to use, because Phaedrus would have them. And now\r\nforgive the past and accept the present, and be gracious and merciful to\r\nme, and do not in thine anger deprive me of sight, or take from me the\r\nart of love which thou hast given me, but grant that I may be yet more\r\nesteemed in the eyes of the fair. And if Phaedrus or I myself said\r\nanything rude in our first speeches, blame Lysias, who is the father\r\nof the brat, and let us have no more of his progeny; bid him study\r\nphilosophy, like his brother Polemarchus; and then his lover Phaedrus\r\nwill no longer halt between two opinions, but will dedicate himself\r\nwholly to love and to philosophical discourses.\r\n\r\nPHAEDRUS: I join in the prayer, Socrates, and say with you, if this\r\nbe for my good, may your words come to pass. But why did you make your\r\nsecond oration so much finer than the first? I wonder why. And I begin\r\nto be afraid that I shall lose conceit of Lysias, and that he will\r\nappear tame in comparison, even if he be willing to put another as fine\r\nand as long as yours into the field, which I doubt. For quite lately one\r\nof your politicians was abusing him on this very account; and called\r\nhim a 'speech writer' again and again. So that a feeling of pride may\r\nprobably induce him to give up writing speeches.\r\n\r\nSOCRATES: What a very amusing notion! But I think, my young man,\r\nthat you are much mistaken in your friend if you imagine that he\r\nis frightened at a little noise; and, possibly, you think that his\r\nassailant was in earnest?\r\n\r\nPHAEDRUS: I thought, Socrates, that he was. And you are aware that the\r\ngreatest and most influential statesmen are ashamed of writing speeches\r\nand leaving them in a written form, lest they should be called Sophists\r\nby posterity.\r\n\r\nSOCRATES: You seem to be unconscious, Phaedrus, that the 'sweet elbow'\r\n(A proverb, like 'the grapes are sour,' applied to pleasures which\r\ncannot be had, meaning sweet things which, like the elbow, are out of\r\nthe reach of the mouth. The promised pleasure turns out to be a long and\r\ntedious affair.) of the proverb is really the long arm of the Nile. And\r\nyou appear to be equally unaware of the fact that this sweet elbow\r\nof theirs is also a long arm. For there is nothing of which our great\r\npoliticians are so fond as of writing speeches and bequeathing them to\r\nposterity. And they add their admirers' names at the top of the writing,\r\nout of gratitude to them.\r\n\r\nPHAEDRUS: What do you mean? I do not understand.\r\n\r\nSOCRATES: Why, do you not know that when a politician writes, he begins\r\nwith the names of his approvers?\r\n\r\nPHAEDRUS: How so?\r\n\r\nSOCRATES: Why, he begins in this manner: 'Be it enacted by the senate,\r\nthe people, or both, on the motion of a certain person,' who is our\r\nauthor; and so putting on a serious face, he proceeds to display his own\r\nwisdom to his admirers in what is often a long and tedious composition.\r\nNow what is that sort of thing but a regular piece of authorship?\r\n\r\nPHAEDRUS: True.\r\n\r\nSOCRATES: And if the law is finally approved, then the author leaves the\r\ntheatre in high delight; but if the law is rejected and he is done out\r\nof his speech-making, and not thought good enough to write, then he and\r\nhis party are in mourning.\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: So far are they from despising, or rather so highly do they\r\nvalue the practice of writing.\r\n\r\nPHAEDRUS: No doubt.\r\n\r\nSOCRATES: And when the king or orator has the power, as Lycurgus or\r\nSolon or Darius had, of attaining an immortality or authorship in a\r\nstate, is he not thought by posterity, when they see his compositions,\r\nand does he not think himself, while he is yet alive, to be a god?\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: Then do you think that any one of this class, however\r\nill-disposed, would reproach Lysias with being an author?\r\n\r\nPHAEDRUS: Not upon your view; for according to you he would be casting a\r\nslur upon his own favourite pursuit.\r\n\r\nSOCRATES: Any one may see that there is no disgrace in the mere fact of\r\nwriting.\r\n\r\nPHAEDRUS: Certainly not.\r\n\r\nSOCRATES: The disgrace begins when a man writes not well, but badly.\r\n\r\nPHAEDRUS: Clearly.\r\n\r\nSOCRATES: And what is well and what is badly--need we ask Lysias, or any\r\nother poet or orator, who ever wrote or will write either a political or\r\nany other work, in metre or out of metre, poet or prose writer, to teach\r\nus this?\r\n\r\nPHAEDRUS: Need we? For what should a man live if not for the pleasures\r\nof discourse? Surely not for the sake of bodily pleasures, which almost\r\nalways have previous pain as a condition of them, and therefore are\r\nrightly called slavish.\r\n\r\nSOCRATES: There is time enough. And I believe that the grasshoppers\r\nchirruping after their manner in the heat of the sun over our heads are\r\ntalking to one another and looking down at us. What would they say if\r\nthey saw that we, like the many, are not conversing, but slumbering at\r\nmid-day, lulled by their voices, too indolent to think? Would they not\r\nhave a right to laugh at us? They might imagine that we were slaves,\r\nwho, coming to rest at a place of resort of theirs, like sheep lie\r\nasleep at noon around the well. But if they see us discoursing, and\r\nlike Odysseus sailing past them, deaf to their siren voices, they may\r\nperhaps, out of respect, give us of the gifts which they receive from\r\nthe gods that they may impart them to men.\r\n\r\nPHAEDRUS: What gifts do you mean? I never heard of any.\r\n\r\nSOCRATES: A lover of music like yourself ought surely to have heard the\r\nstory of the grasshoppers, who are said to have been human beings in\r\nan age before the Muses. And when the Muses came and song appeared they\r\nwere ravished with delight; and singing always, never thought of eating\r\nand drinking, until at last in their forgetfulness they died. And now\r\nthey live again in the grasshoppers; and this is the return which the\r\nMuses make to them--they neither hunger, nor thirst, but from the hour\r\nof their birth are always singing, and never eating or drinking; and\r\nwhen they die they go and inform the Muses in heaven who honours them on\r\nearth. They win the love of Terpsichore for the dancers by their report\r\nof them; of Erato for the lovers, and of the other Muses for those who\r\ndo them honour, according to the several ways of honouring them;--of\r\nCalliope the eldest Muse and of Urania who is next to her, for the\r\nphilosophers, of whose music the grasshoppers make report to them; for\r\nthese are the Muses who are chiefly concerned with heaven and thought,\r\ndivine as well as human, and they have the sweetest utterance. For many\r\nreasons, then, we ought always to talk and not to sleep at mid-day.\r\n\r\nPHAEDRUS: Let us talk.\r\n\r\nSOCRATES: Shall we discuss the rules of writing and speech as we were\r\nproposing?\r\n\r\nPHAEDRUS: Very good.\r\n\r\nSOCRATES: In good speaking should not the mind of the speaker know the\r\ntruth of the matter about which he is going to speak?\r\n\r\nPHAEDRUS: And yet, Socrates, I have heard that he who would be an orator\r\nhas nothing to do with true justice, but only with that which is likely\r\nto be approved by the many who sit in judgment; nor with the truly good\r\nor honourable, but only with opinion about them, and that from opinion\r\ncomes persuasion, and not from the truth.\r\n\r\nSOCRATES: The words of the wise are not to be set aside; for there is\r\nprobably something in them; and therefore the meaning of this saying is\r\nnot hastily to be dismissed.\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: Let us put the matter thus:--Suppose that I persuaded you\r\nto buy a horse and go to the wars. Neither of us knew what a horse was\r\nlike, but I knew that you believed a horse to be of tame animals the one\r\nwhich has the longest ears.\r\n\r\nPHAEDRUS: That would be ridiculous.\r\n\r\nSOCRATES: There is something more ridiculous coming:--Suppose, further,\r\nthat in sober earnest I, having persuaded you of this, went and composed\r\na speech in honour of an ass, whom I entitled a horse beginning: 'A\r\nnoble animal and a most useful possession, especially in war, and you\r\nmay get on his back and fight, and he will carry baggage or anything.'\r\n\r\nPHAEDRUS: How ridiculous!\r\n\r\nSOCRATES: Ridiculous! Yes; but is not even a ridiculous friend better\r\nthan a cunning enemy?\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: And when the orator instead of putting an ass in the place\r\nof a horse, puts good for evil, being himself as ignorant of their true\r\nnature as the city on which he imposes is ignorant; and having studied\r\nthe notions of the multitude, falsely persuades them not about 'the\r\nshadow of an ass,' which he confounds with a horse, but about good which\r\nhe confounds with evil,--what will be the harvest which rhetoric will be\r\nlikely to gather after the sowing of that seed?\r\n\r\nPHAEDRUS: The reverse of good.\r\n\r\nSOCRATES: But perhaps rhetoric has been getting too roughly handled by\r\nus, and she might answer: What amazing nonsense you are talking! As if I\r\nforced any man to learn to speak in ignorance of the truth! Whatever\r\nmy advice may be worth, I should have told him to arrive at the truth\r\nfirst, and then come to me. At the same time I boldly assert that mere\r\nknowledge of the truth will not give you the art of persuasion.\r\n\r\nPHAEDRUS: There is reason in the lady's defence of herself.\r\n\r\nSOCRATES: Quite true; if only the other arguments which remain to be\r\nbrought up bear her witness that she is an art at all. But I seem to\r\nhear them arraying themselves on the opposite side, declaring that she\r\nspeaks falsely, and that rhetoric is a mere routine and trick, not an\r\nart. Lo! a Spartan appears, and says that there never is nor ever will\r\nbe a real art of speaking which is divorced from the truth.\r\n\r\nPHAEDRUS: And what are these arguments, Socrates? Bring them out that we\r\nmay examine them.\r\n\r\nSOCRATES: Come out, fair children, and convince Phaedrus, who is the\r\nfather of similar beauties, that he will never be able to speak about\r\nanything as he ought to speak unless he have a knowledge of philosophy.\r\nAnd let Phaedrus answer you.\r\n\r\nPHAEDRUS: Put the question.\r\n\r\nSOCRATES: Is not rhetoric, taken generally, a universal art of\r\nenchanting the mind by arguments; which is practised not only in courts\r\nand public assemblies, but in private houses also, having to do with\r\nall matters, great as well as small, good and bad alike, and is in all\r\nequally right, and equally to be esteemed--that is what you have heard?\r\n\r\nPHAEDRUS: Nay, not exactly that; I should say rather that I have heard\r\nthe art confined to speaking and writing in lawsuits, and to speaking in\r\npublic assemblies--not extended farther.\r\n\r\nSOCRATES: Then I suppose that you have only heard of the rhetoric of\r\nNestor and Odysseus, which they composed in their leisure hours when at\r\nTroy, and never of the rhetoric of Palamedes?\r\n\r\nPHAEDRUS: No more than of Nestor and Odysseus, unless Gorgias is your\r\nNestor, and Thrasymachus or Theodorus your Odysseus.\r\n\r\nSOCRATES: Perhaps that is my meaning. But let us leave them. And do\r\nyou tell me, instead, what are plaintiff and defendant doing in a law\r\ncourt--are they not contending?\r\n\r\nPHAEDRUS: Exactly so.\r\n\r\nSOCRATES: About the just and unjust--that is the matter in dispute?\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: And a professor of the art will make the same thing appear to\r\nthe same persons to be at one time just, at another time, if he is so\r\ninclined, to be unjust?\r\n\r\nPHAEDRUS: Exactly.\r\n\r\nSOCRATES: And when he speaks in the assembly, he will make the same\r\nthings seem good to the city at one time, and at another time the\r\nreverse of good?\r\n\r\nPHAEDRUS: That is true.\r\n\r\nSOCRATES: Have we not heard of the Eleatic Palamedes (Zeno), who has an\r\nart of speaking by which he makes the same things appear to his hearers\r\nlike and unlike, one and many, at rest and in motion?\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: The art of disputation, then, is not confined to the courts\r\nand the assembly, but is one and the same in every use of language; this\r\nis the art, if there be such an art, which is able to find a likeness of\r\neverything to which a likeness can be found, and draws into the light of\r\nday the likenesses and disguises which are used by others?\r\n\r\nPHAEDRUS: How do you mean?\r\n\r\nSOCRATES: Let me put the matter thus: When will there be more chance of\r\ndeception--when the difference is large or small?\r\n\r\nPHAEDRUS: When the difference is small.\r\n\r\nSOCRATES: And you will be less likely to be discovered in passing by\r\ndegrees into the other extreme than when you go all at once?\r\n\r\nPHAEDRUS: Of course.\r\n\r\nSOCRATES: He, then, who would deceive others, and not be deceived, must\r\nexactly know the real likenesses and differences of things?\r\n\r\nPHAEDRUS: He must.\r\n\r\nSOCRATES: And if he is ignorant of the true nature of any subject, how\r\ncan he detect the greater or less degree of likeness in other things to\r\nthat of which by the hypothesis he is ignorant?\r\n\r\nPHAEDRUS: He cannot.\r\n\r\nSOCRATES: And when men are deceived and their notions are at\r\nvariance with realities, it is clear that the error slips in through\r\nresemblances?\r\n\r\nPHAEDRUS: Yes, that is the way.\r\n\r\nSOCRATES: Then he who would be a master of the art must understand the\r\nreal nature of everything; or he will never know either how to make\r\nthe gradual departure from truth into the opposite of truth which is\r\neffected by the help of resemblances, or how to avoid it?\r\n\r\nPHAEDRUS: He will not.\r\n\r\nSOCRATES: He then, who being ignorant of the truth aims at appearances,\r\nwill only attain an art of rhetoric which is ridiculous and is not an\r\nart at all?\r\n\r\nPHAEDRUS: That may be expected.\r\n\r\nSOCRATES: Shall I propose that we look for examples of art and want of\r\nart, according to our notion of them, in the speech of Lysias which you\r\nhave in your hand, and in my own speech?\r\n\r\nPHAEDRUS: Nothing could be better; and indeed I think that our previous\r\nargument has been too abstract and wanting in illustrations.\r\n\r\nSOCRATES: Yes; and the two speeches happen to afford a very good example\r\nof the way in which the speaker who knows the truth may, without any\r\nserious purpose, steal away the hearts of his hearers. This piece\r\nof good-fortune I attribute to the local deities; and, perhaps, the\r\nprophets of the Muses who are singing over our heads may have imparted\r\ntheir inspiration to me. For I do not imagine that I have any rhetorical\r\nart of my own.\r\n\r\nPHAEDRUS: Granted; if you will only please to get on.\r\n\r\nSOCRATES: Suppose that you read me the first words of Lysias' speech.\r\n\r\nPHAEDRUS: 'You know how matters stand with me, and how, as I conceive,\r\nthey might be arranged for our common interest; and I maintain that I\r\nought not to fail in my suit, because I am not your lover. For lovers\r\nrepent--'\r\n\r\nSOCRATES: Enough:--Now, shall I point out the rhetorical error of those\r\nwords?\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: Every one is aware that about some things we are agreed,\r\nwhereas about other things we differ.\r\n\r\nPHAEDRUS: I think that I understand you; but will you explain yourself?\r\n\r\nSOCRATES: When any one speaks of iron and silver, is not the same thing\r\npresent in the minds of all?\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: But when any one speaks of justice and goodness we part\r\ncompany and are at odds with one another and with ourselves?\r\n\r\nPHAEDRUS: Precisely.\r\n\r\nSOCRATES: Then in some things we agree, but not in others?\r\n\r\nPHAEDRUS: That is true.\r\n\r\nSOCRATES: In which are we more likely to be deceived, and in which has\r\nrhetoric the greater power?\r\n\r\nPHAEDRUS: Clearly, in the uncertain class.\r\n\r\nSOCRATES: Then the rhetorician ought to make a regular division, and\r\nacquire a distinct notion of both classes, as well of that in which the\r\nmany err, as of that in which they do not err?\r\n\r\nPHAEDRUS: He who made such a distinction would have an excellent\r\nprinciple.\r\n\r\nSOCRATES: Yes; and in the next place he must have a keen eye for the\r\nobservation of particulars in speaking, and not make a mistake about the\r\nclass to which they are to be referred.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: Now to which class does love belong--to the debatable or to\r\nthe undisputed class?\r\n\r\nPHAEDRUS: To the debatable, clearly; for if not, do you think that love\r\nwould have allowed you to say as you did, that he is an evil both to the\r\nlover and the beloved, and also the greatest possible good?\r\n\r\nSOCRATES: Capital. But will you tell me whether I defined love at the\r\nbeginning of my speech? for, having been in an ecstasy, I cannot well\r\nremember.\r\n\r\nPHAEDRUS: Yes, indeed; that you did, and no mistake.\r\n\r\nSOCRATES: Then I perceive that the Nymphs of Achelous and Pan the son\r\nof Hermes, who inspired me, were far better rhetoricians than Lysias\r\nthe son of Cephalus. Alas! how inferior to them he is! But perhaps I\r\nam mistaken; and Lysias at the commencement of his lover's speech did\r\ninsist on our supposing love to be something or other which he fancied\r\nhim to be, and according to this model he fashioned and framed the\r\nremainder of his discourse. Suppose we read his beginning over again:\r\n\r\nPHAEDRUS: If you please; but you will not find what you want.\r\n\r\nSOCRATES: Read, that I may have his exact words.\r\n\r\nPHAEDRUS: 'You know how matters stand with me, and how, as I conceive,\r\nthey might be arranged for our common interest; and I maintain I ought\r\nnot to fail in my suit because I am not your lover, for lovers repent of\r\nthe kindnesses which they have shown, when their love is over.'\r\n\r\nSOCRATES: Here he appears to have done just the reverse of what he\r\nought; for he has begun at the end, and is swimming on his back through\r\nthe flood to the place of starting. His address to the fair youth begins\r\nwhere the lover would have ended. Am I not right, sweet Phaedrus?\r\n\r\nPHAEDRUS: Yes, indeed, Socrates; he does begin at the end.\r\n\r\nSOCRATES: Then as to the other topics--are they not thrown down anyhow?\r\nIs there any principle in them? Why should the next topic follow next in\r\norder, or any other topic? I cannot help fancying in my ignorance that\r\nhe wrote off boldly just what came into his head, but I dare say that\r\nyou would recognize a rhetorical necessity in the succession of the\r\nseveral parts of the composition?\r\n\r\nPHAEDRUS: You have too good an opinion of me if you think that I have\r\nany such insight into his principles of composition.\r\n\r\nSOCRATES: At any rate, you will allow that every discourse ought to be\r\na living creature, having a body of its own and a head and feet; there\r\nshould be a middle, beginning, and end, adapted to one another and to\r\nthe whole?\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: Can this be said of the discourse of Lysias? See whether you\r\ncan find any more connexion in his words than in the epitaph which is\r\nsaid by some to have been inscribed on the grave of Midas the Phrygian.\r\n\r\nPHAEDRUS: What is there remarkable in the epitaph?\r\n\r\nSOCRATES: It is as follows:--\r\n\r\n'I am a maiden of bronze and lie on the tomb of Midas; So long as water\r\nflows and tall trees grow, So long here on this spot by his sad tomb\r\nabiding, I shall declare to passers-by that Midas sleeps below.'\r\n\r\nNow in this rhyme whether a line comes first or comes last, as you will\r\nperceive, makes no difference.\r\n\r\nPHAEDRUS: You are making fun of that oration of ours.\r\n\r\nSOCRATES: Well, I will say no more about your friend's speech lest I\r\nshould give offence to you; although I think that it might furnish many\r\nother examples of what a man ought rather to avoid. But I will proceed\r\nto the other speech, which, as I think, is also suggestive to students\r\nof rhetoric.\r\n\r\nPHAEDRUS: In what way?\r\n\r\nSOCRATES: The two speeches, as you may remember, were unlike; the one\r\nargued that the lover and the other that the non-lover ought to be\r\naccepted.\r\n\r\nPHAEDRUS: And right manfully.\r\n\r\nSOCRATES: You should rather say 'madly;' and madness was the argument of\r\nthem, for, as I said, 'love is a madness.'\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: And of madness there were two kinds; one produced by human\r\ninfirmity, the other was a divine release of the soul from the yoke of\r\ncustom and convention.\r\n\r\nPHAEDRUS: True.\r\n\r\nSOCRATES: The divine madness was subdivided into four kinds, prophetic,\r\ninitiatory, poetic, erotic, having four gods presiding over them; the\r\nfirst was the inspiration of Apollo, the second that of Dionysus, the\r\nthird that of the Muses, the fourth that of Aphrodite and Eros. In the\r\ndescription of the last kind of madness, which was also said to be\r\nthe best, we spoke of the affection of love in a figure, into which we\r\nintroduced a tolerably credible and possibly true though partly erring\r\nmyth, which was also a hymn in honour of Love, who is your lord and also\r\nmine, Phaedrus, and the guardian of fair children, and to him we sung\r\nthe hymn in measured and solemn strain.\r\n\r\nPHAEDRUS: I know that I had great pleasure in listening to you.\r\n\r\nSOCRATES: Let us take this instance and note how the transition was made\r\nfrom blame to praise.\r\n\r\nPHAEDRUS: What do you mean?\r\n\r\nSOCRATES: I mean to say that the composition was mostly playful. Yet in\r\nthese chance fancies of the hour were involved two principles of which\r\nwe should be too glad to have a clearer description if art could give us\r\none.\r\n\r\nPHAEDRUS: What are they?\r\n\r\nSOCRATES: First, the comprehension of scattered particulars in one idea;\r\nas in our definition of love, which whether true or false certainly gave\r\nclearness and consistency to the discourse, the speaker should define\r\nhis several notions and so make his meaning clear.\r\n\r\nPHAEDRUS: What is the other principle, Socrates?\r\n\r\nSOCRATES: The second principle is that of division into species\r\naccording to the natural formation, where the joint is, not breaking any\r\npart as a bad carver might. Just as our two discourses, alike assumed,\r\nfirst of all, a single form of unreason; and then, as the body which\r\nfrom being one becomes double and may be divided into a left side and\r\nright side, each having parts right and left of the same name--after\r\nthis manner the speaker proceeded to divide the parts of the left side\r\nand did not desist until he found in them an evil or left-handed love\r\nwhich he justly reviled; and the other discourse leading us to the\r\nmadness which lay on the right side, found another love, also having the\r\nsame name, but divine, which the speaker held up before us and applauded\r\nand affirmed to be the author of the greatest benefits.\r\n\r\nPHAEDRUS: Most true.\r\n\r\nSOCRATES: I am myself a great lover of these processes of division and\r\ngeneralization; they help me to speak and to think. And if I find any\r\nman who is able to see 'a One and Many' in nature, him I follow, and\r\n'walk in his footsteps as if he were a god.' And those who have this\r\nart, I have hitherto been in the habit of calling dialecticians; but God\r\nknows whether the name is right or not. And I should like to know what\r\nname you would give to your or to Lysias' disciples, and whether this\r\nmay not be that famous art of rhetoric which Thrasymachus and others\r\nteach and practise? Skilful speakers they are, and impart their skill to\r\nany who is willing to make kings of them and to bring gifts to them.\r\n\r\nPHAEDRUS: Yes, they are royal men; but their art is not the same\r\nwith the art of those whom you call, and rightly, in my opinion,\r\ndialecticians:--Still we are in the dark about rhetoric.\r\n\r\nSOCRATES: What do you mean? The remains of it, if there be anything\r\nremaining which can be brought under rules of art, must be a fine thing;\r\nand, at any rate, is not to be despised by you and me. But how much is\r\nleft?\r\n\r\nPHAEDRUS: There is a great deal surely to be found in books of rhetoric?\r\n\r\nSOCRATES: Yes; thank you for reminding me:--There is the exordium,\r\nshowing how the speech should begin, if I remember rightly; that is what\r\nyou mean--the niceties of the art?\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: Then follows the statement of facts, and upon that witnesses;\r\nthirdly, proofs; fourthly, probabilities are to come; the great\r\nByzantian word-maker also speaks, if I am not mistaken, of confirmation\r\nand further confirmation.\r\n\r\nPHAEDRUS: You mean the excellent Theodorus.\r\n\r\nSOCRATES: Yes; and he tells how refutation or further refutation is to\r\nbe managed, whether in accusation or defence. I ought also to mention\r\nthe illustrious Parian, Evenus, who first invented insinuations and\r\nindirect praises; and also indirect censures, which according to some\r\nhe put into verse to help the memory. But shall I 'to dumb forgetfulness\r\nconsign' Tisias and Gorgias, who are not ignorant that probability is\r\nsuperior to truth, and who by force of argument make the little appear\r\ngreat and the great little, disguise the new in old fashions and the old\r\nin new fashions, and have discovered forms for everything, either short\r\nor going on to infinity. I remember Prodicus laughing when I told him of\r\nthis; he said that he had himself discovered the true rule of art, which\r\nwas to be neither long nor short, but of a convenient length.\r\n\r\nPHAEDRUS: Well done, Prodicus!\r\n\r\nSOCRATES: Then there is Hippias the Elean stranger, who probably agrees\r\nwith him.\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: And there is also Polus, who has treasuries of diplasiology,\r\nand gnomology, and eikonology, and who teaches in them the names of\r\nwhich Licymnius made him a present; they were to give a polish.\r\n\r\nPHAEDRUS: Had not Protagoras something of the same sort?\r\n\r\nSOCRATES: Yes, rules of correct diction and many other fine precepts;\r\nfor the 'sorrows of a poor old man,' or any other pathetic case, no one\r\nis better than the Chalcedonian giant; he can put a whole company of\r\npeople into a passion and out of one again by his mighty magic, and\r\nis first-rate at inventing or disposing of any sort of calumny on any\r\ngrounds or none. All of them agree in asserting that a speech should end\r\nin a recapitulation, though they do not all agree to use the same word.\r\n\r\nPHAEDRUS: You mean that there should be a summing up of the arguments in\r\norder to remind the hearers of them.\r\n\r\nSOCRATES: I have now said all that I have to say of the art of rhetoric:\r\nhave you anything to add?\r\n\r\nPHAEDRUS: Not much; nothing very important.\r\n\r\nSOCRATES: Leave the unimportant and let us bring the really important\r\nquestion into the light of day, which is: What power has this art of\r\nrhetoric, and when?\r\n\r\nPHAEDRUS: A very great power in public meetings.\r\n\r\nSOCRATES: It has. But I should like to know whether you have the same\r\nfeeling as I have about the rhetoricians? To me there seem to be a great\r\nmany holes in their web.\r\n\r\nPHAEDRUS: Give an example.\r\n\r\nSOCRATES: I will. Suppose a person to come to your friend Eryximachus,\r\nor to his father Acumenus, and to say to him: 'I know how to apply drugs\r\nwhich shall have either a heating or a cooling effect, and I can give\r\na vomit and also a purge, and all that sort of thing; and knowing all\r\nthis, as I do, I claim to be a physician and to make physicians by\r\nimparting this knowledge to others,'--what do you suppose that they\r\nwould say?\r\n\r\nPHAEDRUS: They would be sure to ask him whether he knew 'to whom' he\r\nwould give his medicines, and 'when,' and 'how much.'\r\n\r\nSOCRATES: And suppose that he were to reply: 'No; I know nothing of all\r\nthat; I expect the patient who consults me to be able to do these things\r\nfor himself'?\r\n\r\nPHAEDRUS: They would say in reply that he is a madman or a pedant who\r\nfancies that he is a physician because he has read something in a\r\nbook, or has stumbled on a prescription or two, although he has no real\r\nunderstanding of the art of medicine.\r\n\r\nSOCRATES: And suppose a person were to come to Sophocles or Euripides\r\nand say that he knows how to make a very long speech about a small\r\nmatter, and a short speech about a great matter, and also a sorrowful\r\nspeech, or a terrible, or threatening speech, or any other kind of\r\nspeech, and in teaching this fancies that he is teaching the art of\r\ntragedy--?\r\n\r\nPHAEDRUS: They too would surely laugh at him if he fancies that tragedy\r\nis anything but the arranging of these elements in a manner which will\r\nbe suitable to one another and to the whole.\r\n\r\nSOCRATES: But I do not suppose that they would be rude or abusive to\r\nhim: Would they not treat him as a musician a man who thinks that he is\r\na harmonist because he knows how to pitch the highest and lowest note;\r\nhappening to meet such an one he would not say to him savagely, 'Fool,\r\nyou are mad!' But like a musician, in a gentle and harmonious tone of\r\nvoice, he would answer: 'My good friend, he who would be a harmonist\r\nmust certainly know this, and yet he may understand nothing of harmony\r\nif he has not got beyond your stage of knowledge, for you only know the\r\npreliminaries of harmony and not harmony itself.'\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: And will not Sophocles say to the display of the would-be\r\ntragedian, that this is not tragedy but the preliminaries of tragedy?\r\nand will not Acumenus say the same of medicine to the would-be\r\nphysician?\r\n\r\nPHAEDRUS: Quite true.\r\n\r\nSOCRATES: And if Adrastus the mellifluous or Pericles heard of these\r\nwonderful arts, brachylogies and eikonologies and all the hard names\r\nwhich we have been endeavouring to draw into the light of day, what\r\nwould they say? Instead of losing temper and applying uncomplimentary\r\nepithets, as you and I have been doing, to the authors of such an\r\nimaginary art, their superior wisdom would rather censure us, as well\r\nas them. 'Have a little patience, Phaedrus and Socrates, they would say;\r\nyou should not be in such a passion with those who from some want of\r\ndialectical skill are unable to define the nature of rhetoric, and\r\nconsequently suppose that they have found the art in the preliminary\r\nconditions of it, and when these have been taught by them to others,\r\nfancy that the whole art of rhetoric has been taught by them; but as\r\nto using the several instruments of the art effectively, or making the\r\ncomposition a whole,--an application of it such as this is they regard\r\nas an easy thing which their disciples may make for themselves.'\r\n\r\nPHAEDRUS: I quite admit, Socrates, that the art of rhetoric which these\r\nmen teach and of which they write is such as you describe--there I\r\nagree with you. But I still want to know where and how the true art of\r\nrhetoric and persuasion is to be acquired.\r\n\r\nSOCRATES: The perfection which is required of the finished orator is,\r\nor rather must be, like the perfection of anything else; partly given by\r\nnature, but may also be assisted by art. If you have the natural power\r\nand add to it knowledge and practice, you will be a distinguished\r\nspeaker; if you fall short in either of these, you will be to that\r\nextent defective. But the art, as far as there is an art, of rhetoric\r\ndoes not lie in the direction of Lysias or Thrasymachus.\r\n\r\nPHAEDRUS: In what direction then?\r\n\r\nSOCRATES: I conceive Pericles to have been the most accomplished of\r\nrhetoricians.\r\n\r\nPHAEDRUS: What of that?\r\n\r\nSOCRATES: All the great arts require discussion and high speculation\r\nabout the truths of nature; hence come loftiness of thought and\r\ncompleteness of execution. And this, as I conceive, was the quality\r\nwhich, in addition to his natural gifts, Pericles acquired from his\r\nintercourse with Anaxagoras whom he happened to know. He was thus imbued\r\nwith the higher philosophy, and attained the knowledge of Mind and the\r\nnegative of Mind, which were favourite themes of Anaxagoras, and applied\r\nwhat suited his purpose to the art of speaking.\r\n\r\nPHAEDRUS: Explain.\r\n\r\nSOCRATES: Rhetoric is like medicine.\r\n\r\nPHAEDRUS: How so?\r\n\r\nSOCRATES: Why, because medicine has to define the nature of the body\r\nand rhetoric of the soul--if we would proceed, not empirically but\r\nscientifically, in the one case to impart health and strength by giving\r\nmedicine and food, in the other to implant the conviction or virtue\r\nwhich you desire, by the right application of words and training.\r\n\r\nPHAEDRUS: There, Socrates, I suspect that you are right.\r\n\r\nSOCRATES: And do you think that you can know the nature of the soul\r\nintelligently without knowing the nature of the whole?\r\n\r\nPHAEDRUS: Hippocrates the Asclepiad says that the nature even of the\r\nbody can only be understood as a whole. (Compare Charmides.)\r\n\r\nSOCRATES: Yes, friend, and he was right:--still, we ought not to be\r\ncontent with the name of Hippocrates, but to examine and see whether his\r\nargument agrees with his conception of nature.\r\n\r\nPHAEDRUS: I agree.\r\n\r\nSOCRATES: Then consider what truth as well as Hippocrates says about\r\nthis or about any other nature. Ought we not to consider first whether\r\nthat which we wish to learn and to teach is a simple or multiform thing,\r\nand if simple, then to enquire what power it has of acting or being\r\nacted upon in relation to other things, and if multiform, then to number\r\nthe forms; and see first in the case of one of them, and then in the\r\ncase of all of them, what is that power of acting or being acted upon\r\nwhich makes each and all of them to be what they are?\r\n\r\nPHAEDRUS: You may very likely be right, Socrates.\r\n\r\nSOCRATES: The method which proceeds without analysis is like the groping\r\nof a blind man. Yet, surely, he who is an artist ought not to admit of\r\na comparison with the blind, or deaf. The rhetorician, who teaches his\r\npupil to speak scientifically, will particularly set forth the nature of\r\nthat being to which he addresses his speeches; and this, I conceive, to\r\nbe the soul.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: His whole effort is directed to the soul; for in that he seeks\r\nto produce conviction.\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: Then clearly, Thrasymachus or any one else who teaches\r\nrhetoric in earnest will give an exact description of the nature of the\r\nsoul; which will enable us to see whether she be single and same, or,\r\nlike the body, multiform. That is what we should call showing the nature\r\nof the soul.\r\n\r\nPHAEDRUS: Exactly.\r\n\r\nSOCRATES: He will explain, secondly, the mode in which she acts or is\r\nacted upon.\r\n\r\nPHAEDRUS: True.\r\n\r\nSOCRATES: Thirdly, having classified men and speeches, and their kinds\r\nand affections, and adapted them to one another, he will tell the\r\nreasons of his arrangement, and show why one soul is persuaded by a\r\nparticular form of argument, and another not.\r\n\r\nPHAEDRUS: You have hit upon a very good way.\r\n\r\nSOCRATES: Yes, that is the true and only way in which any subject can\r\nbe set forth or treated by rules of art, whether in speaking or writing.\r\nBut the writers of the present day, at whose feet you have sat, craftily\r\nconceal the nature of the soul which they know quite well. Nor, until\r\nthey adopt our method of reading and writing, can we admit that they\r\nwrite by rules of art?\r\n\r\nPHAEDRUS: What is our method?\r\n\r\nSOCRATES: I cannot give you the exact details; but I should like to\r\ntell you generally, as far as is in my power, how a man ought to proceed\r\naccording to rules of art.\r\n\r\nPHAEDRUS: Let me hear.\r\n\r\nSOCRATES: Oratory is the art of enchanting the soul, and therefore he\r\nwho would be an orator has to learn the differences of human souls--they\r\nare so many and of such a nature, and from them come the differences\r\nbetween man and man. Having proceeded thus far in his analysis, he\r\nwill next divide speeches into their different classes:--'Such and such\r\npersons,' he will say, are affected by this or that kind of speech in\r\nthis or that way,' and he will tell you why. The pupil must have a good\r\ntheoretical notion of them first, and then he must have experience of\r\nthem in actual life, and be able to follow them with all his senses\r\nabout him, or he will never get beyond the precepts of his masters. But\r\nwhen he understands what persons are persuaded by what arguments, and\r\nsees the person about whom he was speaking in the abstract actually\r\nbefore him, and knows that it is he, and can say to himself, 'This is\r\nthe man or this is the character who ought to have a certain argument\r\napplied to him in order to convince him of a certain opinion;'--he who\r\nknows all this, and knows also when he should speak and when he should\r\nrefrain, and when he should use pithy sayings, pathetic appeals,\r\nsensational effects, and all the other modes of speech which he has\r\nlearned;--when, I say, he knows the times and seasons of all these\r\nthings, then, and not till then, he is a perfect master of his art; but\r\nif he fail in any of these points, whether in speaking or teaching or\r\nwriting them, and yet declares that he speaks by rules of art, he who\r\nsays 'I don't believe you' has the better of him. Well, the teacher will\r\nsay, is this, Phaedrus and Socrates, your account of the so-called art\r\nof rhetoric, or am I to look for another?\r\n\r\nPHAEDRUS: He must take this, Socrates, for there is no possibility of\r\nanother, and yet the creation of such an art is not easy.\r\n\r\nSOCRATES: Very true; and therefore let us consider this matter in every\r\nlight, and see whether we cannot find a shorter and easier road; there\r\nis no use in taking a long rough roundabout way if there be a shorter\r\nand easier one. And I wish that you would try and remember whether\r\nyou have heard from Lysias or any one else anything which might be of\r\nservice to us.\r\n\r\nPHAEDRUS: If trying would avail, then I might; but at the moment I can\r\nthink of nothing.\r\n\r\nSOCRATES: Suppose I tell you something which somebody who knows told me.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: May not 'the wolf,' as the proverb says, 'claim a hearing'?\r\n\r\nPHAEDRUS: Do you say what can be said for him.\r\n\r\nSOCRATES: He will argue that there is no use in putting a solemn face\r\non these matters, or in going round and round, until you arrive at first\r\nprinciples; for, as I said at first, when the question is of justice and\r\ngood, or is a question in which men are concerned who are just and good,\r\neither by nature or habit, he who would be a skilful rhetorician has\r\nno need of truth--for that in courts of law men literally care\r\nnothing about truth, but only about conviction: and this is based on\r\nprobability, to which he who would be a skilful orator should therefore\r\ngive his whole attention. And they say also that there are cases in\r\nwhich the actual facts, if they are improbable, ought to be withheld,\r\nand only the probabilities should be told either in accusation or\r\ndefence, and that always in speaking, the orator should keep probability\r\nin view, and say good-bye to the truth. And the observance of this\r\nprinciple throughout a speech furnishes the whole art.\r\n\r\nPHAEDRUS: That is what the professors of rhetoric do actually say,\r\nSocrates. I have not forgotten that we have quite briefly touched upon\r\nthis matter already; with them the point is all-important.\r\n\r\nSOCRATES: I dare say that you are familiar with Tisias. Does he not\r\ndefine probability to be that which the many think?\r\n\r\nPHAEDRUS: Certainly, he does.\r\n\r\nSOCRATES: I believe that he has a clever and ingenious case of this\r\nsort:--He supposes a feeble and valiant man to have assaulted a strong\r\nand cowardly one, and to have robbed him of his coat or of something or\r\nother; he is brought into court, and then Tisias says that both parties\r\nshould tell lies: the coward should say that he was assaulted by more\r\nmen than one; the other should prove that they were alone, and should\r\nargue thus: 'How could a weak man like me have assaulted a strong man\r\nlike him?' The complainant will not like to confess his own cowardice,\r\nand will therefore invent some other lie which his adversary will thus\r\ngain an opportunity of refuting. And there are other devices of the same\r\nkind which have a place in the system. Am I not right, Phaedrus?\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: Bless me, what a wonderfully mysterious art is this which\r\nTisias or some other gentleman, in whatever name or country he rejoices,\r\nhas discovered. Shall we say a word to him or not?\r\n\r\nPHAEDRUS: What shall we say to him?\r\n\r\nSOCRATES: Let us tell him that, before he appeared, you and I were\r\nsaying that the probability of which he speaks was engendered in the\r\nminds of the many by the likeness of the truth, and we had just been\r\naffirming that he who knew the truth would always know best how to\r\ndiscover the resemblances of the truth. If he has anything else to say\r\nabout the art of speaking we should like to hear him; but if not, we\r\nare satisfied with our own view, that unless a man estimates the various\r\ncharacters of his hearers and is able to divide all things into classes\r\nand to comprehend them under single ideas, he will never be a skilful\r\nrhetorician even within the limits of human power. And this skill he\r\nwill not attain without a great deal of trouble, which a good man ought\r\nto undergo, not for the sake of speaking and acting before men, but in\r\norder that he may be able to say what is acceptable to God and always\r\nto act acceptably to Him as far as in him lies; for there is a saying of\r\nwiser men than ourselves, that a man of sense should not try to please\r\nhis fellow-servants (at least this should not be his first object)\r\nbut his good and noble masters; and therefore if the way is long and\r\ncircuitous, marvel not at this, for, where the end is great, there we\r\nmay take the longer road, but not for lesser ends such as yours. Truly,\r\nthe argument may say, Tisias, that if you do not mind going so far,\r\nrhetoric has a fair beginning here.\r\n\r\nPHAEDRUS: I think, Socrates, that this is admirable, if only\r\npracticable.\r\n\r\nSOCRATES: But even to fail in an honourable object is honourable.\r\n\r\nPHAEDRUS: True.\r\n\r\nSOCRATES: Enough appears to have been said by us of a true and false art\r\nof speaking.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: But there is something yet to be said of propriety and\r\nimpropriety of writing.\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: Do you know how you can speak or act about rhetoric in a\r\nmanner which will be acceptable to God?\r\n\r\nPHAEDRUS: No, indeed. Do you?\r\n\r\nSOCRATES: I have heard a tradition of the ancients, whether true or not\r\nthey only know; although if we had found the truth ourselves, do you\r\nthink that we should care much about the opinions of men?\r\n\r\nPHAEDRUS: Your question needs no answer; but I wish that you would tell\r\nme what you say that you have heard.\r\n\r\nSOCRATES: At the Egyptian city of Naucratis, there was a famous old god,\r\nwhose name was Theuth; the bird which is called the Ibis is sacred\r\nto him, and he was the inventor of many arts, such as arithmetic and\r\ncalculation and geometry and astronomy and draughts and dice, but his\r\ngreat discovery was the use of letters. Now in those days the god Thamus\r\nwas the king of the whole country of Egypt; and he dwelt in that great\r\ncity of Upper Egypt which the Hellenes call Egyptian Thebes, and the\r\ngod himself is called by them Ammon. To him came Theuth and showed his\r\ninventions, desiring that the other Egyptians might be allowed to have\r\nthe benefit of them; he enumerated them, and Thamus enquired about\r\ntheir several uses, and praised some of them and censured others, as he\r\napproved or disapproved of them. It would take a long time to repeat all\r\nthat Thamus said to Theuth in praise or blame of the various arts. But\r\nwhen they came to letters, This, said Theuth, will make the Egyptians\r\nwiser and give them better memories; it is a specific both for the\r\nmemory and for the wit. Thamus replied: O most ingenious Theuth, the\r\nparent or inventor of an art is not always the best judge of the utility\r\nor inutility of his own inventions to the users of them. And in this\r\ninstance, you who are the father of letters, from a paternal love of\r\nyour own children have been led to attribute to them a quality which\r\nthey cannot have; for this discovery of yours will create forgetfulness\r\nin the learners' souls, because they will not use their memories;\r\nthey will trust to the external written characters and not remember\r\nof themselves. The specific which you have discovered is an aid not to\r\nmemory, but to reminiscence, and you give your disciples not truth, but\r\nonly the semblance of truth; they will be hearers of many things and\r\nwill have learned nothing; they will appear to be omniscient and will\r\ngenerally know nothing; they will be tiresome company, having the show\r\nof wisdom without the reality.\r\n\r\nPHAEDRUS: Yes, Socrates, you can easily invent tales of Egypt, or of any\r\nother country.\r\n\r\nSOCRATES: There was a tradition in the temple of Dodona that oaks first\r\ngave prophetic utterances. The men of old, unlike in their simplicity to\r\nyoung philosophy, deemed that if they heard the truth even from 'oak or\r\nrock,' it was enough for them; whereas you seem to consider not whether\r\na thing is or is not true, but who the speaker is and from what country\r\nthe tale comes.\r\n\r\nPHAEDRUS: I acknowledge the justice of your rebuke; and I think that the\r\nTheban is right in his view about letters.\r\n\r\nSOCRATES: He would be a very simple person, and quite a stranger to the\r\noracles of Thamus or Ammon, who should leave in writing or receive\r\nin writing any art under the idea that the written word would be\r\nintelligible or certain; or who deemed that writing was at all better\r\nthan knowledge and recollection of the same matters?\r\n\r\nPHAEDRUS: That is most true.\r\n\r\nSOCRATES: I cannot help feeling, Phaedrus, that writing is unfortunately\r\nlike painting; for the creations of the painter have the attitude of\r\nlife, and yet if you ask them a question they preserve a solemn silence.\r\nAnd the same may be said of speeches. You would imagine that they had\r\nintelligence, but if you want to know anything and put a question to one\r\nof them, the speaker always gives one unvarying answer. And when they\r\nhave been once written down they are tumbled about anywhere among those\r\nwho may or may not understand them, and know not to whom they should\r\nreply, to whom not: and, if they are maltreated or abused, they have no\r\nparent to protect them; and they cannot protect or defend themselves.\r\n\r\nPHAEDRUS: That again is most true.\r\n\r\nSOCRATES: Is there not another kind of word or speech far better than\r\nthis, and having far greater power--a son of the same family, but\r\nlawfully begotten?\r\n\r\nPHAEDRUS: Whom do you mean, and what is his origin?\r\n\r\nSOCRATES: I mean an intelligent word graven in the soul of the learner,\r\nwhich can defend itself, and knows when to speak and when to be silent.\r\n\r\nPHAEDRUS: You mean the living word of knowledge which has a soul, and of\r\nwhich the written word is properly no more than an image?\r\n\r\nSOCRATES: Yes, of course that is what I mean. And now may I be allowed\r\nto ask you a question: Would a husbandman, who is a man of sense, take\r\nthe seeds, which he values and which he wishes to bear fruit, and in\r\nsober seriousness plant them during the heat of summer, in some garden\r\nof Adonis, that he may rejoice when he sees them in eight days appearing\r\nin beauty? at least he would do so, if at all, only for the sake of\r\namusement and pastime. But when he is in earnest he sows in fitting\r\nsoil, and practises husbandry, and is satisfied if in eight months the\r\nseeds which he has sown arrive at perfection?\r\n\r\nPHAEDRUS: Yes, Socrates, that will be his way when he is in earnest; he\r\nwill do the other, as you say, only in play.\r\n\r\nSOCRATES: And can we suppose that he who knows the just and good and\r\nhonourable has less understanding, than the husbandman, about his own\r\nseeds?\r\n\r\nPHAEDRUS: Certainly not.\r\n\r\nSOCRATES: Then he will not seriously incline to 'write' his thoughts\r\n'in water' with pen and ink, sowing words which can neither speak for\r\nthemselves nor teach the truth adequately to others?\r\n\r\nPHAEDRUS: No, that is not likely.\r\n\r\nSOCRATES: No, that is not likely--in the garden of letters he will sow\r\nand plant, but only for the sake of recreation and amusement; he will\r\nwrite them down as memorials to be treasured against the forgetfulness\r\nof old age, by himself, or by any other old man who is treading the same\r\npath. He will rejoice in beholding their tender growth; and while others\r\nare refreshing their souls with banqueting and the like, this will be\r\nthe pastime in which his days are spent.\r\n\r\nPHAEDRUS: A pastime, Socrates, as noble as the other is ignoble, the\r\npastime of a man who can be amused by serious talk, and can discourse\r\nmerrily about justice and the like.\r\n\r\nSOCRATES: True, Phaedrus. But nobler far is the serious pursuit of the\r\ndialectician, who, finding a congenial soul, by the help of science sows\r\nand plants therein words which are able to help themselves and him who\r\nplanted them, and are not unfruitful, but have in them a seed which\r\nothers brought up in different soils render immortal, making the\r\npossessors of it happy to the utmost extent of human happiness.\r\n\r\nPHAEDRUS: Far nobler, certainly.\r\n\r\nSOCRATES: And now, Phaedrus, having agreed upon the premises we may\r\ndecide about the conclusion.\r\n\r\nPHAEDRUS: About what conclusion?\r\n\r\nSOCRATES: About Lysias, whom we censured, and his art of writing, and\r\nhis discourses, and the rhetorical skill or want of skill which was\r\nshown in them--these are the questions which we sought to determine, and\r\nthey brought us to this point. And I think that we are now pretty well\r\ninformed about the nature of art and its opposite.\r\n\r\nPHAEDRUS: Yes, I think with you; but I wish that you would repeat what\r\nwas said.\r\n\r\nSOCRATES: Until a man knows the truth of the several particulars of\r\nwhich he is writing or speaking, and is able to define them as they are,\r\nand having defined them again to divide them until they can be no longer\r\ndivided, and until in like manner he is able to discern the nature\r\nof the soul, and discover the different modes of discourse which are\r\nadapted to different natures, and to arrange and dispose them in such\r\na way that the simple form of speech may be addressed to the simpler\r\nnature, and the complex and composite to the more complex nature--until\r\nhe has accomplished all this, he will be unable to handle arguments\r\naccording to rules of art, as far as their nature allows them to\r\nbe subjected to art, either for the purpose of teaching or\r\npersuading;--such is the view which is implied in the whole preceding\r\nargument.\r\n\r\nPHAEDRUS: Yes, that was our view, certainly.\r\n\r\nSOCRATES: Secondly, as to the censure which was passed on the speaking\r\nor writing of discourses, and how they might be rightly or wrongly\r\ncensured--did not our previous argument show--?\r\n\r\nPHAEDRUS: Show what?\r\n\r\nSOCRATES: That whether Lysias or any other writer that ever was or will\r\nbe, whether private man or statesman, proposes laws and so becomes\r\nthe author of a political treatise, fancying that there is any great\r\ncertainty and clearness in his performance, the fact of his so writing\r\nis only a disgrace to him, whatever men may say. For not to know the\r\nnature of justice and injustice, and good and evil, and not to be able\r\nto distinguish the dream from the reality, cannot in truth be otherwise\r\nthan disgraceful to him, even though he have the applause of the whole\r\nworld.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: But he who thinks that in the written word there is\r\nnecessarily much which is not serious, and that neither poetry\r\nnor prose, spoken or written, is of any great value, if, like the\r\ncompositions of the rhapsodes, they are only recited in order to be\r\nbelieved, and not with any view to criticism or instruction; and who\r\nthinks that even the best of writings are but a reminiscence of what we\r\nknow, and that only in principles of justice and goodness and nobility\r\ntaught and communicated orally for the sake of instruction and graven\r\nin the soul, which is the true way of writing, is there clearness and\r\nperfection and seriousness, and that such principles are a man's own and\r\nhis legitimate offspring;--being, in the first place, the word which\r\nhe finds in his own bosom; secondly, the brethren and descendants and\r\nrelations of his idea which have been duly implanted by him in the souls\r\nof others;--and who cares for them and no others--this is the right sort\r\nof man; and you and I, Phaedrus, would pray that we may become like him.\r\n\r\nPHAEDRUS: That is most assuredly my desire and prayer.\r\n\r\nSOCRATES: And now the play is played out; and of rhetoric enough. Go and\r\ntell Lysias that to the fountain and school of the Nymphs we went\r\ndown, and were bidden by them to convey a message to him and to other\r\ncomposers of speeches--to Homer and other writers of poems, whether set\r\nto music or not; and to Solon and others who have composed writings in\r\nthe form of political discourses which they would term laws--to all of\r\nthem we are to say that if their compositions are based on knowledge of\r\nthe truth, and they can defend or prove them, when they are put to the\r\ntest, by spoken arguments, which leave their writings poor in\r\ncomparison of them, then they are to be called, not only poets, orators,\r\nlegislators, but are worthy of a higher name, befitting the serious\r\npursuit of their life.\r\n\r\nPHAEDRUS: What name would you assign to them?\r\n\r\nSOCRATES: Wise, I may not call them; for that is a great name which\r\nbelongs to God alone,--lovers of wisdom or philosophers is their modest\r\nand befitting title.\r\n\r\nPHAEDRUS: Very suitable.\r\n\r\nSOCRATES: And he who cannot rise above his own compilations and\r\ncompositions, which he has been long patching and piecing, adding some\r\nand taking away some, may be justly called poet or speech-maker or\r\nlaw-maker.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: Now go and tell this to your companion.\r\n\r\nPHAEDRUS: But there is also a friend of yours who ought not to be\r\nforgotten.\r\n\r\nSOCRATES: Who is he?\r\n\r\nPHAEDRUS: Isocrates the fair:--What message will you send to him, and\r\nhow shall we describe him?\r\n\r\nSOCRATES: Isocrates is still young, Phaedrus; but I am willing to hazard\r\na prophecy concerning him.\r\n\r\nPHAEDRUS: What would you prophesy?\r\n\r\nSOCRATES: I think that he has a genius which soars above the orations of\r\nLysias, and that his character is cast in a finer mould. My impression\r\nof him is that he will marvellously improve as he grows older, and that\r\nall former rhetoricians will be as children in comparison of him. And I\r\nbelieve that he will not be satisfied with rhetoric, but that there is\r\nin him a divine inspiration which will lead him to things higher still.\r\nFor he has an element of philosophy in his nature. This is the message\r\nof the gods dwelling in this place, and which I will myself deliver to\r\nIsocrates, who is my delight; and do you give the other to Lysias, who\r\nis yours.\r\n\r\nPHAEDRUS: I will; and now as the heat is abated let us depart.\r\n\r\nSOCRATES: Should we not offer up a prayer first of all to the local\r\ndeities?\r\n\r\nPHAEDRUS: By all means.\r\n\r\nSOCRATES: Beloved Pan, and all ye other gods who haunt this place, give\r\nme beauty in the inward soul; and may the outward and inward man be\r\nat one. May I reckon the wise to be the wealthy, and may I have such\r\na quantity of gold as a temperate man and he only can bear and\r\ncarry.--Anything more? The prayer, I think, is enough for me.\r\n\r\nPHAEDRUS: Ask the same for me, for friends should have all things in\r\ncommon.\r\n\r\nSOCRATES: Let us go.\r\n\r\n\r\n\r\n\r\n\r\nEnd of the Project Gutenberg EBook of Phaedrus, by Plato\r\n\r\n*** END OF THIS PROJECT GUTENBERG EBOOK PHAEDRUS ***\r\n\r\n***** This file should be named 1636.txt or 1636.zip *****\r\nThis and all associated files of various formats will be found in:\r\n http://www.gutenberg.org/1/6/3/1636/\r\n\r\nProduced by Sue Asscher\r\n\r\nUpdated editions will replace the previous one--the old editions\r\nwill be renamed.\r\n\r\nCreating the works from public domain print editions means that no\r\none owns a United States copyright in these works, so the Foundation\r\n(and you!) can copy and distribute it in the United States without\r\npermission and without paying copyright royalties. Special rules,\r\nset forth in the General Terms of Use part of this license, apply to\r\ncopying and distributing Project Gutenberg-tm electronic works to\r\nprotect the PROJECT GUTENBERG-tm concept and trademark. Project\r\nGutenberg is a registered trademark, and may not be used if you\r\ncharge for the eBooks, unless you receive specific permission. If you\r\ndo not charge anything for copies of this eBook, complying with the\r\nrules is very easy. You may use this eBook for nearly any purpose\r\nsuch as creation of derivative works, reports, performances and\r\nresearch. They may be modified and printed and given away--you may do\r\npractically ANYTHING with public domain eBooks. Redistribution is\r\nsubject to the trademark license, especially commercial\r\nredistribution.\r\n\r\n\r\n\r\n*** START: FULL LICENSE ***\r\n\r\nTHE FULL PROJECT GUTENBERG LICENSE\r\nPLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK\r\n\r\nTo protect the Project Gutenberg-tm mission of promoting the free\r\ndistribution of electronic works, by using or distributing this work\r\n(or any other work associated in any way with the phrase \"Project\r\nGutenberg\"), you agree to comply with all the terms of the Full Project\r\nGutenberg-tm License (available with this file or online at\r\nhttp://gutenberg.org/license).\r\n\r\n\r\nSection 1. General Terms of Use and Redistributing Project Gutenberg-tm\r\nelectronic works\r\n\r\n1.A. By reading or using any part of this Project Gutenberg-tm\r\nelectronic work, you indicate that you have read, understand, agree to\r\nand accept all the terms of this license and intellectual property\r\n(trademark/copyright) agreement. If you do not agree to abide by all\r\nthe terms of this agreement, you must cease using and return or destroy\r\nall copies of Project Gutenberg-tm electronic works in your possession.\r\nIf you paid a fee for obtaining a copy of or access to a Project\r\nGutenberg-tm electronic work and you do not agree to be bound by the\r\nterms of this agreement, you may obtain a refund from the person or\r\nentity to whom you paid the fee as set forth in paragraph 1.E.8.\r\n\r\n1.B. \"Project Gutenberg\" is a registered trademark. It may only be\r\nused on or associated in any way with an electronic work by people who\r\nagree to be bound by the terms of this agreement. There are a few\r\nthings that you can do with most Project Gutenberg-tm electronic works\r\neven without complying with the full terms of this agreement. See\r\nparagraph 1.C below. There are a lot of things you can do with Project\r\nGutenberg-tm electronic works if you follow the terms of this agreement\r\nand help preserve free future access to Project Gutenberg-tm electronic\r\nworks. See paragraph 1.E below.\r\n\r\n1.C. The Project Gutenberg Literary Archive Foundation (\"the Foundation\"\r\nor PGLAF), owns a compilation copyright in the collection of Project\r\nGutenberg-tm electronic works. Nearly all the individual works in the\r\ncollection are in the public domain in the United States. If an\r\nindividual work is in the public domain in the United States and you are\r\nlocated in the United States, we do not claim a right to prevent you from\r\ncopying, distributing, performing, displaying or creating derivative\r\nworks based on the work as long as all references to Project Gutenberg\r\nare removed. Of course, we hope that you will support the Project\r\nGutenberg-tm mission of promoting free access to electronic works by\r\nfreely sharing Project Gutenberg-tm works in compliance with the terms of\r\nthis agreement for keeping the Project Gutenberg-tm name associated with\r\nthe work. You can easily comply with the terms of this agreement by\r\nkeeping this work in the same format with its attached full Project\r\nGutenberg-tm License when you share it without charge with others.\r\n\r\n1.D. The copyright laws of the place where you are located also govern\r\nwhat you can do with this work. Copyright laws in most countries are in\r\na constant state of change. If you are outside the United States, check\r\nthe laws of your country in addition to the terms of this agreement\r\nbefore downloading, copying, displaying, performing, distributing or\r\ncreating derivative works based on this work or any other Project\r\nGutenberg-tm work. The Foundation makes no representations concerning\r\nthe copyright status of any work in any country outside the United\r\nStates.\r\n\r\n1.E. Unless you have removed all references to Project Gutenberg:\r\n\r\n1.E.1. The following sentence, with active links to, or other immediate\r\naccess to, the full Project Gutenberg-tm License must appear prominently\r\nwhenever any copy of a Project Gutenberg-tm work (any work on which the\r\nphrase \"Project Gutenberg\" appears, or with which the phrase \"Project\r\nGutenberg\" is associated) is accessed, displayed, performed, viewed,\r\ncopied or distributed:\r\n\r\nThis eBook is for the use of anyone anywhere at no cost and with\r\nalmost no restrictions whatsoever. You may copy it, give it away or\r\nre-use it under the terms of the Project Gutenberg License included\r\nwith this eBook or online at www.gutenberg.org\r\n\r\n1.E.2. If an individual Project Gutenberg-tm electronic work is derived\r\nfrom the public domain (does not contain a notice indicating that it is\r\nposted with permission of the copyright holder), the work can be copied\r\nand distributed to anyone in the United States without paying any fees\r\nor charges. If you are redistributing or providing access to a work\r\nwith the phrase \"Project Gutenberg\" associated with or appearing on the\r\nwork, you must comply either with the requirements of paragraphs 1.E.1\r\nthrough 1.E.7 or obtain permission for the use of the work and the\r\nProject Gutenberg-tm trademark as set forth in paragraphs 1.E.8 or\r\n1.E.9.\r\n\r\n1.E.3. If an individual Project Gutenberg-tm electronic work is posted\r\nwith the permission of the copyright holder, your use and distribution\r\nmust comply with both paragraphs 1.E.1 through 1.E.7 and any additional\r\nterms imposed by the copyright holder. Additional terms will be linked\r\nto the Project Gutenberg-tm License for all works posted with the\r\npermission of the copyright holder found at the beginning of this work.\r\n\r\n1.E.4. Do not unlink or detach or remove the full Project Gutenberg-tm\r\nLicense terms from this work, or any files containing a part of this\r\nwork or any other work associated with Project Gutenberg-tm.\r\n\r\n1.E.5. Do not copy, display, perform, distribute or redistribute this\r\nelectronic work, or any part of this electronic work, without\r\nprominently displaying the sentence set forth in paragraph 1.E.1 with\r\nactive links or immediate access to the full terms of the Project\r\nGutenberg-tm License.\r\n\r\n1.E.6. You may convert to and distribute this work in any binary,\r\ncompressed, marked up, nonproprietary or proprietary form, including any\r\nword processing or hypertext form. However, if you provide access to or\r\ndistribute copies of a Project Gutenberg-tm work in a format other than\r\n\"Plain Vanilla ASCII\" or other format used in the official version\r\nposted on the official Project Gutenberg-tm web site (www.gutenberg.org),\r\nyou must, at no additional cost, fee or expense to the user, provide a\r\ncopy, a means of exporting a copy, or a means of obtaining a copy upon\r\nrequest, of the work in its original \"Plain Vanilla ASCII\" or other\r\nform. Any alternate format must include the full Project Gutenberg-tm\r\nLicense as specified in paragraph 1.E.1.\r\n\r\n1.E.7. Do not charge a fee for access to, viewing, displaying,\r\nperforming, copying or distributing any Project Gutenberg-tm works\r\nunless you comply with paragraph 1.E.8 or 1.E.9.\r\n\r\n1.E.8. You may charge a reasonable fee for copies of or providing\r\naccess to or distributing Project Gutenberg-tm electronic works provided\r\nthat\r\n\r\n- You pay a royalty fee of 20% of the gross profits you derive from\r\n the use of Project Gutenberg-tm works calculated using the method\r\n you already use to calculate your applicable taxes. The fee is\r\n owed to the owner of the Project Gutenberg-tm trademark, but he\r\n has agreed to donate royalties under this paragraph to the\r\n Project Gutenberg Literary Archive Foundation. Royalty payments\r\n must be paid within 60 days following each date on which you\r\n prepare (or are legally required to prepare) your periodic tax\r\n returns. Royalty payments should be clearly marked as such and\r\n sent to the Project Gutenberg Literary Archive Foundation at the\r\n address specified in Section 4, \"Information about donations to\r\n the Project Gutenberg Literary Archive Foundation.\"\r\n\r\n- You provide a full refund of any money paid by a user who notifies\r\n you in writing (or by e-mail) within 30 days of receipt that s/he\r\n does not agree to the terms of the full Project Gutenberg-tm\r\n License. You must require such a user to return or\r\n destroy all copies of the works possessed in a physical medium\r\n and discontinue all use of and all access to other copies of\r\n Project Gutenberg-tm works.\r\n\r\n- You provide, in accordance with paragraph 1.F.3, a full refund of any\r\n money paid for a work or a replacement copy, if a defect in the\r\n electronic work is discovered and reported to you within 90 days\r\n of receipt of the work.\r\n\r\n- You comply with all other terms of this agreement for free\r\n distribution of Project Gutenberg-tm works.\r\n\r\n1.E.9. If you wish to charge a fee or distribute a Project Gutenberg-tm\r\nelectronic work or group of works on different terms than are set\r\nforth in this agreement, you must obtain permission in writing from\r\nboth the Project Gutenberg Literary Archive Foundation and Michael\r\nHart, the owner of the Project Gutenberg-tm trademark. Contact the\r\nFoundation as set forth in Section 3 below.\r\n\r\n1.F.\r\n\r\n1.F.1. Project Gutenberg volunteers and employees expend considerable\r\neffort to identify, do copyright research on, transcribe and proofread\r\npublic domain works in creating the Project Gutenberg-tm\r\ncollection. Despite these efforts, Project Gutenberg-tm electronic\r\nworks, and the medium on which they may be stored, may contain\r\n\"Defects,\" such as, but not limited to, incomplete, inaccurate or\r\ncorrupt data, transcription errors, a copyright or other intellectual\r\nproperty infringement, a defective or damaged disk or other medium, a\r\ncomputer virus, or computer codes that damage or cannot be read by\r\nyour equipment.\r\n\r\n1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the \"Right\r\nof Replacement or Refund\" described in paragraph 1.F.3, the Project\r\nGutenberg Literary Archive Foundation, the owner of the Project\r\nGutenberg-tm trademark, and any other party distributing a Project\r\nGutenberg-tm electronic work under this agreement, disclaim all\r\nliability to you for damages, costs and expenses, including legal\r\nfees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT\r\nLIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE\r\nPROVIDED IN PARAGRAPH F3. YOU AGREE THAT THE FOUNDATION, THE\r\nTRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE\r\nLIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR\r\nINCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH\r\nDAMAGE.\r\n\r\n1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a\r\ndefect in this electronic work within 90 days of receiving it, you can\r\nreceive a refund of the money (if any) you paid for it by sending a\r\nwritten explanation to the person you received the work from. If you\r\nreceived the work on a physical medium, you must return the medium with\r\nyour written explanation. The person or entity that provided you with\r\nthe defective work may elect to provide a replacement copy in lieu of a\r\nrefund. If you received the work electronically, the person or entity\r\nproviding it to you may choose to give you a second opportunity to\r\nreceive the work electronically in lieu of a refund. If the second copy\r\nis also defective, you may demand a refund in writing without further\r\nopportunities to fix the problem.\r\n\r\n1.F.4. Except for the limited right of replacement or refund set forth\r\nin paragraph 1.F.3, this work is provided to you 'AS-IS' WITH NO OTHER\r\nWARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\r\nWARRANTIES OF MERCHANTIBILITY OR FITNESS FOR ANY PURPOSE.\r\n\r\n1.F.5. Some states do not allow disclaimers of certain implied\r\nwarranties or the exclusion or limitation of certain types of damages.\r\nIf any disclaimer or limitation set forth in this agreement violates the\r\nlaw of the state applicable to this agreement, the agreement shall be\r\ninterpreted to make the maximum disclaimer or limitation permitted by\r\nthe applicable state law. The invalidity or unenforceability of any\r\nprovision of this agreement shall not void the remaining provisions.\r\n\r\n1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the\r\ntrademark owner, any agent or employee of the Foundation, anyone\r\nproviding copies of Project Gutenberg-tm electronic works in accordance\r\nwith this agreement, and any volunteers associated with the production,\r\npromotion and distribution of Project Gutenberg-tm electronic works,\r\nharmless from all liability, costs and expenses, including legal fees,\r\nthat arise directly or indirectly from any of the following which you do\r\nor cause to occur: (a) distribution of this or any Project Gutenberg-tm\r\nwork, (b) alteration, modification, or additions or deletions to any\r\nProject Gutenberg-tm work, and (c) any Defect you cause.\r\n\r\n\r\nSection 2. Information about the Mission of Project Gutenberg-tm\r\n\r\nProject Gutenberg-tm is synonymous with the free distribution of\r\nelectronic works in formats readable by the widest variety of computers\r\nincluding obsolete, old, middle-aged and new computers. It exists\r\nbecause of the efforts of hundreds of volunteers and donations from\r\npeople in all walks of life.\r\n\r\nVolunteers and financial support to provide volunteers with the\r\nassistance they need, is critical to reaching Project Gutenberg-tm's\r\ngoals and ensuring that the Project Gutenberg-tm collection will\r\nremain freely available for generations to come. In 2001, the Project\r\nGutenberg Literary Archive Foundation was created to provide a secure\r\nand permanent future for Project Gutenberg-tm and future generations.\r\nTo learn more about the Project Gutenberg Literary Archive Foundation\r\nand how your efforts and donations can help, see Sections 3 and 4\r\nand the Foundation web page at http://www.pglaf.org.\r\n\r\n\r\nSection 3. Information about the Project Gutenberg Literary Archive\r\nFoundation\r\n\r\nThe Project Gutenberg Literary Archive Foundation is a non profit\r\n501(c)(3) educational corporation organized under the laws of the\r\nstate of Mississippi and granted tax exempt status by the Internal\r\nRevenue Service. The Foundation's EIN or federal tax identification\r\nnumber is 64-6221541. Its 501(c)(3) letter is posted at\r\nhttp://pglaf.org/fundraising. Contributions to the Project Gutenberg\r\nLiterary Archive Foundation are tax deductible to the full extent\r\npermitted by U.S. federal laws and your state's laws.\r\n\r\nThe Foundation's principal office is located at 4557 Melan Dr. S.\r\nFairbanks, AK, 99712., but its volunteers and employees are scattered\r\nthroughout numerous locations. Its business office is located at\r\n809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887, email\r\[email protected]. Email contact links and up to date contact\r\ninformation can be found at the Foundation's web site and official\r\npage at http://pglaf.org\r\n\r\nFor additional contact information:\r\n Dr. Gregory B. Newby\r\n Chief Executive and Director\r\n [email protected]\r\n\r\n\r\nSection 4. Information about Donations to the Project Gutenberg\r\nLiterary Archive Foundation\r\n\r\nProject Gutenberg-tm depends upon and cannot survive without wide\r\nspread public support and donations to carry out its mission of\r\nincreasing the number of public domain and licensed works that can be\r\nfreely distributed in machine readable form accessible by the widest\r\narray of equipment including outdated equipment. Many small donations\r\n($1 to $5,000) are particularly important to maintaining tax exempt\r\nstatus with the IRS.\r\n\r\nThe Foundation is committed to complying with the laws regulating\r\ncharities and charitable donations in all 50 states of the United\r\nStates. Compliance requirements are not uniform and it takes a\r\nconsiderable effort, much paperwork and many fees to meet and keep up\r\nwith these requirements. We do not solicit donations in locations\r\nwhere we have not received written confirmation of compliance. To\r\nSEND DONATIONS or determine the status of compliance for any\r\nparticular state visit http://pglaf.org\r\n\r\nWhile we cannot and do not solicit contributions from states where we\r\nhave not met the solicitation requirements, we know of no prohibition\r\nagainst accepting unsolicited donations from donors in such states who\r\napproach us with offers to donate.\r\n\r\nInternational donations are gratefully accepted, but we cannot make\r\nany statements concerning tax treatment of donations received from\r\noutside the United States. U.S. laws alone swamp our small staff.\r\n\r\nPlease check the Project Gutenberg Web pages for current donation\r\nmethods and addresses. Donations are accepted in a number of other\r\nways including checks, online payments and credit card donations.\r\nTo donate, please visit: http://pglaf.org/donate\r\n\r\n\r\nSection 5. General Information About Project Gutenberg-tm electronic\r\nworks.\r\n\r\nProfessor Michael S. Hart is the originator of the Project Gutenberg-tm\r\nconcept of a library of electronic works that could be freely shared\r\nwith anyone. For thirty years, he produced and distributed Project\r\nGutenberg-tm eBooks with only a loose network of volunteer support.\r\n\r\n\r\nProject Gutenberg-tm eBooks are often created from several printed\r\neditions, all of which are confirmed as Public Domain in the U.S.\r\nunless a copyright notice is included. Thus, we do not necessarily\r\nkeep eBooks in compliance with any particular paper edition.\r\n\r\n\r\nMost people start at our Web site which has the main PG search facility:\r\n\r\n http://www.gutenberg.org\r\n\r\nThis Web site includes information about Project Gutenberg-tm,\r\nincluding how to make donations to the Project Gutenberg Literary\r\nArchive Foundation, how to help produce our new eBooks, and how to\r\nsubscribe to our email newsletter to hear about new eBooks.\r\n\n" ], [ "fullDialogue.find(\"SOCRATES: My dear\")", "_____no_output_____" ], [ "fullDialogue2=fullDialogue[87840:]", "_____no_output_____" ], [ "print(fullDialogue2)", "SOCRATES: My dear Phaedrus, whence come you, and whither are you going?\r\n\r\nPHAEDRUS: I come from Lysias the son of Cephalus, and I am going to\r\ntake a walk outside the wall, for I have been sitting with him the whole\r\nmorning; and our common friend Acumenus tells me that it is much more\r\nrefreshing to walk in the open air than to be shut up in a cloister.\r\n\r\nSOCRATES: There he is right. Lysias then, I suppose, was in the town?\r\n\r\nPHAEDRUS: Yes, he was staying with Epicrates, here at the house of\r\nMorychus; that house which is near the temple of Olympian Zeus.\r\n\r\nSOCRATES: And how did he entertain you? Can I be wrong in supposing that\r\nLysias gave you a feast of discourse?\r\n\r\nPHAEDRUS: You shall hear, if you can spare time to accompany me.\r\n\r\nSOCRATES: And should I not deem the conversation of you and Lysias 'a\r\nthing of higher import,' as I may say in the words of Pindar, 'than any\r\nbusiness'?\r\n\r\nPHAEDRUS: Will you go on?\r\n\r\nSOCRATES: And will you go on with the narration?\r\n\r\nPHAEDRUS: My tale, Socrates, is one of your sort, for love was the theme\r\nwhich occupied us--love after a fashion: Lysias has been writing about\r\na fair youth who was being tempted, but not by a lover; and this was\r\nthe point: he ingeniously proved that the non-lover should be accepted\r\nrather than the lover.\r\n\r\nSOCRATES: O that is noble of him! I wish that he would say the poor man\r\nrather than the rich, and the old man rather than the young one;--then\r\nhe would meet the case of me and of many a man; his words would be quite\r\nrefreshing, and he would be a public benefactor. For my part, I do so\r\nlong to hear his speech, that if you walk all the way to Megara, and\r\nwhen you have reached the wall come back, as Herodicus recommends,\r\nwithout going in, I will keep you company.\r\n\r\nPHAEDRUS: What do you mean, my good Socrates? How can you imagine that\r\nmy unpractised memory can do justice to an elaborate work, which the\r\ngreatest rhetorician of the age spent a long time in composing. Indeed,\r\nI cannot; I would give a great deal if I could.\r\n\r\nSOCRATES: I believe that I know Phaedrus about as well as I know myself,\r\nand I am very sure that the speech of Lysias was repeated to him, not\r\nonce only, but again and again;--he insisted on hearing it many times\r\nover and Lysias was very willing to gratify him; at last, when nothing\r\nelse would do, he got hold of the book, and looked at what he most\r\nwanted to see,--this occupied him during the whole morning;--and then\r\nwhen he was tired with sitting, he went out to take a walk, not until,\r\nby the dog, as I believe, he had simply learned by heart the entire\r\ndiscourse, unless it was unusually long, and he went to a place outside\r\nthe wall that he might practise his lesson. There he saw a certain\r\nlover of discourse who had a similar weakness;--he saw and rejoiced; now\r\nthought he, 'I shall have a partner in my revels.' And he invited him to\r\ncome and walk with him. But when the lover of discourse begged that he\r\nwould repeat the tale, he gave himself airs and said, 'No I cannot,'\r\nas if he were indisposed; although, if the hearer had refused, he would\r\nsooner or later have been compelled by him to listen whether he would or\r\nno. Therefore, Phaedrus, bid him do at once what he will soon do whether\r\nbidden or not.\r\n\r\nPHAEDRUS: I see that you will not let me off until I speak in some\r\nfashion or other; verily therefore my best plan is to speak as I best\r\ncan.\r\n\r\nSOCRATES: A very true remark, that of yours.\r\n\r\nPHAEDRUS: I will do as I say; but believe me, Socrates, I did not learn\r\nthe very words--O no; nevertheless I have a general notion of what\r\nhe said, and will give you a summary of the points in which the lover\r\ndiffered from the non-lover. Let me begin at the beginning.\r\n\r\nSOCRATES: Yes, my sweet one; but you must first of all show what you\r\nhave in your left hand under your cloak, for that roll, as I suspect,\r\nis the actual discourse. Now, much as I love you, I would not have you\r\nsuppose that I am going to have your memory exercised at my expense, if\r\nyou have Lysias himself here.\r\n\r\nPHAEDRUS: Enough; I see that I have no hope of practising my art upon\r\nyou. But if I am to read, where would you please to sit?\r\n\r\nSOCRATES: Let us turn aside and go by the Ilissus; we will sit down at\r\nsome quiet spot.\r\n\r\nPHAEDRUS: I am fortunate in not having my sandals, and as you never have\r\nany, I think that we may go along the brook and cool our feet in the\r\nwater; this will be the easiest way, and at midday and in the summer is\r\nfar from being unpleasant.\r\n\r\nSOCRATES: Lead on, and look out for a place in which we can sit down.\r\n\r\nPHAEDRUS: Do you see the tallest plane-tree in the distance?\r\n\r\nSOCRATES: Yes.\r\n\r\nPHAEDRUS: There are shade and gentle breezes, and grass on which we may\r\neither sit or lie down.\r\n\r\nSOCRATES: Move forward.\r\n\r\nPHAEDRUS: I should like to know, Socrates, whether the place is not\r\nsomewhere here at which Boreas is said to have carried off Orithyia from\r\nthe banks of the Ilissus?\r\n\r\nSOCRATES: Such is the tradition.\r\n\r\nPHAEDRUS: And is this the exact spot? The little stream is delightfully\r\nclear and bright; I can fancy that there might be maidens playing near.\r\n\r\nSOCRATES: I believe that the spot is not exactly here, but about a\r\nquarter of a mile lower down, where you cross to the temple of Artemis,\r\nand there is, I think, some sort of an altar of Boreas at the place.\r\n\r\nPHAEDRUS: I have never noticed it; but I beseech you to tell me,\r\nSocrates, do you believe this tale?\r\n\r\nSOCRATES: The wise are doubtful, and I should not be singular if, like\r\nthem, I too doubted. I might have a rational explanation that Orithyia\r\nwas playing with Pharmacia, when a northern gust carried her over the\r\nneighbouring rocks; and this being the manner of her death, she was said\r\nto have been carried away by Boreas. There is a discrepancy, however,\r\nabout the locality; according to another version of the story she was\r\ntaken from Areopagus, and not from this place. Now I quite acknowledge\r\nthat these allegories are very nice, but he is not to be envied who has\r\nto invent them; much labour and ingenuity will be required of him; and\r\nwhen he has once begun, he must go on and rehabilitate Hippocentaurs and\r\nchimeras dire. Gorgons and winged steeds flow in apace, and numberless\r\nother inconceivable and portentous natures. And if he is sceptical\r\nabout them, and would fain reduce them one after another to the rules of\r\nprobability, this sort of crude philosophy will take up a great deal of\r\ntime. Now I have no leisure for such enquiries; shall I tell you why? I\r\nmust first know myself, as the Delphian inscription says; to be curious\r\nabout that which is not my concern, while I am still in ignorance of my\r\nown self, would be ridiculous. And therefore I bid farewell to all this;\r\nthe common opinion is enough for me. For, as I was saying, I want to\r\nknow not about this, but about myself: am I a monster more complicated\r\nand swollen with passion than the serpent Typho, or a creature of a\r\ngentler and simpler sort, to whom Nature has given a diviner and lowlier\r\ndestiny? But let me ask you, friend: have we not reached the plane-tree\r\nto which you were conducting us?\r\n\r\nPHAEDRUS: Yes, this is the tree.\r\n\r\nSOCRATES: By Here, a fair resting-place, full of summer sounds and\r\nscents. Here is this lofty and spreading plane-tree, and the agnus\r\ncastus high and clustering, in the fullest blossom and the greatest\r\nfragrance; and the stream which flows beneath the plane-tree is\r\ndeliciously cold to the feet. Judging from the ornaments and images,\r\nthis must be a spot sacred to Achelous and the Nymphs. How delightful is\r\nthe breeze:--so very sweet; and there is a sound in the air shrill and\r\nsummerlike which makes answer to the chorus of the cicadae. But the\r\ngreatest charm of all is the grass, like a pillow gently sloping to the\r\nhead. My dear Phaedrus, you have been an admirable guide.\r\n\r\nPHAEDRUS: What an incomprehensible being you are, Socrates: when you are\r\nin the country, as you say, you really are like some stranger who is led\r\nabout by a guide. Do you ever cross the border? I rather think that you\r\nnever venture even outside the gates.\r\n\r\nSOCRATES: Very true, my good friend; and I hope that you will excuse me\r\nwhen you hear the reason, which is, that I am a lover of knowledge, and\r\nthe men who dwell in the city are my teachers, and not the trees or the\r\ncountry. Though I do indeed believe that you have found a spell with\r\nwhich to draw me out of the city into the country, like a hungry cow\r\nbefore whom a bough or a bunch of fruit is waved. For only hold up\r\nbefore me in like manner a book, and you may lead me all round Attica,\r\nand over the wide world. And now having arrived, I intend to lie down,\r\nand do you choose any posture in which you can read best. Begin.\r\n\r\nPHAEDRUS: Listen. You know how matters stand with me; and how, as I\r\nconceive, this affair may be arranged for the advantage of both of us.\r\nAnd I maintain that I ought not to fail in my suit, because I am not\r\nyour lover: for lovers repent of the kindnesses which they have shown\r\nwhen their passion ceases, but to the non-lovers who are free and not\r\nunder any compulsion, no time of repentance ever comes; for they confer\r\ntheir benefits according to the measure of their ability, in the way\r\nwhich is most conducive to their own interest. Then again, lovers\r\nconsider how by reason of their love they have neglected their own\r\nconcerns and rendered service to others: and when to these benefits\r\nconferred they add on the troubles which they have endured, they think\r\nthat they have long ago made to the beloved a very ample return. But the\r\nnon-lover has no such tormenting recollections; he has never neglected\r\nhis affairs or quarrelled with his relations; he has no troubles to\r\nadd up or excuses to invent; and being well rid of all these evils, why\r\nshould he not freely do what will gratify the beloved? If you say that\r\nthe lover is more to be esteemed, because his love is thought to be\r\ngreater; for he is willing to say and do what is hateful to other men,\r\nin order to please his beloved;--that, if true, is only a proof that he\r\nwill prefer any future love to his present, and will injure his old\r\nlove at the pleasure of the new. And how, in a matter of such infinite\r\nimportance, can a man be right in trusting himself to one who is\r\nafflicted with a malady which no experienced person would attempt to\r\ncure, for the patient himself admits that he is not in his right mind,\r\nand acknowledges that he is wrong in his mind, but says that he is\r\nunable to control himself? And if he came to his right mind, would he\r\never imagine that the desires were good which he conceived when in his\r\nwrong mind? Once more, there are many more non-lovers than lovers; and\r\nif you choose the best of the lovers, you will not have many to choose\r\nfrom; but if from the non-lovers, the choice will be larger, and you\r\nwill be far more likely to find among them a person who is worthy of\r\nyour friendship. If public opinion be your dread, and you would avoid\r\nreproach, in all probability the lover, who is always thinking that\r\nother men are as emulous of him as he is of them, will boast to some\r\none of his successes, and make a show of them openly in the pride of his\r\nheart;--he wants others to know that his labour has not been lost; but\r\nthe non-lover is more his own master, and is desirous of solid good, and\r\nnot of the opinion of mankind. Again, the lover may be generally noted\r\nor seen following the beloved (this is his regular occupation), and\r\nwhenever they are observed to exchange two words they are supposed to\r\nmeet about some affair of love either past or in contemplation; but when\r\nnon-lovers meet, no one asks the reason why, because people know that\r\ntalking to another is natural, whether friendship or mere pleasure\r\nbe the motive. Once more, if you fear the fickleness of friendship,\r\nconsider that in any other case a quarrel might be a mutual calamity;\r\nbut now, when you have given up what is most precious to you, you will\r\nbe the greater loser, and therefore, you will have more reason in\r\nbeing afraid of the lover, for his vexations are many, and he is always\r\nfancying that every one is leagued against him. Wherefore also he\r\ndebars his beloved from society; he will not have you intimate with\r\nthe wealthy, lest they should exceed him in wealth, or with men of\r\neducation, lest they should be his superiors in understanding; and he is\r\nequally afraid of anybody's influence who has any other advantage over\r\nhimself. If he can persuade you to break with them, you are left without\r\na friend in the world; or if, out of a regard to your own interest, you\r\nhave more sense than to comply with his desire, you will have to quarrel\r\nwith him. But those who are non-lovers, and whose success in love is the\r\nreward of their merit, will not be jealous of the companions of their\r\nbeloved, and will rather hate those who refuse to be his associates,\r\nthinking that their favourite is slighted by the latter and benefited by\r\nthe former; for more love than hatred may be expected to come to him out\r\nof his friendship with others. Many lovers too have loved the person of\r\na youth before they knew his character or his belongings; so that when\r\ntheir passion has passed away, there is no knowing whether they will\r\ncontinue to be his friends; whereas, in the case of non-lovers who were\r\nalways friends, the friendship is not lessened by the favours granted;\r\nbut the recollection of these remains with them, and is an earnest of\r\ngood things to come.\r\n\r\nFurther, I say that you are likely to be improved by me, whereas the\r\nlover will spoil you. For they praise your words and actions in a wrong\r\nway; partly, because they are afraid of offending you, and also, their\r\njudgment is weakened by passion. Such are the feats which love exhibits;\r\nhe makes things painful to the disappointed which give no pain to\r\nothers; he compels the successful lover to praise what ought not to\r\ngive him pleasure, and therefore the beloved is to be pitied rather\r\nthan envied. But if you listen to me, in the first place, I, in my\r\nintercourse with you, shall not merely regard present enjoyment, but\r\nalso future advantage, being not mastered by love, but my own master;\r\nnor for small causes taking violent dislikes, but even when the cause\r\nis great, slowly laying up little wrath--unintentional offences I shall\r\nforgive, and intentional ones I shall try to prevent; and these are the\r\nmarks of a friendship which will last.\r\n\r\nDo you think that a lover only can be a firm friend? reflect:--if this\r\nwere true, we should set small value on sons, or fathers, or mothers;\r\nnor should we ever have loyal friends, for our love of them arises\r\nnot from passion, but from other associations. Further, if we ought\r\nto shower favours on those who are the most eager suitors,--on that\r\nprinciple, we ought always to do good, not to the most virtuous, but to\r\nthe most needy; for they are the persons who will be most relieved,\r\nand will therefore be the most grateful; and when you make a feast you\r\nshould invite not your friend, but the beggar and the empty soul; for\r\nthey will love you, and attend you, and come about your doors, and\r\nwill be the best pleased, and the most grateful, and will invoke many a\r\nblessing on your head. Yet surely you ought not to be granting favours\r\nto those who besiege you with prayer, but to those who are best able to\r\nreward you; nor to the lover only, but to those who are worthy of love;\r\nnor to those who will enjoy the bloom of your youth, but to those who\r\nwill share their possessions with you in age; nor to those who, having\r\nsucceeded, will glory in their success to others, but to those who\r\nwill be modest and tell no tales; nor to those who care about you for a\r\nmoment only, but to those who will continue your friends through life;\r\nnor to those who, when their passion is over, will pick a quarrel with\r\nyou, but rather to those who, when the charm of youth has left you, will\r\nshow their own virtue. Remember what I have said; and consider yet this\r\nfurther point: friends admonish the lover under the idea that his way of\r\nlife is bad, but no one of his kindred ever yet censured the non-lover,\r\nor thought that he was ill-advised about his own interests.\r\n\r\n'Perhaps you will ask me whether I propose that you should indulge every\r\nnon-lover. To which I reply that not even the lover would advise you to\r\nindulge all lovers, for the indiscriminate favour is less esteemed by\r\nthe rational recipient, and less easily hidden by him who would escape\r\nthe censure of the world. Now love ought to be for the advantage of both\r\nparties, and for the injury of neither.\r\n\r\n'I believe that I have said enough; but if there is anything more which\r\nyou desire or which in your opinion needs to be supplied, ask and I will\r\nanswer.'\r\n\r\nNow, Socrates, what do you think? Is not the discourse excellent, more\r\nespecially in the matter of the language?\r\n\r\nSOCRATES: Yes, quite admirable; the effect on me was ravishing. And this\r\nI owe to you, Phaedrus, for I observed you while reading to be in an\r\necstasy, and thinking that you are more experienced in these matters\r\nthan I am, I followed your example, and, like you, my divine darling, I\r\nbecame inspired with a phrenzy.\r\n\r\nPHAEDRUS: Indeed, you are pleased to be merry.\r\n\r\nSOCRATES: Do you mean that I am not in earnest?\r\n\r\nPHAEDRUS: Now don't talk in that way, Socrates, but let me have your\r\nreal opinion; I adjure you, by Zeus, the god of friendship, to tell me\r\nwhether you think that any Hellene could have said more or spoken better\r\non the same subject.\r\n\r\nSOCRATES: Well, but are you and I expected to praise the sentiments\r\nof the author, or only the clearness, and roundness, and finish, and\r\ntournure of the language? As to the first I willingly submit to your\r\nbetter judgment, for I am not worthy to form an opinion, having only\r\nattended to the rhetorical manner; and I was doubting whether this could\r\nhave been defended even by Lysias himself; I thought, though I speak\r\nunder correction, that he repeated himself two or three times, either\r\nfrom want of words or from want of pains; and also, he appeared to me\r\nostentatiously to exult in showing how well he could say the same thing\r\nin two or three ways.\r\n\r\nPHAEDRUS: Nonsense, Socrates; what you call repetition was the especial\r\nmerit of the speech; for he omitted no topic of which the subject\r\nrightly allowed, and I do not think that any one could have spoken\r\nbetter or more exhaustively.\r\n\r\nSOCRATES: There I cannot go along with you. Ancient sages, men and\r\nwomen, who have spoken and written of these things, would rise up in\r\njudgment against me, if out of complaisance I assented to you.\r\n\r\nPHAEDRUS: Who are they, and where did you hear anything better than\r\nthis?\r\n\r\nSOCRATES: I am sure that I must have heard; but at this moment I do not\r\nremember from whom; perhaps from Sappho the fair, or Anacreon the wise;\r\nor, possibly, from a prose writer. Why do I say so? Why, because I\r\nperceive that my bosom is full, and that I could make another speech as\r\ngood as that of Lysias, and different. Now I am certain that this is\r\nnot an invention of my own, who am well aware that I know nothing, and\r\ntherefore I can only infer that I have been filled through the ears,\r\nlike a pitcher, from the waters of another, though I have actually\r\nforgotten in my stupidity who was my informant.\r\n\r\nPHAEDRUS: That is grand:--but never mind where you heard the discourse\r\nor from whom; let that be a mystery not to be divulged even at my\r\nearnest desire. Only, as you say, promise to make another and better\r\noration, equal in length and entirely new, on the same subject; and I,\r\nlike the nine Archons, will promise to set up a golden image at Delphi,\r\nnot only of myself, but of you, and as large as life.\r\n\r\nSOCRATES: You are a dear golden ass if you suppose me to mean that\r\nLysias has altogether missed the mark, and that I can make a speech from\r\nwhich all his arguments are to be excluded. The worst of authors will\r\nsay something which is to the point. Who, for example, could speak on\r\nthis thesis of yours without praising the discretion of the non-lover\r\nand blaming the indiscretion of the lover? These are the commonplaces of\r\nthe subject which must come in (for what else is there to be said?) and\r\nmust be allowed and excused; the only merit is in the arrangement of\r\nthem, for there can be none in the invention; but when you leave the\r\ncommonplaces, then there may be some originality.\r\n\r\nPHAEDRUS: I admit that there is reason in what you say, and I too will\r\nbe reasonable, and will allow you to start with the premiss that the\r\nlover is more disordered in his wits than the non-lover; if in what\r\nremains you make a longer and better speech than Lysias, and use other\r\narguments, then I say again, that a statue you shall have of beaten\r\ngold, and take your place by the colossal offerings of the Cypselids at\r\nOlympia.\r\n\r\nSOCRATES: How profoundly in earnest is the lover, because to tease him I\r\nlay a finger upon his love! And so, Phaedrus, you really imagine that I\r\nam going to improve upon the ingenuity of Lysias?\r\n\r\nPHAEDRUS: There I have you as you had me, and you must just speak 'as\r\nyou best can.' Do not let us exchange 'tu quoque' as in a farce, or\r\ncompel me to say to you as you said to me, 'I know Socrates as well as\r\nI know myself, and he was wanting to speak, but he gave himself airs.'\r\nRather I would have you consider that from this place we stir not until\r\nyou have unbosomed yourself of the speech; for here are we all alone,\r\nand I am stronger, remember, and younger than you:--Wherefore perpend,\r\nand do not compel me to use violence.\r\n\r\nSOCRATES: But, my sweet Phaedrus, how ridiculous it would be of me to\r\ncompete with Lysias in an extempore speech! He is a master in his art\r\nand I am an untaught man.\r\n\r\nPHAEDRUS: You see how matters stand; and therefore let there be no more\r\npretences; for, indeed, I know the word that is irresistible.\r\n\r\nSOCRATES: Then don't say it.\r\n\r\nPHAEDRUS: Yes, but I will; and my word shall be an oath. 'I say, or\r\nrather swear'--but what god will be witness of my oath?--'By this\r\nplane-tree I swear, that unless you repeat the discourse here in the\r\nface of this very plane-tree, I will never tell you another; never let\r\nyou have word of another!'\r\n\r\nSOCRATES: Villain! I am conquered; the poor lover of discourse has no\r\nmore to say.\r\n\r\nPHAEDRUS: Then why are you still at your tricks?\r\n\r\nSOCRATES: I am not going to play tricks now that you have taken the\r\noath, for I cannot allow myself to be starved.\r\n\r\nPHAEDRUS: Proceed.\r\n\r\nSOCRATES: Shall I tell you what I will do?\r\n\r\nPHAEDRUS: What?\r\n\r\nSOCRATES: I will veil my face and gallop through the discourse as fast\r\nas I can, for if I see you I shall feel ashamed and not know what to\r\nsay.\r\n\r\nPHAEDRUS: Only go on and you may do anything else which you please.\r\n\r\nSOCRATES: Come, O ye Muses, melodious, as ye are called, whether you\r\nhave received this name from the character of your strains, or because\r\nthe Melians are a musical race, help, O help me in the tale which my\r\ngood friend here desires me to rehearse, in order that his friend whom\r\nhe always deemed wise may seem to him to be wiser than ever.\r\n\r\nOnce upon a time there was a fair boy, or, more properly speaking, a\r\nyouth; he was very fair and had a great many lovers; and there was one\r\nspecial cunning one, who had persuaded the youth that he did not love\r\nhim, but he really loved him all the same; and one day when he was\r\npaying his addresses to him, he used this very argument--that he\r\nought to accept the non-lover rather than the lover; his words were as\r\nfollows:--\r\n\r\n'All good counsel begins in the same way; a man should know what he\r\nis advising about, or his counsel will all come to nought. But people\r\nimagine that they know about the nature of things, when they don't know\r\nabout them, and, not having come to an understanding at first\r\nbecause they think that they know, they end, as might be expected, in\r\ncontradicting one another and themselves. Now you and I must not be\r\nguilty of this fundamental error which we condemn in others; but as our\r\nquestion is whether the lover or non-lover is to be preferred, let us\r\nfirst of all agree in defining the nature and power of love, and then,\r\nkeeping our eyes upon the definition and to this appealing, let us\r\nfurther enquire whether love brings advantage or disadvantage.\r\n\r\n'Every one sees that love is a desire, and we know also that non-lovers\r\ndesire the beautiful and good. Now in what way is the lover to be\r\ndistinguished from the non-lover? Let us note that in every one of us\r\nthere are two guiding and ruling principles which lead us whither they\r\nwill; one is the natural desire of pleasure, the other is an acquired\r\nopinion which aspires after the best; and these two are sometimes in\r\nharmony and then again at war, and sometimes the one, sometimes the\r\nother conquers. When opinion by the help of reason leads us to the best,\r\nthe conquering principle is called temperance; but when desire, which\r\nis devoid of reason, rules in us and drags us to pleasure, that power of\r\nmisrule is called excess. Now excess has many names, and many members,\r\nand many forms, and any of these forms when very marked gives a name,\r\nneither honourable nor creditable, to the bearer of the name. The desire\r\nof eating, for example, which gets the better of the higher reason and\r\nthe other desires, is called gluttony, and he who is possessed by it\r\nis called a glutton; the tyrannical desire of drink, which inclines the\r\npossessor of the desire to drink, has a name which is only too obvious,\r\nand there can be as little doubt by what name any other appetite of the\r\nsame family would be called;--it will be the name of that which happens\r\nto be dominant. And now I think that you will perceive the drift of\r\nmy discourse; but as every spoken word is in a manner plainer than the\r\nunspoken, I had better say further that the irrational desire which\r\novercomes the tendency of opinion towards right, and is led away to the\r\nenjoyment of beauty, and especially of personal beauty, by the desires\r\nwhich are her own kindred--that supreme desire, I say, which by leading\r\nconquers and by the force of passion is reinforced, from this very\r\nforce, receiving a name, is called love (erromenos eros).'\r\n\r\nAnd now, dear Phaedrus, I shall pause for an instant to ask whether you\r\ndo not think me, as I appear to myself, inspired?\r\n\r\nPHAEDRUS: Yes, Socrates, you seem to have a very unusual flow of words.\r\n\r\nSOCRATES: Listen to me, then, in silence; for surely the place is holy;\r\nso that you must not wonder, if, as I proceed, I appear to be in a\r\ndivine fury, for already I am getting into dithyrambics.\r\n\r\nPHAEDRUS: Nothing can be truer.\r\n\r\nSOCRATES: The responsibility rests with you. But hear what follows, and\r\nperhaps the fit may be averted; all is in their hands above. I will go\r\non talking to my youth. Listen:--\r\n\r\nThus, my friend, we have declared and defined the nature of the subject.\r\nKeeping the definition in view, let us now enquire what advantage or\r\ndisadvantage is likely to ensue from the lover or the non-lover to him\r\nwho accepts their advances.\r\n\r\nHe who is the victim of his passions and the slave of pleasure will of\r\ncourse desire to make his beloved as agreeable to himself as possible.\r\nNow to him who has a mind diseased anything is agreeable which is not\r\nopposed to him, but that which is equal or superior is hateful to him,\r\nand therefore the lover will not brook any superiority or equality\r\non the part of his beloved; he is always employed in reducing him to\r\ninferiority. And the ignorant is the inferior of the wise, the coward\r\nof the brave, the slow of speech of the speaker, the dull of the\r\nclever. These, and not these only, are the mental defects of the\r\nbeloved;--defects which, when implanted by nature, are necessarily\r\na delight to the lover, and when not implanted, he must contrive to\r\nimplant them in him, if he would not be deprived of his fleeting joy.\r\nAnd therefore he cannot help being jealous, and will debar his beloved\r\nfrom the advantages of society which would make a man of him, and\r\nespecially from that society which would have given him wisdom, and\r\nthereby he cannot fail to do him great harm. That is to say, in his\r\nexcessive fear lest he should come to be despised in his eyes he will be\r\ncompelled to banish from him divine philosophy; and there is no greater\r\ninjury which he can inflict upon him than this. He will contrive that\r\nhis beloved shall be wholly ignorant, and in everything shall look\r\nto him; he is to be the delight of the lover's heart, and a curse to\r\nhimself. Verily, a lover is a profitable guardian and associate for him\r\nin all that relates to his mind.\r\n\r\nLet us next see how his master, whose law of life is pleasure and not\r\ngood, will keep and train the body of his servant. Will he not choose a\r\nbeloved who is delicate rather than sturdy and strong? One brought up\r\nin shady bowers and not in the bright sun, a stranger to manly exercises\r\nand the sweat of toil, accustomed only to a soft and luxurious diet,\r\ninstead of the hues of health having the colours of paint and ornament,\r\nand the rest of a piece?--such a life as any one can imagine and which I\r\nneed not detail at length. But I may sum up all that I have to say in a\r\nword, and pass on. Such a person in war, or in any of the great crises\r\nof life, will be the anxiety of his friends and also of his lover, and\r\ncertainly not the terror of his enemies; which nobody can deny.\r\n\r\nAnd now let us tell what advantage or disadvantage the beloved will\r\nreceive from the guardianship and society of his lover in the matter of\r\nhis property; this is the next point to be considered. The lover will be\r\nthe first to see what, indeed, will be sufficiently evident to all men,\r\nthat he desires above all things to deprive his beloved of his dearest\r\nand best and holiest possessions, father, mother, kindred, friends, of\r\nall whom he thinks may be hinderers or reprovers of their most sweet\r\nconverse; he will even cast a jealous eye upon his gold and silver or\r\nother property, because these make him a less easy prey, and when caught\r\nless manageable; hence he is of necessity displeased at his possession\r\nof them and rejoices at their loss; and he would like him to be\r\nwifeless, childless, homeless, as well; and the longer the better, for\r\nthe longer he is all this, the longer he will enjoy him.\r\n\r\nThere are some sort of animals, such as flatterers, who are dangerous\r\nand mischievous enough, and yet nature has mingled a temporary pleasure\r\nand grace in their composition. You may say that a courtesan is hurtful,\r\nand disapprove of such creatures and their practices, and yet for the\r\ntime they are very pleasant. But the lover is not only hurtful to his\r\nlove; he is also an extremely disagreeable companion. The old proverb\r\nsays that 'birds of a feather flock together'; I suppose that equality\r\nof years inclines them to the same pleasures, and similarity begets\r\nfriendship; yet you may have more than enough even of this; and verily\r\nconstraint is always said to be grievous. Now the lover is not only\r\nunlike his beloved, but he forces himself upon him. For he is old and\r\nhis love is young, and neither day nor night will he leave him if he\r\ncan help; necessity and the sting of desire drive him on, and allure\r\nhim with the pleasure which he receives from seeing, hearing, touching,\r\nperceiving him in every way. And therefore he is delighted to fasten\r\nupon him and to minister to him. But what pleasure or consolation can\r\nthe beloved be receiving all this time? Must he not feel the extremity\r\nof disgust when he looks at an old shrivelled face and the remainder to\r\nmatch, which even in a description is disagreeable, and quite detestable\r\nwhen he is forced into daily contact with his lover; moreover he is\r\njealously watched and guarded against everything and everybody, and\r\nhas to hear misplaced and exaggerated praises of himself, and censures\r\nequally inappropriate, which are intolerable when the man is sober, and,\r\nbesides being intolerable, are published all over the world in all their\r\nindelicacy and wearisomeness when he is drunk.\r\n\r\nAnd not only while his love continues is he mischievous and unpleasant,\r\nbut when his love ceases he becomes a perfidious enemy of him on whom\r\nhe showered his oaths and prayers and promises, and yet could hardly\r\nprevail upon him to tolerate the tedium of his company even from motives\r\nof interest. The hour of payment arrives, and now he is the servant of\r\nanother master; instead of love and infatuation, wisdom and temperance\r\nare his bosom's lords; but the beloved has not discovered the change\r\nwhich has taken place in him, when he asks for a return and recalls to\r\nhis recollection former sayings and doings; he believes himself to be\r\nspeaking to the same person, and the other, not having the courage to\r\nconfess the truth, and not knowing how to fulfil the oaths and promises\r\nwhich he made when under the dominion of folly, and having now grown\r\nwise and temperate, does not want to do as he did or to be as he was\r\nbefore. And so he runs away and is constrained to be a defaulter; the\r\noyster-shell (In allusion to a game in which two parties fled or pursued\r\naccording as an oyster-shell which was thrown into the air fell with\r\nthe dark or light side uppermost.) has fallen with the other side\r\nuppermost--he changes pursuit into flight, while the other is compelled\r\nto follow him with passion and imprecation, not knowing that he ought\r\nnever from the first to have accepted a demented lover instead of a\r\nsensible non-lover; and that in making such a choice he was giving\r\nhimself up to a faithless, morose, envious, disagreeable being, hurtful\r\nto his estate, hurtful to his bodily health, and still more hurtful to\r\nthe cultivation of his mind, than which there neither is nor ever will\r\nbe anything more honoured in the eyes both of gods and men. Consider\r\nthis, fair youth, and know that in the friendship of the lover there is\r\nno real kindness; he has an appetite and wants to feed upon you:\r\n\r\n'As wolves love lambs so lovers love their loves.'\r\n\r\nBut I told you so, I am speaking in verse, and therefore I had better\r\nmake an end; enough.\r\n\r\nPHAEDRUS: I thought that you were only half-way and were going to make a\r\nsimilar speech about all the advantages of accepting the non-lover. Why\r\ndo you not proceed?\r\n\r\nSOCRATES: Does not your simplicity observe that I have got out of\r\ndithyrambics into heroics, when only uttering a censure on the lover?\r\nAnd if I am to add the praises of the non-lover what will become of me?\r\nDo you not perceive that I am already overtaken by the Nymphs to whom\r\nyou have mischievously exposed me? And therefore I will only add that\r\nthe non-lover has all the advantages in which the lover is accused of\r\nbeing deficient. And now I will say no more; there has been enough of\r\nboth of them. Leaving the tale to its fate, I will cross the river and\r\nmake the best of my way home, lest a worse thing be inflicted upon me by\r\nyou.\r\n\r\nPHAEDRUS: Not yet, Socrates; not until the heat of the day has passed;\r\ndo you not see that the hour is almost noon? there is the midday sun\r\nstanding still, as people say, in the meridian. Let us rather stay and\r\ntalk over what has been said, and then return in the cool.\r\n\r\nSOCRATES: Your love of discourse, Phaedrus, is superhuman, simply\r\nmarvellous, and I do not believe that there is any one of your\r\ncontemporaries who has either made or in one way or another has\r\ncompelled others to make an equal number of speeches. I would except\r\nSimmias the Theban, but all the rest are far behind you. And now I do\r\nverily believe that you have been the cause of another.\r\n\r\nPHAEDRUS: That is good news. But what do you mean?\r\n\r\nSOCRATES: I mean to say that as I was about to cross the stream the\r\nusual sign was given to me,--that sign which always forbids, but never\r\nbids, me to do anything which I am going to do; and I thought that I\r\nheard a voice saying in my ear that I had been guilty of impiety,\r\nand that I must not go away until I had made an atonement. Now I am a\r\ndiviner, though not a very good one, but I have enough religion for my\r\nown use, as you might say of a bad writer--his writing is good enough\r\nfor him; and I am beginning to see that I was in error. O my friend, how\r\nprophetic is the human soul! At the time I had a sort of misgiving, and,\r\nlike Ibycus, 'I was troubled; I feared that I might be buying honour\r\nfrom men at the price of sinning against the gods.' Now I recognize my\r\nerror.\r\n\r\nPHAEDRUS: What error?\r\n\r\nSOCRATES: That was a dreadful speech which you brought with you, and you\r\nmade me utter one as bad.\r\n\r\nPHAEDRUS: How so?\r\n\r\nSOCRATES: It was foolish, I say,--to a certain extent, impious; can\r\nanything be more dreadful?\r\n\r\nPHAEDRUS: Nothing, if the speech was really such as you describe.\r\n\r\nSOCRATES: Well, and is not Eros the son of Aphrodite, and a god?\r\n\r\nPHAEDRUS: So men say.\r\n\r\nSOCRATES: But that was not acknowledged by Lysias in his speech, nor by\r\nyou in that other speech which you by a charm drew from my lips. For if\r\nlove be, as he surely is, a divinity, he cannot be evil. Yet this was\r\nthe error of both the speeches. There was also a simplicity about them\r\nwhich was refreshing; having no truth or honesty in them, nevertheless\r\nthey pretended to be something, hoping to succeed in deceiving the\r\nmanikins of earth and gain celebrity among them. Wherefore I must have\r\na purgation. And I bethink me of an ancient purgation of mythological\r\nerror which was devised, not by Homer, for he never had the wit to\r\ndiscover why he was blind, but by Stesichorus, who was a philosopher and\r\nknew the reason why; and therefore, when he lost his eyes, for that was\r\nthe penalty which was inflicted upon him for reviling the lovely Helen,\r\nhe at once purged himself. And the purgation was a recantation, which\r\nbegan thus,--\r\n\r\n 'False is that word of mine--the truth is that thou didst not embark in\r\n ships, nor ever go to the walls of Troy;'\r\n\r\nand when he had completed his poem, which is called 'the recantation,'\r\nimmediately his sight returned to him. Now I will be wiser than either\r\nStesichorus or Homer, in that I am going to make my recantation for\r\nreviling love before I suffer; and this I will attempt, not as before,\r\nveiled and ashamed, but with forehead bold and bare.\r\n\r\nPHAEDRUS: Nothing could be more agreeable to me than to hear you say so.\r\n\r\nSOCRATES: Only think, my good Phaedrus, what an utter want of delicacy\r\nwas shown in the two discourses; I mean, in my own and in that which you\r\nrecited out of the book. Would not any one who was himself of a noble\r\nand gentle nature, and who loved or ever had loved a nature like his\r\nown, when we tell of the petty causes of lovers' jealousies, and of\r\ntheir exceeding animosities, and of the injuries which they do to their\r\nbeloved, have imagined that our ideas of love were taken from some haunt\r\nof sailors to which good manners were unknown--he would certainly never\r\nhave admitted the justice of our censure?\r\n\r\nPHAEDRUS: I dare say not, Socrates.\r\n\r\nSOCRATES: Therefore, because I blush at the thought of this person, and\r\nalso because I am afraid of Love himself, I desire to wash the brine out\r\nof my ears with water from the spring; and I would counsel Lysias not to\r\ndelay, but to write another discourse, which shall prove that 'ceteris\r\nparibus' the lover ought to be accepted rather than the non-lover.\r\n\r\nPHAEDRUS: Be assured that he shall. You shall speak the praises of the\r\nlover, and Lysias shall be compelled by me to write another discourse on\r\nthe same theme.\r\n\r\nSOCRATES: You will be true to your nature in that, and therefore I\r\nbelieve you.\r\n\r\nPHAEDRUS: Speak, and fear not.\r\n\r\nSOCRATES: But where is the fair youth whom I was addressing before, and\r\nwho ought to listen now; lest, if he hear me not, he should accept a\r\nnon-lover before he knows what he is doing?\r\n\r\nPHAEDRUS: He is close at hand, and always at your service.\r\n\r\nSOCRATES: Know then, fair youth, that the former discourse was the word\r\nof Phaedrus, the son of Vain Man, who dwells in the city of Myrrhina\r\n(Myrrhinusius). And this which I am about to utter is the recantation of\r\nStesichorus the son of Godly Man (Euphemus), who comes from the town of\r\nDesire (Himera), and is to the following effect: 'I told a lie when I\r\nsaid' that the beloved ought to accept the non-lover when he might have\r\nthe lover, because the one is sane, and the other mad. It might be so\r\nif madness were simply an evil; but there is also a madness which is a\r\ndivine gift, and the source of the chiefest blessings granted to\r\nmen. For prophecy is a madness, and the prophetess at Delphi and the\r\npriestesses at Dodona when out of their senses have conferred great\r\nbenefits on Hellas, both in public and private life, but when in their\r\nsenses few or none. And I might also tell you how the Sibyl and other\r\ninspired persons have given to many an one many an intimation of the\r\nfuture which has saved them from falling. But it would be tedious to\r\nspeak of what every one knows.\r\n\r\nThere will be more reason in appealing to the ancient inventors of names\r\n(compare Cratylus), who would never have connected prophecy (mantike)\r\nwhich foretells the future and is the noblest of arts, with madness\r\n(manike), or called them both by the same name, if they had deemed\r\nmadness to be a disgrace or dishonour;--they must have thought that\r\nthere was an inspired madness which was a noble thing; for the two\r\nwords, mantike and manike, are really the same, and the letter tau is\r\nonly a modern and tasteless insertion. And this is confirmed by the\r\nname which was given by them to the rational investigation of futurity,\r\nwhether made by the help of birds or of other signs--this, for as much\r\nas it is an art which supplies from the reasoning faculty mind (nous)\r\nand information (istoria) to human thought (oiesis) they originally\r\ntermed oionoistike, but the word has been lately altered and made\r\nsonorous by the modern introduction of the letter Omega (oionoistike and\r\noionistike), and in proportion as prophecy (mantike) is more perfect and\r\naugust than augury, both in name and fact, in the same proportion, as\r\nthe ancients testify, is madness superior to a sane mind (sophrosune)\r\nfor the one is only of human, but the other of divine origin. Again,\r\nwhere plagues and mightiest woes have bred in certain families, owing\r\nto some ancient blood-guiltiness, there madness has entered with holy\r\nprayers and rites, and by inspired utterances found a way of deliverance\r\nfor those who are in need; and he who has part in this gift, and is\r\ntruly possessed and duly out of his mind, is by the use of purifications\r\nand mysteries made whole and exempt from evil, future as well as\r\npresent, and has a release from the calamity which was afflicting him.\r\nThe third kind is the madness of those who are possessed by the Muses;\r\nwhich taking hold of a delicate and virgin soul, and there inspiring\r\nfrenzy, awakens lyrical and all other numbers; with these adorning the\r\nmyriad actions of ancient heroes for the instruction of posterity. But\r\nhe who, having no touch of the Muses' madness in his soul, comes to the\r\ndoor and thinks that he will get into the temple by the help of art--he,\r\nI say, and his poetry are not admitted; the sane man disappears and is\r\nnowhere when he enters into rivalry with the madman.\r\n\r\nI might tell of many other noble deeds which have sprung from inspired\r\nmadness. And therefore, let no one frighten or flutter us by saying that\r\nthe temperate friend is to be chosen rather than the inspired, but let\r\nhim further show that love is not sent by the gods for any good to lover\r\nor beloved; if he can do so we will allow him to carry off the palm. And\r\nwe, on our part, will prove in answer to him that the madness of love is\r\nthe greatest of heaven's blessings, and the proof shall be one which the\r\nwise will receive, and the witling disbelieve. But first of all, let us\r\nview the affections and actions of the soul divine and human, and try\r\nto ascertain the truth about them. The beginning of our proof is as\r\nfollows:--\r\n\r\n(Translated by Cic. Tus. Quaest.) The soul through all her being is\r\nimmortal, for that which is ever in motion is immortal; but that which\r\nmoves another and is moved by another, in ceasing to move ceases also to\r\nlive. Only the self-moving, never leaving self, never ceases to move,\r\nand is the fountain and beginning of motion to all that moves besides.\r\nNow, the beginning is unbegotten, for that which is begotten has a\r\nbeginning; but the beginning is begotten of nothing, for if it were\r\nbegotten of something, then the begotten would not come from a\r\nbeginning. But if unbegotten, it must also be indestructible; for if\r\nbeginning were destroyed, there could be no beginning out of anything,\r\nnor anything out of a beginning; and all things must have a beginning.\r\nAnd therefore the self-moving is the beginning of motion; and this can\r\nneither be destroyed nor begotten, else the whole heavens and all\r\ncreation would collapse and stand still, and never again have motion or\r\nbirth. But if the self-moving is proved to be immortal, he who affirms\r\nthat self-motion is the very idea and essence of the soul will not be\r\nput to confusion. For the body which is moved from without is soulless;\r\nbut that which is moved from within has a soul, for such is the nature\r\nof the soul. But if this be true, must not the soul be the self-moving,\r\nand therefore of necessity unbegotten and immortal? Enough of the soul's\r\nimmortality.\r\n\r\nOf the nature of the soul, though her true form be ever a theme of large\r\nand more than mortal discourse, let me speak briefly, and in a\r\nfigure. And let the figure be composite--a pair of winged horses and a\r\ncharioteer. Now the winged horses and the charioteers of the gods are\r\nall of them noble and of noble descent, but those of other races are\r\nmixed; the human charioteer drives his in a pair; and one of them is\r\nnoble and of noble breed, and the other is ignoble and of ignoble breed;\r\nand the driving of them of necessity gives a great deal of trouble to\r\nhim. I will endeavour to explain to you in what way the mortal differs\r\nfrom the immortal creature. The soul in her totality has the care of\r\ninanimate being everywhere, and traverses the whole heaven in divers\r\nforms appearing--when perfect and fully winged she soars upward, and\r\norders the whole world; whereas the imperfect soul, losing her wings\r\nand drooping in her flight at last settles on the solid ground--there,\r\nfinding a home, she receives an earthly frame which appears to be\r\nself-moved, but is really moved by her power; and this composition of\r\nsoul and body is called a living and mortal creature. For immortal no\r\nsuch union can be reasonably believed to be; although fancy, not\r\nhaving seen nor surely known the nature of God, may imagine an immortal\r\ncreature having both a body and also a soul which are united throughout\r\nall time. Let that, however, be as God wills, and be spoken of\r\nacceptably to him. And now let us ask the reason why the soul loses her\r\nwings!\r\n\r\nThe wing is the corporeal element which is most akin to the divine,\r\nand which by nature tends to soar aloft and carry that which gravitates\r\ndownwards into the upper region, which is the habitation of the gods.\r\nThe divine is beauty, wisdom, goodness, and the like; and by these the\r\nwing of the soul is nourished, and grows apace; but when fed upon evil\r\nand foulness and the opposite of good, wastes and falls away. Zeus, the\r\nmighty lord, holding the reins of a winged chariot, leads the way in\r\nheaven, ordering all and taking care of all; and there follows him the\r\narray of gods and demi-gods, marshalled in eleven bands; Hestia alone\r\nabides at home in the house of heaven; of the rest they who are reckoned\r\namong the princely twelve march in their appointed order. They see many\r\nblessed sights in the inner heaven, and there are many ways to and fro,\r\nalong which the blessed gods are passing, every one doing his own\r\nwork; he may follow who will and can, for jealousy has no place in the\r\ncelestial choir. But when they go to banquet and festival, then they\r\nmove up the steep to the top of the vault of heaven. The chariots of\r\nthe gods in even poise, obeying the rein, glide rapidly; but the others\r\nlabour, for the vicious steed goes heavily, weighing down the charioteer\r\nto the earth when his steed has not been thoroughly trained:--and\r\nthis is the hour of agony and extremest conflict for the soul. For the\r\nimmortals, when they are at the end of their course, go forth and stand\r\nupon the outside of heaven, and the revolution of the spheres carries\r\nthem round, and they behold the things beyond. But of the heaven which\r\nis above the heavens, what earthly poet ever did or ever will sing\r\nworthily? It is such as I will describe; for I must dare to speak the\r\ntruth, when truth is my theme. There abides the very being with which\r\ntrue knowledge is concerned; the colourless, formless, intangible\r\nessence, visible only to mind, the pilot of the soul. The divine\r\nintelligence, being nurtured upon mind and pure knowledge, and the\r\nintelligence of every soul which is capable of receiving the food proper\r\nto it, rejoices at beholding reality, and once more gazing upon truth,\r\nis replenished and made glad, until the revolution of the worlds\r\nbrings her round again to the same place. In the revolution she beholds\r\njustice, and temperance, and knowledge absolute, not in the form of\r\ngeneration or of relation, which men call existence, but knowledge\r\nabsolute in existence absolute; and beholding the other true existences\r\nin like manner, and feasting upon them, she passes down into the\r\ninterior of the heavens and returns home; and there the charioteer\r\nputting up his horses at the stall, gives them ambrosia to eat and\r\nnectar to drink.\r\n\r\nSuch is the life of the gods; but of other souls, that which follows\r\nGod best and is likest to him lifts the head of the charioteer into the\r\nouter world, and is carried round in the revolution, troubled indeed by\r\nthe steeds, and with difficulty beholding true being; while another\r\nonly rises and falls, and sees, and again fails to see by reason of the\r\nunruliness of the steeds. The rest of the souls are also longing after\r\nthe upper world and they all follow, but not being strong enough they\r\nare carried round below the surface, plunging, treading on one another,\r\neach striving to be first; and there is confusion and perspiration and\r\nthe extremity of effort; and many of them are lamed or have their wings\r\nbroken through the ill-driving of the charioteers; and all of them after\r\na fruitless toil, not having attained to the mysteries of true being,\r\ngo away, and feed upon opinion. The reason why the souls exhibit this\r\nexceeding eagerness to behold the plain of truth is that pasturage is\r\nfound there, which is suited to the highest part of the soul; and the\r\nwing on which the soul soars is nourished with this. And there is a law\r\nof Destiny, that the soul which attains any vision of truth in company\r\nwith a god is preserved from harm until the next period, and if\r\nattaining always is always unharmed. But when she is unable to follow,\r\nand fails to behold the truth, and through some ill-hap sinks beneath\r\nthe double load of forgetfulness and vice, and her wings fall from her\r\nand she drops to the ground, then the law ordains that this soul shall\r\nat her first birth pass, not into any other animal, but only into man;\r\nand the soul which has seen most of truth shall come to the birth as a\r\nphilosopher, or artist, or some musical and loving nature; that which\r\nhas seen truth in the second degree shall be some righteous king\r\nor warrior chief; the soul which is of the third class shall be a\r\npolitician, or economist, or trader; the fourth shall be a lover of\r\ngymnastic toils, or a physician; the fifth shall lead the life of a\r\nprophet or hierophant; to the sixth the character of poet or some other\r\nimitative artist will be assigned; to the seventh the life of an artisan\r\nor husbandman; to the eighth that of a sophist or demagogue; to the\r\nninth that of a tyrant--all these are states of probation, in which\r\nhe who does righteously improves, and he who does unrighteously,\r\ndeteriorates his lot.\r\n\r\nTen thousand years must elapse before the soul of each one can return to\r\nthe place from whence she came, for she cannot grow her wings in less;\r\nonly the soul of a philosopher, guileless and true, or the soul of a\r\nlover, who is not devoid of philosophy, may acquire wings in the third\r\nof the recurring periods of a thousand years; he is distinguished from\r\nthe ordinary good man who gains wings in three thousand years:--and they\r\nwho choose this life three times in succession have wings given them,\r\nand go away at the end of three thousand years. But the others (The\r\nphilosopher alone is not subject to judgment (krisis), for he has never\r\nlost the vision of truth.) receive judgment when they have completed\r\ntheir first life, and after the judgment they go, some of them to the\r\nhouses of correction which are under the earth, and are punished; others\r\nto some place in heaven whither they are lightly borne by justice, and\r\nthere they live in a manner worthy of the life which they led here when\r\nin the form of men. And at the end of the first thousand years the good\r\nsouls and also the evil souls both come to draw lots and choose their\r\nsecond life, and they may take any which they please. The soul of a man\r\nmay pass into the life of a beast, or from the beast return again into\r\nthe man. But the soul which has never seen the truth will not pass into\r\nthe human form. For a man must have intelligence of universals, and be\r\nable to proceed from the many particulars of sense to one conception of\r\nreason;--this is the recollection of those things which our soul once\r\nsaw while following God--when regardless of that which we now call being\r\nshe raised her head up towards the true being. And therefore the mind\r\nof the philosopher alone has wings; and this is just, for he is always,\r\naccording to the measure of his abilities, clinging in recollection to\r\nthose things in which God abides, and in beholding which He is what He\r\nis. And he who employs aright these memories is ever being initiated\r\ninto perfect mysteries and alone becomes truly perfect. But, as he\r\nforgets earthly interests and is rapt in the divine, the vulgar deem him\r\nmad, and rebuke him; they do not see that he is inspired.\r\n\r\nThus far I have been speaking of the fourth and last kind of madness,\r\nwhich is imputed to him who, when he sees the beauty of earth, is\r\ntransported with the recollection of the true beauty; he would like to\r\nfly away, but he cannot; he is like a bird fluttering and looking upward\r\nand careless of the world below; and he is therefore thought to be mad.\r\nAnd I have shown this of all inspirations to be the noblest and highest\r\nand the offspring of the highest to him who has or shares in it, and\r\nthat he who loves the beautiful is called a lover because he partakes of\r\nit. For, as has been already said, every soul of man has in the way of\r\nnature beheld true being; this was the condition of her passing into the\r\nform of man. But all souls do not easily recall the things of the other\r\nworld; they may have seen them for a short time only, or they may have\r\nbeen unfortunate in their earthly lot, and, having had their hearts\r\nturned to unrighteousness through some corrupting influence, they may\r\nhave lost the memory of the holy things which once they saw. Few only\r\nretain an adequate remembrance of them; and they, when they behold\r\nhere any image of that other world, are rapt in amazement; but they\r\nare ignorant of what this rapture means, because they do not clearly\r\nperceive. For there is no light of justice or temperance or any of the\r\nhigher ideas which are precious to souls in the earthly copies of them:\r\nthey are seen through a glass dimly; and there are few who, going to the\r\nimages, behold in them the realities, and these only with difficulty.\r\nThere was a time when with the rest of the happy band they saw beauty\r\nshining in brightness,--we philosophers following in the train of Zeus,\r\nothers in company with other gods; and then we beheld the beatific\r\nvision and were initiated into a mystery which may be truly called most\r\nblessed, celebrated by us in our state of innocence, before we had\r\nany experience of evils to come, when we were admitted to the sight\r\nof apparitions innocent and simple and calm and happy, which we beheld\r\nshining in pure light, pure ourselves and not yet enshrined in that\r\nliving tomb which we carry about, now that we are imprisoned in the\r\nbody, like an oyster in his shell. Let me linger over the memory of\r\nscenes which have passed away.\r\n\r\nBut of beauty, I repeat again that we saw her there shining in company\r\nwith the celestial forms; and coming to earth we find her here too,\r\nshining in clearness through the clearest aperture of sense. For sight\r\nis the most piercing of our bodily senses; though not by that is wisdom\r\nseen; her loveliness would have been transporting if there had been\r\na visible image of her, and the other ideas, if they had visible\r\ncounterparts, would be equally lovely. But this is the privilege of\r\nbeauty, that being the loveliest she is also the most palpable to sight.\r\nNow he who is not newly initiated or who has become corrupted, does not\r\neasily rise out of this world to the sight of true beauty in the other;\r\nhe looks only at her earthly namesake, and instead of being awed at the\r\nsight of her, he is given over to pleasure, and like a brutish beast he\r\nrushes on to enjoy and beget; he consorts with wantonness, and is not\r\nafraid or ashamed of pursuing pleasure in violation of nature. But\r\nhe whose initiation is recent, and who has been the spectator of many\r\nglories in the other world, is amazed when he sees any one having a\r\ngodlike face or form, which is the expression of divine beauty; and at\r\nfirst a shudder runs through him, and again the old awe steals over him;\r\nthen looking upon the face of his beloved as of a god he reverences him,\r\nand if he were not afraid of being thought a downright madman, he would\r\nsacrifice to his beloved as to the image of a god; then while he gazes\r\non him there is a sort of reaction, and the shudder passes into an\r\nunusual heat and perspiration; for, as he receives the effluence of\r\nbeauty through the eyes, the wing moistens and he warms. And as he\r\nwarms, the parts out of which the wing grew, and which had been hitherto\r\nclosed and rigid, and had prevented the wing from shooting forth, are\r\nmelted, and as nourishment streams upon him, the lower end of the wing\r\nbegins to swell and grow from the root upwards; and the growth extends\r\nunder the whole soul--for once the whole was winged. During this process\r\nthe whole soul is all in a state of ebullition and effervescence,--which\r\nmay be compared to the irritation and uneasiness in the gums at the\r\ntime of cutting teeth,--bubbles up, and has a feeling of uneasiness and\r\ntickling; but when in like manner the soul is beginning to grow wings,\r\nthe beauty of the beloved meets her eye and she receives the sensible\r\nwarm motion of particles which flow towards her, therefore called\r\nemotion (imeros), and is refreshed and warmed by them, and then she\r\nceases from her pain with joy. But when she is parted from her beloved\r\nand her moisture fails, then the orifices of the passage out of which\r\nthe wing shoots dry up and close, and intercept the germ of the wing;\r\nwhich, being shut up with the emotion, throbbing as with the pulsations\r\nof an artery, pricks the aperture which is nearest, until at length the\r\nentire soul is pierced and maddened and pained, and at the recollection\r\nof beauty is again delighted. And from both of them together the soul is\r\noppressed at the strangeness of her condition, and is in a great strait\r\nand excitement, and in her madness can neither sleep by night nor abide\r\nin her place by day. And wherever she thinks that she will behold the\r\nbeautiful one, thither in her desire she runs. And when she has seen\r\nhim, and bathed herself in the waters of beauty, her constraint is\r\nloosened, and she is refreshed, and has no more pangs and pains; and\r\nthis is the sweetest of all pleasures at the time, and is the reason\r\nwhy the soul of the lover will never forsake his beautiful one, whom he\r\nesteems above all; he has forgotten mother and brethren and companions,\r\nand he thinks nothing of the neglect and loss of his property; the rules\r\nand proprieties of life, on which he formerly prided himself, he now\r\ndespises, and is ready to sleep like a servant, wherever he is allowed,\r\nas near as he can to his desired one, who is the object of his worship,\r\nand the physician who can alone assuage the greatness of his pain. And\r\nthis state, my dear imaginary youth to whom I am talking, is by men\r\ncalled love, and among the gods has a name at which you, in your\r\nsimplicity, may be inclined to mock; there are two lines in the\r\napocryphal writings of Homer in which the name occurs. One of them is\r\nrather outrageous, and not altogether metrical. They are as follows:\r\n\r\n'Mortals call him fluttering love, But the immortals call him winged\r\none, Because the growing of wings (Or, reading pterothoiton, 'the\r\nmovement of wings.') is a necessity to him.'\r\n\r\nYou may believe this, but not unless you like. At any rate the loves of\r\nlovers and their causes are such as I have described.\r\n\r\nNow the lover who is taken to be the attendant of Zeus is better able to\r\nbear the winged god, and can endure a heavier burden; but the attendants\r\nand companions of Ares, when under the influence of love, if they fancy\r\nthat they have been at all wronged, are ready to kill and put an end\r\nto themselves and their beloved. And he who follows in the train of any\r\nother god, while he is unspoiled and the impression lasts, honours and\r\nimitates him, as far as he is able; and after the manner of his God he\r\nbehaves in his intercourse with his beloved and with the rest of the\r\nworld during the first period of his earthly existence. Every one\r\nchooses his love from the ranks of beauty according to his character,\r\nand this he makes his god, and fashions and adorns as a sort of image\r\nwhich he is to fall down and worship. The followers of Zeus desire that\r\ntheir beloved should have a soul like him; and therefore they seek out\r\nsome one of a philosophical and imperial nature, and when they have\r\nfound him and loved him, they do all they can to confirm such a nature\r\nin him, and if they have no experience of such a disposition hitherto,\r\nthey learn of any one who can teach them, and themselves follow in the\r\nsame way. And they have the less difficulty in finding the nature of\r\ntheir own god in themselves, because they have been compelled to gaze\r\nintensely on him; their recollection clings to him, and they become\r\npossessed of him, and receive from him their character and disposition,\r\nso far as man can participate in God. The qualities of their god they\r\nattribute to the beloved, wherefore they love him all the more, and if,\r\nlike the Bacchic Nymphs, they draw inspiration from Zeus, they pour out\r\ntheir own fountain upon him, wanting to make him as like as possible\r\nto their own god. But those who are the followers of Here seek a royal\r\nlove, and when they have found him they do just the same with him; and\r\nin like manner the followers of Apollo, and of every other god walking\r\nin the ways of their god, seek a love who is to be made like him whom\r\nthey serve, and when they have found him, they themselves imitate their\r\ngod, and persuade their love to do the same, and educate him into the\r\nmanner and nature of the god as far as they each can; for no feelings of\r\nenvy or jealousy are entertained by them towards their beloved, but they\r\ndo their utmost to create in him the greatest likeness of themselves and\r\nof the god whom they honour. Thus fair and blissful to the beloved is\r\nthe desire of the inspired lover, and the initiation of which I speak\r\ninto the mysteries of true love, if he be captured by the lover and\r\ntheir purpose is effected. Now the beloved is taken captive in the\r\nfollowing manner:--\r\n\r\nAs I said at the beginning of this tale, I divided each soul into\r\nthree--two horses and a charioteer; and one of the horses was good and\r\nthe other bad: the division may remain, but I have not yet explained in\r\nwhat the goodness or badness of either consists, and to that I will\r\nnow proceed. The right-hand horse is upright and cleanly made; he has a\r\nlofty neck and an aquiline nose; his colour is white, and his eyes dark;\r\nhe is a lover of honour and modesty and temperance, and the follower\r\nof true glory; he needs no touch of the whip, but is guided by word and\r\nadmonition only. The other is a crooked lumbering animal, put together\r\nanyhow; he has a short thick neck; he is flat-faced and of a dark\r\ncolour, with grey eyes and blood-red complexion (Or with grey and\r\nblood-shot eyes.); the mate of insolence and pride, shag-eared and deaf,\r\nhardly yielding to whip and spur. Now when the charioteer beholds the\r\nvision of love, and has his whole soul warmed through sense, and is full\r\nof the prickings and ticklings of desire, the obedient steed, then\r\nas always under the government of shame, refrains from leaping on the\r\nbeloved; but the other, heedless of the pricks and of the blows of\r\nthe whip, plunges and runs away, giving all manner of trouble to his\r\ncompanion and the charioteer, whom he forces to approach the beloved and\r\nto remember the joys of love. They at first indignantly oppose him and\r\nwill not be urged on to do terrible and unlawful deeds; but at last,\r\nwhen he persists in plaguing them, they yield and agree to do as he bids\r\nthem. And now they are at the spot and behold the flashing beauty of the\r\nbeloved; which when the charioteer sees, his memory is carried to the\r\ntrue beauty, whom he beholds in company with Modesty like an image\r\nplaced upon a holy pedestal. He sees her, but he is afraid and falls\r\nbackwards in adoration, and by his fall is compelled to pull back the\r\nreins with such violence as to bring both the steeds on their haunches,\r\nthe one willing and unresisting, the unruly one very unwilling; and when\r\nthey have gone back a little, the one is overcome with shame and wonder,\r\nand his whole soul is bathed in perspiration; the other, when the\r\npain is over which the bridle and the fall had given him, having with\r\ndifficulty taken breath, is full of wrath and reproaches, which he\r\nheaps upon the charioteer and his fellow-steed, for want of courage\r\nand manhood, declaring that they have been false to their agreement and\r\nguilty of desertion. Again they refuse, and again he urges them on, and\r\nwill scarce yield to their prayer that he would wait until another time.\r\nWhen the appointed hour comes, they make as if they had forgotten, and\r\nhe reminds them, fighting and neighing and dragging them on, until at\r\nlength he on the same thoughts intent, forces them to draw near again.\r\nAnd when they are near he stoops his head and puts up his tail, and\r\ntakes the bit in his teeth and pulls shamelessly. Then the charioteer is\r\nworse off than ever; he falls back like a racer at the barrier, and with\r\na still more violent wrench drags the bit out of the teeth of the wild\r\nsteed and covers his abusive tongue and jaws with blood, and forces his\r\nlegs and haunches to the ground and punishes him sorely. And when this\r\nhas happened several times and the villain has ceased from his wanton\r\nway, he is tamed and humbled, and follows the will of the charioteer,\r\nand when he sees the beautiful one he is ready to die of fear. And from\r\nthat time forward the soul of the lover follows the beloved in modesty\r\nand holy fear.\r\n\r\nAnd so the beloved who, like a god, has received every true and loyal\r\nservice from his lover, not in pretence but in reality, being also\r\nhimself of a nature friendly to his admirer, if in former days he\r\nhas blushed to own his passion and turned away his lover, because his\r\nyouthful companions or others slanderously told him that he would be\r\ndisgraced, now as years advance, at the appointed age and time, is led\r\nto receive him into communion. For fate which has ordained that there\r\nshall be no friendship among the evil has also ordained that there shall\r\never be friendship among the good. And the beloved when he has received\r\nhim into communion and intimacy, is quite amazed at the good-will of the\r\nlover; he recognises that the inspired friend is worth all other\r\nfriends or kinsmen; they have nothing of friendship in them worthy to be\r\ncompared with his. And when this feeling continues and he is nearer\r\nto him and embraces him, in gymnastic exercises and at other times of\r\nmeeting, then the fountain of that stream, which Zeus when he was in\r\nlove with Ganymede named Desire, overflows upon the lover, and some\r\nenters into his soul, and some when he is filled flows out again; and as\r\na breeze or an echo rebounds from the smooth rocks and returns whence it\r\ncame, so does the stream of beauty, passing through the eyes which are\r\nthe windows of the soul, come back to the beautiful one; there arriving\r\nand quickening the passages of the wings, watering them and inclining\r\nthem to grow, and filling the soul of the beloved also with love. And\r\nthus he loves, but he knows not what; he does not understand and cannot\r\nexplain his own state; he appears to have caught the infection of\r\nblindness from another; the lover is his mirror in whom he is beholding\r\nhimself, but he is not aware of this. When he is with the lover, both\r\ncease from their pain, but when he is away then he longs as he is\r\nlonged for, and has love's image, love for love (Anteros) lodging in his\r\nbreast, which he calls and believes to be not love but friendship only,\r\nand his desire is as the desire of the other, but weaker; he wants\r\nto see him, touch him, kiss him, embrace him, and probably not long\r\nafterwards his desire is accomplished. When they meet, the wanton steed\r\nof the lover has a word to say to the charioteer; he would like to have\r\na little pleasure in return for many pains, but the wanton steed of\r\nthe beloved says not a word, for he is bursting with passion which he\r\nunderstands not;--he throws his arms round the lover and embraces him\r\nas his dearest friend; and, when they are side by side, he is not in a\r\nstate in which he can refuse the lover anything, if he ask him; although\r\nhis fellow-steed and the charioteer oppose him with the arguments\r\nof shame and reason. After this their happiness depends upon their\r\nself-control; if the better elements of the mind which lead to order\r\nand philosophy prevail, then they pass their life here in happiness and\r\nharmony--masters of themselves and orderly--enslaving the vicious and\r\nemancipating the virtuous elements of the soul; and when the end comes,\r\nthey are light and winged for flight, having conquered in one of the\r\nthree heavenly or truly Olympian victories; nor can human discipline or\r\ndivine inspiration confer any greater blessing on man than this. If,\r\non the other hand, they leave philosophy and lead the lower life of\r\nambition, then probably, after wine or in some other careless hour, the\r\ntwo wanton animals take the two souls when off their guard and bring\r\nthem together, and they accomplish that desire of their hearts which to\r\nthe many is bliss; and this having once enjoyed they continue to enjoy,\r\nyet rarely because they have not the approval of the whole soul. They\r\ntoo are dear, but not so dear to one another as the others, either at\r\nthe time of their love or afterwards. They consider that they have given\r\nand taken from each other the most sacred pledges, and they may not\r\nbreak them and fall into enmity. At last they pass out of the body,\r\nunwinged, but eager to soar, and thus obtain no mean reward of love and\r\nmadness. For those who have once begun the heavenward pilgrimage may not\r\ngo down again to darkness and the journey beneath the earth, but they\r\nlive in light always; happy companions in their pilgrimage, and when the\r\ntime comes at which they receive their wings they have the same plumage\r\nbecause of their love.\r\n\r\nThus great are the heavenly blessings which the friendship of a lover\r\nwill confer upon you, my youth. Whereas the attachment of the non-lover,\r\nwhich is alloyed with a worldly prudence and has worldly and niggardly\r\nways of doling out benefits, will breed in your soul those vulgar\r\nqualities which the populace applaud, will send you bowling round the\r\nearth during a period of nine thousand years, and leave you a fool in\r\nthe world below.\r\n\r\nAnd thus, dear Eros, I have made and paid my recantation, as well and as\r\nfairly as I could; more especially in the matter of the poetical figures\r\nwhich I was compelled to use, because Phaedrus would have them. And now\r\nforgive the past and accept the present, and be gracious and merciful to\r\nme, and do not in thine anger deprive me of sight, or take from me the\r\nart of love which thou hast given me, but grant that I may be yet more\r\nesteemed in the eyes of the fair. And if Phaedrus or I myself said\r\nanything rude in our first speeches, blame Lysias, who is the father\r\nof the brat, and let us have no more of his progeny; bid him study\r\nphilosophy, like his brother Polemarchus; and then his lover Phaedrus\r\nwill no longer halt between two opinions, but will dedicate himself\r\nwholly to love and to philosophical discourses.\r\n\r\nPHAEDRUS: I join in the prayer, Socrates, and say with you, if this\r\nbe for my good, may your words come to pass. But why did you make your\r\nsecond oration so much finer than the first? I wonder why. And I begin\r\nto be afraid that I shall lose conceit of Lysias, and that he will\r\nappear tame in comparison, even if he be willing to put another as fine\r\nand as long as yours into the field, which I doubt. For quite lately one\r\nof your politicians was abusing him on this very account; and called\r\nhim a 'speech writer' again and again. So that a feeling of pride may\r\nprobably induce him to give up writing speeches.\r\n\r\nSOCRATES: What a very amusing notion! But I think, my young man,\r\nthat you are much mistaken in your friend if you imagine that he\r\nis frightened at a little noise; and, possibly, you think that his\r\nassailant was in earnest?\r\n\r\nPHAEDRUS: I thought, Socrates, that he was. And you are aware that the\r\ngreatest and most influential statesmen are ashamed of writing speeches\r\nand leaving them in a written form, lest they should be called Sophists\r\nby posterity.\r\n\r\nSOCRATES: You seem to be unconscious, Phaedrus, that the 'sweet elbow'\r\n(A proverb, like 'the grapes are sour,' applied to pleasures which\r\ncannot be had, meaning sweet things which, like the elbow, are out of\r\nthe reach of the mouth. The promised pleasure turns out to be a long and\r\ntedious affair.) of the proverb is really the long arm of the Nile. And\r\nyou appear to be equally unaware of the fact that this sweet elbow\r\nof theirs is also a long arm. For there is nothing of which our great\r\npoliticians are so fond as of writing speeches and bequeathing them to\r\nposterity. And they add their admirers' names at the top of the writing,\r\nout of gratitude to them.\r\n\r\nPHAEDRUS: What do you mean? I do not understand.\r\n\r\nSOCRATES: Why, do you not know that when a politician writes, he begins\r\nwith the names of his approvers?\r\n\r\nPHAEDRUS: How so?\r\n\r\nSOCRATES: Why, he begins in this manner: 'Be it enacted by the senate,\r\nthe people, or both, on the motion of a certain person,' who is our\r\nauthor; and so putting on a serious face, he proceeds to display his own\r\nwisdom to his admirers in what is often a long and tedious composition.\r\nNow what is that sort of thing but a regular piece of authorship?\r\n\r\nPHAEDRUS: True.\r\n\r\nSOCRATES: And if the law is finally approved, then the author leaves the\r\ntheatre in high delight; but if the law is rejected and he is done out\r\nof his speech-making, and not thought good enough to write, then he and\r\nhis party are in mourning.\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: So far are they from despising, or rather so highly do they\r\nvalue the practice of writing.\r\n\r\nPHAEDRUS: No doubt.\r\n\r\nSOCRATES: And when the king or orator has the power, as Lycurgus or\r\nSolon or Darius had, of attaining an immortality or authorship in a\r\nstate, is he not thought by posterity, when they see his compositions,\r\nand does he not think himself, while he is yet alive, to be a god?\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: Then do you think that any one of this class, however\r\nill-disposed, would reproach Lysias with being an author?\r\n\r\nPHAEDRUS: Not upon your view; for according to you he would be casting a\r\nslur upon his own favourite pursuit.\r\n\r\nSOCRATES: Any one may see that there is no disgrace in the mere fact of\r\nwriting.\r\n\r\nPHAEDRUS: Certainly not.\r\n\r\nSOCRATES: The disgrace begins when a man writes not well, but badly.\r\n\r\nPHAEDRUS: Clearly.\r\n\r\nSOCRATES: And what is well and what is badly--need we ask Lysias, or any\r\nother poet or orator, who ever wrote or will write either a political or\r\nany other work, in metre or out of metre, poet or prose writer, to teach\r\nus this?\r\n\r\nPHAEDRUS: Need we? For what should a man live if not for the pleasures\r\nof discourse? Surely not for the sake of bodily pleasures, which almost\r\nalways have previous pain as a condition of them, and therefore are\r\nrightly called slavish.\r\n\r\nSOCRATES: There is time enough. And I believe that the grasshoppers\r\nchirruping after their manner in the heat of the sun over our heads are\r\ntalking to one another and looking down at us. What would they say if\r\nthey saw that we, like the many, are not conversing, but slumbering at\r\nmid-day, lulled by their voices, too indolent to think? Would they not\r\nhave a right to laugh at us? They might imagine that we were slaves,\r\nwho, coming to rest at a place of resort of theirs, like sheep lie\r\nasleep at noon around the well. But if they see us discoursing, and\r\nlike Odysseus sailing past them, deaf to their siren voices, they may\r\nperhaps, out of respect, give us of the gifts which they receive from\r\nthe gods that they may impart them to men.\r\n\r\nPHAEDRUS: What gifts do you mean? I never heard of any.\r\n\r\nSOCRATES: A lover of music like yourself ought surely to have heard the\r\nstory of the grasshoppers, who are said to have been human beings in\r\nan age before the Muses. And when the Muses came and song appeared they\r\nwere ravished with delight; and singing always, never thought of eating\r\nand drinking, until at last in their forgetfulness they died. And now\r\nthey live again in the grasshoppers; and this is the return which the\r\nMuses make to them--they neither hunger, nor thirst, but from the hour\r\nof their birth are always singing, and never eating or drinking; and\r\nwhen they die they go and inform the Muses in heaven who honours them on\r\nearth. They win the love of Terpsichore for the dancers by their report\r\nof them; of Erato for the lovers, and of the other Muses for those who\r\ndo them honour, according to the several ways of honouring them;--of\r\nCalliope the eldest Muse and of Urania who is next to her, for the\r\nphilosophers, of whose music the grasshoppers make report to them; for\r\nthese are the Muses who are chiefly concerned with heaven and thought,\r\ndivine as well as human, and they have the sweetest utterance. For many\r\nreasons, then, we ought always to talk and not to sleep at mid-day.\r\n\r\nPHAEDRUS: Let us talk.\r\n\r\nSOCRATES: Shall we discuss the rules of writing and speech as we were\r\nproposing?\r\n\r\nPHAEDRUS: Very good.\r\n\r\nSOCRATES: In good speaking should not the mind of the speaker know the\r\ntruth of the matter about which he is going to speak?\r\n\r\nPHAEDRUS: And yet, Socrates, I have heard that he who would be an orator\r\nhas nothing to do with true justice, but only with that which is likely\r\nto be approved by the many who sit in judgment; nor with the truly good\r\nor honourable, but only with opinion about them, and that from opinion\r\ncomes persuasion, and not from the truth.\r\n\r\nSOCRATES: The words of the wise are not to be set aside; for there is\r\nprobably something in them; and therefore the meaning of this saying is\r\nnot hastily to be dismissed.\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: Let us put the matter thus:--Suppose that I persuaded you\r\nto buy a horse and go to the wars. Neither of us knew what a horse was\r\nlike, but I knew that you believed a horse to be of tame animals the one\r\nwhich has the longest ears.\r\n\r\nPHAEDRUS: That would be ridiculous.\r\n\r\nSOCRATES: There is something more ridiculous coming:--Suppose, further,\r\nthat in sober earnest I, having persuaded you of this, went and composed\r\na speech in honour of an ass, whom I entitled a horse beginning: 'A\r\nnoble animal and a most useful possession, especially in war, and you\r\nmay get on his back and fight, and he will carry baggage or anything.'\r\n\r\nPHAEDRUS: How ridiculous!\r\n\r\nSOCRATES: Ridiculous! Yes; but is not even a ridiculous friend better\r\nthan a cunning enemy?\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: And when the orator instead of putting an ass in the place\r\nof a horse, puts good for evil, being himself as ignorant of their true\r\nnature as the city on which he imposes is ignorant; and having studied\r\nthe notions of the multitude, falsely persuades them not about 'the\r\nshadow of an ass,' which he confounds with a horse, but about good which\r\nhe confounds with evil,--what will be the harvest which rhetoric will be\r\nlikely to gather after the sowing of that seed?\r\n\r\nPHAEDRUS: The reverse of good.\r\n\r\nSOCRATES: But perhaps rhetoric has been getting too roughly handled by\r\nus, and she might answer: What amazing nonsense you are talking! As if I\r\nforced any man to learn to speak in ignorance of the truth! Whatever\r\nmy advice may be worth, I should have told him to arrive at the truth\r\nfirst, and then come to me. At the same time I boldly assert that mere\r\nknowledge of the truth will not give you the art of persuasion.\r\n\r\nPHAEDRUS: There is reason in the lady's defence of herself.\r\n\r\nSOCRATES: Quite true; if only the other arguments which remain to be\r\nbrought up bear her witness that she is an art at all. But I seem to\r\nhear them arraying themselves on the opposite side, declaring that she\r\nspeaks falsely, and that rhetoric is a mere routine and trick, not an\r\nart. Lo! a Spartan appears, and says that there never is nor ever will\r\nbe a real art of speaking which is divorced from the truth.\r\n\r\nPHAEDRUS: And what are these arguments, Socrates? Bring them out that we\r\nmay examine them.\r\n\r\nSOCRATES: Come out, fair children, and convince Phaedrus, who is the\r\nfather of similar beauties, that he will never be able to speak about\r\nanything as he ought to speak unless he have a knowledge of philosophy.\r\nAnd let Phaedrus answer you.\r\n\r\nPHAEDRUS: Put the question.\r\n\r\nSOCRATES: Is not rhetoric, taken generally, a universal art of\r\nenchanting the mind by arguments; which is practised not only in courts\r\nand public assemblies, but in private houses also, having to do with\r\nall matters, great as well as small, good and bad alike, and is in all\r\nequally right, and equally to be esteemed--that is what you have heard?\r\n\r\nPHAEDRUS: Nay, not exactly that; I should say rather that I have heard\r\nthe art confined to speaking and writing in lawsuits, and to speaking in\r\npublic assemblies--not extended farther.\r\n\r\nSOCRATES: Then I suppose that you have only heard of the rhetoric of\r\nNestor and Odysseus, which they composed in their leisure hours when at\r\nTroy, and never of the rhetoric of Palamedes?\r\n\r\nPHAEDRUS: No more than of Nestor and Odysseus, unless Gorgias is your\r\nNestor, and Thrasymachus or Theodorus your Odysseus.\r\n\r\nSOCRATES: Perhaps that is my meaning. But let us leave them. And do\r\nyou tell me, instead, what are plaintiff and defendant doing in a law\r\ncourt--are they not contending?\r\n\r\nPHAEDRUS: Exactly so.\r\n\r\nSOCRATES: About the just and unjust--that is the matter in dispute?\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: And a professor of the art will make the same thing appear to\r\nthe same persons to be at one time just, at another time, if he is so\r\ninclined, to be unjust?\r\n\r\nPHAEDRUS: Exactly.\r\n\r\nSOCRATES: And when he speaks in the assembly, he will make the same\r\nthings seem good to the city at one time, and at another time the\r\nreverse of good?\r\n\r\nPHAEDRUS: That is true.\r\n\r\nSOCRATES: Have we not heard of the Eleatic Palamedes (Zeno), who has an\r\nart of speaking by which he makes the same things appear to his hearers\r\nlike and unlike, one and many, at rest and in motion?\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: The art of disputation, then, is not confined to the courts\r\nand the assembly, but is one and the same in every use of language; this\r\nis the art, if there be such an art, which is able to find a likeness of\r\neverything to which a likeness can be found, and draws into the light of\r\nday the likenesses and disguises which are used by others?\r\n\r\nPHAEDRUS: How do you mean?\r\n\r\nSOCRATES: Let me put the matter thus: When will there be more chance of\r\ndeception--when the difference is large or small?\r\n\r\nPHAEDRUS: When the difference is small.\r\n\r\nSOCRATES: And you will be less likely to be discovered in passing by\r\ndegrees into the other extreme than when you go all at once?\r\n\r\nPHAEDRUS: Of course.\r\n\r\nSOCRATES: He, then, who would deceive others, and not be deceived, must\r\nexactly know the real likenesses and differences of things?\r\n\r\nPHAEDRUS: He must.\r\n\r\nSOCRATES: And if he is ignorant of the true nature of any subject, how\r\ncan he detect the greater or less degree of likeness in other things to\r\nthat of which by the hypothesis he is ignorant?\r\n\r\nPHAEDRUS: He cannot.\r\n\r\nSOCRATES: And when men are deceived and their notions are at\r\nvariance with realities, it is clear that the error slips in through\r\nresemblances?\r\n\r\nPHAEDRUS: Yes, that is the way.\r\n\r\nSOCRATES: Then he who would be a master of the art must understand the\r\nreal nature of everything; or he will never know either how to make\r\nthe gradual departure from truth into the opposite of truth which is\r\neffected by the help of resemblances, or how to avoid it?\r\n\r\nPHAEDRUS: He will not.\r\n\r\nSOCRATES: He then, who being ignorant of the truth aims at appearances,\r\nwill only attain an art of rhetoric which is ridiculous and is not an\r\nart at all?\r\n\r\nPHAEDRUS: That may be expected.\r\n\r\nSOCRATES: Shall I propose that we look for examples of art and want of\r\nart, according to our notion of them, in the speech of Lysias which you\r\nhave in your hand, and in my own speech?\r\n\r\nPHAEDRUS: Nothing could be better; and indeed I think that our previous\r\nargument has been too abstract and wanting in illustrations.\r\n\r\nSOCRATES: Yes; and the two speeches happen to afford a very good example\r\nof the way in which the speaker who knows the truth may, without any\r\nserious purpose, steal away the hearts of his hearers. This piece\r\nof good-fortune I attribute to the local deities; and, perhaps, the\r\nprophets of the Muses who are singing over our heads may have imparted\r\ntheir inspiration to me. For I do not imagine that I have any rhetorical\r\nart of my own.\r\n\r\nPHAEDRUS: Granted; if you will only please to get on.\r\n\r\nSOCRATES: Suppose that you read me the first words of Lysias' speech.\r\n\r\nPHAEDRUS: 'You know how matters stand with me, and how, as I conceive,\r\nthey might be arranged for our common interest; and I maintain that I\r\nought not to fail in my suit, because I am not your lover. For lovers\r\nrepent--'\r\n\r\nSOCRATES: Enough:--Now, shall I point out the rhetorical error of those\r\nwords?\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: Every one is aware that about some things we are agreed,\r\nwhereas about other things we differ.\r\n\r\nPHAEDRUS: I think that I understand you; but will you explain yourself?\r\n\r\nSOCRATES: When any one speaks of iron and silver, is not the same thing\r\npresent in the minds of all?\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: But when any one speaks of justice and goodness we part\r\ncompany and are at odds with one another and with ourselves?\r\n\r\nPHAEDRUS: Precisely.\r\n\r\nSOCRATES: Then in some things we agree, but not in others?\r\n\r\nPHAEDRUS: That is true.\r\n\r\nSOCRATES: In which are we more likely to be deceived, and in which has\r\nrhetoric the greater power?\r\n\r\nPHAEDRUS: Clearly, in the uncertain class.\r\n\r\nSOCRATES: Then the rhetorician ought to make a regular division, and\r\nacquire a distinct notion of both classes, as well of that in which the\r\nmany err, as of that in which they do not err?\r\n\r\nPHAEDRUS: He who made such a distinction would have an excellent\r\nprinciple.\r\n\r\nSOCRATES: Yes; and in the next place he must have a keen eye for the\r\nobservation of particulars in speaking, and not make a mistake about the\r\nclass to which they are to be referred.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: Now to which class does love belong--to the debatable or to\r\nthe undisputed class?\r\n\r\nPHAEDRUS: To the debatable, clearly; for if not, do you think that love\r\nwould have allowed you to say as you did, that he is an evil both to the\r\nlover and the beloved, and also the greatest possible good?\r\n\r\nSOCRATES: Capital. But will you tell me whether I defined love at the\r\nbeginning of my speech? for, having been in an ecstasy, I cannot well\r\nremember.\r\n\r\nPHAEDRUS: Yes, indeed; that you did, and no mistake.\r\n\r\nSOCRATES: Then I perceive that the Nymphs of Achelous and Pan the son\r\nof Hermes, who inspired me, were far better rhetoricians than Lysias\r\nthe son of Cephalus. Alas! how inferior to them he is! But perhaps I\r\nam mistaken; and Lysias at the commencement of his lover's speech did\r\ninsist on our supposing love to be something or other which he fancied\r\nhim to be, and according to this model he fashioned and framed the\r\nremainder of his discourse. Suppose we read his beginning over again:\r\n\r\nPHAEDRUS: If you please; but you will not find what you want.\r\n\r\nSOCRATES: Read, that I may have his exact words.\r\n\r\nPHAEDRUS: 'You know how matters stand with me, and how, as I conceive,\r\nthey might be arranged for our common interest; and I maintain I ought\r\nnot to fail in my suit because I am not your lover, for lovers repent of\r\nthe kindnesses which they have shown, when their love is over.'\r\n\r\nSOCRATES: Here he appears to have done just the reverse of what he\r\nought; for he has begun at the end, and is swimming on his back through\r\nthe flood to the place of starting. His address to the fair youth begins\r\nwhere the lover would have ended. Am I not right, sweet Phaedrus?\r\n\r\nPHAEDRUS: Yes, indeed, Socrates; he does begin at the end.\r\n\r\nSOCRATES: Then as to the other topics--are they not thrown down anyhow?\r\nIs there any principle in them? Why should the next topic follow next in\r\norder, or any other topic? I cannot help fancying in my ignorance that\r\nhe wrote off boldly just what came into his head, but I dare say that\r\nyou would recognize a rhetorical necessity in the succession of the\r\nseveral parts of the composition?\r\n\r\nPHAEDRUS: You have too good an opinion of me if you think that I have\r\nany such insight into his principles of composition.\r\n\r\nSOCRATES: At any rate, you will allow that every discourse ought to be\r\na living creature, having a body of its own and a head and feet; there\r\nshould be a middle, beginning, and end, adapted to one another and to\r\nthe whole?\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: Can this be said of the discourse of Lysias? See whether you\r\ncan find any more connexion in his words than in the epitaph which is\r\nsaid by some to have been inscribed on the grave of Midas the Phrygian.\r\n\r\nPHAEDRUS: What is there remarkable in the epitaph?\r\n\r\nSOCRATES: It is as follows:--\r\n\r\n'I am a maiden of bronze and lie on the tomb of Midas; So long as water\r\nflows and tall trees grow, So long here on this spot by his sad tomb\r\nabiding, I shall declare to passers-by that Midas sleeps below.'\r\n\r\nNow in this rhyme whether a line comes first or comes last, as you will\r\nperceive, makes no difference.\r\n\r\nPHAEDRUS: You are making fun of that oration of ours.\r\n\r\nSOCRATES: Well, I will say no more about your friend's speech lest I\r\nshould give offence to you; although I think that it might furnish many\r\nother examples of what a man ought rather to avoid. But I will proceed\r\nto the other speech, which, as I think, is also suggestive to students\r\nof rhetoric.\r\n\r\nPHAEDRUS: In what way?\r\n\r\nSOCRATES: The two speeches, as you may remember, were unlike; the one\r\nargued that the lover and the other that the non-lover ought to be\r\naccepted.\r\n\r\nPHAEDRUS: And right manfully.\r\n\r\nSOCRATES: You should rather say 'madly;' and madness was the argument of\r\nthem, for, as I said, 'love is a madness.'\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: And of madness there were two kinds; one produced by human\r\ninfirmity, the other was a divine release of the soul from the yoke of\r\ncustom and convention.\r\n\r\nPHAEDRUS: True.\r\n\r\nSOCRATES: The divine madness was subdivided into four kinds, prophetic,\r\ninitiatory, poetic, erotic, having four gods presiding over them; the\r\nfirst was the inspiration of Apollo, the second that of Dionysus, the\r\nthird that of the Muses, the fourth that of Aphrodite and Eros. In the\r\ndescription of the last kind of madness, which was also said to be\r\nthe best, we spoke of the affection of love in a figure, into which we\r\nintroduced a tolerably credible and possibly true though partly erring\r\nmyth, which was also a hymn in honour of Love, who is your lord and also\r\nmine, Phaedrus, and the guardian of fair children, and to him we sung\r\nthe hymn in measured and solemn strain.\r\n\r\nPHAEDRUS: I know that I had great pleasure in listening to you.\r\n\r\nSOCRATES: Let us take this instance and note how the transition was made\r\nfrom blame to praise.\r\n\r\nPHAEDRUS: What do you mean?\r\n\r\nSOCRATES: I mean to say that the composition was mostly playful. Yet in\r\nthese chance fancies of the hour were involved two principles of which\r\nwe should be too glad to have a clearer description if art could give us\r\none.\r\n\r\nPHAEDRUS: What are they?\r\n\r\nSOCRATES: First, the comprehension of scattered particulars in one idea;\r\nas in our definition of love, which whether true or false certainly gave\r\nclearness and consistency to the discourse, the speaker should define\r\nhis several notions and so make his meaning clear.\r\n\r\nPHAEDRUS: What is the other principle, Socrates?\r\n\r\nSOCRATES: The second principle is that of division into species\r\naccording to the natural formation, where the joint is, not breaking any\r\npart as a bad carver might. Just as our two discourses, alike assumed,\r\nfirst of all, a single form of unreason; and then, as the body which\r\nfrom being one becomes double and may be divided into a left side and\r\nright side, each having parts right and left of the same name--after\r\nthis manner the speaker proceeded to divide the parts of the left side\r\nand did not desist until he found in them an evil or left-handed love\r\nwhich he justly reviled; and the other discourse leading us to the\r\nmadness which lay on the right side, found another love, also having the\r\nsame name, but divine, which the speaker held up before us and applauded\r\nand affirmed to be the author of the greatest benefits.\r\n\r\nPHAEDRUS: Most true.\r\n\r\nSOCRATES: I am myself a great lover of these processes of division and\r\ngeneralization; they help me to speak and to think. And if I find any\r\nman who is able to see 'a One and Many' in nature, him I follow, and\r\n'walk in his footsteps as if he were a god.' And those who have this\r\nart, I have hitherto been in the habit of calling dialecticians; but God\r\nknows whether the name is right or not. And I should like to know what\r\nname you would give to your or to Lysias' disciples, and whether this\r\nmay not be that famous art of rhetoric which Thrasymachus and others\r\nteach and practise? Skilful speakers they are, and impart their skill to\r\nany who is willing to make kings of them and to bring gifts to them.\r\n\r\nPHAEDRUS: Yes, they are royal men; but their art is not the same\r\nwith the art of those whom you call, and rightly, in my opinion,\r\ndialecticians:--Still we are in the dark about rhetoric.\r\n\r\nSOCRATES: What do you mean? The remains of it, if there be anything\r\nremaining which can be brought under rules of art, must be a fine thing;\r\nand, at any rate, is not to be despised by you and me. But how much is\r\nleft?\r\n\r\nPHAEDRUS: There is a great deal surely to be found in books of rhetoric?\r\n\r\nSOCRATES: Yes; thank you for reminding me:--There is the exordium,\r\nshowing how the speech should begin, if I remember rightly; that is what\r\nyou mean--the niceties of the art?\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: Then follows the statement of facts, and upon that witnesses;\r\nthirdly, proofs; fourthly, probabilities are to come; the great\r\nByzantian word-maker also speaks, if I am not mistaken, of confirmation\r\nand further confirmation.\r\n\r\nPHAEDRUS: You mean the excellent Theodorus.\r\n\r\nSOCRATES: Yes; and he tells how refutation or further refutation is to\r\nbe managed, whether in accusation or defence. I ought also to mention\r\nthe illustrious Parian, Evenus, who first invented insinuations and\r\nindirect praises; and also indirect censures, which according to some\r\nhe put into verse to help the memory. But shall I 'to dumb forgetfulness\r\nconsign' Tisias and Gorgias, who are not ignorant that probability is\r\nsuperior to truth, and who by force of argument make the little appear\r\ngreat and the great little, disguise the new in old fashions and the old\r\nin new fashions, and have discovered forms for everything, either short\r\nor going on to infinity. I remember Prodicus laughing when I told him of\r\nthis; he said that he had himself discovered the true rule of art, which\r\nwas to be neither long nor short, but of a convenient length.\r\n\r\nPHAEDRUS: Well done, Prodicus!\r\n\r\nSOCRATES: Then there is Hippias the Elean stranger, who probably agrees\r\nwith him.\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: And there is also Polus, who has treasuries of diplasiology,\r\nand gnomology, and eikonology, and who teaches in them the names of\r\nwhich Licymnius made him a present; they were to give a polish.\r\n\r\nPHAEDRUS: Had not Protagoras something of the same sort?\r\n\r\nSOCRATES: Yes, rules of correct diction and many other fine precepts;\r\nfor the 'sorrows of a poor old man,' or any other pathetic case, no one\r\nis better than the Chalcedonian giant; he can put a whole company of\r\npeople into a passion and out of one again by his mighty magic, and\r\nis first-rate at inventing or disposing of any sort of calumny on any\r\ngrounds or none. All of them agree in asserting that a speech should end\r\nin a recapitulation, though they do not all agree to use the same word.\r\n\r\nPHAEDRUS: You mean that there should be a summing up of the arguments in\r\norder to remind the hearers of them.\r\n\r\nSOCRATES: I have now said all that I have to say of the art of rhetoric:\r\nhave you anything to add?\r\n\r\nPHAEDRUS: Not much; nothing very important.\r\n\r\nSOCRATES: Leave the unimportant and let us bring the really important\r\nquestion into the light of day, which is: What power has this art of\r\nrhetoric, and when?\r\n\r\nPHAEDRUS: A very great power in public meetings.\r\n\r\nSOCRATES: It has. But I should like to know whether you have the same\r\nfeeling as I have about the rhetoricians? To me there seem to be a great\r\nmany holes in their web.\r\n\r\nPHAEDRUS: Give an example.\r\n\r\nSOCRATES: I will. Suppose a person to come to your friend Eryximachus,\r\nor to his father Acumenus, and to say to him: 'I know how to apply drugs\r\nwhich shall have either a heating or a cooling effect, and I can give\r\na vomit and also a purge, and all that sort of thing; and knowing all\r\nthis, as I do, I claim to be a physician and to make physicians by\r\nimparting this knowledge to others,'--what do you suppose that they\r\nwould say?\r\n\r\nPHAEDRUS: They would be sure to ask him whether he knew 'to whom' he\r\nwould give his medicines, and 'when,' and 'how much.'\r\n\r\nSOCRATES: And suppose that he were to reply: 'No; I know nothing of all\r\nthat; I expect the patient who consults me to be able to do these things\r\nfor himself'?\r\n\r\nPHAEDRUS: They would say in reply that he is a madman or a pedant who\r\nfancies that he is a physician because he has read something in a\r\nbook, or has stumbled on a prescription or two, although he has no real\r\nunderstanding of the art of medicine.\r\n\r\nSOCRATES: And suppose a person were to come to Sophocles or Euripides\r\nand say that he knows how to make a very long speech about a small\r\nmatter, and a short speech about a great matter, and also a sorrowful\r\nspeech, or a terrible, or threatening speech, or any other kind of\r\nspeech, and in teaching this fancies that he is teaching the art of\r\ntragedy--?\r\n\r\nPHAEDRUS: They too would surely laugh at him if he fancies that tragedy\r\nis anything but the arranging of these elements in a manner which will\r\nbe suitable to one another and to the whole.\r\n\r\nSOCRATES: But I do not suppose that they would be rude or abusive to\r\nhim: Would they not treat him as a musician a man who thinks that he is\r\na harmonist because he knows how to pitch the highest and lowest note;\r\nhappening to meet such an one he would not say to him savagely, 'Fool,\r\nyou are mad!' But like a musician, in a gentle and harmonious tone of\r\nvoice, he would answer: 'My good friend, he who would be a harmonist\r\nmust certainly know this, and yet he may understand nothing of harmony\r\nif he has not got beyond your stage of knowledge, for you only know the\r\npreliminaries of harmony and not harmony itself.'\r\n\r\nPHAEDRUS: Very true.\r\n\r\nSOCRATES: And will not Sophocles say to the display of the would-be\r\ntragedian, that this is not tragedy but the preliminaries of tragedy?\r\nand will not Acumenus say the same of medicine to the would-be\r\nphysician?\r\n\r\nPHAEDRUS: Quite true.\r\n\r\nSOCRATES: And if Adrastus the mellifluous or Pericles heard of these\r\nwonderful arts, brachylogies and eikonologies and all the hard names\r\nwhich we have been endeavouring to draw into the light of day, what\r\nwould they say? Instead of losing temper and applying uncomplimentary\r\nepithets, as you and I have been doing, to the authors of such an\r\nimaginary art, their superior wisdom would rather censure us, as well\r\nas them. 'Have a little patience, Phaedrus and Socrates, they would say;\r\nyou should not be in such a passion with those who from some want of\r\ndialectical skill are unable to define the nature of rhetoric, and\r\nconsequently suppose that they have found the art in the preliminary\r\nconditions of it, and when these have been taught by them to others,\r\nfancy that the whole art of rhetoric has been taught by them; but as\r\nto using the several instruments of the art effectively, or making the\r\ncomposition a whole,--an application of it such as this is they regard\r\nas an easy thing which their disciples may make for themselves.'\r\n\r\nPHAEDRUS: I quite admit, Socrates, that the art of rhetoric which these\r\nmen teach and of which they write is such as you describe--there I\r\nagree with you. But I still want to know where and how the true art of\r\nrhetoric and persuasion is to be acquired.\r\n\r\nSOCRATES: The perfection which is required of the finished orator is,\r\nor rather must be, like the perfection of anything else; partly given by\r\nnature, but may also be assisted by art. If you have the natural power\r\nand add to it knowledge and practice, you will be a distinguished\r\nspeaker; if you fall short in either of these, you will be to that\r\nextent defective. But the art, as far as there is an art, of rhetoric\r\ndoes not lie in the direction of Lysias or Thrasymachus.\r\n\r\nPHAEDRUS: In what direction then?\r\n\r\nSOCRATES: I conceive Pericles to have been the most accomplished of\r\nrhetoricians.\r\n\r\nPHAEDRUS: What of that?\r\n\r\nSOCRATES: All the great arts require discussion and high speculation\r\nabout the truths of nature; hence come loftiness of thought and\r\ncompleteness of execution. And this, as I conceive, was the quality\r\nwhich, in addition to his natural gifts, Pericles acquired from his\r\nintercourse with Anaxagoras whom he happened to know. He was thus imbued\r\nwith the higher philosophy, and attained the knowledge of Mind and the\r\nnegative of Mind, which were favourite themes of Anaxagoras, and applied\r\nwhat suited his purpose to the art of speaking.\r\n\r\nPHAEDRUS: Explain.\r\n\r\nSOCRATES: Rhetoric is like medicine.\r\n\r\nPHAEDRUS: How so?\r\n\r\nSOCRATES: Why, because medicine has to define the nature of the body\r\nand rhetoric of the soul--if we would proceed, not empirically but\r\nscientifically, in the one case to impart health and strength by giving\r\nmedicine and food, in the other to implant the conviction or virtue\r\nwhich you desire, by the right application of words and training.\r\n\r\nPHAEDRUS: There, Socrates, I suspect that you are right.\r\n\r\nSOCRATES: And do you think that you can know the nature of the soul\r\nintelligently without knowing the nature of the whole?\r\n\r\nPHAEDRUS: Hippocrates the Asclepiad says that the nature even of the\r\nbody can only be understood as a whole. (Compare Charmides.)\r\n\r\nSOCRATES: Yes, friend, and he was right:--still, we ought not to be\r\ncontent with the name of Hippocrates, but to examine and see whether his\r\nargument agrees with his conception of nature.\r\n\r\nPHAEDRUS: I agree.\r\n\r\nSOCRATES: Then consider what truth as well as Hippocrates says about\r\nthis or about any other nature. Ought we not to consider first whether\r\nthat which we wish to learn and to teach is a simple or multiform thing,\r\nand if simple, then to enquire what power it has of acting or being\r\nacted upon in relation to other things, and if multiform, then to number\r\nthe forms; and see first in the case of one of them, and then in the\r\ncase of all of them, what is that power of acting or being acted upon\r\nwhich makes each and all of them to be what they are?\r\n\r\nPHAEDRUS: You may very likely be right, Socrates.\r\n\r\nSOCRATES: The method which proceeds without analysis is like the groping\r\nof a blind man. Yet, surely, he who is an artist ought not to admit of\r\na comparison with the blind, or deaf. The rhetorician, who teaches his\r\npupil to speak scientifically, will particularly set forth the nature of\r\nthat being to which he addresses his speeches; and this, I conceive, to\r\nbe the soul.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: His whole effort is directed to the soul; for in that he seeks\r\nto produce conviction.\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: Then clearly, Thrasymachus or any one else who teaches\r\nrhetoric in earnest will give an exact description of the nature of the\r\nsoul; which will enable us to see whether she be single and same, or,\r\nlike the body, multiform. That is what we should call showing the nature\r\nof the soul.\r\n\r\nPHAEDRUS: Exactly.\r\n\r\nSOCRATES: He will explain, secondly, the mode in which she acts or is\r\nacted upon.\r\n\r\nPHAEDRUS: True.\r\n\r\nSOCRATES: Thirdly, having classified men and speeches, and their kinds\r\nand affections, and adapted them to one another, he will tell the\r\nreasons of his arrangement, and show why one soul is persuaded by a\r\nparticular form of argument, and another not.\r\n\r\nPHAEDRUS: You have hit upon a very good way.\r\n\r\nSOCRATES: Yes, that is the true and only way in which any subject can\r\nbe set forth or treated by rules of art, whether in speaking or writing.\r\nBut the writers of the present day, at whose feet you have sat, craftily\r\nconceal the nature of the soul which they know quite well. Nor, until\r\nthey adopt our method of reading and writing, can we admit that they\r\nwrite by rules of art?\r\n\r\nPHAEDRUS: What is our method?\r\n\r\nSOCRATES: I cannot give you the exact details; but I should like to\r\ntell you generally, as far as is in my power, how a man ought to proceed\r\naccording to rules of art.\r\n\r\nPHAEDRUS: Let me hear.\r\n\r\nSOCRATES: Oratory is the art of enchanting the soul, and therefore he\r\nwho would be an orator has to learn the differences of human souls--they\r\nare so many and of such a nature, and from them come the differences\r\nbetween man and man. Having proceeded thus far in his analysis, he\r\nwill next divide speeches into their different classes:--'Such and such\r\npersons,' he will say, are affected by this or that kind of speech in\r\nthis or that way,' and he will tell you why. The pupil must have a good\r\ntheoretical notion of them first, and then he must have experience of\r\nthem in actual life, and be able to follow them with all his senses\r\nabout him, or he will never get beyond the precepts of his masters. But\r\nwhen he understands what persons are persuaded by what arguments, and\r\nsees the person about whom he was speaking in the abstract actually\r\nbefore him, and knows that it is he, and can say to himself, 'This is\r\nthe man or this is the character who ought to have a certain argument\r\napplied to him in order to convince him of a certain opinion;'--he who\r\nknows all this, and knows also when he should speak and when he should\r\nrefrain, and when he should use pithy sayings, pathetic appeals,\r\nsensational effects, and all the other modes of speech which he has\r\nlearned;--when, I say, he knows the times and seasons of all these\r\nthings, then, and not till then, he is a perfect master of his art; but\r\nif he fail in any of these points, whether in speaking or teaching or\r\nwriting them, and yet declares that he speaks by rules of art, he who\r\nsays 'I don't believe you' has the better of him. Well, the teacher will\r\nsay, is this, Phaedrus and Socrates, your account of the so-called art\r\nof rhetoric, or am I to look for another?\r\n\r\nPHAEDRUS: He must take this, Socrates, for there is no possibility of\r\nanother, and yet the creation of such an art is not easy.\r\n\r\nSOCRATES: Very true; and therefore let us consider this matter in every\r\nlight, and see whether we cannot find a shorter and easier road; there\r\nis no use in taking a long rough roundabout way if there be a shorter\r\nand easier one. And I wish that you would try and remember whether\r\nyou have heard from Lysias or any one else anything which might be of\r\nservice to us.\r\n\r\nPHAEDRUS: If trying would avail, then I might; but at the moment I can\r\nthink of nothing.\r\n\r\nSOCRATES: Suppose I tell you something which somebody who knows told me.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: May not 'the wolf,' as the proverb says, 'claim a hearing'?\r\n\r\nPHAEDRUS: Do you say what can be said for him.\r\n\r\nSOCRATES: He will argue that there is no use in putting a solemn face\r\non these matters, or in going round and round, until you arrive at first\r\nprinciples; for, as I said at first, when the question is of justice and\r\ngood, or is a question in which men are concerned who are just and good,\r\neither by nature or habit, he who would be a skilful rhetorician has\r\nno need of truth--for that in courts of law men literally care\r\nnothing about truth, but only about conviction: and this is based on\r\nprobability, to which he who would be a skilful orator should therefore\r\ngive his whole attention. And they say also that there are cases in\r\nwhich the actual facts, if they are improbable, ought to be withheld,\r\nand only the probabilities should be told either in accusation or\r\ndefence, and that always in speaking, the orator should keep probability\r\nin view, and say good-bye to the truth. And the observance of this\r\nprinciple throughout a speech furnishes the whole art.\r\n\r\nPHAEDRUS: That is what the professors of rhetoric do actually say,\r\nSocrates. I have not forgotten that we have quite briefly touched upon\r\nthis matter already; with them the point is all-important.\r\n\r\nSOCRATES: I dare say that you are familiar with Tisias. Does he not\r\ndefine probability to be that which the many think?\r\n\r\nPHAEDRUS: Certainly, he does.\r\n\r\nSOCRATES: I believe that he has a clever and ingenious case of this\r\nsort:--He supposes a feeble and valiant man to have assaulted a strong\r\nand cowardly one, and to have robbed him of his coat or of something or\r\nother; he is brought into court, and then Tisias says that both parties\r\nshould tell lies: the coward should say that he was assaulted by more\r\nmen than one; the other should prove that they were alone, and should\r\nargue thus: 'How could a weak man like me have assaulted a strong man\r\nlike him?' The complainant will not like to confess his own cowardice,\r\nand will therefore invent some other lie which his adversary will thus\r\ngain an opportunity of refuting. And there are other devices of the same\r\nkind which have a place in the system. Am I not right, Phaedrus?\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: Bless me, what a wonderfully mysterious art is this which\r\nTisias or some other gentleman, in whatever name or country he rejoices,\r\nhas discovered. Shall we say a word to him or not?\r\n\r\nPHAEDRUS: What shall we say to him?\r\n\r\nSOCRATES: Let us tell him that, before he appeared, you and I were\r\nsaying that the probability of which he speaks was engendered in the\r\nminds of the many by the likeness of the truth, and we had just been\r\naffirming that he who knew the truth would always know best how to\r\ndiscover the resemblances of the truth. If he has anything else to say\r\nabout the art of speaking we should like to hear him; but if not, we\r\nare satisfied with our own view, that unless a man estimates the various\r\ncharacters of his hearers and is able to divide all things into classes\r\nand to comprehend them under single ideas, he will never be a skilful\r\nrhetorician even within the limits of human power. And this skill he\r\nwill not attain without a great deal of trouble, which a good man ought\r\nto undergo, not for the sake of speaking and acting before men, but in\r\norder that he may be able to say what is acceptable to God and always\r\nto act acceptably to Him as far as in him lies; for there is a saying of\r\nwiser men than ourselves, that a man of sense should not try to please\r\nhis fellow-servants (at least this should not be his first object)\r\nbut his good and noble masters; and therefore if the way is long and\r\ncircuitous, marvel not at this, for, where the end is great, there we\r\nmay take the longer road, but not for lesser ends such as yours. Truly,\r\nthe argument may say, Tisias, that if you do not mind going so far,\r\nrhetoric has a fair beginning here.\r\n\r\nPHAEDRUS: I think, Socrates, that this is admirable, if only\r\npracticable.\r\n\r\nSOCRATES: But even to fail in an honourable object is honourable.\r\n\r\nPHAEDRUS: True.\r\n\r\nSOCRATES: Enough appears to have been said by us of a true and false art\r\nof speaking.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: But there is something yet to be said of propriety and\r\nimpropriety of writing.\r\n\r\nPHAEDRUS: Yes.\r\n\r\nSOCRATES: Do you know how you can speak or act about rhetoric in a\r\nmanner which will be acceptable to God?\r\n\r\nPHAEDRUS: No, indeed. Do you?\r\n\r\nSOCRATES: I have heard a tradition of the ancients, whether true or not\r\nthey only know; although if we had found the truth ourselves, do you\r\nthink that we should care much about the opinions of men?\r\n\r\nPHAEDRUS: Your question needs no answer; but I wish that you would tell\r\nme what you say that you have heard.\r\n\r\nSOCRATES: At the Egyptian city of Naucratis, there was a famous old god,\r\nwhose name was Theuth; the bird which is called the Ibis is sacred\r\nto him, and he was the inventor of many arts, such as arithmetic and\r\ncalculation and geometry and astronomy and draughts and dice, but his\r\ngreat discovery was the use of letters. Now in those days the god Thamus\r\nwas the king of the whole country of Egypt; and he dwelt in that great\r\ncity of Upper Egypt which the Hellenes call Egyptian Thebes, and the\r\ngod himself is called by them Ammon. To him came Theuth and showed his\r\ninventions, desiring that the other Egyptians might be allowed to have\r\nthe benefit of them; he enumerated them, and Thamus enquired about\r\ntheir several uses, and praised some of them and censured others, as he\r\napproved or disapproved of them. It would take a long time to repeat all\r\nthat Thamus said to Theuth in praise or blame of the various arts. But\r\nwhen they came to letters, This, said Theuth, will make the Egyptians\r\nwiser and give them better memories; it is a specific both for the\r\nmemory and for the wit. Thamus replied: O most ingenious Theuth, the\r\nparent or inventor of an art is not always the best judge of the utility\r\nor inutility of his own inventions to the users of them. And in this\r\ninstance, you who are the father of letters, from a paternal love of\r\nyour own children have been led to attribute to them a quality which\r\nthey cannot have; for this discovery of yours will create forgetfulness\r\nin the learners' souls, because they will not use their memories;\r\nthey will trust to the external written characters and not remember\r\nof themselves. The specific which you have discovered is an aid not to\r\nmemory, but to reminiscence, and you give your disciples not truth, but\r\nonly the semblance of truth; they will be hearers of many things and\r\nwill have learned nothing; they will appear to be omniscient and will\r\ngenerally know nothing; they will be tiresome company, having the show\r\nof wisdom without the reality.\r\n\r\nPHAEDRUS: Yes, Socrates, you can easily invent tales of Egypt, or of any\r\nother country.\r\n\r\nSOCRATES: There was a tradition in the temple of Dodona that oaks first\r\ngave prophetic utterances. The men of old, unlike in their simplicity to\r\nyoung philosophy, deemed that if they heard the truth even from 'oak or\r\nrock,' it was enough for them; whereas you seem to consider not whether\r\na thing is or is not true, but who the speaker is and from what country\r\nthe tale comes.\r\n\r\nPHAEDRUS: I acknowledge the justice of your rebuke; and I think that the\r\nTheban is right in his view about letters.\r\n\r\nSOCRATES: He would be a very simple person, and quite a stranger to the\r\noracles of Thamus or Ammon, who should leave in writing or receive\r\nin writing any art under the idea that the written word would be\r\nintelligible or certain; or who deemed that writing was at all better\r\nthan knowledge and recollection of the same matters?\r\n\r\nPHAEDRUS: That is most true.\r\n\r\nSOCRATES: I cannot help feeling, Phaedrus, that writing is unfortunately\r\nlike painting; for the creations of the painter have the attitude of\r\nlife, and yet if you ask them a question they preserve a solemn silence.\r\nAnd the same may be said of speeches. You would imagine that they had\r\nintelligence, but if you want to know anything and put a question to one\r\nof them, the speaker always gives one unvarying answer. And when they\r\nhave been once written down they are tumbled about anywhere among those\r\nwho may or may not understand them, and know not to whom they should\r\nreply, to whom not: and, if they are maltreated or abused, they have no\r\nparent to protect them; and they cannot protect or defend themselves.\r\n\r\nPHAEDRUS: That again is most true.\r\n\r\nSOCRATES: Is there not another kind of word or speech far better than\r\nthis, and having far greater power--a son of the same family, but\r\nlawfully begotten?\r\n\r\nPHAEDRUS: Whom do you mean, and what is his origin?\r\n\r\nSOCRATES: I mean an intelligent word graven in the soul of the learner,\r\nwhich can defend itself, and knows when to speak and when to be silent.\r\n\r\nPHAEDRUS: You mean the living word of knowledge which has a soul, and of\r\nwhich the written word is properly no more than an image?\r\n\r\nSOCRATES: Yes, of course that is what I mean. And now may I be allowed\r\nto ask you a question: Would a husbandman, who is a man of sense, take\r\nthe seeds, which he values and which he wishes to bear fruit, and in\r\nsober seriousness plant them during the heat of summer, in some garden\r\nof Adonis, that he may rejoice when he sees them in eight days appearing\r\nin beauty? at least he would do so, if at all, only for the sake of\r\namusement and pastime. But when he is in earnest he sows in fitting\r\nsoil, and practises husbandry, and is satisfied if in eight months the\r\nseeds which he has sown arrive at perfection?\r\n\r\nPHAEDRUS: Yes, Socrates, that will be his way when he is in earnest; he\r\nwill do the other, as you say, only in play.\r\n\r\nSOCRATES: And can we suppose that he who knows the just and good and\r\nhonourable has less understanding, than the husbandman, about his own\r\nseeds?\r\n\r\nPHAEDRUS: Certainly not.\r\n\r\nSOCRATES: Then he will not seriously incline to 'write' his thoughts\r\n'in water' with pen and ink, sowing words which can neither speak for\r\nthemselves nor teach the truth adequately to others?\r\n\r\nPHAEDRUS: No, that is not likely.\r\n\r\nSOCRATES: No, that is not likely--in the garden of letters he will sow\r\nand plant, but only for the sake of recreation and amusement; he will\r\nwrite them down as memorials to be treasured against the forgetfulness\r\nof old age, by himself, or by any other old man who is treading the same\r\npath. He will rejoice in beholding their tender growth; and while others\r\nare refreshing their souls with banqueting and the like, this will be\r\nthe pastime in which his days are spent.\r\n\r\nPHAEDRUS: A pastime, Socrates, as noble as the other is ignoble, the\r\npastime of a man who can be amused by serious talk, and can discourse\r\nmerrily about justice and the like.\r\n\r\nSOCRATES: True, Phaedrus. But nobler far is the serious pursuit of the\r\ndialectician, who, finding a congenial soul, by the help of science sows\r\nand plants therein words which are able to help themselves and him who\r\nplanted them, and are not unfruitful, but have in them a seed which\r\nothers brought up in different soils render immortal, making the\r\npossessors of it happy to the utmost extent of human happiness.\r\n\r\nPHAEDRUS: Far nobler, certainly.\r\n\r\nSOCRATES: And now, Phaedrus, having agreed upon the premises we may\r\ndecide about the conclusion.\r\n\r\nPHAEDRUS: About what conclusion?\r\n\r\nSOCRATES: About Lysias, whom we censured, and his art of writing, and\r\nhis discourses, and the rhetorical skill or want of skill which was\r\nshown in them--these are the questions which we sought to determine, and\r\nthey brought us to this point. And I think that we are now pretty well\r\ninformed about the nature of art and its opposite.\r\n\r\nPHAEDRUS: Yes, I think with you; but I wish that you would repeat what\r\nwas said.\r\n\r\nSOCRATES: Until a man knows the truth of the several particulars of\r\nwhich he is writing or speaking, and is able to define them as they are,\r\nand having defined them again to divide them until they can be no longer\r\ndivided, and until in like manner he is able to discern the nature\r\nof the soul, and discover the different modes of discourse which are\r\nadapted to different natures, and to arrange and dispose them in such\r\na way that the simple form of speech may be addressed to the simpler\r\nnature, and the complex and composite to the more complex nature--until\r\nhe has accomplished all this, he will be unable to handle arguments\r\naccording to rules of art, as far as their nature allows them to\r\nbe subjected to art, either for the purpose of teaching or\r\npersuading;--such is the view which is implied in the whole preceding\r\nargument.\r\n\r\nPHAEDRUS: Yes, that was our view, certainly.\r\n\r\nSOCRATES: Secondly, as to the censure which was passed on the speaking\r\nor writing of discourses, and how they might be rightly or wrongly\r\ncensured--did not our previous argument show--?\r\n\r\nPHAEDRUS: Show what?\r\n\r\nSOCRATES: That whether Lysias or any other writer that ever was or will\r\nbe, whether private man or statesman, proposes laws and so becomes\r\nthe author of a political treatise, fancying that there is any great\r\ncertainty and clearness in his performance, the fact of his so writing\r\nis only a disgrace to him, whatever men may say. For not to know the\r\nnature of justice and injustice, and good and evil, and not to be able\r\nto distinguish the dream from the reality, cannot in truth be otherwise\r\nthan disgraceful to him, even though he have the applause of the whole\r\nworld.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: But he who thinks that in the written word there is\r\nnecessarily much which is not serious, and that neither poetry\r\nnor prose, spoken or written, is of any great value, if, like the\r\ncompositions of the rhapsodes, they are only recited in order to be\r\nbelieved, and not with any view to criticism or instruction; and who\r\nthinks that even the best of writings are but a reminiscence of what we\r\nknow, and that only in principles of justice and goodness and nobility\r\ntaught and communicated orally for the sake of instruction and graven\r\nin the soul, which is the true way of writing, is there clearness and\r\nperfection and seriousness, and that such principles are a man's own and\r\nhis legitimate offspring;--being, in the first place, the word which\r\nhe finds in his own bosom; secondly, the brethren and descendants and\r\nrelations of his idea which have been duly implanted by him in the souls\r\nof others;--and who cares for them and no others--this is the right sort\r\nof man; and you and I, Phaedrus, would pray that we may become like him.\r\n\r\nPHAEDRUS: That is most assuredly my desire and prayer.\r\n\r\nSOCRATES: And now the play is played out; and of rhetoric enough. Go and\r\ntell Lysias that to the fountain and school of the Nymphs we went\r\ndown, and were bidden by them to convey a message to him and to other\r\ncomposers of speeches--to Homer and other writers of poems, whether set\r\nto music or not; and to Solon and others who have composed writings in\r\nthe form of political discourses which they would term laws--to all of\r\nthem we are to say that if their compositions are based on knowledge of\r\nthe truth, and they can defend or prove them, when they are put to the\r\ntest, by spoken arguments, which leave their writings poor in\r\ncomparison of them, then they are to be called, not only poets, orators,\r\nlegislators, but are worthy of a higher name, befitting the serious\r\npursuit of their life.\r\n\r\nPHAEDRUS: What name would you assign to them?\r\n\r\nSOCRATES: Wise, I may not call them; for that is a great name which\r\nbelongs to God alone,--lovers of wisdom or philosophers is their modest\r\nand befitting title.\r\n\r\nPHAEDRUS: Very suitable.\r\n\r\nSOCRATES: And he who cannot rise above his own compilations and\r\ncompositions, which he has been long patching and piecing, adding some\r\nand taking away some, may be justly called poet or speech-maker or\r\nlaw-maker.\r\n\r\nPHAEDRUS: Certainly.\r\n\r\nSOCRATES: Now go and tell this to your companion.\r\n\r\nPHAEDRUS: But there is also a friend of yours who ought not to be\r\nforgotten.\r\n\r\nSOCRATES: Who is he?\r\n\r\nPHAEDRUS: Isocrates the fair:--What message will you send to him, and\r\nhow shall we describe him?\r\n\r\nSOCRATES: Isocrates is still young, Phaedrus; but I am willing to hazard\r\na prophecy concerning him.\r\n\r\nPHAEDRUS: What would you prophesy?\r\n\r\nSOCRATES: I think that he has a genius which soars above the orations of\r\nLysias, and that his character is cast in a finer mould. My impression\r\nof him is that he will marvellously improve as he grows older, and that\r\nall former rhetoricians will be as children in comparison of him. And I\r\nbelieve that he will not be satisfied with rhetoric, but that there is\r\nin him a divine inspiration which will lead him to things higher still.\r\nFor he has an element of philosophy in his nature. This is the message\r\nof the gods dwelling in this place, and which I will myself deliver to\r\nIsocrates, who is my delight; and do you give the other to Lysias, who\r\nis yours.\r\n\r\nPHAEDRUS: I will; and now as the heat is abated let us depart.\r\n\r\nSOCRATES: Should we not offer up a prayer first of all to the local\r\ndeities?\r\n\r\nPHAEDRUS: By all means.\r\n\r\nSOCRATES: Beloved Pan, and all ye other gods who haunt this place, give\r\nme beauty in the inward soul; and may the outward and inward man be\r\nat one. May I reckon the wise to be the wealthy, and may I have such\r\na quantity of gold as a temperate man and he only can bear and\r\ncarry.--Anything more? The prayer, I think, is enough for me.\r\n\r\nPHAEDRUS: Ask the same for me, for friends should have all things in\r\ncommon.\r\n\r\nSOCRATES: Let us go.\r\n\r\n\r\n\r\n\r\n\r\nEnd of the Project Gutenberg EBook of Phaedrus, by Plato\r\n\r\n*** END OF THIS PROJECT GUTENBERG EBOOK PHAEDRUS ***\r\n\r\n***** This file should be named 1636.txt or 1636.zip *****\r\nThis and all associated files of various formats will be found in:\r\n http://www.gutenberg.org/1/6/3/1636/\r\n\r\nProduced by Sue Asscher\r\n\r\nUpdated editions will replace the previous one--the old editions\r\nwill be renamed.\r\n\r\nCreating the works from public domain print editions means that no\r\none owns a United States copyright in these works, so the Foundation\r\n(and you!) can copy and distribute it in the United States without\r\npermission and without paying copyright royalties. Special rules,\r\nset forth in the General Terms of Use part of this license, apply to\r\ncopying and distributing Project Gutenberg-tm electronic works to\r\nprotect the PROJECT GUTENBERG-tm concept and trademark. Project\r\nGutenberg is a registered trademark, and may not be used if you\r\ncharge for the eBooks, unless you receive specific permission. If you\r\ndo not charge anything for copies of this eBook, complying with the\r\nrules is very easy. You may use this eBook for nearly any purpose\r\nsuch as creation of derivative works, reports, performances and\r\nresearch. They may be modified and printed and given away--you may do\r\npractically ANYTHING with public domain eBooks. Redistribution is\r\nsubject to the trademark license, especially commercial\r\nredistribution.\r\n\r\n\r\n\r\n*** START: FULL LICENSE ***\r\n\r\nTHE FULL PROJECT GUTENBERG LICENSE\r\nPLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK\r\n\r\nTo protect the Project Gutenberg-tm mission of promoting the free\r\ndistribution of electronic works, by using or distributing this work\r\n(or any other work associated in any way with the phrase \"Project\r\nGutenberg\"), you agree to comply with all the terms of the Full Project\r\nGutenberg-tm License (available with this file or online at\r\nhttp://gutenberg.org/license).\r\n\r\n\r\nSection 1. General Terms of Use and Redistributing Project Gutenberg-tm\r\nelectronic works\r\n\r\n1.A. By reading or using any part of this Project Gutenberg-tm\r\nelectronic work, you indicate that you have read, understand, agree to\r\nand accept all the terms of this license and intellectual property\r\n(trademark/copyright) agreement. If you do not agree to abide by all\r\nthe terms of this agreement, you must cease using and return or destroy\r\nall copies of Project Gutenberg-tm electronic works in your possession.\r\nIf you paid a fee for obtaining a copy of or access to a Project\r\nGutenberg-tm electronic work and you do not agree to be bound by the\r\nterms of this agreement, you may obtain a refund from the person or\r\nentity to whom you paid the fee as set forth in paragraph 1.E.8.\r\n\r\n1.B. \"Project Gutenberg\" is a registered trademark. It may only be\r\nused on or associated in any way with an electronic work by people who\r\nagree to be bound by the terms of this agreement. There are a few\r\nthings that you can do with most Project Gutenberg-tm electronic works\r\neven without complying with the full terms of this agreement. See\r\nparagraph 1.C below. There are a lot of things you can do with Project\r\nGutenberg-tm electronic works if you follow the terms of this agreement\r\nand help preserve free future access to Project Gutenberg-tm electronic\r\nworks. See paragraph 1.E below.\r\n\r\n1.C. The Project Gutenberg Literary Archive Foundation (\"the Foundation\"\r\nor PGLAF), owns a compilation copyright in the collection of Project\r\nGutenberg-tm electronic works. Nearly all the individual works in the\r\ncollection are in the public domain in the United States. If an\r\nindividual work is in the public domain in the United States and you are\r\nlocated in the United States, we do not claim a right to prevent you from\r\ncopying, distributing, performing, displaying or creating derivative\r\nworks based on the work as long as all references to Project Gutenberg\r\nare removed. Of course, we hope that you will support the Project\r\nGutenberg-tm mission of promoting free access to electronic works by\r\nfreely sharing Project Gutenberg-tm works in compliance with the terms of\r\nthis agreement for keeping the Project Gutenberg-tm name associated with\r\nthe work. You can easily comply with the terms of this agreement by\r\nkeeping this work in the same format with its attached full Project\r\nGutenberg-tm License when you share it without charge with others.\r\n\r\n1.D. The copyright laws of the place where you are located also govern\r\nwhat you can do with this work. Copyright laws in most countries are in\r\na constant state of change. If you are outside the United States, check\r\nthe laws of your country in addition to the terms of this agreement\r\nbefore downloading, copying, displaying, performing, distributing or\r\ncreating derivative works based on this work or any other Project\r\nGutenberg-tm work. The Foundation makes no representations concerning\r\nthe copyright status of any work in any country outside the United\r\nStates.\r\n\r\n1.E. Unless you have removed all references to Project Gutenberg:\r\n\r\n1.E.1. The following sentence, with active links to, or other immediate\r\naccess to, the full Project Gutenberg-tm License must appear prominently\r\nwhenever any copy of a Project Gutenberg-tm work (any work on which the\r\nphrase \"Project Gutenberg\" appears, or with which the phrase \"Project\r\nGutenberg\" is associated) is accessed, displayed, performed, viewed,\r\ncopied or distributed:\r\n\r\nThis eBook is for the use of anyone anywhere at no cost and with\r\nalmost no restrictions whatsoever. You may copy it, give it away or\r\nre-use it under the terms of the Project Gutenberg License included\r\nwith this eBook or online at www.gutenberg.org\r\n\r\n1.E.2. If an individual Project Gutenberg-tm electronic work is derived\r\nfrom the public domain (does not contain a notice indicating that it is\r\nposted with permission of the copyright holder), the work can be copied\r\nand distributed to anyone in the United States without paying any fees\r\nor charges. If you are redistributing or providing access to a work\r\nwith the phrase \"Project Gutenberg\" associated with or appearing on the\r\nwork, you must comply either with the requirements of paragraphs 1.E.1\r\nthrough 1.E.7 or obtain permission for the use of the work and the\r\nProject Gutenberg-tm trademark as set forth in paragraphs 1.E.8 or\r\n1.E.9.\r\n\r\n1.E.3. If an individual Project Gutenberg-tm electronic work is posted\r\nwith the permission of the copyright holder, your use and distribution\r\nmust comply with both paragraphs 1.E.1 through 1.E.7 and any additional\r\nterms imposed by the copyright holder. Additional terms will be linked\r\nto the Project Gutenberg-tm License for all works posted with the\r\npermission of the copyright holder found at the beginning of this work.\r\n\r\n1.E.4. Do not unlink or detach or remove the full Project Gutenberg-tm\r\nLicense terms from this work, or any files containing a part of this\r\nwork or any other work associated with Project Gutenberg-tm.\r\n\r\n1.E.5. Do not copy, display, perform, distribute or redistribute this\r\nelectronic work, or any part of this electronic work, without\r\nprominently displaying the sentence set forth in paragraph 1.E.1 with\r\nactive links or immediate access to the full terms of the Project\r\nGutenberg-tm License.\r\n\r\n1.E.6. You may convert to and distribute this work in any binary,\r\ncompressed, marked up, nonproprietary or proprietary form, including any\r\nword processing or hypertext form. However, if you provide access to or\r\ndistribute copies of a Project Gutenberg-tm work in a format other than\r\n\"Plain Vanilla ASCII\" or other format used in the official version\r\nposted on the official Project Gutenberg-tm web site (www.gutenberg.org),\r\nyou must, at no additional cost, fee or expense to the user, provide a\r\ncopy, a means of exporting a copy, or a means of obtaining a copy upon\r\nrequest, of the work in its original \"Plain Vanilla ASCII\" or other\r\nform. Any alternate format must include the full Project Gutenberg-tm\r\nLicense as specified in paragraph 1.E.1.\r\n\r\n1.E.7. Do not charge a fee for access to, viewing, displaying,\r\nperforming, copying or distributing any Project Gutenberg-tm works\r\nunless you comply with paragraph 1.E.8 or 1.E.9.\r\n\r\n1.E.8. You may charge a reasonable fee for copies of or providing\r\naccess to or distributing Project Gutenberg-tm electronic works provided\r\nthat\r\n\r\n- You pay a royalty fee of 20% of the gross profits you derive from\r\n the use of Project Gutenberg-tm works calculated using the method\r\n you already use to calculate your applicable taxes. The fee is\r\n owed to the owner of the Project Gutenberg-tm trademark, but he\r\n has agreed to donate royalties under this paragraph to the\r\n Project Gutenberg Literary Archive Foundation. Royalty payments\r\n must be paid within 60 days following each date on which you\r\n prepare (or are legally required to prepare) your periodic tax\r\n returns. Royalty payments should be clearly marked as such and\r\n sent to the Project Gutenberg Literary Archive Foundation at the\r\n address specified in Section 4, \"Information about donations to\r\n the Project Gutenberg Literary Archive Foundation.\"\r\n\r\n- You provide a full refund of any money paid by a user who notifies\r\n you in writing (or by e-mail) within 30 days of receipt that s/he\r\n does not agree to the terms of the full Project Gutenberg-tm\r\n License. You must require such a user to return or\r\n destroy all copies of the works possessed in a physical medium\r\n and discontinue all use of and all access to other copies of\r\n Project Gutenberg-tm works.\r\n\r\n- You provide, in accordance with paragraph 1.F.3, a full refund of any\r\n money paid for a work or a replacement copy, if a defect in the\r\n electronic work is discovered and reported to you within 90 days\r\n of receipt of the work.\r\n\r\n- You comply with all other terms of this agreement for free\r\n distribution of Project Gutenberg-tm works.\r\n\r\n1.E.9. If you wish to charge a fee or distribute a Project Gutenberg-tm\r\nelectronic work or group of works on different terms than are set\r\nforth in this agreement, you must obtain permission in writing from\r\nboth the Project Gutenberg Literary Archive Foundation and Michael\r\nHart, the owner of the Project Gutenberg-tm trademark. Contact the\r\nFoundation as set forth in Section 3 below.\r\n\r\n1.F.\r\n\r\n1.F.1. Project Gutenberg volunteers and employees expend considerable\r\neffort to identify, do copyright research on, transcribe and proofread\r\npublic domain works in creating the Project Gutenberg-tm\r\ncollection. Despite these efforts, Project Gutenberg-tm electronic\r\nworks, and the medium on which they may be stored, may contain\r\n\"Defects,\" such as, but not limited to, incomplete, inaccurate or\r\ncorrupt data, transcription errors, a copyright or other intellectual\r\nproperty infringement, a defective or damaged disk or other medium, a\r\ncomputer virus, or computer codes that damage or cannot be read by\r\nyour equipment.\r\n\r\n1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the \"Right\r\nof Replacement or Refund\" described in paragraph 1.F.3, the Project\r\nGutenberg Literary Archive Foundation, the owner of the Project\r\nGutenberg-tm trademark, and any other party distributing a Project\r\nGutenberg-tm electronic work under this agreement, disclaim all\r\nliability to you for damages, costs and expenses, including legal\r\nfees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT\r\nLIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE\r\nPROVIDED IN PARAGRAPH F3. YOU AGREE THAT THE FOUNDATION, THE\r\nTRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE\r\nLIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR\r\nINCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH\r\nDAMAGE.\r\n\r\n1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a\r\ndefect in this electronic work within 90 days of receiving it, you can\r\nreceive a refund of the money (if any) you paid for it by sending a\r\nwritten explanation to the person you received the work from. If you\r\nreceived the work on a physical medium, you must return the medium with\r\nyour written explanation. The person or entity that provided you with\r\nthe defective work may elect to provide a replacement copy in lieu of a\r\nrefund. If you received the work electronically, the person or entity\r\nproviding it to you may choose to give you a second opportunity to\r\nreceive the work electronically in lieu of a refund. If the second copy\r\nis also defective, you may demand a refund in writing without further\r\nopportunities to fix the problem.\r\n\r\n1.F.4. Except for the limited right of replacement or refund set forth\r\nin paragraph 1.F.3, this work is provided to you 'AS-IS' WITH NO OTHER\r\nWARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\r\nWARRANTIES OF MERCHANTIBILITY OR FITNESS FOR ANY PURPOSE.\r\n\r\n1.F.5. Some states do not allow disclaimers of certain implied\r\nwarranties or the exclusion or limitation of certain types of damages.\r\nIf any disclaimer or limitation set forth in this agreement violates the\r\nlaw of the state applicable to this agreement, the agreement shall be\r\ninterpreted to make the maximum disclaimer or limitation permitted by\r\nthe applicable state law. The invalidity or unenforceability of any\r\nprovision of this agreement shall not void the remaining provisions.\r\n\r\n1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the\r\ntrademark owner, any agent or employee of the Foundation, anyone\r\nproviding copies of Project Gutenberg-tm electronic works in accordance\r\nwith this agreement, and any volunteers associated with the production,\r\npromotion and distribution of Project Gutenberg-tm electronic works,\r\nharmless from all liability, costs and expenses, including legal fees,\r\nthat arise directly or indirectly from any of the following which you do\r\nor cause to occur: (a) distribution of this or any Project Gutenberg-tm\r\nwork, (b) alteration, modification, or additions or deletions to any\r\nProject Gutenberg-tm work, and (c) any Defect you cause.\r\n\r\n\r\nSection 2. Information about the Mission of Project Gutenberg-tm\r\n\r\nProject Gutenberg-tm is synonymous with the free distribution of\r\nelectronic works in formats readable by the widest variety of computers\r\nincluding obsolete, old, middle-aged and new computers. It exists\r\nbecause of the efforts of hundreds of volunteers and donations from\r\npeople in all walks of life.\r\n\r\nVolunteers and financial support to provide volunteers with the\r\nassistance they need, is critical to reaching Project Gutenberg-tm's\r\ngoals and ensuring that the Project Gutenberg-tm collection will\r\nremain freely available for generations to come. In 2001, the Project\r\nGutenberg Literary Archive Foundation was created to provide a secure\r\nand permanent future for Project Gutenberg-tm and future generations.\r\nTo learn more about the Project Gutenberg Literary Archive Foundation\r\nand how your efforts and donations can help, see Sections 3 and 4\r\nand the Foundation web page at http://www.pglaf.org.\r\n\r\n\r\nSection 3. Information about the Project Gutenberg Literary Archive\r\nFoundation\r\n\r\nThe Project Gutenberg Literary Archive Foundation is a non profit\r\n501(c)(3) educational corporation organized under the laws of the\r\nstate of Mississippi and granted tax exempt status by the Internal\r\nRevenue Service. The Foundation's EIN or federal tax identification\r\nnumber is 64-6221541. Its 501(c)(3) letter is posted at\r\nhttp://pglaf.org/fundraising. Contributions to the Project Gutenberg\r\nLiterary Archive Foundation are tax deductible to the full extent\r\npermitted by U.S. federal laws and your state's laws.\r\n\r\nThe Foundation's principal office is located at 4557 Melan Dr. S.\r\nFairbanks, AK, 99712., but its volunteers and employees are scattered\r\nthroughout numerous locations. Its business office is located at\r\n809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887, email\r\[email protected]. Email contact links and up to date contact\r\ninformation can be found at the Foundation's web site and official\r\npage at http://pglaf.org\r\n\r\nFor additional contact information:\r\n Dr. Gregory B. Newby\r\n Chief Executive and Director\r\n [email protected]\r\n\r\n\r\nSection 4. Information about Donations to the Project Gutenberg\r\nLiterary Archive Foundation\r\n\r\nProject Gutenberg-tm depends upon and cannot survive without wide\r\nspread public support and donations to carry out its mission of\r\nincreasing the number of public domain and licensed works that can be\r\nfreely distributed in machine readable form accessible by the widest\r\narray of equipment including outdated equipment. Many small donations\r\n($1 to $5,000) are particularly important to maintaining tax exempt\r\nstatus with the IRS.\r\n\r\nThe Foundation is committed to complying with the laws regulating\r\ncharities and charitable donations in all 50 states of the United\r\nStates. Compliance requirements are not uniform and it takes a\r\nconsiderable effort, much paperwork and many fees to meet and keep up\r\nwith these requirements. We do not solicit donations in locations\r\nwhere we have not received written confirmation of compliance. To\r\nSEND DONATIONS or determine the status of compliance for any\r\nparticular state visit http://pglaf.org\r\n\r\nWhile we cannot and do not solicit contributions from states where we\r\nhave not met the solicitation requirements, we know of no prohibition\r\nagainst accepting unsolicited donations from donors in such states who\r\napproach us with offers to donate.\r\n\r\nInternational donations are gratefully accepted, but we cannot make\r\nany statements concerning tax treatment of donations received from\r\noutside the United States. U.S. laws alone swamp our small staff.\r\n\r\nPlease check the Project Gutenberg Web pages for current donation\r\nmethods and addresses. Donations are accepted in a number of other\r\nways including checks, online payments and credit card donations.\r\nTo donate, please visit: http://pglaf.org/donate\r\n\r\n\r\nSection 5. General Information About Project Gutenberg-tm electronic\r\nworks.\r\n\r\nProfessor Michael S. Hart is the originator of the Project Gutenberg-tm\r\nconcept of a library of electronic works that could be freely shared\r\nwith anyone. For thirty years, he produced and distributed Project\r\nGutenberg-tm eBooks with only a loose network of volunteer support.\r\n\r\n\r\nProject Gutenberg-tm eBooks are often created from several printed\r\neditions, all of which are confirmed as Public Domain in the U.S.\r\nunless a copyright notice is included. Thus, we do not necessarily\r\nkeep eBooks in compliance with any particular paper edition.\r\n\r\n\r\nMost people start at our Web site which has the main PG search facility:\r\n\r\n http://www.gutenberg.org\r\n\r\nThis Web site includes information about Project Gutenberg-tm,\r\nincluding how to make donations to the Project Gutenberg Literary\r\nArchive Foundation, how to help produce our new eBooks, and how to\r\nsubscribe to our email newsletter to hear about new eBooks.\r\n\n" ], [ "import urllib.request\npath = 'http://www.gutenberg.org/cache/epub/1636/pg1636.txt'\nwith urllib.request.urlopen(path) as response:\n fullDialogue = response.read().decode('utf-8')\nprint(fullDialogue[:100])", "The Project Gutenberg EBook of Phaedrus, by Plato\r\n\r\nThis eBook is for the use of anyone anywhere a\n" ], [ "fullDialogue.find(\"truth\")", "_____no_output_____" ], [ "fullDialogue.count(\"truth\")", "_____no_output_____" ], [ "fullDialogue.find(\"truth\",10746)", "_____no_output_____" ], [ "def printHello(name):\n print(\"Hello \" + name + \"!\")", "_____no_output_____" ], [ "name2Get = input(\"What is your name? \")\nprintHello(name2Get)", "What is your name? Farshid\nHello Farshid!\n" ], [ "def pullText(index,what):\n leftInd = index - 50\n rightInd = index + 50\n theFound = what[leftInd:rightInd]\n return theFound", "_____no_output_____" ], [ "print(pullText(10745,fullDialogue))", "h contention, to turn away and leave the plain of truth. But if\r\nthe soul has followed in the train \n" ], [ "def pullText2(index,what):\n leftInd = index - 50\n rightInd = index + 50\n theFound = what[leftInd:rightInd].replace(\"\\r\\n\",\" \")\n return theFound\n\nprint(pullText2(10745,fullDialogue))", "h contention, to turn away and leave the plain of truth. But if the soul has followed in the train \n" ], [ "for sa in range(3):\n print(\"Hello\")", "Hello\nHello\nHello\n" ], [ "names2Salute = [\"Mary\",\"Margaret\",\"Meredith\"]\n\ndef printHello(name):\n print(\"Hello \" + name + \"!\")\nfor theName in names2Salute:\n printHello(theName)", "Hello Mary!\nHello Margaret!\nHello Meredith!\n" ], [ "theCount = range(fullDialogue.count(\"truth\"))\n\nfor instance in theCount:\n print(str(instance))", "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "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" ] ]
ec52e4c4736fb53838246da8817619918969e322
39,433
ipynb
Jupyter Notebook
models/stockCNN0209.ipynb
cali-in-cau/auto-ta-ml
0b32b5350120001b3eb31fcb9043b66c088a2a6f
[ "Xnet", "X11" ]
5
2021-01-22T10:37:49.000Z
2022-01-15T09:37:19.000Z
models/stockCNN0209.ipynb
cali-in-cau/auto-ta-ml
0b32b5350120001b3eb31fcb9043b66c088a2a6f
[ "Xnet", "X11" ]
null
null
null
models/stockCNN0209.ipynb
cali-in-cau/auto-ta-ml
0b32b5350120001b3eb31fcb9043b66c088a2a6f
[ "Xnet", "X11" ]
3
2021-01-23T11:41:58.000Z
2021-06-29T11:24:26.000Z
79.024048
21,924
0.74496
[ [ [ "!pip install fastai --upgrade -q\n!pip install google\n!pip install kornia\n", "Requirement already satisfied: google in /home/super/anaconda3/envs/fastai/lib/python3.8/site-packages (3.0.0)\nRequirement already satisfied: beautifulsoup4 in /home/super/anaconda3/envs/fastai/lib/python3.8/site-packages (from google) (4.9.3)\nRequirement already satisfied: soupsieve>1.2 in /home/super/anaconda3/envs/fastai/lib/python3.8/site-packages (from beautifulsoup4->google) (2.1)\nCollecting kornia\n Downloading kornia-0.4.1-py2.py3-none-any.whl (225 kB)\n\u001b[K |████████████████████████████████| 225 kB 1.9 MB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: numpy in /home/super/anaconda3/envs/fastai/lib/python3.8/site-packages (from kornia) (1.19.2)\nRequirement already satisfied: torch>=1.6.0 in /home/super/anaconda3/envs/fastai/lib/python3.8/site-packages (from kornia) (1.7.1)\nRequirement already satisfied: typing_extensions in /home/super/anaconda3/envs/fastai/lib/python3.8/site-packages (from torch>=1.6.0->kornia) (3.7.4.3)\nInstalling collected packages: kornia\nSuccessfully installed kornia-0.4.1\n" ], [ "from fastai.vision.all import *\nfrom kornia import rgb_to_grayscale", "_____no_output_____" ], [ "#!unzip data/top20.zip -d data/top20", "_____no_output_____" ], [ "chart_class = ['CDLENGULFING_BULL', 'CDLENGULFING_BEAR', 'CDLSHORTLINE_BULL', 'CDLSHORTLINE_BEAR', 'CDLHIKKAKE_BULL', 'CDLHARAMI_BULL', 'CDLBELTHOLD_BULL', 'CDLHIKKAKE_BEAR', 'CDLHARAMI_BEAR', 'CDLBELTHOLD_BEAR', 'CDLLONGLINE_BULL', 'CDLLONGLINE_BEAR', 'CDLCLOSINGMARUBOZU_BULL', 'CDLHIGHWAVE_BEAR', 'CDLCLOSINGMARUBOZU_BEAR', 'CDLDOJI_BULL', 'CDLRICKSHAWMAN_BULL', 'CDLSPINNINGTOP_BULL', 'CDLHIGHWAVE_BULL', 'CDLSPINNINGTOP_BEAR', 'CDLLONGLEGGEDDOJI_BULL']\nprint(\"numer of class : {0}\".format(len(chart_class)))\nroot_dir = 'data'\n#base_dir = root_dir + '/top20'\n#base_dir = root_dir + '/top10'\nbase_dir = root_dir + '/2018-3year-5days-nasdaqtop300-new-reduced'\npath = Path(base_dir)\nprint(path)", "numer of class : 21\ndata/2018-3year-5days-nasdaqtop300-new-reduced\n" ], [ "class RGB2GreyTransform(DisplayedTransform):\n order = 15 # run after IntToFloatTransform\n def encodes(self, o:TensorImage):\n c = o.shape[1]\n return rgb_to_grayscale(o).expand(-1,c,-1,-1)\n \ncharts = DataBlock(blocks=(ImageBlock, CategoryBlock),\n get_items=get_image_files,\n get_y=parent_label,\n splitter=RandomSplitter(valid_pct=0.2, seed=42),\n #item_tfms=Resize(400),\n# 288*201\n batch_tfms = [IntToFloatTensor(), RGB2GreyTransform()])\n #item_tfms=RandomResizedCrop(224, min_scale=0.5)\n #batch_tfms=aug_transforms()", "_____no_output_____" ], [ "dls = charts.dataloaders(path)", "_____no_output_____" ], [ "dls.train.show_batch(max_n=8, nrows=2)", "_____no_output_____" ], [ "torch.cuda.empty_cache()\nlearn = cnn_learner(dls, resnet34, loss_func=CrossEntropyLossFlat(), metrics=accuracy)\nlearn.model = torch.nn.DataParallel(learn.model, device_ids=[0,1,2,3,4,5,6,7])\n#learn.model.to(f'cuda:{learn.model.device_ids[0]}')\n\n#서버 multiple gpu 8대\nlearn.fine_tune(15)\n#사용할수 있는 learner, epoch숫자는 어떻게 변하는가?\n#mnasnet이랑 resnet152, densenet161, 돌려보기\n#metrics== accuracy로 돌려볼것\n\n\n# import torch\n\n# torch.cuda.empty_cache()\n# learn = cnn_learner(dls, resnet50, metrics=error_rate)\n# #learn.model = torch.nn.DataParallel(learn.model, device_ids=[0, 1,2,3,4,5,6,7])\n# #lr_min, lr_steep = learn.lr_find()\n# learn.fine_tune(15)", "_____no_output_____" ], [ "#dls.vocab", "_____no_output_____" ], [ "interp = ClassificationInterpretation.from_learner(learn)\ninterp.print_classification_report()", "_____no_output_____" ], [ "pkl_name = \"2016-5year-5days-nasdaqtop300-reduced-wb-5000.pkl\"\nlearn.model = learn.model.module\nlearn.export(pkl_name)\npath = Path()\npath.ls(file_exts=pkl_name)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec53125cb6acc657cab8cff0597e7203582ec2a1
85,579
ipynb
Jupyter Notebook
lab 10/yxu29.ipynb
topseer/APL_Great
7ae3bd06e4d520d023bc9b992c88b6e3c758d551
[ "MIT" ]
null
null
null
lab 10/yxu29.ipynb
topseer/APL_Great
7ae3bd06e4d520d023bc9b992c88b6e3c758d551
[ "MIT" ]
null
null
null
lab 10/yxu29.ipynb
topseer/APL_Great
7ae3bd06e4d520d023bc9b992c88b6e3c758d551
[ "MIT" ]
null
null
null
99.742424
24,216
0.801961
[ [ [ "# Lab 10 - Linear Models", "_____no_output_____" ] ], [ [ "% matplotlib inline", "_____no_output_____" ] ], [ [ "## Directions\n\n**Failure to follow the directions will result in a \"0\"**\n\nThe due dates for each are indicated in the Syllabus and the course calendar. If anything is unclear, please email [email protected] the official email for the course or ask questions in the Lab discussion area on Blackboard.\n\nThe Labs also present technical material that augments the lectures and \"book\". You should read through the entire lab at the start of each module.\n\n### General Instructions\n\n1. You will be submitting your assignment to Blackboard. If there are no accompanying files, you should submit *only* your notebook and it should be named using *only* your JHED id: fsmith79.ipynb for example if your JHED id were \"fsmith79\". If the assignment requires additional files, you should name the *folder/directory* your JHED id and put all items in that folder/directory, ZIP it up (only ZIP...no other compression), and submit it to Blackboard.\n \n * do **not** use absolute paths in your notebooks. All resources should appear in the same directory as the rest of your assignments.\n * the directory **must** be named your JHED id and **only** your JHED id.\n \n2. Data Science is as much about what you write (communicating) as the code you execute (researching). In many places, you will be required to execute code and discuss both the purpose and the result. Additionally, Data Science is about reproducibility and transparency. This includes good communication with your team and possibly with yourself. Therefore, you must show **all** work.\n\n3. Avail yourself of the Markdown/Codecell nature of the notebook. If you don't know about Markdown, look it up. Your notebooks should not look like ransom notes. Don't make everything bold. Clearly indicate what question you are answering.\n\n4. Submit a cleanly executed notebook. It should say `In [1]` for the first codecell and increase by 1 throughout.", "_____no_output_____" ], [ "## Linear Regression\n\nIn a previous module (Lab 5), you performed EDA on the insurance data set. In this Lab, you should build a linear regression model trying to estimate `charges`.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport random as py_random\nimport numpy.random as np_random\nimport time\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport scipy.stats as stats\n\nsns.set(style=\"whitegrid\")", "_____no_output_____" ] ], [ [ "# Answer", "_____no_output_____" ] ], [ [ "data_raw = pd.read_csv(\"insurance.csv\")\n\ndata_raw.head()", "_____no_output_____" ] ], [ [ "## Transfer categorical data to dummy variables ", "_____no_output_____" ] ], [ [ "data = pd.get_dummies(data_raw)\ndata.head()", "_____no_output_____" ], [ "data.describe()", "_____no_output_____" ] ], [ [ "## Transform \"charges\" to \"log (charges + 1)\"", "_____no_output_____" ] ], [ [ "sns.distplot(np.log1p(data.charges))\nplt.show()\nsns.distplot(data.charges)\ndata.charges = np.log1p(data.charges)", "_____no_output_____" ] ], [ [ "## Check NA/Null values. Found no NAs", "_____no_output_____" ] ], [ [ "data.isnull().values.any() \n#data = data.fillna(data.mean()) ", "_____no_output_____" ] ], [ [ "## A Simple Liner Regression Model", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LinearRegression\n\nindpendent_variables = [i for i in data.dtypes.index if i != \"charges\"]\ndpendent_variables = \"charges\"\n\nX = data[indpendent_variables]\ny = data[dpendent_variables]\n\nreg = LinearRegression().fit(X, y)\nreg.score(X, y)", "_____no_output_____" ] ], [ [ "## Train and Test", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import cross_val_score\n\nnp.sqrt(-cross_val_score(reg, X, y, cv=5, scoring=\"neg_mean_squared_error\"))", "_____no_output_____" ], [ "cross_val_score(reg, X, y, cv=5, scoring=\"r2\") ", "_____no_output_____" ], [ "from sklearn.linear_model import Ridge, RidgeCV, ElasticNet, LassoCV, LassoLarsCV\n\ndef rmse_cv(model):\n rmse= np.sqrt(-cross_val_score(model, X, y, scoring=\"neg_mean_squared_error\", cv = 5))\n return(rmse)\n\nmodel_ridge = Ridge()\n\nalphas = [0.05, 0.1, 0.3, 1, 3, 5, 10, 15, 30, 50, 75,100]\ncv_ridge = [rmse_cv(Ridge(alpha = alpha)).mean() \n for alpha in alphas]", "_____no_output_____" ], [ "cv_ridge = pd.Series(cv_ridge, index = alphas)\ncv_ridge.plot(title = \"Validation - Just Do It\")\nplt.xlabel(\"alpha\")\nplt.ylabel(\"rmse\")", "_____no_output_____" ], [ "cv_ridge.min()", "_____no_output_____" ], [ "model_lasso = LassoCV(alphas = [1, 0.1, 0.001, 0.0005]).fit(X, y)", "_____no_output_____" ], [ "rmse_cv(model_lasso).mean()", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
ec531d73244b432662836c327cda6da27f35e47c
8,336
ipynb
Jupyter Notebook
Lesson 2_Python_Refresher/Functions & Generators/class.ipynb
majorhenry/animated-journey
26d0f23d54825566245883dfa3d3444cde8a6017
[ "MIT" ]
null
null
null
Lesson 2_Python_Refresher/Functions & Generators/class.ipynb
majorhenry/animated-journey
26d0f23d54825566245883dfa3d3444cde8a6017
[ "MIT" ]
null
null
null
Lesson 2_Python_Refresher/Functions & Generators/class.ipynb
majorhenry/animated-journey
26d0f23d54825566245883dfa3d3444cde8a6017
[ "MIT" ]
null
null
null
46.311111
1,022
0.551224
[ [ [ "Exercise 1\nNow let's assume that the current month is April, and you want to use a Person class to help make use of information about the friends in \nyour contacts list. In particular, you'd like to increment the age of all of your friends with birthdays in April. You would also like to \nknow who they are, along with their current ages, so you can send them birthday cards. Finally, you would also like to figure out which month \nhas the most friends with birthdays, so you can budget for all of the birthday cards you will need to buy.\n\nIn the following exercise, the Person class will be provided for you, and you will be working with a list of instances of the class, representing \nfriends in your contacts. This list is stored in the variable people.\n\nTo complete the exercise, you will need to do two things:\n\nComplete the function get_april_birthdays(people). This function should return a dictionary with each name of your friend with an April birthday as \na key, and their updated age as the value.\nComplete the function get_most_common_month(people). This function should return the name of the month with the most number of birthdays among your friends.\nThere is some testing code provided in test(), and there are more specific TODO instructions in each of the two functions mentioned.", "_____no_output_____" ] ], [ [ "class Person:\n def __init__(self, name, age, month):\n self.name = name\n self.age = age\n self.birthday_month = month\n \n def birthday(self):\n self.age += 1\n\ndef create_person_objects(names, ages, months):\n my_data = zip(names, ages, months)\n person_objects = []\n for item in my_data:\n person_objects.append(Person(*item))\n return person_objects\n\ndef get_april_birthdays(people):\n # TODO:\n # Increment \"age\" for all people with birthdays in April.\n # Return a dictionary \"april_birthdays\" with the names of\n # all people with April birthdays as keys, and their updated ages \n # as values. See the test below for an example expected output.\n april_birthdays = {}\n\n \n # TODO: Modify the return statement \n return\n\ndef get_most_common_month(people):\n # TODO:\n # Use the \"months\" dictionary to record counts of birthday months\n # for persons in the \"people\" data.\n # Return the month with the largest number of birthdays.\n months = {'January':0, 'February':0, 'March':0, 'April':0, 'May':0, \n 'June':0, 'July':0, 'August':0, 'September':0, 'October':0,\n 'November':0, 'December':0}\n \n # TODO: Modify the return statement.\n return\n\n\ndef test():\n # Here is the data for the test. Assume there is a single most common month.\n names = ['Howard', 'Richard', 'Jules', 'Trula', 'Michael', 'Elizabeth', 'Richard', 'Shirley', 'Mark', 'Brianna', 'Kenneth', 'Gwen', 'William', 'Rosa', 'Denver', 'Shelly', 'Sammy', 'Maryann', 'Kathleen', 'Andrew', 'Joseph', 'Kathleen', 'Lisa', 'Viola', 'George', 'Bonnie', 'Robert', 'William', 'Sabrina', 'John', 'Robert', 'Gil', 'Calvin', 'Robert', 'Dusty', 'Dario', 'Joeann', 'Terry', 'Alan', 'Rosa', 'Jeane', 'James', 'Rachel', 'Tu', 'Chelsea', 'Andrea', 'Ernest', 'Erica', 'Priscilla', 'Carol', 'Michael', 'Dale', 'Arthur', 'Helen', 'James', 'Donna', 'Patricia', 'Betty', 'Patricia', 'Mollie', 'Nicole', 'Ernest', 'Wendy', 'Graciela', 'Teresa', 'Nicole', 'Trang', 'Caleb', 'Robert', 'Paul', 'Nieves', 'Arleen', 'Milton', 'James', 'Lawrence', 'Edward', 'Susan', 'Patricia', 'Tana', 'Jessica', 'Suzanne', 'Darren', 'Arthur', 'Holly', 'Mary', 'Randal', 'John', 'Laura', 'Betty', 'Chelsea', 'Margaret', 'Angel', 'Jeffrey', 'Mary', 'Donald', 'David', 'Roger', 'Evan', 'Danny', 'William']\n ages = [17, 58, 79, 8, 10, 57, 4, 98, 19, 47, 81, 68, 48, 13, 39, 21, 98, 51, 49, 12, 24, 78, 36, 59, 3, 87, 94, 85, 43, 69, 15, 52, 57, 36, 52, 5, 52, 5, 33, 10, 71, 28, 70, 9, 25, 28, 76, 71, 22, 35, 35, 100, 9, 95, 69, 52, 66, 91, 39, 84, 65, 29, 20, 98, 30, 83, 30, 15, 88, 89, 24, 98, 62, 94, 86, 63, 34, 23, 23, 19, 10, 80, 88, 67, 17, 91, 85, 97, 29, 7, 34, 38, 92, 29, 14, 52, 94, 62, 70, 22]\n months = ['January', 'March', 'January', 'October', 'April', 'February', 'August', 'January', 'June', 'August', 'February', 'May', 'March', 'June', 'February', 'August', 'June', 'March', 'August', 'April', 'April', 'June', 'April', 'June', 'February', 'September', 'March', 'July', 'September', 'December', 'June', 'June', 'August', 'November', 'April', 'November', 'August', 'June', 'January', 'August', 'May', 'March', 'March', 'March', 'May', 'September', 'August', 'April', 'February', 'April', 'May', 'March', 'March', 'January', 'August', 'October', 'February', 'November', 'August', 'June', 'September', 'September', 'January', 'September', 'July', 'July', 'December', 'June', 'April', 'February', 'August', 'September', 'August', 'February', 'April', 'July', 'May', 'November', 'December', 'February', 'August', 'August', 'September', 'December', 'February', 'March', 'June', 'December', 'February', 'May', 'April', 'July', 'March', 'June', 'December', 'March', 'July', 'May', 'September', 'November']\n people = create_person_objects(names, ages, months)\n\n # Calls to the two functions you have completed.\n print(get_april_birthdays(people))\n print(get_most_common_month(people))\n\n\n\ntest()\n# Expected result:\n# {'Michael': 11, 'Erica': 72, 'Carol': 36, 'Lisa': 37, 'Lawrence': 87, 'Joseph': 25, 'Margaret': 35, 'Andrew': 13, 'Dusty': 53, 'Robert': 89}\n# August\n", "_____no_output_____" ], [ "board = [[5,3,4,6,7,8,9,1,2],\n [6,7,2,1,9,5,3,4,8],\n [1,9,8,3,4,2,5,6,7],\n [8,5,9,7,6,1,4,2,3],\n [4,2,6,8,5,3,7,9,1],\n [7,1,3,9,2,4,8,5,6],\n [9,6,1,5,3,7,2,8,4],\n [2,8,7,4,1,9,6,3,5],\n [3,4,5,2,8,6,1,7,9],]\n\ndef checkCol(board):\n for i in range(len(board)):\n arr = []\n for j in range(len(board[0])):\n arr.append(board[i][j])\n if not sorted(arr) == [1,2,3,4,5,6,7,8,9]:\n return False\n return True\n\ndef checkRow(board):\n for i in board:\n if not sorted(i) == [1,2,3,4,5,6,7,8,9]:\n return False\n return True\n\nprint(checkRow(board))\n\n", "True\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
ec5321255f1cf4c0e96216e581795665bffea5a4
35,803
ipynb
Jupyter Notebook
Data Science 1_ Introduction to Python for Data Science/Azure Notebook Files/1-Python.ipynb
raspyweather/Reactors
a8e05ec1e585958f932c4c304a595f03bd15db39
[ "MIT" ]
1
2019-09-18T13:23:09.000Z
2019-09-18T13:23:09.000Z
Data Science 1_ Introduction to Python for Data Science/Azure Notebook Files/1-Python.ipynb
raspyweather/Reactors
a8e05ec1e585958f932c4c304a595f03bd15db39
[ "MIT" ]
null
null
null
Data Science 1_ Introduction to Python for Data Science/Azure Notebook Files/1-Python.ipynb
raspyweather/Reactors
a8e05ec1e585958f932c4c304a595f03bd15db39
[ "MIT" ]
1
2020-11-25T16:21:42.000Z
2020-11-25T16:21:42.000Z
24.472317
327
0.438567
[ [ [ "# Introduction to Python", "_____no_output_____" ], [ "## Comments", "_____no_output_____" ] ], [ [ "# this is the first comment\nspam = 1 # and this is the second comment\n # ... and now a third!\ntext = \"# This is not a comment because it's inside quotes.\"\nprint(text)", "_____no_output_____" ] ], [ [ "## Python basics", "_____no_output_____" ], [ "### Arithmetic and numeric types\n\n> **Learning goal:** By the end of this subsection, you should be comfortable with using numeric types in Python arithmetic.", "_____no_output_____" ], [ "#### Python numeric operators", "_____no_output_____" ] ], [ [ "2 + 3", "_____no_output_____" ] ], [ [ "**Share**: What is the answer? Why?", "_____no_output_____" ] ], [ [ "30 - 4 * 5", "_____no_output_____" ] ], [ [ "**Share**: What is the answer? Why?", "_____no_output_____" ] ], [ [ "7 / 5", "_____no_output_____" ], [ "3 * 3.5", "_____no_output_____" ], [ "7.0 / 5", "_____no_output_____" ] ], [ [ "**Floor Division**", "_____no_output_____" ] ], [ [ "7 // 5", "_____no_output_____" ] ], [ [ "**Remainder (modulo)**", "_____no_output_____" ] ], [ [ "7 % 5", "_____no_output_____" ] ], [ [ "**Exponents**", "_____no_output_____" ] ], [ [ "5 ** 2", "_____no_output_____" ], [ "2 ** 5", "_____no_output_____" ] ], [ [ "**Share**: What is the answer? Why?", "_____no_output_____" ] ], [ [ "-5 ** 2", "_____no_output_____" ], [ "(-5) ** 2", "_____no_output_____" ], [ "(30 - 4) * 5", "_____no_output_____" ] ], [ [ "### Variables\n\n**Share**: What is the answer? Why?", "_____no_output_____" ] ], [ [ "length = 15\nwidth = 3 * 5\nlength * width", "_____no_output_____" ] ], [ [ "**Variables don't need types**", "_____no_output_____" ] ], [ [ "length = 15\nlength", "_____no_output_____" ], [ "length = 15.0\nlength", "_____no_output_____" ], [ "length = 'fifteen'\nlength", "_____no_output_____" ] ], [ [ "**Share**: What will happen? Why?", "_____no_output_____" ] ], [ [ "n", "_____no_output_____" ] ], [ [ "**Previous Output**", "_____no_output_____" ] ], [ [ "tax = 11.3 / 100\nprice = 19.95\nprice * tax", "_____no_output_____" ], [ "price + _", "_____no_output_____" ], [ "round(_, 2)", "_____no_output_____" ] ], [ [ "**Multiple Variable Assignment**", "_____no_output_____" ] ], [ [ "a, b, c, = 3.2, 1, 6\na, b, c", "_____no_output_____" ] ], [ [ "### Expressions\n\n**Share**: What is the answer? Why?", "_____no_output_____" ] ], [ [ "2 < 5", "_____no_output_____" ] ], [ [ "*(Run after learners have shared the above)*\n**Python Comparison Operators**:\n![all of the comparison operators](https://notebooks.azure.com/sguthals/projects/data-science-1-instructor/raw/Images%2FScreen%20Shot%202019-09-10%20at%207.15.49%20AM.png)", "_____no_output_____" ], [ "**Complex Expressions**", "_____no_output_____" ] ], [ [ "a, b, c = 1, 2, 3\na < b < c", "_____no_output_____" ] ], [ [ "**Built-In Functions**", "_____no_output_____" ] ], [ [ "min(3, 2.4, 5)", "_____no_output_____" ], [ "max(3, 2.4, 5)", "_____no_output_____" ] ], [ [ "**Compound Expressions**", "_____no_output_____" ] ], [ [ "1 < 2 and 2 < 3", "_____no_output_____" ] ], [ [ "\n\n### Exercise:\n\n**Think, Pair, Share**\n1. Quietly think about what would happen if you flipped one of the `<` to a `>`. \n2. Share with the person next to you what you think will happen. \n3. Try it out in the code cell below. \n4. Share anything you thought was surprising.", "_____no_output_____" ] ], [ [ "# Now flip around one of the simple expressions and see if the output matches your expectations:\n", "_____no_output_____" ] ], [ [ "**Or and Not** \n**Share**: What is the answer? Why?", "_____no_output_____" ] ], [ [ "1 < 2 or 1 > 2", "_____no_output_____" ], [ "not (2 < 3)", "_____no_output_____" ] ], [ [ "### Exercise:\n**Think, Pair, Share**\n1. Quietly think about what would the results would be. *Tip: Use paper!*\n2. Share with the person next to you what you think will happen. \n3. Try it out in the code cell below. \n4. Share anything you thought was surprising.\n5. Instructor Demo", "_____no_output_____" ] ], [ [ "# Play around with compound expressions.\n# Set i to different values to see what results this complex compound expression returns:\ni = 7\n(i == 2) or not (i % 2 != 0 and 1 < i < 5)", "_____no_output_____" ] ], [ [ "> **Takeaway:** Arithmetic operations on numeric data form the foundation of data science work in Python. Even sophisticated numeric operations are predicated on these basics, so mastering them is essential to doing data science.", "_____no_output_____" ], [ "## Strings\n\n> **Learning goal:** By the end of this subsection, you should be comfortable working with strings at a basic level in Python.", "_____no_output_____" ] ], [ [ "'spam eggs' # Single quotes.", "_____no_output_____" ], [ "'doesn\\'t' # Use \\' to escape the single quote...", "_____no_output_____" ], [ "\"doesn't\" # ...or use double quotes instead.", "_____no_output_____" ], [ "'\"Isn\\'t,\" she said.'", "_____no_output_____" ], [ "print('\"Isn\\'t,\" she said.')", "_____no_output_____" ] ], [ [ "**Pause**\nNotice the difference between the previous two code cells when they are run. ", "_____no_output_____" ] ], [ [ "print('C:\\some\\name') # Here \\n means newline!", "_____no_output_____" ], [ "print(r'C:\\some\\name') # Note the r before the quote.", "_____no_output_____" ] ], [ [ "### String literals", "_____no_output_____" ], [ "**Think, Pair, Share**", "_____no_output_____" ] ], [ [ "3 * 'un' + 'ium'", "_____no_output_____" ] ], [ [ "### Concatenating strings", "_____no_output_____" ] ], [ [ "'Py' 'thon'", "_____no_output_____" ], [ "prefix = 'Py'\nprefix + 'thon'", "_____no_output_____" ] ], [ [ "### String indexes\n\n**Think, Pair, Share**", "_____no_output_____" ] ], [ [ "word = 'Python'\nword[0]", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "word[5]", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "word[-1]", "_____no_output_____" ], [ "word[-2]", "_____no_output_____" ], [ "word[-6]", "_____no_output_____" ] ], [ [ "### Slicing strings\n\n**Think, Pair, Share**", "_____no_output_____" ] ], [ [ "word[0:2]", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "word[2:5]", "_____no_output_____" ], [ "word[:2]", "_____no_output_____" ], [ "word[4:]", "_____no_output_____" ], [ "word[-2:]", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "word[:2] + word[2:]", "_____no_output_____" ], [ "word[:4] + word[4:]", "_____no_output_____" ] ], [ [ "**TIP**", "_____no_output_____" ] ], [ [ " +---+---+---+---+---+---+\n | P | y | t | h | o | n |\n +---+---+---+---+---+---+\n 0 1 2 3 4 5 6\n-6 -5 -4 -3 -2 -1", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "word[42] # The word only has 6 characters.", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "word[4:42]", "_____no_output_____" ], [ "word[42:]", "_____no_output_____" ] ], [ [ "**Strings are Immutable**", "_____no_output_____" ] ], [ [ "word[0] = 'J'", "_____no_output_____" ], [ "word[2:] = 'py'", "_____no_output_____" ], [ "'J' + word[1:]", "_____no_output_____" ], [ "word[:2] + 'Py'", "_____no_output_____" ] ], [ [ "**Built-In Function: len**", "_____no_output_____" ] ], [ [ "s = 'supercalifragilisticexpialidocious'\nlen(s)", "_____no_output_____" ] ], [ [ "**Built-In Function: str**", "_____no_output_____" ] ], [ [ "str(2)", "_____no_output_____" ], [ "str(2.5)", "_____no_output_____" ] ], [ [ "## Other data types\n\n> **Learning goal:** By the end of this subsection, you should have a basic understanding of the remaining fundamental data types in Python and an idea of how and when to use them.", "_____no_output_____" ], [ "### Lists", "_____no_output_____" ] ], [ [ "squares = [1, 4, 9, 16, 25]\nsquares", "_____no_output_____" ] ], [ [ "**Indexing and Slicing is the Same as Strings**", "_____no_output_____" ] ], [ [ "squares[0] ", "_____no_output_____" ], [ "squares[-1]", "_____no_output_____" ], [ "squares[-3:]", "_____no_output_____" ], [ "squares[:]", "_____no_output_____" ] ], [ [ "**Think, Pair, Share**", "_____no_output_____" ] ], [ [ "squares + [36, 49, 64, 81, 100]", "_____no_output_____" ] ], [ [ "**Lists are Mutable**", "_____no_output_____" ] ], [ [ "cubes = [1, 8, 27, 65, 125]\n4 ** 3 ", "_____no_output_____" ] ], [ [ "**Think, Pair, Share**", "_____no_output_____" ] ], [ [ "# Replace the wrong value.\ncubes", "_____no_output_____" ] ], [ [ "**Replace Many Values**", "_____no_output_____" ] ], [ [ "letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\nletters", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "letters[2:5] = ['C', 'D', 'E']\nletters", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "letters[2:5] = []\nletters", "_____no_output_____" ], [ "letters[:] = []\nletters", "_____no_output_____" ] ], [ [ "**Built-In Functions: len**", "_____no_output_____" ] ], [ [ "letters = ['a', 'b', 'c', 'd']\nlen(letters)", "_____no_output_____" ] ], [ [ "**Nesting**\n\n**Think, Pair, Share**", "_____no_output_____" ] ], [ [ "a = ['a', 'b', 'c']\nn = [1, 2, 3]\nx = [a, n]\nx", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "x[0]", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "x[0][0]", "_____no_output_____" ] ], [ [ "### Exercise:", "_____no_output_____" ] ], [ [ "# Nested lists come up a lot in programming, so it pays to practice.\n# Which indices would you include after x to get ‘c’?\n# How about to get 3?\n", "_____no_output_____" ] ], [ [ "### List object methods\n\n**Share**", "_____no_output_____" ] ], [ [ "beatles = ['John', 'Paul']\nbeatles.append('George')\nbeatles", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "beatles2 = ['John', 'Paul', 'George']\nbeatles2.append(['Stuart', 'Pete'])\nbeatles2", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "beatles.extend(['Stuart', 'Pete'])\nbeatles", "_____no_output_____" ] ], [ [ "**Share**", "_____no_output_____" ] ], [ [ "beatles.index('George')", "_____no_output_____" ], [ "beatles.count('John')", "_____no_output_____" ], [ "beatles.remove('Stuart')\nbeatles", "_____no_output_____" ], [ "beatles.pop()", "_____no_output_____" ], [ "beatles.insert(1, 'Ringo')\nbeatles", "_____no_output_____" ], [ "beatles.reverse()\nbeatles", "_____no_output_____" ], [ "beatles.sort()\nbeatles", "_____no_output_____" ] ], [ [ "### Exercise:", "_____no_output_____" ] ], [ [ "# What happens if you run beatles.extend(beatles)?\n# How about beatles.append(beatles)?\n", "_____no_output_____" ] ], [ [ "### Tuples", "_____no_output_____" ] ], [ [ "t = (1, 2, 3)\nt", "_____no_output_____" ] ], [ [ "**Tuples are Immutable**", "_____no_output_____" ] ], [ [ "t[1] = 2.0", "_____no_output_____" ], [ "t[1]", "_____no_output_____" ], [ "t[:2]", "_____no_output_____" ] ], [ [ "**Lists <-> Tuples**", "_____no_output_____" ] ], [ [ "l = ['baked', 'beans', 'spam']\nl = tuple(l)\nl", "_____no_output_____" ], [ "l = list(l)\nl", "_____no_output_____" ] ], [ [ "### Membership testing\n\n**Share**", "_____no_output_____" ] ], [ [ "tup = ('a', 'b', 'c')\n'b' in tup", "_____no_output_____" ], [ "lis = ['a', 'b', 'c']\n'a' not in lis", "_____no_output_____" ] ], [ [ "### Exercise:", "_____no_output_____" ] ], [ [ "# What happens if you run lis in lis?\n# Is that the behavior you expected?\n# If not, think back to the nested lists we’ve already encountered.\n", "_____no_output_____" ] ], [ [ "### Dictionaries", "_____no_output_____" ] ], [ [ "capitals = {'France': ('Paris', 2140526)}", "_____no_output_____" ], [ "capitals['Nigeria'] = ('Lagos', 6048430)\ncapitals", "_____no_output_____" ] ], [ [ "### Exercise:", "_____no_output_____" ] ], [ [ "# Now try adding another country (or something else) to the capitals dictionary", "_____no_output_____" ] ], [ [ "**Interacting with Dictionaries**", "_____no_output_____" ] ], [ [ "capitals['France']", "_____no_output_____" ], [ "capitals['Nigeria'] = ('Abuja', 1235880)\ncapitals", "_____no_output_____" ], [ "len(capitals)", "_____no_output_____" ], [ "capitals.popitem()", "_____no_output_____" ], [ "capitals", "_____no_output_____" ] ], [ [ "> **Takeaway:** Regardless of how complex and voluminous the data you will work with, these basic data structures will repeatedly be your means for handling and manipulating it. Comfort with these basic data structures is essential to being able to understand and use Python code written by others.", "_____no_output_____" ], [ "### List comprehensions\n\n> **Learning goal:** By the end of this subsection, you should understand how to economically and computationally create lists.", "_____no_output_____" ] ], [ [ "for x in range(1,11):\n print(x)", "_____no_output_____" ], [ "numbers = [x for x in range(1,11)] # Remember to create a range 1 more than the number you actually want.\nnumbers\n\nnumbers = [x for x in range(1,11)]\nnumbers = [x for x in [1,2,3,4,5,6,7,8,9,10]]\nnumbers = [1,2,3,4,5,6,7,8,9,10]", "_____no_output_____" ], [ "for x in range(1,11):\n print(x*x)", "_____no_output_____" ], [ "squares = [x*x for x in range(1,11)]\nsquares\n\nsquares = [x*x for x in range(1,11)]\nsquares = [x*x for x in [1,2,3,4,5,6,7,8,9,10]]\nsquares = [1*1,2*2,3*3,4*4,5,6,7,8,9,10]\nsquares = [1,2,9...]", "_____no_output_____" ] ], [ [ "**Demo**", "_____no_output_____" ] ], [ [ "odd_squares = [x*x for x in range(1,11) if x % 2 != 0]\nodd_squares", "_____no_output_____" ] ], [ [ "### Exercise:", "_____no_output_____" ] ], [ [ "# Now use a list comprehension to generate a list of odd cubes\n# from 1 to 2,197\n", "_____no_output_____" ] ], [ [ "> **Takeaway:** List comprehensions are a popular tool in Python because they enable the rapid, programmatic generation of lists. The economy and ease of use therefore make them an essential tool for you (in addition to a necessary topic to understand as you try to understand Python code written by others).", "_____no_output_____" ], [ "### Importing modules\n\n> **Learning goal:** By the end of this subsection, you should be comfortable importing modules in Python.", "_____no_output_____" ] ], [ [ "factorial(5)", "_____no_output_____" ], [ "import math\nmath.factorial(5)", "_____no_output_____" ], [ "from math import factorial\nfactorial(5)", "_____no_output_____" ] ], [ [ "\n> **Takeaway:** There are several Python modules that you will regularly use in conducting data science in Python, so understanding how to import them will be essential (especially in this training).", "_____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", "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", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "raw" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
ec53440dbf55926d14273748f07e3291d9a8a038
322,232
ipynb
Jupyter Notebook
notebooks/fastspeech_inference.ipynb
pedromanrique/tensorflow-tts
62796295284c7cc19f3224df1116a82ce3b1c1d7
[ "Apache-2.0" ]
2
2020-07-03T05:47:47.000Z
2020-07-03T19:59:09.000Z
notebooks/fastspeech_inference.ipynb
pedromanrique/tensorflow-tts
62796295284c7cc19f3224df1116a82ce3b1c1d7
[ "Apache-2.0" ]
null
null
null
notebooks/fastspeech_inference.ipynb
pedromanrique/tensorflow-tts
62796295284c7cc19f3224df1116a82ce3b1c1d7
[ "Apache-2.0" ]
4
2021-02-23T13:05:59.000Z
2021-04-23T05:15:32.000Z
1,022.95873
109,472
0.95848
[ [ [ "import yaml\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\n\nfrom tensorflow_tts.processor.ljspeech import LJSpeechProcessor\nfrom tensorflow_tts.processor.ljspeech import symbols, _symbol_to_id\n\nfrom tensorflow_tts.configs import FastSpeechConfig\nfrom tensorflow_tts.models import TFFastSpeech", "_____no_output_____" ], [ "with open('../examples/fastspeech/conf/fastspeech.v3.yaml') as f:\n config = yaml.load(f, Loader=yaml.Loader)", "_____no_output_____" ], [ "config = FastSpeechConfig(**config[\"fastspeech_params\"])\nprocessor = LJSpeechProcessor(None, \"english_cleaners\")", "_____no_output_____" ], [ "input_text = \"i love you so much.\"\ninput_ids = processor.text_to_sequence(input_text)", "_____no_output_____" ], [ "fastspeech = TFFastSpeech(config=config, name=\"fastspeech\")", "_____no_output_____" ] ], [ [ "# Save to Pb", "_____no_output_____" ] ], [ [ "mel_before, mel_after, duration_outputs = fastspeech.inference(\n input_ids=tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0),\n attention_mask=tf.math.not_equal(tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0), 0),\n speaker_ids=tf.convert_to_tensor([0], dtype=tf.int32),\n speed_ratios=tf.convert_to_tensor([1.0], dtype=tf.float32),\n)", "_____no_output_____" ], [ "fastspeech.load_weights(\"../examples/fastspeech/checkpoints/model-150000.h5\")", "_____no_output_____" ], [ "# save model into pb and do inference. Note that signatures should be a tf.function with input_signatures.\ntf.saved_model.save(fastspeech, \"./test_saved\", signatures=fastspeech.inference)", "WARNING:tensorflow:Skipping full serialization of Keras model <tensorflow_tts.models.fastspeech.TFFastSpeech object at 0x7f61b1c8d510>, because its inputs are not defined.\nWARNING:tensorflow:From /home/lap13548/anaconda3/envs/tensorflow-tts/lib/python3.7/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1786: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\nInstructions for updating:\nIf using Keras pass *_constraint arguments to layers.\nINFO:tensorflow:Assets written to: ./test_saved/assets\n" ] ], [ [ "# Load and Inference", "_____no_output_____" ] ], [ [ "fastspeech = tf.saved_model.load(\"./test_saved\")", "_____no_output_____" ], [ "input_text = \"There’s a way to measure the acute emotional intelligence that has never gone out of style.\"\ninput_ids = processor.text_to_sequence(input_text)", "_____no_output_____" ], [ "mel_before, mel_after, duration_outputs = fastspeech.inference(\n input_ids=tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0),\n attention_mask=tf.math.not_equal(tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0), 0),\n speaker_ids=tf.convert_to_tensor([0], dtype=tf.int32),\n speed_ratios=tf.convert_to_tensor([1.0], dtype=tf.float32),\n)", "_____no_output_____" ], [ "mel_after = tf.reshape(mel_after, [-1, 80]).numpy()\nfig = plt.figure(figsize=(10, 8))\nax1 = fig.add_subplot(311)\nax1.set_title(f'Predicted Mel-after-Spectrogram')\nim = ax1.imshow(np.rot90(mel_after), aspect='auto', interpolation='none')\nfig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)\nplt.show()\nplt.close()", "_____no_output_____" ] ], [ [ "# Let inference other input to check dynamic shape", "_____no_output_____" ] ], [ [ "input_text = \"The Commission further recommends that the Secret Service coordinate its planning as closely as possible with all of the Federal agencies from which it receives information.\"\ninput_ids = processor.text_to_sequence(input_text)", "_____no_output_____" ], [ "mel_before, mel_after, duration_outputs = fastspeech.inference(\n input_ids=tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0),\n attention_mask=tf.math.not_equal(tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0), 0),\n speaker_ids=tf.convert_to_tensor([0], dtype=tf.int32),\n speed_ratios=tf.convert_to_tensor([1.0], dtype=tf.float32),\n)", "_____no_output_____" ], [ "mel_after = tf.reshape(mel_after, [-1, 80]).numpy()\nfig = plt.figure(figsize=(10, 8))\nax1 = fig.add_subplot(311)\nax1.set_title(f'Predicted Mel-after-Spectrogram')\nim = ax1.imshow(np.rot90(mel_after), aspect='auto', interpolation='none')\nfig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)\nplt.show()\nplt.close()", "_____no_output_____" ] ], [ [ "# Let check speed control", "_____no_output_____" ] ], [ [ "mel_before, mel_after, duration_outputs = fastspeech.inference(\n input_ids=tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0),\n attention_mask=tf.math.not_equal(tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0), 0),\n speaker_ids=tf.convert_to_tensor([0], dtype=tf.int32),\n speed_ratios=tf.convert_to_tensor([1.5], dtype=tf.float32),\n)", "_____no_output_____" ], [ "mel_after = tf.reshape(mel_after, [-1, 80]).numpy()\nfig = plt.figure(figsize=(10, 8))\nax1 = fig.add_subplot(311)\nax1.set_title(f'Predicted Mel-after-Spectrogram')\nim = ax1.imshow(np.rot90(mel_after), aspect='auto', interpolation='none')\nfig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)\nplt.show()\nplt.close()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ec53464988a754038300cdcecca1f6a710becf10
5,801
ipynb
Jupyter Notebook
Research/Experimental.ipynb
shew91/Retropy
9feb34855b997c48d93a5343a9842788d19582e6
[ "MIT" ]
13
2018-06-02T09:11:15.000Z
2020-08-29T01:01:19.000Z
Research/Experimental.ipynb
shew91/Retropy
9feb34855b997c48d93a5343a9842788d19582e6
[ "MIT" ]
1
2021-01-17T14:03:13.000Z
2021-01-17T14:03:13.000Z
Research/Experimental.ipynb
shew91/Retropy
9feb34855b997c48d93a5343a9842788d19582e6
[ "MIT" ]
6
2018-06-02T16:20:47.000Z
2021-12-30T22:26:54.000Z
25.442982
333
0.552319
[ [ [ "%run -i \"../Retropy_framework.py\"", "_____no_output_____" ] ], [ [ "## Mean/Median series\n- mean_series - this is what we usually want, but it's hard to calculate for a set of series with different scales and start/end dates\n- mean_series_perf - this is easy to calculate, and is fairly similar to mean_series\n- median_series - will work similar to mean_series for many series, but very differently for a few\n- median_series_perf - is reasonably similar to median_series, but might not be useful at all", "_____no_output_____" ] ], [ [ "lst = get([GLD, SPY, i_ac], trim=True)\nshow(*lst, median_series(lst, align=True), mean_series(lst, align=True), median_series_perf(lst), mean_series_perf(lst), ta=False)", "_____no_output_____" ] ], [ [ "## despike risk-return", "_____no_output_____" ] ], [ [ "# we should despike by default to avoid vast mistakes like ANGL\n# but there are no \"right\" answers since despike also removes some true data\n\nall = assets_core + [\"ANGL\"]\n#r = reduce_series([BND], y_func=[compose(cagr, price), cagr], x_func=ulcer)\n#r = reduce_series([BND], g_func=[price, get], y_func=cagr, x_func=ulcer)\n#r = reduce_series(all, g_func=[ft.partial(get, despike=False), get], y_func=cagr, x_func=ulcer)\n\nshow_risk_return2(*all, g_func=[ft.partial(get, despike=False), ft.partial(get, despike=True)])", "_____no_output_____" ] ], [ [ "## currency exposure", "_____no_output_____" ] ], [ [ "lst = lmap(partial(lrret_beta, X=usdBroad, pvalue=True), all)\ndf = pd.DataFrame(list(zip(*lst))).T\ndf.index = map(get_name, all)\ndf.columns = [\"beta\", \"pvalue\"]\ndf = df[df.pvalue<=0.05].sort_values(\"beta\")\ndf", "_____no_output_____" ], [ "for x, y in df[\"beta\"].iteritems():\n print(x, y)", "_____no_output_____" ], [ "lrret(VXUS, usdBroad, fit_values=False, pos_weights=False, sum1=False)\nlrret_beta(VXUS, usdBroad)", "_____no_output_____" ] ], [ [ "## portfolio flow", "_____no_output_____" ] ], [ [ "show_port_with_flow(gb, rate=0.05, inf=0, income_smooth=3)", "_____no_output_____" ], [ "show_port_flow_comp(SPY, BDCL)", "_____no_output_____" ] ], [ [ "## Rebalance", "_____no_output_____" ] ], [ [ "show_risk_return(mix(gb, \"SPY\", do_get=True, mode=\"PR\"), mix(gb, \"SPY\", do_get=True, mode=\"NTR\"), mix(gb, \"SPY\", do_get=True, mode=\"TR\"), mix(gb, \"SPY\", do_get=True, mode=\"NTR\", rebal=\"day\"), mix(gb, \"SPY\", do_get=True, mode=\"TR\", rebal=\"day\"), mix(gb, \"SPY\", do_get=True, mode=\"PR\", rebal=\"day\"))", "_____no_output_____" ], [ "show_rolling_beta(get(\"SPY:50|BND:50\", rebal=\"none\"), [\"SPY\", \"BND\"], window=10)\nshow_rolling_beta(get(\"SPY:50|BND:50\", rebal=\"day\"), [\"SPY\", \"BND\"], window=10)", "_____no_output_____" ] ], [ [ "## Generate", "_____no_output_____" ] ], [ [ "\nn = 500\nx = np.cumprod(np.random.normal(size=n)/100+1)\ndt = pd.date_range(start='1/1/2017', periods=n)\ns = pd.Series(x, dt)\nshow(s)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
ec53465e361efce91dfbbcefa95971b765c7a33b
5,995
ipynb
Jupyter Notebook
08_tf2_migration/helloworld.ipynb
llv22/tensorflow_daily
dfe28de689bd2308919b54e174a2736ce5c93b90
[ "Apache-2.0" ]
null
null
null
08_tf2_migration/helloworld.ipynb
llv22/tensorflow_daily
dfe28de689bd2308919b54e174a2736ce5c93b90
[ "Apache-2.0" ]
null
null
null
08_tf2_migration/helloworld.ipynb
llv22/tensorflow_daily
dfe28de689bd2308919b54e174a2736ce5c93b90
[ "Apache-2.0" ]
null
null
null
30.125628
141
0.563303
[ [ [ "import tensorflow as tf\n\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D\nfrom tensorflow.keras import Model", "_____no_output_____" ], [ "mnist = tf.keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\n# Add a channels dimension\nx_train = x_train[..., tf.newaxis]\nx_test = x_test[..., tf.newaxis]", "_____no_output_____" ], [ "train_ds = tf.data.Dataset.from_tensor_slices(\n (x_train, y_train)).shuffle(10000).batch(32)\n\ntest_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)", "_____no_output_____" ], [ "class MyModel(Model):\n def __init__(self):\n super(MyModel, self).__init__()\n self.conv1 = Conv2D(32, 3, activation='relu')\n self.flatten = Flatten()\n self.d1 = Dense(128, activation='relu')\n self.d2 = Dense(10)\n\n def call(self, x):\n x = self.conv1(x)\n x = self.flatten(x)\n x = self.d1(x)\n return self.d2(x)\n\n# Create an instance of the model\nmodel = MyModel()", "_____no_output_____" ], [ "loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n\noptimizer = tf.keras.optimizers.Adam()", "_____no_output_____" ], [ "train_loss = tf.keras.metrics.Mean(name='train_loss')\ntrain_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n\ntest_loss = tf.keras.metrics.Mean(name='test_loss')\ntest_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')", "_____no_output_____" ], [ "@tf.function\ndef train_step(images, labels):\n with tf.GradientTape() as tape:\n # training=True is only needed if there are layers with different\n # behavior during training versus inference (e.g. Dropout).\n predictions = model(images, training=True)\n loss = loss_object(labels, predictions)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n train_loss(loss)\n train_accuracy(labels, predictions)", "_____no_output_____" ], [ "@tf.function\ndef test_step(images, labels):\n # training=False is only needed if there are layers with different\n # behavior during training versus inference (e.g. Dropout).\n predictions = model(images, training=False)\n t_loss = loss_object(labels, predictions)\n\n test_loss(t_loss)\n test_accuracy(labels, predictions)", "_____no_output_____" ], [ "EPOCHS = 5\n\nfor epoch in range(EPOCHS):\n # Reset the metrics at the start of the next epoch\n train_loss.reset_states()\n train_accuracy.reset_states()\n test_loss.reset_states()\n test_accuracy.reset_states()\n\n for images, labels in train_ds:\n train_step(images, labels)\n\n for test_images, test_labels in test_ds:\n test_step(test_images, test_labels)\n\n template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'\n print(template.format(epoch + 1,\n train_loss.result(),\n train_accuracy.result() * 100,\n test_loss.result(),\n test_accuracy.result() * 100))", "Epoch 1, Loss: 0.13628286123275757, Accuracy: 95.8800048828125, Test Loss: 0.0610753633081913, Test Accuracy: 98.04000091552734\nEpoch 2, Loss: 0.04434698075056076, Accuracy: 98.6066665649414, Test Loss: 0.0568249449133873, Test Accuracy: 98.15999603271484\nEpoch 3, Loss: 0.024262024089694023, Accuracy: 99.21500396728516, Test Loss: 0.047597501426935196, Test Accuracy: 98.3699951171875\nEpoch 4, Loss: 0.014465118758380413, Accuracy: 99.51666259765625, Test Loss: 0.05319734290242195, Test Accuracy: 98.47999572753906\nEpoch 5, Loss: 0.010146095417439938, Accuracy: 99.62833404541016, Test Loss: 0.0664728656411171, Test Accuracy: 98.4000015258789\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec534a25cd87383228af57c86b12a7c84195e6c6
567,239
ipynb
Jupyter Notebook
HOT_spots_world-deaths.ipynb
JupyterJones/COVID-19-Jupyter-Notebooks
8b65ade0d4b2b69bb50ab377655497909e3d4a05
[ "MIT" ]
1
2020-05-15T07:28:58.000Z
2020-05-15T07:28:58.000Z
HOT_spots_world-deaths.ipynb
JupyterJones/COVID-19-Jupyter-Notebooks
8b65ade0d4b2b69bb50ab377655497909e3d4a05
[ "MIT" ]
null
null
null
HOT_spots_world-deaths.ipynb
JupyterJones/COVID-19-Jupyter-Notebooks
8b65ade0d4b2b69bb50ab377655497909e3d4a05
[ "MIT" ]
null
null
null
249.885022
2,659
0.476415
[ [ [ "import requests as req\nimport time\nDATE = time.strftime(\"%m-%d-%H_\")\nURL =\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv\"\n\nresp = req.get(URL)\ncontent = resp.text\n\n#create a date oriented filename and print it\nfilename=str(DATE)+\"_\"+URL[-17:]\nprint(filename)\ncontent=content.replace(\",,\",\",Ex,\")\ncontent=content.replace(\"(\",\"\")\ncontent=content.replace(\")\",\"\")\ncontent=content.replace(\"\\\"\",\"\")\n\nprint(content)\n# Open a file using the new filename and write the content of the 'gitfile' to it.\n# Update one time daily\nTEMP = open(filename,\"w\")\nTEMP.write(content)\nTEMP.close() \n", "05-01-20__deaths_global.csv\nProvince/State,Country/Region,Lat,Long,1/22/20,1/23/20,1/24/20,1/25/20,1/26/20,1/27/20,1/28/20,1/29/20,1/30/20,1/31/20,2/1/20,2/2/20,2/3/20,2/4/20,2/5/20,2/6/20,2/7/20,2/8/20,2/9/20,2/10/20,2/11/20,2/12/20,2/13/20,2/14/20,2/15/20,2/16/20,2/17/20,2/18/20,2/19/20,2/20/20,2/21/20,2/22/20,2/23/20,2/24/20,2/25/20,2/26/20,2/27/20,2/28/20,2/29/20,3/1/20,3/2/20,3/3/20,3/4/20,3/5/20,3/6/20,3/7/20,3/8/20,3/9/20,3/10/20,3/11/20,3/12/20,3/13/20,3/14/20,3/15/20,3/16/20,3/17/20,3/18/20,3/19/20,3/20/20,3/21/20,3/22/20,3/23/20,3/24/20,3/25/20,3/26/20,3/27/20,3/28/20,3/29/20,3/30/20,3/31/20,4/1/20,4/2/20,4/3/20,4/4/20,4/5/20,4/6/20,4/7/20,4/8/20,4/9/20,4/10/20,4/11/20,4/12/20,4/13/20,4/14/20,4/15/20,4/16/20,4/17/20,4/18/20,4/19/20,4/20/20,4/21/20,4/22/20,4/23/20,4/24/20,4/25/20,4/26/20,4/27/20,4/28/20,4/29/20,4/30/20\n,Afghanistan,33.0,65.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,4,4,4,4,4,4,4,6,6,7,7,11,14,14,15,15,18,18,21,23,25,30,30,30,33,36,36,40,42,43,47,50,57,58,60,64\n,Albania,41.1533,20.1683,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,4,5,5,6,8,10,10,11,15,15,16,17,20,20,21,22,22,23,23,23,23,23,24,25,26,26,26,26,26,26,27,27,27,27,28,28,30,30,31\n,Algeria,28.0339,1.6596,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,4,4,7,9,11,15,17,17,19,21,25,26,29,31,35,44,58,86,105,130,152,173,193,205,235,256,275,293,313,326,336,348,364,367,375,384,392,402,407,415,419,425,432,437,444,450\n,Andorra,42.5063,1.5218,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,3,3,3,6,8,12,14,15,16,17,18,21,22,23,25,26,26,29,29,31,33,33,35,35,36,37,37,37,37,40,40,40,40,41,42,42\n,Angola,-11.2027,17.8739,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\n,Antigua and Barbuda,17.0608,-61.7964,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3\n,Argentina,-38.4161,-63.6167,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,2,3,3,4,4,4,6,8,9,13,18,19,23,27,28,36,39,43,44,48,56,63,72,82,83,90,97,102,111,115,123,129,132,136,147,152,165,176,185,192,197,207,214,218\n,Armenia,40.0691,45.0382,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,3,3,3,4,7,7,7,7,8,8,9,10,12,13,13,14,16,17,18,19,20,20,22,24,24,24,27,28,28,29,30,30,32\nAustralian Capital Territory,Australia,-35.4735,149.0124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3\nNew South Wales,Australia,-33.8688,151.2093,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,2,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,10,12,12,16,18,21,21,21,22,23,24,25,25,25,25,26,26,26,26,26,26,31,33,33,34,34,39,40,41\nNorthern Territory,Australia,-12.4634,130.8456,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nQueensland,Australia,-28.0167,153.4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,2,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6\nSouth Australia,Australia,-34.9285,138.6007,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4\nTasmania,Australia,-41.4545,145.9707,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,3,3,4,4,5,5,6,6,6,7,7,7,7,7,7,8,9,10,11,11,11,12,13\nVictoria,Australia,-37.8136,144.9631,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,4,4,4,4,5,7,8,8,10,11,12,12,13,14,14,14,14,14,14,14,14,14,14,14,14,16,16,16,17,17,18,18,18\nWestern Australia,Australia,-31.9505,115.8605,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,4,4,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,8,8,8,8,8,8,8\n,Austria,47.5162,14.5501,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,3,3,4,6,6,8,16,21,28,30,49,58,68,86,108,128,146,158,168,186,204,220,243,273,295,319,337,350,368,384,393,410,431,443,452,470,491,510,522,530,536,542,549,569,580,584\n,Azerbaijan,40.1431,47.5769,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,2,3,3,4,4,4,5,5,5,5,5,7,7,8,8,9,10,11,11,12,13,13,15,15,18,19,19,20,20,20,21,21,21,22,22,23,24\n,Bahamas,25.0343,-77.3963,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,4,4,5,6,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,11,11,11,11,11,11,11,11\n,Bahrain,26.0275,50.55,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,6,6,6,6,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8\n,Bangladesh,23.685,90.3563,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,4,5,5,5,5,5,5,5,6,6,6,8,9,12,17,20,21,27,30,34,39,46,50,60,75,84,91,101,110,120,127,131,140,145,152,155,163,168\n,Barbados,13.1939,-59.5432,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6,6,6,6,7,7\n,Belarus,53.7098,27.9534,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,4,4,5,8,13,13,13,16,19,23,26,29,33,36,40,42,45,47,51,55,58,60,63,67,72,75,79,84,89\n,Belgium,50.8333,4.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,4,4,5,10,14,21,37,67,75,88,122,178,220,289,353,431,513,705,828,1011,1143,1283,1447,1632,2035,2240,2523,3019,3346,3600,3903,4157,4440,4857,5163,5453,5683,5828,5998,6262,6490,6679,6917,7094,7207,7331,7501,7594\n,Benin,9.3077,2.3158,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Bhutan,27.5142,90.4336,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Bolivia,-16.2902,-63.5887,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,4,6,7,8,9,10,10,11,14,15,18,19,20,24,27,28,28,29,31,31,32,33,34,37,43,44,46,50,53,53,59,59\n,Bosnia and Herzegovina,43.9159,17.6791,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,3,3,3,4,5,6,10,13,13,16,17,21,23,29,33,34,35,36,37,39,39,40,41,43,46,47,48,49,51,53,54,55,57,59,60,63,65,69\n,Brazil,-14.235,-51.9253,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,6,11,15,25,34,46,59,77,92,111,136,159,201,240,324,359,445,486,564,686,819,950,1057,1124,1223,1328,1532,1736,1924,2141,2354,2462,2587,2741,2906,3331,3704,4057,4286,4603,5083,5513,6006\n,Brunei,4.5353,114.7277,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Bulgaria,42.7339,25.4858,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3,3,3,7,8,8,8,10,10,14,17,20,22,23,24,24,25,28,29,32,35,36,38,41,41,42,43,45,49,52,54,55,56,58,58,64,66\n,Burkina Faso,12.2383,-1.5616,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,4,4,4,4,7,9,11,12,12,14,16,16,16,16,17,18,19,23,24,24,27,27,27,30,32,32,35,36,36,38,38,39,41,41,41,42,42,42,43,43\n,Cabo Verde,16.5388,-23.0418,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Cambodia,11.55,104.9167,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Cameroon,3.8480000000000003,11.5021,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,6,6,6,6,7,8,9,9,9,9,10,10,12,12,12,12,14,17,22,22,22,42,42,43,43,43,43,53,56,58,58,61,61\nAlberta,Canada,53.9333,-116.5765,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,8,9,13,13,18,20,23,24,26,29,32,40,40,46,48,48,48,50,51,51,59,61,66,68,72,73,73,75,80,87,90\nBritish Columbia,Canada,49.2827,-123.1207,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,4,4,7,7,8,10,10,13,13,13,14,14,17,17,19,24,24,31,31,38,38,38,39,43,48,50,58,58,69,69,72,75,77,78,81,82,87,90,94,98,100,100,104,106,109,111\nGrand Princess,Canada,37.6489,-122.6655,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nManitoba,Canada,53.7609,-98.8139,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6\nNew Brunswick,Canada,46.5653,-66.4619,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nNewfoundland and Labrador,Canada,53.1355,-57.6604,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3\nNova Scotia,Canada,44.681999999999995,-63.7443,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,3,3,3,3,4,7,9,9,10,12,16,16,22,24,24,27,28,28\nOntario,Canada,51.2538,-85.3232,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,3,5,6,7,8,13,18,18,21,31,33,37,53,67,94,119,150,153,153,200,222,253,274,291,334,385,490,524,564,591,624,694,762,806,862,916,960,1023,1072,1153,1205\nPrince Edward Island,Canada,46.5107,-63.4168,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nQuebec,Canada,52.9399,-73.5491,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,5,4,4,4,6,8,18,22,22,22,31,33,36,61,61,75,121,150,175,216,241,289,328,360,435,487,630,688,688,820,939,1044,1134,1243,1340,1446,1516,1600,1683,1762,1859\nSaskatchewan,Canada,52.9399,-106.4509,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,6,7\n,Central African Republic,6.6111,20.9394,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Chad,15.4542,18.7322,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,5\n,Chile,-35.6751,-71.543,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,4,5,6,7,8,12,16,18,22,27,34,37,43,48,57,65,73,80,82,92,94,105,116,126,133,139,147,160,168,174,181,189,198,207,216,227\nAnhui,China,31.8257,117.2264,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,4,4,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6\nBeijing,China,40.1824,116.4142,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,5,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9\nChongqing,China,30.0572,107.874,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,2,2,3,3,4,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6\nFujian,China,26.0789,117.9874,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nGansu,China,37.8099,101.0583,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nGuangdong,China,23.3417,113.4244,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,4,4,5,5,5,5,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8\nGuangxi,China,23.8298,108.7881,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nGuizhou,China,26.8154,106.8748,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nHainan,China,19.1959,109.7453,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,2,2,3,3,3,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6\nHebei,China,39.549,116.1306,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6\nHeilongjiang,China,47.861999999999995,127.7615,0,0,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,5,6,7,8,8,9,11,11,11,11,11,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13\nHenan,China,33.882,113.61399999999999,0,0,0,0,1,1,1,2,2,2,2,2,2,2,2,2,3,4,6,6,7,8,10,11,13,13,16,19,19,19,19,19,19,19,19,19,20,20,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22\nHong Kong,China,22.3,114.2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4\nHubei,China,30.9756,112.2707,17,17,24,40,52,76,125,125,162,204,249,350,414,479,549,618,699,780,871,974,1068,1068,1310,1457,1596,1696,1789,1921,2029,2144,2144,2346,2346,2495,2563,2615,2641,2682,2727,2761,2803,2835,2871,2902,2931,2959,2986,3008,3024,3046,3056,3062,3075,3085,3099,3111,3122,3130,3133,3139,3153,3153,3160,3163,3169,3174,3177,3182,3186,3187,3193,3199,3203,3207,3210,3212,3212,3213,3215,3216,3219,3219,3221,3221,3222,3222,4512,4512,4512,4512,4512,4512,4512,4512,4512,4512,4512,4512,4512,4512\nHunan,China,27.6104,111.7088,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4\nInner Mongolia,China,44.0935,113.9448,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nJiangsu,China,32.9711,119.455,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nJiangxi,China,27.614,115.7221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nJilin,China,43.6661,126.1923,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nLiaoning,China,41.2956,122.6085,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nMacau,China,22.1667,113.55,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nNingxia,China,37.2692,106.1655,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nQinghai,China,35.7452,95.9956,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nShaanxi,China,35.1917,108.8701,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3\nShandong,China,36.3427,118.1498,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,2,3,3,4,4,4,4,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7\nShanghai,China,31.201999999999998,121.4491,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7\nShanxi,China,37.5777,112.2922,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nSichuan,China,30.6171,102.7103,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3\nTianjin,China,39.3054,117.323,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3\nTibet,China,31.6927,88.0924,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXinjiang,China,41.1129,85.2401,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3\nYunnan,China,24.974,101.48700000000001,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nZhejiang,China,29.1832,120.0934,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Colombia,4.5709,-74.2973,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,3,4,6,6,6,10,12,16,17,19,25,32,35,46,50,54,69,80,100,109,112,127,131,144,153,153,179,189,196,206,215,225,233,244,253,269,278,293\n,Congo Brazzaville,-4.0383,21.7587,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,8,8,9\n,Congo Kinshasa,-4.0383,21.7587,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,3,6,6,8,8,9,13,13,18,18,18,18,18,18,20,20,20,20,20,21,22,23,25,25,25,25,25,25,25,28,28,28,30,30,31\n,Costa Rica,9.7489,-83.7534,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,5,6,6,6,6,6,6,6,6,6,6,6\n,Cote d'Ivoire,7.54,-5.5471,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,3,3,3,3,3,3,4,5,6,6,6,6,6,8,9,9,13,14,14,14,14,14,14,14,14,14\n,Croatia,45.1,15.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,3,3,5,6,6,6,6,7,8,12,15,16,18,19,20,21,21,23,25,31,33,35,36,39,47,47,48,48,50,51,54,55,59,63,67,69\n,Diamond Princess,0.0,0.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,3,3,3,4,4,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13\n,Cuba,22.0,-80.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,3,3,4,6,6,6,6,6,8,9,11,12,15,15,16,18,21,21,24,27,31,32,34,36,38,40,43,49,51,54,56,58,58,61\n,Cyprus,35.1264,33.4299,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,3,3,5,5,5,7,8,9,10,11,11,9,9,9,9,10,10,10,11,12,12,12,12,12,12,12,12,12,13,13,14,14,14,15,15,15,15\n,Czechia,49.8175,15.472999999999999,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,6,9,9,11,16,23,31,39,44,53,59,67,78,88,99,112,119,129,138,143,161,166,169,173,181,186,194,201,208,210,214,218,220,223,227,227,236\nFaroe Islands,Denmark,61.8926,-6.9118,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nGreenland,Denmark,71.7069,-42.6043,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Denmark,56.2639,9.5018,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,4,6,9,13,13,24,32,34,41,52,65,72,77,90,104,123,139,161,179,187,203,218,237,247,260,273,285,299,309,321,336,346,355,364,370,384,394,403,418,422,427,434,443,452\n,Djibouti,11.8251,42.5903,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\n,Dominican Republic,18.7357,-70.1627,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,2,3,3,6,10,10,20,28,39,42,51,57,60,68,68,82,86,98,108,118,126,135,173,177,183,189,196,200,217,226,235,245,260,265,267,273,278,282,286,293,301\n,Ecuador,-1.8312,-78.1834,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,3,5,7,14,18,27,28,34,36,48,58,60,75,93,120,145,172,180,191,191,242,272,297,315,333,355,369,388,403,421,456,474,507,520,537,560,576,576,576,663,871,883,900\n,Egypt,26.0,30.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,4,6,6,8,10,14,19,20,21,24,30,36,40,41,46,52,58,66,71,78,85,94,103,118,135,146,159,164,178,183,196,205,224,239,250,264,276,287,294,307,317,337,359,380,392\n,El Salvador,13.7942,-88.8965,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,3,3,4,4,5,6,6,6,6,6,6,6,6,7,7,7,7,7,7,8,8,8,8,8,8,9,10\n,Equatorial Guinea,1.5,10.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1\n,Eritrea,15.1794,39.7823,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Estonia,58.5953,25.0136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,3,3,4,5,11,12,13,15,19,21,24,24,24,24,25,28,31,35,36,38,38,40,40,43,44,45,46,46,49,50,50,50,52\n,Eswatini,-26.5225,31.4659,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Ethiopia,9.145,40.4897,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3\n,Fiji,-17.7134,178.065,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Finland,64.0,26.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,3,5,7,9,11,13,17,17,19,20,25,28,27,34,40,42,48,49,56,59,64,72,75,82,90,94,98,141,149,172,177,186,190,193,199,206,211\nFrench Guiana,France,3.9339,-53.1258,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1\nFrench Polynesia,France,-17.6797,149.4068,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nGuadeloupe,France,16.25,-61.5833,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,4,4,4,6,6,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,12,12,12,12,12,12,12,12,12,12\nMayotte,France,-12.8275,45.1662,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4\nNew Caledonia,France,-20.9043,165.618,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nReunion,France,-21.1351,55.2471,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nSaint Barthelemy,France,17.9,-62.8333,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nSt Martin,France,18.0708,-63.0501,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3\nMartinique,France,14.6415,-61.0242,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,4,4,4,6,6,6,6,6,6,6,8,8,8,8,12,12,14,14,14,14,14,14,14,14,14,14\n,France,46.2276,2.2137,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,3,4,4,6,9,11,19,19,33,48,48,79,91,91,148,148,148,243,450,562,674,860,1100,1331,1696,1995,2314,2606,3024,3523,4403,5387,6507,7560,8078,8911,10328,10869,12210,13197,13832,14393,14967,15729,17167,17920,18681,19323,19718,20265,20796,21340,21856,22245,22614,22856,23293,23660,24087,24376\n,Gabon,-0.8037,11.6094,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3\n,Gambia,13.4432,-15.3101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Georgia,42.3154,43.3569,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,6\n,Germany,51.0,9.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,3,3,7,9,11,17,24,28,44,67,84,94,123,157,206,267,342,433,533,645,775,920,1107,1275,1444,1584,1810,2016,2349,2607,2767,2736,3022,3194,3294,3804,4052,4352,4459,4586,4862,5033,5279,5575,5760,5877,5976,6126,6314,6467,6623\n,Ghana,7.9465,-1.0232,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,4,4,4,5,5,5,5,5,5,5,5,5,5,5,6,6,6,8,8,8,8,8,8,8,9,9,9,9,9,9,10,10,11,11,16,16,17\n,Greece,39.0742,21.8243,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,3,4,4,5,5,6,6,13,15,17,20,22,26,28,32,38,43,49,50,53,63,68,73,79,81,83,87,92,93,98,99,101,102,105,108,110,113,116,121,121,125,130,130,134,136,138,139,140\n,Guatemala,15.7835,-90.2308,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,3,3,3,3,3,3,5,5,5,5,5,7,7,7,7,7,8,11,11,13,15,15,15,16,16\n,Guinea,9.9456,-9.6966,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,3,5,5,6,6,6,6,7,7,7,7,7,7\n,Guyana,5.0,-58.75,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,4,4,4,4,4,5,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,8,8,8,8,9\n,Haiti,18.9712,-72.2852,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,3,3,3,3,3,3,3,3,3,3,4,5,5,6,6,6,6,6,8\n,Holy See,41.9029,12.4534,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Honduras,15.2,-86.2419,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,3,7,7,10,14,15,15,22,22,22,22,23,23,24,25,25,26,31,35,41,46,46,46,46,46,47,55,59,59,61,64,66,71\n,Hungary,47.1625,19.5033,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,3,4,6,7,9,10,10,10,11,13,15,16,20,21,26,32,34,38,47,58,66,77,85,99,109,122,134,142,156,172,189,199,213,225,239,262,262,272,280,291,300,312\n,Iceland,64.9631,-19.0208,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,1,1,1,0,1,1,1,2,2,2,2,2,2,2,2,2,4,4,4,4,6,6,6,6,7,8,8,8,8,8,8,9,9,9,10,10,10,10,10,10,10,10,10,10,10\n,India,21.0,78.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,2,2,3,3,4,5,4,7,10,10,12,20,20,24,27,32,35,58,72,72,86,99,136,150,178,226,246,288,331,358,393,405,448,486,521,559,592,645,681,721,780,825,881,939,1008,1079,1154\n,Indonesia,-0.7893,113.9213,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,4,5,5,5,5,19,25,32,38,48,49,55,58,78,87,102,114,122,136,157,170,181,191,198,209,221,240,280,306,327,373,399,459,469,496,520,535,582,590,616,635,647,689,720,743,765,773,784,792\n,Iran,32.0,53.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,4,5,8,12,16,19,26,34,43,54,66,77,92,107,124,145,194,237,291,354,429,514,611,724,853,988,1135,1284,1433,1556,1685,1812,1934,2077,2234,2378,2517,2640,2757,2898,3036,3160,3294,3452,3603,3739,3872,3993,4110,4232,4357,4474,4585,4683,4777,4869,4958,5031,5118,5209,5297,5391,5481,5574,5650,5710,5806,5877,5957,6028\n,Iraq,33.0,44.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,3,4,6,6,7,7,8,9,10,10,10,11,12,13,17,17,20,23,27,29,36,40,42,42,46,50,52,54,54,56,61,64,65,69,69,70,72,76,78,78,79,80,81,82,82,82,83,83,83,86,86,87,88,90,92,93\n,Ireland,53.1424,-7.6921,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,3,3,3,4,6,7,9,19,22,36,46,54,71,85,98,120,137,158,174,210,235,263,287,320,334,365,406,444,486,530,571,610,687,730,769,794,1014,1063,1087,1102,1159,1190,1232\n,Israel,31.0,35.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,3,5,8,12,12,15,16,20,26,36,40,44,49,57,65,73,86,95,101,103,116,123,130,142,151,164,172,177,184,189,192,194,199,201,204,210,215,222\n,Italy,43.0,12.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,7,10,12,17,21,29,34,52,79,107,148,197,233,366,463,631,827,827,1266,1441,1809,2158,2503,2978,3405,4032,4825,5476,6077,6820,7503,8215,9134,10023,10779,11591,12428,13155,13915,14681,15362,15887,16523,17127,17669,18279,18849,19468,19899,20465,21067,21645,22170,22745,23227,23660,24114,24648,25085,25549,25969,26384,26644,26977,27359,27682,27967\n,Jamaica,18.1096,-77.2975,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,3,3,4,4,4,4,4,4,4,5,5,5,5,5,5,6,6,6,7,7,7,7,7,7,8\n,Japan,36.0,138.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,2,4,4,5,6,6,6,6,6,6,6,6,10,10,15,16,19,22,22,27,29,29,29,33,35,41,42,43,45,47,49,52,54,54,56,57,62,63,77,77,85,92,93,94,99,99,108,123,143,146,178,190,222,236,236,263,281,328,345,360,372,385,394,413,430\n,Jordan,31.24,36.51,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,5,5,5,5,5,5,5,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8\n,Kazakhstan,48.0196,66.9237,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,1,1,1,1,1,2,3,3,6,5,6,6,6,7,8,10,10,10,12,14,16,17,17,17,17,19,19,19,20,25,25,25,25,25,25,25\n,Kenya,-0.0236,37.9062,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,3,4,4,4,6,6,6,7,7,7,8,9,9,10,11,11,12,14,14,14,14,14,14,14,14,14,14,15,17\n,Korea, South,36.0,128.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,6,8,10,12,13,13,16,17,28,28,35,35,42,44,50,53,54,60,66,66,72,75,75,81,84,91,94,102,111,111,120,126,131,139,144,152,158,162,165,169,174,177,183,186,192,200,204,208,211,214,217,222,225,229,230,232,234,236,237,238,240,240,242,243,244,246,247,248\n,Kuwait,29.5,47.75,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,2,3,3,3,5,6,7,9,11,13,14,15,19,20,22,23,24,26\n,Kyrgyzstan,41.2044,74.7661,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,4,4,4,4,5,5,5,5,5,5,5,5,5,5,7,7,7,8,8,8,8,8,8,8,8\n,Latvia,56.8796,24.6032,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,3,3,3,5,5,5,5,5,5,5,5,5,9,11,11,12,12,12,13,13,15,15\n,Lebanon,33.8547,35.8623,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,4,4,4,4,4,4,6,6,8,8,10,11,12,14,16,17,17,18,19,19,19,19,20,20,20,20,21,21,21,21,21,21,21,21,22,22,22,24,24,24,24,24,24\n,Liberia,6.4281,-9.4295,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,4,4,5,5,5,6,6,6,6,7,7,8,8,8,8,8,8,11,12,12,16,16,16\n,Liechtenstein,47.14,9.55,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Lithuania,55.1694,23.8813,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,4,4,5,7,7,7,8,8,9,9,11,13,15,15,15,16,22,23,23,24,29,30,32,33,33,35,37,38,38,40,40,41,41,41,44,45,45\n,Luxembourg,49.8153,6.1296,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,4,4,8,8,8,8,8,9,15,18,21,22,23,29,30,31,31,36,41,44,46,52,54,62,66,69,67,69,69,72,72,73,75,78,80,83,85,85,88,88,89,89,90\n,Madagascar,-18.7669,46.8691,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Malaysia,2.5,112.5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,3,4,10,14,16,20,23,26,27,35,37,43,45,50,53,57,61,62,63,65,67,70,73,76,77,82,83,84,86,88,89,89,92,93,95,96,98,98,99,100,100,102\n,Maldives,3.2028,73.2207,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1\n,Malta,35.9375,14.3754,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4\n,Mauritania,21.0079,10.9408,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Mauritius,-20.2,57.5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,3,3,5,6,7,7,7,7,7,7,7,7,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10\n,Mexico,23.6345,-102.5528,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,4,5,6,8,12,16,20,28,29,37,50,60,79,94,125,141,174,194,233,273,296,332,406,449,486,546,650,686,712,857,970,1069,1221,1305,1351,1434,1569,1732,1859\n,Moldova,47.4116,28.3699,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,2,2,2,2,4,5,6,8,12,15,19,22,27,29,29,30,31,35,40,46,54,56,57,67,70,72,75,80,84,94,96,102,103,111,116\n,Monaco,43.7333,7.4167,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4\n,Mongolia,46.8625,103.8467,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Montenegro,42.5,19.3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,4,4,4,5,5,5,5,5,5,5,6,6,7,7,7,7,7\n,Morocco,31.7917,-7.0926,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,3,3,4,4,5,6,11,23,25,26,33,36,39,44,48,59,70,80,90,93,97,107,111,118,126,126,127,130,135,137,141,143,145,149,155,158,159,161,162,165,168,170\n,Namibia,-22.9576,18.4904,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Nepal,28.1667,84.25,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nAruba,Netherlands,12.5186,-70.0358,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nCuracao,Netherlands,12.1696,-68.99,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nSint Maarten,Netherlands,18.0425,-63.0548,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,4,4,6,6,6,6,8,9,9,9,9,9,9,9,9,10,10,10,11,12,12,12,13,13,13,13,13\n,Netherlands,52.1326,5.2913,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,3,4,5,5,10,12,20,24,43,58,76,106,136,179,213,276,356,434,546,639,771,864,1039,1173,1339,1487,1651,1766,1867,2101,2248,2396,2511,2643,2737,2823,2945,3134,3315,3459,3601,3684,3751,3916,4054,4177,4289,4409,4475,4518,4566,4711,4795\n,New Zealand,-40.9006,174.886,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,2,4,4,5,9,9,9,11,11,12,12,13,14,17,18,18,19,19,19,19,19\n,Nicaragua,12.8654,-85.2072,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3,3\n,Niger,17.6078,8.0817,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,3,3,5,5,5,8,10,10,11,11,11,11,11,12,12,14,14,14,18,19,20,20,20,22,24,24,27,29,29,31,32,32\n,Nigeria,9.082,8.6753,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,4,4,5,5,6,6,7,7,10,10,10,11,12,13,17,19,21,22,22,28,31,32,35,40,40,44,51,58\n,North Macedonia,41.6086,21.7453,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,3,3,4,6,7,9,11,11,12,17,18,23,26,29,30,32,34,34,38,44,45,46,49,49,51,54,55,56,56,57,59,61,65,71,73,77\n,Norway,60.472,8.4689,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,6,7,7,7,7,10,12,14,14,19,23,25,32,39,44,50,59,62,71,76,89,101,108,113,119,128,134,139,150,152,161,164,165,181,182,187,194,199,201,201,205,206,207,210\n,Oman,21.0,57.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,2,3,3,3,4,4,4,4,4,6,6,7,7,8,8,9,10,10,10,10,10,10,11\n,Pakistan,30.3753,69.3451,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,3,5,6,7,8,9,11,12,14,21,26,27,34,40,41,47,53,57,61,65,66,86,91,93,96,111,128,135,143,168,176,201,212,237,253,269,281,292,312,343,385\n,Panama,8.538,-80.7821,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,3,6,6,8,8,9,14,17,24,30,30,32,37,41,46,54,55,59,63,66,74,79,87,94,95,103,109,116,120,126,136,141,146,154,159,165,167,167,178,188\n,Papua New Guinea,-6.315,143.9555,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Paraguay,-23.4425,-58.4438,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,3,3,3,3,3,3,3,3,3,3,3,3,5,5,5,5,6,6,6,6,7,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10\n,Peru,-9.19,-75.0152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,5,5,5,7,9,9,11,16,18,24,30,38,55,61,73,83,92,107,121,138,169,181,193,216,230,254,274,300,348,400,445,484,530,572,634,700,728,782,854,943,1051\n,Philippines,13.0,122.0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,5,8,11,12,12,19,17,18,19,25,33,35,38,45,54,68,71,78,88,96,107,136,144,152,163,177,182,203,221,247,297,315,335,349,362,387,397,409,428,437,446,462,477,494,501,511,530,558,568\n,Poland,51.9194,19.1451,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,3,4,5,5,5,5,5,7,8,10,14,16,16,18,22,31,33,43,57,71,79,94,107,129,159,174,181,208,232,245,263,286,314,332,347,360,380,401,426,454,494,524,535,562,596,624,644\n,Portugal,39.3999,-8.2245,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,6,12,14,23,33,43,60,76,100,119,140,160,187,209,246,266,295,311,345,380,409,435,470,504,535,567,599,629,657,687,714,735,762,785,820,854,880,903,928,948,973,989\n,Qatar,25.3548,51.1839,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,3,3,4,4,6,6,6,6,6,7,7,7,7,7,7,8,8,9,9,10,10,10,10,10,10,10,10,10\n,Romania,45.9432,24.9668,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,7,11,17,23,26,37,43,65,82,92,115,133,146,151,176,197,220,248,270,291,316,331,351,372,392,411,421,451,478,498,524,545,567,601,619,641,663,693,717\n,Russia,60.0,90.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,3,3,4,4,8,9,17,24,30,34,43,45,47,58,63,76,94,106,130,148,170,198,232,273,313,361,405,456,513,555,615,681,747,794,867,972,1073\n,Rwanda,-1.9403,29.8739,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Saint Lucia,13.9094,-60.9789,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Saint Vincent and the Grenadines,12.9843,-61.2872,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,San Marino,43.9424,12.4578,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,3,5,5,5,7,7,11,11,14,20,20,20,21,21,21,21,22,22,25,26,26,30,30,32,32,32,34,34,34,34,35,35,35,36,36,38,39,39,39,39,40,40,40,40,40,41,41,41,41,41\n,Saudi Arabia,24.0,45.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,3,4,8,8,10,16,21,25,29,34,38,41,41,44,47,52,59,65,73,79,83,87,92,97,103,109,114,121,127,136,139,144,152,157,162\n,Senegal,14.4974,-14.4524,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,5,5,6,6,7,7,9,9,9,9,9\n,Serbia,44.0165,21.0059,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,3,3,4,1,1,10,13,16,16,28,31,39,44,51,58,61,65,66,71,74,80,85,94,99,103,110,117,122,125,125,125,125,125,125,125,125,125,125,179\n,Seychelles,-4.6796,55.492,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Singapore,1.2833,103.8333,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,3,3,3,3,4,5,6,6,6,6,6,6,7,8,8,9,10,10,10,11,11,11,11,11,12,12,12,12,12,14,14,14,15\n,Slovakia,48.669,19.699,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,2,2,2,2,6,8,9,11,12,13,14,14,15,17,17,18,18,20,22,23\n,Slovenia,46.1512,14.9955,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,3,4,5,6,9,9,11,11,15,15,17,20,22,28,30,36,40,43,45,50,53,55,56,61,61,66,70,74,77,77,79,79,80,81,82,83,86,89,91\n,Somalia,5.1521,46.1996,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,5,5,6,7,7,8,8,8,16,16,18,23,26,28,28,28\n,South Africa,-30.5595,22.9375,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,3,5,5,5,9,9,11,12,13,18,18,24,25,25,27,27,34,48,50,52,54,58,58,65,75,79,86,87,90,93,103,103\n,Spain,40.0,-4.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,5,10,17,28,35,54,55,133,195,289,342,533,623,830,1043,1375,1772,2311,2808,3647,4365,5138,5982,6803,7716,8464,9387,10348,11198,11947,12641,13341,14045,14792,15447,16081,16606,17209,17756,18056,18708,19315,20002,20043,20453,20852,21282,21717,22157,22524,22902,23190,23521,23822,24275,24543\n,Sri Lanka,7.0,81.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,3,4,4,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7\n,Sudan,12.8628,30.2176,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,4,5,5,5,6,10,10,12,12,13,16,16,17,21,22,25,28,31\n,Suriname,3.9193,-56.0278,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Sweden,63.0,16.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,3,6,7,10,11,16,20,21,25,36,62,77,105,105,110,146,180,239,308,358,373,401,477,591,687,793,870,887,899,919,1033,1203,1333,1400,1511,1540,1580,1765,1937,2021,2152,2192,2194,2274,2355,2462,2586\n,Switzerland,46.8182,8.2275,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,4,4,11,13,14,14,27,28,41,54,75,98,120,122,153,191,231,264,300,359,433,488,536,591,666,715,765,821,895,948,1002,1036,1106,1138,1174,1239,1281,1327,1368,1393,1429,1478,1509,1549,1589,1599,1610,1665,1699,1716,1737\n,Taiwan*,23.7,121.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6\n,Tanzania,-6.369,34.8888,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,4,4,5,5,7,10,10,10,10,10,10,10,10,10,16,16\n,Thailand,15.0,101.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,4,4,4,5,6,7,9,10,12,15,19,20,23,26,27,30,32,33,35,38,40,41,43,46,47,47,47,47,48,49,50,51,51,51,52,54,54,54\n,Togo,8.6195,0.8248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,5,5,5,5,6,6,6,6,6,6,6,6,6,7,9\n,Trinidad and Tobago,10.6918,-61.2225,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,3,3,3,3,5,5,6,6,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8\n,Tunisia,34.0,9.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,3,3,4,5,6,6,8,8,8,10,12,14,18,18,22,22,23,24,25,25,28,31,34,34,35,37,37,37,38,38,38,38,38,38,38,38,39,40,40,41\n,Turkey,38.9637,35.2433,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,4,9,30,37,44,59,75,92,108,131,168,214,277,356,425,501,574,649,725,812,908,1006,1101,1198,1296,1403,1518,1643,1769,1890,2017,2140,2259,2376,2491,2600,2706,2805,2900,2992,3081,3174\n,Uganda,1.0,32.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Ukraine,48.3794,31.1656,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,3,3,3,3,3,5,5,5,9,10,13,17,20,22,27,32,37,38,45,52,57,69,73,83,93,98,108,116,125,133,141,151,161,174,187,201,201,209,220,239,250,261\n,United Arab Emirates,24.0,54.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,3,5,6,8,8,9,10,10,11,12,12,14,16,20,22,25,28,33,35,37,37,41,43,46,52,56,64,71,76,82,89,98,105\nBermuda,United Kingdom,32.3078,-64.7505,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,3,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6\nCayman Islands,United Kingdom,19.3133,-81.2546,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nChannel Islands,United Kingdom,49.3723,-2.3644,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,3,3,4,5,6,7,7,8,8,9,9,9,9,13,15,19,20,21,21,24,24,28,29,34,35,35,35,36,38,40\nGibraltar,United Kingdom,36.1408,-5.3536,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nIsle of Man,United Kingdom,54.2361,-4.5481,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,4,4,4,6,6,9,9,15,16,18,18,18,20,21,21,21\nMontserrat,United Kingdom,16.7425,-62.1874,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1\n,United Kingdom,55.3781,-3.4360000000000004,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,7,7,9,10,28,43,65,81,115,158,194,250,285,359,508,694,877,1161,1455,1669,2043,2425,3095,3747,4461,5221,5865,6433,7471,8505,9608,10760,11599,12285,13029,14073,14915,15944,16879,17994,18492,19051,20223,21060,21787,22792,23635,24055,24393,25302,26097,26771\n,Uruguay,-32.5228,-55.7658,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,4,4,5,5,6,7,7,7,7,7,7,8,8,8,9,9,9,10,10,11,12,12,12,14,15,15,15,15,17\n,US,37.0902,-95.7129,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,6,7,11,12,14,17,21,22,28,36,41,49,58,73,99,133,164,258,349,442,586,786,1008,1316,1726,2265,2731,3420,4192,5367,6501,7921,9246,10855,12375,13894,16191,18270,20255,22333,24342,26086,27870,30262,32734,34827,37411,39753,40945,42659,45086,47412,49724,51493,53755,54881,56259,58355,60967,62996\n,Uzbekistan,41.3775,64.5853,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,2,2,2,2,3,3,3,4,4,4,4,4,4,4,5,5,5,6,7,7,8,8,8,8,8,9,9\n,Venezuela,6.4238,-66.5897,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,3,3,5,7,7,7,7,7,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,16\n,Vietnam,16.0,108.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Zambia,-15.4167,28.2833,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3\n,Zimbabwe,-20.0,30.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4\nDiamond Princess,Canada,0.0,0.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Dominica,15.415,-61.371,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Grenada,12.1165,-61.678999999999995,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Mozambique,-18.665695,35.529562,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Syria,34.802075,38.99681500000001,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3\n,Timor-Leste,-8.874217,125.727539,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Belize,13.1939,-59.5432,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nRecovered,Canada,0.0,0.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Laos,19.856270000000002,102.495496,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Libya,26.3351,17.228331,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,3\n,West Bank and Gaza,31.9522,35.2332,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,4,4,4,4,2,2,2,2,2,2\n,Guinea-Bissau,11.8037,-15.1804,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1\n,Mali,17.570692,-3.996166000000001,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,3,3,3,5,5,5,7,7,7,7,9,10,13,13,13,13,13,14,14,14,17,21,21,21,23,23,24,25,26\n,Saint Kitts and Nevis,17.357822,-62.782998,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nNorthwest Territories,Canada,64.8255,-124.8457,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nYukon,Canada,64.2823,-135.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Kosovo,42.602636,20.902977,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,4,5,5,7,7,7,7,8,8,11,12,12,12,12,12,12,12,12,12,12,12,12,12,22\n,Burma,21.9162,95.956,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,3,3,3,3,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,6,6\nAnguilla,United Kingdom,18.2206,-63.0686,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nBritish Virgin Islands,United Kingdom,18.4207,-64.64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1\nTurks and Caicos Islands,United Kingdom,21.69400000000001,-71.7979,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,MS Zaandam,0.0,0.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\n,Botswana,-22.3285,24.6849,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Burundi,-3.3731,29.9189,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n,Sierra Leone,8.460555000000001,-11.779889,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,4,4,4,4,7\nBonaire, Sint Eustatius and Saba,Netherlands,12.1784,-68.2385,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Malawi,-13.254307999999998,34.301525,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3\nFalkland Islands Malvinas,United Kingdom,-51.7963,-59.5236,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nSaint Pierre and Miquelon,France,46.8852,-56.3159,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,South Sudan,6.8770000000000024,31.307,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Western Sahara,24.2155,-12.8858,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Sao Tome and Principe,0.18636,6.613081,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Yemen,15.552726999999999,48.516388,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2\n,Comoros,-11.6455,43.3333,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n,Tajikistan,38.861034,71.276093,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n\n" ], [ "LASTFILE=filename", "_____no_output_____" ], [ "import requests as req\nimport time\nDATA=[]\n#LASTFILE=\"05-01-20__deaths_global.csv\"\nDataIn = open(LASTFILE).read()\nALLcountries=[]\nDataIn = DataIn.split(\"\\n\")\nDatain = DataIn[7:]\nfor line in Datain:\n lines = line.lstrip(\",\")\n lines=lines.split(\",\")\n ALLcountries.append(lines)\n data=\"0,0,\"+str(line).split(\"0,0,\",1)[-1]\n DATA.append(data) ", "_____no_output_____" ], [ "# Set N for threshhold\ncnt=0\nE=len(ALLcountries)\nfor lines in ALLcountries:\n cnt=cnt+1\n if cnt>=E:break\n linez=str(lines)\n linez=linez.replace(\"[\",\"\")\n linez=linez.replace(\"]\",\"\")\n linez=linez.replace(\"'\",\"\")\n lineZ=str(linez).split(\",\")\n if int(lineZ[-1])-int(lineZ[-2])>=150:\n print(\"\\nID-\"+str(cnt)+\": In \"+lineZ[0]+\" there was a\",int(lineZ[-2])-int(lineZ[-3]),\"increase yesterday and\",int(lineZ[-1])-int(lineZ[-2]),\"increase today:\\n\",linez)", "\nID-23: In Brazil there was a 430 increase yesterday and 493 increase today:\n Brazil, -14.235, -51.9253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 6, 11, 15, 25, 34, 46, 59, 77, 92, 111, 136, 159, 201, 240, 324, 359, 445, 486, 564, 686, 819, 950, 1057, 1124, 1223, 1328, 1532, 1736, 1924, 2141, 2354, 2462, 2587, 2741, 2906, 3331, 3704, 4057, 4286, 4603, 5083, 5513, 6006\n\nID-111: In France there was a 427 increase yesterday and 289 increase today:\n France, 46.2276, 2.2137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 4, 4, 6, 9, 11, 19, 19, 33, 48, 48, 79, 91, 91, 148, 148, 148, 243, 450, 562, 674, 860, 1100, 1331, 1696, 1995, 2314, 2606, 3024, 3523, 4403, 5387, 6507, 7560, 8078, 8911, 10328, 10869, 12210, 13197, 13832, 14393, 14967, 15729, 17167, 17920, 18681, 19323, 19718, 20265, 20796, 21340, 21856, 22245, 22614, 22856, 23293, 23660, 24087, 24376\n\nID-115: In Germany there was a 153 increase yesterday and 156 increase today:\n Germany, 51.0, 9.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 3, 7, 9, 11, 17, 24, 28, 44, 67, 84, 94, 123, 157, 206, 267, 342, 433, 533, 645, 775, 920, 1107, 1275, 1444, 1584, 1810, 2016, 2349, 2607, 2767, 2736, 3022, 3194, 3294, 3804, 4052, 4352, 4459, 4586, 4862, 5033, 5279, 5575, 5760, 5877, 5976, 6126, 6314, 6467, 6623\n\nID-132: In Italy there was a 323 increase yesterday and 285 increase today:\n Italy, 43.0, 12.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 7, 10, 12, 17, 21, 29, 34, 52, 79, 107, 148, 197, 233, 366, 463, 631, 827, 827, 1266, 1441, 1809, 2158, 2503, 2978, 3405, 4032, 4825, 5476, 6077, 6820, 7503, 8215, 9134, 10023, 10779, 11591, 12428, 13155, 13915, 14681, 15362, 15887, 16523, 17127, 17669, 18279, 18849, 19468, 19899, 20465, 21067, 21645, 22170, 22745, 23227, 23660, 24114, 24648, 25085, 25549, 25969, 26384, 26644, 26977, 27359, 27682, 27967\n\nID-196: In Spain there was a 453 increase yesterday and 268 increase today:\n Spain, 40.0, -4.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 5, 10, 17, 28, 35, 54, 55, 133, 195, 289, 342, 533, 623, 830, 1043, 1375, 1772, 2311, 2808, 3647, 4365, 5138, 5982, 6803, 7716, 8464, 9387, 10348, 11198, 11947, 12641, 13341, 14045, 14792, 15447, 16081, 16606, 17209, 17756, 18056, 18708, 19315, 20002, 20043, 20453, 20852, 21282, 21717, 22157, 22524, 22902, 23190, 23521, 23822, 24275, 24543\n\nID-218: In United Kingdom there was a 795 increase yesterday and 674 increase today:\n United Kingdom, 55.3781, -3.4360000000000004, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 3, 7, 7, 9, 10, 28, 43, 65, 81, 115, 158, 194, 250, 285, 359, 508, 694, 877, 1161, 1455, 1669, 2043, 2425, 3095, 3747, 4461, 5221, 5865, 6433, 7471, 8505, 9608, 10760, 11599, 12285, 13029, 14073, 14915, 15944, 16879, 17994, 18492, 19051, 20223, 21060, 21787, 22792, 23635, 24055, 24393, 25302, 26097, 26771\n\nID-220: In US there was a 2612 increase yesterday and 2029 increase today:\n US, 37.0902, -95.7129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 6, 7, 11, 12, 14, 17, 21, 22, 28, 36, 41, 49, 58, 73, 99, 133, 164, 258, 349, 442, 586, 786, 1008, 1316, 1726, 2265, 2731, 3420, 4192, 5367, 6501, 7921, 9246, 10855, 12375, 13894, 16191, 18270, 20255, 22333, 24342, 26086, 27870, 30262, 32734, 34827, 37411, 39753, 40945, 42659, 45086, 47412, 49724, 51493, 53755, 54881, 56259, 58355, 60967, 62996\n" ], [ "# Set N for threshhold\n\nN=250\nCNT=0\ncnt=0\nfor line in ALLcountries:\n cnt=cnt+1\nprint(\"-------------------\",cnt,len(ALLcountries),\"---------------------\")\ncnt=0\nfor line in DATA:\n cnt=cnt+1\n if cnt==len(DATA):break\n lines=line.split(\",\")\n #print(cnt,lines[-2],lines[-1])\n #c=int(lines[-2]),int(lines[-1]),int(lines[-1])-int(lines[-2])\n if int(lines[-1])-int(lines[-2])>=N:\n CNT=CNT+1\n print(\"\\n\",CNT,\"____\",cnt,int(lines[-1])-int(lines[-2]))\n print(cnt,ALLcountries[cnt-1])\nprint(cnt)", "------------------- 261 261 ---------------------\n\n 1 ____ 23 493\n23 ['Brazil', '-14.235', '-51.9253', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '3', '6', '11', '15', '25', '34', '46', '59', '77', '92', '111', '136', '159', '201', '240', '324', '359', '445', '486', '564', '686', '819', '950', '1057', '1124', '1223', '1328', '1532', '1736', '1924', '2141', '2354', '2462', '2587', '2741', '2906', '3331', '3704', '4057', '4286', '4603', '5083', '5513', '6006']\n\n 2 ____ 111 289\n111 ['France', '46.2276', '2.2137', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '3', '4', '4', '6', '9', '11', '19', '19', '33', '48', '48', '79', '91', '91', '148', '148', '148', '243', '450', '562', '674', '860', '1100', '1331', '1696', '1995', '2314', '2606', '3024', '3523', '4403', '5387', '6507', '7560', '8078', '8911', '10328', '10869', '12210', '13197', '13832', '14393', '14967', '15729', '17167', '17920', '18681', '19323', '19718', '20265', '20796', '21340', '21856', '22245', '22614', '22856', '23293', '23660', '24087', '24376']\n\n 3 ____ 132 285\n132 ['Italy', '43.0', '12.0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '3', '7', '10', '12', '17', '21', '29', '34', '52', '79', '107', '148', '197', '233', '366', '463', '631', '827', '827', '1266', '1441', '1809', '2158', '2503', '2978', '3405', '4032', '4825', '5476', '6077', '6820', '7503', '8215', '9134', '10023', '10779', '11591', '12428', '13155', '13915', '14681', '15362', '15887', '16523', '17127', '17669', '18279', '18849', '19468', '19899', '20465', '21067', '21645', '22170', '22745', '23227', '23660', '24114', '24648', '25085', '25549', '25969', '26384', '26644', '26977', '27359', '27682', '27967']\n\n 4 ____ 196 268\n196 ['Spain', '40.0', '-4.0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '3', '5', '10', '17', '28', '35', '54', '55', '133', '195', '289', '342', '533', '623', '830', '1043', '1375', '1772', '2311', '2808', '3647', '4365', '5138', '5982', '6803', '7716', '8464', '9387', '10348', '11198', '11947', '12641', '13341', '14045', '14792', '15447', '16081', '16606', '17209', '17756', '18056', '18708', '19315', '20002', '20043', '20453', '20852', '21282', '21717', '22157', '22524', '22902', '23190', '23521', '23822', '24275', '24543']\n\n 5 ____ 218 674\n218 ['United Kingdom', '55.3781', '-3.4360000000000004', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '2', '3', '7', '7', '9', '10', '28', '43', '65', '81', '115', '158', '194', '250', '285', '359', '508', '694', '877', '1161', '1455', '1669', '2043', '2425', '3095', '3747', '4461', '5221', '5865', '6433', '7471', '8505', '9608', '10760', '11599', '12285', '13029', '14073', '14915', '15944', '16879', '17994', '18492', '19051', '20223', '21060', '21787', '22792', '23635', '24055', '24393', '25302', '26097', '26771']\n\n 6 ____ 220 2029\n220 ['US', '37.0902', '-95.7129', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '6', '7', '11', '12', '14', '17', '21', '22', '28', '36', '41', '49', '58', '73', '99', '133', '164', '258', '349', '442', '586', '786', '1008', '1316', '1726', '2265', '2731', '3420', '4192', '5367', '6501', '7921', '9246', '10855', '12375', '13894', '16191', '18270', '20255', '22333', '24342', '26086', '27870', '30262', '32734', '34827', '37411', '39753', '40945', '42659', '45086', '47412', '49724', '51493', '53755', '54881', '56259', '58355', '60967', '62996']\n261\n" ], [ "COUNTRY=\"Brazil\"\n\nfor lines in ALLcountries:\n linez=str(lines)\n linez=linez.replace(\"[\",\"\")\n linez=linez.replace(\"]\",\"\")\n linez=linez.replace(\"'\",\"\")\n lineZ=str(linez).split(\",\") \n if COUNTRY==(lineZ[0]):print(linez)", "Brazil, -14.235, -51.9253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 6, 11, 15, 25, 34, 46, 59, 77, 92, 111, 136, 159, 201, 240, 324, 359, 445, 486, 564, 686, 819, 950, 1057, 1124, 1223, 1328, 1532, 1736, 1924, 2141, 2354, 2462, 2587, 2741, 2906, 3331, 3704, 4057, 4286, 4603, 5083, 5513, 6006\n" ], [ "cnt=0\nfor line in ALLcountries:\n cnt=cnt+1\nprint(cnt)\nprint(len(ALLcountries))\nprint(\"----------------------------------------\")\ncnt=0\nfor line in DATA:\n cnt=cnt+1\n lines=line.split(\",\")\n c=int(lines[-2]),int(lines[-1]),int(lines[-1])-int(lines[-2])\n if int(lines[-1])-int(lines[-2])>500:\n print(\"\\n____\",cnt,int(lines[-1])-int(lines[-2]))\n print(cnt,ALLcountries[cnt-1])\nprint(cnt)", "261\n261\n----------------------------------------\n\n____ 218 674\n218 ['United Kingdom', '55.3781', '-3.4360000000000004', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '2', '3', '7', '7', '9', '10', '28', '43', '65', '81', '115', '158', '194', '250', '285', '359', '508', '694', '877', '1161', '1455', '1669', '2043', '2425', '3095', '3747', '4461', '5221', '5865', '6433', '7471', '8505', '9608', '10760', '11599', '12285', '13029', '14073', '14915', '15944', '16879', '17994', '18492', '19051', '20223', '21060', '21787', '22792', '23635', '24055', '24393', '25302', '26097', '26771']\n\n____ 220 2029\n220 ['US', '37.0902', '-95.7129', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '6', '7', '11', '12', '14', '17', '21', '22', '28', '36', '41', '49', '58', '73', '99', '133', '164', '258', '349', '442', '586', '786', '1008', '1316', '1726', '2265', '2731', '3420', '4192', '5367', '6501', '7921', '9246', '10855', '12375', '13894', '16191', '18270', '20255', '22333', '24342', '26086', '27870', '30262', '32734', '34827', '37411', '39753', '40945', '42659', '45086', '47412', '49724', '51493', '53755', '54881', '56259', '58355', '60967', '62996']\n" ], [ "LASTFILE=\"05-01-13__id19_confirmed_US.csv\"\nDataIn = open(LASTFILE).read()\nALLCASES=[]\nDataIn = DataIn.split(\"\\n\")\nDatain = DataIn[7:]\nfor line in Datain:\n if len(line)>80:\n line=line.replace('\"','')\n #line=line.replace(',,',',XX,')\n #line=line.replace(\"\\n\",\"\")\n line = line.lstrip(\",\")\n line = line.split(\",\")\n ALLCASES.append(line)", "_____no_output_____" ], [ "LASTFILE=\"05-01-13__id19_confirmed_US.csv\"\nDataIn = open(LASTFILE).read()\nALLCASES=[]\nDataIn = DataIn.split(\"\\n\")\nDatain = DataIn[7:]\nfor line in Datain:\n if len(line)>80:\n linez = line.split(\"US,\",2)[-1]\n linez=linez.replace(\",\",\", \")\n linez=linez.split(\" \")\n if len(linez)!=100:\n linez = linez[:-1]\n ALLCASES.append(linez)\n if len(linez)==100: \n ALLCASES.append(linez)\n", "_____no_output_____" ], [ "694: 77 : ['0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '1,', '2,', '3,', '9,', '9,', '12,', '21,', '24,', '28,', '40,', '40,', '104,', '127,', '182,', '223,', '228,', '322,', '384,', '455,', '582,', '648,', '697,', '']\n695: 24 : ['840,', '914,', '1010,', '1077,', '1126,', '1228,', '1283,', '1350,', '1433,', '1494,', '1566,', '1603,', '1643,', '1692,', '1736,', '1820,', '1885,', '2009,', '2060,', '2126,', '2173,', '2254,', '2369,', '2492']\n2357: 97 : ['0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '1,', '4,', '8,', '22,', '27,', '29,', '43,', '45,', '59,', '59,', '65,', '81,', '95,', '135,', '148,', '176,', '200,', '224,', '242,', '298,', '311,', '340,', '340,', '417,', '452,', '479,', '494,', '494,', '535,', '548,', '579,', '612,', '626,', '652,', '657,', '657,', '725,', '736,', '766,', '787,', '837,', '']", "_____no_output_____" ], [ "cnt=0\nfor line in ALLCASES[1:]:\n cnt=cnt+1\n if cnt<5:print(line)\n", "['316.0', 'GU', 'GUM', '316', '66.0', 'Ex', 'Guam', 'US', '13.4443', '144.7937', 'Guam', ' US', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '3', '3', '5', '12', '14', '15', '27', '29', '32', '37', '45', '51', '55', '56', '58', '69', '77', '82', '84', '93', '112', '113', '121', '121', '128', '130', '133', '133', '133', '133', '135', '135', '136', '136', '136', '136', '136', '136', '139', '141', '141', '141', '141', '141', '141', '145']\n['580.0', 'MP', 'MNP', '580', '69.0', 'Ex', 'Northern Mariana Islands', 'US', '15.0979', '145.6739', 'Northern Mariana Islands', ' US', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '2', '6', '6', '8', '8', '8', '8', '8', '11', '11', '11', '11', '11', '11', '11', '13', '13', '13', '14', '14', '14', '14', '14', '14', '14', '14', '14', '14', '14', '14', '14']\n['630.0', 'PR', 'PRI', '630', '72.0', 'Ex', 'Puerto Rico', 'US', '18.2208', '-66.5901', 'Puerto Rico', ' US', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '5', '5', '5', '5', '14', '21', '23', '31', '39', '51', '64', '79', '100', '127', '174', '239', '286', '316', '316', '452', '475', '513', '573', '620', '683', '725', '788', '897', '903', '923', '974', '1043', '1068', '1118', '1213', '1252', '1298', '1252', '1416', '1276', '1307', '1371', '1389', '1400', '1433', '1539']\n['850.0', 'VI', 'VIR', '850', '78.0', 'Ex', 'Virgin Islands', 'US', '18.3358', '-64.8963', 'Virgin Islands', ' US', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '2', '3', '3', '6', '6', '7', '17', '17', '17', '19', '22', '23', '30', '30', '30', '30', '37', '40', '42', '43', '43', '45', '45', '50', '51', '51', '51', '51', '51', '51', '51', '53', '53', '53', '53', '54', '54', '54', '55', '57', '57', '57', '57', '66']\n" ], [ "TOTAL=0\nDATA = []\nL=len(ALLCASES)\nALL = ALLCASES[6:]\nprint(len(ALL))", "3252\n" ], [ "TOTAL=0\nDATA = []\nL=len(ALLCASES)\nALL = ALLCASES[1:]\nDAILY=[]\ncnt=0\nfor i in range(0,len(ALL)):\n if str(ALL[i]).count(\",\") !=109:\n print(\"XX\",i,\"XX\",str(ALL[i]).count(\",\"),ALL[i][-97:])\n print(len(ALL[i][-96:]),end=\" \")", "XX 30 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '3', '3', '3', '3', '4', '4', '5', '5', '6', '8', '10', '10', '12', '13', '14', '17', '18', '18', '18', '20', '24', '29', '29', '32', '32', '40', '41', '44', '44', '46', '46', '47', '50', '55']\n96 XX 77 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '3', '3', '4', '4', '4', '5', '7', '7', '7', '7', '8', '10', '11', '12', '13', '13', '13', '14', '15', '15', '15', '15', '15', '16', '16', '17', '19', '19', '19', '19', '19', '19', '19', '19', '19', '19', '19', '19', '19']\n96 XX 178 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '5', '5', '5', '5', '5', '5', '5', '5', '5', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7']\n96 XX 220 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '3', '5', '9', '10', '17', '17', '31', '38', '54', '54', '76', '76', '111', '125', '183', '254', '304', '353', '372', '373', '530', '547', '641', '729', '810', '810', '887', '977', '977', '996', '1032', '1219', '1286', '1406', '1489', '1489', '1608', '1666', '1666', '1732', '1772', '1827', '1928', '2058']\n96 XX 600 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1']\n96 XX 644 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3']\n96 XX 692 XX 86 ['840', '17197.0', 'Will', 'Illinois', 'US', '41.44619267', '-87.97862712', 'Will', ' Illinois', ' US', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '3', '9', '9', '12', '21', '24', '28', '40', '40', '104', '127', '182', '223', '228', '322', '384', '455', '582', '648', '697', '']\n87 XX 693 XX 23 ['840', '914', '1010', '1077', '1126', '1228', '1283', '1350', '1433', '1494', '1566', '1603', '1643', '1692', '1736', '1820', '1885', '2009', '2060', '2126', '2173', '2254', '2369', '2492']\n24 XX 1115 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '2', '3', '12', '12', '26', '36', '65', '91', '90', '107', '139', '153', '161', '189', '201', '222', '284', '286', '347', '358', '366', '370', '397', '415', '428', '432', '438', '440', '451', '468', '496', '508', '512', '515', '533', '536', '551', '557', '568', '574', '576', '587', '593']\n96 XX 1181 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '2', '2', '2', '2', '2', '2', '3', '3', '4', '4', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', '7', '8', '8', '8', '9', '9', '10', '10', '10']\n96 XX 1219 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '2', '5', '5', '6', '6', '14', '24', '25', '31', '67', '90', '129', '179', '208', '263', '306', '366', '424', '517', '601', '659', '722', '768', '835', '994', '1086', '1191', '1327', '1394', '1435', '1508', '1605', '1659', '1698', '1731', '1731', '1852', '1908', '2181', '2697', '2829', '2923', '3068', '3270', '3429', '3580']\n96 XX 1312 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '2', '6', '8', '14', '14', '23', '44', '67', '102', '477', '638', '876', '1122', '1389', '1810', '2316', '2704', '3195', '3735', '4470', '5069', '6096', '6762', '7518', '8270', '9045', '9626', '10093', '10539', '10951', '11164', '11648', '12209', '12544', '12544', '13233', '13471', '13692', '13912', '13912', '14561', '14994', '15407', '15407', '15748', '15872', '16173', '16494', '16729']\n96 XX 1382 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '2', '2', '3', '5', '5', '5', '10', '12', '12', '13', '13', '13', '13', '15', '16', '17', '28', '33', '34', '37', '38', '38', '42', '43', '43', '45', '46', '48', '52', '53', '54', '58', '59', '61', '61', '67', '69', '71', '71']\n96 XX 1430 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '2', '3', '3', '5', '7', '10', '12', '16', '24', '33', '34', '34', '40', '52', '57', '75', '79', '86', '98', '108', '111', '122', '135', '139', '140', '147', '157', '182', '189', '196', '201', '205', '209', '211', '221', '228', '235', '237', '238', '240', '252', '255', '259']\n96 XX 1698 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']\n96 XX 1814 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '2', '3', '3', '3', '3', '3', '3', '3', '4', '4', '3', '3', '3', '3', '3', '3', '3', '3', '3', '5', '4', '4', '4', '4', '4', '5', '5']\n96 XX 1829 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '6', '7', '9', '10', '12', '14', '16', '16', '17', '17', '21', '22', '26', '26', '26', '26', '28', '28', '28', '29', '30', '30', '30', '30', '30', '30', '31', '35', '35', '35', '35', '35', '35']\n96 XX 1876 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '2', '2', '2', '3', '3', '4', '4', '4', '4', '4', '4', '5', '5', '5', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', '7', '7', '7', '7', '7', '7', '7', '7']\n96 XX 2029 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1']\n96 XX 2145 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']\n96 XX 2298 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '2', '2', '3', '3', '4', '6', '8', '8', '9', '9', '9', '12', '16', '20', '23', '24', '24', '24', '25', '27', '27', '28', '30', '31', '31', '31', '32', '33', '33', '33', '33', '33']\n96 XX 2355 XX 106 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '4', '8', '22', '27', '29', '43', '45', '59', '59', '65', '81', '95', '135', '148', '176', '200', '224', '242', '298', '311', '340', '340', '417', '452', '479', '494', '494', '535', '548', '579', '612', '626', '652', '657', '657', '725', '736', '766', '787', '837', '']\n96 XX 2390 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1']\n96 XX 2445 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '2', '2', '2', '3', '3', '6', '6', '6', '9', '9', '11', '14', '16', '22', '23', '26', '26', '32', '33', '34', '39', '40', '42', '43', '51', '51', '53', '55', '56', '57', '58', '59', '59', '61', '67', '66', '67', '68', '70', '74', '74']\n96 XX 2484 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '2', '3', '3', '3', '3', '5', '7', '13', '17', '19', '19', '22', '43', '43', '47', '56', '56', '59', '68', '73', '73', '75', '73', '83', '86', '87', '90', '90', '96', '98', '99', '101', '104', '128', '131', '135']\n96 XX 2546 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1']\n96 XX 2625 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '2', '4', '4', '4', '4', '4', '4', '4']\n96 XX 2639 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '6', '6', '7', '7', '8', '9', '9', '9', '10', '11', '11', '13', '13', '13', '14']\n96 XX 2665 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '3', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '6']\n96 XX 2680 XX 104 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '3', '3', '3', '3', '3', '6', '6', '6', '6', '6', '7', '9', '9', '9', '13']\n96 XX 2723 XX 108 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '3', '3', '5', '6', '7', '11', '12', '12', '13', '14', '14', '14', '14', '16', '16', '16', '17', '25', '27', '28', '28', '28', '29', '29', '30', '30', '30', '32', '32', '33', '33', '35']\n96 XX 2724 XX 108 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1']\n96 XX 2725 XX 108 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '4', '4', '4', '4', '4', '4', '7', '9', '9', '9', '9', '9', '9', '11', '14', '14', '14', '14', '14', '14', '15', '16', '16', '16', '16', '16', '16', '16']\n96 XX 2726 XX 108 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '3', '3', '3', '5', '5', '7', '8', '7', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '9', '9', '9']\n96 XX 2727 XX 108 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '2', '2', '2', '2', '2', '2', '2', '2', '3', '4', '5', '2', '2', '7', '7', '7', '7', '7', '7', '9', '8', '8', '8', '8', '8', '8', '8', '9', '11', '11', '12', '12', '12', '13', '13', '13']\n96 XX 2739 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']\n96 XX 2952 XX 108 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '3', '3', '5', '5', '9', '10', '11', '13', '14', '15', '16', '16', '19', '19', '20', '20', '21', '21', '22', '25', '25', '25', '27', '29', '30', '31', '33', '33', '33', '36', '36', '37']\n96 XX 3027 XX 103 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '1', '1', '3', '3', '3', '3', '3', '3', '3']\n96 XX 3195 XX 108 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '47', '47', '47', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49', '49']\n96 XX 3247 XX 108 ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '20', '21', '21', '22', '23', '23', '30', '28', '28', '28', '28', '28', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103', '103']\n96 " ], [ "TOTAL=0\nDATA = []\nL=len(ALLCASES)\nALL = ALLCASES[1:]\nDAILY=[]\ncnt=0\nfor i in range(0,len(ALL)):\n print(ALL[i].count(\",\"))\n L=int(len(ALL[i]))\n cnt=cnt+1\n if cnt==1:print(ALL[i][5],ALL[i][6],ALL[i][8],ALL[i][9],int(ALL[i][-2]),int(ALL[i][-1]))\n if len(ALL[i])>5:Daily = \"'0', '0',\"+str(ALL[i]).split(\"', '0', '0',\",1)[-1]\n Daily=Daily.replace('\\'','')\n Daily=Daily.replace(']','')\n Daily=Daily.replace('[','')\n Daily=Daily.replace(' ','')\n Daily=Daily.replace('\"','')\n Dail=Daily.replace(',,',',X,')\n \n print(Dail)\n #print(Daily)\n daily = map(int,Dail.split(\",\"))\n \n daily =(list(daily))\n DAILY.append(daily)\n inc= daily[-1]-daily[-2]\n #print(ALL[i])\n print(\"XXXXXX\",i,ALL[i][3],ALL[i][4],ALL[i][5],ALL[i][6],ALL[i][9],ALL[i][10],daily,daily[-2],daily[-1],inc)\n #TOTAL=TOTAL+daily[-1]\n DATA.append([ALL[i][5],ALL[i][6],ALL[i][9],ALL[i][10],daily,daily[-2],daily[-1],inc])\nprint(cnt,TOTAL) ", "30.72774991 -87.72207058 Alabama US 174 174\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,3,4,4,5,5,10,15,18,19,20,24,28,29,29,38,42,44,56,59,66,71,72,87,91,101,103,109,112,117,123,132,143,147,147,161,168,171,174,174\nXXXXXX 0 Alabama US 30.72774991 -87.72207058 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 5, 10, 15, 18, 19, 20, 24, 28, 29, 29, 38, 42, 44, 56, 59, 66, 71, 72, 87, 91, 101, 103, 109, 112, 117, 123, 132, 143, 147, 147, 161, 168, 171, 174, 174] 174 174 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,3,3,4,9,9,10,10,11,12,14,15,18,20,22,28,29,30,32,32,33,35,37,37,39\nXXXXXX 1 Alabama US 31.868263 -85.3871286 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3, 3, 4, 9, 9, 10, 10, 11, 12, 14, 15, 18, 20, 22, 28, 29, 30, 32, 32, 33, 35, 37, 37, 39] 37 39 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,3,4,4,4,5,7,8,9,9,11,13,16,17,17,18,22,24,26,28,32,32,34,33,34,34,38,42,42,42,42\nXXXXXX 2 Alabama US 32.99642064 -87.12511459999996 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 4, 4, 5, 7, 8, 9, 9, 11, 13, 16, 17, 17, 18, 22, 24, 26, 28, 32, 32, 34, 33, 34, 34, 38, 42, 42, 42, 42] 42 42 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,4,5,5,5,5,5,6,9,10,10,10,10,10,11,12,12,13,14,16,17,18,20,20,21,22,26,29,31,31,31,34,34,34,36,37\nXXXXXX 3 Alabama US 33.98210918 -86.56790593 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 5, 5, 5, 5, 5, 6, 9, 10, 10, 10, 10, 10, 11, 12, 12, 13, 14, 16, 17, 18, 20, 20, 21, 22, 26, 29, 31, 31, 31, 34, 34, 34, 36, 37] 36 37 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,3,3,3,3,3,2,2,2,2,2,2,3,3,4,4,4,5,8,8,8,8,9,9,11,11,11,12,12,12,12,12,12,12,13\nXXXXXX 4 Alabama US 32.10030533 -85.71265535 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 8, 8, 8, 8, 9, 9, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13] 12 13 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,3,3,6,7,8,8,9,11,16,13,14,14,15,17,19,21,21,32,34,45,50,53\nXXXXXX 5 Alabama US 31.75300095 -86.68057478 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 6, 7, 8, 8, 9, 11, 16, 13, 14, 14, 15, 17, 19, 21, 21, 32, 34, 45, 50, 53] 50 53 3\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,8,9,11,12,18,21,23,34,41,49,53,54,57,59,61,62,62,62,63,66,71,80,83,85,88,89,89,91,90,92,93,94\nXXXXXX 6 Alabama US 33.77483727 -85.82630386 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 8, 9, 11, 12, 18, 21, 23, 34, 41, 49, 53, 54, 57, 59, 61, 62, 62, 62, 63, 66, 71, 80, 83, 85, 88, 89, 89, 91, 90, 92, 93, 94] 93 94 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,1,2,2,5,10,13,13,17,27,33,36,42,67,80,87,89,94,101,109,151,168,181,198,212,216,221,231,236,240,245,257,259,270,275,282,282,285,289,291,293,295\nXXXXXX 7 Alabama US 32.91360079 -85.39072749 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 2, 5, 10, 13, 13, 17, 27, 33, 36, 42, 67, 80, 87, 89, 94, 101, 109, 151, 168, 181, 198, 212, 216, 221, 231, 236, 240, 245, 257, 259, 270, 275, 282, 282, 285, 289, 291, 293, 295] 293 295 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,4,5,6,6,6,6,7,7,7,7,8,9,9,9,11,12,12,12,12,13,13,12,12,12,14,14,15,15,15\nXXXXXX 8 Alabama US 34.17805983 -85.60638968 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 4, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 9, 9, 9, 11, 12, 12, 12, 12, 13, 13, 12, 12, 12, 14, 14, 15, 15, 15] 15 15 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,4,6,7,7,10,11,13,14,15,15,15,19,20,20,25,26,30,30,33,33,35,37,37,39,41,43,44,46,47,49,49,51,51,52,53,53\nXXXXXX 9 Alabama US 32.85044126 -86.7173256 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 6, 7, 7, 10, 11, 13, 14, 15, 15, 15, 19, 20, 20, 25, 26, 30, 30, 33, 33, 35, 37, 37, 39, 41, 43, 44, 46, 47, 49, 49, 51, 51, 52, 53, 53] 53 53 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,3,4,4,4,4,5,5,6,6,6,6,8,10,10,12,12,13,13,14,14,17,18,21,22,25,25,32,39,39,39,43\nXXXXXX 10 Alabama US 32.02227341 -88.26564429999998 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 8, 10, 10, 12, 12, 13, 13, 14, 14, 17, 18, 21, 22, 25, 25, 32, 39, 39, 39, 43] 39 43 4\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,6,8,9,10,10,12,13,15,19,19,21,21,24,24,24,24,24,24,25,25,24,24,25,27,28,30,32\nXXXXXX 11 Alabama US 31.68099859 -87.83548597 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 6, 8, 9, 10, 10, 12, 13, 15, 19, 19, 21, 21, 24, 24, 24, 24, 24, 24, 25, 25, 24, 24, 25, 27, 28, 30, 32] 30 32 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,6,8,8,9,9,9,10,11,11,12,14,14,14,14,14,14,17,18,19,19,19,19,19,19,19,19,19,21,21\nXXXXXX 12 Alabama US 33.26984193 -85.85836077 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 6, 8, 8, 9, 9, 9, 10, 11, 11, 12, 14, 14, 14, 14, 14, 14, 17, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 21, 21] 21 21 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,4,5,5,5,6,6,7,7,7,9,9,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12\nXXXXXX 13 Alabama US 33.67679204 -85.52005899 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 9, 9, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12] 12 12 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,5,7,7,8,8,8,13,14,17,31,36,36,40,47,51,55,59,64,68,73,80,87,87,95,98,105,107,111\nXXXXXX 14 Alabama US 31.39932826 -85.98901039 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 5, 7, 7, 8, 8, 8, 13, 14, 17, 31, 36, 36, 40, 47, 51, 55, 59, 64, 68, 73, 80, 87, 87, 95, 98, 105, 107, 111] 107 111 4\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,4,4,4,5,5,5,6,6,7,7,7,8,8,9,10,11,11,12,13,15,16,16,16,20,22,23,23,23,23,27,27,29\nXXXXXX 15 Alabama US 34.69847452 -87.80168544 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, 10, 11, 11, 12, 13, 15, 16, 16, 16, 20, 22, 23, 23, 23, 23, 27, 27, 29] 27 29 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,2,2,4,4,3,3,5,5,5,5,8,8,10,10,9,9,9,9,9,9,9,9,9,9,9\nXXXXXX 16 Alabama US 31.43401703 -86.99320044 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 4, 4, 3, 3, 5, 5, 5, 5, 8, 8, 10, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9] 9 9 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,3,3,4,4,5,6,6,7,8,9,9,9,10,11,18,18,18,19,20,20,22,22,23,24,24,28,29,29,29,30,31,31,31\nXXXXXX 17 Alabama US 32.93690146 -86.24847739 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9, 9, 10, 11, 18, 18, 18, 19, 20, 20, 22, 22, 23, 24, 24, 28, 29, 29, 29, 30, 31, 31, 31] 31 31 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,3,3,4,4,4,4,5,9,10,10,11,13,13,16,17,18,19,21,22,24,26,27,29,31,31,33,34,35,36,36\nXXXXXX 18 Alabama US 31.247785399999998 -86.45050893 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 9, 10, 10, 11, 13, 13, 16, 17, 18, 19, 21, 22, 24, 26, 27, 29, 31, 31, 33, 34, 35, 36, 36] 36 36 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,5,5,6,6,6,6,6,8,10,10,11,12,16,17,19\nXXXXXX 19 Alabama US 31.72941803 -86.31593104 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 5, 5, 6, 6, 6, 6, 6, 8, 10, 10, 11, 12, 16, 17, 19] 17 19 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,3,4,6,6,7,7,8,8,9,9,15,15,15,20,21,22,22,30,31,39,39,40,40,40,53,42,42,44,45,44,44,47,47,50,52,52,55,55\nXXXXXX 20 Alabama US 34.13020303 -86.86888037 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 4, 6, 6, 7, 7, 8, 8, 9, 9, 15, 15, 15, 20, 21, 22, 22, 30, 31, 39, 39, 40, 40, 40, 53, 42, 42, 44, 45, 44, 44, 47, 47, 50, 52, 52, 55, 55] 55 55 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,4,4,4,6,6,6,8,12,12,12,14,14,17,20,21,21,22,22,23,23,25,25,25,25,27\nXXXXXX 21 Alabama US 31.43037123 -85.61095742 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 4, 4, 4, 6, 6, 6, 8, 12, 12, 12, 14, 14, 17, 20, 21, 21, 22, 22, 23, 23, 25, 25, 25, 25, 27] 25 27 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,4,7,7,7,7,7,7,7,11,10,14,14,17,18,21,21,22,25,26,29,30,29,32,32,33,37,37,37,41\nXXXXXX 22 Alabama US 32.32688101 -87.10866709999998 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 4, 7, 7, 7, 7, 7, 7, 7, 11, 10, 14, 14, 17, 18, 21, 21, 22, 25, 26, 29, 30, 29, 32, 32, 33, 37, 37, 37, 41] 37 41 4\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,4,4,4,4,5,8,10,13,14,14,14,14,15,17,21,26,27,29,29,32,34,40,42,46,51,58,61,61,61,70,74,76,77,77\nXXXXXX 23 Alabama US 34.45946862 -85.80782906 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 4, 4, 4, 4, 5, 8, 10, 13, 14, 14, 14, 14, 15, 17, 21, 26, 27, 29, 29, 32, 34, 40, 42, 46, 51, 58, 61, 61, 61, 70, 74, 76, 77, 77] 77 77 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,4,5,5,6,6,6,8,9,10,12,12,13,13,13,14,17,19,19,19,19,22,22,27,29,30,33,35,43,47,54,54,58,63,69,73,74,74,74,74,79,79,82,84,86\nXXXXXX 24 Alabama US 32.59785413 -86.14415284 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 4, 5, 5, 6, 6, 6, 8, 9, 10, 12, 12, 13, 13, 13, 14, 17, 19, 19, 19, 19, 22, 22, 27, 29, 30, 33, 35, 43, 47, 54, 54, 58, 63, 69, 73, 74, 74, 74, 74, 79, 79, 82, 84, 86] 84 86 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,3,3,3,3,5,5,9,8,8,10,9,11,14,12,14,16,17,18,21,22,22,25,26,27,27,28\nXXXXXX 25 Alabama US 31.1256789 -87.15918694 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 5, 5, 9, 8, 8, 10, 9, 11, 14, 12, 14, 16, 17, 18, 21, 22, 22, 25, 26, 27, 27, 28] 27 28 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,4,6,6,6,8,10,13,19,26,35,41,43,43,49,63,74,75,77,78,78,86,87,93,98,100,109,116,120,121,121,125,126,130,139,139\nXXXXXX 26 Alabama US 34.04567266 -86.04051873 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 6, 6, 6, 8, 10, 13, 19, 26, 35, 41, 43, 43, 49, 63, 74, 75, 77, 78, 78, 86, 87, 93, 98, 100, 109, 116, 120, 121, 121, 125, 126, 130, 139, 139] 139 139 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,2,3,4,4,4,4,4,4,4,4,3,4,4,4,4,4,5,5,5,6,6\nXXXXXX 27 Alabama US 33.72076938 -87.73886638 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 5, 5, 6, 6] 6 6 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,3,3,3,3,3,3,3,4,5,6,6,6,7,7,8,8,8,10,10,12,14,17,18,17,17,18,18,22,25,32,32,41,43,44,45,58\nXXXXXX 28 Alabama US 34.44235334 -87.84289505 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 6, 6, 7, 7, 8, 8, 8, 10, 10, 12, 14, 17, 18, 17, 17, 18, 18, 22, 25, 32, 32, 41, 43, 44, 45, 58] 45 58 13\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,1,2,2,2,4,4,4,4,5,6,6,6,8,8,8,9,9\nXXXXXX 29 Alabama US 31.09389027 -85.83572839 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 2, 2, 2, 4, 4, 4, 4, 5, 6, 6, 6, 8, 8, 8, 9, 9] 9 9 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,4,4,5,5,6,8,10,10,12,13,14,17,18,18,18,20,24,29,29,32,32,40,41,44,44,46,46,47,50,55\nXXXXXX 30 US 0 0 0 0 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 3, 3, 3, 4, 4, 5, 5, 6, 8, 10, 10, 12, 13, 14, 17, 18, 18, 18, 20, 24, 29, 29, 32, 32, 40, 41, 44, 44, 46, 46, 47, 50, 55] 50 55 5\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,3,3,3,4,7,7,7,7,11,15,15,17,18,21,22,23,25,31,34,36,37,39,39,41,41,41,43,47\nXXXXXX 31 Alabama US 32.76039258 -87.63284988 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 3, 3, 3, 4, 7, 7, 7, 7, 11, 15, 15, 17, 18, 21, 22, 23, 25, 31, 34, 36, 37, 39, 39, 41, 41, 41, 43, 47] 43 47 4\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,3,4,4,5,7,10,10,11,13,14,14,15,16,17,17,18,20,20,22,22,22,22,22,22,23,24\nXXXXXX 32 Alabama US 31.51148016 -85.24267944 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 4, 4, 5, 7, 10, 10, 11, 13, 14, 14, 15, 16, 17, 17, 18, 20, 20, 22, 22, 22, 22, 22, 22, 23, 24] 23 24 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,3,3,4,6,9,9,8,9,12,14,15,22,25,25,30,33,37,44,47,52,54,57,64,63,66,70,73,75,78,76,76,77,79,84,87,90\nXXXXXX 33 Alabama US 31.15197924 -85.29939599 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 3, 4, 6, 9, 9, 8, 9, 12, 14, 15, 22, 25, 25, 30, 33, 37, 44, 47, 52, 54, 57, 64, 63, 66, 70, 73, 75, 78, 76, 76, 77, 79, 84, 87, 90] 87 90 3\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,4,4,5,5,5,8,8,9,12,12,14,17,18,19,22,22,22,24,26,29,31,32,32,38,38,39,41,42,43,45,45,45,45,46,47,49\nXXXXXX 34 Alabama US 34.78144169 -85.99750489 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 4, 4, 5, 5, 5, 8, 8, 9, 12, 12, 14, 17, 18, 19, 22, 22, 22, 24, 26, 29, 31, 32, 32, 38, 38, 39, 41, 42, 43, 45, 45, 45, 45, 46, 47, 49] 47 49 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,5,17,21,25,34,50,61,71,86,91,129,159,177,195,245,254,270,292,314,351,373,416,423,457,479,507,536,579,597,612,620,625,634,651,671,682,688,698,726,778,797,797,839,839,861,880,886\nXXXXXX 35 Alabama US 33.55554728 -86.89506300000002 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 5, 17, 21, 25, 34, 50, 61, 71, 86, 91, 129, 159, 177, 195, 245, 254, 270, 292, 314, 351, 373, 416, 423, 457, 479, 507, 536, 579, 597, 612, 620, 625, 634, 651, 671, 682, 688, 698, 726, 778, 797, 797, 839, 839, 861, 880, 886] 880 886 6\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,5,5,5,7,7,7,8,8,7,7,7,7,8,8,9,9,8,9,10,10,10,10,10,10,11\nXXXXXX 36 Alabama US 33.77995024 -88.09668032 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 5, 5, 5, 7, 7, 7, 8, 8, 7, 7, 7, 7, 8, 8, 9, 9, 8, 9, 10, 10, 10, 10, 10, 10, 11] 10 11 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,3,6,9,9,12,12,12,12,12,14,14,16,16,16,18,18,20,20,21,21,22,22,22,22,23,23,23,24,25,25,25,25,25,31,31,30,31,38\nXXXXXX 37 Alabama US 34.90171875 -87.65624729 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 3, 3, 6, 9, 9, 12, 12, 12, 12, 12, 14, 14, 16, 16, 16, 18, 18, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 24, 25, 25, 25, 25, 25, 31, 31, 30, 31, 38] 31 38 7\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,2,3,3,3,3,3,3,4,4,6,8,8,8,8,8,8,8,8,8,8,8,8,9,9,10,10,12,12,12,12,12,12,12,12,12\nXXXXXX 38 Alabama US 34.52041498 -87.31069453 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 3, 3, 3, 3, 3, 3, 4, 4, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12] 12 12 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,8,10,11,12,16,19,26,40,47,48,56,59,71,75,81,91,99,102,109,113,128,148,199,209,218,236,250,265,269,292,301,305,308,311,319,331,340,351,351,365,368,377,386,394\nXXXXXX 39 Alabama US 32.60154883 -85.35132246 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 8, 10, 11, 12, 16, 19, 26, 40, 47, 48, 56, 59, 71, 75, 81, 91, 99, 102, 109, 113, 128, 148, 199, 209, 218, 236, 250, 265, 269, 292, 301, 305, 308, 311, 319, 331, 340, 351, 351, 365, 368, 377, 386, 394] 386 394 8\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,4,6,13,14,16,16,20,22,23,25,30,31,31,33,32,32,34,36,36,37,37,37,37,38,40,40,40,40,40,39,40,41,41,41,42,44,44,44\nXXXXXX 40 Alabama US 34.81185586 -86.98310072 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 6, 13, 14, 16, 16, 20, 22, 23, 25, 30, 31, 31, 33, 32, 32, 34, 36, 36, 37, 37, 37, 37, 38, 40, 40, 40, 40, 40, 39, 40, 41, 41, 41, 42, 44, 44, 44] 44 44 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,3,6,6,8,10,12,12,14,14,15,19,20,24,25,27,28,31,32,32,34,36,36,38,39,53,57,65\nXXXXXX 41 Alabama US 32.1597283 -86.65158371 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 6, 6, 8, 10, 12, 12, 14, 14, 15, 19, 20, 24, 25, 27, 28, 31, 32, 32, 34, 36, 36, 38, 39, 53, 57, 65] 57 65 8\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,3,5,5,5,5,6,6,9,9,11,14,15,19,19,21,24,24,25,26,27,28,27,29,29,34,34,35,36,37\nXXXXXX 42 Alabama US 32.38759944 -85.69267724 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 3, 5, 5, 5, 5, 6, 6, 9, 9, 11, 14, 15, 19, 19, 21, 24, 24, 25, 26, 27, 28, 27, 29, 29, 34, 34, 35, 36, 37] 36 37 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,5,7,9,16,21,21,35,43,47,62,79,91,99,105,114,121,125,134,141,150,153,173,178,186,187,187,191,191,198,217,197,199,202,203,205,205,202,202,211,214,222,224,227\nXXXXXX 43 Alabama US 34.76327133 -86.55069633 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 5, 7, 9, 16, 21, 21, 35, 43, 47, 62, 79, 91, 99, 105, 114, 121, 125, 134, 141, 150, 153, 173, 178, 186, 187, 187, 191, 191, 198, 217, 197, 199, 202, 203, 205, 205, 202, 202, 211, 214, 222, 224, 227] 224 227 3\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,5,5,4,4,5,7,8,8,13,14,14,14,15,19,21,22,23,23,24,24,25,26,30,35,40,38,39,39,41,43,44,46,49\nXXXXXX 44 Alabama US 32.24767634 -87.78796182 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 5, 5, 4, 4, 5, 7, 8, 8, 13, 14, 14, 14, 15, 19, 21, 22, 23, 23, 24, 24, 25, 26, 30, 35, 40, 38, 39, 39, 41, 43, 44, 46, 49] 46 49 3\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,3,7,7,9,10,10,9,9,11,16,17,17,19,21,23,33,39,42,48,56,58,58,59,61,60,61,63,65,65,67,69,69,74,75,76,76,75\nXXXXXX 45 Alabama US 34.13697363 -87.88704173 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 3, 7, 7, 9, 10, 10, 9, 9, 11, 16, 17, 17, 19, 21, 23, 33, 39, 42, 48, 56, 58, 58, 59, 61, 60, 61, 63, 65, 65, 67, 69, 69, 74, 75, 76, 76, 75] 76 75 -1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,4,4,5,7,7,6,6,16,17,20,33,39,42,60,69,82,97,102,104,106,114,122,138,149,167,194,241,258,267,267,307,310,313,316,317\nXXXXXX 46 Alabama US 34.36975964 -86.30486727 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 4, 4, 5, 7, 7, 6, 6, 16, 17, 20, 33, 39, 42, 60, 69, 82, 97, 102, 104, 106, 114, 122, 138, 149, 167, 194, 241, 258, 267, 267, 307, 310, 313, 316, 317] 316 317 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,2,2,2,6,10,18,23,29,40,44,52,56,67,103,114,125,143,201,249,309,358,408,454,468,509,548,577,621,637,661,680,714,756,810,845,845,917,942,994,1033,1058\nXXXXXX 47 Alabama US 30.78472347 -88.20842409 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 2, 2, 2, 6, 10, 18, 23, 29, 40, 44, 52, 56, 67, 103, 114, 125, 143, 201, 249, 309, 358, 408, 454, 468, 509, 548, 577, 621, 637, 661, 680, 714, 756, 810, 845, 845, 917, 942, 994, 1033, 1058] 1033 1058 25\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,3,5,5,5,5,5,5,6,6,6,6,7,7,7,7,7,8,9,9,9,9,9,11,11,12,11,12,12,13\nXXXXXX 48 Alabama US 31.56729412 -87.36995001 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 3, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 9, 9, 9, 9, 9, 11, 11, 12, 11, 12, 12, 13] 12 13 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,3,3,3,3,4,9,13,17,18,18,21,22,29,35,45,59,62,67,71,74,77,88,92,102,119,135,161,174,197,207,215,226,231,245,253,263,274,274,289,292,302,316,337\nXXXXXX 49 Alabama US 32.2206831 -86.20969272 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 9, 13, 17, 18, 18, 21, 22, 29, 35, 45, 59, 62, 67, 71, 74, 77, 88, 92, 102, 119, 135, 161, 174, 197, 207, 215, 226, 231, 245, 253, 263, 274, 274, 289, 292, 302, 316, 337] 316 337 21\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,5,9,9,15,17,17,20,19,21,24,24,27,29,30,31,36,36,37,38,42,41,42,44,46,45,47,48,51,52,50,55,55,64,65,68,68,68\nXXXXXX 50 Alabama US 34.45500589 -86.85475946 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, 9, 9, 15, 17, 17, 20, 19, 21, 24, 24, 27, 29, 30, 31, 36, 36, 37, 38, 42, 41, 42, 44, 46, 45, 47, 48, 51, 52, 50, 55, 55, 64, 65, 68, 68, 68] 68 68 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,3,4,6,6,7,7,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9\nXXXXXX 51 Alabama US 32.64048341 -87.29770589 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 3, 4, 6, 6, 7, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9] 9 9 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,4,4,9,10,12,12,12,14,15,17,19,21,22,23,24,26,30,32,32,38,40,43,44,44,45,45,48,47,47,48,48\nXXXXXX 52 Alabama US 33.28094866 -88.08818103 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 4, 4, 9, 10, 12, 12, 12, 14, 15, 17, 19, 21, 22, 23, 24, 26, 30, 32, 32, 38, 40, 43, 44, 44, 45, 45, 48, 47, 47, 48, 48] 48 48 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,4,4,4,4,5,7,10,10,14,14,14,16,17,18,18,20,21,22,24,27,29,34,37,41,46,53,57,58,58,62,65,65,67,67\nXXXXXX 53 Alabama US 31.80396383 -85.9408295 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 4, 4, 4, 4, 5, 7, 10, 10, 14, 14, 14, 16, 17, 18, 18, 20, 21, 22, 24, 27, 29, 34, 37, 41, 46, 53, 57, 58, 58, 62, 65, 65, 67, 67] 67 67 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,5,6,10,11,11,12,13,15,16,22,27,36,40,45,45,46,51,51,53,56,59,60,58,60,60,60,61,62,62,62\nXXXXXX 54 Alabama US 33.29526734 -85.45708831 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 5, 6, 10, 11, 11, 12, 13, 15, 16, 22, 27, 36, 40, 45, 45, 46, 51, 51, 53, 56, 59, 60, 58, 60, 60, 60, 61, 62, 62, 62] 62 62 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,4,4,8,10,12,14,14,20,22,24,27,30,30,32,35,41,43,48,48,52,54,53,53,53,53,55,55,57\nXXXXXX 55 Alabama US 32.28725256 -85.18415324 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 4, 8, 10, 12, 14, 14, 20, 22, 24, 27, 30, 30, 32, 35, 41, 43, 48, 48, 52, 54, 53, 53, 53, 53, 55, 55, 57] 55 57 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,3,3,4,6,6,9,11,13,13,15,18,19,23,25,26,31,30,30,36,37,38,42,43,45,47,49,52,53,54,57,59,62,62,63,63,64,68,70,70,72\nXXXXXX 56 Alabama US 33.71902176 -86.31029372 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 3, 3, 4, 6, 6, 9, 11, 13, 13, 15, 18, 19, 23, 25, 26, 31, 30, 30, 36, 37, 38, 42, 43, 45, 47, 49, 52, 53, 54, 57, 59, 62, 62, 63, 63, 64, 68, 70, 70, 72] 70 72 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,4,9,10,16,17,22,27,42,52,66,72,79,79,88,88,98,109,124,139,147,158,159,170,184,193,212,230,235,237,243,248,257,268,273,273,278,283,294,294,311,318,319,320,320\nXXXXXX 57 Alabama US 33.26879845 -86.66232561 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 4, 9, 10, 16, 17, 22, 27, 42, 52, 66, 72, 79, 79, 88, 88, 98, 109, 124, 139, 147, 158, 159, 170, 184, 193, 212, 230, 235, 237, 243, 248, 257, 268, 273, 273, 278, 283, 294, 294, 311, 318, 319, 320, 320] 320 320 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,4,7,6,6,8,15,16,17,18,19,20,21,26,28,31,33,35,36,40,44,46,47,51,51,53,55,55,56,64\nXXXXXX 58 Alabama US 32.59117397 -88.19916205 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 7, 6, 6, 8, 15, 16, 17, 18, 19, 20, 21, 26, 28, 31, 33, 35, 36, 40, 44, 46, 47, 51, 51, 53, 55, 55, 56, 64] 56 64 8\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,3,4,4,4,4,5,7,7,8,11,16,17,20,20,22,29,32,32,34,38,38,38,40,42,44,46,47,50,52,53,54,54,57,58,59,59,61\nXXXXXX 59 Alabama US 33.37823223 -86.16886178 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 7, 7, 8, 11, 16, 17, 20, 20, 22, 29, 32, 32, 34, 38, 38, 38, 40, 42, 44, 46, 47, 50, 52, 53, 54, 54, 57, 58, 59, 59, 61] 59 61 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,4,4,4,5,8,8,12,13,17,19,20,29,30,33,35,45,53,61,98,101,123,127,158,160,179,195,193,228,242,254,261,261,274,275,279,282,285\nXXXXXX 60 Alabama US 32.86698258 -85.79833053 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 4, 4, 5, 8, 8, 12, 13, 17, 19, 20, 29, 30, 33, 35, 45, 53, 61, 98, 101, 123, 127, 158, 160, 179, 195, 193, 228, 242, 254, 261, 261, 274, 275, 279, 282, 285] 282 285 3\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,3,3,4,4,6,7,9,10,15,19,21,22,23,24,29,30,34,41,43,44,73,77,83,85,91,99,119,121,122,128,132,152,141,145,153,158,165,173,182,182,192,195,199,202,208\nXXXXXX 61 Alabama US 33.28726072 -87.52556818 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 3, 4, 4, 6, 7, 9, 10, 15, 19, 21, 22, 23, 24, 29, 30, 34, 41, 43, 44, 73, 77, 83, 85, 91, 99, 119, 121, 122, 128, 132, 152, 141, 145, 153, 158, 165, 173, 182, 182, 192, 195, 199, 202, 208] 202 208 6\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,3,5,9,17,23,28,30,30,32,32,34,48,49,49,54,63,65,69,72,78,81,84,84,84,84,83,83,85,90,91,90,89,89,89,92,93,94,95,96\nXXXXXX 62 Alabama US 33.80270512 -87.30027177 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 3, 5, 9, 17, 23, 28, 30, 30, 32, 32, 34, 48, 49, 49, 54, 63, 65, 69, 72, 78, 81, 84, 84, 84, 84, 83, 83, 85, 90, 91, 90, 89, 89, 89, 92, 93, 94, 95, 96] 95 96 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,4,4,3,3,3,5,5,5,5,7,7,11,11,12,12,12,12,12,13,14,15,16,16,17,18,18,19,19,26,27,33,34,34\nXXXXXX 63 Alabama US 31.4092794 -88.20689944 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 4, 4, 3, 3, 3, 5, 5, 5, 5, 7, 7, 11, 11, 12, 12, 12, 12, 12, 13, 14, 15, 16, 16, 17, 18, 18, 19, 19, 26, 27, 33, 34, 34] 34 34 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,2,2,3,3,5,6,11,12,12,13,13,16,18,24,30,31,31,34,39,40,45,47,49,49,50,52,53,53,56,58,60,62,66\nXXXXXX 64 Alabama US 31.98773215 -87.30891118 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 3, 5, 6, 11, 12, 12, 13, 13, 16, 18, 24, 30, 31, 31, 34, 39, 40, 45, 47, 49, 49, 50, 52, 53, 53, 56, 58, 60, 62, 66] 62 66 4\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,7,9,9,9,9,10,10,10,10,10,11,11,13,13,15\nXXXXXX 65 Alabama US 34.15030532 -87.37325922 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 7, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 11, 13, 13, 15] 13 15 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 66 Alaska US 55.32222414 -161.9722021 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 67 Alaska US 52.72541116 -110.4086433 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,4,4,4,5,13,17,17,28,30,43,54,59,61,65,67,73,81,85,88,98,103,109,112,121,127,131,136,139,143,150,151,154,155,160,164,166,168,168,168,171,175,179,179\nXXXXXX 68 Alaska US 61.14998174 -149.14269860000005 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 4, 4, 4, 5, 13, 17, 17, 28, 30, 43, 54, 59, 61, 65, 67, 73, 81, 85, 88, 98, 103, 109, 112, 121, 127, 131, 136, 139, 143, 150, 151, 154, 155, 160, 164, 166, 168, 168, 168, 171, 175, 179, 179] 179 179 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nXXXXXX 69 Alaska US 60.90980451 -159.8561831 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 1 1 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 70 Alaska US 58.74513976 -156.701064 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 71 Alaska US 63.67264044 -150.0076108 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 72 Alaska US 59.79603738 -158.23819419999995 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,3,5,6,7,7,7,10,11,10,19,23,28,30,35,40,42,46,53,53,65,71,73,76,76,79,79,79,79,79,79,79,79,79,79,79,79,79,79,80,80,81,81,81\nXXXXXX 73 Alaska US 64.80726247 -146.5692662 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 5, 6, 7, 7, 7, 10, 11, 10, 19, 23, 28, 30, 35, 40, 42, 46, 53, 53, 65, 71, 73, 76, 76, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 80, 80, 81, 81, 81] 81 81 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 74 Alaska US 59.09893571 -135.4679843 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 75 Alaska US 58.29307365 -135.64244240000002 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,3,4,4,5,5,9,10,11,12,14,14,14,14,14,15,15,16,17,18,21,23,24,24,24,24,26,27,27,27,27,27,27,27,27,27\nXXXXXX 76 Alaska US 58.45031811 -134.200436 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 9, 10, 11, 12, 14, 14, 14, 14, 14, 15, 15, 16, 17, 18, 21, 23, 24, 24, 24, 24, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27] 27 27 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,4,4,4,5,7,7,7,7,8,10,11,12,13,13,13,14,15,15,15,15,15,16,16,17,19,19,19,19,19,19,19,19,19,19,19,19,19\nXXXXXX 77 US 0 0 0 0 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4, 4, 5, 7, 7, 7, 7, 8, 10, 11, 12, 13, 13, 13, 14, 15, 15, 15, 15, 15, 16, 16, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19] 19 19 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,6,6,6,8,11,11,12,12,13,13,13,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16\nXXXXXX 78 Alaska US 55.57445008 -130.975561 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 6, 6, 6, 8, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16] 16 16 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nXXXXXX 79 Alaska US 57.65529415 -153.7493579 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 1 1 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 80 Alaska US 62.15429159999999 -163.39678830000003 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 81 Alaska US 58.62403337 -156.21405890000003 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,3,3,4,4,4,4,4,4,5,6,9,10,14,14,15,15,15,15,17,18,19,19,20,20,20,20,20,21,21,21,21\nXXXXXX 82 Alaska US 62.31305045 -149.5741743 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 4, 4, 4, 4, 4, 4, 5, 6, 9, 10, 14, 14, 15, 15, 15, 15, 17, 18, 19, 19, 20, 20, 20, 20, 20, 21, 21, 21, 21] 21 21 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nXXXXXX 83 Alaska US 64.90320724 -164.0353804 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 1 1 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 84 Alaska US 69.31479216 -153.4836093 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 85 Alaska US 67.04919196 -159.7503946 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,4,4,4\nXXXXXX 86 Alaska US 57.13978948 -132.9540995 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4] 4 4 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nXXXXXX 87 Alaska US 55.76261984 -133.0511621 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] 2 2 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1\nXXXXXX 88 Alaska US 57.24124555 -135.3206587 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1] 1 1 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 89 Alaska US 59.56149996 -135.33377480000001 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nXXXXXX 90 Alaska US 63.87692095 -143.2127643 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 1 1 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 91 Alaska US 61.47502768 -144.7126799 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 92 Alaska US 56.3202004 -132.05837309999998 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 93 Alaska US 59.890980799999994 -140.36014509999998 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\nXXXXXX 94 Alaska US 65.50815459 -151.39073869999999 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 1 1 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,4,4,7,9,11,13,13,17,16,17,17,17,20,23,25,28,34,52,55,66,72,89,97,110,118,141,169,178,202,226,235,268,296,314,336,362,380,392,449\nXXXXXX 95 Arizona US 35.39465006 -109.4892383 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4, 7, 9, 11, 13, 13, 17, 16, 17, 17, 17, 20, 23, 25, 28, 34, 52, 55, 66, 72, 89, 97, 110, 118, 141, 169, 178, 202, 226, 235, 268, 296, 314, 336, 362, 380, 392, 449] 392 449 57\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,3,3,4,4,4,4,5,7,8,9,9,9,11,11,13,15,16,15,15,18,20,22,24,28,29,31,31,34,36,36,36,37,38,39\nXXXXXX 96 Arizona US 31.87934684 -109.7516088 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 7, 8, 9, 9, 9, 11, 11, 13, 15, 16, 15, 15, 18, 20, 22, 24, 28, 29, 31, 31, 34, 36, 36, 36, 37, 38, 39] 38 39 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,8,11,14,17,18,23,28,41,56,62,71,81,85,114,126,147,155,167,179,186,210,214,238,243,253,270,266,299,304,314,333,337,342,353,372,391,402,420,425,439,453,486\nXXXXXX 97 Arizona US 35.83883429 -111.77071780000001 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 8, 11, 14, 17, 18, 23, 28, 41, 56, 62, 71, 81, 85, 114, 126, 147, 155, 167, 179, 186, 210, 214, 238, 243, 253, 270, 266, 299, 304, 314, 333, 337, 342, 353, 372, 391, 402, 420, 425, 439, 453, 486] 453 486 33\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,3,3,3,3,3,3,3,3,3,3,3,3,5,5,7,7,8,9,10,12,11,11,11,11,11,12,13\nXXXXXX 98 Arizona US 33.80190085 -110.8132779 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 7, 7, 8, 9, 10, 12, 11, 11, 11, 11, 11, 12, 13] 12 13 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,4,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,4,7,6,7,9,9,10,16\nXXXXXX 99 Arizona US 32.93166885 -109.8882178 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 7, 6, 7, 9, 9, 10, 16] 10 16 6\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nXXXXXX 100 Arizona US 33.21498827 -109.2405279 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] 2 2 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,3,3,3,3,4,4,4,4,4,4,5,5,5,5,5,5,6,6,6,8,7,7,7,7,8,14\nXXXXXX 101 Arizona US 33.72854224 -113.98100290000001 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 8, 7, 7, 7, 7, 8, 14] 8 14 6\n0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,4,4,8,9,11,22,34,49,81,139,199,251,299,399,454,545,690,788,871,961,1049,1171,1326,1433,1495,1559,1689,1741,1891,1960,2020,2056,2146,2264,2404,2491,2589,2636,2738,2846,2970,3116,3234,3359,3457,3578,3723,3972\nXXXXXX 102 Arizona US 33.34835867 -112.49181540000001 US 0 [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 8, 9, 11, 22, 34, 49, 81, 139, 199, 251, 299, 399, 454, 545, 690, 788, 871, 961, 1049, 1171, 1326, 1433, 1495, 1559, 1689, 1741, 1891, 1960, 2020, 2056, 2146, 2264, 2404, 2491, 2589, 2636, 2738, 2846, 2970, 3116, 3234, 3359, 3457, 3578, 3723, 3972] 3723 3972 249\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,4,5,6,7,7,7,8,9,12,16,20,23,23,27,28,30,30,40,45,45,51,51,52,54,56,59,62,69,73,81,88,96,99,105,117\nXXXXXX 103 Arizona US 35.70471703 -113.7577902 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 5, 6, 7, 7, 7, 8, 9, 12, 16, 20, 23, 23, 27, 28, 30, 30, 40, 45, 45, 51, 51, 52, 54, 56, 59, 62, 69, 73, 81, 88, 96, 99, 105, 117] 105 117 12\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,3,10,13,25,32,37,43,49,57,62,88,91,102,129,148,177,195,210,222,240,286,287,321,335,345,355,390,410,435,452,459,473,485,527,564,583,612,625,628,665,682,712\nXXXXXX 104 Arizona US 35.3997715 -110.3218983 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 10, 13, 25, 32, 37, 43, 49, 57, 62, 88, 91, 102, 129, 148, 177, 195, 210, 222, 240, 286, 287, 321, 335, 345, 355, 390, 410, 435, 452, 459, 473, 485, 527, 564, 583, 612, 625, 628, 665, 682, 712] 682 712 30\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,4,4,5,7,8,12,17,24,42,49,75,102,120,153,187,202,217,237,280,326,372,415,415,464,512,543,591,622,668,685,700,760,819,856,913,941,963,973,1026,1060,1090,1136,1164,1188,1215,1241\nXXXXXX 105 Arizona US 32.0971334 -111.7890033 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 4, 4, 5, 7, 8, 12, 17, 24, 42, 49, 75, 102, 120, 153, 187, 202, 217, 237, 280, 326, 372, 415, 415, 464, 512, 543, 591, 622, 668, 685, 700, 760, 819, 856, 913, 941, 963, 973, 1026, 1060, 1090, 1136, 1164, 1188, 1215, 1241] 1215 1241 26\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,3,5,5,5,5,5,5,5,8,10,10,14,16,17,22,23,35,36,41,51,64,62,65,69,77,89,103,106,120,124,137,138,146,163,168,175,182,197,212,235,247,256,268,283,303,317,332,342,359,365,387,397\nXXXXXX 106 Arizona US 32.90525627 -111.3449483 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 5, 5, 5, 5, 5, 5, 5, 8, 10, 10, 14, 16, 17, 22, 23, 35, 36, 41, 51, 64, 62, 65, 69, 77, 89, 103, 106, 120, 124, 137, 138, 146, 163, 168, 175, 182, 197, 212, 235, 247, 256, 268, 283, 303, 317, 332, 342, 359, 365, 387, 397] 387 397 10\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,4,4,4,5,6,7,7,8,8,10,10,12,14,14,16,19,20,23,28,28,30,30,30,30,31,31,33\nXXXXXX 107 Arizona US 31.52508998 -110.8479088 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 7, 7, 8, 8, 10, 10, 12, 14, 14, 16, 19, 20, 23, 28, 28, 30, 30, 30, 30, 31, 31, 33] 31 33 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,3,3,4,5,9,13,12,15,21,24,34,35,43,45,49,57,58,62,62,63,63,65,70,66,68,69,72,72,71,72,73,75,75,76,76,77,77,79,79\nXXXXXX 108 Arizona US 34.59933926 -112.5538588 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 3, 3, 3, 4, 5, 9, 13, 12, 15, 21, 24, 34, 35, 43, 45, 49, 57, 58, 62, 62, 63, 63, 65, 70, 66, 68, 69, 72, 72, 71, 72, 73, 75, 75, 76, 76, 77, 77, 79, 79] 79 79 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,4,4,4,5,6,9,12,13,13,14,13,13,13,14,15,16,15,20,20,20,20,24,28,29,29,31,32,42,42,42,53,59,62,67,72,85\nXXXXXX 109 Arizona US 32.76895712 -113.90666740000002 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 9, 12, 13, 13, 14, 13, 13, 13, 14, 15, 16, 15, 20, 20, 20, 20, 24, 28, 29, 29, 31, 32, 42, 42, 42, 53, 59, 62, 67, 72, 85] 72 85 13\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\nXXXXXX 110 Arkansas US 34.29145151 -91.37277296 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] 2 2 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,5,5,8,9,10,10,11,11,11,11,11,11,11,12,12,13,13,13,13,13,13,13,13,15\nXXXXXX 111 Arkansas US 33.19153461 -91.76984709999999 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 8, 9, 10, 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 15] 13 15 2\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5\nXXXXXX 112 Arkansas US 36.28784385 -92.33782872 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] 5 5 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,18,23,28,31,35,38,39,40,42,42,43,42,42,45,47,47,47,48,50,60,62,61,62,62,62,62,66,68,70,77,79,93,94,94,101,102\nXXXXXX 113 Arkansas US 36.33644656 -94.25680817 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 18, 23, 28, 31, 35, 38, 39, 40, 42, 42, 43, 42, 42, 45, 47, 47, 47, 48, 50, 60, 62, 61, 62, 62, 62, 62, 66, 68, 70, 77, 79, 93, 94, 94, 101, 102] 101 102 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5,5\nXXXXXX 114 Arkansas US 36.3084504 -93.09374925 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5] 5 5 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,11,12\nXXXXXX 115 Arkansas US 33.46755808 -92.15980837 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 11, 12] 11 12 1\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nXXXXXX 116 Arkansas US 33.55598792 -92.49974403 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 0 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,4,4,4,5,5,5\nXXXXXX 117 Arkansas US 36.34038560000001 -93.54270261 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 5, 5, 5] 5 5 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,2,2,2,4,4,5,5,5,7,7,7,7,7,7,7,7,7,7,7,8,9,9,9,9,9\nXXXXXX 118 Arkansas US 33.26458973 -91.29539209 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 5, 5, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 9, 9] 9 9 0\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,7,6,12,15,17,18,17,21,24,24,26,27,27,27,27,27,27,27,27,27,27,26,26,27,27,27,27,27,27,27,27,27,28,29,28,27,27,27,30\nXXXXXX 119 Arkansas US 34.04613432 -93.17484713 US 0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 6, 12, 15, 17, 18, 17, 21, 24, 24, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 29, 28, 27, 27, 27, 30] 27 30 3\n0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,3,3,3\n" ], [ "line =\"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 9, 15, 18, 18, 21, 21, 23, 24, 25, 26, 28, 30, 29, 30, 31, 36, 36, 41, 42, 45, 49, 53, 59, 62, 67, 76, 76, 84]\"\nprint(line.count(\",\"))", "99\n" ], [ "line=\"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 5, 5, 5, 5, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 14, 16, 16, 17]\"\nprint(line.count(\",\"))", "99\n" ], [ "TOTAL=0\nDATA = []\nL=len(ALLCASES)\nALL = ALLCASES[1:]\nDAILY=[]\ncnt=0\nfor i in range(0,len(ALL)):\n print(ALL[i].count(\",\"))\n L=int(len(ALL[i]))\n cnt=cnt+1\n if cnt==1:print(ALL[i][5],ALL[i][6],ALL[i][8],ALL[i][9],int(ALL[i][-2]),int(ALL[i][-1]))\n if len(ALL[i])>5:\n Daily = \"'0', '0',\"+str(ALL[i]).split(\"', '0', '0',\",1)[-1]", "_____no_output_____" ], [ "TOTAL=0\nDATA = []\nL=len(ALLCASES)\nALL = ALLCASES[1:]\nDAILY=[]\ncnt=0\nfor i in range(0,len(ALL)):\n print(ALL[i].count(\",\"))\n L=int(len(ALL[i]))\n cnt=cnt+1", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec534c2e076ae7b765fffe0e4b0ad0ed1a2945bb
18,062
ipynb
Jupyter Notebook
Notebooks/01_jupyter_notebooks.ipynb
pycroscopy/MM_2018_Workshop
9e250baa329a918b9971ff2f9ba686983767e8fd
[ "MIT" ]
1
2021-05-20T17:36:11.000Z
2021-05-20T17:36:11.000Z
Notebooks/01_jupyter_notebooks.ipynb
pycroscopy/MM_2018_Workshop
9e250baa329a918b9971ff2f9ba686983767e8fd
[ "MIT" ]
null
null
null
Notebooks/01_jupyter_notebooks.ipynb
pycroscopy/MM_2018_Workshop
9e250baa329a918b9971ff2f9ba686983767e8fd
[ "MIT" ]
null
null
null
37.164609
817
0.601871
[ [ [ "# Notebook Basics\n\nhttp://nbviewer.jupyter.org/github/jupyter/notebook/blob/master/docs/source/examples/Notebook/Notebook%20Basics.ipynb", "_____no_output_____" ], [ "## The Notebook dashboard", "_____no_output_____" ], [ "When you first start the notebook server, your browser will open to the notebook dashboard. The dashboard serves as a home page for the notebook. Its main purpose is to display the notebooks and files in the current directory. For example, here is a screenshot of the dashboard page for the `examples` directory in the Jupyter repository:\n\n![Jupyter dashboard showing files tab](jupyter_notebooks/dashboard_files_tab.png)", "_____no_output_____" ], [ "The top of the notebook list displays clickable breadcrumbs of the current directory. By clicking on these breadcrumbs or on sub-directories in the notebook list, you can navigate your file system.\n\nTo create a new notebook, click on the \"New\" button at the top of the list and select a kernel from the dropdown (as seen below). Which kernels are listed depend on what's installed on the server. Some of the kernels in the screenshot below may not exist as an option to you.\n\n![Jupyter \"New\" menu](jupyter_notebooks/dashboard_files_tab_new.png)", "_____no_output_____" ], [ "Notebooks and files can be uploaded to the current directory by dragging a notebook file onto the notebook list or by the \"click here\" text above the list.\n\nThe notebook list shows green \"Running\" text and a green notebook icon next to running notebooks (as seen below). Notebooks remain running until you explicitly shut them down; closing the notebook's page is not sufficient.\n\n\n![Jupyter dashboard showing one notebook with a running kernel](jupyter_notebooks/dashboard_files_tab_run.png)", "_____no_output_____" ], [ "To shutdown, delete, duplicate, or rename a notebook check the checkbox next to it and an array of controls will appear at the top of the notebook list (as seen below). You can also use the same operations on directories and files when applicable.\n\n![Buttons: Duplicate, rename, shutdown, delete, new, refresh](jupyter_notebooks/dashboard_files_tab_btns.png)", "_____no_output_____" ], [ "To see all of your running notebooks along with their directories, click on the \"Running\" tab:\n\n![Jupyter dashboard running tab](jupyter_notebooks/dashboard_running_tab.png)\n\nThis view provides a convenient way to track notebooks that you start as you navigate the file system in a long running notebook server.", "_____no_output_____" ], [ "## Overview of the Notebook UI", "_____no_output_____" ], [ "If you create a new notebook or open an existing one, you will be taken to the notebook user interface (UI). This UI allows you to run code and author notebook documents interactively. The notebook UI has the following main areas:\n\n* Menu\n* Toolbar\n* Notebook area and cells\n\nThe notebook has an interactive tour of these elements that can be started in the \"Help:User Interface Tour\" menu item.", "_____no_output_____" ], [ "## Modal editor", "_____no_output_____" ], [ "Starting with IPython 2.0, the Jupyter Notebook has a modal user interface. This means that the keyboard does different things depending on which mode the Notebook is in. There are two modes: edit mode and command mode.", "_____no_output_____" ], [ "### Edit mode", "_____no_output_____" ], [ "Edit mode is indicated by a green cell border and a prompt showing in the editor area:\n\n![Jupyter cell with green border](jupyter_notebooks/edit_mode.png)\n\nWhen a cell is in edit mode, you can type into the cell, like a normal text editor.", "_____no_output_____" ], [ "<div class=\"alert alert-success\">\nEnter edit mode by pressing `Enter` or using the mouse to click on a cell's editor area.\n</div>", "_____no_output_____" ], [ "### Command mode", "_____no_output_____" ], [ "Command mode is indicated by a grey cell border with a blue left margin:\n\n![Jupyter cell with blue & grey border](jupyter_notebooks/command_mode.png)\n\nWhen you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently. For example, if you are in command mode and you press `c`, you will copy the current cell - no modifier is needed.", "_____no_output_____" ], [ "<div class=\"alert alert-error\">\nDon't try to type into a cell in command mode; unexpected things will happen!\n</div>", "_____no_output_____" ], [ "<div class=\"alert alert-success\">\nEnter command mode by pressing `Esc` or using the mouse to click *outside* a cell's editor area.\n</div>", "_____no_output_____" ], [ "## Mouse navigation", "_____no_output_____" ], [ "All navigation and actions in the Notebook are available using the mouse through the menubar and toolbar, which are both above the main Notebook area:\n\n![Jupyter notebook menus and toolbar](jupyter_notebooks/menubar_toolbar.png)", "_____no_output_____" ], [ "The first idea of mouse based navigation is that **cells can be selected by clicking on them.** The currently selected cell gets a grey or green border depending on whether the notebook is in edit or command mode. If you click inside a cell's editor area, you will enter edit mode. If you click on the prompt or output area of a cell you will enter command mode.\n\nIf you are running this notebook in a live session (not on http://nbviewer.jupyter.org) try selecting different cells and going between edit and command mode. Try typing into a cell.", "_____no_output_____" ], [ "The second idea of mouse based navigation is that **cell actions usually apply to the currently selected cell**. Thus if you want to run the code in a cell, you would select it and click the <button class='btn btn-default btn-xs'><i class=\"fa fa-step-forward icon-step-forward\"></i></button> button in the toolbar or the \"Cell:Run\" menu item. Similarly, to copy a cell you would select it and click the <button class='btn btn-default btn-xs'><i class=\"fa fa-copy icon-copy\"></i></button> button in the toolbar or the \"Edit:Copy\" menu item. With this simple pattern, you should be able to do most everything you need with the mouse.\n\nMarkdown cells have one other state that can be modified with the mouse. These cells can either be rendered or unrendered. When they are rendered, you will see a nice formatted representation of the cell's contents. When they are unrendered, you will see the raw text source of the cell. To render the selected cell with the mouse, click the <button class='btn btn-default btn-xs'><i class=\"fa fa-step-forward icon-step-forward\"></i></button> button in the toolbar or the \"Cell:Run\" menu item. To unrender the selected cell, double click on the cell.", "_____no_output_____" ], [ "## Keyboard Navigation", "_____no_output_____" ], [ "The modal user interface of the Jupyter Notebook has been optimized for efficient keyboard usage. This is made possible by having two different sets of keyboard shortcuts: one set that is active in edit mode and another in command mode.\n\nThe most important keyboard shortcuts are `Enter`, which enters edit mode, and `Esc`, which enters command mode.\n\nIn edit mode, most of the keyboard is dedicated to typing into the cell's editor. Thus, in edit mode there are relatively few shortcuts. In command mode, the entire keyboard is available for shortcuts, so there are many more. The `Help`->`Keyboard Shortcuts` dialog lists the available shortcuts.", "_____no_output_____" ], [ "We recommend learning the command mode shortcuts in the following rough order:\n\n1. Basic navigation: `enter`, `shift-enter`, `up/k`, `down/j`\n2. Saving the notebook: `s`\n2. Change Cell types: `y`, `m`, `1-6`, `t`\n3. Cell creation: `a`, `b`\n4. Cell editing: `x`, `c`, `v`, `d`, `z`\n5. Kernel operations: `i`, `0` (press twice)", "_____no_output_____" ], [ "### A handy way to shortcuts is to use the command palette: Cmd + Shift + P (or Ctrl + Shift + P on Linux and Windows). ", "_____no_output_____" ], [ "Esc will take you into command mode where you can navigate around your notebook with arrow keys.\nWhile in command mode:\n\n* A to insert a new cell above the current cell, B to insert a new cell below.\n\n* M to change the current cell to Markdown, Y to change it back to code\n\n* D + D (press the key twice) to delete the current cell\n\n* Enter will take you from command mode back into edit mode for the given cell.\n\n* Shift + Tab will show you the Docstring (documentation) for the the object you have just typed in a code cell - you can keep pressing this short cut to cycle through a few modes of documentation.\n\n* Ctrl + Shift + - will split the current cell into two from where your cursor is.\n\n* Esc + F Find and replace on your code but not the outputs.\n\n* Esc + O Toggle cell output.\n\n* Select Multiple Cells:\n Shift + J or Shift + Down selects the next sell in a downwards direction. You can also select sells in an upwards direction by using Shift + K or Shift + Up.\n Once cells are selected, you can then delete / copy / cut / paste / run them as a batch. This is helpful when you need to move parts of a notebook.\n You can also use Shift + M to merge multiple cells.", "_____no_output_____" ] ], [ [ "%lsmagic", "_____no_output_____" ] ] ]
[ "markdown", "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" ], [ "code" ] ]
ec535f5ddc06fb1068c356f26e9992298b339138
13,074
ipynb
Jupyter Notebook
Ternary_data_preprocessing.ipynb
Docurdt/Cell-Graph_Signature
7030e2ed273b6e0785c74315cad20743220a74c1
[ "MIT" ]
2
2021-09-27T14:14:48.000Z
2021-11-05T14:09:51.000Z
Ternary_data_preprocessing.ipynb
Docurdt/Cell-Graph_Signature
7030e2ed273b6e0785c74315cad20743220a74c1
[ "MIT" ]
null
null
null
Ternary_data_preprocessing.ipynb
Docurdt/Cell-Graph_Signature
7030e2ed273b6e0785c74315cad20743220a74c1
[ "MIT" ]
null
null
null
45.395833
151
0.505278
[ [ [ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 8 01:49:00 2019\n\n@author: Yuguang Wang & Yanan Wang\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport scipy.io as sio\nimport os\nfrom scipy.sparse import csr_matrix", "_____no_output_____" ], [ "def create_samples(file_name):\n subdir = '_{}/'.format(file_name.split(\".\")[0])\n # critical distance 20 \\mu m, pix width 0.5 \\mu m\n critical = 20/0.5\n num_node = 100\n adj = list()\n feature = list()\n label = list()\n pid = list()\n pid_name = list()\n coor = list()\n edge_index = list()\n edge_coor = list()\n edge_attr = list()\n factor_flag = 'selected_new'\n #factor_flag = 'selected'\n #factor_flag = 'full'\n sv_dir = \"data/\" + factor_flag + subdir\n if not os.path.exists(sv_dir):\n os.makedirs(sv_dir)\n \n print('****** Processing data for %s ******' % file_name)\n df_diagnosis = pd.read_excel(file_name)\n id_participant = df_diagnosis['Id']\n num_id_1 = len(id_participant)\n survival_time_all = df_diagnosis['survival_time'].array\n \n for kid, row in df_diagnosis.iterrows():\n ld_csv = row['file_path']\n old_new_flag = ld_csv.split(\"/\")[2]\n #print(ld_csv)\n #print(old_new_flag)\n \n label1 = row['prognosis_label']\n df_csv = pd.read_csv(ld_csv)\n # extract the features\n if factor_flag == 'full': # from \"DAPI (DAPI) Nucleus Intensity\" to end\n lv = np.linspace(22,59,38,dtype=int)\n if factor_flag == 'selected_old':\n lv = np.array([11,12,18,35,36,37,38,39],dtype=np.int)\n if(old_new_flag == 'stomach_csv_1' and factor_flag == 'selected_new'):\n lv = np.concatenate((np.linspace(20,44,25,dtype=int),np.linspace(50,59,10,dtype=int)))\n elif(old_new_flag == 'stomach_csv_2' and factor_flag == 'selected_new'):\n lv = np.concatenate((np.linspace(32,56,25,dtype=int),np.linspace(62,71,10,dtype=int)))\n feature_all = df_csv.take(lv,axis=1).values\n #print(feature_all)\n feature_all = feature_all/(feature_all.max(axis=0)+0.00000000000001) # Add normalization\n #print(feature_all)\n \n \n # compute adjacency matrix\n xmin = np.array(df_csv['XMin'])\n xmax = np.array(df_csv['XMax'])\n ymin = np.array(df_csv['YMin'])\n ymax = np.array(df_csv['YMax'])\n num_cell = len(xmin)\n if np.mod(num_cell,num_node)==0:\n num_graph = int(num_cell/num_node)\n else:\n num_graph = int(num_cell/num_node)+1\n # compute the centre coordinates of cells\n xc = (xmin+xmax)/2\n yc = (ymin+ymax)/2\n #% compute the adjacency matrix for each graph\n # deal with the graphs except the last\n for i in range(num_graph-1):\n A = np.zeros([num_node,num_node])\n coor1 = list()\n coor1.append(xc[i*num_node:(i+1)*num_node])\n coor1.append(yc[i*num_node:(i+1)*num_node])\n coor1 = np.reshape(np.array(coor1),[num_node,2])\n edge_coor_1 = list()\n edge_index_1 =list()\n edge_attr_1 = list()\n for k in range(num_node):\n for j in range(k+1,num_node):\n # turn to global coordinates\n k1 = i*num_node + k\n j1 = i*num_node + j\n dist = np.sqrt((xc[k1]-xc[j1])**2+(yc[k1]-yc[j1])**2)\n if dist<critical:\n A[k,j] = critical/dist\n A[j,k] = critical/dist\n edge_coor_temp = np.array([xc[k1],yc[k1],xc[j1],yc[j1]],dtype=np.float64)\n edge_coor_1.append(edge_coor_temp)\n edge_coor_temp = np.array([xc[j1],yc[j1],xc[k1],yc[k1]],dtype=np.float64)\n edge_coor_1.append(edge_coor_temp)\n edge_index_temp = np.array([k,j],dtype=np.int)\n edge_index_1.append(edge_index_temp)\n edge_index_temp = np.array([j,k],dtype=np.int)\n edge_index_1.append(edge_index_temp)\n edge_attr_temp = np.array([A[k,j],A[j,k]],dtype=np.float)\n edge_attr_1.append(edge_attr_temp)\n A = csr_matrix(A)\n adj.append(A)\n #print('kid, id_participant[kid]:',kid, id_participant[kid])\n tissue_id = row['组织编码']\n #print(tissue_id)\n pid_name.append(tissue_id)\n pid.append(kid)\n label.append(label1)\n coor.append(coor1)\n edge_coor.append(np.reshape(np.array(edge_coor_1),[len(edge_coor_1),4]))\n edge_index.append(np.reshape(np.array(edge_index_1),[len(edge_index_1),2]))\n edge_attr.append(np.reshape(np.array(edge_attr_1),[len(edge_index_1),1]))\n feature.append(feature_all[i*num_node:(i+1)*num_node,])\n # deal with the last graph\n if np.mod(num_cell,num_node)>0:\n num_node_last = int(np.mod(num_cell,num_node))\n else:\n num_node_last = num_node\n coor1 = list()\n coor1.append(xc[(i+1)*num_node:])\n coor1.append(yc[(i+1)*num_node:])\n coor1 = np.reshape(np.array(coor1),[num_node_last,2])\n A = np.zeros([num_node_last,num_node_last])\n for k in range(num_node_last):\n for j in range(k,num_node_last):\n dist = np.sqrt((xc[k1]-xc[j1])**2+(yc[k1]-yc[j1])**2)\n k1 = i*num_node + k\n j1 = i*num_node + j\n if dist<critical:\n A[k,j] = critical/dist\n A[j,k] = critical/dist\n edge_coor_temp = np.array([xc[k1],yc[k1],xc[j1],yc[j1]],dtype=np.float64)\n edge_coor_1.append(edge_coor_temp)\n edge_coor_temp = np.array([xc[j1],yc[j1],xc[k1],yc[k1]],dtype=np.float64)\n edge_coor_1.append(edge_coor_temp)\n edge_index_temp = np.array([k,j],dtype=np.int)\n edge_index_1.append(edge_index_temp)\n edge_index_temp = np.array([j,k],dtype=np.int)\n edge_index_1.append(edge_index_temp)\n edge_attr_temp = np.array([A[k,j],A[j,k]],dtype=np.float)\n edge_attr_1.append(edge_attr_temp)\n A = csr_matrix(A)\n # print('kid, id_participant[kid]:',kid, id_participant[kid])\n adj.append(A)\n \n tissue_id = row['组织编码']\n #print(tissue_id)\n pid.append(kid)\n pid_name.append(tissue_id)\n \n\n label.append(label1)\n coor.append(coor1)\n edge_coor.append(np.reshape(np.array(edge_coor_1),[len(edge_coor_1),4]))\n edge_index.append(np.reshape(np.array(edge_index_1),[len(edge_index_1),2]))\n edge_attr.append(np.reshape(np.array(edge_attr_1),[len(edge_index_1),1]))\n feature.append(feature_all[i*num_node:(i+1)*num_node,])\n \n #%% save data\n # adj\n sv_adj = sv_dir + 'graph' + str(len(label)) + '_node' + str(num_node) + '_weighted' + '_adj_csr' + '.mat'\n sio.savemat(sv_adj,mdict={'adj':adj})\n # feature\n sv_feature = sv_dir + 'graph' + str(len(label)) + '_node' + str(num_node) + '_weighted' + '_feature' + '.mat'\n sio.savemat(sv_feature,mdict={'feature':feature})\n # label in survival time classes\n sv_label = sv_dir + 'graph' + str(len(label)) + '_node' + str(num_node) + '_weighted' + '_label' + '.mat'\n sio.savemat(sv_label,mdict={'label':label})\n # label in participant id\n sv_pid = sv_dir + 'graph' + str(len(label)) + '_node' + str(num_node) + '_weighted' + '_pid' + '.mat'\n sio.savemat(sv_pid,mdict={'pid':pid})\n # label in participant id name\n sv_pid_name = sv_dir + 'graph' + str(len(label)) + '_node' + str(num_node) + '_weighted' + '_pid_name' + '.mat'\n sio.savemat(sv_pid_name,mdict={'pid_name':pid_name})\n # coordinates of nodes\n sv_node_coor = sv_dir + 'graph' + str(len(label)) + '_node' + str(num_node) + '_weighted' + '_nodecoor' + '.mat'\n sio.savemat(sv_node_coor,mdict={'coor':coor})\n # index of the two ends of edges\n sv_edge = sv_dir + 'graph' + str(len(label)) + '_node' + str(num_node) + '_weighted' + '_edge_index' + '.mat'\n sio.savemat(sv_edge,mdict={'edge_index':edge_index})\n # weight on each edge\n sv_edge_attr = sv_dir + 'graph' + str(len(label)) + '_node' + str(num_node) + '_weighted' + '_edge_attr' + '.mat'\n sio.savemat(sv_edge_attr,mdict={'edge_attr':edge_attr})\n # coordinates of the two ends of edges\n sv_edge_coor = sv_dir + 'graph' + str(len(label)) + '_node' + str(num_node) + '_weighted' + '_edge_coor' + '.mat'\n sio.savemat(sv_edge_coor,mdict={'edge_coor':edge_coor})\n \n \n \n \n \ncreate_samples(\"data_file/test_data.xlsx\")\n\nfor i in [0,1,2,3,4]:\n create_samples(\"data_file/val_data_fold_{}.xlsx\".format(i))\n create_samples(\"data_file/train_data_fold_{}.xlsx\".format(i))\n\n \n \n \n ", "****** Processing data for data_file/test_data.xlsx ******\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
ec53781190ef6d12a169314bf36c362722fd97de
176,461
ipynb
Jupyter Notebook
Documentation Hands On Machine Learning with Scikit Learn And TensorFlow Book/Capitulo 4 Entrenamiento de modelos.ipynb
johnma23/Training-and-studying-Machine-Learning
7e6242ae190b62c48969037c00ef926426ec0b3d
[ "Apache-2.0" ]
5
2021-01-10T16:15:10.000Z
2021-04-30T02:39:50.000Z
Documentation Hands On Machine Learning with Scikit Learn And TensorFlow Book/Capitulo 4 Entrenamiento de modelos.ipynb
johnma23/Training-and-studying-Machine-Learning
7e6242ae190b62c48969037c00ef926426ec0b3d
[ "Apache-2.0" ]
null
null
null
Documentation Hands On Machine Learning with Scikit Learn And TensorFlow Book/Capitulo 4 Entrenamiento de modelos.ipynb
johnma23/Training-and-studying-Machine-Learning
7e6242ae190b62c48969037c00ef926426ec0b3d
[ "Apache-2.0" ]
2
2021-01-17T15:03:37.000Z
2021-05-12T00:35:21.000Z
159.548825
46,848
0.885034
[ [ [ "# The Normal Equation ", "_____no_output_____" ], [ "Para encontrar el valor de **θ** que minimiza la función de costo, existe una solución de forma cerrada, en otras palabras, una ecuación matemática que da el resultado directamente. A esto se le llama Ecuación Normal: ", "_____no_output_____" ], [ "Ecuación normal: $\\theta = (X^{T}X)^{-1}X^{T}Y$", "_____no_output_____" ], [ "\n", "_____no_output_____" ], [ "* $\\theta$ es el valor de θ que minimiza la función de costo.\n\n* Y es el vector de valores objetivo que contiene $Y^{(1)}$ hacia $Y^{(m)}$", "_____no_output_____" ], [ "Primero, importemos algunos módulos comunes, asegurémonos de que MatplotLib traza las figuras en línea y preparemos una función para guardar las figuras. También verificamos que Python 3.5 o posterior esté instalado (aunque Python 2.x puede funcionar, está obsoleto, por lo que le recomendamos encarecidamente que use Python 3 en su lugar), así como Scikit-Learn ≥0.20.", "_____no_output_____" ] ], [ [ "# Verificamos que Python ≥3.5\nimport sys\nassert sys.version_info >= (3, 5)\n\n# Verificamos que Scikit-Learn ≥0.20\nimport sklearn\nassert sklearn.__version__ >= \"0.20\"\n\n# Importamos bibliotecas comunes\nimport numpy as np\nimport os\n\n# Para que salgan resultados semejantes\nnp.random.seed(42)\n\n# Para pintar bonitas figuras\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\n\n# Lugar donde se guardaran las figuras\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"training_linear_models\"\nIMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID)\nos.makedirs(IMAGES_PATH, exist_ok=True)\n\ndef save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n path = os.path.join(IMAGES_PATH, fig_id + \".\" + fig_extension)\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format=fig_extension, dpi=resolution)\n\n# Para ignorar adventencias que no son necesarias\nimport warnings\nwarnings.filterwarnings(action=\"ignore\", message=\"^internal gelsd\")", "_____no_output_____" ] ], [ [ "Vamos a generar algunos datos de apariencia lineal para probar esta ecuación: ", "_____no_output_____" ] ], [ [ "import numpy as np\n\nX = 2 * np.random.rand(100, 1)\ny = 4 + 3 * X + np.random.randn(100, 1)", "_____no_output_____" ] ], [ [ "Mostremos el conjunto de datos lineales generados aleatoriamente", "_____no_output_____" ] ], [ [ "plt.plot(X, y, \"b.\")\nplt.xlabel(\"$x_1$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.axis([0, 2, 0, 15])\nsave_fig(\"generated_data_plot\")\nplt.show()", "Saving figure generated_data_plot\n" ] ], [ [ "Ahora calculemos $\\theta$ usando la ecuación normal. Usaremos la función inv() del módulo de Álgebra lineal de NumPy (np.linalg) para calcular la inversa de una matriz, y el método dot() para la multiplicación de matrices: ", "_____no_output_____" ] ], [ [ "X_b = np.c_[np.ones((100, 1)), X] # agregue x0 = 1 a cada instancia\ntheta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y) ", "_____no_output_____" ] ], [ [ "La función real que usamos para generar los datos es y = 4 + 3x1 + ruido gaussiano. Veamos qué encontró la ecuación:", "_____no_output_____" ] ], [ [ "theta_best", "_____no_output_____" ] ], [ [ "Habríamos esperado $\\theta_{0}$ = 4 y $\\theta_{1}$ = 3 en lugar de $\\theta_{0}$ = 4.215 y $\\theta_{1}$ = 2.770. Lo suficientemente cerca, pero el ruido hizo imposible recuperar los parámetros exactos de la función original. ", "_____no_output_____" ], [ "Ahora harémos predicciones usando θ:", "_____no_output_____" ] ], [ [ "X_new = np.array([[0], [2]])\nX_new_b = np.c_[np.ones((2, 1)), X_new] # agregue x0 = 1 a cada instancia\ny_predict = X_new_b.dot(theta_best)\ny_predict", "_____no_output_____" ] ], [ [ "Tracemos las predicciones de este modelo", "_____no_output_____" ] ], [ [ "'''\nplt.plot(X_new, y_predict, \"r-\")\nplt.plot(X, y, \"b.\")\nplt.axis([0, 2, 0, 15])\nplt.show()\n'''", "_____no_output_____" ] ], [ [ "Realizar una regresión lineal usando Scikit-Learn es bastante simple:", "_____no_output_____" ] ], [ [ "plt.plot(X_new, y_predict, \"r-\", linewidth=2, label=\"Predictions\")\nplt.plot(X, y, \"b.\")\nplt.xlabel(\"$x_1$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.legend(loc=\"upper left\", fontsize=14)\nplt.axis([0, 2, 0, 15])\nsave_fig(\"linear_model_predictions_plot\")\nplt.show()", "Saving figure linear_model_predictions_plot\n" ], [ "from sklearn.linear_model import LinearRegression\n\nlin_reg = LinearRegression()\nlin_reg.fit(X, y)\nlin_reg.intercept_, lin_reg.coef_", "_____no_output_____" ], [ "lin_reg.predict(X_new)", "_____no_output_____" ] ], [ [ "La clase LinearRegression se basa en la función scipy.linalg.lstsq () (el nombre significa \"mínimos cuadrados\"), a la que puede llamar directamente:", "_____no_output_____" ] ], [ [ "theta_best_svd, residuals, rank, s = np.linalg.lstsq(X_b, y, rcond=1e-6)\ntheta_best_svd", "_____no_output_____" ] ], [ [ "Esta función calcula $\\theta$ = $X^+$ + y, donde $X^+$ + es el pseudoinverso de X (específicamente el inverso de Moore-Penrose). Puede usar np.linalg.pinv () para calcular la pseudoinversa directamente:", "_____no_output_____" ] ], [ [ "np.linalg.pinv(X_b).dot(y)", "_____no_output_____" ] ], [ [ "El pseudoinverso en sí mismo se calcula usando una técnica de factorización de matrices estándar llamada Descomposición de valores singulares (SVD) que puede descomponer la matriz **X** del conjunto de entrenamiento en la multiplicación de tres matrices **U Σ** $V^T$ (ver numpy.linalg.svd ()). La pseudoinversa se calcula como $X^+$ = $VΣ^+U^T$. Para calcular la matriz $Σ^+$, el algoritmo toma Σ y pone a cero todos los valores menores que un pequeño valor de umbral, luego reemplaza todos los valores distintos de cero con su inverso, y finalmente transpone la matriz resultante. Este enfoque es más eficiente que calcular la ecuación normal, y además maneja bien los casos extremos: de hecho, la ecuación normal puede no funcionar si la matriz $X^T$X no es invertible (es decir, singular), como si m < n o si algunas características son redundante, pero el pseudoinverso siempre está definido.", "_____no_output_____" ], [ "# Complejidad computacional\n\nLa ecuación normal calcula la inversa de $X^T X$, que es una matriz (n + 1) × (n + 1) (donde n es el número de características). La complejidad computacional de invertir tal matriz es típicamente de aproximadamente O ($n^2.4$) a O ($n^3$) (dependiendo de la implementación). En otras palabras, si duplica el número de características, multiplica el tiempo de cálculo por aproximadamente $2^2,4$ = 5,3 a $2^3$ = 8. \n\nEl enfoque SVD utilizado por la clase LinearRegression de Scikit-Learn es aproximadamente O ($n^2$). Si duplica la cantidad de funciones, multiplica el tiempo de cálculo por aproximadamente 4.", "_____no_output_____" ], [ ">Tanto la ecuación normal como el enfoque SVD se vuelven muy lentos cuando la cantidad de características aumenta (por ejemplo, 100.000). En el lado positivo, ambos son lineales con respecto al número de instancias en el conjunto de entrenamiento (son O (m)), por lo que manejan grandes conjuntos de entrenamiento de manera eficiente, siempre que puedan caber en la memoria.", "_____no_output_____" ], [ "Además, una vez que haya entrenado su modelo de regresión lineal (usando la ecuación normal o cualquier otro algoritmo), las predicciones son muy rápidas: la complejidad computacional es lineal con respecto a la cantidad de instancias en las que desea hacer predicciones y la cantidad de características. En otras palabras, hacer predicciones en el doble de instancias (o el doble de funciones) llevará aproximadamente el doble de tiempo. Ahora veremos formas muy diferentes de entrenar un modelo de regresión lineal, más adecuado para casos donde hay una gran cantidad de características o demasiadas instancias de entrenamiento para caber en la memoria.", "_____no_output_____" ], [ "# Gradient Descent\n\nGradient Descent es un algoritmo de optimización muy genérico capaz de encontrar soluciones óptimas a una amplia gama de problemas. La idea general de Gradient Descent es ajustar los parámetros de forma iterativa para minimizar una función de coste.\n\nSuponga que está perdido en las montañas en una densa niebla; solo puedes sentir la pendiente del suelo debajo de tus pies. Una buena estrategia para llegar rápidamente al fondo del valle es descender en dirección a la pendiente más pronunciada. Esto es exactamente lo que hace Gradient Descent: mide el gradiente local de la función de error con respecto al vector de parámetros θ, y va en la dirección del gradiente descendiente. Una vez que el gradiente es cero, ¡ha alcanzado un mínimo!\n\nConcretamente, comienza llenando θ con valores aleatorios (esto se llama inicialización aleatoria), y luego lo mejora gradualmente, dando un pequeño paso a la vez, cada paso intentando disminuir la función de costo (por ejemplo, el MSE), hasta que el algoritmo converja al mínimo:", "_____no_output_____" ], [ "![1](https://user-images.githubusercontent.com/63415652/104545505-d68c5d80-55ef-11eb-943c-fe01aed20c8b.PNG)", "_____no_output_____" ], [ "Un parámetro importante en Gradient Descent es el tamaño de los pasos, determinado por el hiperparámetro de tasa de aprendizaje. Si la tasa de aprendizaje es demasiado pequeña, el algoritmo tendrá que pasar por muchas iteraciones para converger, lo que llevará mucho tiempo: ", "_____no_output_____" ], [ "![2](https://user-images.githubusercontent.com/63415652/104545665-3a168b00-55f0-11eb-9a6c-eb2014d0d9cc.PNG)", "_____no_output_____" ], [ "Por otro lado, si la tasa de aprendizaje es demasiado alta, podría saltar a través del valle y terminar en el otro lado, posiblemente incluso más alto de lo que estaba antes. Esto podría hacer que el algoritmo diverja, con valores cada vez mayores, sin encontrar una buena solución:", "_____no_output_____" ], [ "![3](https://user-images.githubusercontent.com/63415652/104545887-a2656c80-55f0-11eb-9d96-c42aaf3c97f1.PNG)", "_____no_output_____" ], [ "Por último, no todas las funciones de coste se ven como buenos cuencos normales. Puede haber huecos, crestas, mesetas y todo tipo de terrenos irregulares, lo que dificulta la convergencia al mínimo. La siguiente figura muestra los dos desafíos principales con Gradient Descent: si la inicialización aleatoria inicia el algoritmo de la izquierda, entonces convergerá a un mínimo local, que no es tan bueno como el mínimo global. Si comienza a la derecha, tomará mucho tiempo cruzar la meseta, y si se detiene demasiado pronto, nunca alcanzará el mínimo global.", "_____no_output_____" ], [ "![4](https://user-images.githubusercontent.com/63415652/104546323-89a98680-55f1-11eb-8bc4-de9801badab1.PNG)", "_____no_output_____" ], [ "Afortunadamente, la función de costo MSE para un modelo de regresión lineal resulta ser una función convexa, lo que significa que si elige dos puntos cualesquiera en la curva, el segmento de línea que los une nunca cruza la curva. Esto implica que no hay mínimos locales, solo un mínimo global. También es una función continua con una pendiente que nunca cambia abruptamente. Estos dos hechos tienen una gran consecuencia: Se garantiza que el descenso del gradiente se acercará arbitrariamente al mínimo global (si espera lo suficiente y si la tasa de aprendizaje no es demasiado alta) .\n\nDe hecho, la función de costo tiene la forma de un cuenco, pero puede ser un cuenco alargado si las características tienen escalas muy diferentes. La siguiente figura muestra Gradient Descent en un conjunto de entrenamiento donde las características 1 y 2 tienen la misma escala (a la izquierda), y en un conjunto de entrenamiento donde la característica 1 tiene valores mucho más pequeños que la característica 2 (a la derecha).\n\nGradient Descent con y sin escala de características:", "_____no_output_____" ], [ "![5](https://user-images.githubusercontent.com/63415652/104548011-7dbfc380-55f5-11eb-9e38-0904a7b5a2fa.PNG)", "_____no_output_____" ], [ "Como puede ver, a la izquierda el algoritmo Gradient Descent va directo hacia el mínimo, alcanzándolo rápidamente, mientras que a la derecha primero va en una dirección casi ortogonal a la dirección del mínimo global, y termina con una larga marcha. por un valle casi plano. Eventualmente alcanzará el mínimo, pero llevará mucho tiempo.", "_____no_output_____" ], [ ">Al usar Gradient Descent, debe asegurarse de que todas las funciones tengan una escala similar (por ejemplo, usando la clase StandardScaler de Scikit-Learn), o de lo contrario, la convergencia llevará mucho más tiempo.", "_____no_output_____" ], [ "Este diagrama también ilustra el hecho de que entrenar un modelo significa buscar una combinación de parámetros del modelo que minimice una función de costo (sobre el conjunto de entrenamiento). Es una búsqueda en el espacio de parámetros del modelo: cuantos más parámetros tiene un modelo, más dimensiones tiene este espacio y más difícil es la búsqueda: buscar una aguja en un pajar de 300 dimensiones es mucho más complicado que en tres dimensiones . Afortunadamente, dado que la función de costo es convexa en el caso de la regresión lineal, la aguja está simplemente en el fondo del cuenco.", "_____no_output_____" ], [ "# Batch Gradient Descent\n\nPara implementar el desenso del gradiente, es necesario calcular el gradiente de la función de costo con respecto a cada parámetro del modelo $\\theta_j$. En otras palabras, necesita calcular cuánto cambiará la función de costo si cambia $θ_j$ solo un poco. A esto se le llama derivada parcial. Es como preguntar \"¿Cuál es la pendiente de la montaña bajo mis pies si miro hacia el este?\" y luego hacer la misma pregunta mirando al norte (y así sucesivamente para todas las demás dimensiones, si puede imaginar un universo con más de tres dimensiones). La siguiente ecuación calcula la derivada parcial de la función de costo con respecto al parámetro $θ_j$, anotado $\\frac{\\partial}{\\partial \\theta_j}$ MSE(θ).", "_____no_output_____" ], [ "Está es la ecuación de las derivadas parciales de la función de costo\n\n![6](https://user-images.githubusercontent.com/63415652/104643870-aafe8700-5672-11eb-9a4a-675bf3894df2.PNG)", "_____no_output_____" ], [ "En lugar de calcular estas derivadas parciales individualmente, puede usar la siguiente ecuación para calcularlas todas de una vez. El vector de gradiente, denominado $∇_θ$ MSE (θ), contiene todas las derivadas parciales de la función de costo (una para cada parámetro del modelo).\n\nEcuación del vector de gradiente de la función de costo: \n\n![7](https://user-images.githubusercontent.com/63415652/104644345-47c12480-5673-11eb-831a-484352dd9531.PNG)", "_____no_output_____" ], [ ">Tenga en cuenta que esta fórmula implica cálculos sobre el conjunto de entrenamiento completo X, en cada paso de Gradient Descent. Esta es la razón por la que el algoritmo se llama Descenso de gradiente por lotes: utiliza el lote completo de datos de entrenamiento en cada paso (en realidad, Descenso de gradiente completo probablemente sería un mejor nombre). Como resultado, es terriblemente lento en conjuntos de entrenamiento muy grandes (pero veremos algoritmos de Gradient Descent mucho más rápidos en breve). Sin embargo, Gradient Descent se adapta bien al número de características; El entrenamiento de un modelo de regresión lineal cuando hay cientos de miles de entidades es mucho más rápido usando Gradient Descent que usando la ecuación normal o la descomposición de SVD.", "_____no_output_____" ], [ "Una vez que tenga el vector de gradiente, que apunta hacia arriba, simplemente vaya en la dirección opuesta para ir cuesta abajo. Esto significa restar $∇_θ$MSE (**θ**) de **θ**. Aquí es donde entra en juego la tasa de aprendizaje η: multiplique el vector de gradiente por η para determinar el tamaño del paso cuesta abajo: \n\nEcuación del paso del Decenso del gradiente: \n\n![8](https://user-images.githubusercontent.com/63415652/104644993-201e8c00-5674-11eb-86c4-c78012d305af.PNG)\n\nVeamos una implementación rápida de este algoritmo:", "_____no_output_____" ] ], [ [ "eta = 0.1 # tasa de aprendizaje \nn_iterations = 1000\nm = 100\n\ntheta = np.random.randn(2,1) # inicialización aleatoria \n\nfor iteration in range(n_iterations):\n gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)\n theta = theta - eta * gradients", "_____no_output_____" ] ], [ [ "Veamos la theta resultante:", "_____no_output_____" ] ], [ [ "theta", "_____no_output_____" ], [ "X_new_b.dot(theta)", "_____no_output_____" ] ], [ [ "Es exactamente lo que encontró la ecuación normal. Gradient Descent funcionó a la perfección. Pero, ¿y si hubiera utilizado una eta de tasa de aprendizaje diferente? La grafica siguiente muestra los primeros 10 pasos de Gradient Descent utilizando tres tasas de aprendizaje diferentes (la línea discontinua representa el punto de partida).\n\nAhora verémos el Gradient Descent con varias tasas de aprendizaje: ", "_____no_output_____" ] ], [ [ "theta_path_bgd = []\n\ndef plot_gradient_descent(theta, eta, theta_path=None):\n m = len(X_b)\n plt.plot(X, y, \"b.\")\n n_iterations = 1000\n for iteration in range(n_iterations):\n if iteration < 10:\n y_predict = X_new_b.dot(theta)\n style = \"b-\" if iteration > 0 else \"r--\"\n plt.plot(X_new, y_predict, style)\n gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)\n theta = theta - eta * gradients\n if theta_path is not None:\n theta_path.append(theta)\n plt.xlabel(\"$x_1$\", fontsize=18)\n plt.axis([0, 2, 0, 15])\n plt.title(r\"$\\eta = {}$\".format(eta), fontsize=16)", "_____no_output_____" ], [ "np.random.seed(42)\ntheta = np.random.randn(2,1) # random initialization\n\nplt.figure(figsize=(10,4))\nplt.subplot(131); plot_gradient_descent(theta, eta=0.02)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.subplot(132); plot_gradient_descent(theta, eta=0.1, theta_path=theta_path_bgd)\nplt.subplot(133); plot_gradient_descent(theta, eta=0.5)\n\nsave_fig(\"gradient_descent_plot\")\nplt.show()", "Saving figure gradient_descent_plot\n" ] ], [ [ "A la izquierda, la tasa de aprendizaje es demasiado baja: el algoritmo finalmente alcanzará la solución, pero llevará mucho tiempo. En el medio, la tasa de aprendizaje parece bastante buena: en solo unas pocas iteraciones, ya ha convergido a la solución. A la derecha, la tasa de aprendizaje es demasiado alta: el algoritmo diverge, salta por todos lados y, de hecho, se aleja cada vez más de la solución en cada paso. \n\nPara encontrar una buena tasa de aprendizaje, puede utilizar la búsqueda en cuadrícula. Sin embargo, es posible que desee limitar el número de iteraciones para que la búsqueda de cuadrícula pueda eliminar los modelos que tardan demasiado en converger. \n\nQuizás se pregunte cómo establecer el número de iteraciones. Si es demasiado bajo, aún estará lejos de la solución óptima cuando el algoritmo se detenga, pero si es demasiado alto, perderá tiempo mientras los parámetros del modelo ya no cambian. Una solución simple es establecer una gran cantidad de iteraciones pero interrumpir el algoritmo cuando el vector de gradiente se vuelve pequeño, es decir, cuando su norma se vuelve más pequeña que un número diminuto ϵ (llamado tolerancia), porque esto sucede cuando Gradient El descenso ha llegado (casi) al mínimo.", "_____no_output_____" ], [ "### Tasa de convergencia\n\nCuando la función de costo es convexa y su pendiente no cambia abruptamente (como es el caso de la función de costo MSE), Batch Gradient Descent con una tasa de aprendizaje fija eventualmente convergerá a la solución óptima, pero es posible que tenga que esperar un poco: puede tomar O (1/ϵ) iteraciones para alcanzar el óptimo dentro de un rango de ϵ dependiendo de la forma de la función de costo. Si divide la tolerancia por 10 para tener una solución más precisa, es posible que el algoritmo deba ejecutarse unas 10 veces más. ", "_____no_output_____" ], [ "# Stochastic Gradient Descent\n\nEl principal problema con Batch Gradient Descent es el hecho de que utiliza todo el conjunto de entrenamiento para calcular los gradientes en cada paso, lo que lo hace muy lento cuando el conjunto de entrenamiento es grande. En el extremo opuesto, Stochastic Gradient Descent solo elige una instancia aleatoria en el conjunto de entrenamiento en cada paso y calcula los gradientes basándose solo en esa única instancia. Obviamente, esto hace que el algoritmo sea mucho más rápido, ya que tiene muy pocos datos para manipular en cada iteración. También hace posible entrenar en grandes conjuntos de entrenamiento, ya que solo una instancia necesita estar en la memoria en cada iteración (SGD se puede implementar como un algoritmo fuera del núcleo.)\n\nPor otro lado, debido a su naturaleza estocástica (es decir, aleatoria), este algoritmo es mucho menos regular que Batch Gradient Descent: en lugar de disminuir suavemente hasta alcanzar el mínimo, la función de costo rebotará hacia arriba y hacia abajo, disminuyendo solo en promedio. Con el tiempo, terminará muy cerca del mínimo, pero una vez que llegue allí, continuará rebotando y nunca se asentará. Entonces, una vez que se detiene el algoritmo, los valores finales de los parámetros son buenos, pero no óptimos.\n\nStochastic Gradient Descent\n\n![9](https://user-images.githubusercontent.com/63415652/104658893-54e90e00-5689-11eb-9976-c23bff509ab7.PNG)", "_____no_output_____" ], [ "Cuando la función de costo es muy irregular, esto puede ayudar al algoritmo a saltar de los mínimos locales, por lo que el Descenso de gradiente estocástico tiene más posibilidades de encontrar el mínimo global que el Descenso de gradiente por lotes.\n\nPor lo tanto, la aleatoriedad es buena para escapar de los óptimos locales, pero mala porque significa que el algoritmo nunca puede establecerse en el mínimo. Una solución a este dilema es reducir gradualmente la tasa de aprendizaje. Los pasos comienzan siendo grandes (lo que ayuda a avanzar rápidamente y escapar de los mínimos locales), luego se vuelven cada vez más pequeños, lo que permite que el algoritmo se establezca en el mínimo global. Este proceso es similar al recocido simulado, un algoritmo inspirado en el proceso de recocido en metalurgia donde el metal fundido se enfría lentamente. La función que determina la tasa de aprendizaje en cada iteración se llama programa de aprendizaje. Si la tasa de aprendizaje se reduce demasiado rápido, puede quedarse atascado en un mínimo local o incluso terminar congelado a la mitad del mínimo. Si la tasa de aprendizaje se reduce demasiado lentamente, puede saltar alrededor del mínimo durante mucho tiempo y terminar con una solución subóptima si detiene el entrenamiento demasiado pronto. \n\nEste código implementa el descenso de gradiente estocástico usando un programa de aprendizaje simple:", "_____no_output_____" ] ], [ [ "theta_path_sgd = []\nm = len(X_b)\nnp.random.seed(42)", "_____no_output_____" ] ], [ [ "Por convención iteramos por rondas de m iteraciones; cada ronda se llama época. Mientras que el código Batch Gradient Descent se repitió 1000 veces a través de todo el conjunto de entrenamiento, este código pasa por el conjunto de entrenamiento solo 50 veces y alcanza una solución bastante buena:", "_____no_output_____" ] ], [ [ "theta", "_____no_output_____" ] ], [ [ "Aquí se muestra los primeros 20 pasos del entrenamiento (observe cuál irregulares son los pasos).", "_____no_output_____" ] ], [ [ "n_epochs = 50\nt0, t1 = 5, 50 # learning schedule hyperparameters\n\ndef learning_schedule(t):\n return t0 / (t + t1)\n\ntheta = np.random.randn(2,1) # random initialization\n\nfor epoch in range(n_epochs):\n for i in range(m):\n if epoch == 0 and i < 20: # not shown in the book\n y_predict = X_new_b.dot(theta) # not shown\n style = \"b-\" if i > 0 else \"r--\" # not shown\n plt.plot(X_new, y_predict, style) # not shown\n random_index = np.random.randint(m)\n xi = X_b[random_index:random_index+1]\n yi = y[random_index:random_index+1]\n gradients = 2 * xi.T.dot(xi.dot(theta) - yi)\n eta = learning_schedule(epoch * m + i)\n theta = theta - eta * gradients\n theta_path_sgd.append(theta) # not shown\n\nplt.plot(X, y, \"b.\") # not shown\nplt.xlabel(\"$x_1$\", fontsize=18) # not shown\nplt.ylabel(\"$y$\", rotation=0, fontsize=18) # not shown\nplt.axis([0, 2, 0, 15]) # not shown\nsave_fig(\"sgd_plot\") # not shown\nplt.show() # not shown", "Saving figure sgd_plot\n" ] ], [ [ "Tenga en cuenta que, dado que las instancias se seleccionan al azar, algunas instancias pueden elegirse varias veces por época, mientras que otras pueden no seleccionarse en absoluto. Si quieres estar seguro de que el algoritmo pasa por cada instancia en cada época, otro enfoque es mezclar el conjunto de entrenamiento (asegurándote de mezclar las características de entrada y las etiquetas de manera conjunta), luego revisarlo instancia por instancia, luego mezclarlo de nuevo, y así sucesivamente. Sin embargo, esto generalmente converge más lentamente.\n\n>Cuando se usa el descenso de gradiente estocástico, las instancias de entrenamiento deben ser independientes y distribuidas de manera idéntica (IID), para garantizar que los parámetros se acerquen al óptimo global, en promedio. Una forma sencilla de garantizar esto es barajar las instancias durante el entrenamiento (por ejemplo, elegir cada instancia al azar o mezclar el conjunto de entrenamiento al comienzo de cada época). Si no hace esto, por ejemplo, si las instancias están ordenadas por etiqueta, entonces SGD comenzará optimizando para una etiqueta, luego la siguiente, y así sucesivamente, y no se acercará al mínimo global.\n\nPara realizar una regresión lineal usando SGD con Scikit-Learn, puede usar la clase SGDRegressor, que por defecto optimiza la función de costo de error al cuadrado. El siguiente código se ejecuta durante un máximo de 1000 épocas (max_iter = 1000) o hasta que la pérdida disminuya en menos de 1e-3 durante una época (tol = 1e-3), comenzando con una tasa de aprendizaje de 0.1 (eta0 = 0.1), usando el horario de aprendizaje predeterminado (diferente del anterior), y no usa ninguna regularización (penalización = Ninguna; más detalles sobre esto en breve):", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import SGDRegressor\n\nsgd_reg = SGDRegressor(max_iter=1000, tol=1e-3, penalty=None, eta0=0.1, random_state=42)\nsgd_reg.fit(X, y.ravel())", "_____no_output_____" ] ], [ [ "Una vez más, encuentra una solución bastante cercana a la devuelta por la Ecuación Normal:", "_____no_output_____" ] ], [ [ "sgd_reg.intercept_, sgd_reg.coef_", "_____no_output_____" ] ], [ [ "# Descenso de gradiente de mini lotes\n\nEl último algoritmo de Gradient Descent que veremos se llama Gradient Descent por mini lotes. Es bastante simple de entender una vez que se conoce el descenso de gradientes por lotes y estocástico: en cada paso, en lugar de calcular los gradientes basados en el conjunto de entrenamiento completo (como en GD por lotes) o basados en una sola instancia (como en el estocástico GD), Minibatch GD calcula los gradientes en pequeños conjuntos aleatorios de instancias llamados minibatches. La principal ventaja de Mini-batch GD sobre Stochastic GD es que puede obtener un aumento del rendimiento de la optimización del hardware de las operaciones matriciales, especialmente cuando se utilizan GPU.\n\nEl progreso del algoritmo en el espacio de parámetros es menos errático que con SGD, especialmente con mini lotes bastante grandes. Como resultado, Mini-batch GD terminará caminando un poco más cerca del mínimo que SGD. Pero, por otro lado, puede resultarle más difícil escapar de los mínimos locales (en el caso de problemas que sufren de mínimos locales, a diferencia de la Regresión lineal como vimos anteriormente). El siguiente grafico muestra las rutas tomadas por los tres algoritmos de descenso de gradiente en el espacio de parámetros durante el entrenamiento. Todos terminan cerca del mínimo, pero el camino de Batch GD en realidad se detiene en el mínimo, mientras que tanto Stochastic GD como Mini-batch GD continúan caminando. Sin embargo, no olvide que la GD por lotes requiere mucho tiempo para dar cada paso, y la GD estocástica y la GD por mini lotes también alcanzarían el mínimo si utilizara un buen programa de aprendizaje. \n\nRutas de descenso de gradientes en el espacio de parámetros", "_____no_output_____" ] ], [ [ "theta_path_mgd = []\n\nn_iterations = 50\nminibatch_size = 20\n\nnp.random.seed(42)\ntheta = np.random.randn(2,1) # random initialization\n\nt0, t1 = 200, 1000\ndef learning_schedule(t):\n return t0 / (t + t1)\n\nt = 0\nfor epoch in range(n_iterations):\n shuffled_indices = np.random.permutation(m)\n X_b_shuffled = X_b[shuffled_indices]\n y_shuffled = y[shuffled_indices]\n for i in range(0, m, minibatch_size):\n t += 1\n xi = X_b_shuffled[i:i+minibatch_size]\n yi = y_shuffled[i:i+minibatch_size]\n gradients = 2/minibatch_size * xi.T.dot(xi.dot(theta) - yi)\n eta = learning_schedule(t)\n theta = theta - eta * gradients\n theta_path_mgd.append(theta)", "_____no_output_____" ], [ "theta", "_____no_output_____" ], [ "theta_path_bgd = np.array(theta_path_bgd)\ntheta_path_sgd = np.array(theta_path_sgd)\ntheta_path_mgd = np.array(theta_path_mgd)", "_____no_output_____" ], [ "plt.figure(figsize=(7,4))\nplt.plot(theta_path_sgd[:, 0], theta_path_sgd[:, 1], \"r-s\", linewidth=1, label=\"Stochastic\")\nplt.plot(theta_path_mgd[:, 0], theta_path_mgd[:, 1], \"g-+\", linewidth=2, label=\"Mini-batch\")\nplt.plot(theta_path_bgd[:, 0], theta_path_bgd[:, 1], \"b-o\", linewidth=3, label=\"Batch\")\nplt.legend(loc=\"upper left\", fontsize=16)\nplt.xlabel(r\"$\\theta_0$\", fontsize=20)\nplt.ylabel(r\"$\\theta_1$ \", fontsize=20, rotation=0)\nplt.axis([2.5, 4.5, 2.3, 3.9])\nsave_fig(\"gradient_descent_paths_plot\")\nplt.show()", "Saving figure gradient_descent_paths_plot\n" ] ], [ [ "Ahora vamos a comparar los algoritmos que hemos discutido hasta ahora para Regresión lineal (recuerde que m es el número de instancias de entrenamiento y n es el número de características)\n\nComparación de algoritmos para regresión lineal\n\n![10](https://user-images.githubusercontent.com/63415652/104665724-b6b07480-5697-11eb-98f2-26a52a880dd1.PNG) \n\n>Casi no hay diferencia después del entrenamiento: todos estos algoritmos terminan con modelos muy similares y hacen predicciones exactamente de la misma manera.", "_____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" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
ec538772f729d2a7783abf311c88b55770be2e93
43,393
ipynb
Jupyter Notebook
Relazione_2020.ipynb
bankit-cfin/ra-rolli
18765a9bb54e1d8f95c9678cec0599cb61e49bfc
[ "MIT" ]
null
null
null
Relazione_2020.ipynb
bankit-cfin/ra-rolli
18765a9bb54e1d8f95c9678cec0599cb61e49bfc
[ "MIT" ]
null
null
null
Relazione_2020.ipynb
bankit-cfin/ra-rolli
18765a9bb54e1d8f95c9678cec0599cb61e49bfc
[ "MIT" ]
null
null
null
82.969407
25,912
0.722305
[ [ [ "from jelcode import build_dataset, dataset, make_graph", "_____no_output_____" ], [ "data = build_dataset(filename = \"data/File Pub Est pronto per la routine.xlsx\", sheet = \"Publications\")", "_____no_output_____" ], [ "data", "_____no_output_____" ], [ "data2020 = dataset([2020], d = data).append(dataset([2017,2018,2019], d = data))\ndata2020", "_____no_output_____" ], [ "make_graph(data2020)", "_____no_output_____" ], [ "from IPython.display import FileLink, FileLinks\n\ndata2020.to_csv(\"output/Relazione_2020.csv\", index=False)\ndata2020.to_excel(\"output/Relazione_2020.xlsx\", index=False)\n\nFileLinks('output/')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
ec53adf2659c0d5d3c677a0353e8fca0aff5de4e
835,517
ipynb
Jupyter Notebook
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
davidoort/CVND_Exercises
9989a0475983ad6b828bb9d0b0828b2e85d8d230
[ "MIT" ]
null
null
null
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
davidoort/CVND_Exercises
9989a0475983ad6b828bb9d0b0828b2e85d8d230
[ "MIT" ]
null
null
null
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
davidoort/CVND_Exercises
9989a0475983ad6b828bb9d0b0828b2e85d8d230
[ "MIT" ]
null
null
null
1,684.510081
170,231
0.939275
[ [ [ "# Day and Night Image Classifier\n---\n\nThe day/night image dataset consists of 200 RGB color images in two categories: day and night. There are equal numbers of each example: 100 day images and 100 night images.\n\nWe'd like to build a classifier that can accurately label these images as day or night, and that relies on finding distinguishing features between the two types of images!\n\n*Note: All images come from the [AMOS dataset](http://cs.uky.edu/~jacobs/datasets/amos/) (Archive of Many Outdoor Scenes).*\n", "_____no_output_____" ], [ "### Import resources\n\nBefore you get started on the project code, import the libraries and resources that you'll need.", "_____no_output_____" ] ], [ [ "import cv2 # computer vision library\nimport helpers\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Training and Testing Data\nThe 200 day/night images are separated into training and testing datasets. \n\n* 60% of these images are training images, for you to use as you create a classifier.\n* 40% are test images, which will be used to test the accuracy of your classifier.\n\nFirst, we set some variables to keep track of some where our images are stored:\n\n image_dir_training: the directory where our training image data is stored\n image_dir_test: the directory where our test image data is stored", "_____no_output_____" ] ], [ [ "# Image data directories\nimage_dir_training = \"day_night_images/training/\"\nimage_dir_test = \"day_night_images/test/\"", "_____no_output_____" ] ], [ [ "## Load the datasets\n\nThese first few lines of code will load the training day/night images and store all of them in a variable, `IMAGE_LIST`. This list contains the images and their associated label (\"day\" or \"night\"). \n\nFor example, the first image-label pair in `IMAGE_LIST` can be accessed by index: \n``` IMAGE_LIST[0][:]```.\n", "_____no_output_____" ] ], [ [ "# Using the load_dataset function in helpers.py\n# Load training data\nIMAGE_LIST = helpers.load_dataset(image_dir_training)\n", "_____no_output_____" ] ], [ [ "## Construct a `STANDARDIZED_LIST` of input images and output labels.\n\nThis function takes in a list of image-label pairs and outputs a **standardized** list of resized images and numerical labels.", "_____no_output_____" ] ], [ [ "# Standardize all training images\nSTANDARDIZED_LIST = helpers.standardize(IMAGE_LIST)", "_____no_output_____" ] ], [ [ "## Visualize the standardized data\n\nDisplay a standardized image from STANDARDIZED_LIST.", "_____no_output_____" ] ], [ [ "# Display a standardized image and its label\n\n# Select an image by index\nimage_num = 0\nselected_image = STANDARDIZED_LIST[image_num][0]\nselected_label = STANDARDIZED_LIST[image_num][1]\n\n# Display image and data about it\nplt.imshow(selected_image)\nprint(\"Shape: \"+str(selected_image.shape))\nprint(\"Label [1 = day, 0 = night]: \" + str(selected_label))\n", "Shape: (600, 1100, 3)\nLabel [1 = day, 0 = night]: 1\n" ] ], [ [ "# Feature Extraction\n\nCreate a feature that represents the brightness in an image. We'll be extracting the **average brightness** using HSV colorspace. Specifically, we'll use the V channel (a measure of brightness), add up the pixel values in the V channel, then divide that sum by the area of the image to get the average Value of the image.\n", "_____no_output_____" ], [ "---\n### Find the average brigtness using the V channel\n\nThis function takes in a **standardized** RGB image and returns a feature (a single value) that represent the average level of brightness in the image. We'll use this value to classify the image as day or night.", "_____no_output_____" ] ], [ [ "# Find the average Value or brightness of an image\ndef avg_brightness(rgb_image):\n # Convert image to HSV\n hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV)\n\n # Add up all the pixel values in the V channel\n sum_brightness = np.sum(hsv[:,:,2])\n area = 600*1100.0 # pixels\n \n # find the avg\n avg = sum_brightness/area\n \n return avg", "_____no_output_____" ], [ "# Testing average brightness levels\n# Look at a number of different day and night images and think about \n# what average brightness value separates the two types of images\n\n# As an example, a \"night\" image is loaded in and its avg brightness is displayed\nimage_num = 190\ntest_im = STANDARDIZED_LIST[image_num][0]\n\navg = avg_brightness(test_im)\nprint('Avg brightness: ' + str(avg))\nplt.imshow(test_im)", "Avg brightness: 38.9022106061\n" ] ], [ [ "# Classification and Visualizing Error\n\nIn this section, we'll turn our average brightness feature into a classifier that takes in a standardized image and returns a `predicted_label` for that image. This `estimate_label` function should return a value: 0 or 1 (night or day, respectively).", "_____no_output_____" ], [ "---\n### TODO: Build a complete classifier \n\nComplete this code so that it returns an estimated class label given an input RGB image.", "_____no_output_____" ] ], [ [ "# This function should take in RGB image input\ndef estimate_label(rgb_image):\n \n # Extract average brightness feature from an RGB image \n avg = avg_brightness(rgb_image)\n \n # Use the avg brightness feature to predict a label (0, 1)\n predicted_label = 0\n threshold = 90\n if(avg > threshold):\n # if the average brightness is above the threshold value, we classify it as \"day\"\n predicted_label = 1\n # else, the pred-cted_label can stay 0 (it is predicted to be \"night\")\n \n return predicted_label \n ", "_____no_output_____" ] ], [ [ "## Testing the classifier\n\nHere is where we test your classification algorithm using our test set of data that we set aside at the beginning of the notebook!\n\nSince we are using a pretty simple brightess feature, we may not expect this classifier to be 100% accurate. We'll aim for around 75-85% accuracy usin this one feature.\n\n\n### Test dataset\n\nBelow, we load in the test dataset, standardize it using the `standardize` function you defined above, and then **shuffle** it; this ensures that order will not play a role in testing accuracy.\n", "_____no_output_____" ] ], [ [ "import random\n\n# Using the load_dataset function in helpers.py\n# Load test data\nTEST_IMAGE_LIST = helpers.load_dataset(image_dir_test)\n\n# Standardize the test data\nSTANDARDIZED_TEST_LIST = helpers.standardize(TEST_IMAGE_LIST)\n\n# Shuffle the standardized test data\nrandom.shuffle(STANDARDIZED_TEST_LIST)", "_____no_output_____" ] ], [ [ "## Determine the Accuracy\n\nCompare the output of your classification algorithm (a.k.a. your \"model\") with the true labels and determine the accuracy.\n\nThis code stores all the misclassified images, their predicted labels, and their true labels, in a list called `misclassified`.", "_____no_output_____" ] ], [ [ "# Constructs a list of misclassified images given a list of test images and their labels\ndef get_misclassified_images(test_images):\n # Track misclassified images by placing them into a list\n misclassified_images_labels = []\n\n # Iterate through all the test images\n # Classify each image and compare to the true label\n for image in test_images:\n\n # Get true data\n im = image[0]\n true_label = image[1]\n\n # Get predicted label from your classifier\n predicted_label = estimate_label(im)\n\n # Compare true and predicted labels \n if(predicted_label != true_label):\n # If these labels are not equal, the image has been misclassified\n misclassified_images_labels.append((im, predicted_label, true_label))\n \n # Return the list of misclassified [image, predicted_label, true_label] values\n return misclassified_images_labels\n", "_____no_output_____" ], [ "# Find all misclassified images in a given test set\nMISCLASSIFIED = get_misclassified_images(STANDARDIZED_TEST_LIST)\n\n# Accuracy calculations\ntotal = len(STANDARDIZED_TEST_LIST)\nnum_correct = total - len(MISCLASSIFIED)\naccuracy = num_correct/total\n\nprint('Accuracy: ' + str(accuracy))\nprint(\"Number of misclassified images = \" + str(len(MISCLASSIFIED)) +' out of '+ str(total))", "Accuracy: 0.875\nNumber of misclassified images = 20 out of 160\n" ] ], [ [ "---\n<a id='task9'></a>\n### Visualize the misclassified images\n\nVisualize some of the images you classified wrong (in the `MISCLASSIFIED` list) and note any qualities that make them difficult to classify. This will help you identify any weaknesses in your classification algorithm.", "_____no_output_____" ] ], [ [ "# Visualize misclassified example(s)\n## TODO: Display an image in the `MISCLASSIFIED` list \n## TODO: Print out its predicted label - to see what the image *was* incorrectly classified as5\nnum = 7\ntest_mis_im = MISCLASSIFIED[num][0]\nplt.imshow(test_mis_im)\nprint(str(MISCLASSIFIED[num][1]))", "1\n" ] ], [ [ "---\n<a id='question2'></a>\n## (Question): After visualizing these misclassifications, what weaknesses do you think your classification algorithm has?", "_____no_output_____" ], [ "**Answer:** Write your answer, here.", "_____no_output_____" ], [ "# 5. Improve your algorithm!\n\n* (Optional) Tweak your threshold so that accuracy is better.\n* (Optional) Add another feature that tackles a weakness you identified!\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" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
ec53b259bd939746129a2e7603fc5f203298acea
15,933
ipynb
Jupyter Notebook
src/examples/.ipynb_checkpoints/dataWrangling-checkpoint.ipynb
kylmcgr/RL-RNN-SURF
5d6db3e6ff4534003f2a7e832f221b5e529775d5
[ "Apache-2.0" ]
null
null
null
src/examples/.ipynb_checkpoints/dataWrangling-checkpoint.ipynb
kylmcgr/RL-RNN-SURF
5d6db3e6ff4534003f2a7e832f221b5e529775d5
[ "Apache-2.0" ]
null
null
null
src/examples/.ipynb_checkpoints/dataWrangling-checkpoint.ipynb
kylmcgr/RL-RNN-SURF
5d6db3e6ff4534003f2a7e832f221b5e529775d5
[ "Apache-2.0" ]
null
null
null
33.332636
381
0.507061
[ [ [ "cd ..", "C:\\Users\\User\\Documents\\SURF 2021\\RL RNN SURF\\src\n" ], [ "import pandas as pd\nimport os\n\nscores = pd.read_csv(\"selfReportScores.csv\")\ncie = pd.read_csv(\"CIE_measures.csv\")\nmerged = scores.merge(cie, on='workerId')\n\ndirectory = r'C:\\Users\\User\\Documents\\SURF 2021\\RL RNN SURF\\src\\taskData'\nframes = [pd.read_csv('taskData\\\\'+filename) for filename in os.listdir(directory)]\ntaskData = pd.concat(frames, ignore_index=True)", "_____no_output_____" ], [ "length = merged.shape[0]\nquartile = int(length/4)\nfirst_quartile = range(0,quartile)\nlast_quartile = range(length-quartile,length)", "_____no_output_____" ], [ "cd quartileData", "C:\\Users\\User\\Documents\\SURF 2021\\RL RNN SURF\\src\\quartileData\n" ], [ "barratt = merged.sort_values(by=['Barratt'], ignore_index=True)\nbarrattTop = barratt['workerId'][first_quartile]\nbarrattBottom = barratt['workerId'][last_quartile]\ntaskData_barrattTop = taskData[taskData['workerId'].isin(barrattTop)]\ntaskData_barrattBottom = taskData[taskData['workerId'].isin(barrattBottom)]\ntaskData_barrattTop = taskData_barrattTop.dropna(subset=['blockID', 'outcome', 'respKey', 'trialStimID_1', 'trialStimID_2'])\ntaskData_barrattBottom = taskData_barrattBottom.dropna(subset=['blockID', 'outcome', 'respKey', 'trialStimID_1', 'trialStimID_2'])\ntaskData_barrattTop.to_csv('taskData_barrattTop.csv', index=False)\ntaskData_barrattBottom.to_csv('taskData_barrattBottom.csv', index=False)", "_____no_output_____" ], [ "stai = merged.sort_values(by=['STAI.T'], ignore_index=True)\nstaiTop = stai['workerId'][first_quartile]\nstaiBottom = stai['workerId'][last_quartile]\ntaskData_staiTop = taskData[taskData['workerId'].isin(staiTop)]\ntaskData_staiBottom = taskData[taskData['workerId'].isin(staiBottom)]\ntaskData_staiTop = taskData_staiTop.dropna(subset=['blockID', 'outcome', 'respKey', 'trialStimID_1', 'trialStimID_2'])\ntaskData_staiBottom = taskData_staiBottom.dropna(subset=['blockID', 'outcome', 'respKey', 'trialStimID_1', 'trialStimID_2'])\ntaskData_staiTop.to_csv('taskData_staiTop.csv', index=False)\ntaskData_staiBottom.to_csv('taskData_staiBottom.csv', index=False)", "_____no_output_____" ], [ "bdi = merged.sort_values(by=['BDI.II'], ignore_index=True)\nbdiTop = bdi['workerId'][first_quartile]\nbdiBottom = bdi['workerId'][last_quartile]\ntaskData_bdiTop = taskData[taskData['workerId'].isin(bdiTop)]\ntaskData_bdiBottom = taskData[taskData['workerId'].isin(bdiBottom)]\ntaskData_bdiTop = taskData_bdiTop.dropna(subset=['blockID', 'outcome', 'respKey', 'trialStimID_1', 'trialStimID_2'])\ntaskData_bdiBottom = taskData_bdiBottom.dropna(subset=['blockID', 'outcome', 'respKey', 'trialStimID_1', 'trialStimID_2'])\ntaskData_bdiTop.to_csv('taskData_bdiTop.csv', index=False)\ntaskData_bdiBottom.to_csv('taskData_bdiBottom.csv', index=False)", "_____no_output_____" ], [ "bis = merged.sort_values(by=['BIS.BAS'], ignore_index=True)\nbisTop = bis['workerId'][first_quartile]\nbisBottom = bis['workerId'][last_quartile]\ntaskData_bisTop = taskData[taskData['workerId'].isin(bisTop)]\ntaskData_bisBottom = taskData[taskData['workerId'].isin(bisBottom)]\ntaskData_bisTop = taskData_bisTop.dropna(subset=['blockID', 'outcome', 'respKey', 'trialStimID_1', 'trialStimID_2'])\ntaskData_bisBottom = taskData_bisBottom.dropna(subset=['blockID', 'outcome', 'respKey', 'trialStimID_1', 'trialStimID_2'])\ntaskData_bisTop.to_csv('taskData_bisTop.csv', index=False)\ntaskData_bisBottom.to_csv('taskData_bisBottom.csv', index=False)", "_____no_output_____" ], [ "cd ..", "C:\\Users\\User\\Documents\\SURF 2021\\RL RNN SURF\\src\n" ] ], [ [ "Run networks on quartile data, following code merges the predictions", "_____no_output_____" ] ], [ [ "import numpy as np\nimport csv", "_____no_output_____" ], [ "data={}\nwith open('policyData\\\\taskData_barrattBottom.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[3] in barrattBottom.values.tolist():\n if line[3] not in data:\n data[line[3]] = []\n data[line[3]].append(line)\nrlpOption={}\nwith open('rlpOption.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[0] in data:\n if line[0] not in rlpOption:\n rlpOption[line[0]] = []\n i = 0\n if line[1] != 'NaN':\n data[line[0]][i].append(line[1])\n data[line[0]][i].append(line[2])\n i += 1", "_____no_output_____" ], [ "results = [['id','varRNN','varRL']]\nfor i in data:\n varRNN = sum([np.log(float(pred[1])) for pred in data[i]])\n varRL = sum([np.log(float(pred[5])) for pred in data[i]])\n results.append([i,varRNN,varRL])\nnp.savetxt(\"varData\\\\results_barrattBottom.csv\", \n results,\n delimiter =\", \", \n fmt ='% s')", "c:\\users\\user\\documents\\surf 2021\\rl rnn surf\\venv\\lib\\site-packages\\numpy\\lib\\npyio.py:1378: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.\n X = np.asarray(X)\n" ], [ "data={}\nwith open('policyData\\\\taskData_barrattTop.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[3] in barrattBottom.values.tolist():\n if line[3] not in data:\n data[line[3]] = []\n data[line[3]].append(line)\nrlpOption={}\nwith open('rlpOption.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[0] in data:\n if line[0] not in rlpOption:\n rlpOption[line[0]] = []\n i = 0\n if line[1] != 'NaN':\n data[line[0]][i].append(line[1])\n data[line[0]][i].append(line[2])\n i += 1", "_____no_output_____" ], [ "data={}\nwith open('policyData\\\\taskData_bdiBottom.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[3] in barrattBottom.values.tolist():\n if line[3] not in data:\n data[line[3]] = []\n data[line[3]].append(line)\nrlpOption={}\nwith open('rlpOption.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[0] in data:\n if line[0] not in rlpOption:\n rlpOption[line[0]] = []\n i = 0\n if line[1] != 'NaN':\n data[line[0]][i].append(line[1])\n data[line[0]][i].append(line[2])\n i += 1", "_____no_output_____" ], [ "data={}\nwith open('policyData\\\\taskData_bdiTop.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[3] in barrattBottom.values.tolist():\n if line[3] not in data:\n data[line[3]] = []\n data[line[3]].append(line)\nrlpOption={}\nwith open('rlpOption.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[0] in data:\n if line[0] not in rlpOption:\n rlpOption[line[0]] = []\n i = 0\n if line[1] != 'NaN':\n data[line[0]][i].append(line[1])\n data[line[0]][i].append(line[2])\n i += 1", "_____no_output_____" ], [ "data={}\nwith open('policyData\\\\taskData_bisBottom.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[3] in barrattBottom.values.tolist():\n if line[3] not in data:\n data[line[3]] = []\n data[line[3]].append(line)\nrlpOption={}\nwith open('rlpOption.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[0] in data:\n if line[0] not in rlpOption:\n rlpOption[line[0]] = []\n i = 0\n if line[1] != 'NaN':\n data[line[0]][i].append(line[1])\n data[line[0]][i].append(line[2])\n i += 1", "_____no_output_____" ], [ "data={}\nwith open('policyData\\\\taskData_bisTop.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[3] in barrattBottom.values.tolist():\n if line[3] not in data:\n data[line[3]] = []\n data[line[3]].append(line)\nrlpOption={}\nwith open('rlpOption.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[0] in data:\n if line[0] not in rlpOption:\n rlpOption[line[0]] = []\n i = 0\n if line[1] != 'NaN':\n data[line[0]][i].append(line[1])\n data[line[0]][i].append(line[2])\n i += 1", "_____no_output_____" ], [ "data={}\nwith open('policyData\\\\taskData_staiBottom.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[3] in barrattBottom.values.tolist():\n if line[3] not in data:\n data[line[3]] = []\n data[line[3]].append(line)\nrlpOption={}\nwith open('rlpOption.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[0] in data:\n if line[0] not in rlpOption:\n rlpOption[line[0]] = []\n i = 0\n if line[1] != 'NaN':\n data[line[0]][i].append(line[1])\n data[line[0]][i].append(line[2])\n i += 1", "_____no_output_____" ], [ "data={}\nwith open('policyData\\\\taskData_staiTop.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[3] in barrattBottom.values.tolist():\n if line[3] not in data:\n data[line[3]] = []\n data[line[3]].append(line)\nrlpOption={}\nwith open('rlpOption.csv', 'r' ) as theFile:\n reader = csv.reader(theFile)\n headers = next(reader, None)\n for line in reader:\n if line[0] in data:\n if line[0] not in rlpOption:\n rlpOption[line[0]] = []\n i = 0\n if line[1] != 'NaN':\n data[line[0]][i].append(line[1])\n data[line[0]][i].append(line[2])\n i += 1", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec53b895b5364457098ee3696004a48318986397
474,832
ipynb
Jupyter Notebook
Part 7 - Loading Image Data.ipynb
Hamez/DL_PyTorch
4c2367ec8f46aac7951ca3a2963fcf3d611cef6b
[ "MIT" ]
null
null
null
Part 7 - Loading Image Data.ipynb
Hamez/DL_PyTorch
4c2367ec8f46aac7951ca3a2963fcf3d611cef6b
[ "MIT" ]
null
null
null
Part 7 - Loading Image Data.ipynb
Hamez/DL_PyTorch
4c2367ec8f46aac7951ca3a2963fcf3d611cef6b
[ "MIT" ]
2
2018-11-11T04:37:06.000Z
2019-11-26T12:02:20.000Z
1,330.061625
320,388
0.954348
[ [ [ "# Loading Image Data\n\nSo far we've been working with fairly artificial datasets that you wouldn't typically be using in real projects. Instead, you'll likely be dealing with full-sized images like you'd get from smart phone cameras. In this notebook, we'll look at how to load images and use them to train neural networks.\n\nWe'll be using a [dataset of cat and dog photos](https://www.kaggle.com/c/dogs-vs-cats) available from Kaggle. Here are a couple example images:\n\n<img src='assets/dog_cat.png'>\n\nWe'll use this dataset to train a neural network that can differentiate between cats and dogs. These days it doesn't seem like a big accomplishment, but five years ago it was a serious challenge for computer vision systems.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torchvision import datasets, transforms\n\nimport helper\nimport fc_model", "_____no_output_____" ] ], [ [ "The easiest way to load image data is with `datasets.ImageFolder` from `torchvision` ([documentation](http://pytorch.org/docs/master/torchvision/datasets.html#imagefolder)). In general you'll use `ImageFolder` like so:\n\n```python\ndataset = datasets.ImageFolder('path/to/data', transform=transforms)\n```\n\nwhere `'path/to/data'` is the file path to the data directory and `transforms` is a list of processing steps built with the [`transforms`](http://pytorch.org/docs/master/torchvision/transforms.html) module from `torchvision`. ImageFolder expects the files and directories to be constructed like so:\n```\nroot/dog/xxx.png\nroot/dog/xxy.png\nroot/dog/xxz.png\n\nroot/cat/123.png\nroot/cat/nsdf3.png\nroot/cat/asd932_.png\n```\n\nwhere each class has it's own directory (`cat` and `dog`) for the images. The images are then labeled with the class taken from the directory name. So here, the image `123.png` would be loaded with the class label `cat`. You can download the dataset already structured like this [from here](https://s3.amazonaws.com/content.udacity-data.com/nd089/Cat_Dog_data.zip). I've also split it into a training set and test set.\n\n### Transforms\n\nWhen you load in the data with `ImageFolder`, you'll need to define some transforms. For example, the images are different sizes but we'll need them to all be the same size for training. You can either resize them with `transforms.Resize()` or crop with `transforms.CenterCrop()`, `transforms.RandomResizedCrop()`, etc. We'll also need to convert the images to PyTorch tensors with `transforms.ToTensor()`. Typically you'll combine these transforms into a pipeline with `transforms.Compose()`, which accepts a list of transforms and runs them in sequence. It looks something like this to scale, then crop, then convert to a tensor:\n\n```python\ntransforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor()])\n\n```\n\nThere are plenty of transforms available, I'll cover more in a bit and you can read through the [documentation](http://pytorch.org/docs/master/torchvision/transforms.html). \n\n### Data Loaders\n\nWith the `ImageFolder` loaded, you have to pass it to a [`DataLoader`](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader). The `DataLoader` takes a dataset (such as you would get from `ImageFolder`) and returns batches of images and the corresponding labels. You can set various parameters like the batch size and if the data is shuffled after each epoch.\n\n```python\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)\n```\n\nHere `dataloader` is a [generator](https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/). To get data out of it, you need to loop through it or convert it to an iterator and call `next()`.\n\n```python\n# Looping through it, get a batch on each loop \nfor images, labels in dataloader:\n pass\n\n# Get one batch\nimages, labels = next(iter(dataloader))\n```\n \n>**Exercise:** Load images from the `Cat_Dog_data/train` folder, define a few transforms, then build the dataloader.", "_____no_output_____" ] ], [ [ "data_dir = 'Cat_Dog_data/train'\n\ntransform = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor()])\ndataset = datasets.ImageFolder(data_dir, transform=transform)\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=64, shuffle=True)", "_____no_output_____" ], [ "# Run this to test your data loader\nimages, labels = next(iter(dataloader))\nhelper.imshow(images[0], normalize=False)", "_____no_output_____" ] ], [ [ "If you loaded the data correctly, you should see something like this (your image will be different):\n\n<img src='assets/cat_cropped.png', width=244>", "_____no_output_____" ], [ "## Data Augmentation\n\nA common strategy for training neural networks is to introduce randomness in the input data itself. For example, you can randomly rotate, mirror, scale, and/or crop your images during training. This will help your network generalize as it's seeing the same images but in different locations, with different sizes, in different orientations, etc.\n\nTo randomly rotate, scale and crop, then flip your images you would define your transforms like this:\n\n```python\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(100),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], \n [0.5, 0.5, 0.5])])\n```\n\nYou'll also typically want to normalize images with `transforms.Normalize`. You pass in a list of means and list of standard deviations, then the color channels are normalized like so\n\n```input[channel] = (input[channel] - mean[channel]) / std[channel]```\n\nSubtracting `mean` centers the data around zero and dividing by `std` squishes the values to be between -1 and 1. Normalizing helps keep the network work weights near zero which in turn makes backpropagation more stable. Without normalization, networks will tend to fail to learn.\n\nYou can find a list of all [the available transforms here](http://pytorch.org/docs/0.3.0/torchvision/transforms.html). When you're testing however, you'll want to use images that aren't altered (except you'll need to normalize the same way). So, for validation/test images, you'll typically just resize and crop.\n\n>**Exercise:** Define transforms for training data and testing data below.", "_____no_output_____" ] ], [ [ "data_dir = 'Cat_Dog_data'\n\n# TODO: Define transforms for the training data and testing data\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(100),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], \n [0.5, 0.5, 0.5])])\n\ntest_transforms = transforms.Compose([ transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], \n [0.5, 0.5, 0.5])])\n\n\n# Pass transforms in here, then run the next cell to see how the transforms look\ntrain_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)\ntest_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)\n\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=32)\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=32)", "_____no_output_____" ], [ "# change this to the trainloader or testloader \ndata_iter = iter(testloader)\n\nimages, labels = next(data_iter)\nfig, axes = plt.subplots(figsize=(10,4), ncols=4)\nfor ii in range(4):\n ax = axes[ii]\n helper.imshow(images[ii], ax=ax)", "_____no_output_____" ] ], [ [ "Your transformed images should look something like this.\n\n<center>Training examples:</center>\n<img src='assets/train_examples.png' width=500px>\n\n<center>Testing examples:</center>\n<img src='assets/test_examples.png' width=500px>", "_____no_output_____" ], [ "At this point you should be able to load data for training and testing. Now, you should try building a network that can classify cats vs dogs. This is quite a bit more complicated than before with the MNIST and Fashion-MNIST datasets. To be honest, you probably won't get it to work with a fully-connected network, no matter how deep. These images have three color channels and at a higher resolution (so far you've seen 28x28 images which are tiny).\n\nIn the next part, I'll show you how to use a pre-trained network to build a model that can actually solve this problem.", "_____no_output_____" ] ], [ [ "# Optional TODO: Attempt to build a network to classify cats vs dogs from this dataset\nmodel = fc_model.Network(224**2,2,[25000,12500,6250,3125,1024,256,128,64,32])\nmodel\n", "_____no_output_____" ], [ "criterion = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)", "_____no_output_____" ], [ "fc_model.train(model,trainloader,testloader,criterion,optimizer,epochs=3,print_every=40,pixels=224**2)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
ec53c06b0ae849d612c149c0f642380599063fd1
18,874
ipynb
Jupyter Notebook
Ch04/04_03/04_03.ipynb
Sinclair-Seo/Python-for-Data-Science-Essential-Training-in-LinkedIn
5d0c30e760f29d36f68078da1fab3f0987aae4f3
[ "MIT" ]
null
null
null
Ch04/04_03/04_03.ipynb
Sinclair-Seo/Python-for-Data-Science-Essential-Training-in-LinkedIn
5d0c30e760f29d36f68078da1fab3f0987aae4f3
[ "MIT" ]
null
null
null
Ch04/04_03/04_03.ipynb
Sinclair-Seo/Python-for-Data-Science-Essential-Training-in-LinkedIn
5d0c30e760f29d36f68078da1fab3f0987aae4f3
[ "MIT" ]
null
null
null
67.16726
12,368
0.782664
[ [ [ "![title](Header__0006_4.png \"Header\")\n___\n# Chapter 4 - Dimensionality Reduction\n## Segment 3 - Principal component analysis (PCA)", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport pylab as plt\nimport seaborn as sb\nfrom IPython.display import Image\nfrom IPython.core.display import HTML \nfrom pylab import rcParams\n\nimport sklearn\nfrom sklearn import decomposition\nfrom sklearn.decomposition import PCA\nfrom sklearn import datasets", "_____no_output_____" ], [ "%matplotlib inline\nrcParams['figure.figsize'] = 5, 4\nsb.set_style('whitegrid')", "_____no_output_____" ] ], [ [ "### PCA on the iris dataset", "_____no_output_____" ] ], [ [ "iris = datasets.load_iris()\nX = iris.data\nvariable_names = iris.feature_names\nX[0:10,]", "_____no_output_____" ], [ "pca = decomposition.PCA()\niris_pca = pca.fit_transform(X)\n\npca.explained_variance_ratio_", "_____no_output_____" ], [ "pca.explained_variance_ratio_.sum()", "_____no_output_____" ], [ "comps = pd.DataFrame(pca.components_, columns=variable_names)\ncomps", "_____no_output_____" ], [ "sb.heatmap(comps)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
ec53c544c886130a86788c03bbcb12441637b0b4
46,776
ipynb
Jupyter Notebook
test.ipynb
yamaceay/nqdm
6c7961ba5c6c0eca35ac4303bf542058a7a80f72
[ "MIT" ]
4
2021-05-02T18:12:29.000Z
2021-10-14T19:47:39.000Z
test.ipynb
yamaceay/nqdm
6c7961ba5c6c0eca35ac4303bf542058a7a80f72
[ "MIT" ]
1
2021-05-02T11:36:06.000Z
2021-05-02T17:29:50.000Z
test.ipynb
yamaceay/nqdm
6c7961ba5c6c0eca35ac4303bf542058a7a80f72
[ "MIT" ]
null
null
null
32.104324
125
0.33731
[ [ [ "!pip install nqdm\nfrom nqdm import nqdm\n\nimport numpy as np\nimport pandas as pd", "WARNING: You are using pip version 20.2.3; however, version 21.1.1 is available.\nYou should consider upgrading via the 'c:\\users\\yamaç\\python\\python.exe -m pip install --upgrade pip' command.\nRequirement already satisfied: nqdm in c:\\users\\yamaç\\python\\lib\\site-packages (0.1.3)\n" ], [ "arg1 = {k: v for k,v in zip(list(\"abcde\"), list(\"fghij\"))}\narg2 = [v**2 for v in range(10)]\narg3 = 4.0", "_____no_output_____" ], [ "for data in nqdm(arg1):\n print(data)", "100%|██████████| 5/5 [00:00<00:00, 1664.80it/s]\n\n{'a': 'f'}\n{'b': 'g'}\n{'c': 'h'}\n{'d': 'i'}\n{'e': 'j'}\n\n" ], [ "for data in nqdm(arg1, arg2, arg3):\n print(data)", "100%|██████████| 200/200 [00:00<00:00, 1210.61it/s]\n\n[{'a': 'f'}, 0, 0]\n[{'b': 'g'}, 0, 0]\n[{'c': 'h'}, 0, 0]\n[{'d': 'i'}, 0, 0]\n[{'e': 'j'}, 0, 0]\n[{'a': 'f'}, 1, 0]\n[{'b': 'g'}, 1, 0]\n[{'c': 'h'}, 1, 0]\n[{'d': 'i'}, 1, 0]\n[{'e': 'j'}, 1, 0]\n[{'a': 'f'}, 4, 0]\n[{'b': 'g'}, 4, 0]\n[{'c': 'h'}, 4, 0]\n[{'d': 'i'}, 4, 0]\n[{'e': 'j'}, 4, 0]\n[{'a': 'f'}, 9, 0]\n[{'b': 'g'}, 9, 0]\n[{'c': 'h'}, 9, 0]\n[{'d': 'i'}, 9, 0]\n[{'e': 'j'}, 9, 0]\n[{'a': 'f'}, 16, 0]\n[{'b': 'g'}, 16, 0]\n[{'c': 'h'}, 16, 0]\n[{'d': 'i'}, 16, 0]\n[{'e': 'j'}, 16, 0]\n[{'a': 'f'}, 25, 0]\n[{'b': 'g'}, 25, 0]\n[{'c': 'h'}, 25, 0]\n[{'d': 'i'}, 25, 0]\n[{'e': 'j'}, 25, 0]\n[{'a': 'f'}, 36, 0]\n[{'b': 'g'}, 36, 0]\n[{'c': 'h'}, 36, 0]\n[{'d': 'i'}, 36, 0]\n[{'e': 'j'}, 36, 0]\n[{'a': 'f'}, 49, 0]\n[{'b': 'g'}, 49, 0]\n[{'c': 'h'}, 49, 0]\n[{'d': 'i'}, 49, 0]\n[{'e': 'j'}, 49, 0]\n[{'a': 'f'}, 64, 0]\n[{'b': 'g'}, 64, 0]\n[{'c': 'h'}, 64, 0]\n[{'d': 'i'}, 64, 0]\n[{'e': 'j'}, 64, 0]\n[{'a': 'f'}, 81, 0]\n[{'b': 'g'}, 81, 0]\n[{'c': 'h'}, 81, 0]\n[{'d': 'i'}, 81, 0]\n[{'e': 'j'}, 81, 0]\n[{'a': 'f'}, 0, 1]\n[{'b': 'g'}, 0, 1]\n[{'c': 'h'}, 0, 1]\n[{'d': 'i'}, 0, 1]\n[{'e': 'j'}, 0, 1]\n[{'a': 'f'}, 1, 1]\n[{'b': 'g'}, 1, 1]\n[{'c': 'h'}, 1, 1]\n[{'d': 'i'}, 1, 1]\n[{'e': 'j'}, 1, 1]\n[{'a': 'f'}, 4, 1]\n[{'b': 'g'}, 4, 1]\n[{'c': 'h'}, 4, 1]\n[{'d': 'i'}, 4, 1]\n[{'e': 'j'}, 4, 1]\n[{'a': 'f'}, 9, 1]\n[{'b': 'g'}, 9, 1]\n[{'c': 'h'}, 9, 1]\n[{'d': 'i'}, 9, 1]\n[{'e': 'j'}, 9, 1]\n[{'a': 'f'}, 16, 1]\n[{'b': 'g'}, 16, 1]\n[{'c': 'h'}, 16, 1]\n[{'d': 'i'}, 16, 1]\n[{'e': 'j'}, 16, 1]\n[{'a': 'f'}, 25, 1]\n[{'b': 'g'}, 25, 1]\n[{'c': 'h'}, 25, 1]\n[{'d': 'i'}, 25, 1]\n[{'e': 'j'}, 25, 1]\n[{'a': 'f'}, 36, 1]\n[{'b': 'g'}, 36, 1]\n[{'c': 'h'}, 36, 1]\n[{'d': 'i'}, 36, 1]\n[{'e': 'j'}, 36, 1]\n[{'a': 'f'}, 49, 1]\n[{'b': 'g'}, 49, 1]\n[{'c': 'h'}, 49, 1]\n[{'d': 'i'}, 49, 1]\n[{'e': 'j'}, 49, 1]\n[{'a': 'f'}, 64, 1]\n[{'b': 'g'}, 64, 1]\n[{'c': 'h'}, 64, 1]\n[{'d': 'i'}, 64, 1]\n[{'e': 'j'}, 64, 1]\n[{'a': 'f'}, 81, 1]\n[{'b': 'g'}, 81, 1]\n[{'c': 'h'}, 81, 1]\n[{'d': 'i'}, 81, 1]\n[{'e': 'j'}, 81, 1]\n[{'a': 'f'}, 0, 2]\n[{'b': 'g'}, 0, 2]\n[{'c': 'h'}, 0, 2]\n[{'d': 'i'}, 0, 2]\n[{'e': 'j'}, 0, 2]\n[{'a': 'f'}, 1, 2]\n[{'b': 'g'}, 1, 2]\n[{'c': 'h'}, 1, 2]\n[{'d': 'i'}, 1, 2]\n[{'e': 'j'}, 1, 2]\n[{'a': 'f'}, 4, 2]\n[{'b': 'g'}, 4, 2]\n[{'c': 'h'}, 4, 2]\n[{'d': 'i'}, 4, 2]\n[{'e': 'j'}, 4, 2]\n[{'a': 'f'}, 9, 2]\n[{'b': 'g'}, 9, 2]\n[{'c': 'h'}, 9, 2]\n[{'d': 'i'}, 9, 2]\n[{'e': 'j'}, 9, 2]\n[{'a': 'f'}, 16, 2]\n[{'b': 'g'}, 16, 2]\n[{'c': 'h'}, 16, 2]\n[{'d': 'i'}, 16, 2]\n[{'e': 'j'}, 16, 2]\n[{'a': 'f'}, 25, 2]\n[{'b': 'g'}, 25, 2]\n[{'c': 'h'}, 25, 2]\n[{'d': 'i'}, 25, 2]\n[{'e': 'j'}, 25, 2]\n[{'a': 'f'}, 36, 2]\n[{'b': 'g'}, 36, 2]\n[{'c': 'h'}, 36, 2]\n[{'d': 'i'}, 36, 2]\n[{'e': 'j'}, 36, 2]\n[{'a': 'f'}, 49, 2]\n[{'b': 'g'}, 49, 2]\n[{'c': 'h'}, 49, 2]\n[{'d': 'i'}, 49, 2]\n[{'e': 'j'}, 49, 2]\n[{'a': 'f'}, 64, 2]\n[{'b': 'g'}, 64, 2]\n[{'c': 'h'}, 64, 2]\n[{'d': 'i'}, 64, 2]\n[{'e': 'j'}, 64, 2]\n[{'a': 'f'}, 81, 2]\n[{'b': 'g'}, 81, 2]\n[{'c': 'h'}, 81, 2]\n[{'d': 'i'}, 81, 2]\n[{'e': 'j'}, 81, 2]\n[{'a': 'f'}, 0, 3]\n[{'b': 'g'}, 0, 3]\n[{'c': 'h'}, 0, 3]\n[{'d': 'i'}, 0, 3]\n[{'e': 'j'}, 0, 3]\n[{'a': 'f'}, 1, 3]\n[{'b': 'g'}, 1, 3]\n[{'c': 'h'}, 1, 3]\n[{'d': 'i'}, 1, 3]\n[{'e': 'j'}, 1, 3]\n[{'a': 'f'}, 4, 3]\n[{'b': 'g'}, 4, 3]\n[{'c': 'h'}, 4, 3]\n[{'d': 'i'}, 4, 3]\n[{'e': 'j'}, 4, 3]\n[{'a': 'f'}, 9, 3]\n[{'b': 'g'}, 9, 3]\n[{'c': 'h'}, 9, 3]\n[{'d': 'i'}, 9, 3]\n[{'e': 'j'}, 9, 3]\n[{'a': 'f'}, 16, 3]\n[{'b': 'g'}, 16, 3]\n[{'c': 'h'}, 16, 3]\n[{'d': 'i'}, 16, 3]\n[{'e': 'j'}, 16, 3]\n[{'a': 'f'}, 25, 3]\n[{'b': 'g'}, 25, 3]\n[{'c': 'h'}, 25, 3]\n[{'d': 'i'}, 25, 3]\n[{'e': 'j'}, 25, 3]\n[{'a': 'f'}, 36, 3]\n[{'b': 'g'}, 36, 3]\n[{'c': 'h'}, 36, 3]\n[{'d': 'i'}, 36, 3]\n[{'e': 'j'}, 36, 3]\n[{'a': 'f'}, 49, 3]\n[{'b': 'g'}, 49, 3]\n[{'c': 'h'}, 49, 3]\n[{'d': 'i'}, 49, 3]\n[{'e': 'j'}, 49, 3]\n[{'a': 'f'}, 64, 3]\n[{'b': 'g'}, 64, 3]\n[{'c': 'h'}, 64, 3]\n[{'d': 'i'}, 64, 3]\n[{'e': 'j'}, 64, 3]\n[{'a': 'f'}, 81, 3]\n[{'b': 'g'}, 81, 3]\n[{'c': 'h'}, 81, 3]\n[{'d': 'i'}, 81, 3]\n[{'e': 'j'}, 81, 3]\n\n" ], [ "arg1_deep = np.arange(125).reshape(5, 5, 5)\narg2_deep = {str(i): {k+str(i): v+str(i) for k,v in zip(list(\"abcde\"), list(\"fghij\"))} for i in range(20)}", "_____no_output_____" ], [ "for data in nqdm(arg1_deep, depth=0):\n print(data)", "100%|██████████| 5/5 [00:00<00:00, 1248.75it/s]\n\n[[ 0 1 2 3 4]\n [ 5 6 7 8 9]\n [10 11 12 13 14]\n [15 16 17 18 19]\n [20 21 22 23 24]]\n[[25 26 27 28 29]\n [30 31 32 33 34]\n [35 36 37 38 39]\n [40 41 42 43 44]\n [45 46 47 48 49]]\n[[50 51 52 53 54]\n [55 56 57 58 59]\n [60 61 62 63 64]\n [65 66 67 68 69]\n [70 71 72 73 74]]\n[[75 76 77 78 79]\n [80 81 82 83 84]\n [85 86 87 88 89]\n [90 91 92 93 94]\n [95 96 97 98 99]]\n[[100 101 102 103 104]\n [105 106 107 108 109]\n [110 111 112 113 114]\n [115 116 117 118 119]\n [120 121 122 123 124]]\n\n" ], [ "for data in nqdm(arg1_deep, depth=1):\n print(data)", "100%|██████████| 25/25 [00:00<00:00, 2832.38it/s]\n\n[0 1 2 3 4]\n[5 6 7 8 9]\n[10 11 12 13 14]\n[15 16 17 18 19]\n[20 21 22 23 24]\n[25 26 27 28 29]\n[30 31 32 33 34]\n[35 36 37 38 39]\n[40 41 42 43 44]\n[45 46 47 48 49]\n[50 51 52 53 54]\n[55 56 57 58 59]\n[60 61 62 63 64]\n[65 66 67 68 69]\n[70 71 72 73 74]\n[75 76 77 78 79]\n[80 81 82 83 84]\n[85 86 87 88 89]\n[90 91 92 93 94]\n[95 96 97 98 99]\n[100 101 102 103 104]\n[105 106 107 108 109]\n[110 111 112 113 114]\n[115 116 117 118 119]\n[120 121 122 123 124]\n\n" ], [ "for data in nqdm(arg1_deep, depth=2):\n print(data)", "100%|██████████| 125/125 [00:00<00:00, 5686.30it/s]\n\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n101\n102\n103\n104\n105\n106\n107\n108\n109\n110\n111\n112\n113\n114\n115\n116\n117\n118\n119\n120\n121\n122\n123\n124\n\n" ], [ "for data in nqdm(arg2_deep, depth=0):\n print(data)", "100%|██████████| 20/20 [00:00<00:00, 6671.39it/s]\n\n{'0': {'a0': 'f0', 'b0': 'g0', 'c0': 'h0', 'd0': 'i0', 'e0': 'j0'}}\n{'1': {'a1': 'f1', 'b1': 'g1', 'c1': 'h1', 'd1': 'i1', 'e1': 'j1'}}\n{'2': {'a2': 'f2', 'b2': 'g2', 'c2': 'h2', 'd2': 'i2', 'e2': 'j2'}}\n{'3': {'a3': 'f3', 'b3': 'g3', 'c3': 'h3', 'd3': 'i3', 'e3': 'j3'}}\n{'4': {'a4': 'f4', 'b4': 'g4', 'c4': 'h4', 'd4': 'i4', 'e4': 'j4'}}\n{'5': {'a5': 'f5', 'b5': 'g5', 'c5': 'h5', 'd5': 'i5', 'e5': 'j5'}}\n{'6': {'a6': 'f6', 'b6': 'g6', 'c6': 'h6', 'd6': 'i6', 'e6': 'j6'}}\n{'7': {'a7': 'f7', 'b7': 'g7', 'c7': 'h7', 'd7': 'i7', 'e7': 'j7'}}\n{'8': {'a8': 'f8', 'b8': 'g8', 'c8': 'h8', 'd8': 'i8', 'e8': 'j8'}}\n{'9': {'a9': 'f9', 'b9': 'g9', 'c9': 'h9', 'd9': 'i9', 'e9': 'j9'}}\n{'10': {'a10': 'f10', 'b10': 'g10', 'c10': 'h10', 'd10': 'i10', 'e10': 'j10'}}\n{'11': {'a11': 'f11', 'b11': 'g11', 'c11': 'h11', 'd11': 'i11', 'e11': 'j11'}}\n{'12': {'a12': 'f12', 'b12': 'g12', 'c12': 'h12', 'd12': 'i12', 'e12': 'j12'}}\n{'13': {'a13': 'f13', 'b13': 'g13', 'c13': 'h13', 'd13': 'i13', 'e13': 'j13'}}\n{'14': {'a14': 'f14', 'b14': 'g14', 'c14': 'h14', 'd14': 'i14', 'e14': 'j14'}}\n{'15': {'a15': 'f15', 'b15': 'g15', 'c15': 'h15', 'd15': 'i15', 'e15': 'j15'}}\n{'16': {'a16': 'f16', 'b16': 'g16', 'c16': 'h16', 'd16': 'i16', 'e16': 'j16'}}\n{'17': {'a17': 'f17', 'b17': 'g17', 'c17': 'h17', 'd17': 'i17', 'e17': 'j17'}}\n{'18': {'a18': 'f18', 'b18': 'g18', 'c18': 'h18', 'd18': 'i18', 'e18': 'j18'}}\n{'19': {'a19': 'f19', 'b19': 'g19', 'c19': 'h19', 'd19': 'i19', 'e19': 'j19'}}\n\n" ], [ "for data in nqdm(arg2_deep, depth=1):\n print(data)", "100%|██████████| 100/100 [00:00<00:00, 14489.10it/s]\n\nf0\ng0\nh0\ni0\nj0\nf1\ng1\nh1\ni1\nj1\nf2\ng2\nh2\ni2\nj2\nf3\ng3\nh3\ni3\nj3\nf4\ng4\nh4\ni4\nj4\nf5\ng5\nh5\ni5\nj5\nf6\ng6\nh6\ni6\nj6\nf7\ng7\nh7\ni7\nj7\nf8\ng8\nh8\ni8\nj8\nf9\ng9\nh9\ni9\nj9\nf10\ng10\nh10\ni10\nj10\nf11\ng11\nh11\ni11\nj11\nf12\ng12\nh12\ni12\nj12\nf13\ng13\nh13\ni13\nj13\nf14\ng14\nh14\ni14\nj14\nf15\ng15\nh15\ni15\nj15\nf16\ng16\nh16\ni16\nj16\nf17\ng17\nh17\ni17\nj17\nf18\ng18\nh18\ni18\nj18\nf19\ng19\nh19\ni19\nj19\n\n" ], [ "arg1_bin = [2, 2, 2, 2]", "_____no_output_____" ], [ "for data in nqdm(*arg1_bin, order=\"last\"):\n print(data)", "100%|██████████| 16/16 [00:00<00:00, 2217.45it/s]\n\n[0, 0, 0, 0]\n[0, 0, 0, 1]\n[0, 0, 1, 0]\n[0, 0, 1, 1]\n[0, 1, 0, 0]\n[0, 1, 0, 1]\n[0, 1, 1, 0]\n[0, 1, 1, 1]\n[1, 0, 0, 0]\n[1, 0, 0, 1]\n[1, 0, 1, 0]\n[1, 0, 1, 1]\n[1, 1, 0, 0]\n[1, 1, 0, 1]\n[1, 1, 1, 0]\n[1, 1, 1, 1]\n\n" ], [ "for data in nqdm(*arg1_bin, order=\"first\"):\n print(data)", "100%|██████████| 16/16 [00:00<00:00, 941.26it/s]\n\n[0, 0, 0, 0]\n[1, 0, 0, 0]\n[0, 1, 0, 0]\n[1, 1, 0, 0]\n[0, 0, 1, 0]\n[1, 0, 1, 0]\n[0, 1, 1, 0]\n[1, 1, 1, 0]\n[0, 0, 0, 1]\n[1, 0, 0, 1]\n[0, 1, 0, 1]\n[1, 1, 0, 1]\n[0, 0, 1, 1]\n[1, 0, 1, 1]\n[0, 1, 1, 1]\n[1, 1, 1, 1]\n\n" ], [ "for data in nqdm(*arg1_bin, order=[0, 3, 1, 2]):\n print(data)", "100%|██████████| 16/16 [00:00<00:00, 2000.56it/s]\n\n[0, 0, 0, 0]\n[1, 0, 0, 0]\n[0, 0, 1, 0]\n[1, 0, 1, 0]\n[0, 0, 0, 1]\n[1, 0, 0, 1]\n[0, 0, 1, 1]\n[1, 0, 1, 1]\n[0, 1, 0, 0]\n[1, 1, 0, 0]\n[0, 1, 1, 0]\n[1, 1, 1, 0]\n[0, 1, 0, 1]\n[1, 1, 0, 1]\n[0, 1, 1, 1]\n[1, 1, 1, 1]\n\n" ], [ "for data in nqdm(*arg1_bin, order=\"last\", enum=True):\n print(data)", "100%|██████████| 16/16 [00:00<00:00, 841.98it/s]\n\n(0, [0, 0, 0, 0])\n(1, [0, 0, 0, 1])\n(2, [0, 0, 1, 0])\n(3, [0, 0, 1, 1])\n(4, [0, 1, 0, 0])\n(5, [0, 1, 0, 1])\n(6, [0, 1, 1, 0])\n(7, [0, 1, 1, 1])\n(8, [1, 0, 0, 0])\n(9, [1, 0, 0, 1])\n(10, [1, 0, 1, 0])\n(11, [1, 0, 1, 1])\n(12, [1, 1, 0, 0])\n(13, [1, 1, 0, 1])\n(14, [1, 1, 1, 0])\n(15, [1, 1, 1, 1])\n\n" ], [ "for data in nqdm(arg1_deep, arg2_deep, depth=[0, 1], order=\"last\", enum=False):\n print(data)", "96, 97, 98, 99]]), 'g17']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'h17']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'i17']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'j17']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'f18']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'g18']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'h18']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'i18']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'j18']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'f19']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'g19']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'h19']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'i19']\n[array([[75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84],\n [85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94],\n [95, 96, 97, 98, 99]]), 'j19']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f0']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g0']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h0']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i0']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j0']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f1']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g1']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h1']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i1']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j1']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f2']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g2']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h2']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i2']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j2']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f3']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g3']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h3']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i3']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j3']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f4']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g4']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h4']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i4']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j4']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f5']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g5']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h5']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i5']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j5']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f6']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g6']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h6']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i6']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j6']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f7']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g7']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h7']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i7']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j7']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f8']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g8']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h8']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i8']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j8']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f9']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g9']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h9']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i9']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j9']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f10']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g10']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h10']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i10']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j10']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f11']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g11']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h11']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i11']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j11']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f12']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g12']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h12']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i12']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n100%|██████████| 500/500 [00:00<00:00, 827.92it/s]\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f13']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g13']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h13']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i13']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j13']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f14']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g14']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h14']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i14']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j14']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f15']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g15']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h15']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i15']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j15']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f16']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g16']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h16']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i16']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j16']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f17']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g17']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h17']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i17']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j17']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f18']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g18']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h18']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i18']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j18']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'f19']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'g19']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'h19']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'i19']\n[array([[100, 101, 102, 103, 104],\n [105, 106, 107, 108, 109],\n [110, 111, 112, 113, 114],\n [115, 116, 117, 118, 119],\n [120, 121, 122, 123, 124]]), 'j19']\n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec53d8752ba62987456b11bf009ac5b07fefb40a
10,097
ipynb
Jupyter Notebook
package_expos/flashtext/FlashText Tutorial.ipynb
hanisaf/advanced-data-management-and-analytics-spring2021
35178f14b942f2accbcfcbaa5a27e134a9a9f96b
[ "MIT" ]
6
2021-01-21T17:53:34.000Z
2021-04-20T17:37:50.000Z
package_expos/flashtext/FlashText Tutorial.ipynb
hanisaf/advanced-data-management-and-analytics-spring2021
35178f14b942f2accbcfcbaa5a27e134a9a9f96b
[ "MIT" ]
null
null
null
package_expos/flashtext/FlashText Tutorial.ipynb
hanisaf/advanced-data-management-and-analytics-spring2021
35178f14b942f2accbcfcbaa5a27e134a9a9f96b
[ "MIT" ]
13
2021-01-20T16:11:55.000Z
2021-04-28T21:38:07.000Z
34.578767
1,034
0.622165
[ [ [ "This tutorial contains the text of *The Hunger Games* by Suzanne Collins.", "_____no_output_____" ], [ "# FlashText Tutorial", "_____no_output_____" ] ], [ [ "#install for the first time - uncomment the below line to install", "_____no_output_____" ], [ "#!pip install flashtext", "_____no_output_____" ], [ "from flashtext import KeywordProcessor\nkp = KeywordProcessor() #can make the search for keywords case sensitive by adding the argument (case_sensitive = True)", "_____no_output_____" ] ], [ [ "The dataset is a text file (.txt) containing the text of the the novel *The Hunger Games*.", "_____no_output_____" ] ], [ [ "#import text data\n\nwith open('The Hunger Games.txt') as f:\n contents = f.read()\n\n print(contents[82:1000])", "1.\n\nWhen I wake up, the other side of the bed is cold. My fingers stretch out, seeking Prims warmth but finding only the rough canvas cover of the mattress. She must have had bad dreams and climbed in with our mother. Of course, she did. This is the day of the reaping. I prop myself up on one elbow. Theres enough light in the bedroom to see them. My little sister, Prim, curled up on her side, cocooned in my mothers body, their cheeks pressed together. In sleep, my mother looks younger, still worn but not so beaten-down. Prims face is as fresh as a raindrop, as lovely as the primrose for which she was named. My mother was very beautiful once, too. Or so\n\nthey tell me. Sitting at Prims knees, guarding her, is the worlds ugliest cat. Mashed-in nose, half of one ear missing, eyes the color of rotting squash. Prim named him Buttercup, insisting that his muddy yellow coat matched the bright flower. I he hates m\n" ] ], [ [ "## Extracting keywords", "_____no_output_____" ] ], [ [ "#compile keywords to search for\n#function structure: kp.add_keyword(<unprocessed word>, optional: <standardized word to extract when unprocessed word is found>)\n\nkp.add_keyword('Katniss', 'Katniss Everdeen - protagonist')\nkp.add_keyword('District twelve', 'District 12') \nkp.add_keyword('costume', 'battle costume')\n\nwordsfound = kp.extract_keywords(contents)\n\nprint(set(wordsfound))", "{'Katniss Everdeen - protagonist', 'District 12', 'battle costume'}\n" ] ], [ [ "### Add multiple keywords simultaneously", "_____no_output_____" ] ], [ [ "#when want to substitute standardized word for an unprocessed word, compile keywords in a dictionary\n#dict structure: {<standardized word to extract: [<list of unprocessed words that can be substituted for standardized word>]}\n\nword_dict = {'Primrose Everdeen': ['Prim', 'my sister'], 'Hunger Games setting': ['dome', 'arena']}\nkp.add_keywords_from_dict(word_dict)\n\n#when there is no need to differentiate between the unprocessed and standardized word, keywords can be compiled in a list\n\ncharacters = ['Peeta', 'Gale', 'Rue', 'capitol']\nkp.add_keywords_from_list(characters)\n\nwordsfound = kp.extract_keywords(contents)\nprint(set(wordsfound))", "{'Katniss Everdeen - protagonist', 'Peeta', 'Rue', 'Primrose Everdeen', 'capitol', 'District 12', 'Gale', 'Hunger Games setting', 'battle costume'}\n" ] ], [ [ "Note that words added previously are still in the dictionary and therefore extracted. The dictionary is cumulative; the function will also extract or replace all words added to the dictionary in previous steps, unless they are removed.", "_____no_output_____" ], [ "## Replacing keywords", "_____no_output_____" ] ], [ [ "#To replace keywords, the standardized word identified in the add_keywords step(s) will be what replaces the unprocessed words listed in the add_keywords step(s) as they are found\"\n\nsample_sentence = 'Katniss wore her costume in the arena, allowing her to move quickly and hide when necessary.'\nnew_sentence = kp.replace_keywords(sample_sentence)\nprint(new_sentence)", "Katniss Everdeen - protagonist wore her battle costume in the Hunger Games setting, allowing her to move quickly and hide when necessary.\n" ], [ "new_contents = kp.replace_keywords(contents)\nprint(new_contents[18000:20000])", "t. Gale and I divide our spoils, leaving two fish, a couple of loaves of good bread, greens, a quart of strawberries, salt, paraffin, and a bit of money for each. See you in the square, I say. Wear something\n\npretty, he says flatly. At home, I find my mother and sister are ready to go. My mother wears a fine dress from her apothecary days. Primrose Everdeen is in my first reaping outfit, a skirt and ruffled blouse. Its a bit big on her, but my mother has made it stay with pins. Even so, shes having trouble keeping the blouse tucked in at the back. A tub of warm water waits for me. I scrub off the dirt and sweat from the woods and even wash my hair. To my surprise, my mother has laid out one of her own lovely dresses for me. A soft blue thing with matching shoes. Are you sure? I ask. Im trying to get past rejecting offers of help from her. For a while, I was so angry, I wouldnt allow her to do anything for me. And this is something special. Her clothes from her\n\npast are very precious to her. Of course. Lets put your hair up, too, she says. I let her towel-dry it and braid it up on my head. I can hardly recognize myself in the cracked mirror that leans against the wall. You look beautiful, says Primrose Everdeen in a hushed voice. And nothing like myself, I say. I hug her, because I know these next few hours will be terrible for her. Her first reaping. Shes about as safe as you can get, since shes only entered once. I wouldnt let her take out any tesserae. But shes worried about me. That the unthinkable might happen. I protect Primrose Everdeen in every way I can, but Im powerless against the reaping. The anguish I always feel when shes in pain wells up in my chest and threatens to register on my (ace. I notice her blouse has pulled out of her skirt in the back again and force myself to stay calm. Tuck your tail in, little duck, I say, smoothing the blouse back in place. Primrose Everdeen giggles and gives me a small Quack. Quack yourself, I say with a light laugh. T\n" ] ], [ [ "## Determine words in dictionary", "_____no_output_____" ] ], [ [ "#get all keywords in the dictionary\n\nall_words = kp.get_all_keywords()\nprint(all_words)\n\n#check if a keyword is present in the dictionary\n\n'Prim' in kp", "{'katniss': 'Katniss Everdeen - protagonist', 'district twelve': 'District 12', 'dome': 'Hunger Games setting', 'costume': 'battle costume', 'capitol': 'capitol', 'prim': 'Primrose Everdeen', 'peeta': 'Peeta', 'my sister': 'Primrose Everdeen', 'arena': 'Hunger Games setting', 'gale': 'Gale', 'rue': 'Rue'}\n" ], [ "#Remove keyword\n\nprint(kp.extract_keywords(sample_sentence))\n\nkp.remove_keyword('costume')\nnew_sentence2 = kp.extract_keywords(sample_sentence)\nprint(new_sentence2)\n", "['Katniss Everdeen - protagonist', 'battle costume', 'Hunger Games setting']\n['Katniss Everdeen - protagonist', 'Hunger Games setting']\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ec53e60190d1d02a955af71793865bcca0cb0d1b
7,805
ipynb
Jupyter Notebook
02_introduzione_a_jupyter_notebook.ipynb
mnslarcher/metodi-statistici-big-data
4587b4e4104557e50d09d028259d6c42c44d2814
[ "MIT" ]
1
2019-02-17T09:28:04.000Z
2019-02-17T09:28:04.000Z
02_introduzione_a_jupyter_notebook.ipynb
mnslarcher/metodi-statistici-big-data
4587b4e4104557e50d09d028259d6c42c44d2814
[ "MIT" ]
null
null
null
02_introduzione_a_jupyter_notebook.ipynb
mnslarcher/metodi-statistici-big-data
4587b4e4104557e50d09d028259d6c42c44d2814
[ "MIT" ]
null
null
null
31.987705
400
0.602562
[ [ [ "# Introduzione a Jupyter Notebook", "_____no_output_____" ], [ "## Indice\n1. [Jupyter Notebook](#jupyter)<br>\n 1.1 [Lanciare Jupyter Notebook](#lanciare)<br>\n 1.2 [Modalità](#modalità)<br>\n 1.3 [Alcuni comandi utili](#comandi)<br>\n2. [Celle *Markdown*](#markdown)<br>\n3. [Celle *Code*](#code)<br>", "_____no_output_____" ], [ "# 1. Jupyter Notebook\n\n![jupyter_logo](figures/jupyter_logo.jpg)\n\nDal [sito ufficiale](https://jupyter.org/) di Project Jupyter:\n> *The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.*", "_____no_output_____" ], [ "## 1.1 Lanciare Jupyter Notebook <a id=lanciare> \n\nDa terminale, eseguire il comando:\n```\njupyter notebook\n```\n\nAlternativamente, cliccare sull'incona *Jupyter Notebook* installata da Anaconda nel menu start (*Windows only*).\n\n>Nota: il comando da terminale funziona solamente se Anaconda è stata aggiunta al PATH. Su Windows questa opzione va selezionata in fase di installazione oppure il PATH va inserito manualmente in seguito.", "_____no_output_____" ], [ "## 1.2 Modalità <a id=modalità> \n\nJupyter Notebook ha due differenti modalità di inserimento da tastiera: **Edit mode** (premere <kbd>Enter</kbd> per abilitare) consente di digitare codice o testo in una cella ed è indicato da un bordo di cella verde. **Command mode** (premere <kbd>Esc</kbd> per abilitare) lega la tastiera a comandi a livello del notebook ed è indicata da un bordo di cella grigio con un margine sinistro blu.", "_____no_output_____" ], [ "### Esercizio\n\nNella cella seguente, passare dalla modalità **Edit** alla modalità **Command** e viceversa (il margine sinistro deve cambiare come descritto sopra).", "_____no_output_____" ], [ "## 1.3 Alcuni comandi utili <a id=comandi> \n\n* Riavviare il kernel e pulire l'output: *Kernel* $\\rightarrow$ *Restart & Clean Output*\n* Eseguire una cella e selezionare quella sotto: <kbd>Shift</kbd> + <kbd>Enter</kbd> oppure *Cell* $\\rightarrow$ *Run Cells and Select Below*\n* Inserire una cella sopra: <kbd>A</kbd> (Command mode) oppure *Insert* $\\rightarrow$ *Insert Cell Above*\n* Inserire una cella sotto: <kbd>B</kbd> (Command mode) oppure *Insert* $\\rightarrow$ *Insert Cell Below*\n* Cancellare le celle selezionate: <kbd>D</kbd>, <kbd>D</kbd> (Command mode) oppure *Edit* $\\rightarrow$ *Delete Cells*\n* Tagliare le celle selezionate: <kbd>X</kbd> (Command mode) oppure *Edit* $\\rightarrow$ *Cut Cells*\n* Copiare le celle selezionate: <kbd>C</kbd> (Command mode) oppure *Edit* $\\rightarrow$ *Copy Cells*\n* Incollare le celle selezionate: <kbd>V</kbd> (Command mode) oppure *Edit* $\\rightarrow$ *Paste Cells Below*\n* Cambiare il tipo di cella in *Markdown*: <kbd>M</kbd> (Command mode) oppure *Cell* $\\rightarrow$ *Cell Type* $\\rightarrow$ *Markdown*\n* Cambiare il tipo di cella in *Code*: <kbd>Y</kbd> (Command mode) oppure *Cell* $\\rightarrow$ *Cell Type* $\\rightarrow$ *Code*\n* Salvare e creare un *Checkpoint*: <kbd>S</kbd> (Command mode) oppure *File* $\\rightarrow$ *Save and Checkpoint*\n\n>Nota: l'elenco completo delle abbreviazioni da tastiera si può trovare in *Help* $\\rightarrow$ *Keyboard Shortcuts*.", "_____no_output_____" ], [ "### Esercizio\n\nInserire una cella sopra e sotto questa usando le abbreviazioni da tastiera.", "_____no_output_____" ], [ "### Esercizio\n\nCancellare le celle inserite nell'esercizio predecente usando le abbreviazioni da tastiera.", "_____no_output_____" ], [ "### Esercizio\n\nCambiare il tipo della cella seguente da *Markdown* a *Code* e viceversa, eseguire la cella ogni volta.", "_____no_output_____" ] ], [ [ "1 + 1", "_____no_output_____" ] ], [ [ "# 2. Celle *Markdown* <a id=markdown> \n\nDal [sito ufficiale](https://daringfireball.net/projects/markdown/) di Markdown:\n>*Markdown is a text-to-HTML conversion tool for web writers. Markdown allows you to write using an easy-to-read, easy-to-write plain text format, then convert it to structurally valid XHTML (or HTML).*\n\nMarkdown permette di arricchire il Notebook con link, immagini, testi formattati, espressioni in $\\LaTeX$ e molto altro.\n\nUn utile riferimento è il [Markdown-Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).", "_____no_output_____" ], [ "### Esercizio\n\nCreare un link.", "_____no_output_____" ], [ "### Esercizio\nAggiungere un'immagine.", "_____no_output_____" ], [ "### Esercizio\n\nScrivere un'espressione matematica in $\\LaTeX$.\n\n>Suggerimento: prendere spunto dalla seguente [identità di Eulero](https://it.wikipedia.org/wiki/Identit%C3%A0_di_Eulero): $e^{i \\pi} + 1 = 0$", "_____no_output_____" ], [ "# 3. Celle *Code* <a id=code> \n\nUna cella di tipo *Code* permette di inserire del codice ed eseguirlo visualizzandone il risultato. Nelle due parentesi quadre a sinistra della cella viene visualizzato se il contenuto della cella è in esecuzione (simbolo $\\ast$), l'ordine in cui la cella è stata eseguita, oppure nulla se la cella non è mai stata eseguita.", "_____no_output_____" ], [ "### Esercizio\n\nScrivere ed eseguire il comando `print(\"Hello world\")` nella cella seguente.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
ec53e6c321c1be3461faad2d75c6e326ed25dea7
372,676
ipynb
Jupyter Notebook
Seattle AirBnb.ipynb
ronger4242/Seattle_Airbnb
9b238e000c5ad9c6350646c61fc24c4593864aef
[ "CNRI-Python" ]
null
null
null
Seattle AirBnb.ipynb
ronger4242/Seattle_Airbnb
9b238e000c5ad9c6350646c61fc24c4593864aef
[ "CNRI-Python" ]
null
null
null
Seattle AirBnb.ipynb
ronger4242/Seattle_Airbnb
9b238e000c5ad9c6350646c61fc24c4593864aef
[ "CNRI-Python" ]
null
null
null
59.819583
39,764
0.635997
[ [ [ "# Business Understanding", "_____no_output_____" ], [ "### Background\n Seattle tourism is booming and the housing price of Seattle is attractive. Investing now will likely guarantee a return in value. Airbnb investing be a viable option for real estate investors. \n### Business Objectives:\n Which neigborhood and what type of properties will more likely guarantee a return in value in Airbnb investment?\n### Data Mining Goal:\n#### To make better investing decision, a few key factors should be considered and analyzed first: \n * market saturation across neighborhoods<br/>\n * visitors’ rating on location <br/>\n * occupancy rates and monthly revenues across neighborhoods<br/>\n * occupancy rates and monthly revenues by property types<br/>\n\n#### Data mining success criteria\n * Define features of listings/calendars that have strong relationships with price\n\n### Project Plan\n#### Gather\n* Data source: Airbnb data for Seattle<br/>\n\n#### Assess\n* Describe data<br/>\n* Explore data for useful features<br/>\n\n#### Clean\n* Select required subset of data<br/>\n* Preprocess categorical data<br/>\n* Preprocess missing data<br/>\n\n#### Analyze\n* Analyze data for answering relevant questions<br/>\n\n#### Visualize\n* Visualize findings<br/>\n\n#### Results\n* Formulate the answers for the business data mining process", "_____no_output_____" ], [ "# Data Understanding", "_____no_output_____" ], [ "## Collect initial data", "_____no_output_____" ] ], [ [ "#Import libaries and read the listing table\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, mean_squared_error\n\n\ndf = pd.read_csv('C:/Users/Nancy Zhao/Desktop/Nano degrees/Data science/CRISP-DM/data science blog post/listings.csv')\n# remove columns with missing values more than 40%\ncolumns = df.columns\ncolumns = columns[(len(df) - df.count()) / len(df) < 0.4]\ndf = df[columns]\n\n#read the calendar table\ndf1 = pd.read_csv('C:/Users/Nancy Zhao/Desktop/Nano degrees/Data science/CRISP-DM/data science blog post/calendar.csv')\n\n#merge the listing table and the calendar table by id\ndf2 = pd.merge(df, df1, left_on = 'id', right_on = 'listing_id')", "_____no_output_____" ] ], [ [ "## Describe and explore data", "_____no_output_____" ] ], [ [ "# Describe and explore df\ndf.columns", "_____no_output_____" ], [ "df = df[['id', 'host_response_rate', 'neighbourhood_cleansed', 'property_type', 'room_type', 'accommodates', 'bathrooms', 'bedrooms', 'beds','price', 'review_scores_rating', 'review_scores_location','cancellation_policy']]\ndf.head()", "_____no_output_____" ], [ "#check dtypes and see whether it is necessary to do conversion\ndf.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 3818 entries, 0 to 3817\nData columns (total 13 columns):\nid 3818 non-null int64\nhost_response_rate 3295 non-null object\nneighbourhood_cleansed 3818 non-null object\nproperty_type 3817 non-null object\nroom_type 3818 non-null object\naccommodates 3818 non-null int64\nbathrooms 3802 non-null float64\nbedrooms 3812 non-null float64\nbeds 3817 non-null float64\nprice 3818 non-null object\nreview_scores_rating 3171 non-null float64\nreview_scores_location 3163 non-null float64\ncancellation_policy 3818 non-null object\ndtypes: float64(5), int64(2), object(6)\nmemory usage: 387.8+ KB\n" ], [ "# get numeric variables\nnum_vars = df.select_dtypes(include = ['float64', 'int64']).columns\nnum_vars", "_____no_output_____" ], [ "df[num_vars].describe()", "_____no_output_____" ], [ "df_num = df[num_vars].drop(['id'], axis = 1)\ndf_num.hist()", "_____no_output_____" ], [ "df_num.head()", "_____no_output_____" ], [ "sns.heatmap(df_num.corr(), annot = True)", "_____no_output_____" ], [ "# get categorical variables\nobj_vars = df.select_dtypes(include = ['object']).columns\nobj_vars", "_____no_output_____" ], [ "obj_var_list = ['neighbourhood_cleansed','property_type', 'room_type', 'cancellation_policy']\ndf_obj = df[obj_var_list]\n\ndef bar_group(df, list_variable):\n '''\n Description: plot bar graphs for a list of categorical variables.\n Arguments:\n df: dataset\n list_variable: a list of categorical variables\n Return:\n a set of bar plots\n '''\n j = 1\n for i in list_variable:\n plt.subplot(2,2,j)\n graph = df[i].value_counts().plot(kind = 'bar', subplots = True)\n j+=1\n return graph\nbar_group(df_obj,['property_type', 'room_type', 'cancellation_policy'])", "_____no_output_____" ], [ "df1.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1393570 entries, 0 to 1393569\nData columns (total 4 columns):\nlisting_id 1393570 non-null int64\ndate 1393570 non-null object\navailable 1393570 non-null object\nprice 934542 non-null object\ndtypes: int64(1), object(3)\nmemory usage: 42.5+ MB\n" ], [ "df1.head()", "_____no_output_____" ], [ "df2.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 1393570 entries, 0 to 1393569\nData columns (total 90 columns):\nid 1393570 non-null int64\nlisting_url 1393570 non-null object\nscrape_id 1393570 non-null int64\nlast_scraped 1393570 non-null object\nname 1393570 non-null object\nsummary 1328965 non-null object\nspace 1185885 non-null object\ndescription 1393570 non-null object\nexperiences_offered 1393570 non-null object\nneighborhood_overview 1016890 non-null object\ntransit 1052660 non-null object\nthumbnail_url 1276770 non-null object\nmedium_url 1276770 non-null object\npicture_url 1393570 non-null object\nxl_picture_url 1276770 non-null object\nhost_id 1393570 non-null int64\nhost_url 1393570 non-null object\nhost_name 1392840 non-null object\nhost_since 1392840 non-null object\nhost_location 1390650 non-null object\nhost_about 1080035 non-null object\nhost_response_time 1202675 non-null object\nhost_response_rate 1202675 non-null object\nhost_acceptance_rate 1111425 non-null object\nhost_is_superhost 1392840 non-null object\nhost_thumbnail_url 1392840 non-null object\nhost_picture_url 1392840 non-null object\nhost_neighbourhood 1284070 non-null object\nhost_listings_count 1392840 non-null float64\nhost_total_listings_count 1392840 non-null float64\nhost_verifications 1393570 non-null object\nhost_has_profile_pic 1392840 non-null object\nhost_identity_verified 1392840 non-null object\nstreet 1393570 non-null object\nneighbourhood 1241730 non-null object\nneighbourhood_cleansed 1393570 non-null object\nneighbourhood_group_cleansed 1393570 non-null object\ncity 1393570 non-null object\nstate 1393570 non-null object\nzipcode 1391015 non-null object\nmarket 1393570 non-null object\nsmart_location 1393570 non-null object\ncountry_code 1393570 non-null object\ncountry 1393570 non-null object\nlatitude 1393570 non-null float64\nlongitude 1393570 non-null float64\nis_location_exact 1393570 non-null object\nproperty_type 1393205 non-null object\nroom_type 1393570 non-null object\naccommodates 1393570 non-null int64\nbathrooms 1387730 non-null float64\nbedrooms 1391380 non-null float64\nbeds 1393205 non-null float64\nbed_type 1393570 non-null object\namenities 1393570 non-null object\nprice_x 1393570 non-null object\ncleaning_fee 1017620 non-null object\nguests_included 1393570 non-null int64\nextra_people 1393570 non-null object\nminimum_nights 1393570 non-null int64\nmaximum_nights 1393570 non-null int64\ncalendar_updated 1393570 non-null object\nhas_availability 1393570 non-null object\navailability_30 1393570 non-null int64\navailability_60 1393570 non-null int64\navailability_90 1393570 non-null int64\navailability_365 1393570 non-null int64\ncalendar_last_scraped 1393570 non-null object\nnumber_of_reviews 1393570 non-null int64\nfirst_review 1164715 non-null object\nlast_review 1164715 non-null object\nreview_scores_rating 1157415 non-null float64\nreview_scores_accuracy 1153400 non-null float64\nreview_scores_cleanliness 1155225 non-null float64\nreview_scores_checkin 1153400 non-null float64\nreview_scores_communication 1155955 non-null float64\nreview_scores_location 1154495 non-null float64\nreview_scores_value 1154130 non-null float64\nrequires_license 1393570 non-null object\njurisdiction_names 1393570 non-null object\ninstant_bookable 1393570 non-null object\ncancellation_policy 1393570 non-null object\nrequire_guest_profile_picture 1393570 non-null object\nrequire_guest_phone_verification 1393570 non-null object\ncalculated_host_listings_count 1393570 non-null int64\nreviews_per_month 1164715 non-null float64\nlisting_id 1393570 non-null int64\ndate 1393570 non-null object\navailable 1393570 non-null object\nprice_y 934542 non-null object\ndtypes: float64(15), int64(14), object(61)\nmemory usage: 967.5+ MB\n" ], [ "df2.head()", "_____no_output_____" ], [ "# check dtypes for the variables and see whether a conversion is needed.\ndf.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 3818 entries, 0 to 3817\nData columns (total 13 columns):\nid 3818 non-null int64\nhost_response_rate 3295 non-null object\nneighbourhood_cleansed 3818 non-null object\nproperty_type 3817 non-null object\nroom_type 3818 non-null object\naccommodates 3818 non-null int64\nbathrooms 3802 non-null float64\nbedrooms 3812 non-null float64\nbeds 3817 non-null float64\nprice 3818 non-null object\nreview_scores_rating 3171 non-null float64\nreview_scores_location 3163 non-null float64\ncancellation_policy 3818 non-null object\ndtypes: float64(5), int64(2), object(6)\nmemory usage: 387.8+ KB\n" ] ], [ [ "# Data Preparation", "_____no_output_____" ], [ "## Data prepration for the listing table", "_____no_output_____" ] ], [ [ "# Convert a few strings to floats\ndf['host_response_rate_val'] = df['host_response_rate'].str.rstrip('%').astype(float)/100\ndf['price_val'] = df['price'].str.lstrip('$').str.replace(',', '').astype(float)", "_____no_output_____" ], [ "#how many missing values each variable has?\nfor num_var in num_vars:\n print(str(num_var) + ' ' + str(df[num_var].isnull().sum()))", "id 0\naccommodates 0\nbathrooms 16\nbedrooms 6\nbeds 1\nreview_scores_rating 647\nreview_scores_location 655\n" ], [ "#replace NAs using means for numeric variable\nfor num_var in num_vars:\n df[num_var].fillna(df[num_var].mean(), inplace = True)", "_____no_output_____" ], [ "#check whether they are replaced\nfor num_var in num_vars:\n print(str(num_var) + ' ' + str(df[num_var].isnull().sum()))", "id 0\naccommodates 0\nbathrooms 0\nbedrooms 0\nbeds 0\nreview_scores_rating 0\nreview_scores_location 0\n" ], [ "df.head()", "_____no_output_____" ] ], [ [ "## Data preparation for the calendar table", "_____no_output_____" ] ], [ [ "#Convert date_trans to datetime type, slice the data of 2016, convert 'available' from \"t and f\" to \"0 and 1\"\ndf1['date_trans'] = pd.to_datetime(df1['date'])\ndf1['date_month'] = df1['date_trans'].apply(lambda x: x.strftime('%m'))\n\ndf1 = df1[(df1['date_trans'] >= pd.datetime(2016,1,1)) & (df1['date_trans'] <= pd.datetime(2016,12,31))]\ndf1['available_bool'] = np.where(df1['available'].str.contains('f'), 1,0)", "_____no_output_____" ] ], [ [ "# Modeling/Analysis", "_____no_output_____" ], [ "## Question 1: Number of Airbnb properties by neighborhood", "_____no_output_____" ] ], [ [ "#How many Airbnb properties in Seattle\ntotal_properties = len(np.unique(df['id']))\ntotal_properties", "_____no_output_____" ], [ "#Create groupby_stats() function:\ndef groupby_stats(df, method, stats_var, grouping_var):\n ''' Description: group stats_var by grouping_var and conduct statistical analysis on stats_var\n Arguments:\n df: dataset\n method: statistical method to use\n stats_var: the variable to be analyzed\n grouping_var: the variable used to do grouping\n Return:\n a dataframe where the index is the grouping_var, and the values are the statistical values of stats_var\n '''\n df_grouping1 = df.groupby(df[grouping_var])[stats_var]\n \n if method == 'sum':\n df_grouping2 = df_grouping1.sum()\n elif method == 'mean':\n df_grouping2 = df_grouping1.mean()\n elif method == 'count':\n df_grouping2 = df_grouping1.count()\n return pd.DataFrame(df_grouping2.sort_values(ascending = False))\n # return df_grouping", "_____no_output_____" ], [ "#number of properties by neighborhood\nnumber_properties = groupby_stats(df, 'count', 'id', 'neighbourhood_cleansed')\nnumber_properties.head()", "_____no_output_____" ], [ "# number of properties in a few communities\nprint(number_properties.loc[['Pike-Market', 'Alki', 'Fauntleroy', 'Highland Park', 'South Beacon Hill', 'South Park']])", " id\nneighbourhood_cleansed \nPike-Market 28\nAlki 42\nFauntleroy 10\nHighland Park 11\nSouth Beacon Hill 4\nSouth Park 3\n" ], [ "# Market share by neighborhood\nproportion_properties = number_properties/number_properties.sum()\nproportion_properties = proportion_properties.rename(columns = {'id': 'proportion'})\nproportion_properties.head()", "_____no_output_____" ], [ "# Market share for a few communities\nproportion_properties.loc[['Montlake', 'Westlake', 'South Lake Union', 'Madrona', 'East Queen Anne', 'North Beach/Blue Ridge', 'Belltown', 'West Queen Anne']]", "_____no_output_____" ], [ "# Market share for the top three communities\nproportion_properties.iloc[0:3].sum()", "_____no_output_____" ] ], [ [ "## Question 2: Ten top rated neighbourhood by location", "_____no_output_____" ] ], [ [ "rating_by_neighbor = groupby_stats(df, 'mean', 'review_scores_location', 'neighbourhood_cleansed')\nrating_by_neighbor", "_____no_output_____" ], [ "#Concat rating and number of properties: how saturated the market is in the communities of 'good location'\nrating_properties = pd.merge(rating_by_neighbor, number_properties, on = 'neighbourhood_cleansed')\nrating_properties.iloc[0:11]", "_____no_output_____" ] ], [ [ "## Question 3 Occupancy rate and monthly revenue by neighbourhood in 2016", "_____no_output_____" ], [ "### Calculate the occupancy rate by neighbourhood", "_____no_output_____" ] ], [ [ "df2.head()", "_____no_output_____" ], [ "df2 = pd.merge(df, df1, left_on = 'id', right_on = 'listing_id')\noccupancy_neighbour = groupby_stats(df2, 'sum', 'available_bool', 'neighbourhood_cleansed')\ntotal_neighbour = groupby_stats(df2, 'count', 'available_bool', 'neighbourhood_cleansed')\noccupancy_rate_neighbour = occupancy_neighbour / total_neighbour\noccupancy_rate_neighbour.sort_values(ascending = False, by = ['available_bool'])", "_____no_output_____" ] ], [ [ "### Calculate the average price by neighbourhood", "_____no_output_____" ] ], [ [ "price_by_neighbor = groupby_stats(df2, 'mean', 'price_val', 'neighbourhood_cleansed')\nprice_by_neighbor.sort_values(ascending = False, by = ['price_val'])", "_____no_output_____" ], [ "#Get prices for a few communities\nprice_by_neighbor.loc[['Pike-Market', 'Alki', 'Fauntleroy']]", "_____no_output_____" ] ], [ [ "### Calculate monthly reveunue by neighbourhood", "_____no_output_____" ] ], [ [ "monthly_income_neighbour = pd.DataFrame(30*occupancy_rate_neighbour['available_bool'].multiply(price_by_neighbor['price_val'], axis = \"index\"))\nmonthly_income_neighbour = monthly_income_neighbour.rename(columns = {0:'monthly revenue'}).sort_values(ascending = False, by = ['monthly revenue'])\nmonthly_income_neighbour", "_____no_output_____" ] ], [ [ "### Bar plot the five most profitable Airbnb properties by neighborhood", "_____no_output_____" ] ], [ [ "g_income = monthly_income_neighbour.head(n=5)\ng_income.info()\ng_income.plot.bar()", "<class 'pandas.core.frame.DataFrame'>\nIndex: 5 entries, Montlake to East Queen Anne\nData columns (total 1 columns):\nmonthly revenue 5 non-null float64\ndtypes: float64(1)\nmemory usage: 80.0+ bytes\n" ], [ "#Get monthly revenue for a few communities\nmonthly_income_neighbour.loc[['Broadway', 'Belltown', 'Wallingford', 'Pike-Market', 'Alki', 'Fauntleroy']]", "_____no_output_____" ], [ "#Merge revenue and proportion to see: how profitable the properties are by neighbourhood? How saturated the market is? (Any potential for market entry)\nrevenue_proportion = pd.merge(monthly_income_neighbour, proportion_properties, on = 'neighbourhood_cleansed')\nrevenue_proportion", "_____no_output_____" ] ], [ [ "## Question 4: Monthly revenue by property type", "_____no_output_____" ], [ "### Occupancy rate by property", "_____no_output_____" ] ], [ [ "occupancy_property = groupby_stats(df2, 'sum', 'available_bool', 'property_type')\n\n#df2.groupby(df2['property_type'])['available_bool'].sum()\ntotal_property = groupby_stats(df2, 'count', 'available_bool', 'property_type')\noccupancy_rate_property = occupancy_property / total_property\noccupancy_rate_property = pd.DataFrame(occupancy_rate_property.sort_values(ascending = False, by = ['available_bool']))\noccupancy_rate_property = occupancy_rate_property.rename(columns = {'available_bool' : 'occupancy rate'})\noccupancy_rate_property", "_____no_output_____" ] ], [ [ "### Average price by property", "_____no_output_____" ] ], [ [ "avg_price_property = groupby_stats(df2, 'mean', 'price_val', 'property_type')\navg_price_property = pd.DataFrame(avg_price_property )\navg_price_property = avg_price_property.rename(columns = {'price_val' : 'price per night'})\navg_price_property", "_____no_output_____" ] ], [ [ "### Monthly revenue by property", "_____no_output_____" ] ], [ [ "monthly_income_property = pd.DataFrame(30*occupancy_rate_property['occupancy rate'].multiply(avg_price_property['price per night'], axis = \"index\"))\nmonthly_income_property = monthly_income_property.rename(columns = {0 : 'monthly revenue'}).sort_values(ascending = False, by = ['monthly revenue'])\nmonthly_income_property", "_____no_output_____" ], [ "#merge monthly revenue, price, occupancy rate by property for better presentation\nrevenue_property = pd.merge(pd.merge(monthly_income_property,avg_price_property,on = 'property_type'), occupancy_rate_property, on = 'property_type')\nrevenue_property", "_____no_output_____" ] ], [ [ "### Bar plot monthly revenue by property type", "_____no_output_____" ] ], [ [ "monthly_income_property.plot.bar()", "_____no_output_____" ] ], [ [ "## Question 5: Price prediction", "_____no_output_____" ] ], [ [ "df_num = df[['accommodates','bathrooms', 'beds','bedrooms', 'review_scores_location', 'zipcode', 'property_type', 'room_type', 'price_val']]\nsns.heatmap(df_num.corr(), annot = True)", "_____no_output_____" ], [ "# There are 7 numeric variables: accommodates, bathrooms, bedrooms, beds, zipcode, review_scores_location, review_scores_rating to consider, \n# due to the strong correlations between beds and berooms, beds and accommodates, I decided to drop beds. New properties may not have review scores yet\n# Thus, I will drop review_scores_rating. The review_score_location rating is not strongly related with price, thus will be dropped. Therefore, the X variables include:\n # numeric:accommodates, bathrooms, bedrooms, zipcode\n # categorical: property_type, room_type\n\nx = df[['accommodates','bathrooms', 'bedrooms', 'zipcode', 'property_type', 'room_type']]\nx.head()", "_____no_output_____" ], [ "# dummy categorical variables: neighbourhood_cleansed,property_type, room_type\nobj_var_list1 = x.select_dtypes(include = ['object']).columns\nfor cat in obj_var_list1:\n x = pd.concat([x.drop(cat, axis = 1), pd.get_dummies(x[cat], prefix = cat, prefix_sep = '_')], axis = 1)", "_____no_output_____" ], [ "x.head()", "_____no_output_____" ], [ "y = df['price'].str.lstrip('$').str.replace(',', '').astype(float)\ny.head()", "_____no_output_____" ], [ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = .3, random_state= 42)\nprint(x_train.shape)\nprint(x_test.shape)", "(2672, 50)\n(1146, 50)\n" ], [ "#check any missing values\nx.isnull().sum()", "_____no_output_____" ], [ "#instantiate-->fit training -->predict -->score\nlm_model = LinearRegression(normalize = True)\nlm_model.fit(x_train, y_train) ", "_____no_output_____" ], [ "y_test_preds = lm_model.predict(x_test)\ny_train_preds = lm_model.predict(x_train)", "_____no_output_____" ], [ "y_test_preds", "_____no_output_____" ], [ "correlations = pd.DataFrame({'name': list(x), 'value':lm_model.coef_})\ncorrelations", "_____no_output_____" ] ], [ [ "# Evaluation", "_____no_output_____" ], [ "### Evaluating results", "_____no_output_____" ] ], [ [ "r2_score(y_test, y_test_preds)", "_____no_output_____" ], [ "# overage housing price for the test data\nnp.mean(y_test_preds)", "_____no_output_____" ], [ "ax=plt.subplot(122, frameon=True)\nax.scatter(y_train, y_train_preds)\nax.scatter(y_test,y_test_preds)\nax.set_xlabel('predicted')\nax.set_ylabel('real')\nax.legend(['Train', 'Test'])\nax.title.set_text('Real Price vs Predicted Price')\nax.plot([0, 550], [0, 550], c='r', linewidth=3)", "_____no_output_____" ], [ "#Testing a new data point: an apartment property (room type: Entire home/apt) which can accommodates 4, have 1 bathroom, 1 bedrooms, with 10 on its location rating, \n#located in 98119\nx.loc[1]", "_____no_output_____" ], [ "new_data = x.loc[1]\nlm_model.predict([new_data])", "_____no_output_____" ], [ "#In reality, the value is $150, very similar to the one that is estimated.\ny.loc[1]", "_____no_output_____" ] ], [ [ "### Review process", "_____no_output_____" ], [ "* Data collected from Airbnb Seattle was used to explore the market saturation, visitors' rating on location, average housing price by neighborhood and property type, and build a multiple linear regression model to predict the price.\n* Only subset of Airbnb listings with less than 40% missin values were selected for analysis\n* Missing values were then replaced by using mean.\n* Categorical variables, such as property type and room type, are dummied for the linear regression model.", "_____no_output_____" ], [ "### Determine next steps", "_____no_output_____" ], [ "* Include other years' data to predict\n* Include other independent variables (features), especially amenity and other review scores.\n* Apply the formula for new property owners to set price for their new listings", "_____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" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
ec540e17741e75607602e4dffeb863f7c85f892b
36,122
ipynb
Jupyter Notebook
solutions/03_WebSearching_solution.ipynb
pbooth01/CSCI-E-96
1b7965ca820939bf5be6fd5a9c62d15a99fd81ed
[ "MIT" ]
null
null
null
solutions/03_WebSearching_solution.ipynb
pbooth01/CSCI-E-96
1b7965ca820939bf5be6fd5a9c62d15a99fd81ed
[ "MIT" ]
null
null
null
solutions/03_WebSearching_solution.ipynb
pbooth01/CSCI-E-96
1b7965ca820939bf5be6fd5a9c62d15a99fd81ed
[ "MIT" ]
null
null
null
44.927861
573
0.626073
[ [ [ "# Assignment 03\n## Web Search\n## CSCI S-96 \n\n> **Instructions:** For this assignment you will complete the exercises shown. All exercises involve creating and executing some Python code. Additionally, most exercises have questions for you to answer. You can answer questions by creating a Markdown cell and writing your answer. If you are not familiar with Markdown, you can find a brief tutorial [here](https://www.markdownguide.org/cheat-sheet/). \n\nIn this assignment you will gain some experience and insight into how web search algorithms work. Specifically, you will implement versions of three algorithms, simple PageRank, PageRank with damping, and the HITS algorithm. All three of these algorithms use a directed graph model of the web. \n\nData small scale examples and coding methods used here are not directly scalable to web sized problems. Rather, the point is for you to understand the basic characteristics of these web search algorithms. Web scale searching requires massive resources not readily available to most people. ", "_____no_output_____" ], [ "## Simple PageRank Example\n\nTo get a feeling for the basics of the PageRank algorithm you will create and test simple code. \n\nAs a first step, execute the code in the cell below to import the packages you will need for the exercises. ", "_____no_output_____" ] ], [ [ "import numpy as np", "_____no_output_____" ] ], [ [ "We will start with a simple example. Figure 1 shows a set of web pages and their hyperlinks. This is a directed graph with the pages as nodes and the hyperlinks as the directed edges. This graph is **complete**. Every page is accessable from any other page, possibly with visits to intermediate nodes required. \n\n<img src=\"../images/web1.png\" alt=\"Drawing\" style=\"width:500px; height:400px\"/>\n<center>Figure 1: A small set of web pages</center>\n\nThe directed edges of the graph define the association between the nodes. A directed edge, or hyperlink, runs from a node's column to another node's row. The association is binary. The directed edge either exists or it does not. ", "_____no_output_____" ], [ "> **Exercise 03-1:** In the cell below you will create the association matrix and the initial page probability vector. Do the following: \n> 1. Create the association matrix, $A$, using [numpy.array](https://numpy.org/doc/stable/reference/generated/numpy.array.html). This matrix is constructed with a 1 where a page in a column links to another page, and 0 elsewhere. \n> 2. Print the shape of your association matrix as a check of your association matrix.\n> 3. Print the in degree and out degree of your association matrix, using [numpy.sum](https://numpy.org/doc/stable/reference/generated/numpy.sum.html). Set the argument `axis` to 1 to sum across rows and 0 to sum down columns. \n> 3. Create the uniformly distributed page probability vector, $p$, using `numpy.array`. \n> 4. Verify that the page probability vector sums to 1.0 using `numpy.sum`.", "_____no_output_____" ] ], [ [ "## Create the Association Matrix and print the summary\n## Put your code below\nA = np.array([[0,1,0,1,0],\n [1,0,0,0,0],\n [1,0,0,0,0],\n [1,1,1,0,1],\n [0,1,1,1,0]])\nprint(A.shape)\nprint(np.sum(A, axis=1))\nprint(np.sum(A, axis=0))\n\n## Create the equal probability starting values\n## Put your code below\np = np.array([0.2,0.2,0.2,0.2,0.2])\nprint(np.sum(p))", "(5, 5)\n[2 1 1 4 3]\n[3 3 2 2 1]\n1.0\n" ] ], [ [ "> Answer the following questions: \n> - Are the out degree and in degree you computed from the association matrix consistent with the graph? \n> - Are the page probabilities a proper distribution summing to 1.0? \n> **End of exercise.**", "_____no_output_____" ], [ "For the PageRank algorithm we must normalize the association matrix by the inverse of the out degree of each page. This normalization uniformly distributes the influence of each page on the PageRank of the other pages over its out degree. The calculation of the out degree of a network is illustrated in Figure 2. \n\n<img src=\"../images/outdegree.png\" alt=\"Drawing\" style=\"width:400px; height:200px\"/>\n<center>Figure 2: Example of computing out degree from an association matrix</center>\n\nThe normalized transition probability matrix, $M$, is then computed from the association matrix, $A$: \n\n$$M = A D^{-1}$$\n\nWhere, $D^{-1}$ is the inverse of a matrix with the out degree values on the diagonal and zeros elsewhere. \n\nYou can see from the foregoing that $M$ distributes the influence of the page by the in|verse of the out degree. In other words, the influence is inversely weighted by the number of pages each page links to. ", "_____no_output_____" ], [ "> **Exercise 03-2:** You will now compute the normalized transition matrix, $M$. To do so create a function called `norm_association` with the association matrix as the argument. Do the following: \n> 1. Create your function `norm_association` which will do the following: \n> - Compute the sum of the columns of the association matrix using `numpy.sum` with the `axis=0` argument to sum along columns. \n> - Compute the inverse of the column sums as a vector. Be sure to avoid zero divides, which will occur in subsequent exercises. If the column sum is 0 set the inverse to zero. \n> - Create a square diagonal matrix from the inverse column sums using [numpy.diag](https://numpy.org/doc/stable/reference/generated/numpy.diag.html) to form the inverse out degree diagonal matrix.\n> - Finally, return the matrix product of the association matrix and inverse out degree matrix using [numpy.matmul](https://numpy.org/doc/stable/reference/generated/numpy.matmul.html). \n2. Execute your function on the association matrix you computed. Save and print the normalized transition matrix, and examine the result. ", "_____no_output_____" ] ], [ [ "def norm_association(A):\n '''Function to normalize the association matrix by out degree.\n The function accounts for cases where the column sum is 0'''\n ## Put your code below\n col_sum = np.sum(A, axis=0)\n d = [0.0]*len(col_sum)\n for i,x in enumerate(col_sum): \n if x > .0001: d[i] = 1.0/x \n D_inv = np.diag(d)\n return np.matmul(A,D_inv)\n\n## Execute the function\n## Put your code below\nM = norm_association(A)\nM", "_____no_output_____" ] ], [ [ "> Does the result look correct based on the out degree of each page on the graph? \n> **End of exercise.**", "_____no_output_____" ], [ "With the transition probability matrix, $M$ computed it is time to investigate the convergence of the PageRank algorithm. You can think of the PageRank algorithm as a series of transitions of a Markov Chain. Given the transition probability matrix, $M$, the update, or single Markov transition, of the page probabilities, $p_i$, is computed: \n\n$$p_i = M p_{i-1}$$\n\nThe Markov chain can be executed for a great many transitions. The result of $n$ transitions, starting from an initial set of page probabilities, $p_0$, can be written: \n\n$$p_n = M^n p_{0}$$\n\nAt convergence the page probabilities, $p_n$, approach a constant or **steady state** value. This steady state probability vector values are the PageRank of the web pages. ", "_____no_output_____" ], [ "> **Exercise 03-3:** You will now create and execute code with the goal of getting a feel for how the page probabilities change for a single transition of a Markov process. The accomplish this task you will create a function called `transition` with arguments of the the normalized transition probability matrix and the vector of page probabilities. Specifically you will: \n> 1. Create the function `transition` which uses [numpy.dot](https://numpy.org/doc/stable/reference/generated/numpy.dot.html) to compute the product of the transition matrix and the page probability vector. \n> 2. Execute the `transition` function on the normalized transition probability matrix and vector of initial page probabilities you have created, saving the result. \n> 3. Print the Euclidean (L2) norm of the difference between the initial page probabilities and the updated page probabilities. \n> 4. Print the sum of the page probabilities computed with `transition` along with the actual vector of values. ", "_____no_output_____" ] ], [ [ "def transition(transition_probs, probs):\n '''Function to compute the probabilities resulting from a \n single transition of a Markov process'''\n ## Put your code below\n return np.dot(transition_probs, probs)\n\n## Compute probabilities after first state trasnition and print the sumamries\n## Put your code below\np1 = transition(M, p)\nprint(np.linalg.norm(np.subtract(p,p1)))\nprint(np.sum(p1))\np1", "0.30912061651652345\n1.0\n" ] ], [ [ "> Is the sum of the page probabilities equal to 1.0 as it should be? Considering in degree of the pages, are the relative changes in the page probabilities what you would expect and why. \n> **End of exercise.**", "_____no_output_____" ], [ "> **Exercise 03-4:** You will continue with computing transitions of the Markov chain. Use the `transition` function with the normalized transition probability matrix and the page probability vector computed from the first transition as arguments. Your code must do the following: \n> 1. Compute the resulting page probabilities of the second transition.\n> 2. Compute and print the Euclidean (L2) norm of the difference between the page probabilities before and after the transition. \n> 3. Compute and print the sum of the page probabilities. \n> 4. Display the page probabilities. ", "_____no_output_____" ] ], [ [ "# Compute probabilities after second state transition\n## Put your code below\np2 = transition(M, p1)\nprint(np.linalg.norm(np.subtract(p2,p1)))\nprint(np.sum(p2))\np2", "0.09262962222518371\n1.0\n" ] ], [ [ "> Note the difference between the Euclidean norms of the differences for the first and second transition calculations. Does the change in this difference from one step to the next indicate the algorithm is converging to the steady state probabilities? \n> **End of exercise.**", "_____no_output_____" ], [ "> **Exercise 03-4:** The question now is how does this simplified version of page rank converge with more iterations? To find out, do the following: \n> 1. Create a function `pagerank1` with arguments, the normalized transition matrix, the initial page probabilities and a convergence threshold value of 0.01, which does the following: \n> - Initialize a euclidean distance norm to 1.0 and the resulting page probabilities to a vector of 0.0 values of length equal to the dimension of the transition matrix. \n> - Set a loop counter to 1. \n> - Use a 'while' loop with termination conditions the euclidean distance norm less than the threshold value AND the loop counter less than 50. In side this loop do the following: \n> 1. Update the page probabilities using the `transition` function you created. \n> 2. Compute the Euclidean norm of the difference between the initial and updated page probabilities from the transition. \n> 3. Print the value of the loop counter and the Euclidean norm value. \n> 4. Copy the updated page probability vector into the input page probability vector. \n> 5. Increment the loop counter by 1. \n> - Return the page probabilities at convergence. \n> 2. Execute your `pagerank1` function using the transition matrix and initial page probability vector. ", "_____no_output_____" ] ], [ [ "# Compute probabilities after a larger number of state transitions \ndef pagerank1(M, in_probs, threshold = 0.01): \n euclidean_dist = 1.0 \n page_probabilities = np.array([0.0]*len(M))\n i = 1 \n ## Put your code below\n while euclidean_dist > threshold and i < 50: \n page_probabilities = transition(M, in_probs)\n euclidean_dist = np.linalg.norm(np.subtract(in_probs, page_probabilities)) \n in_probs = page_probabilities\n print('Iteration ' + str(i) + ' Euclidean distance = ' + str(euclidean_dist))\n i += 1\n return page_probabilities \n\n## Execute your function\n## Put your code below\npagerank1(M,p)", "Iteration 1 Euclidean distance = 0.30912061651652345\nIteration 2 Euclidean distance = 0.09262962222518371\nIteration 3 Euclidean distance = 0.0627447198003608\nIteration 4 Euclidean distance = 0.04713034716117629\nIteration 5 Euclidean distance = 0.04044983066499079\nIteration 6 Euclidean distance = 0.034751469502374295\nIteration 7 Euclidean distance = 0.02965169022900917\nIteration 8 Euclidean distance = 0.025297173726972686\nIteration 9 Euclidean distance = 0.021602992445622173\nIteration 10 Euclidean distance = 0.018452365792341184\nIteration 11 Euclidean distance = 0.01575978617875431\nIteration 12 Euclidean distance = 0.013459509556315313\nIteration 13 Euclidean distance = 0.011495031885715244\nIteration 14 Euclidean distance = 0.00981734526591825\n" ] ], [ [ "> Answer the following questions: \n> - Does the convergence of this algorithm seem fairly rapid? \n> - Does the rank order of the computed page probabilities make sense given the directed graph of the pages? \n> **End of exercise.**", "_____no_output_____" ], [ "## A More Complicated Example \n\nYou will now work with a more complicated example The graph of 6 web pages, shown in Figure 2, is no longer complete. The out degree of page 6 is 0. A random surfer transitioning to page 6 will have no escape, a **spider trap**! \n\n<img src=\"../images/web2.png\" alt=\"Drawing\" style=\"width:500px; height:500px\"/>\n<center>Figure 3: A small set of web pages with a dead end</center>", "_____no_output_____" ], [ "> **Exercise 03-5:** You will now create both the normalized transition matrix and the initial page probability vector for the graph of Figure 3. In this exercise you will . Do the following: \n> 1. Create the association matrix and normalize it using your `norm_association` function. Name your transition matrix M_deadend. Print the result. \n> 2. Create a vector of containing the the in degree of the graph. Normalize the vector so the initial probabilities sum to 1.0. Save and print the result. ", "_____no_output_____" ] ], [ [ "## Create the Association Matrix\n## Put your code below\nA_deadend = np.array([[0,1,0,1,0,0],\n [1,0,0,0,0,0],\n [1,0,0,0,0,0],\n [1,1,1,0,1,0],\n [0,1,1,1,0,0],\n [1,0,1,0,0,0]])\n\n## Normalize the association matrix\n## Put your code below\nM_deadend = norm_association(A_deadend)\nprint(M_deadend)\n\n## Create the equal probability starting values\n## Put your code below\np_deadend = np.sum(A_deadend, axis=1)\np_deadend = np.divide(p_deadend, np.sum(p_deadend))\nprint(p_deadend)", "[[0. 0.33333333 0. 0.5 0. 0. ]\n [0.25 0. 0. 0. 0. 0. ]\n [0.25 0. 0. 0. 0. 0. ]\n [0.25 0.33333333 0.33333333 0. 1. 0. ]\n [0. 0.33333333 0.33333333 0.5 0. 0. ]\n [0.25 0. 0.33333333 0. 0. 0. ]]\n[0.15384615 0.07692308 0.07692308 0.30769231 0.23076923 0.15384615]\n" ] ], [ [ "> Examine your results. Are the 0 values for the transition probabilities of page 6 and the associated non-zero in the page probabilities consistent with the graph of these pages? \n> **End of exercise.** ", "_____no_output_____" ], [ "> **Exercises 03-6:** What happens if you apply the simplified PageRank algorithm to the pages on a graph that is not complete, like the one shown in Figure 2? To find out, execute your `pagerank1` function with arguments `M_deadend`, `p_deadend` and `threshold=0.001`. The smaller threshold value is to ensure convergence. ", "_____no_output_____" ] ], [ [ "## Put your code below\npagerank1(M_deadend,p_deadend, threshold = 0.001)", "Iteration 1 Euclidean distance = 0.11176663957796601\nIteration 2 Euclidean distance = 0.05047440944879368\nIteration 3 Euclidean distance = 0.03196212671293077\nIteration 4 Euclidean distance = 0.02896215595961246\nIteration 5 Euclidean distance = 0.02609541048864403\nIteration 6 Euclidean distance = 0.024648655232248615\nIteration 7 Euclidean distance = 0.021962192704449258\nIteration 8 Euclidean distance = 0.020672129115029844\nIteration 9 Euclidean distance = 0.01857250748188292\nIteration 10 Euclidean distance = 0.01740991694999164\nIteration 11 Euclidean distance = 0.015726745028649337\nIteration 12 Euclidean distance = 0.014693350586384997\nIteration 13 Euclidean distance = 0.013329322358288835\nIteration 14 Euclidean distance = 0.01241850218375155\nIteration 15 Euclidean distance = 0.011302786548359096\nIteration 16 Euclidean distance = 0.010506080760252699\nIteration 17 Euclidean distance = 0.0095866222704363\nIteration 18 Euclidean distance = 0.008894086069700165\nIteration 19 Euclidean distance = 0.008131821623074763\nIteration 20 Euclidean distance = 0.007532889360837013\nIteration 21 Euclidean distance = 0.006897936542135277\nIteration 22 Euclidean distance = 0.006382068086832507\nIteration 23 Euclidean distance = 0.00585117073929888\nIteration 24 Euclidean distance = 0.005408291804685317\nIteration 25 Euclidean distance = 0.0049630760097738\nIteration 26 Euclidean distance = 0.0045838426342154305\nIteration 27 Euclidean distance = 0.004209603153160863\nIteration 28 Euclidean distance = 0.0038855346900220156\nIteration 29 Euclidean distance = 0.0035703736741941167\nIteration 30 Euclidean distance = 0.003293894987984416\nIteration 31 Euclidean distance = 0.0030280984919274752\nIteration 32 Euclidean distance = 0.0027925236148161284\nIteration 33 Euclidean distance = 0.0025681014459444347\nIteration 34 Euclidean distance = 0.0023675823069946155\nIteration 35 Euclidean distance = 0.0021779220952863752\nIteration 36 Euclidean distance = 0.002007378698010694\nIteration 37 Euclidean distance = 0.0018469813098276342\nIteration 38 Euclidean distance = 0.0017020242143684337\nIteration 39 Euclidean distance = 0.001566298165075935\nIteration 40 Euclidean distance = 0.0014431501493835724\nIteration 41 Euclidean distance = 0.0013282495839958316\nIteration 42 Euclidean distance = 0.0012236705958436616\nIteration 43 Euclidean distance = 0.001126366006553914\nIteration 44 Euclidean distance = 0.001037583662304846\nIteration 45 Euclidean distance = 0.00095515761263852\n" ] ], [ [ "> Answer the following questions: \n> - Given the lower convergence threshold (factor of 10) does the convergence of the algorithm generally seem fast? \n> - Examine the page probabilities, noticing that the sum is far less than 1.0. Does this indicate that the algorithm is converging to a point where all page probabilities are 0.0? \n> **End of exercise.**", "_____no_output_____" ], [ "It is clear from the results of the foregoing exercise that the simple PageRank algorithm does not converge to a usable set of page probabilities when faced with graph that is not complete.Fortunately, there is a simple fix, add a damping term. You can think of the damping term as allowing a random surfer to make an arbitrary transition or jump with some small probability. These random jumps help the random surfer to better explore the graph and to escape from spider traps. The jump probabilities from states, $p_i$, are a function of the damping factor $d$: \n\n$$Jump\\ Probability = \\frac{(1-d)}{n}$$\n\nWhere $n$ is the dimension of the transition probability matrix. \n\nThe updated page probabilities, $p_i$, are then computed with the damped PageRank algorithm as: \n\n$$p_{i} = d * M p_{i-1} + \\frac{(1-d)}{n}$$\n\nWhere $M$ is the transition probability matrix and p are the initial page probability values. \n\n> **Exercise 03-7:** To implement the PageRank algorithm with a damping factor do the following: \n> 1. Create a `transition_damped` function with arguments, the transition probability matrix, the initial page probabilities, and the damping factor, $d=0.85$, which does the following: \n> - Compute the updated page probabilities by multiplying the inner (dot) product of the transition probability matrix by the initial page probabilities by the damping factor, `d`. Use the [numpy.multiply](https://numpy.org/doc/stable/reference/generated/numpy.multiply.html) and numpy.dot functions.\n> - Compute the jump probabilities vector of length the dimension of the transition matrix and multiply these by element wise by the page probabilities using `np.multiply`. *Note:* the jump probabilities are constant, so you can create code that only computes them once if you so choose. \n> - Return the sum of the damped page probabilities and the jump probabilities. \n> 2. Create a `pagerank_damped` function. This function is identical to the `pagerank1` function you already created except that it uses the `transiton_damped` function in place of the `transition` function. \n> 3. Call your `pagerank_damped` function using arguments of `M_deadend` and `p_deadend`. ", "_____no_output_____" ] ], [ [ "## Add a damping facgtor to the transiton \ndef transition_damped(transition_probs, probs, d=0.85):\n '''Function to compute the probabilities resulting from a \n single transition of a Markov process including a damping\n factor to deal with dead ends'''\n ## Put your code below\n out = np.multiply(np.dot(transition_probs, probs), d)\n damping = np.array([(1-d)/len(probs)]*len(probs))\n out = np.add(out,damping)\n return out\n\n## function for the PageRank algorithm using the damped transition algorithm \n## Put your code below\ndef pagerank_damped(M, in_probs, threshold = 0.01): \n euclidean_dist = 1.0 \n page_probabilities = np.array([0.0]*len(M))\n i = 1\n while euclidean_dist > threshold and i < 50: \n page_probabilities = transition_damped(M, in_probs)\n euclidean_dist = np.linalg.norm(np.subtract(in_probs, page_probabilities)) \n in_probs = page_probabilities\n print('Iteration ' + str(i) + ' Euclidean distance = ' + str(euclidean_dist))\n i += 1\n return page_probabilities \n\n## Execute your funciton\n## Put your code below\ndamped_rank = pagerank_damped(M_deadend,p_deadend)\nprint(sum(damped_rank))\ndamped_rank", "Iteration 1 Euclidean distance = 0.08901259061855184\nIteration 2 Euclidean distance = 0.037944951600823416\nIteration 3 Euclidean distance = 0.02079410296917142\nIteration 4 Euclidean distance = 0.016465473690449515\nIteration 5 Euclidean distance = 0.012780435459627378\nIteration 6 Euclidean distance = 0.010158493874458772\nIteration 7 Euclidean distance = 0.007796135866124159\n0.6847979085593676\n" ] ], [ [ "> Answer the following questions: \n> - Notice the convergence of the damped page rank algorithm. Compare this convergence to that of the undamped PageRank algorithm on the complete graph of 5 pages. Do you think this change is a result of the jumps the random surfer makes? \n> - Examine the final page probabilities. Does the rank of these page probabilities make sense given the graph of the pages in this case? \n> **End of exercise.**", "_____no_output_____" ], [ "## Hubs, Authorities, and the HITS Algorithm \n\nThe hubs and authorities model is an alternative to PageRank. Rather than using a single metric to rank the importance of web pages, the **HITS** algorithm iteratively updates the hub and authority scores for each of the pages. \n\nThe HITS algorithm updates the authority and hub scores iteratively. The authority score is sum of the hubs linked to it: \n$$𝑎= \\beta 𝐴 ℎ$$\n\nHub score is sum of the authorities it links to: \n$$ℎ= \\alpha 𝐴^𝑇 a$$\n\nThe algorithm iterates between updates to $𝑎$ and $ℎ$ until convergence. To ensure convergence, must normalize $𝑎$ and $ℎ$ to have unit Euclidean norm at each iteration. Therefore, the choice of $\\alpha$ and $\\beta$ are therefore unimportant ", "_____no_output_____" ], [ "> ** Exercise 03-8:** To understand the HITS algorithm you will now create and test code for this algorithm. Follow these steps: \n> 1. Create a function called `HITS` with arguments of the association matrix, initial hub vector, initial authority vector, and the number of iterations of the algorithm to run. This function does the following: \n> - Inside a for loop over the number of iterations: \n> 1. Updates the authority vector using the association matrix and the hub vector as argument to the `transition` function. \n> 2. Normalizes the authority vector by using `numpy.divide` with arguments of the updated authority vector and its L2 norm, computed with [numpy.linalg.norm](https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html). \n> 3. Updates the hub vector using the association matrix and the authority vector as argument to the `transition` function. \n> 4. Normalizes the hub vector by using `numpy.divide` with arguments of the updated hub vector and its L2 norm, computed with `numpy.linalg.norm`. \n> - Return the hub and authority vectors\n> 2. Initialize an initial hub and authority vector of length the dimension of the association matrix with uniformly distributed values of $\\frac{1.0}{dimension(association\\ matrix)}$. \n> 3. Execute your function using the association matrix for the 6-page network and the initial hub and authority vectors as arguments. ", "_____no_output_____" ] ], [ [ "def HITS(association, hub, authority, iters=100):\n ## Put your code below\n for _ in range(iters):\n ## Update and normalize the authorithm vector\n authority = transition(association, hub)\n authority = np.divide(authority, np.linalg.norm(authority))\n ## Update and normalize the hubieness \n hub = transition(np.transpose(association), authority)\n hub = np.divide(hub, np.linalg.norm(hub))\n return hub, authority \n\n## Compute the intial hub and authority vectors\n## Put your code below\nn_row = A_deadend.shape[0]\nauth_start = np.array([1.0/n_row]*n_row)\nhub_start = np.array([1.0/n_row]*n_row)\n\n## Execute your funciton\n## Put your code below\nHITS(A_deadend, hub_start, auth_start)", "_____no_output_____" ] ], [ [ "> Examine your results and answer the following questions:\n> - Which of the pages have the highest hub scores? Considering the graph of the pages, is this ordering consistent? \n> - Notice the last value of the hub scores. Is this value expected given the graph of the pages? \n> - Which of the pages have the highest authority. Given the in degree of the pages is this ranking consistent? \n> - Compare the ranking of the pages based on authority that found with PageRank. Are these results consistent? \n> **End of exercise.** ", "_____no_output_____" ], [ "#### Copyright 2021, Stephen F Elston. All rights reserved.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec54178b084d3fb29beadfec8971ee69ce956a60
46,857
ipynb
Jupyter Notebook
paper/Cable_equation/Paper/.ipynb_checkpoints/fit_spline-checkpoint.ipynb
remykusters/DeePyMoD
c53ce939c5e6a5f0207b042d8d42bc0197d66073
[ "MIT" ]
null
null
null
paper/Cable_equation/Paper/.ipynb_checkpoints/fit_spline-checkpoint.ipynb
remykusters/DeePyMoD
c53ce939c5e6a5f0207b042d8d42bc0197d66073
[ "MIT" ]
null
null
null
paper/Cable_equation/Paper/.ipynb_checkpoints/fit_spline-checkpoint.ipynb
remykusters/DeePyMoD
c53ce939c5e6a5f0207b042d8d42bc0197d66073
[ "MIT" ]
null
null
null
135.424855
20,616
0.873658
[ [ [ "import csv\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import interp1d\n\n# DeepMoD stuff\nfrom deepymod import DeepMoD\nfrom deepymod.model.func_approx import NN, Siren\nfrom deepymod.model.library import Library1D\nfrom deepymod.model.constraint import LeastSquares\nfrom deepymod.model.sparse_estimators import Clustering, Threshold, PDEFIND\nfrom deepymod.training import train\nfrom deepymod.analysis import load_tensorboard\nfrom derivatives import library, finite_diff, spline_diff\n\n# %% Imports\nfrom scipy.ndimage import convolve1d\nfrom scipy.interpolate import UnivariateSpline\nimport numpy as np\nfrom deepymod.data import Dataset\nfrom deepymod.data.burgers import BurgersDelta\nfrom sklearn.linear_model import LassoCV\n\nfrom deepymod.training.sparsity_scheduler import TrainTestPeriodic\nif torch.cuda.is_available():\n device = 'cuda'\nelse:\n device = 'cpu'\n# Settings for reproducibility\nnp.random.seed(42)\ntorch.manual_seed(0)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False", "_____no_output_____" ], [ "# %% Functions\ndef finite_diff(y, x, order, axis=0, bc_mode='reflect'):\n ''' Calculates finite difference of order n over axis. \n Uses 2nd order accurate central difference.'''\n step_size = np.diff(x)[0] # assumes step size is constant\n if order == 1:\n stencil = np.array([1/2, 0, -1/2])\n elif order == 2:\n stencil = np.array([1, -2, 1])\n elif order == 3:\n stencil = np.array([1/2, -1, 0, 1, -1/2])\n else:\n raise NotImplementedError\n\n deriv = convolve1d(y, stencil, axis=axis, mode=bc_mode) / step_size**order\n return deriv\n\n\ndef spline_diff(y, x, order, **spline_kwargs):\n \"\"\"Fits spline to data and returns derivatives of given order. order=0 corresponds to data.\n Good defaults for spline, k=4, s=1e-2/0.0 if not smooth\"\"\"\n spline = UnivariateSpline(x, y, **spline_kwargs)\n return spline(x, nu=order)\n\n\ndef library(y, x, t, poly_order=2, deriv_order=3, deriv_kind='spline', **deriv_kwargs):\n ''' Returns time deriv and library of given data. x and t are vectors, first axis of y should be time.'''\n if deriv_kind == 'spline':\n # Calculating polynomials\n u = np.stack([spline_diff(y[frame, :], x, order=0, **deriv_kwargs) for frame in np.arange(t.size)], axis=0).reshape(-1, 1) # if we do a spline on noisy data, we also get a 'denoised' data\n u = np.concatenate([u**order for order in np.arange(poly_order+1)], axis=1) # getting polynomials including offset\n\n # Calculating derivatives\n du = [np.ones((u.shape[0], 1))]\n for order in np.arange(1, deriv_order+1):\n du.append(np.stack([spline_diff(y[frame, :], x, order=order, **deriv_kwargs) for frame in np.arange(t.size)], axis=0).reshape(-1, 1)) \n du = np.concatenate(du, axis=1)\n\n # Calculating theta\n theta = (u[:, :, None] @ du[:, None, :]).reshape(-1, u.shape[1] * du.shape[1])\n \n elif deriv_kind == 'fd':\n # Calculating polynomials\n u = np.concatenate([(y**order).reshape(-1, 1) for order in np.arange(poly_order+1)], axis=1)\n\n # Getting derivatives\n du = np.concatenate([(finite_diff(y, x, order=order, axis=1, **deriv_kwargs)).reshape(-1, 1) for order in np.arange(1, deriv_order+1)], axis=1)\n du = np.concatenate((np.ones((du.shape[0], 1)), du), axis=1)\n\n # Calculating theta\n theta = (u[:, :, None] @ du[:, None, :]).reshape(-1, u.shape[1] * du.shape[1])\n\n else:\n raise NotImplementedError\n # Calculating time diff by finite diff\n dt = finite_diff(u[:, 1].reshape(t.size, x.size), t, order=1, axis=0).reshape(-1, 1)\n return dt, theta\n\n", "_____no_output_____" ], [ "# Loading and scaling the data\n\nlower_lim, upper_lim = 540, 3000 \ndelta_V = np.load('11_elements.npy')\ny = delta_V[lower_lim:upper_lim,:]\ny = y# /np.max(y)\nt = np.linspace(0, 1, y.shape[0])\nx = np.linspace(0, 1, y.shape[1])", "_____no_output_____" ] ], [ [ "y has time on the first axis and space on the second ", "_____no_output_____" ] ], [ [ "y.shape", "_____no_output_____" ], [ "plt.imshow(y,aspect=0.001)", "_____no_output_____" ], [ "threshold = 0.1\ndt, theta = library(y, x, t, deriv_kind='spline',poly_order=1,deriv_order=2, s=0.00, k=3)\nreg = LassoCV(fit_intercept=False, cv=10)\nxi = reg.fit(theta, dt).coef_[:, None].flatten()\nxi[np.abs(xi) < threshold] = 0\nprint(xi)", "[ 0. -1.56275251 0.24724303 -3.01560819 0. 0. ]\n" ], [ "noise = 0.02\nA = 1\nv = 0.25\n\nruns = 1\ndataset = Dataset(BurgersDelta, A=A, v=v)\nn_x, n_t = 100, 50 \nx = np.linspace(-2, 2, n_x)\nt = np.linspace(0.1, 1.1, n_t) \nt_grid, x_grid = np.meshgrid(t, x, indexing='ij')\nX, y = dataset.create_dataset(x_grid.reshape(-1, 1), t_grid.reshape(-1, 1), n_samples=0, noise=noise, random=False, normalize=False)\ny= y.reshape(t.shape[0],x.shape[0]).numpy()", "_____no_output_____" ] ], [ [ "y has time on the first axis and space on the second ", "_____no_output_____" ] ], [ [ "y.shape", "_____no_output_____" ], [ "plt.imshow(y,aspect=1)", "_____no_output_____" ], [ "threshold = 0.1\ndt, theta = library(y, x, t, deriv_kind='spline',poly_order=1,deriv_order=2, s=0.00, k=3)\nreg = LassoCV(fit_intercept=False, cv=10)\nxi = reg.fit(theta, dt).coef_[:, None].flatten()\nxi[np.abs(xi) < threshold] = 0\nprint(xi)", "[ 0.2941514 -0.38277507 0. -1.16642921 -0.24891237 0. ]\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ec541e33fe95e0a88f088c16f8be55445e13213c
141,056
ipynb
Jupyter Notebook
code/ch16/ch16.ipynb
rohinsung/python1
b1916dd1ccd7fe166959bfc14cca642a12fb243c
[ "MIT" ]
null
null
null
code/ch16/ch16.ipynb
rohinsung/python1
b1916dd1ccd7fe166959bfc14cca642a12fb243c
[ "MIT" ]
null
null
null
code/ch16/ch16.ipynb
rohinsung/python1
b1916dd1ccd7fe166959bfc14cca642a12fb243c
[ "MIT" ]
null
null
null
44.135169
17,900
0.607638
[ [ [ "# 16장. 순환 신경망으로 시퀀스 데이터 모델링", "_____no_output_____" ], [ "**아래 링크를 통해 이 노트북을 주피터 노트북 뷰어(nbviewer.jupyter.org)로 보거나 구글 코랩(colab.research.google.com)에서 실행할 수 있습니다.**\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://nbviewer.jupyter.org/github/rickiepark/python-machine-learning-book-2nd-edition/blob/master/code/ch16/ch16.ipynb\"><img src=\"https://jupyter.org/assets/main-logo.svg\" width=\"28\" />주피터 노트북 뷰어로 보기</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/rickiepark/python-machine-learning-book-2nd-edition/blob/master/code/ch16/ch16.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />구글 코랩(Colab)에서 실행하기</a>\n </td>\n</table>", "_____no_output_____" ], [ "`watermark`는 주피터 노트북에 사용하는 파이썬 패키지를 출력하기 위한 유틸리티입니다. `watermark` 패키지를 설치하려면 다음 셀의 주석을 제거한 뒤 실행하세요.", "_____no_output_____" ] ], [ [ "#!pip install watermark", "_____no_output_____" ], [ "%load_ext watermark\n%watermark -u -d -v -p numpy,scipy,pyprind,tensorflow", "last updated: 2019-12-29 \n\nCPython 3.7.3\nIPython 7.5.0\n\nnumpy 1.16.3\nscipy 1.4.1\npyprind 2.11.2\ntensorflow 2.1.0-rc2\n" ] ], [ [ "**이 노트북을 실행하려면 텐서플로 2.0.0-alpha0 버전 이상이 필요합니다. 이전 버전의 텐서플로가 설치되어 있다면 다음 셀의 주석을 제거한 뒤 실행하세요.**", "_____no_output_____" ] ], [ [ "#!pip install tensorflow==2.0.0", "_____no_output_____" ] ], [ [ "**코랩을 사용할 때는 다음 셀의 주석을 제거하고 GPU 버전의 텐서플로 2.0.0 버전을 설치하세요.**", "_____no_output_____" ] ], [ [ "#!pip install tensorflow-gpu==2.0.0", "_____no_output_____" ] ], [ [ "**코랩을 사용할 때는 다음 셀의 주석을 제거하고 실행하세요.**", "_____no_output_____" ] ], [ [ "#!wget https://github.com/rickiepark/python-machine-learning-book-2nd-edition/raw/master/code/ch16/movie_data.csv.gz", "_____no_output_____" ], [ "import gzip\n\n\nwith gzip.open('movie_data.csv.gz') as f_in, open('movie_data.csv', 'wb') as f_out:\n f_out.writelines(f_in)", "_____no_output_____" ] ], [ [ "# 텐서플로의 케라스 API로 시퀀스 모델링을 위한 다층 RNN 구현하기", "_____no_output_____" ], [ "## 첫 번째 프로젝트 - 다층 RNN으로 IMDb 영화 리뷰의 감성 분석 수행하기", "_____no_output_____" ], [ "### 데이터 준비", "_____no_output_____" ], [ "`pyprind`는 주피터 노트북에서 진행바를 출력하기 위한 유틸리티입니다. `pyprind` 패키지를 설치하려면 다음 셀의 주석을 제거한 뒤 실행하세요.", "_____no_output_____" ] ], [ [ "#!pip install pyprind", "_____no_output_____" ], [ "import pyprind\nimport pandas as pd\nfrom string import punctuation\nimport re\nimport numpy as np\n\n\ndf = pd.read_csv('movie_data.csv', encoding='utf-8')\nprint(df.head(3))", " review sentiment\n0 In 1974, the teenager Martha Moxley (Maggie Gr... 1\n1 OK... so... I really like Kris Kristofferson a... 0\n2 ***SPOILER*** Do not read this, if you think a... 0\n" ], [ "## 데이터 전처리:\n## 단어를 나누고 등장 횟수를 카운트합니다.\n\nfrom collections import Counter\n\n\ncounts = Counter()\npbar = pyprind.ProgBar(len(df['review']),\n title='단어의 등장 횟수를 카운트합니다.')\nfor i,review in enumerate(df['review']):\n text = ''.join([c if c not in punctuation else ' '+c+' ' \\\n for c in review]).lower()\n df.loc[i,'review'] = text\n pbar.update()\n counts.update(text.split())", "단어의 등장 횟수를 카운트합니다.\n0% [##############################] 100% | ETA: 00:00:00\nTotal time elapsed: 00:06:32\n" ], [ "## 고유한 각 단어를 정수로 매핑하는\n## 딕셔너리를 만듭니다.\n\nword_counts = sorted(counts, key=counts.get, reverse=True)\nprint(word_counts[:5])\nword_to_int = {word: ii for ii, word in enumerate(word_counts, 1)}\n\n\nmapped_reviews = []\npbar = pyprind.ProgBar(len(df['review']),\n title='리뷰를 정수로 매핑합니다.')\nfor review in df['review']:\n mapped_reviews.append([word_to_int[word] for word in review.split()])\n pbar.update()", "리뷰를 정수로 매핑합니다.\n" ], [ "## 동일 길이의 시퀀스를 만듭니다.\n## 시퀀스 길이가 200보다 작으면 왼쪽에 0이 패딩됩니다.\n## 시퀀스 길이가 200보다 크면 마지막 200개 원소만 사용합니다.\n\nsequence_length = 200 ## (RNN 공식에 있는 T 값 입니다)\nsequences = np.zeros((len(mapped_reviews), sequence_length), dtype=int)\nfor i, row in enumerate(mapped_reviews):\n review_arr = np.array(row)\n sequences[i, -len(row):] = review_arr[-sequence_length:]\n\nX_train = sequences[:37500, :]\ny_train = df.loc[:37499, 'sentiment'].values\nX_test = sequences[37500:, :]\ny_test = df.loc[37500:, 'sentiment'].values", "_____no_output_____" ], [ "print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)", "(37500, 200) (37500,) (12500, 200) (12500,)\n" ], [ "n_words = len(word_to_int) + 1\nprint(n_words)", "102967\n" ] ], [ [ "### 임베딩", "_____no_output_____" ] ], [ [ "from tensorflow.keras import models, layers", "_____no_output_____" ], [ "model = models.Sequential()", "_____no_output_____" ], [ "model.add(layers.Embedding(n_words, 200, \n embeddings_regularizer='l2'))", "_____no_output_____" ], [ "model.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding (Embedding) (None, None, 200) 20593400 \n=================================================================\nTotal params: 20,593,400\nTrainable params: 20,593,400\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### RNN 모델 만들기", "_____no_output_____" ] ], [ [ "model.add(layers.LSTM(16))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(1, activation='sigmoid'))", "_____no_output_____" ], [ "model.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding (Embedding) (None, None, 200) 20593400 \n_________________________________________________________________\nlstm (LSTM) (None, 16) 13888 \n_________________________________________________________________\nflatten (Flatten) (None, 16) 0 \n_________________________________________________________________\ndense (Dense) (None, 1) 17 \n=================================================================\nTotal params: 20,607,305\nTrainable params: 20,607,305\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### 감성 분석 RNN 모델 훈련하기", "_____no_output_____" ] ], [ [ "model.compile(loss='binary_crossentropy', \n optimizer='adam', metrics=['acc'])", "_____no_output_____" ], [ "import time\nfrom tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard\n\ncallback_list = [ModelCheckpoint(filepath='sentiment_rnn_checkpoint.h5',\n monitor='val_loss', \n save_best_only=True), \n TensorBoard(log_dir=\"sentiment_rnn_logs/{}\".format(\n time.asctime()))]", "_____no_output_____" ], [ "history = model.fit(X_train, y_train, \n batch_size=64, epochs=10, \n validation_split=0.3, callbacks=callback_list)", "Train on 26250 samples, validate on 11250 samples\nEpoch 1/10\n" ], [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "epochs = np.arange(1, 11)\nplt.plot(epochs, history.history['loss'])\nplt.plot(epochs, history.history['val_loss'])\nplt.xlabel('epochs')\nplt.ylabel('loss')\nplt.show()", "_____no_output_____" ], [ "epochs = np.arange(1, 11)\nplt.plot(epochs, history.history['acc'])\nplt.plot(epochs, history.history['val_acc'])\nplt.xlabel('epochs')\nplt.ylabel('loss')\nplt.show()", "_____no_output_____" ] ], [ [ "### 감성 분석 RNN 모델 평가하기", "_____no_output_____" ] ], [ [ "model.load_weights('sentiment_rnn_checkpoint.h5')\nmodel.evaluate(X_test, y_test)", "12500/12500 [==============================] - 21s 2ms/sample - loss: 0.4527 - acc: 0.87300s - loss: 0.4534 - acc: 0.\n" ], [ "model.predict_proba(X_test[:10])", "_____no_output_____" ], [ "model.predict_classes(X_test[:10])", "_____no_output_____" ] ], [ [ "## 두 번째 프로젝트 – 텐서플로로 글자 단위 언어 모델 구현하기", "_____no_output_____" ], [ "### 데이터 전처리", "_____no_output_____" ], [ "**코랩을 사용할 때는 다음 셀의 주석을 제거하고 실행하세요.**", "_____no_output_____" ] ], [ [ "#!wget https://github.com/rickiepark/python-machine-learning-book-2nd-edition/raw/master/code/ch16/pg2265.txt", "_____no_output_____" ], [ "import numpy as np\n\n\n## 텍스트를 읽고 처리합니다.\nwith open('pg2265.txt', 'r', encoding='utf-8') as f: \n text=f.read()\n\ntext = text[15858:]\nchars = set(text)\nchar2int = {ch:i for i,ch in enumerate(chars)}\nint2char = dict(enumerate(chars))\ntext_ints = np.array([char2int[ch] for ch in text], \n dtype=np.int32)", "_____no_output_____" ], [ "len(text)", "_____no_output_____" ], [ "len(chars)", "_____no_output_____" ], [ "def reshape_data(sequence, batch_size, num_steps):\n mini_batch_length = batch_size * num_steps\n num_batches = int(len(sequence) / mini_batch_length)\n if num_batches*mini_batch_length + 1 > len(sequence):\n num_batches = num_batches - 1\n ## 전체 배치에 포함되지 않는 시퀀스 끝부분은 삭제합니다.\n x = sequence[0 : num_batches*mini_batch_length]\n y = sequence[1 : num_batches*mini_batch_length + 1]\n ## x와 y를 시퀀스 배치의 리스트로 나눕니다.\n x_batch_splits = np.split(x, batch_size)\n y_batch_splits = np.split(y, batch_size)\n ## 합쳐진 배치 크기는\n ## batch_size x mini_batch_length가 됩니다.\n x = np.stack(x_batch_splits)\n y = np.stack(y_batch_splits)\n \n return x, y", "_____no_output_____" ], [ "## 테스트\ntrain_x, train_y = reshape_data(text_ints, 64, 10)\nprint(train_x.shape)\nprint(train_x[0, :10])\nprint(train_y[0, :10])\nprint(''.join(int2char[i] for i in train_x[0, :10]))\nprint(''.join(int2char[i] for i in train_y[0, :10]))", "(64, 2540)\n[44 52 40 15 44 63 35 17 40 16]\n[52 40 15 44 63 35 17 40 16 45]\nThe Traged\nhe Tragedi\n" ], [ "def create_batch_generator(data_x, data_y, num_steps):\n batch_size, tot_batch_length = data_x.shape[0:2] \n num_batches = int(tot_batch_length/num_steps)\n for b in range(num_batches):\n yield (data_x[:, b*num_steps: (b+1)*num_steps], \n data_y[:, b*num_steps: (b+1)*num_steps])", "_____no_output_____" ], [ "bgen = create_batch_generator(train_x[:,:100], train_y[:,:100], 15)\nfor x, y in bgen:\n print(x.shape, y.shape, end=' ')\n print(''.join(int2char[i] for i in x[0,:]).replace('\\n', '*'), ' ',\n ''.join(int2char[i] for i in y[0,:]).replace('\\n', '*'))", "(64, 15) (64, 15) The Tragedie of he Tragedie of \n(64, 15) (64, 15) Hamlet**Actus Hamlet**Actus P\n(64, 15) (64, 15) Primus. Scoena rimus. Scoena P\n(64, 15) (64, 15) Prima.**Enter B rima.**Enter Ba\n(64, 15) (64, 15) arnardo and Fra rnardo and Fran\n(64, 15) (64, 15) ncisco two Cent cisco two Centi\n" ], [ "batch_size = 64\nnum_steps = 100 \ntrain_x, train_y = reshape_data(text_ints, batch_size, num_steps)\nprint(train_x.shape, train_y.shape)", "(64, 2500) (64, 2500)\n" ], [ "from tensorflow.keras.utils import to_categorical\n\ntrain_encoded_x = to_categorical(train_x)\ntrain_encoded_y = to_categorical(train_y)\nprint(train_encoded_x.shape, train_encoded_y.shape)", "(64, 2500, 65) (64, 2500, 65)\n" ], [ "print(np.max(train_x), np.max(train_y))", "64 64\n" ] ], [ [ "### 글자 단위 RNN 모델 만들기", "_____no_output_____" ] ], [ [ "char_model = models.Sequential()", "_____no_output_____" ], [ "num_classes = len(chars)\n\nchar_model.add(layers.LSTM(128, input_shape=(None, num_classes), \n return_sequences=True))\nchar_model.add(layers.TimeDistributed(layers.Dense(num_classes, \n activation='softmax')))", "_____no_output_____" ], [ "char_model.summary()", "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nlstm_1 (LSTM) (None, None, 128) 99328 \n_________________________________________________________________\ntime_distributed (TimeDistri (None, None, 65) 8385 \n=================================================================\nTotal params: 107,713\nTrainable params: 107,713\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### 글자 단위 RNN 모델 훈련하기", "_____no_output_____" ] ], [ [ "from tensorflow.keras.optimizers import Adam\n\nadam = Adam(clipnorm=5.0)", "_____no_output_____" ], [ "char_model.compile(loss='categorical_crossentropy', optimizer=adam)", "_____no_output_____" ], [ "callback_list = [ModelCheckpoint(filepath='char_rnn_checkpoint.h5')] ", "_____no_output_____" ], [ "for i in range(500):\n bgen = create_batch_generator(train_encoded_x, \n train_encoded_y, num_steps)\n char_model.fit_generator(bgen, steps_per_epoch=25, epochs=1, \n callbacks=callback_list, verbose=0)", "WARNING: Logging before flag parsing goes to stderr.\nW1229 18:05:35.765786 140646600587072 deprecation.py:323] From <ipython-input-46-062c8924be64>:5: Model.fit_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use Model.fit, which supports generators.\nW1229 18:05:35.769821 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:38.338448 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:40.038974 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:41.745880 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:43.434699 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:45.134787 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:46.804035 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:48.495185 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:50.217340 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:51.914597 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:53.627550 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:55.355918 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:57.062990 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:05:58.779914 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:00.480176 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:02.190725 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:03.890574 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:05.582960 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:07.276114 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:09.117440 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:10.809123 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:12.516601 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:14.198718 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:15.905500 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:17.859015 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:19.566459 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:21.282801 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:22.991777 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:24.681223 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:26.378648 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:28.070212 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:29.762652 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:31.443903 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:33.137063 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:34.834873 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:36.537410 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:38.225658 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:39.916959 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:41.603821 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:43.297357 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:44.993569 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:46.682159 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:48.367245 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:50.060869 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:51.761508 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:53.452468 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:55.142110 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:56.842447 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:06:58.543332 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:00.232861 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:01.921278 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:03.614964 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:05.304825 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:06.990450 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:08.825974 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:10.505884 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:12.206003 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:13.915230 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:15.600847 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:17.341429 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:19.052709 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:20.755462 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:22.446350 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\nW1229 18:07:24.126732 140646600587072 data_adapter.py:1091] sample_weight modes were coerced from\n ...\n to \n ['...']\n" ] ], [ [ "### 글자 단위 RNN 모델로 텍스트 생성하기", "_____no_output_____" ] ], [ [ "np.random.seed(42)\n\ndef get_top_char(probas, char_size, top_n=5):\n p = np.squeeze(probas)\n p[np.argsort(p)[:-top_n]] = 0.0\n p = p / np.sum(p)\n ch_id = np.random.choice(char_size, 1, p=p)[0]\n return ch_id", "_____no_output_____" ], [ "seed_text = \"The \"\nfor ch in seed_text:\n num = [char2int[ch]]\n onehot = to_categorical(num, num_classes=65)\n onehot = np.expand_dims(onehot, axis=0)\n probas = char_model.predict(onehot)\nnum = get_top_char(probas, len(chars))\nseed_text += int2char[num]", "_____no_output_____" ], [ "for i in range(500):\n onehot = to_categorical([num], num_classes=65)\n onehot = np.expand_dims(onehot, axis=0)\n probas = char_model.predict(onehot)\n num = get_top_char(probas, len(chars))\n seed_text += int2char[num]\nprint(seed_text)", "The wheno the th w win in wes auld tst inotor ind wher. to we t wingort thes w thand ithe ithe, ano indinde w thert this wertot w whaus ts an ie wh ar it ingus t w itot ingeronor. is anor. weshis, tho illdes indesthe wane thiend inou thinor tst win arenourothes, wisthe,\nThis w and wille as illd its windo the witharthe weso the at athe wiere ildus induer. il toue ither ishe t thestor t t tonerend withil athanous iles t wishe therotono ithin t tororerots itendillis in athor.\n\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", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ec5429a0320e76b9ab73dba0daf6e2e3c2d237ce
69,309
ipynb
Jupyter Notebook
tweet_similarity_ranking.ipynb
soumyaa1804/twitter_data_analysis
e5ee2a1dc5c6685e198132777f3bd276432a3759
[ "MIT" ]
null
null
null
tweet_similarity_ranking.ipynb
soumyaa1804/twitter_data_analysis
e5ee2a1dc5c6685e198132777f3bd276432a3759
[ "MIT" ]
null
null
null
tweet_similarity_ranking.ipynb
soumyaa1804/twitter_data_analysis
e5ee2a1dc5c6685e198132777f3bd276432a3759
[ "MIT" ]
null
null
null
50.296807
17,672
0.677199
[ [ [ "# Tweet similarity ranking\n\n### Problem:\n\n1: Use Twitter API to collect 1000 tweets in which keyword ‘narendra modi’ appears, save the collected tweets in nm.txt \n\n2: Convert the collected tweets into BoW vectors and find cosine similarity of a pair of tweets and print the top-10 most similar tweet pairs, print these pairs\n\n3: Do the same using TF-IDF vectors\n", "_____no_output_____" ], [ "## Collect and store the data in nm.csv", "_____no_output_____" ] ], [ [ "import tweepy\nimport pandas as pd\nimport numpy as np\nimport csv", "_____no_output_____" ], [ "from secrets import *", "_____no_output_____" ], [ "# Connect twitter API\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, wait_on_rate_limit=True)", "_____no_output_____" ], [ "data_path = './data/'", "_____no_output_____" ], [ "search_words = \"narendra modi\"\nno_of_tweets = 1000", "_____no_output_____" ], [ "# Ignoring retweets to avoid duplicacy\n\nnew_search = \"narendra modi -filter:retweets\"", "_____no_output_____" ], [ "tweets = tweepy.Cursor(api.search,\n q=new_search).items(no_of_tweets)", "_____no_output_____" ], [ "# Adding tweet text to nm.txt\ndef text_to_file(tweets, file_name):\n with open(data_path+file_name, \"w\") as f:\n for tweet in tweets:\n f.write(tweet.text + '\\n\\n ----------------------\\n')", "_____no_output_____" ], [ "# Convert tweets data into dataframe\n\ntext_details = [[tweet.id, tweet.created_at, tweet.user.screen_name, tweet.text] for tweet in tweets]", "_____no_output_____" ], [ "# Save tweets to csv\n\nwith open(data_path + \"nm2.csv\", 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['Tweet_id', 'Created At', 'Created By', 'Tweet Text'])\n writer.writerows(text_details)\npass", "_____no_output_____" ] ], [ [ "## Process the stored data\n\n### Convert the collected tweets into BoW vectors and find cosine similarity of a pair of tweets and print the top-10 most similar tweet pairs, print these pairs", "_____no_output_____" ] ], [ [ "# Read data from nm.csv\n\ndf = pd.read_csv(data_path+\"nm2.csv\")", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "texts = df[\"text\"]\ntexts[0]", "_____no_output_____" ], [ "# Add text to python list\n\ntext_list = []\nfor text in texts:\n text_list.append(text)", "_____no_output_____" ], [ "len(text_list)", "_____no_output_____" ], [ "# tfidf vectorize\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\ntfidf_vectorizer = TfidfVectorizer()", "_____no_output_____" ], [ "T = tfidf_vectorizer.fit_transform(text_list)", "_____no_output_____" ], [ "len(tfidf_vectorizer.get_feature_names())", "_____no_output_____" ], [ "T.shape", "_____no_output_____" ], [ "T = T.toarray()", "_____no_output_____" ], [ "T", "_____no_output_____" ], [ "len(T)", "_____no_output_____" ], [ "len(T[0])", "_____no_output_____" ], [ "print(T[0])", "[0. 0. 0. ... 0. 0. 0.]\n" ], [ "T_df = pd.DataFrame(T, columns = tfidf_vectorizer.get_feature_names()) ", "_____no_output_____" ], [ "T_df.head()", "_____no_output_____" ], [ "# Cosine similarity\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ntweet_similarity = []\n\nfor i in range(len(T)):\n tweet_similarity_row = []\n for j in range(len(T)):\n a = np.reshape(T[i], (1, T[i].size))\n b = np.reshape(T[j], (1, T[j].size))\n c = cosine_similarity(a,b)\n tweet_similarity_row.append(c[0][0])\n tweet_similarity.append(tweet_similarity_row)\n ", "_____no_output_____" ], [ "len(tweet_similarity)", "_____no_output_____" ], [ "len(tweet_similarity[0])", "_____no_output_____" ], [ "# Find pair which are most similar (max value in tweet_similarity)\n\nrow_col_similarity = []\n\nfor i in range(len(T)):\n for j in range(i, len(T)):\n if i != j:\n row_col_similarity.append([i, j, tweet_similarity[i][j]])", "_____no_output_____" ], [ "len(row_col_similarity)", "_____no_output_____" ], [ "len(row_col_similarity[0])", "_____no_output_____" ], [ "# Create the pandas DataFrame \nsimilarity_df = pd.DataFrame(row_col_similarity, columns = ['Tweet1 index', 'Tweet2 index', 'cosine similarity']) ", "_____no_output_____" ], [ "# Sort in dec order of cosine similarity\n\ntop_ten_df = similarity_df.nlargest(10, 'cosine similarity')", "_____no_output_____" ], [ "top_ten_df.reset_index(drop=True)", "_____no_output_____" ], [ "df = pd.read_csv(data_path+\"nm.csv\")", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "## Similar tweets pair", "_____no_output_____" ] ], [ [ "for i in range(len(top_ten_df)):\n print(\"\\nTweet pair \", i+1)\n t1 = top_ten_df.iloc[i, 0]\n t2 = top_ten_df.iloc[i, 1] \n print(\"Tweet1\")\n print(df.iloc[t1, 3])\n print(\"Tweet2\")\n print(df.iloc[t2, 3])\n print(\"************************************************************\")", "\nTweet pair 1\nTweet1\nsarahtweets8t\nTweet2\nsarahtweets8t\n************************************************************\n\nTweet pair 2\nTweet1\nPatelGiraK2\nTweet2\nSunilGu96576773\n************************************************************\n\nTweet pair 3\nTweet1\nDimitriCruz5\nTweet2\nPTI_News\n************************************************************\n\nTweet pair 4\nTweet1\nblan_sera\nTweet2\nblan_sera\n************************************************************\n\nTweet pair 5\nTweet1\nblan_sera\nTweet2\nblan_sera\n************************************************************\n\nTweet pair 6\nTweet1\nblan_sera\nTweet2\nblan_sera\n************************************************************\n\nTweet pair 7\nTweet1\nblan_sera\nTweet2\nblan_sera\n************************************************************\n\nTweet pair 8\nTweet1\nblan_sera\nTweet2\nblan_sera\n************************************************************\n\nTweet pair 9\nTweet1\nblan_sera\nTweet2\nblan_sera\n************************************************************\n\nTweet pair 10\nTweet1\nblan_sera\nTweet2\nblan_sera\n************************************************************\n" ] ], [ [ " ### The could have been better if duplicate text of tweets were dropped", "_____no_output_____" ] ], [ [ "!pip install networkx", "Defaulting to user installation because normal site-packages is not writeable\nCollecting networkx\n Downloading networkx-2.4-py3-none-any.whl (1.6 MB)\n\u001b[K |████████████████████████████████| 1.6 MB 33 kB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: decorator>=4.3.0 in /home/soumya/.local/lib/python3.5/site-packages (from networkx) (4.4.2)\nInstalling collected packages: networkx\nSuccessfully installed networkx-2.4\n\u001b[33mWARNING: You are using pip version 20.1.1; however, version 20.2.4 is available.\nYou should consider upgrading via the '/usr/bin/python3 -m pip install --upgrade pip' command.\u001b[0m\n" ], [ "import networkx as nx \n# importing matplotlib.pyplot \nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "g = nx.DiGraph()", "_____no_output_____" ], [ "g.add_edge(\"soumya\", \"tanu\")\ng.add_edge(\"soumya\", \"vaibhav\")\ng.add_edge(\"vaibhav\", \"tanu\")\ng.add_edge(\"vaibhav\", \"tanu\")\nnx.draw(g, with_labels = True)", "_____no_output_____" ], [ "g = nx.DiGraph()\ns = [1, 8]\nff = []\na = [1, 2, 3]\nb = [5, 6, 7]\nff = [a, b]\nff\ngg = []\ngg.append(ff)\n\nd = [8, 4, 3]\ne = [4, 8, 5]\nk = [d, e]\ngg.append(k)\nuser_list = gg\nunique_creators = s\nfor i in range(len(user_list)):\n for j in range(len(user_list[i][0])):\n g.add_edge(user_list[i][0][j], unique_creators[i])\n \n for k in range(len(user_list[i][1])):\n g.add_edge(unique_creators[i], user_list[i][1][k])\n \nnx.draw(g, with_labels = True)", "_____no_output_____" ] ], [ [ "Find popular users in this G based on\n\nDegree centrality\n\nBetweeness centrality\n\nCloseness centrality", "_____no_output_____" ] ], [ [ "nx.degree_centrality(g)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
ec54326064d03b03922d91cc3996da2b5630cc01
830,891
ipynb
Jupyter Notebook
Starbucks_Capstone.ipynb
prabowst/udacity-dsnd-capstone-starbucks
a0150094792a8e630c4b4207db608a2f33904912
[ "FTL", "CNRI-Python", "RSA-MD" ]
2
2020-09-25T10:31:58.000Z
2020-10-11T20:30:37.000Z
Starbucks_Capstone.ipynb
prabowst/udacity-ds-nanodegree-capstone
a0150094792a8e630c4b4207db608a2f33904912
[ "FTL", "CNRI-Python", "RSA-MD" ]
null
null
null
Starbucks_Capstone.ipynb
prabowst/udacity-ds-nanodegree-capstone
a0150094792a8e630c4b4207db608a2f33904912
[ "FTL", "CNRI-Python", "RSA-MD" ]
1
2020-05-19T05:51:12.000Z
2020-05-19T05:51:12.000Z
196.428132
166,260
0.862203
[ [ [ "# Starbucks Capstone Challenge\n\n### Introduction\n\nThis data set contains simulated data that mimics customer behavior on the Starbucks rewards mobile app. Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisement for a drink or an actual offer such as a discount or BOGO (buy one get one free). Some users might not receive any offer during certain weeks. \n\nNot all users receive the same offer, and that is the challenge to solve with this data set.\n\nYour task is to combine transaction, demographic and offer data to determine which demographic groups respond best to which offer type. This data set is a simplified version of the real Starbucks app because the underlying simulator only has one product whereas Starbucks actually sells dozens of products.\n\nEvery offer has a validity period before the offer expires. As an example, a BOGO offer might be valid for only 5 days. You'll see in the data set that informational offers have a validity period even though these ads are merely providing information about a product; for example, if an informational offer has 7 days of validity, you can assume the customer is feeling the influence of the offer for 7 days after receiving the advertisement.\n\nYou'll be given transactional data showing user purchases made on the app including the timestamp of purchase and the amount of money spent on a purchase. This transactional data also has a record for each offer that a user receives as well as a record for when a user actually views the offer. There are also records for when a user completes an offer. \n\nKeep in mind as well that someone using the app might make a purchase through the app without having received an offer or seen an offer.\n\n### Example\n\nTo give an example, a user could receive a discount offer buy 10 dollars get 2 off on Monday. The offer is valid for 10 days from receipt. If the customer accumulates at least 10 dollars in purchases during the validity period, the customer completes the offer.\n\nHowever, there are a few things to watch out for in this data set. Customers do not opt into the offers that they receive; in other words, a user can receive an offer, never actually view the offer, and still complete the offer. For example, a user might receive the \"buy 10 dollars get 2 dollars off offer\", but the user never opens the offer during the 10 day validity period. The customer spends 15 dollars during those ten days. There will be an offer completion record in the data set; however, the customer was not influenced by the offer because the customer never viewed the offer.\n\n### Cleaning\n\nThis makes data cleaning especially important and tricky.\n\nYou'll also want to take into account that some demographic groups will make purchases even if they don't receive an offer. From a business perspective, if a customer is going to make a 10 dollar purchase without an offer anyway, you wouldn't want to send a buy 10 dollars get 2 dollars off offer. You'll want to try to assess what a certain demographic group will buy when not receiving any offers.\n\n### Final Advice\n\nBecause this is a capstone project, you are free to analyze the data any way you see fit. For example, you could build a machine learning model that predicts how much someone will spend based on demographics and offer type. Or you could build a model that predicts whether or not someone will respond to an offer. Or, you don't need to build a machine learning model at all. You could develop a set of heuristics that determine what offer you should send to each customer (i.e., 75 percent of women customers who were 35 years old responded to offer A vs 40 percent from the same demographic to offer B, so send offer A).", "_____no_output_____" ], [ "# Data Sets\n\nThe data is contained in three files:\n\n* portfolio.json - containing offer ids and meta data about each offer (duration, type, etc.)\n* profile.json - demographic data for each customer\n* transcript.json - records for transactions, offers received, offers viewed, and offers completed\n\nHere is the schema and explanation of each variable in the files:\n\n**portfolio.json**\n* id (string) - offer id\n* offer_type (string) - type of offer ie BOGO, discount, informational\n* difficulty (int) - minimum required spend to complete an offer\n* reward (int) - reward given for completing an offer\n* duration (int) - time for offer to be open, in days\n* channels (list of strings)\n\n**profile.json**\n* age (int) - age of the customer \n* became_member_on (int) - date when customer created an app account\n* gender (str) - gender of the customer (note some entries contain 'O' for other rather than M or F)\n* id (str) - customer id\n* income (float) - customer's income\n\n**transcript.json**\n* event (str) - record description (ie transaction, offer received, offer viewed, etc.)\n* person (str) - customer id\n* time (int) - time in hours since start of test. The data begins at time t=0\n* value - (dict of strings) - either an offer id or transaction amount depending on the record", "_____no_output_____" ], [ "# 1. Project Definition\n\nThe Starbucks Capstone project is one of many options provided to students within the Udacity Data Science Nanodegree Program. This particular project is chosen considering the open ended problem presented along with the data set. The full description of the project as well as the information regarding the data set is presented above.", "_____no_output_____" ], [ "## 1.a. Project Overview\n\nThe projects entails simulated data of Starbucks customers' behavior on the Starbucks rewards app. Starbucks customers sometimes receive an offer or two regarding Starbucks' products. Since this is only a simplified version of the actual data, this data set only contains an offer related to one product instead of many. The data set also notes that not all users receive the same offer, which means ultimately each user can receive a different combination of offers.", "_____no_output_____" ], [ "## 1.b. Problem Statement\n\nThis capstone challenge aims to build a successful machine learning model which could predict whether customers will most likely to complete an offer. The result of this project hopes to assist Starbucks decision in concentrating on which group of customers who are more likely to provide a positive reaction towards those offers. The customers' likeliness to participate and complete any sort of offer can depend on many things, such as (although not limited to):\n\n1. Income level\n2. Gender\n3. Age\n4. Platform of communication\n5. Type of offer\n\nIt is noted that these are some of the variables which are expected to have a significant impact on the customers' behavior. The actual features which are deemed to be significant or substantial towards the completed offer will be explored further within the notebook.", "_____no_output_____" ], [ "## 1.c. Metrics\n\nSince the final goal of this project is to build a machine learning model to predict the customers behavior, the problem can be simplified into a binary classification problem. Ultimately, the machine learning will predict:\n\n**Whether a certain customer would more likely to complete an offer based on their profiles**\n\nDue to the problem being a binary classification, we can simplify the metrics to an overall accuracy of the model. The other scoring computations will be included, e.g. *f1_score* and *precision*.", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport math\nimport json\n\nimport datetime\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style = 'whitegrid')\n%matplotlib inline", "_____no_output_____" ], [ "# read in the json files\nportfolio = pd.read_json('data/portfolio.json', orient='records', lines=True)\nprofile = pd.read_json('data/profile.json', orient='records', lines=True)\ntranscript = pd.read_json('data/transcript.json', orient='records', lines=True)", "_____no_output_____" ] ], [ [ "# 2. Analysis\n\nThe bulk of the data cleaning and exploration process will be performed in this part of the notebook. It is noted that while the visualization of the data presents in this section, the dataframes do not currently show the customers ids who have successfully completed the offer. A more thorough analysis regarding the relations between completed offer and other demographic features are shown in the next section.\n\n## 2.a. Data Exploration and Visualization\n\nIn this section, the process of data cleaning and exploration for each dataset will be performed. The datasets portfolio, profile, and transcript are cleaned in order. Depending on the dataset's contents, data exploration is also carried out either before or after data cleaning. Each of the data cleaning process is captured within one function (therefore there are 3 different functions for the data cleaning process). \n\nAs mentioned above, the data visualization in this section only concerns with the distribution of demographic features within the data set, such as age distribution based on gender, income, percentage of different event types of offers and so on.\n\n### 2.a.i. Dataset: *portfolio.json* \n\nThe following process are performed in order to clean and explore the *portfolio.json* dataset:\n\n1. Check the categorical data type columns to plan on how to clean them\n2. Prior to cleaning the data, create a copy of the dataframe\n3. Create dummies on the offer_type\n4. Create dummies for the channels (different type of offer campaigns)\n5. Concat these dummies values and drop the original columns", "_____no_output_____" ] ], [ [ "portfolio.head()", "_____no_output_____" ], [ "offer_types = portfolio['offer_type'].unique()\nchannels_combination = portfolio['channels'].values\n\nprint(offer_types)\nprint(channels_combination)", "['bogo' 'informational' 'discount']\n[list(['email', 'mobile', 'social'])\n list(['web', 'email', 'mobile', 'social'])\n list(['web', 'email', 'mobile']) list(['web', 'email', 'mobile'])\n list(['web', 'email']) list(['web', 'email', 'mobile', 'social'])\n list(['web', 'email', 'mobile', 'social'])\n list(['email', 'mobile', 'social'])\n list(['web', 'email', 'mobile', 'social'])\n list(['web', 'email', 'mobile'])]\n" ] ], [ [ "From the output above, it can be seen that the offer_types are consisted of 3 different types. The interesting aspect of this dataset is the values within the channels column. Since the values are contained within list, this is something that needs to be addressed when the data has to be cleaned.\n\nA function to clean the dataset is provided below. Note that a new dataframe is created to preserve the original if it's ever needed in the future.", "_____no_output_____" ] ], [ [ "def portfolio_clean(df = portfolio):\n '''\n Clean portfolio dataframe\n\n Args:\n df (pandas.DataFrame): DataFrame of portfolio\n\n Returns:\n df (pandas.DataFrame): Cleaned DataFrame of portfolio\n '''\n df = df.copy()\n offer_dummies = pd.get_dummies(df['offer_type'], prefix = 'offer')\n channels = df['channels'].str.join(sep = '*').str.get_dummies(sep = '*').add_prefix('channel_') # indexing the list within the column\n df = df.drop(['channels', 'offer_type'], axis = 1)\n df = df.rename(columns = {'id': 'offer_id', 'reward': 'offer_reward', 'difficulty': 'offer_difficulty', 'duration': 'offer_duration'})\n columns_order = ['offer_id', 'offer_reward', 'offer_difficulty', 'offer_duration']\n df = df.reindex(columns = columns_order)\n df = pd.concat([df, offer_dummies, channels], axis = 1)\n df = df.reset_index(drop=True)\n return df", "_____no_output_____" ] ], [ [ "The portfolio data can now be cleaned. The following cell runs how the cleaned dataframe looks like.", "_____no_output_____" ] ], [ [ "df_portfolio = portfolio_clean()\ndf_portfolio.head(10)", "_____no_output_____" ] ], [ [ "### 2.a.ii. Dataset: *profile.json* \n\nThe following process are performed in order to clean and explore the *profile.json* dataset:\n\n1. Check how many data entries are missing values\n2. Check the customers' gender and income values for missing values\n3. Create copy of dataframe and drop missing values (12.8% of the total data)\n4. Create a datetime format for became_member_on column data\n5. Find the total number of days a customer has been a member, assigned to days_membership column\n6. Rename the column id to customer_id\n7. The distribution plot of their income, age, and days of membership based on their genders are explored and visualized", "_____no_output_____" ] ], [ [ "profile.head()", "_____no_output_____" ], [ "profile.describe().T", "_____no_output_____" ], [ "profile.isnull().sum()*100/len(profile)", "_____no_output_____" ], [ "profile[(profile['gender'].isna()) & (profile['income'].isna())]", "_____no_output_____" ] ], [ [ "It is interesting to see how for every gender unknown, the income is also unknown. Also notice that the age is set to 118 for all the rows with NaN values. Due to the ratio of these missing values amount to roughly 12.8%, let's drop these rows.\n\nThe following function cleans the profile dataframe. This process includes dropping the NaN values and converting the became_member_on to datetime format. In addition, it might be in our best interest to check when the customers start becoming a member. This can be illustrated better by creating membership days.", "_____no_output_____" ] ], [ [ "def profile_clean(df = profile):\n '''\n Clean profile dataframe\n\n Args:\n df (pandas.DataFrame): DataFrame of profile\n\n Returns:\n df (pandas.DataFrame): Cleaned DataFrame of profile\n '''\n df = df.copy()\n df = df.dropna()\n df['became_member_on'] = pd.to_datetime(df['became_member_on'], format = '%Y%m%d')\n df['days_membership'] = (datetime.datetime.today().date() - df['became_member_on'].dt.date).dt.days\n df = df.rename(columns = {'id': 'customer_id'})\n columns_order = ['customer_id', 'gender', 'age', 'income', 'became_member_on', 'days_membership']\n df = df.reindex(columns = columns_order)\n df = df.reset_index(drop=True)\n return df", "_____no_output_____" ], [ "df_profile = profile_clean()\ndf_profile.head()", "_____no_output_____" ] ], [ [ "Several distribution plots can be presented to give an idea regarding the customers' demographic.", "_____no_output_____" ] ], [ [ "sns.set(style = 'whitegrid', font_scale = 1.25)\npalette = sns.color_palette()\n\nfig, ax = plt.subplots(figsize=(20,4), nrows = 1, ncols = 3, sharex = True, sharey = True)\n\nplt.sca(ax[0])\nsns.distplot(df_profile[df_profile['gender'] == 'F']['age'], bins = 10, color = palette[0]);\nplt.title('Female\\'s Age Distribution')\nplt.xlabel('Age')\nplt.ylabel('Distribution')\n\nplt.sca(ax[1])\nsns.distplot(df_profile[df_profile['gender'] == 'M']['age'], bins = 10, color = palette[1]);\nplt.title('Male\\'s Age Distribution')\nplt.xlabel('Age')\n\nplt.sca(ax[2])\nsns.distplot(df_profile[df_profile['gender'] == 'O']['age'], bins = 10, color = palette[2]);\nplt.title('Other\\'s Age Distribution')\nplt.xlabel('Age')\nplt.show()\n\nfig.savefig('figures/profile_age.svg', dpi = 300)", "_____no_output_____" ], [ "sns.set(style = 'whitegrid', font_scale = 1.25)\npalette = sns.color_palette()\n\nfig, ax = plt.subplots(figsize=(20,4), nrows = 1, ncols = 3, sharex = True, sharey = True)\n\nplt.sca(ax[0])\nsns.distplot(df_profile[df_profile['gender'] == 'F']['income'], bins = 10, color = palette[3]);\nplt.title('Female\\'s Income Distribution')\nplt.xlabel('Income($)')\nplt.ylabel('Distribution')\n\nplt.sca(ax[1])\nsns.distplot(df_profile[df_profile['gender'] == 'M']['income'], bins = 10, color = palette[4]);\nplt.title('Male\\'s Income Distribution')\nplt.xlabel('Income($)')\n\nplt.sca(ax[2])\nsns.distplot(df_profile[df_profile['gender'] == 'O']['income'], bins = 10, color = palette[5]);\nplt.title('Other\\'s Income Distribution')\nplt.xlabel('Income($)')\nplt.show()\n\nfig.savefig('figures/profile_income.svg', dpi = 300)", "_____no_output_____" ], [ "sns.set(style = 'whitegrid', font_scale = 1.25)\npalette = sns.color_palette()\n\nfig, ax = plt.subplots(figsize=(20,4), nrows = 1, ncols = 3, sharex = True, sharey = True)\n\nplt.sca(ax[0])\nsns.distplot(df_profile[df_profile['gender'] == 'F']['days_membership'], bins = 10, color = palette[6]);\nplt.title('Female\\'s Membership Duration Distribution')\nplt.xlabel('Days of Membership')\nplt.ylabel('Distribution')\n\nplt.sca(ax[1])\nsns.distplot(df_profile[df_profile['gender'] == 'M']['days_membership'], bins = 10, color = palette[7]);\nplt.title('Male\\'s Membership Distribution')\nplt.xlabel('Days of Membership')\n\nplt.sca(ax[2])\nsns.distplot(df_profile[df_profile['gender'] == 'O']['days_membership'], bins = 10, color = palette[8]);\nplt.title('Other\\'s Membership Distribution')\nplt.xlabel('Days of Membership')\nplt.show()\n\nfig.savefig('figures/profile_membership.svg', dpi = 300)", "_____no_output_____" ] ], [ [ "### 2.c.iii. Dataset: *transcript.json* \n\nThe following process are performed in order to clean and explore the *transcript.json* dataset:\n\n1. Check the unique event types\n2. Check the percentage of each types (useful to see how many completed the offer)\n3. Plot the percentage of these unique event types\n4. Create a copy of the dataframe prior to cleaning\n5. Finding the customer_id data to keep (the one intersecting or contained in the *profile.json*)\n6. Change the time format from hours to days\n7. Create two dataframes:\n - One containing offer ids\n - One containing transaction amount\n8. Rename the person column to customer_id to keep it consistent with the df_profile dataframe", "_____no_output_____" ] ], [ [ "transcript.head()", "_____no_output_____" ], [ "transcript['event'].unique().tolist()", "_____no_output_____" ], [ "percentage = transcript['event'].value_counts()*100/len(transcript)\nval_trans = percentage.values.tolist()\nevent_type = percentage.index.tolist()\nsns.set(style = 'whitegrid', font_scale = 1.0)\nsns.barplot(x = val_trans, y = event_type)\nplt.title('Percentage of Event Types')\nplt.xlabel('Percentage(%)')\nplt.show()\n\nplt.savefig('figures/event_types.svg', dpi = 300)", "_____no_output_____" ], [ "def transcript_clean(df = transcript, profile = df_profile):\n '''\n Clean transcript dataframe\n\n Args:\n df (pandas.DataFrame): DataFrame of transcript\n\n Returns:\n df_o (pandas.DataFrame): Cleaned DataFrame containing offers\n df_t (pandas.DataFrame): Cleaned DataFrame containing transactions\n '''\n df = df.copy()\n data_to_keep = df['person'].isin(profile['customer_id'])\n df = df[data_to_keep]\n df['time'] = df['time']/24\n \n filter_row = df['event'] == 'transaction'\n non_offer_df = df[filter_row]\n df_t = pd.DataFrame(data = non_offer_df)\n df_t = df_t.drop(['value', 'event'], axis = 1)\n df_t['amount'] = non_offer_df['value'].apply(lambda x: list(x.values())[0])\n df_t = df_t.rename(columns = {'person': 'customer_id'})\n df_t = df_t.reset_index(drop=True)\n \n filter_row = df['event'] != 'transaction'\n offer_df = df[filter_row]\n df_o = pd.DataFrame(data = offer_df)\n dummies = pd.get_dummies(df_o['event'])\n df_o = df_o.drop(['event', 'value'], axis = 1)\n df_o['offer_id'] = offer_df['value'].apply(lambda x: list(x.values())[0])\n df_o = df_o.rename(columns = {'person': 'customer_id'})\n df_o = pd.concat([df_o, dummies], axis = 1)\n columns_order = ['customer_id', 'offer_id', 'time', 'offer completed', 'offer received', 'offer viewed']\n df_o = df_o.reindex(columns = columns_order)\n df_o = df_o.reset_index(drop=True)\n \n return df_o, df_t", "_____no_output_____" ], [ "df_offer, df_transaction = transcript_clean()", "_____no_output_____" ], [ "df_transaction.head()", "_____no_output_____" ], [ "df_offer.head()", "_____no_output_____" ] ], [ [ "## 2.b. Conclusion\n\nFrom these separate datasets, it can be concluded that some of the information are related through features such as customer_id. Therefore, it is beneficial to combined the datasets containing desired features into one. This is going to be performed in the next section, Feature Selection and Engineering, which aims to provide enough significant features so that our machine learning model can predict whether a customer is more likely to finish the offer or not.", "_____no_output_____" ], [ "# 3. Feature Selection and Engineering\n\nAlthough the 3 datasets above were successfully cleaned, in order to process these data into a machine learning model, the datasets have to be combined. Features which are deemed significant will be included in constructing the new dataframe as well as any other features to be created (engineered). ", "_____no_output_____" ], [ "## 3.a. Define pandas.DataFrame \n\nThe following procedure is performed in obtaining a clean dataframe complete with its features:\n\n1. Index through unique customer_id\n2. For each unique customer_id, find the offer received for that customer_id\n3. Within the time window given by each offer, determine:\n - Amount of money customer spent\n - Whether the offer is completed \n - Other demographic information regarding this customer\n - Add the offer information", "_____no_output_____" ] ], [ [ "print(df_portfolio.columns.tolist())\nprint(df_profile.columns.tolist())\nprint(df_transaction.columns.tolist())\nprint(df_offer.columns.tolist())", "['offer_id', 'offer_reward', 'offer_difficulty', 'offer_duration', 'offer_bogo', 'offer_discount', 'offer_informational', 'channel_email', 'channel_mobile', 'channel_social', 'channel_web']\n['customer_id', 'gender', 'age', 'income', 'became_member_on', 'days_membership']\n['customer_id', 'time', 'amount']\n['customer_id', 'offer_id', 'time', 'offer completed', 'offer received', 'offer viewed']\n" ], [ "# Read in successful offer, view, and receive:\ndef clean_data(df_portfolio, df_profile, df_offer, df_transaction):\n '''\n Combine df_portfolio, df_profile, df_offer, and\n df_transaction\n\n Args:\n df_portfolio (pandas.DataFrame): Clean DataFrame of portfolio\n df_profile (pandas.DataFrame): Clean DataFrame of profile\n df_offer (pandas.DataFrame): Clean DataFrame of offer\n df_transaction (pandas.DataFrame): Clean DataFrame of transaction\n Returns:\n clean_data (pandas.DataFrame): DataFrame containing information from\n all of the data input in the desired \n format\n '''\n clean_data = []\n customer_list = df_profile['customer_id'].unique().tolist()\n for customer_id in customer_list:\n index_customer = df_profile[df_profile['customer_id'] == customer_id]\n offer_filtered = df_offer[df_offer['customer_id'] == customer_id]\n transaction_id = df_transaction[df_transaction['customer_id'] == customer_id]\n \n offer_complete = offer_filtered[offer_filtered['offer completed'] == 1]\n offer_view = offer_filtered[offer_filtered['offer viewed'] == 1]\n offer_receive = offer_filtered[offer_filtered['offer received'] == 1]\n \n # Loop through customers who obtained offers\n for index in range(len(offer_receive)):\n offer_id = offer_receive.iloc[index]['offer_id']\n offer_info = df_portfolio[df_portfolio['offer_id'] == offer_id]\n duration = offer_info['offer_duration'].values[0]\n portfolio = offer_info[['offer_duration', 'offer_reward', 'offer_difficulty', \n 'offer_bogo', 'offer_discount', 'offer_informational',\n 'channel_email', 'channel_mobile', 'channel_social', \n 'channel_web']].values[0]\n\n customer = index_customer[['gender', 'age', 'income', 'days_membership', 'became_member_on']].values[0]\n\n offer_start = offer_receive.iloc[index]['time']\n offer_end = offer_start + duration\n\n #np.logical_and is used instead of and to avoid ambiguous truth value\n transaction_filter = np.logical_and(transaction_id['time'] >= offer_start, \n transaction_id['time'] <= offer_end)\n completed_filter = np.logical_and(offer_complete['time'] >= offer_start, \n offer_complete['time'] <= offer_end)\n viewed_filter = np.logical_and(offer_view['time'] >= offer_start, \n offer_view['time'] <= offer_end)\n\n offer_finished = (completed_filter.sum() > 0) and (viewed_filter.sum() > 0) # assign 1 if offer is fulfilled, 0 if not\n period_transaction = transaction_id[transaction_filter]['amount'].sum() # amount of transaction during the offer \n\n data_entry_1 = [offer_id, customer_id, int(offer_finished), period_transaction]\n data_entry_2 = list(portfolio)\n data_entry_3 = list(customer)\n\n data = data_entry_1 + data_entry_2 + data_entry_3\n\n clean_data.append(data)\n\n column_names = ['offer_id', 'customer_id', 'offer_completed', 'money_spent', # data entry 1\n 'offer_duration', 'offer_reward', 'offer_difficulty', 'offer_bogo', # data entry 2\n 'offer_discount', 'offer_informational', 'channel_email', 'channel_mobile', # data entry 2\n 'channel_social', 'channel_web', # data entry 2\n 'gender', 'age', 'income', 'days_membership', 'became_member_on'] # data entry 3\n\n clean_data = pd.DataFrame(data = clean_data, columns = column_names)\n # Grab the joining year\n clean_data['became_member_on'] = clean_data['became_member_on'].dt.year\n \n return clean_data", "_____no_output_____" ], [ "processed_data = clean_data(df_portfolio, df_profile, df_offer, df_transaction)", "_____no_output_____" ], [ "processed_data.to_csv('data/processed_data.csv', index = False) # Save data to increase reusability and reduce runtime", "_____no_output_____" ], [ "processed_data.head()", "_____no_output_____" ], [ "filter_data = processed_data[(processed_data['offer_completed'] == 1) & (processed_data['gender'] != 'O')]", "_____no_output_____" ], [ "sns_plot = sns.catplot(data = filter_data, x = 'offer_completed', \n hue = 'offer_id', kind = 'count', col = 'gender');\nplt.savefig('figures/offer_id_gender_dist.svg', dpi = 300);", "_____no_output_____" ] ], [ [ "The plot above presents the number of completed offers by customers filtered by gender. It is seen that more male customers as overall complete the offers, compared to females. But this is not necessarily mean that males are more likely to complete offers in comparison to females, but rather due to the number of males in the data set is larger than the females.\n\nOne thing to note however, the offer_id labeled in red seems to be the more popular completed offer than the rest. One thing that Starbucks can learn from this count plot is that the last two offer types are most likely do not cater to what the customers want, since they only represent a very small portion of the entire completed offer counts. ", "_____no_output_____" ] ], [ [ "male = len(processed_data[processed_data['gender'] == 'M'])\nfemale = len(processed_data[processed_data['gender'] == 'F'])\n\nmale, female", "_____no_output_____" ], [ "ones = len(processed_data[processed_data['offer_completed'] == 1])\nzeros = len(processed_data) - ones\n\nlabels = ['Completed', 'Incomplete']\nsizes = [ones, zeros]\nexplode = (0, 0.05)\npie_plot = plt.pie(sizes, explode = explode, labels = labels, autopct='%1.1f%%',\n shadow=True, startangle=90)\nplt.title('Percentage of Completed vs Incomplete Offers')\nplt.axis('equal')\nplt.show()", "_____no_output_____" ] ], [ [ "This pie chart provides an idea of how balanced the data set is. This means that our target value (offer_completed) which is going to be used for our machine learning will not have negative impact on how the model will perform. ", "_____no_output_____" ] ], [ [ "sns_plot = sns.catplot(data = processed_data, x = 'offer_completed', \n hue = 'offer_id', kind = 'count', col = 'channel_social',\n row = 'channel_web');\nplt.savefig('figures/channel_dist.svg', dpi = 300);", "_____no_output_____" ] ], [ [ "Another interesting aspect to see about the customer behavior of Starbucks is how these offers are sent or distributed to them. The plot above describes how well using either web or social as the channel for advertising or promoting the offers can do in convincing the customers to complete the offer. \n\nDistributing the offer through only one of these two channels are most likely to result in majority of the customers to not complete the offer. If this method still provides a benefit (profitable margin) for Starbucks, then it is still proven to be an effective method. However, Starbucks can pivot their choice of channel into **both web and social** in order to maximize the number of people completing their offers. One reason could be that once a person is exposed to multiple channels showing Starbucks' offers, he or she will be more convinced to complete said offers (this is including email as a channel, as most of these offers are distributed using emails in the first place.", "_____no_output_____" ], [ "## 3.b. Conclusion\n\nThe DataFrame ends up having 19 columns. Out of all these 19 columns, most likely several of these variables will be used for the machine learning model. It is also important to check whether these features can be improved even futher through preprocessing. Not all of these features can have high correlation values with our target column: 'offer_completed'. Therefore it only makes sense to choose features that are significant enough for the machine learning model to make predictions. The next section will explore and discuss about machine learning models. ", "_____no_output_____" ], [ "# 4. Machine Learning Model Selection and Tuning\n\nThis section mainly concerns with how to choose the best machine learning model for this particular problem. The main approach in this section is as follows:\n\n1. Data preprocessing\n2. Model selection (through exploration of five options)\n3. Learning curve analysis\n4. Features importance\n\nFrom these 4 steps, it is expected that the project can achieve a quite high percentage of accuracy score while maintaining minimum number of features, therefore reducing training time. ", "_____no_output_____" ] ], [ [ "from sklearn.utils import shuffle\nfrom sklearn.preprocessing import minmax_scale\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.model_selection import cross_val_score, learning_curve, GridSearchCV\n\nimport xgboost\nfrom xgboost import XGBClassifier", "_____no_output_____" ] ], [ [ "## 4.a. Data Preprocessing\n\nContinuing to prepare the data from the previous section:\n\n1. Once the DataFrame is defined:\n - Create dummies for gender and age\n - Normalize the following features:\n - 'money_spent' \n - 'offer_duration'\n - 'offer_reward'\n - 'offer_difficulty'\n - 'income'\n - 'days_membership'\n\nThe following procedure is performed to complete the appropriate data preprocessing:\n\n1. Shuffle the data (randomize entries)\n2. Determine from the data correlation if there is anything out of the ordinary:\n - Remove channel_email due to little to no variability \n3. Create a heatmap to analyze the signifcant correlations\n4. Include the following features for machine learning model:\n - 'money_spent'\n - 'offer_duration'\n - 'offer_reward'\n - 'offer_difficulty', \n - 'offer_discount'\n - 'offer_informational'\n - 'channel_social'\n - 'channel_web',\n - 'days_membership'\n - '2016'\n - '2018'", "_____no_output_____" ] ], [ [ "data = pd.read_csv('data/processed_data.csv')\ndata.head()", "_____no_output_____" ], [ "# Create dummies for gender, age, year\ngender_dummies = pd.get_dummies(data['gender'], prefix = 'gender')\nyear_dummies = pd.get_dummies(data['became_member_on']).astype(int)\n\n# For age use function process_cut\ncut_points = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\ndata['age_cat'] = pd.cut(data['age'], cut_points)\nage_dummies = pd.get_dummies(data['age_cat'])\n\ndata = pd.concat([data, gender_dummies, age_dummies, year_dummies], axis = 1)\ndata = data.drop(['age', 'age_cat', 'gender', 'became_member_on'], axis = 1)\n\ncolumn_normalize = ['money_spent', 'offer_duration', 'offer_reward', \n 'offer_difficulty', 'income', 'days_membership']\n\nfor col in column_normalize:\n data[col] = minmax_scale(data[col])\n \ndata.columns = data.columns.astype(str)", "_____no_output_____" ], [ "data = shuffle(data)", "_____no_output_____" ], [ "data.corr()", "_____no_output_____" ], [ "data = data.drop(['channel_email'], axis = 1)", "_____no_output_____" ], [ "heatmap_vars = data\n\ncorr = heatmap_vars.corr()\nmask = np.triu(corr)\ncmap = sns.color_palette(\"RdBu_r\", 7)\n\nwith sns.axes_style('white'):\n f, ax = plt.subplots(figsize = (26, 10))\n ax = sns.heatmap(corr, mask = mask, cmap = cmap, annot = True, fmt = '.2f')\n\nfigure = ax.get_figure() \nfigure.savefig('figures/heatmap_features.svg', dpi = 300)", "_____no_output_____" ], [ "train = data[['money_spent', 'offer_duration', 'offer_reward', 'offer_difficulty', \n 'offer_discount', 'offer_informational', 'channel_social', 'channel_web',\n 'days_membership', '2016', '2018']]\ntarget = np.ravel(data[['offer_completed']])", "_____no_output_____" ] ], [ [ "### 4.b. Model Exploration\n\nThere are 5 machine learning models for classification that will be examined thoroughly. These are:\n\n1. Logistic Regression\n2. Decision Tree\n3. Adaptive Boosting\n4. Random Forest\n5. XGB Classifier\n\nFor each of the model, the cross validation technique of 10-fold is used to calculate the accuracy of each model. These values are going to be shown in a DataFrame model_df. The dataframe is sorted based on the model test accuracy (the highest at the top).", "_____no_output_____" ] ], [ [ "model_opt = [LogisticRegression(),\n DecisionTreeClassifier(),\n AdaBoostClassifier(),\n RandomForestClassifier(),\n XGBClassifier()] \n\nmodel_cols = ['Model Name', 'Model Parameters', 'Model Test Accuracy']\nmodel_df = pd.DataFrame(columns = model_cols)\n\ncounter = 0\nfor model in model_opt:\n \n model_name = model.__class__.__name__\n model_df.loc[counter, 'Model Name'] = model_name\n model_df.loc[counter, 'Model Parameters'] = str(model.get_params())\n \n accuracy = cross_val_score(model, train, target, cv = 10)\n \n model_df.loc[counter, 'Model Test Accuracy'] = np.mean(accuracy)\n \n counter += 1\n \nmodel_df.sort_values(by = ['Model Test Accuracy'], ascending = False, inplace = True)", "_____no_output_____" ], [ "model_df.head()", "_____no_output_____" ] ], [ [ "The XGB Classifier comes out on top. The top 3 performed models will be analyzed further using Learning Curve. ", "_____no_output_____" ], [ "## 4.c. Learning Curve\n\nIt is necessary to analyze how the machine learning models perform as overall. One tool that can help us analyze this is the learning curve.\nThe learning curve provides an overall look of how the model performs and how it will generalize to data that it has not seen before.\n\nFrom this analysis, it can be seen that XGB Classifier is the superior model compared to the Random Forest and Adaptive Boosting. This is mainly due to its validation and training score converges to a similar value over time. Unlike the other two which suffer from high bias and high variance.", "_____no_output_____" ] ], [ [ "def plot_learning_curve(model_str, train_sizes, train_scores, validation_scores):\n '''\n Plotting the learning curve of a machine learning model given the input\n parameters\n\n Args:\n model_str (str): string model's name\n train_sizes (list): list of training sizes to be calculated\n train_scores (list): training scores of model (metrics)\n validation_scores (list): validation scores of model (metrics)\n Returns:\n None\n *this function plots learning curves with their std bounds\n '''\n figure, ax = plt.subplots(figsize = (8, 6))\n \n train_scores_mean = train_scores.mean(axis = 1)\n train_scores_std = train_scores.std(axis = 1)\n validation_scores_mean = validation_scores.mean(axis = 1)\n validation_scores_std = validation_scores.std(axis = 1)\n \n plt.plot(train_sizes, train_scores_mean, label = 'Training Score', marker = 'o', color = 'r')\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color = \"r\")\n plt.plot(train_sizes, validation_scores_mean, label = 'Validation Score', marker = 'o', color = 'g')\n plt.fill_between(train_sizes, validation_scores_mean - validation_scores_std,\n validation_scores_mean + validation_scores_std, alpha=0.1,\n color = \"g\")\n \n plt.ylabel('Accuracy')\n plt.xlabel('Training set size')\n plt.title('Learning curves for ' + str(model_str))\n plt.legend()\n plt.show()\n \n figure = ax.get_figure() \n figure.savefig('figures/learning_curve_' + str(model_str).lower() + '.svg', dpi = 300)\n \n return", "_____no_output_____" ], [ "train_sizes = [100, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000]\n\nmodel = RandomForestClassifier()\n \nmodel.fit(train, target)\n \ntrain_sizes, train_scores, validation_scores = learning_curve(estimator = model, \n X = train, y = target, \n train_sizes = train_sizes, cv = 10)\nplot_learning_curve('RandomForestClassifier', train_sizes, train_scores, validation_scores)", "_____no_output_____" ] ], [ [ "Random Forest suffers from high variance. As the training size is increased, the model is not capable of improving any further. This can be fixed by using less features. However the data preprocessing step already reduced a good number of interesting features to include within the model. Another approach is to add more data, yet the number of data in the scope of this project is fixed.", "_____no_output_____" ] ], [ [ "model = AdaBoostClassifier() \nmodel.fit(train, target)\n \ntrain_sizes, train_scores, validation_scores = learning_curve(estimator = model, \n X = train, y = target, \n train_sizes = train_sizes, cv = 10)\nplot_learning_curve('AdaBoostClassifier', train_sizes, train_scores, validation_scores)", "_____no_output_____" ] ], [ [ "The Adaptive Boosting model suffers from high bias. This can be seen from the both training and validation score stays too close together. This will more likely result in poor fit and especially poor generalization of the data (towards the data it hasn't seen before).", "_____no_output_____" ] ], [ [ "train_sizes = list(range(1000, 59000, 5000))\nmodel = XGBClassifier()\n \nfit = model.fit(train, target)\n \ntrain_sizes, train_scores, validation_scores = learning_curve(estimator = model, \n X = train, y = target, \n train_sizes = train_sizes, cv = 10)\nplot_learning_curve('XGBClassifier', train_sizes, train_scores, validation_scores)", "_____no_output_____" ] ], [ [ "This is ideally the desired learning curve of a machine learning model. The validation score of XGB Classifier converges to a similar value of that the training score. This model is more likely to generalize better in comparison to the other models examined previously.", "_____no_output_____" ], [ "## 4.d. Model Tuning GridSearchCV\n\nSeveral of the parameters of the XGB Classifier can also be tuned. Since optimizing the parameters over a large numbers of variation can result in long runtime, only a few of these parameters are going to be tuned. The max depth is chosen to be tuned since it can cause overfitting. The parallel tree is computed for boosting the algorithm. The booster is the type of booster that can assist the model the most.", "_____no_output_____" ] ], [ [ "model = XGBClassifier()\n\nhyperparameters = {\n 'max_depth': [6], # 'max_depth': [3, 5, 6]\n 'booster': ['gbtree'], # 'booster': ['gbtree', 'gblinear']\n 'num_parallel_tree': [1] # 'num_parallel_tree': [1, 2]\n}\n\ngrid = GridSearchCV(model, param_grid = hyperparameters, cv = 10, scoring = ['accuracy', 'precision', 'f1'], refit = 'accuracy')\ngrid.fit(train, target)\n\nbest_params = grid.best_params_\nbest_score = grid.best_score_\ntuned_model = grid.best_estimator_", "_____no_output_____" ], [ "print('Best parameters of XGB Classifier:', str(best_params))\nprint('The model accuracy is: ' + str(round(best_score*100,2)) + '%')", "Best parameters of XGB Classifier: {'booster': 'gbtree', 'max_depth': 6, 'num_parallel_tree': 1}\nThe model accuracy is: 91.43%\n" ], [ "print(tuned_model)", "XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n colsample_bynode=1, colsample_bytree=1, gamma=0, gpu_id=-1,\n importance_type='gain', interaction_constraints=None,\n learning_rate=0.300000012, max_delta_step=0, max_depth=6,\n min_child_weight=1, missing=nan, monotone_constraints=None,\n n_estimators=100, n_jobs=0, num_parallel_tree=1,\n objective='binary:logistic', random_state=0, reg_alpha=0,\n reg_lambda=1, scale_pos_weight=1, subsample=1, tree_method=None,\n validate_parameters=False, verbosity=None)\n" ], [ "xgboost.plot_tree(tuned_model, num_trees = 0, rankdir = 'LR')\nfig = plt.gcf()\nfig.set_size_inches(150, 100)\nfig.savefig('figures/tree.svg')\nplt.close()", "_____no_output_____" ], [ "fit_var = tuned_model.fit(train, target)", "_____no_output_____" ], [ "important_feature = fit_var.feature_importances_\nfeature_names = train.columns.tolist()\ndf_feature = pd.DataFrame(data = important_feature, columns = ['values'])\ndf_feature['feature_names'] = feature_names\ndf_feature = df_feature.sort_values(by = ['values'], ascending = False)\ndf_feature.head()", "_____no_output_____" ], [ "sns.barplot(data = df_feature, x = 'values', y = 'feature_names')\nplt.title('XGB Classifier\\'s Feature Importance')\nplt.xlabel('Importance Values')\nplt.show()\n\nplt.savefig('figures/XGB_feature_importance.svg', dpi = 300);", "_____no_output_____" ] ], [ [ "## 4.e. Conclusion\n\nThe plot above specifies that the three following features to be the most important:\n\n1. offer_duration\n2. money_spent\n3. channel_social\n\nLet's take a look at each of these features. Offer duration might be significant since it specifies the number of days the duration of the offer lasts. The longer the offer lasts, the higher the chance for a particular customer to fulfill its requirement. How about money spent? Unlike income, the money spent by a user typically reflects a closer lifestyle of that person. The more often you buy, the higher the chance that you will buy enough to meet the offer conditions. This is more informational than the income information, since it only gives an idea of how much money they make, not how much money they are willing to spend.\n\nFinally, the social channel feature. The fact that this comes in the top three features signifies how social channel is the one that people pay more attention to (obviously does not apply for everyone). This can be used as a reasoning for Starbucks to concentrate more on advertising/sending their offers through these social channels, instead of through web for example. One thing to note though, the email channel is not included in the training data since it contains little to no variation between datasets. Therefore, it might interesting to do a little further experiment to see if whether email is a more effective and efficient method of sending Starbucks offers.", "_____no_output_____" ], [ "# 5. Discussion and Overall Conclusion\n\nThis capstone project concerns with analyzing customers behavior in whether they are likely to respond to an offer as well as finish them, by knowing their demographic information. The aim of this project is to build a machine learning model that would generalize well enough to a model it has not seen before while maintaining high accuracy prediction values. This project is divided into multiple sections:\n\n1. Project Overview\n2. Data Analysis\n3. Feature Selection and Engineering\n4. Model Selection and Tuning\n\n### Project Overview\n\nThis section mainly explains what the project is about, certain aspects to look forward to, as well as the expectation of the project. It is also mentioned in this section, that several features such as income, can be the driving factor of Starbucks' customers behavior. The metric used for this analysis is an accuracy rating due to the problem being a binary classification. \n\n### Data Analysis\n\nThe data analysis entails exploring and cleaning the data. Since the desired data needs to be entried of unique customers with their offers labeled with the information of whether they fulfill the offer criteria, each of the .json data is cleaned individually prior to be combined. The combination of these three was proven to be the most challenging and time-consuming due to the nature of how the data set is presented. In the end, an offer is marked completed only if the customer has **seen** the offer, and manage to **complete** the offer within the **time frame**.\n\n### Feature Selection and Engineering\n\nThe function to achieve the criterion mentioned before is implemented in this section. Once the data is obtained, a further analysis of the customer behavior based on their demographics is performed. The trend for both male and female is quite similar in the ways they finished the Starbucks offers (based on the offer ids). An interesting find is that Starbucks will have the highest chance of having its customers complete the offers by sending them information through **both web and social**, in addition to email. This is something that can be looked into and tested further for confirmation.\n\n### Model Selection and Tuning\n\nThere are five models used to analyze the data (after preprocessing, applying dummies and normalization). The features used as the input for the model are chosen based on their correlation towards the target value (offer_completed column). Out of those five, three are heavily considered:\n\n1. Random Forest\n - Random Forest performs quite well in terms of accuracy, however it suffers from high variance. This means that the model is not performing any better with higher training sizes. Usually this problem can be fixed easily by adding more data entries, yet this capstone project's data entries are fixed in number.\n \n \n2. Adaptive Boosting\n - Adaptive boosting is superior in terms of accuracy compared to Random Forest, yet it suffers from high bias. This lets the model to fit poorly towards the data it has not seen. \n \n \n3. XGB Classifier\n - XGB Classifier comes out on top. The training and validation scores converge to a similar value, just right so that this model can generalize well to unseen data. Due to its high accuracy score and the ideal learning curve, XGB Classifier is chosen as the machine learning model for this project.\n \nBased on XGB Classifier's features importance, there are three main features that drive this classification model:\n\n1. offer_duration\n - This feature comes first, probably because it describes an appropriate time window for customer to finish their offer (provide just enough frequency for them to purchase Starbucks products).\n \n \n2. money_spent\n - Reflects the spending habit of a person, rather than income. Having a high income does not necessarily mean a person is willing to spend money frequently. This is not as the expectation laid down in section 1 where income is thought to be important. \n \n \n3. channel_social\n - The exposure of social channels are probably huge for most of Starbucks' customers.\n \n### Conclusion and Improvements\n\nBased on these findings, Starbucks can concentrate on campaigning its variety of offers through social channels while maintaining a moderate offer duration for the customers. Trying to find a customer with higher money spent within certain time frames might be beneficial rather than keeping track of their yearly income. As for gender, it does not seem that there should be any preferences for Starbucks to target, as long as these offers are sent based on the parameters discussed. \n\nThere are several improvements that can be implemented:\n\n1. Perform a thorough experiment:\n - This can be performed using A/B Testing where one group consists of people who are exposed to the offers only from web while the other is from social channels.\n - Another experiment that concentrates on determining what offer duration to be best for these customers so that Starbucks can design an offer that would specifically target this behavior. \n \n \n2. A better model tuning:\n - Due to limitation of computing power, only several parameters of XGB Classifier were successfully tuned. Therefore this model can definitely be improved to a higher accuracy (hopefully 95%+). \n \n \n3. A better step or method in combining the data sets:\n - Definitely the main bottleneck of the project, since this process takes a long time to run. It might be beneficial to perform this process using a different method rather than implementing a nested loop. ", "_____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", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
ec54346fd45bfd6410840ba45c19299403f0f0ee
18,220
ipynb
Jupyter Notebook
distributed/3.dask-tensorflow/dask-tensorflow.ipynb
vishalbelsare/Deep-Learning-Tensorflow
1590bfc7007aa53aaab72493e7d6f8154f3ec99b
[ "MIT" ]
51
2017-08-04T12:54:49.000Z
2022-03-04T08:23:46.000Z
distributed/3.dask-tensorflow/dask-tensorflow.ipynb
Jeansding/Deep-Learning-Tensorflow
1590bfc7007aa53aaab72493e7d6f8154f3ec99b
[ "MIT" ]
3
2017-09-24T13:44:30.000Z
2018-12-23T11:43:34.000Z
distributed/3.dask-tensorflow/dask-tensorflow.ipynb
vishalbelsare/Deep-Learning-Tensorflow
1590bfc7007aa53aaab72493e7d6f8154f3ec99b
[ "MIT" ]
45
2017-08-04T02:36:32.000Z
2022-03-04T08:23:50.000Z
41.503417
4,952
0.628321
[ [ [ "import dask.array as da\nfrom dask import delayed\nfrom dask_tensorflow import start_tensorflow\nfrom distributed import Client, progress\nimport dask.dataframe as dd\nimport matplotlib.pyplot as plt\n\nimport dask.array as da\nfrom dask import delayed", "_____no_output_____" ], [ "client = Client()", "_____no_output_____" ], [ "def get_mnist():\n from tensorflow.examples.tutorials.mnist import input_data\n mnist = input_data.read_data_sets('mnist-data', one_hot=True)\n return mnist.train.images, mnist.train.labels\n\ndatasets = [delayed(get_mnist)() for i in range(1)]\nimages = [d[0] for d in datasets]\nlabels = [d[1] for d in datasets]\n\nimages = [da.from_delayed(im, shape=(55000, 784), dtype='float32') for im in images]\nlabels = [da.from_delayed(la, shape=(55000, 10), dtype='float32') for la in labels]\n\nimages = da.concatenate(images, axis=0)\nlabels = da.concatenate(labels, axis=0)\n\nimages", "_____no_output_____" ], [ "images, labels = client.persist([images, labels])", "_____no_output_____" ], [ "im = images[1].compute().reshape((28, 28))\nplt.imshow(im, cmap='gray')", "_____no_output_____" ], [ "images = images.rechunk((10000, 784))\nlabels = labels.rechunk((10000, 10))\n\nimages = images.to_delayed().flatten().tolist()\nlabels = labels.to_delayed().flatten().tolist()\nbatches = [delayed([im, la]) for im, la in zip(images, labels)]\n\nbatches = client.compute(batches)", "_____no_output_____" ], [ "from dask_tensorflow import start_tensorflow\ntf_spec, dask_spec = start_tensorflow(client,ps=1,worker=2,scorer=1)", "_____no_output_____" ], [ "dask_spec", "_____no_output_____" ], [ "import math\nimport tempfile\nimport time\nfrom queue import Empty\n\nIMAGE_PIXELS = 28\nhidden_units = 100\nlearning_rate = 0.01\nsync_replicas = False\nreplicas_to_aggregate = len(dask_spec['worker'])", "_____no_output_____" ], [ "def model(server):\n worker_device = \"/job:%s/task:%d\" % (server.server_def.job_name,\n server.server_def.task_index)\n task_index = server.server_def.task_index\n is_chief = task_index == 0\n\n with tf.device(tf.train.replica_device_setter(\n worker_device=worker_device,\n ps_device=\"/job:ps/cpu:0\",\n cluster=tf_spec)):\n\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n\n # Variables of the hidden layer\n hid_w = tf.Variable(\n tf.truncated_normal(\n [IMAGE_PIXELS * IMAGE_PIXELS, hidden_units],\n stddev=1.0 / IMAGE_PIXELS),\n name=\"hid_w\")\n hid_b = tf.Variable(tf.zeros([hidden_units]), name=\"hid_b\")\n\n # Variables of the softmax layer\n sm_w = tf.Variable(\n tf.truncated_normal(\n [hidden_units, 10],\n stddev=1.0 / math.sqrt(hidden_units)),\n name=\"sm_w\")\n sm_b = tf.Variable(tf.zeros([10]), name=\"sm_b\")\n\n # Ops: located on the worker specified with task_index\n x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS * IMAGE_PIXELS])\n y_ = tf.placeholder(tf.float32, [None, 10])\n\n hid_lin = tf.nn.xw_plus_b(x, hid_w, hid_b)\n hid = tf.nn.relu(hid_lin)\n\n y = tf.nn.softmax(tf.nn.xw_plus_b(hid, sm_w, sm_b))\n cross_entropy = -tf.reduce_sum(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)))\n\n opt = tf.train.AdamOptimizer(learning_rate)\n\n if sync_replicas:\n if replicas_to_aggregate is None:\n replicas_to_aggregate = num_workers\n else:\n replicas_to_aggregate = replicas_to_aggregate\n\n opt = tf.train.SyncReplicasOptimizer(\n opt,\n replicas_to_aggregate=replicas_to_aggregate,\n total_num_replicas=num_workers,\n name=\"mnist_sync_replicas\")\n\n train_step = opt.minimize(cross_entropy, global_step=global_step)\n\n if sync_replicas:\n local_init_op = opt.local_step_init_op\n if is_chief:\n local_init_op = opt.chief_init_op\n\n ready_for_local_init_op = opt.ready_for_local_init_op\n\n # Initial token and chief queue runners required by the sync_replicas mode\n chief_queue_runner = opt.get_chief_queue_runner()\n sync_init_op = opt.get_init_tokens_op()\n\n init_op = tf.global_variables_initializer()\n train_dir = tempfile.mkdtemp()\n\n if sync_replicas:\n sv = tf.train.Supervisor(\n is_chief=is_chief,\n logdir=train_dir,\n init_op=init_op,\n local_init_op=local_init_op,\n ready_for_local_init_op=ready_for_local_init_op,\n recovery_wait_secs=1,\n global_step=global_step)\n else:\n sv = tf.train.Supervisor(\n is_chief=is_chief,\n logdir=train_dir,\n init_op=init_op,\n recovery_wait_secs=1,\n global_step=global_step)\n\n sess_config = tf.ConfigProto(\n allow_soft_placement=True,\n log_device_placement=False,\n device_filters=[\"/job:ps\", \"/job:worker/task:%d\" % task_index])\n\n # The chief worker (task_index==0) session will prepare the session,\n # while the remaining workers will wait for the preparation to complete.\n if is_chief:\n print(\"Worker %d: Initializing session...\" % task_index)\n else:\n print(\"Worker %d: Waiting for session to be initialized...\" %\n task_index)\n\n sess = sv.prepare_or_wait_for_session(server.target, config=sess_config)\n\n if sync_replicas and is_chief:\n sess.run(sync_init_op)\n sv.start_queue_runners(sess, [chief_queue_runner])\n\n return sess, x, y_, train_step, global_step, cross_entropy", "_____no_output_____" ], [ "def ps_task():\n with local_client() as c:\n c.worker.tensorflow_server.join()", "_____no_output_____" ], [ "def scoring_task():\n with local_client() as c:\n # Scores Channel\n scores = c.channel('scores', maxlen=10)\n\n # Make Model\n server = c.worker.tensorflow_server\n sess, _, _, _, _, cross_entropy = model(c.worker.tensorflow_server)\n\n # Testing Data\n from tensorflow.examples.tutorials.mnist import input_data\n mnist = input_data.read_data_sets('/tmp/mnist-data', one_hot=True)\n test_data = {x: mnist.validation.images,\n y_: mnist.validation.labels}\n\n # Main Loop\n while True:\n score = sess.run(cross_entropy, feed_dict=test_data)\n scores.append(float(score))\n\n time.sleep(1)", "_____no_output_____" ], [ "def worker_task():\n with local_client() as c:\n scores = c.channel('scores')\n num_workers = replicas_to_aggregate = len(dask_spec['worker'])\n\n server = c.worker.tensorflow_server\n queue = c.worker.tensorflow_queue\n\n # Make model\n sess, x, y_, train_step, global_step, _= model(c.worker.tensorflow_server)\n\n # Main loop\n while not scores or scores.data[-1] > 1000:\n try:\n batch = queue.get(timeout=0.5)\n except Empty:\n continue\n\n train_data = {x: batch[0],\n y_: batch[1]}\n\n sess.run([train_step, global_step], feed_dict=train_data)", "_____no_output_____" ], [ "ps_tasks = [client.submit(ps_task, workers=worker)\n for worker in dask_spec['ps']]\n\nworker_tasks = [client.submit(worker_task, workers=addr, pure=False)\n for addr in dask_spec['worker']]\n\nscorer_task = client.submit(scoring_task, workers=dask_spec['scorer'][0])", "_____no_output_____" ], [ "dask_spec", "_____no_output_____" ], [ "from distributed.worker_client import get_worker\n\ndef transfer_dask_to_tensorflow(batch):\n worker = get_worker()\n worker.tensorflow_queue.put(batch)\n\ndump = client.map(transfer_dask_to_tensorflow, batches,\n workers=dask_spec['worker'], pure=False)\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec543e79371a422fadc8830d914a2881a437ffc8
376,031
ipynb
Jupyter Notebook
notebooks/white noise has a flat power spectrum.ipynb
avirukt/lensing_lfi
1f3b351b690f39488066a06d94335b265fae818a
[ "MIT" ]
1
2019-05-30T21:27:30.000Z
2019-05-30T21:27:30.000Z
notebooks/white noise has a flat power spectrum.ipynb
avirukt/lensing_lfi
1f3b351b690f39488066a06d94335b265fae818a
[ "MIT" ]
null
null
null
notebooks/white noise has a flat power spectrum.ipynb
avirukt/lensing_lfi
1f3b351b690f39488066a06d94335b265fae818a
[ "MIT" ]
null
null
null
2,827.300752
193,660
0.962434
[ [ [ "In $d$ dimensions, with conventions \\begin{align}\\tilde\\phi(k) &= \\int d^dx\\:e^{ik\\cdot x}\\phi(x),\\\\\\phi(x) &= \\frac{1}{(2\\pi)^d}\\int d^dk\\:e^{-ik\\cdot x}\\tilde\\phi(k),\\\\\\left\\langle\\tilde\\phi(k)\\tilde\\phi^*(k')\\right\\rangle&=(2\\pi)^dP(k)\\delta(k-k').\\end{align} For white noise, $\\langle\\phi(x)\\phi(x')\\rangle = A\\delta(x-x'),$ $$\\left\\langle\\tilde\\phi(k)\\tilde\\phi^*(k')\\right\\rangle=\\int d^dx\\: d^dx' e^{ik\\cdot x -ik'\\cdot x'}\\langle\\phi(x)\\phi(x')\\rangle=A\\int d^dx\\: e^{i(k-k')\\cdot x}=A(2\\pi)^d\\delta(k'-k).$$ Thus $P(k)=A$, i.e. __is flat__. Now, the contribution to the pdf is $$\\left\\langle \\phi(x)^2\\right\\rangle = \\frac{1}{(2\\pi)^{2d}}\\int d^dk\\:d^dk'\\:e^{i(k+k')\\cdot x}\\left\\langle \\tilde\\phi(k)\\tilde\\phi^*(-k')\\right\\rangle = \\frac{1}{(2\\pi)^d}\\int d^dk\\:P(k) = \\frac{S_{d-1}}{(2\\pi)^d} \\int d|k|\\: |k|^{d-1}P(|k|)=\\frac{S_{d-1}}{(2\\pi)^d}\\int d\\log|k|\\: k^dP(|k|),$$ where $S_n$ is the surface area of the unit $n$-sphere. However this $k^d$ term is not part of the power spectrum. Maybe you're thinking of the scale-invariant power spectrum $P(k)=k^{-d}$? \n\nIf we used the convention $$\\left\\langle\\tilde\\phi(k)\\tilde\\phi^*(k')\\right\\rangle=\\frac{(2\\pi)^dP(k)\\delta(k-k')}{k^d},$$ then white noise is $P(k)\\propto k^d$ (__increasing__ with $k$) and the scale-invariant power spectrum is flat. Whichever convention we use, for white noise, the total power (summed over different $k$ with the same $|k|$) increases like $k^{d-1}$, and the average power (averaged over different $k$ with the same $|k|$) is flat.", "_____no_output_____" ] ], [ [ "from numpy import *\nfrom matplotlib import pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "x = random.randn(256,256)", "_____no_output_____" ], [ "plt.imshow(x)\nplt.colorbar()", "_____no_output_____" ], [ "f = fft.fft2(x)", "_____no_output_____" ], [ "plt.imshow(fft.fftshift(abs(f)))\nplt.colorbar()", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
ec5441b3ec553f67ff7232b6232f67757c475d91
129,052
ipynb
Jupyter Notebook
resnet50_onnxmlir.ipynb
andrewsi-z/bento-onnxmlir-model-test
8e84f1a928a7f7a597fbc8b0b714b1456d9bc7d2
[ "Apache-2.0" ]
null
null
null
resnet50_onnxmlir.ipynb
andrewsi-z/bento-onnxmlir-model-test
8e84f1a928a7f7a597fbc8b0b714b1456d9bc7d2
[ "Apache-2.0" ]
null
null
null
resnet50_onnxmlir.ipynb
andrewsi-z/bento-onnxmlir-model-test
8e84f1a928a7f7a597fbc8b0b714b1456d9bc7d2
[ "Apache-2.0" ]
null
null
null
441.958904
116,336
0.929339
[ [ [ "This example assumes our ONNX model has been downloaded and compiled using ONNX-MLIR. \n\nWe are making this assumption and not performing it inline as setup and install for LLVM, ONNX-MLIR and related projects is not lightweight. (Pre-built container images are available). \n\nModel should be compiled as follows to ensure library is emitted: \n\n./onnx-mlir --EmitLib resnet50-v2-7.onnx\n\nThis will generate the resnet50-v2-7.so file referenced below.\n\nNote that this leverages the ONNX-MLIR PyRuntime interface documented here: http://onnx.ai/onnx-mlir//UsingPyRuntime.html\n\nThis requires a pybind binary that is built as part of ONNX-MLIR as a shared library under ONNX-MLIR in: \nbuild/lib/PyRuntime.cpython-<target>.so. \n\nThe model used in this example is retrieved here:\nonnx_model_url = \"https://s3.amazonaws.com/onnx-model-zoo/resnet/resnet50v2/resnet50v2.tar.gz\"", "_____no_output_____" ] ], [ [ "import numpy as np # we're going to use numpy to process input and output data\nimport urllib.request\nimport json\nimport time\n\n# display images in notebook\nfrom PIL import Image, ImageDraw, ImageFont", "_____no_output_____" ], [ "#onnx_model_url = \"https://s3.amazonaws.com/onnx-model-zoo/resnet/resnet50v2/resnet50v2.tar.gz\"\nimagenet_labels_url = \"https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json\"\n\nurllib.request.urlretrieve(imagenet_labels_url, filename=\"imagenet-simple-labels.json\")\n\n!curl https://raw.githubusercontent.com/onnx/onnx-docker/master/onnx-ecosystem/inference_demos/images/dog.jpg -o dog.jpg\n#!tar xvzf resnet50v2.tar.gz\n\n", " % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 21240 100 21240 0 0 65353 0 --:--:-- --:--:-- --:--:-- 65353\n" ], [ "import bentoml\nfrom bentoml import env, artifacts, api, BentoService\nfrom bentoml.adapters import ImageInput\nfrom bentoml.frameworks.onnxmlir import OnnxMlirModelArtifact\nfrom bentoml.types import JsonSerializable, InferenceTask, InferenceError\nfrom bentoml.service.artifacts.common import PickleArtifact\nfrom typing import List\nimport numpy as np\nimport pandas as pd\nimport sys\n\nsys.path.insert(0, 'Documents/models/resnet/')\nprint(sys.path)\n\[email protected](infer_pip_packages=True)\[email protected]([OnnxMlirModelArtifact('model'), PickleArtifact('labels')])\nclass ResNetPredict(BentoService):\n \"\"\"\n A simple prediction service exposing a Onnx-Mlir model\n \"\"\"\n\n def preprocess(self, input_data):\n # convert the input data into the float32 input\n img_data = np.stack(input_data).transpose(0, 3, 1, 2)\n\n #normalize\n mean_vec = np.array([0.485, 0.456, 0.406])\n stddev_vec = np.array([0.229, 0.224, 0.225])\n\n\n norm_img_data = np.zeros(img_data.shape).astype('float32')\n\n\n for i in range(img_data.shape[0]):\n for j in range(img_data.shape[1]):\n norm_img_data[i,j,:,:] = (img_data[i,j,:,:]/255 - mean_vec[j]) / stddev_vec[j]\n\n #add batch channel\n norm_img_data = norm_img_data.reshape(-1, 3, 224, 224).astype('float32')\n return norm_img_data\n\n def softmax(self, x):\n x = x.reshape(-1)\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum(axis=0)\n \n def post_process(self, raw_result):\n return self.softmax(np.array(raw_result)).tolist()\n\n @bentoml.api(input=ImageInput(), batch=True)\n def predict(self, image_ndarrays: List[np.ndarray]) -> List[str]:\n input_datas = self.preprocess(image_ndarrays)\n \n outputs = []\n for i in range(input_datas.shape[0]):\n raw_result = self.artifacts.model.run(input_datas[i:i+1])\n result = self.post_process(raw_result)\n idx = np.argmax(result)\n sort_idx = np.flip(np.squeeze(np.argsort(result)))\n\n # return top 5 labels\n outputs.append(self.artifacts.labels[sort_idx[:5]])\n return outputs\n\n ", "['Documents/models/resnet/', '/Users/andrewsius.ibm.com/Documents/pipeline_tests', '/Users/andrewsius.ibm.com/opt/anaconda3/lib/python38.zip', '/Users/andrewsius.ibm.com/opt/anaconda3/lib/python3.8', '/Users/andrewsius.ibm.com/opt/anaconda3/lib/python3.8/lib-dynload', '', '/Users/andrewsius.ibm.com/opt/anaconda3/lib/python3.8/site-packages', '/Users/andrewsius.ibm.com/Documents/git_hub/BentoML', '/Users/andrewsius.ibm.com/opt/anaconda3/lib/python3.8/site-packages/IPython/extensions', '/Users/andrewsius.ibm.com/.ipython']\n[2021-03-26 11:10:12,341] WARNING - Using BentoML installed in `editable` model, the local BentoML repository including all code changes will be packaged together with saved bundle created, under the './bundled_pip_dependencies' directory of the saved bundle.\n" ], [ "from resnetONNXM import ResNetPredict\nimport urllib.request\nimport sys\nimport json\nimport time\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\n\nimagenet_labels_url = \"https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json\"\nurllib.request.urlretrieve(imagenet_labels_url, filename=\"imagenet-simple-labels.json\")\n\ndef load_labels(path):\n with open(path) as f:\n data = json.load(f)\n return np.asarray(data)\n\nlabels = load_labels('imagenet-simple-labels.json')\n\nsys.path.insert(0, 'resnet/')\nsvc = ResNetPredict()\nsvc.pack('model', 'resnet/resnet50-v2-7.so')\nsvc.pack('labels', labels)\nlocation = svc.save()\nprint(location)", "[2021-03-26 11:12:14,772] WARNING - pip package requirement imageio already exist\n[2021-03-26 11:12:14,773] WARNING - pip package requirement numpy already exist\n[2021-03-26 11:12:15,948] INFO - Detected non-PyPI-released BentoML installed, copying local BentoML modulefiles to target saved bundle path..\n" ], [ "image = Image.open('dog.jpg')\nimage", "_____no_output_____" ], [ "!bentoml run ResNetPredict:latest predict --input-file dog.jpg", "[2021-03-26 11:12:31,081] INFO - Getting latest version ResNetPredict:20210326111214_C2BBFA\n[2021-03-26 11:12:31,727] WARNING - Using BentoML installed in `editable` model, the local BentoML repository including all code changes will be packaged together with saved bundle created, under the './bundled_pip_dependencies' directory of the saved bundle.\n[2021-03-26 11:12:31,743] WARNING - Saved BentoService bundle version mismatch: loading BentoService bundle create with BentoML version 0.11.0, but loading from BentoML version 0.11.0+35.g94948b2.dirty\n['/Users/andrewsius.ibm.com/Documents/models/mnist/', '/Users/andrewsius.ibm.com/bentoml/repository/ResNetPredict/20210326111214_C2BBFA/ResNetPredict', '/Users/andrewsius.ibm.com/bentoml/repository/ResNetPredict/20210326111214_C2BBFA', '/Users/andrewsius.ibm.com/opt/anaconda3/bin', '/Users/andrewsius.ibm.com/opt/anaconda3/lib/python38.zip', '/Users/andrewsius.ibm.com/opt/anaconda3/lib/python3.8', '/Users/andrewsius.ibm.com/opt/anaconda3/lib/python3.8/lib-dynload', '/Users/andrewsius.ibm.com/opt/anaconda3/lib/python3.8/site-packages', '/Users/andrewsius.ibm.com/Documents/git_hub/BentoML']\n/Users/andrewsius.ibm.com/bentoml/repository/ResNetPredict/20210326111214_C2BBFA/ResNetPredict/artifacts\n[2021-03-26 11:12:41,765] INFO - {'service_name': 'ResNetPredict', 'service_version': '20210326111214_C2BBFA', 'api': 'predict', 'task': {'data': {'uri': 'file:///Users/andrewsius.ibm.com/Documents/pipeline_tests/dog.jpg', 'name': 'dog.jpg'}, 'task_id': 'aa53e206-c1d3-4555-b76e-0f09a4441dd6', 'cli_args': ('--input-file', 'dog.jpg'), 'inference_job_args': {}}, 'result': {'data': '[\"Golden Retriever\", \"Labrador Retriever\", \"Sussex Spaniel\", \"Vizsla\", \"Otterhound\"]', 'http_status': 200, 'http_headers': (('Content-Type', 'application/json'),)}, 'request_id': 'aa53e206-c1d3-4555-b76e-0f09a4441dd6'}\n[\"Golden Retriever\", \"Labrador Retriever\", \"Sussex Spaniel\", \"Vizsla\", \"Otterhound\"]\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
ec546602119d5dfde9f966dffa8b98c032f2720d
11,312
ipynb
Jupyter Notebook
Detect Email Spams.ipynb
Msamaritan/Detect-Email-Spamming
39dc3c57ee607bcbf111929649a67783d5bf5ce8
[ "MIT" ]
null
null
null
Detect Email Spams.ipynb
Msamaritan/Detect-Email-Spamming
39dc3c57ee607bcbf111929649a67783d5bf5ce8
[ "MIT" ]
null
null
null
Detect Email Spams.ipynb
Msamaritan/Detect-Email-Spamming
39dc3c57ee607bcbf111929649a67783d5bf5ce8
[ "MIT" ]
null
null
null
21.383743
103
0.458451
[ [ [ "import string\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport nltk\nfrom nltk.corpus import stopwords", "_____no_output_____" ], [ "raw_data = pd.read_csv('emails.csv')\ndata = raw_data.copy()\ndata.head()", "_____no_output_____" ], [ "data.shape", "_____no_output_____" ], [ "data.isnull().sum()", "_____no_output_____" ], [ "data.drop_duplicates(inplace=True)\ndata.shape", "_____no_output_____" ] ], [ [ "### There were 33 duplicates, & now they are gone", "_____no_output_____" ] ], [ [ "nltk.download('stopwords')", "[nltk_data] Downloading package stopwords to\n[nltk_data] /home/msamaritan/nltk_data...\n[nltk_data] Unzipping corpora/stopwords.zip.\n" ], [ "def text_process(text):\n no_punc = [c for c in text if c not in string.punctuation]\n no_punc = ''.join(no_punc)\n \n final = [x for x in no_punc.split() if x.lower() not in stopwords.words('english')]\n return final", "_____no_output_____" ], [ "# Just the sample of the preprocessing\n\ndata['text'].head().apply(text_process)", "_____no_output_____" ], [ "from sklearn.feature_extraction.text import CountVectorizer", "_____no_output_____" ], [ "final_text = CountVectorizer(analyzer = text_process).fit_transform(data['text'])", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split as tts\n\na_train, a_test, z_train, z_test = tts(final_text, data['spam'], test_size=0.2, random_state=143)", "_____no_output_____" ], [ "print(a_train.shape, z_train.shape)\nprint(a_test.shape, z_test.shape)", "(4556, 37229) (4556,)\n(1139, 37229) (1139,)\n" ], [ "final_text.shape", "_____no_output_____" ], [ "from sklearn.naive_bayes import MultinomialNB", "_____no_output_____" ], [ "classifier = MultinomialNB().fit(a_train, z_train)", "_____no_output_____" ], [ "classifier.predict(a_train)", "_____no_output_____" ], [ "z_train.values", "_____no_output_____" ], [ "from sklearn.metrics import classification_report, accuracy_score, confusion_matrix", "_____no_output_____" ], [ "predictions = classifier.predict(a_train)\nprint(\"Classification Report \\n\\n\", classification_report(z_train,predictions))", "Classification Report \n\n precision recall f1-score support\n\n 0 1.00 1.00 1.00 3462\n 1 0.99 1.00 0.99 1094\n\n accuracy 1.00 4556\n macro avg 1.00 1.00 1.00 4556\nweighted avg 1.00 1.00 1.00 4556\n\n" ], [ "confusion_matrix(z_train, predictions)", "_____no_output_____" ], [ "accuracy_score(z_train, predictions)", "_____no_output_____" ] ], [ [ "## Our Model is $99.75$ % Accurate", "_____no_output_____" ] ], [ [ "pred = classifier.predict(a_test)", "_____no_output_____" ], [ "confusion_matrix(z_test, pred)", "_____no_output_____" ], [ "accuracy_score(z_test, pred)", "_____no_output_____" ] ], [ [ "## Our Model performs $98.9$ % in the unseen data", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
ec54765ab87e392ace3c6569dae719204a04f789
19,460
ipynb
Jupyter Notebook
notebooks/Dstripes/adversarial/basic/inference_adversarial/dense/AE/pokemonIAAE_Dense_reconst_1ellwlb_01psnr.ipynb
Fidan13/Generative_Models
2c700da53210a16f75c468ba521061106afa6982
[ "MIT" ]
null
null
null
notebooks/Dstripes/adversarial/basic/inference_adversarial/dense/AE/pokemonIAAE_Dense_reconst_1ellwlb_01psnr.ipynb
Fidan13/Generative_Models
2c700da53210a16f75c468ba521061106afa6982
[ "MIT" ]
null
null
null
notebooks/Dstripes/adversarial/basic/inference_adversarial/dense/AE/pokemonIAAE_Dense_reconst_1ellwlb_01psnr.ipynb
Fidan13/Generative_Models
2c700da53210a16f75c468ba521061106afa6982
[ "MIT" ]
null
null
null
22.445213
181
0.564902
[ [ [ "# Settings", "_____no_output_____" ] ], [ [ "%env TF_KERAS = 1\nimport os\nsep_local = os.path.sep\n\nimport sys\nsys.path.append('..'+sep_local+'..')\nprint(sep_local)", "_____no_output_____" ], [ "os.chdir('..'+sep_local+'..'+sep_local+'..'+sep_local+'..'+sep_local+'..')\nprint(os.getcwd())", "_____no_output_____" ], [ "import tensorflow as tf\nprint(tf.__version__)", "_____no_output_____" ] ], [ [ "# Dataset loading", "_____no_output_____" ] ], [ [ "dataset_name='Dstripes'", "_____no_output_____" ], [ "from training.generators.file_image_generator import create_image_lists, get_generators", "_____no_output_____" ], [ "imgs_list = create_image_lists(\n image_dir=images_dir, \n validation_pct=validation_percentage, \n valid_imgae_formats=valid_format\n)", "_____no_output_____" ], [ "inputs_shape= image_size=(200, 200, 3)\nbatch_size = 32\nlatents_dim = 32\nintermediate_dim = 50", "_____no_output_____" ], [ "training_generator, testing_generator = get_generators(\n images_list=imgs_list, \n image_dir=images_dir, \n image_size=image_size, \n batch_size=batch_size, \n class_mode=None\n)", "_____no_output_____" ], [ "import tensorflow as tf", "_____no_output_____" ], [ "train_ds = tf.data.Dataset.from_generator(\n lambda: training_generator, \n output_types=tf.float32 ,\n output_shapes=tf.TensorShape((batch_size, ) + image_size)\n)\n\ntest_ds = tf.data.Dataset.from_generator(\n lambda: testing_generator, \n output_types=tf.float32 ,\n output_shapes=tf.TensorShape((batch_size, ) + image_size)\n)", "_____no_output_____" ], [ "_instance_scale=1.0\nfor data in train_ds:\n _instance_scale = float(data[0].numpy().max())\n break", "_____no_output_____" ], [ "_instance_scale", "_____no_output_____" ], [ "import numpy as np\nfrom collections.abc import Iterable", "_____no_output_____" ], [ "if isinstance(inputs_shape, Iterable):\n _outputs_shape = np.prod(inputs_shape)", "_____no_output_____" ], [ "_outputs_shape", "_____no_output_____" ] ], [ [ "# Model's Layers definition", "_____no_output_____" ] ], [ [ "enc_lays = [tf.keras.layers.Dense(units=intermediate_dim, activation='relu'),\n tf.keras.layers.Dense(units=intermediate_dim, activation='relu'),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(units=latents_dim)]\n\ndec_lays = [tf.keras.layers.Dense(units=latents_dim, activation='relu'),\n tf.keras.layers.Dense(units=intermediate_dim, activation='relu'),\n tf.keras.layers.Dense(units=_outputs_shape),\n tf.keras.layers.Reshape(inputs_shape)]", "_____no_output_____" ] ], [ [ "# Model definition", "_____no_output_____" ] ], [ [ "model_name = dataset_name+'IAAE_Dense_reconst_1ell_01psnr'\nexperiments_dir='experiments'+sep_local+model_name", "_____no_output_____" ], [ "from training.adversarial_basic.inference_adversarial.autoencoders.AAE import AAE as AE", "_____no_output_____" ], [ "inputs_shape=image_size", "_____no_output_____" ], [ "variables_params = \\\n[\n {\n 'name': 'inference', \n 'inputs_shape':inputs_shape,\n 'outputs_shape':latents_dim,\n 'layers': enc_lays\n }\n\n ,\n \n {\n 'name': 'generative', \n 'inputs_shape':latents_dim,\n 'outputs_shape':inputs_shape,\n 'layers':dec_lays\n }\n]", "_____no_output_____" ], [ "from utils.data_and_files.file_utils import create_if_not_exist", "_____no_output_____" ], [ "_restore = os.path.join(experiments_dir, 'var_save_dir')", "_____no_output_____" ], [ "create_if_not_exist(_restore)\n_restore", "_____no_output_____" ], [ "#to restore trained model, set filepath=_restore", "_____no_output_____" ], [ "from statistical.basic_adversarial_losses import \\\n create_inference_discriminator_real_losses, \\\n create_inference_discriminator_fake_losses, \\\n create_inference_generator_fake_losses\n\ninference_discriminator_losses = {\n 'inference_discriminator_real_outputs': create_inference_discriminator_real_losses,\n 'inference_discriminator_fake_outputs': create_inference_discriminator_fake_losses,\n 'inference_generator_fake_outputs': create_inference_generator_fake_losses,\n}", "_____no_output_____" ], [ "ae = AE( \n name=model_name,\n latents_dim=latents_dim,\n batch_size=batch_size,\n variables_params=variables_params, \n filepath=None\n )", "_____no_output_____" ], [ "from evaluation.quantitive_metrics.peak_signal_to_noise_ratio import prepare_psnr\nfrom statistical.losses_utilities import similarty_to_distance\nfrom statistical.ae_losses import expected_loglikelihood_with_lower_bound as ellwlb", "_____no_output_____" ], [ "discr2gen_rate = 0.001\ngen2trad_rate = 0.1\n\nae.compile(\n loss={'x_logits': lambda x_true, x_logits: ellwlb(x_true, x_logits)+ 0.1*similarity_to_distance(prepare_psnr([ae.batch_size]+ae.get_inputs_shape()))(x_true, x_logits)},\n adversarial_losses=inference_discriminator_losses,\n adversarial_weights={'generator_weight': gen2trad_rate, 'discriminator_weight': discr2gen_rate}\n)", "_____no_output_____" ] ], [ [ "# Callbacks", "_____no_output_____" ] ], [ [ "\nfrom training.callbacks.sample_generation import SampleGeneration\nfrom training.callbacks.save_model import ModelSaver", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "es = tf.keras.callbacks.EarlyStopping(\n monitor='loss', \n min_delta=1e-12, \n patience=12, \n verbose=1, \n restore_best_weights=False\n)", "_____no_output_____" ], [ "ms = ModelSaver(filepath=_restore)", "_____no_output_____" ], [ "csv_dir = os.path.join(experiments_dir, 'csv_dir')\ncreate_if_not_exist(csv_dir)\ncsv_dir = os.path.join(csv_dir, ae.name+'.csv')\ncsv_log = tf.keras.callbacks.CSVLogger(csv_dir, append=True)\ncsv_dir", "_____no_output_____" ], [ "image_gen_dir = os.path.join(experiments_dir, 'image_gen_dir')\ncreate_if_not_exist(image_gen_dir)", "_____no_output_____" ], [ "sg = SampleGeneration(latents_shape=latents_dim, filepath=image_gen_dir, gen_freq=5, save_img=True, gray_plot=False)", "_____no_output_____" ] ], [ [ "# Model Training", "_____no_output_____" ] ], [ [ "ae.fit(\n x=train_ds,\n input_kw=None,\n steps_per_epoch=int(1e4),\n epochs=int(1e6), \n verbose=2,\n callbacks=[ es, ms, csv_log, sg],\n workers=-1,\n use_multiprocessing=True,\n validation_data=test_ds,\n validation_steps=int(1e4)\n)", "_____no_output_____" ] ], [ [ "# Model Evaluation", "_____no_output_____" ], [ "## inception_score", "_____no_output_____" ] ], [ [ "from evaluation.generativity_metrics.inception_metrics import inception_score", "_____no_output_____" ], [ "is_mean, is_sigma = inception_score(ae, tolerance_threshold=1e-6, max_iteration=200)\nprint(f'inception_score mean: {is_mean}, sigma: {is_sigma}')", "_____no_output_____" ] ], [ [ "## Frechet_inception_distance", "_____no_output_____" ] ], [ [ "from evaluation.generativity_metrics.inception_metrics import frechet_inception_distance", "_____no_output_____" ], [ "fis_score = frechet_inception_distance(ae, training_generator, tolerance_threshold=1e-6, max_iteration=10, batch_size=32)\nprint(f'frechet inception distance: {fis_score}')", "_____no_output_____" ] ], [ [ "## perceptual_path_length_score", "_____no_output_____" ] ], [ [ "from evaluation.generativity_metrics.perceptual_path_length import perceptual_path_length_score", "_____no_output_____" ], [ "ppl_mean_score = perceptual_path_length_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200, batch_size=32)\nprint(f'perceptual path length score: {ppl_mean_score}')", "_____no_output_____" ] ], [ [ "## precision score", "_____no_output_____" ] ], [ [ "from evaluation.generativity_metrics.precision_recall import precision_score", "_____no_output_____" ], [ "_precision_score = precision_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)\nprint(f'precision score: {_precision_score}')", "_____no_output_____" ] ], [ [ "## recall score", "_____no_output_____" ] ], [ [ "from evaluation.generativity_metrics.precision_recall import recall_score", "_____no_output_____" ], [ "_recall_score = recall_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)\nprint(f'recall score: {_recall_score}')", "_____no_output_____" ] ], [ [ "# Image Generation", "_____no_output_____" ], [ "## image reconstruction", "_____no_output_____" ], [ "### Training dataset", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "from training.generators.image_generation_testing import reconstruct_from_a_batch", "_____no_output_____" ], [ "from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'reconstruct_training_images_like_a_batch_dir')\ncreate_if_not_exist(save_dir)\n\nreconstruct_from_a_batch(ae, training_generator, save_dir)", "_____no_output_____" ], [ "from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'reconstruct_testing_images_like_a_batch_dir')\ncreate_if_not_exist(save_dir)\n\nreconstruct_from_a_batch(ae, testing_generator, save_dir)", "_____no_output_____" ] ], [ [ "## with Randomness", "_____no_output_____" ] ], [ [ "from training.generators.image_generation_testing import generate_images_like_a_batch", "_____no_output_____" ], [ "from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'generate_training_images_like_a_batch_dir')\ncreate_if_not_exist(save_dir)\n\ngenerate_images_like_a_batch(ae, training_generator, save_dir)", "_____no_output_____" ], [ "from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'generate_testing_images_like_a_batch_dir')\ncreate_if_not_exist(save_dir)\n\ngenerate_images_like_a_batch(ae, testing_generator, save_dir)", "_____no_output_____" ] ], [ [ "### Complete Randomness", "_____no_output_____" ] ], [ [ "from training.generators.image_generation_testing import generate_images_randomly", "_____no_output_____" ], [ "from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'random_synthetic_dir')\ncreate_if_not_exist(save_dir)\n\ngenerate_images_randomly(ae, save_dir)", "_____no_output_____" ], [ "from training.generators.image_generation_testing import interpolate_a_batch", "_____no_output_____" ], [ "from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'interpolate_dir')\ncreate_if_not_exist(save_dir)\n\ninterpolate_a_batch(ae, testing_generator, save_dir)", "100%|██████████| 15/15 [00:00<00:00, 19.90it/s]\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", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
ec54775a66f1fa7afb8300fd023261f571d30174
2,999
ipynb
Jupyter Notebook
scikit-learn-official-examples/decomposition/plot_incremental_pca.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
1
2019-05-10T09:16:23.000Z
2019-05-10T09:16:23.000Z
scikit-learn-official-examples/decomposition/plot_incremental_pca.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
null
null
null
scikit-learn-official-examples/decomposition/plot_incremental_pca.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
1
2019-05-10T09:17:28.000Z
2019-05-10T09:17:28.000Z
55.537037
1,221
0.621874
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\n\n# Incremental PCA\n\n\nIncremental principal component analysis (IPCA) is typically used as a\nreplacement for principal component analysis (PCA) when the dataset to be\ndecomposed is too large to fit in memory. IPCA builds a low-rank approximation\nfor the input data using an amount of memory which is independent of the\nnumber of input data samples. It is still dependent on the input data features,\nbut changing the batch size allows for control of memory usage.\n\nThis example serves as a visual check that IPCA is able to find a similar\nprojection of the data to PCA (to a sign flip), while only processing a\nfew samples at a time. This can be considered a \"toy example\", as IPCA is\nintended for large datasets which do not fit in main memory, requiring\nincremental approaches.\n\n\n", "_____no_output_____" ] ], [ [ "print(__doc__)\n\n# Authors: Kyle Kastner\n# License: BSD 3 clause\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.decomposition import PCA, IncrementalPCA\n\niris = load_iris()\nX = iris.data\ny = iris.target\n\nn_components = 2\nipca = IncrementalPCA(n_components=n_components, batch_size=10)\nX_ipca = ipca.fit_transform(X)\n\npca = PCA(n_components=n_components)\nX_pca = pca.fit_transform(X)\n\ncolors = ['navy', 'turquoise', 'darkorange']\n\nfor X_transformed, title in [(X_ipca, \"Incremental PCA\"), (X_pca, \"PCA\")]:\n plt.figure(figsize=(8, 8))\n for color, i, target_name in zip(colors, [0, 1, 2], iris.target_names):\n plt.scatter(X_transformed[y == i, 0], X_transformed[y == i, 1],\n color=color, lw=2, label=target_name)\n\n if \"Incremental\" in title:\n err = np.abs(np.abs(X_pca) - np.abs(X_ipca)).mean()\n plt.title(title + \" of iris dataset\\nMean absolute unsigned error \"\n \"%.6f\" % err)\n else:\n plt.title(title + \" of iris dataset\")\n plt.legend(loc=\"best\", shadow=False, scatterpoints=1)\n plt.axis([-4, 4, -1.5, 1.5])\n\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ] ]
ec547d0d85b4fb0ad4836604058d49502ce4b9f3
5,207
ipynb
Jupyter Notebook
ipynb/Germany-Thüringen-LK-Unstrut-Hainich-Kreis.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-Thüringen-LK-Unstrut-Hainich-Kreis.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-Thüringen-LK-Unstrut-Hainich-Kreis.ipynb
oscovida/oscovida.github.io
c74d6da79feda1b5ccce107ad3acd48cf0e74c1c
[ "CC-BY-4.0" ]
4
2020-04-20T13:24:45.000Z
2021-01-29T11:12:12.000Z
31.179641
201
0.531208
[ [ [ "# Germany: LK Unstrut-Hainich-Kreis (Thüringen)\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-Thüringen-LK-Unstrut-Hainich-Kreis.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 Unstrut-Hainich-Kreis\", weeks=5);", "_____no_output_____" ], [ "overview(country=\"Germany\", subregion=\"LK Unstrut-Hainich-Kreis\");", "_____no_output_____" ], [ "compare_plot(country=\"Germany\", subregion=\"LK Unstrut-Hainich-Kreis\", dates=\"2020-03-15:\");\n", "_____no_output_____" ], [ "# load the data\ncases, deaths = germany_get_region(landkreis=\"LK Unstrut-Hainich-Kreis\")\n\n# get population of the region for future normalisation:\ninhabitants = population(country=\"Germany\", subregion=\"LK Unstrut-Hainich-Kreis\")\nprint(f'Population of country=\"Germany\", subregion=\"LK Unstrut-Hainich-Kreis\": {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-Thüringen-LK-Unstrut-Hainich-Kreis.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" ] ]
ec548c8327aa90bfda8f577e5498bc33b1590c74
195,587
ipynb
Jupyter Notebook
hw4/HW4_Tong.ipynb
Grayson3455/numpde
08709a2e3e94b856c5d3c4d41a01a9098a856b01
[ "BSD-2-Clause" ]
null
null
null
hw4/HW4_Tong.ipynb
Grayson3455/numpde
08709a2e3e94b856c5d3c4d41a01a9098a856b01
[ "BSD-2-Clause" ]
null
null
null
hw4/HW4_Tong.ipynb
Grayson3455/numpde
08709a2e3e94b856c5d3c4d41a01a9098a856b01
[ "BSD-2-Clause" ]
null
null
null
447.567506
39,224
0.927086
[ [ [ "import numpy as np\nimport pandas\nfrom fractions import Fraction\nfrom matplotlib import pyplot as plt\nfrom numpy import linalg as LA", "_____no_output_____" ] ], [ [ "# HW4-Adaptive control of the RK method", "_____no_output_____" ], [ "## Part0: Problem set\n", "_____no_output_____" ], [ "* Implement an explicit Runge-Kutta integrator that takes an initial time step $h_0$ and an error tolerance $\\epsilon$.\n* You can use the Bogacki-Shampine method or any other method with an embedded error estimate.\n* A step should be rejected if the local truncation error exceeds the tolerance.\n* Test your method on the nonlinear equation\n$$ \\begin{bmatrix} \\dot u_0 \\\\ \\dot u_1 \\end{bmatrix} = \\begin{bmatrix} u_1 \\\\ k (1-u_0^2) u_1 - u_0 \\end{bmatrix} $$\nfor $k=2$, $k=5$, and $k=20$.\n* Make a work-precision diagram for your adaptive method and for constant step sizes.\n* State your conclusions or ideas (in a README, or Jupyter notebook) about appropriate (efficient, accurate, reliable) methods for this type of problem.", "_____no_output_____" ], [ "## Part1: Discretization with error estimate embedded", "_____no_output_____" ], [ "The first method to be used is the Bogacki-Shampine method. For a given time step size $h$ and first order differential equation $y'= f(t,y)$, it is a Runge-Kutta method with global order $3$ and stage $4$. In addition, the forth stage is an embedded second-order evalution which will be executed per time step such that an adaptive control could be implemented during the computation. <br>\n\nThe Bogacki-Shampine method$^{[1]}$ of time step $t_{n+1}$ as: <br>\n$$\\begin{split}\nK_1 &= f(t_n,y_n) \\\\\nK_2 &= f(t_n+\\frac{1}{2}h_n,y_n + \\frac{1}{2}h_n K_1) \\\\\nK_3 &= f(t_n+\\frac{3}{4}h_n,y_n + \\frac{3}{4}h_n K_2) \\\\\nK_4 &= f(t_n+h_n,y_{n+1}) \\\\\n\\end{split}$$\n\nwhere <br> \n$$y_{n+1} = y_n + \\frac{4}{9}h_n(\\frac{1}{2}K_1 + \\frac{3}{4}K_2 + K3)$$\nAnd the second-order evaluation as: <br>\n$$z_{n+1} = y_n + \\frac{1}{3}h_n(\\frac{7}{8}K_1 + \\frac{3}{4}K_2 + K_3 + \\frac{3}{8}K_4)$$ <br>\n\nIn adaptive control, we choose $\\epsilon = 10^{-5}$ and if the local truncation error $e_{\\text{loc}}(h) = \\lVert h (b - \\tilde b)^T f(Y) \\rVert$ exceeds the $\\epsilon$, we reject the current time step and compute it again by decreasing the time step size as $h = 0.8 h_*$, for a given method order $p$, the $h_*$ is computed by: $$ h_* = \\left( \\frac{\\epsilon}{e_{\\text{loc}}(h) / h^p} \\right)^{1/p} . $$\n\nFuthermore, in adaptive method, if a time step size is rejected once, then for the Bogacki-Shampine method, 3 more function evaluations is needed. Thus, when counting the total function evaluations for the adaptive method, additional function evaluations $\\text{f_eval}$ should be added to the total number. <br>\n\nThe code for constructing the adaptive method as:", "_____no_output_____" ] ], [ [ "'''the code of this homework is based on the FDTransient notebook in the\n class and some changes has been made\n'''\ndef BS3_bct(): # the Butcher Table of Bogacki-Shampine method\n A = np.array ([[0, 0, 0, 0],\n [1/2, 0, 0, 0],\n [0, 3/4, 0, 0],\n [2/9, 1/3, 4/9, 0]]) #table of coefficients\n \n b = np.array ([[2/9, 1/3, 4/9, 0],\n [7/24, 1/4, 1/3, 1/8]]) # vector of completion weights\n return A, b[0,:], b[1,:] # one for solving, one for error control\n\n\ndef RHS(t,u,k): #the RHS funciton, independent of t\n return np.array([[u[1]], [k*(1-u[0]**2)*u[1] - u[0]]])\n \n\ndef adp_RK(u0, BT, tfinal, h, k, p, e, apt): #u0 is the initial value , p is the order of the method, e is the tolerence\n A, b1, b2 = BT\n c = np.sum(A, axis=1) # vector of abscissa\n s = len(c) # number of stages\n u = u0.copy()\n u_e = u0.copy() # initialize the error control vector\n t = 0\n hist = [(t,u0)] # the initial status pair\n \n f_eval = 0 # to count the additional function evaluations in the adaptive control\n \n ########__decide the final step size__########\n while t < tfinal:\n if tfinal - t < 1.01*h:\n h = tfinal - t\n tnext = tfinal\n else:\n tnext = t + h\n h = min(h, tfinal - t)\n ##############################################\n\n fY = np.zeros((len(u0), s)) #the approximation matrix at t = t + h, col for each stage\n for i in range(s): # i = 0,1,2...s-1\n Yi = u.copy() \n for j in range(i):\n Yi += h * A[i,j] * fY[:,j]\n fY[:,i] = RHS(t + h*c[i], Yi, k).ravel()\n \n if apt==False: # for uniform time steps\n u += h * fY @ b1\n t = tnext\n hist.append((t, u.copy()))\n \n \n else: # for adaptive time steps\n e_loc = LA.norm (h * fY @ (b1-b2), np.inf)\n c_loc = e_loc/(h**p)\n h_star = np.power(e/c_loc,1/p)\n #print(e_loc-e,h,t)\n if (e_loc>=e) and (h_star>=0.001):\n h = h_star* 0.8 # Safe factor = 0.8\n f_eval = f_eval + 3 # if a step is rejected, 3 more evals needed\n \n else:\n u += h * fY @ b1\n t = tnext\n hist.append((t, u.copy())) \n \n #print(f_eval) \n return hist, f_eval", "_____no_output_____" ], [ "for k in [2,5,20]:\n u0 = np.array([1.0, 1.0]) # the initial value\n h = 0.1 # the time step size\n hist,f_eval = adp_RK(u0, BS3_bct(), 30, h, k, 3, 0.00001, True)\n######____plotting___#########\n plt.figure()\n times = [t for t,u in hist]\n plt.plot(times, [u for t,u in hist], 'x')\n plt.title(\"k = \" + str(k))\n ", "_____no_output_____" ] ], [ [ "## Part2: Higher order study", "_____no_output_____" ], [ "In this section, the second numerical method studied is the Runge–Kutta–Fehlberg method$^{[2]}$, a 6-stage, fifth-order technique with error estimate embedded as well. The Butcher table of this method is defined as: <br>\n\n$$ \\left[ \\begin{array}{c|cccccc}\n0 & 0 & 0 & 0 & 0 &0 &0\\\\\n\\frac 1 4 & \\frac 1 4 & 0 & 0 & 0 & 0 &0 \\\\\n\\frac 3 8 & \\frac 3 {32} & \\frac 9 {32} & 0 & 0 & 0 &0\\\\\n\\frac {12} {13} & \\frac {1932}{2197} & \\frac{-7200}{2197} & \\frac{7296}{2197} & 0 & 0 &0 \\\\\n1 & \\frac {439}{216} & -8 & \\frac{3680}{513} & \\frac{-845}{4104} & 0 &0\\\\\n\\frac {1} {2} & \\frac {-8}{27} & 2 & \\frac{-3544}{2565} & \\frac{1859}{4104} & \\frac{-11}{40} &0\\\\\n\\hline\nA: & \\frac {16} {135} & 0 & \\frac {6656} {12825} & \\frac {28561} {56430} &\\frac{-9}{50} &\\frac{2}{55}\\\\\nB: & \\frac {25} {216} & 0 & \\frac {1408} {2565} & \\frac {2797} {4104} &\\frac{-1}{5} &0\n\\end{array} \\right] . $$ <br>\nwhere A and B lead to the accuracy order of $5$ and $4$, respectively. <br>\n<br>\nThe code for constructing the Runge–Kutta–Fehlberg method with adaptive step control embedded as:", "_____no_output_____" ] ], [ [ "def RKF():\n dframe = pandas.read_html('https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta%E2%80%93Fehlberg_method')[0]\n# Clean up unicode minus sign, NaN, and convert to float\n dfloat = dframe.applymap(lambda s: s.replace('−', '-') if isinstance(s, str) else s) \\\n .fillna(0).applymap(Fraction).astype(float)\n\n# Extract the Butcher table\n darray = np.array(dfloat)\n A_RKF = darray[:6,2:]\n b_RKF = darray[6:,2:]\n return A_RKF , b_RKF[0,:] , b_RKF[1,:]", "_____no_output_____" ], [ "for k in [2,5,20]:\n u0 = np.array([1.0, 1.0]) # the initial value\n h = 0.1 # the time step size\n hist,f_eval = adp_RK(u0, RKF(), 30, h, k, 5, 0.00001, True)\n######____plotting___#########\n plt.figure()\n times = [t for t,u in hist]\n plt.plot(times, [u for t,u in hist], 'x')\n plt.title(\"k = \" + str(k))", "_____no_output_____" ] ], [ [ "From the results of the higher order test(5th order Runge–Kutta–Fehlberg), compared to the 3rd-order Bogacki-Shampine method, we can see the adaptive control renders the higher order method with relatively \"coarse\" time discretization. Thus, a faster convergence rate will be achieved.", "_____no_output_____" ], [ "## Part3: Work-Precision test for nonlinear pronlem", "_____no_output_____" ], [ "Clearly, the work-precision test needs a relatively accurate solution for measuring the error. Thus, we use the computation results of the 5th order Runge–Kutta–Fehlberg method with a fine time discretization as $h = 0.001$ as the reference solution. \n<br>\n\nIn the test, the performace of the adaptive control applied to the 3rd-order Bogacki-Shampine method will be studied.<br>\n\nIn the code, the error estimate functions with or without the adaptive error control are denoted as $\\text{error_apt()}$ and $\\text{error_wo_apt()}$, respectively. In addition, note that in adaptive control, the time step size $h$ can not be less than the $0.001$, which we have already seen as the fine step size. <br>", "_____no_output_____" ] ], [ [ "u0 = np.array([1.0, 1.0]) # the initial value\nt_final = 5\ndef error_wo_apt(exact, h, k):\n err = [] # list for error storage\n hist,f_eval = adp_RK(u0, BS3_bct(), t_final, h , k, 3, 0.00001, False) # choose the constant timestep as h=hs\n for j in range(1,len(hist)):\n t = hist[j][0] #current t\n for jj in range(1,len(exact)):\n if t == round(exact[jj][0],4):\n err.append((LA.norm(exact[jj][1]-hist[j][1],np.inf)))\n return max(err) # the global error estimate\n\ndef error_apt(exact, h, k):\n err_apt = [] # list for error storage\n hist,f_eval = adp_RK(u0, BS3_bct(), t_final, h , k, 3, 0.00001, True)\n for j in range(1,len(hist)):\n t = hist[j][0] #current t\n for jj in range(1,len(exact)):\n if t == round(exact[jj][0],4):\n err_apt.append((LA.norm(exact[jj][1]-hist[j][1],np.inf)))\n return max(err_apt), f_eval # additional function evaluations returned\n\nfor k in [2,5,20]:\n exact,_ = adp_RK(u0, RKF(), t_final, 0.001, k, 5, 0.00001, False) # the reference exact solution\n hs = np.logspace(-2.4, -1.4, 10) # fixed time steps hs \n error_BS3_woapt = [error_wo_apt(exact, hx, k) for hx in hs]\n error_BS3_apt = [error_apt(exact, hx, k)[0] for hx in hs] \n f_eval = [error_apt(exact, hx, k)[1] for hx in hs] \n plt.figure()\n plt.loglog(t_final*3/hs, error_BS3_woapt, 'o', label = 'Without adaptive control')\n plt.loglog(t_final*3/hs + f_eval, error_BS3_apt, 'x', label = 'With adaptive control')\n plt.title('Error vs cost with k=' + str(k))\n plt.ylabel('Error')\n plt.xlabel('function evaluations')\n plt.grid()\n plt.legend(loc='upper right');", "_____no_output_____" ] ], [ [ "According to the figures above, we can see for all different values of k, fewer(or relatively equal when $k$=2) function evaluations needed for the adaptive control method in the sense of reaching a specific error bound. Besides, as the coefficient $k$ increases, an adaptive control embedding is even more beneficial. Thus, for the similar nonlinear equations, a fixed time step method could be applied when $k$ is small, while for larger $k$, it is better to implement the adaptive error control.", "_____no_output_____" ], [ "[1]: Bogacki–Shampine method, Wikipedia, https://en.wikipedia.org/wiki/Bogacki%E2%80%93Shampine_method <br>\n[2]: Runge–Kutta–Fehlberg method,Wikipedia, https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta%E2%80%93Fehlberg_method", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec5490815333fe8311d283f6671a76f579e23574
141,471
ipynb
Jupyter Notebook
Making_Data_Management.ipynb
fcollonval/coursera_data_visualization
7a25377a6e93e0cce33d6897d3db48e6617dde9c
[ "MIT" ]
null
null
null
Making_Data_Management.ipynb
fcollonval/coursera_data_visualization
7a25377a6e93e0cce33d6897d3db48e6617dde9c
[ "MIT" ]
null
null
null
Making_Data_Management.ipynb
fcollonval/coursera_data_visualization
7a25377a6e93e0cce33d6897d3db48e6617dde9c
[ "MIT" ]
1
2021-02-17T00:50:33.000Z
2021-02-17T00:50:33.000Z
41.535819
257
0.362223
[ [ [ "# Assignment: Making Data Management Decisions - Python\n\nFollowing is the Python program I wrote to fulfill the third assignment of the [Data Management and Visualization online course]( https://www.coursera.org/learn/data-visualization/).\n\nI decided to use [Jupyter Notebook](http://nbviewer.jupyter.org/github/ipython/ipython/blob/3.x/examples/Notebook/Index.ipynb) as it is a pretty way to write code and present results.\n\n## Research question\n\nUsing the [Gapminder database](http://www.gapminder.org/), I would like to see if an increasing Internet usage results in an increasing suicide rate. A study shows that other factors like unemployment could have a great impact.\n\nSo for this third assignment, the three following variables will be analyzed:\n\n- Internet Usage Rate (per 100 people)\n- Suicide Rate (per 100 000 people)\n- Unemployment Rate (% of the population of age 15+)\n\n\n## Data management\n\nFor the question, I'm interested in the countries for which data are missing will be discarded. As missing data in Gapminder database are replace directly by `NaN` no special data treatment is needed.", "_____no_output_____" ] ], [ [ "# Load a useful Python libraries for handling data\nimport pandas as pd\nimport numpy as np\nfrom IPython.display import Markdown, display", "_____no_output_____" ], [ "# Read the data\ndata_filename = r'gapminder.csv'\ndata = pd.read_csv(data_filename, low_memory=False)\ndata = data.set_index('country')", "_____no_output_____" ] ], [ [ "General information on the Gapminder data", "_____no_output_____" ] ], [ [ "display(Markdown(\"Number of countries: {}\".format(len(data))))\ndisplay(Markdown(\"Number of variables: {}\".format(len(data.columns))))", "_____no_output_____" ], [ "# Convert interesting variables in numeric format\nfor variable in ('internetuserate', 'suicideper100th', 'employrate'):\n data[variable] = pd.to_numeric(data[variable], errors='coerce')", "_____no_output_____" ] ], [ [ "\nBut the unemployment rate is not provided directly. In the database, the employment rate (% of the popluation) is available. So the unemployement rate will be computed as `100 - employment rate`:", "_____no_output_____" ] ], [ [ "data['unemployrate'] = 100. - data['employrate']", "_____no_output_____" ] ], [ [ "The first records of the data restricted to the three analyzed variables are:", "_____no_output_____" ] ], [ [ "subdata = data[['internetuserate', 'suicideper100th', 'unemployrate']]\nsubdata.head(10)", "_____no_output_____" ] ], [ [ "## Data analysis\n\nWe will now have a look at the frequencies of the variables after grouping them as all three are continuous variables. I will group the data in intervals using the `cut` function.\n\n### Internet use rate frequencies", "_____no_output_____" ] ], [ [ "display(Markdown(\"Internet Use Rate (min, max) = ({0:.2f}, {1:.2f})\".format(subdata['internetuserate'].min(), subdata['internetuserate'].max())))", "_____no_output_____" ], [ "internetuserate_bins = pd.cut(subdata['internetuserate'], \n bins=np.linspace(0, 100., num=21))\n\ncounts1 = internetuserate_bins.value_counts(sort=False, dropna=False)\npercentage1 = internetuserate_bins.value_counts(sort=False, normalize=True, dropna=False)\ndata_struct = {\n 'Counts' : counts1,\n 'Cumulative counts' : counts1.cumsum(),\n 'Percentages' : percentage1,\n 'Cumulative percentages' : percentage1.cumsum()\n}\n\ninternetrate_summary = pd.DataFrame(data_struct)\ninternetrate_summary.index.name = 'Internet use rate (per 100 people)'\n(internetrate_summary[['Counts', 'Cumulative counts', 'Percentages', 'Cumulative percentages']]\n .style.set_precision(3)\n .set_properties(**{'text-align':'right'}))", "_____no_output_____" ] ], [ [ "### Suicide per 100,000 people frequencies", "_____no_output_____" ] ], [ [ "display(Markdown(\"Suicide per 100,000 people (min, max) = ({:.2f}, {:.2f})\".format(subdata['suicideper100th'].min(), subdata['suicideper100th'].max())))", "_____no_output_____" ], [ "suiciderate_bins = pd.cut(subdata['suicideper100th'], \n bins=np.linspace(0, 40., num=21))\n\ncounts2 = suiciderate_bins.value_counts(sort=False, dropna=False)\npercentage2 = suiciderate_bins.value_counts(sort=False, normalize=True, dropna=False)\ndata_struct = {\n 'Counts' : counts2,\n 'Cumulative counts' : counts2.cumsum(),\n 'Percentages' : percentage2,\n 'Cumulative percentages' : percentage2.cumsum()\n}\n\nsuiciderate_summary = pd.DataFrame(data_struct)\nsuiciderate_summary.index.name = 'Suicide (per 100 000 people)'\n(suiciderate_summary[['Counts', 'Cumulative counts', 'Percentages', 'Cumulative percentages']]\n .style.set_precision(3)\n .set_properties(**{'text-align':'right'}))", "_____no_output_____" ] ], [ [ "### Unemployment rate frequencies", "_____no_output_____" ] ], [ [ "display(Markdown(\"Unemployment rate (min, max) = ({0:.2f}, {1:.2f})\".format(subdata['unemployrate'].min(), subdata['unemployrate'].max())))", "_____no_output_____" ], [ "unemployment_bins = pd.cut(subdata['unemployrate'], \n bins=np.linspace(0, 100., num=21))\n\n\ncounts3 = unemployment_bins.value_counts(sort=False, dropna=False)\npercentage3 = unemployment_bins.value_counts(sort=False, normalize=True, dropna=False)\ndata_struct = {\n 'Counts' : counts3,\n 'Cumulative counts' : counts3.cumsum(),\n 'Percentages' : percentage3,\n 'Cumulative percentages' : percentage3.cumsum()\n}\n\nunemployment_summary = pd.DataFrame(data_struct)\nunemployment_summary.index.name = 'Unemployement rate (% population age 15+)'\n(unemployment_summary[['Counts', 'Cumulative counts', 'Percentages', 'Cumulative percentages']]\n .style.set_precision(3)\n .set_properties(**{'text-align':'right'}))", "_____no_output_____" ] ], [ [ "## Summary\n\nThe Gapminder data based provides information for 213 countries. \n\nAs the unemployment rate is not provided directly in the database, it was computed as `100 - employment rate`.\n\nThe distributions of the variables are as follow:\n\n- Internet Use Rate per 100 people\n * Data missing for 21 countries\n * Rate ranges from 0.21 to 95.64\n * The majority of the countries (64%) have a rate below 50\n- Suicide Rate per 100 000\n * Data missing for 22 countries\n * Rate ranges from 0.2 to 35.75\n * The rate is more often between 4 and 12\n- Unemployment Rate for age 15+\n * Data missing for 35 countries\n * Rate ranges from 16.8 to 68\n * For the majority of the countries the rate lies below 45\n\nFrom those data, I was surprised that so few people have access to the internet especially now that smartphones are cheap.\n\nAnother astonishing facts is the high unemployment rate, I was expected much less; especially in so called developped countries. But I presume that long school time and retirement can explain those high values as people of age 15+ are considered here.", "_____no_output_____" ], [ "> If you are interested by the subject, follow me on [Tumblr](http://fcollonval.tumblr.com/).", "_____no_output_____" ] ] ]
[ "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" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
ec54a28f9a71e687d20315c3b24e4433a9d15b5f
333,809
ipynb
Jupyter Notebook
signals/sp-m1-5-interpreting-the-dft.ipynb
vatnid/uoe_speech_processing_course
ac479566f2d7b911cac8c94ecac92dda2b80bdb3
[ "MIT" ]
null
null
null
signals/sp-m1-5-interpreting-the-dft.ipynb
vatnid/uoe_speech_processing_course
ac479566f2d7b911cac8c94ecac92dda2b80bdb3
[ "MIT" ]
null
null
null
signals/sp-m1-5-interpreting-the-dft.ipynb
vatnid/uoe_speech_processing_course
ac479566f2d7b911cac8c94ecac92dda2b80bdb3
[ "MIT" ]
null
null
null
322.832689
47,148
0.926778
[ [ [ "#### _Speech Processing Labs 2020: Module 1_", "_____no_output_____" ] ], [ [ "## Run this first! \n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport cmath\nfrom math import floor\nfrom matplotlib.animation import FuncAnimation\nfrom IPython.display import HTML\nplt.style.use('ggplot')\n\nfrom dspMisc import *", "_____no_output_____" ] ], [ [ "# 5 Interpreting the Discrete Fourier Transform\n\n### Learning Outcomes\n* Understand how sampling rate effects the DFT output\n* Understand what the DFT leakage is.\n\n\n### Need to know\n* Topic Videos: Fourier Analysis, Frequency Domain\n* [Digital Signals: Sampling sinusoids](./sp-m1-3-sampling-sinusoids.ipynb)\n* [The Discrete Fourier Transform](./sp-m1-4-discrete-fourier-transform.ipynb) _(desirable)_\n\n<div class=\"alert alert-warning\">\n<strong>Equation alert</strong>: If you're viewing this on github, please note that the equation rendering is not always perfect. You should view the notebooks through a jupyter notebook server for an accurate view.\n</div>", "_____no_output_____" ], [ "## 5.1 A Very Quick DFT recap\nThe previous worksheet went through the mechanics of the Discrete Fourier Transform (DFT). The DFT input and output are broadly: \n\n* **Input:** $N$ amplitude samples over time \n * $x[n]$, for $n=1..N$ (i.e. a time series of $N$ samples)\n \n \n* **Output:** the dot product (i.e., the similiarity) between the input and $N$ sinusoids with different frequencies\n * DFT[k] $= Me^{j\\phi}$, i.e. a complex number with **magnitude** $M$ and **phase** angle $\\phi$\n\nThe outputs are calculated using the following formula for $k=0,...N-1$. \n\n$$ \n\\begin{align}\nDFT[k] &= \\sum_{n=0}^{N-1} x[n] e^{-j \\frac{2\\pi nk}{N}} \\\\\n&= \\sum_{n=0}^{N-1} x[n]\\big[\\cos\\big(\\frac{2\\pi nk}{N} \\big) - j \\sin\\big(\\frac{2\\pi nk}{N} \\big) \\big]\n\\end{align}\n$$\n\nWe saw how the complex numbers in this equation $e^{-j2\\pi nk/N}$ for $k=1...N-1$ represent sinusoids with specific frequencies as projections of phasors. You can just think of a phasor as an analogue clock with one hand (vector) ticking (rotating) around a clockface (i.e. a circle), where the length of the hand is the amplitude of that wave, and how fast it goes around the clock is it's frequency.\n\nEach DFT[k] output essentially tells us how strongly the input is repeats itself (i.e. is periodic) at the frequency of the $k$th DFT phasor. So, we talk about the DFT outputs as providing a **frequency response**. \n\nSince the the DFT outputs are complex numbers, we can talk about them in terms of magnitude and phase angle: The magnitude of DFT[k] tells us how much we'd weight the $k$-th phasor if we were to try to reconstruct the original input by adding all the DFT phasors together. The phase of DFT[k] tells use whether we need to shift that wave along the time axis. ", "_____no_output_____" ], [ "## 5.2 The DFT Frequency Response: Which Frequencies?\n\n\nYou will have noticed in the previous worksheet that we only talked about relative frequencies above, e.g. the $e^{-j2\\pi nk/N}$ phasor has $k$ times the frequency of the $e^{-j2\\pi n/N}$ phasor. \n\n\n\nSince the frequencies of the DFT phasors are all multiples of the $k=1$ phasor, we just have to figure out the frequency of that phasor and we'll know all the rest. Now, the $k=1$ phasor takes $N$ steps to complete a full cycle of the unit circle. So, it's frequency depends on how long each of these steps takes. That is, the **sampling rate**. \n\nAssume we are sampling at a rate of $f_s$ samples per second. Then, we can calculate: \n\n* How long between each sample (i.e. the **sampling time**): \n * $t_s = 1/f_s$ (seconds)\n\n\n* How long does it take to take $N$ samples?\n * $t_s \\times N$ (seconds x samples = seconds)\n \n \n* How long will it take the $k=1$ phasor to make 1 complete cycle?\n * $T_1 = t_s \\times N$ (seconds)\n * This is the **period** or **wavelength** of the phasor\n \n \n* What is the **frequency** of the $k=1$ phasor? \n * $f_{min} = 1/T_1 = 1/(t_s N) $ (cycles/second)\n \n \n* What is the **frequency** of the $k$th phasor? \n * $kf_{min}$ (cycles/second)\n \n\n\n\nSo, the important thing to remember is that the DFT outputs depend on: \n\n* The **number of samples** in the input sequence, $N$\n* The **sampling rate**, $f_s$ samples/second \n", "_____no_output_____" ], [ "### Example\nAssume we have a sampling rate of $f_s = 32$ samples/second, and an input length of $N=16$. \n\nWe can then calculate the $k=1$ DFT output frequency by noting the following: \n\n* The sampling time is: $t_s = 1/f_s = 1/32$ seconds\n* So, the time it takes to complete one cycle is: $T_1 = t_sN = 1/32 \\times 16 = 1/2$ seconds\n* So, the frequency of DFT[1] is $f_{min} = 1/1/2 = 2$ cycles/second", "_____no_output_____" ], [ "### Exercise\n\n* What's the frequency of the $k=5$ phasor in the previous example?\n", "_____no_output_____" ], [ "### Notes", "_____no_output_____" ] ], [ [ "# 10 cycles per second", "_____no_output_____" ] ], [ [ "### Exercise\n\nTry running this code which sets the input to be a sine wave with the same frequency as the the 1st DFT component. That is, `f_in = 1/wavlen_in`. \n", "_____no_output_____" ] ], [ [ "N=64\n\n#sampling rate: \nf_s = 128\nf_s = 256\n\n## sample time\nt_s = 1/f_s\n\n## Notice that the DFT component frequencies as completely determined by the number of samples N\n## and the sampling frequency f_s.\n## So if we wanted the input frequency to exactly match the frequency of the 1st DFT component we\n## could just do this:\n\nwavlen_in = t_s*N\nf_in = 1/wavlen_in\n\nprint(\"f_s: %f\\nt_s: %f\\nwavlen: %f\\nf_in %f\" % (f_s, t_s, wavlen_in, f_in))\n\n## indices of input sequence of size N\nnsteps = np.array(range(N))\n\nsamples_per_cycle = wavlen_in/t_s\nprint(\"samples per cycle %f\" % samples_per_cycle)\n\n## Generate a sine wave with f_in matching the frequency of the k=1 DFT phasor\n## You can look at the code for this function in the file XXX.py\n\nx, time_steps = gen_sinusoid(frequency=f_in, phase=0, amplitude=1, sample_rate=f_s, seq_length=N, gen_function=np.sin)\n\n\n## Plot the input\nfig, timedom = plt.subplots(figsize=(16, 4))\ntimedom.scatter(time_steps, x, color='magenta')\ntimedom.plot(time_steps, x, color='magenta')\ntimedom.set_xlabel(\"time (s)\")\ntimedom.set_ylabel(\"Amplitude\")\ntimedom.set_title(\"Input: $x[n]$ in the time domain\")", "f_s: 256.000000\nt_s: 0.003906\nwavlen: 0.250000\nf_in 4.000000\nsamples per cycle 64.000000\n" ], [ "## Calculate the frequencies associated with each DFT output\ndef get_dft_freqs_all(sample_rate, seq_len):\n ## Get the minimum frequency\n f_min = sample_rate/seq_len\n \n ## All the other frequencies are just integer multiples of the minimum frequency\n ## We have 0,...,seq_len-1 outputs\n dft_outs = np.arange(seq_len)\n \n return f_min * dft_outs", "_____no_output_____" ], [ "## Find the DFT output frequencies for our current sample rate and input length\ndft_freqs = get_dft_freqs_all(sample_rate=f_s, seq_len=N)\nprint(dft_freqs)\n", "[ 0. 4. 8. 12. 16. 20. 24. 28. 32. 36. 40. 44. 48. 52.\n 56. 60. 64. 68. 72. 76. 80. 84. 88. 92. 96. 100. 104. 108.\n 112. 116. 120. 124. 128. 132. 136. 140. 144. 148. 152. 156. 160. 164.\n 168. 172. 176. 180. 184. 188. 192. 196. 200. 204. 208. 212. 216. 220.\n 224. 228. 232. 236. 240. 244. 248. 252.]\n" ], [ "## Apply the DFT to the input and return the magnitudes and phases for each DFT output\nmags, phases = get_dft_mag_phase(x, seq_len=N)\n\n## Plot the magnitudes\nfig, fdom = plt.subplots(figsize=(16, 4))\nfdom.scatter(dft_freqs, mags)\nfdom.set_xlabel(\"Frequency (Hz)\")\nfdom.set_ylabel(\"Magnitude\")\nfdom.set_title(\"Magnitude response\")\n\n\n#print(mags)\n\n## Plot the phases\nfig, fdom = plt.subplots(figsize=(16, 4))\nfdom.scatter(dft_freqs, phases)\nfdom.set_xlabel(\"Frequency (Hz)\")\nfdom.set_ylabel(\"Phase angle (radians)\")\nfdom.set_title(\"Phase response\")\n\n\n\n\n#print(phases)\n", "_____no_output_____" ] ], [ [ "### Exercise\n\n* Is the output what you'd expect given the input? \n* Why is the phase non-zero for the DFT output's 1 and 63? \n* What happens if you change the `amplitude` of the input sine wave? What about the `phase`? \n* What happens to the range of DFT output frequencies if you increase the sampling rate `f_s` but keep the input sequence length `N` fixed? \n* What happens to the range of DFT output frequencies for $k > N/2$? Can the DFT actually model those frequencies? ", "_____no_output_____" ], [ "### Notes", "_____no_output_____" ] ], [ [ "# \n# 1 and 63 are the same phase turning in opposite directions\n# amplitude: the magnitude response increases by the same factor, \n# phase: the phase response changes\n# increase f_s: the output frequency increases by the same amount\n# ", "_____no_output_____" ] ], [ [ "## 5.3 DFT on a compound waveform\n\nNow, let's see what happens when we use a compound waverform as input to the DFT. First we need to set the length of the sequence and the sample rate. ", "_____no_output_____" ] ], [ [ "## Set the number of samples N, sampling rate f_s\nN=64\n\n#sampling rate: \nf_s = 64\n\n## sample time\nt_s = 1/f_s\n\nprint(\"N: %d\\nf_s: %f\\nt_s: %f\" % (N, f_s, t_s))", "N: 64\nf_s: 64.000000\nt_s: 0.015625\n" ] ], [ [ "Let's create a compound waveform as input with frequency components of 4Hz and 12Hz:", "_____no_output_____" ] ], [ [ "## Now let's create a compound waveform as input\n## We're setting gen_function=np.cos, meaning that each of our sinusoids is a cosine wave \nx1, time_steps = gen_sinusoid(frequency=4, phase=0, amplitude=1, sample_rate=f_s, seq_length=N, gen_function=np.cos)\n\n## Let's shift the phase of this one by 90 degrees (pi/2 rads)\nx2, time_steps = gen_sinusoid(frequency=12, phase=np.pi/2, amplitude=1, sample_rate=f_s, seq_length=N, gen_function=np.cos)\n\nx3, time_steps = gen_sinusoid(frequency=0.5, phase=0, amplitude=1, sample_rate=f_s, seq_length=N, gen_function=np.cos)\n\nx_compound = x1 + x2 + x3\n\n## Plot the input\nfig, timedom = plt.subplots(figsize=(16, 4))\ntimedom.scatter(time_steps, x_compound, color='magenta')\ntimedom.plot(time_steps, x_compound, color='magenta')\ntimedom.set_xlabel(\"time (s)\")\ntimedom.set_ylabel(\"Amplitude\")\ntimedom.set_title(\"A compound waveform: $x_compound$ in the time domain\")", "_____no_output_____" ] ], [ [ "You should see a somewhat complicated waveform whose overall pattern repeats 4 times in a second. Now we do the DFT and look at the magnitude and phase values for the different DFT outputs. ", "_____no_output_____" ] ], [ [ "## Do the DFT on the compound waveform as above: \nmags, phases = get_dft_mag_phase(x_compound, seq_len=N)\ndft_freqs = get_dft_freqs_all(sample_rate=f_s, seq_len=N)\n\n## Plot the magnitudes\nfig, fdom = plt.subplots(figsize=(16, 4))\n#timedom.scatter(dft_freqs[:round(N)], mags[:round(N)])\nfdom.scatter(dft_freqs[:round(N/2)], mags[:round(N/2)])\nfdom.set_xlabel(\"Frequency (Hz)\")\nfdom.set_ylabel(\"Magnitude\")\nfdom.set_title(\"Magnitude response\")\n#print(mags)\n\n## Plot the phases - let's just skip this for the moment \nfig, fdom = plt.subplots(figsize=(16, 4))\nfdom.scatter(dft_freqs[:round(N/2)], phases[:round(N/2)])\nfdom.set_xlabel(\"Frequency (Hz)\")\nfdom.set_ylabel(\"Phase (rad)\")\nfdom.set_title(\"Phase response\")\n#print(phases)\n", "_____no_output_____" ] ], [ [ "### Exercise\n\n* Do you see what you would expect given the input? \n* Why does the number of non-zero phases differ from the number of non-zero magnitudes?\n", "_____no_output_____" ], [ "### Notes\n", "_____no_output_____" ] ], [ [ "# yes\n# only the 12 Hz wave was phase-shifted ", "_____no_output_____" ] ], [ [ "### Exercise \n\nExplore the outputs of the DFT when you change the following parameters\n* sampling rate `f_s`\n* sequence length `N`\n* frequency of the input sequence(s) `frequency` (in the function `gen_sinusoid`)\n\n\n**Question**\n* What happens if you set the frequency of one of the input components to be greater than the Nyquist frequency? \n* What happens when the frequency of the input components doesn't match any of the DFT component frequencies? \n(e.g. for the example above what if one of the input frequencies is not a whole number?) \n\n\n", "_____no_output_____" ], [ "### Notes", "_____no_output_____" ] ], [ [ "# it won't appear in the output\n# the output is a combination of component frequencies", "_____no_output_____" ] ], [ [ "## 5.4 Leakage\n\nOne of the main things to remember about the DFT is that you're calculating the correlation between the input and phasors with specific frequencies. If your input exactly matches one of those phasor frequencies the magnitude response will show a positive magnitude for that phasor and zero for everything else. However, if the input frequency falls between phasor frequencies (i.e. doesn't correspond to a specific DFT output), then you'll see spectral **leakage**. The DFT outputs close to the input frequency will also get positive magnitudes, with the DFT output closest to the input frequency getting the highest magnitude. \n\nThe following code gives an example\n", "_____no_output_____" ] ], [ [ "N=64\nf_s = 64\nf_in1 = 4.5 ## In between DFT output frequencies\nf_in2 = 12 ## One of the DFT outputs\n\nx1, time_steps = gen_sinusoid(frequency=f_in1, phase=0, amplitude=1, sample_rate=f_s, seq_length=N, gen_function=np.cos)\nx2, time_steps = gen_sinusoid(frequency=f_in2, phase=np.pi/2, amplitude=0.4, sample_rate=f_s, seq_length=N, gen_function=np.cos)\nx_compound = x1 + x2\n\n## Plot the input\nfig, timedom = plt.subplots(figsize=(16, 4))\ntimedom.scatter(time_steps, x_compound, color='magenta')\ntimedom.plot(time_steps, x_compound, color='magenta')\ntimedom.set_xlabel(\"time (s)\")\ntimedom.set_ylabel(\"Amplitude\")\ntimedom.set_title(\"Leakage example (time domain)\")\n\n", "_____no_output_____" ], [ "## Do the DFT on the compound waveform as above: \nmags, phases = get_dft_mag_phase(x_compound, seq_len=N)\ndft_freqs = get_dft_freqs_all(sample_rate=f_s, seq_len=N)\n\n## Plot the magnitudes\nfig, fdom = plt.subplots(figsize=(16, 4))\n\n## Just plot the first N/2 frequencies since we know that they are the mirrored for k>N/2\nfdom.scatter(dft_freqs[:round(N/2)], mags[:round(N/2)])\nfdom.set_xlabel(\"Frequency (Hz)\")\nfdom.set_ylabel(\"Magnitude\")\nfdom.set_title(\"Leakage example: Magnitude response\")\n#print(mags)\n", "_____no_output_____" ] ], [ [ "\n### Leakage as the normalized sinc function \n\nLeakage makes the DFT harder to interpret. However, we can derive the shape that leakage will have from the the DFT equation and some algebra about rectangular functions. It turns out that leakage for a particular frequency follows the normalized **sinc** function: \n\n$$\n\\begin{align}\nX(m) &= \\Big|\\frac{AN}{2} \\cdot \\mathop{sinc}(c-m)\\Big|\\\\\n&= \\Big|\\frac{AN}{2} \\cdot \\frac{\\sin(\\pi(c-m))}{2\\pi(c-m))}\\Big|\\\\\n\\end{align}\n$$\n\nWhere $A$ is the peak amplitude of the input, $N$ is the input sequence length, $c$ is the number of cycles completed in the input sequence time. If $c$ is a whole number we just get the usual DFT response, but if $c$ is not a whole number, we get a spread across output frequency bins.\n", "_____no_output_____" ], [ "Let's check whether the sinc function matches what we get in the DFT. First we write a function to evaluate the leakage function in between our DFT outputs.", "_____no_output_____" ] ], [ [ "## Calculate the approximated leakage as the sinc function\ndef calc_leakage(freq, sample_rate, seqlen, amplitude=1):\n sequence_time = (1/sample_rate)*seqlen\n \n ## number of cycles in input for component\n c = freq * sequence_time\n print(\"c=\", c)\n \n ## Interpolate between DFT ouput indices\n ms = np.arange(0, seqlen, 0.05)\n \n ## Approximated response - we could actually just return a function here, but \n ## let's just keep things concrete for now.\n leakage = np.abs(amplitude * seqlen * 0.5 * np.sinc((c-ms)))\n\n return leakage, ms * (sample_rate/seqlen)\n\n\n", "_____no_output_____" ] ], [ [ "Now let's plot the leakage predicted for our two input components separately (top) and added together (bottom)", "_____no_output_____" ] ], [ [ "## Calculate the leakage function for our know input wave components\nleakage1, ms = calc_leakage(f_in1, f_s, N)\nleakage2, ms = calc_leakage(f_in2, f_s, N)\n\n\n## Plot the magnitude response and the leakage function for each of our input components\nfig, fdom = plt.subplots(figsize=(16, 4))\nfdom.set(xlim=(-1, N/2), ylim=(-1, N))\nfdom.scatter(dft_freqs, mags)\n\n\nfdom.plot(ms, leakage1)\nfdom.plot(ms, leakage2)\nfdom.set_xlabel(\"Frequency (Hz)\")\nfdom.set_ylabel(\"Magnitude\")\nfdom.set_title(\"Leakage function for each input component frequency\")\n\n## Plot the magnitude response and the sum of the leakage functions\nfig, fdom = plt.subplots(figsize=(16, 4))\nfdom.set(xlim=(-1, N/2), ylim=(-1, N))\nfdom.scatter(dft_freqs, mags)\nfdom.plot(ms, leakage1 + leakage2, color='C5')\nfdom.set_xlabel(\"Frequency (Hz)\")\nfdom.set_ylabel(\"Magnitude\")\nfdom.set_title(\"Sum of leakage functions for input components\")\n\n## It fits, though not perfectly!", "c= 4.5\nc= 12.0\n" ] ], [ [ "In the top figure, you should see that peaks (**main lobes**) of each leakage function are aligned with our input component frequencies. The peaks are at the same points as the DFT outputs when the sinusoidal component has a frequency matching the DFT output frequency (i.e. 12 above Hz). Otherwise we see the spread of leakage around the input component frequency (i.e. around 4.5 Hz). \n\nYou'll also notice that our DFT magnitudes points don't always line up perfectly with our sinc curves. Part of this is because the leakage function is an _approximation_. Nevertheless, it's a very good approximation! ", "_____no_output_____" ], [ "### Exercise\n\n* What happens if the frequencies of the two components making the compound waveform are very close together? \n * e.g. make `f_in2=6`\n* What if one of the components has a relatively small amplitude? \n * e.g. change `amplitude` of the second input to 0.4", "_____no_output_____" ], [ "### Notes", "_____no_output_____" ] ], [ [ "# f_in2=6: the two peaks merge\n# amplitude: the output decreases and doesn't match the sinc function", "_____no_output_____" ] ], [ [ "### Shaping the lobes\nThe leakage sinc function has a peak around a specific frequency. If we want our DFT to be better able to distinguish between close frequencies, we need that peak, the **main lobe** to be narrower. We also want the other peaks, the **side lobes** to be flatter. We can achieve this using different **windowing methods** on our input. This is why you see 'Hanning' as the default option for window method in the advanced spectrogram settings in praat. \n\nWe'll see some more examples of this when we look at different types of filters later. But for now the main thing to observe is that leakage might give you the impression that specific frequency components are present in your waveform, when what's actually happening is that your waveform has frequencies that don't match the DFT phasors. Another thing that can happen is that the peak for a low amplitude component gets subsumed into the main lobe of a nearby frequency component. This might make you miss frequency components in your input! ", "_____no_output_____" ], [ "## 5.6 Extra: \n\nHere's the composition and decomposition for the compound waveform one you saw in Notebook 2! ", "_____no_output_____" ] ], [ [ "N=1028\nf_s = 1028\nf_in1 = 8 ## In between DFT output frequencies\nf_in2 = 20 ## One of the DFT outputs\nf_in3 = 36 ## One of the DFT outputs\n\n\nx1, time_steps = gen_sinusoid(frequency=f_in1, phase=0, amplitude=0.5, sample_rate=f_s, seq_length=N, gen_function=np.cos)\nx2, time_steps = gen_sinusoid(frequency=f_in2, phase=np.pi/2, amplitude=1, sample_rate=f_s, seq_length=N, gen_function=np.cos)\nx3, time_steps = gen_sinusoid(frequency=f_in3, phase=0, amplitude=0.3, sample_rate=f_s, seq_length=N, gen_function=np.cos)\n\n\nx_compound = x1 + x2 + x3\n\n## Plot the input\nfig, timedom = plt.subplots(figsize=(16, 4))\n#timedom.scatter(time_steps, x_compound, color='magenta')\n#timedom.set(xlim=(0, 0.2))\ntimedom.plot(time_steps, x_compound, color='magenta')", "_____no_output_____" ], [ "## Plot the input\n\nfig = plt.figure(figsize=(15,15))\ngs = fig.add_gridspec(3,2)\n\nymax=2\ntimedom = fig.add_subplot(gs[0, 0])\ntimedom.set(xlim=(-0.1, 1), ylim=(-ymax,ymax))\ntimedom.plot(time_steps, x_compound, color='magenta')\ntimedom.set_title(\"waveform made from adding 3 sine waves\")\n\n\n\ns1 = fig.add_subplot(gs[0, 1])\ns1.set(xlim=(-0.1, 1), ylim=(-ymax,ymax))\ns1.plot(time_steps, x1)\ns1.set_title(\"component 1: 8 Hz\")\n\ns2 = fig.add_subplot(gs[1, 1])\ns2.set(xlim=(-0.1, 1), ylim=(-ymax,ymax))\ns2.plot(time_steps, x2)\ns2.set_title(\"component 2: 20 Hz\")\n\n\n\ns3 = fig.add_subplot(gs[2, 1])\ns3.set(xlim=(-0.1, 1), ylim=(-ymax,ymax))\ns3.plot(time_steps, x3)\ns3.set_title(\"component 3: 36 Hz\")\n\n\nfig.savefig(\"./fig/compound_waveform.png\")", "_____no_output_____" ], [ "## Do the DFT on the compound waveform as above: \nmags, phases = get_dft_mag_phase(x_compound, seq_len=N)\ndft_freqs = get_dft_freqs_all(sample_rate=f_s, seq_len=N)\n\n## Plot the magnitudes\nfig,fdom = plt.subplots(figsize=(16, 4))\nfdom.set(xlim=(-1, N/2))\n## Just plot the first N/2 frequencies since we know that they are the mirrored for k>N/2\nfdom.scatter(dft_freqs[:round(N/2)], mags[:round(N/2)])\nfdom.set_xlabel(\"Frequency (Hz)\")\nfdom.set_ylabel(\"Magnitude\")\nfdom.set_title(\"Magnitude Response\")\n#print(mags)\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", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
ec54a974da9755ffad09ea3c0d9f419ef009b07b
1,852
ipynb
Jupyter Notebook
{{cookiecutter.project_slug}}/notebooks/6.Deployment.ipynb
kiri1701/problem-solution-template
19feb15c2beeaa038154fc691d2b41731cb02df5
[ "MIT" ]
null
null
null
{{cookiecutter.project_slug}}/notebooks/6.Deployment.ipynb
kiri1701/problem-solution-template
19feb15c2beeaa038154fc691d2b41731cb02df5
[ "MIT" ]
null
null
null
{{cookiecutter.project_slug}}/notebooks/6.Deployment.ipynb
kiri1701/problem-solution-template
19feb15c2beeaa038154fc691d2b41731cb02df5
[ "MIT" ]
null
null
null
22.313253
180
0.562095
[ [ [ "# Deployment\n\nCreation of the model is generally not the end of the project. Usually, the knowledge gained will need to be organized and presented in a way that the customer can use it.\n\nDepending on the requirements, the deployment phase can be as simple as generating a report or as complex as implementing a repeatable data mining process.\n\nIn any case, it is important to understand up front what actions will need to be carried out in order to actually make use of the created models.\n\n## Plan Deployment\nOutputs\n- Deployment Plan\n\n## Plan Monitoring and Maintenance\nOutputs\n- Monitoring and Maintenance Plan\n\n## Produce Final Report\nOutputs\n- Final Report\n- Final Presentation\n\n## Review Project\nOutputs\n- Experience Documentation", "_____no_output_____" ], [ "## Plan Deployment\n\n", "_____no_output_____" ], [ "## Plan Monitoring and Maintenance\n\n", "_____no_output_____" ], [ "## Produce Final Report\n\n\n", "_____no_output_____" ], [ "## Review Project", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
ec54b66d6765fff331f880ba4693516e886d3bc0
8,667
ipynb
Jupyter Notebook
W02_A--Data_Visualization_Assignment_Master.ipynb
schwaaweb/aimlds1_02
4d7ca4ead30b13671d62f2e9c8383639b818c5e8
[ "MIT" ]
null
null
null
W02_A--Data_Visualization_Assignment_Master.ipynb
schwaaweb/aimlds1_02
4d7ca4ead30b13671d62f2e9c8383639b818c5e8
[ "MIT" ]
null
null
null
W02_A--Data_Visualization_Assignment_Master.ipynb
schwaaweb/aimlds1_02
4d7ca4ead30b13671d62f2e9c8383639b818c5e8
[ "MIT" ]
null
null
null
41.668269
302
0.556132
[ [ [ "[View in Colaboratory](https://colab.research.google.com/github/schwaaweb/aimlds1_02/blob/master/W02_A--Data_Visualization_Assignment_Master.ipynb)", "_____no_output_____" ], [ "https://youtu.be/igOZIsa9yjY\n\n# Data Visualization\n\nVery little machine learning or data science takes place without visualizations. Visualizations help us comprehend our data, segment it, and eventually transform it in a way that allows ML algorithms to produce insights.\n\nThe fundamental visualizations are:\n\n* [line charts](https://jakevdp.github.io/PythonDataScienceHandbook/04.01-simple-line-plots.html)\n* [scatter plots](https://jakevdp.github.io/PythonDataScienceHandbook/04.02-simple-scatter-plots.html)\n* [bar charts](https://jakevdp.github.io/PythonDataScienceHandbook/04.03-errorbars.html)\n\nVisualizations are useful in\n\n* 2 dimensions\n* [3 dimensions](https://jakevdp.github.io/PythonDataScienceHandbook/04.12-three-dimensional-plotting.html)\n* [images](https://matplotlib.org/users/image_tutorial.html)\n\nVisualizations are highlighted by\n\n* [color](https://jakevdp.github.io/PythonDataScienceHandbook/04.07-customizing-colorbars.html)\n* [axis size and spacing](https://jakevdp.github.io/PythonDataScienceHandbook/04.10-customizing-ticks.html)\n* [legends](https://jakevdp.github.io/PythonDataScienceHandbook/04.06-customizing-legends.html)\n* [annotations](https://jakevdp.github.io/PythonDataScienceHandbook/04.08-multiple-subplots.html)\n* [subplots](https://jakevdp.github.io/PythonDataScienceHandbook/04.08-multiple-subplots.html)\n\nIn this assignment, you will use visualizations to explore the titanic and okcupid datasets, looking for linear, polynomial, or gaussian-like relationships. Every other relationship looks like noise.", "_____no_output_____" ], [ "## Assignment\n\nThe following dataset contains a number of hidden functions. Use bar plots, scatter plots, and line plots to explore the dataset, looking for relationships. When you discover a relationship, you will know it.\n\nIt is possible to create a 2d graph for every pair of columns, and a 3d graph for every triple of columns. This would produce `10 choose 2` 2d graphs and `10 choose 3` 3d graphs. See if you can find the functions in this dataset through visualization. Make as many visualizations as you like.", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv('https://www.dropbox.com/s/4jgheggd1dak5pw/data_visualization.csv?raw=1', index_col=0)\nprint(data.columns)\nprint(data.head(5))\n\n# plot the data until you intuit information from it", "Index(['night', 'slice', 'height', 'wind', 'alpha', 'x', 'length', 'y',\n 'under', 'dataset', 'interior', 'pi', 'theta', 'rho', 'nu', 'arrow',\n 'delta'],\n dtype='object')\n night slice height wind alpha \\\n0 7.192724 5590.286963 3.677346e+05 15874.681584 288.844905 \n1 7.965880 25839.548627 7.779735e+06 9731.870015 1327.648026 \n2 12.649505 29783.806651 1.036852e+07 9961.937864 1497.827365 \n3 6.020414 10870.002427 1.383920e+06 13044.847041 323.124781 \n4 10.966374 29566.406602 1.017405e+07 5728.689441 485.635683 \n\n x length y under dataset interior \\\n0 10.791882 -0.092260 -54.865187 -1.454278 9511.765099 1.028905e+10 \n1 6.764308 0.153516 7.928925 0.391918 7178.690641 4.472129e+09 \n2 14.004564 1.369974 -60.682680 1.091300 7298.335485 4.658803e+09 \n3 9.359527 -1.176298 8.748563 -0.114204 5276.337621 1.754074e+09 \n4 10.127836 -1.083204 -38.061848 0.846972 1148.590503 1.971619e+07 \n\n pi theta rho nu arrow \\\n0 513.396285 7.789097e+06 104.555195 7.144070e+07 19705.401491 \n1 180.815877 2.812274e+06 104.880505 3.104463e+07 12124.208351 \n2 258.675569 6.091894e+06 270.704020 3.620836e+07 12411.080891 \n3 84.195988 6.969192e+05 423.431057 2.366268e+06 16191.214414 \n4 640.008215 4.468482e+06 447.661726 1.427828e+07 7153.543024 \n\n delta \n0 -177.307810 \n1 54.341522 \n2 -130.002851 \n3 -42.515638 \n4 -119.907955 \n" ] ], [ [ "# Visualize your result\n\nDraw a single plot containing multiple datasets in different colors and styles. You can use subplots, different colors and symbols, and one or more legends to create an attractive plot. Summarize any knowledge you have gained about the dataset verbally.", "_____no_output_____" ], [ "# Thinking about your assignment\n\n1. What is this assignment asking for? What programming elements are required, like graphing, dataset manipulation, and intuition should I be looking for? What python functions will be required? Why is visualization important?\n2. Make a list of the first four steps I need to take in order to explore and solve this assignment:\n3. What do I want to have accomplished when I have finished this assignment?\n", "_____no_output_____" ], [ "# Googling about your assignment\n\n```\npython bar chart\npython scatter plot\npython plotting dataset\nmatplotlib legend\nmatplotlib subplot\nbeautiful python graphs\n```", "_____no_output_____" ], [ "# Stretch goal\n\nSo, you found all of the relationships in the toy dataset! Try doing the same thing with the titanic set and okcupid. Use categorical data as color indices into your graph! You can plot all three ticket classes aboard the titanic using the same graph to gain even deeper intuitions.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
ec54c2ae597e39b20d04e2f9ea79711efb2f3167
5,282
ipynb
Jupyter Notebook
notebooks/sql/raw/ex3.ipynb
Mattjez914/Blackjack_Microchallenge
c4f60b62a3ada14663eb30ce72563af994e1eda4
[ "Apache-2.0" ]
1
2019-12-09T04:45:42.000Z
2019-12-09T04:45:42.000Z
notebooks/sql/raw/ex3.ipynb
NeuroLaunch/learntools
60f8929f3526b7469d3da236a13748fde8584153
[ "Apache-2.0" ]
null
null
null
notebooks/sql/raw/ex3.ipynb
NeuroLaunch/learntools
60f8929f3526b7469d3da236a13748fde8584153
[ "Apache-2.0" ]
1
2019-04-17T06:12:23.000Z
2019-04-17T06:12:23.000Z
26.676768
296
0.574593
[ [ [ "# Introduction\n\nQueries with **GROUP BY** can be powerful. There are many small things that can trip you up (like the order of the clauses), but it will start to feel natural once you've done it a few times. Here, you'll write queries using **GROUP BY** to answer questions from the Hacker News dataset.\n\nBefore you get started, run the following cell to set everything up:", "_____no_output_____" ] ], [ [ "# Set up feedback system\nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.sql.ex3 import *\nprint(\"Setup Complete\")", "_____no_output_____" ] ], [ [ "The code cell below fetches the `comments` table from the `hacker_news` dataset. We also preview the first five rows of the table.", "_____no_output_____" ] ], [ [ "from google.cloud import bigquery\n\n# Create a \"Client\" object\nclient = bigquery.Client()\n\n# Construct a reference to the \"hacker_news\" dataset\ndataset_ref = client.dataset(\"hacker_news\", project=\"bigquery-public-data\")\n\n# API request - fetch the dataset\ndataset = client.get_dataset(dataset_ref)\n\n# Construct a reference to the \"comments\" table\ntable_ref = dataset_ref.table(\"comments\")\n\n# API request - fetch the table\ntable = client.get_table(table_ref)\n\n# Preview the first five lines of the \"comments\" table\nclient.list_rows(table, max_results=5).to_dataframe()", "_____no_output_____" ] ], [ [ "# Exercises\n\n### 1) Prolific commenters\n\nHacker News would like to send awards to everyone who has written more than 10,000 posts. Write a query that returns all authors with more than 10,000 posts as well as their post counts. Call the column with post counts `NumPosts`.\n\nIn case sample query is helpful, here is a query you saw in the tutorial to answer a similar question:\n```\nquery = \"\"\"\n SELECT parent, COUNT(1) AS NumPosts\n FROM `bigquery-public-data.hacker_news.comments`\n GROUP BY parent\n HAVING COUNT(1) > 10\n \"\"\"\n```", "_____no_output_____" ] ], [ [ "# Query to select prolific commenters and post counts\nprolific_commenters_query = ____ # Your code goes here\n\n# Set up the query (cancel the query if it would use too much of \n# your quota, with the limit set to 1 GB)\nsafe_config = bigquery.QueryJobConfig(maximum_bytes_billed=1e9)\nquery_job = client.query(prolific_commenters_query, job_config=safe_config)\n\n# API request - run the query, and return a pandas DataFrame\nprolific_commenters = query_job.to_dataframe()\n\n# View top few rows of results\nprint(prolific_commenters.head())\n\n# Check your answer\nq_1.check()", "_____no_output_____" ] ], [ [ "For the solution, uncomment the line below.", "_____no_output_____" ] ], [ [ "#q_1.solution()", "_____no_output_____" ] ], [ [ "### 2) Deleted comments\n\nHow many comments have been deleted? (If a comment was deleted, the `deleted` column in the comments table will have the value `True`.)", "_____no_output_____" ] ], [ [ "# Write your query here and figure out the answer", "_____no_output_____" ], [ "num_deleted_posts = ____ # Put your answer here\n\nq_2.check()", "_____no_output_____" ] ], [ [ "For the solution, uncomment the line below.", "_____no_output_____" ] ], [ [ "#q_2.solution()", "_____no_output_____" ] ], [ [ "# Keep Going\n**[Click here](#$NEXT_NOTEBOOK_URL$)** to move on and learn about the **ORDER BY** clause.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec54c44e0ac85d3d379013b216e5c24a28858a19
15,231
ipynb
Jupyter Notebook
notebooks/Reg/sirf_registration.ipynb
paskino/SIRF-Exercises
8203077840b1667719467f0d8c6b009625e8f27d
[ "Apache-2.0" ]
null
null
null
notebooks/Reg/sirf_registration.ipynb
paskino/SIRF-Exercises
8203077840b1667719467f0d8c6b009625e8f27d
[ "Apache-2.0" ]
1
2021-05-18T22:33:44.000Z
2021-05-19T03:03:05.000Z
notebooks/Reg/sirf_registration.ipynb
paskino/SIRF-Exercises
8203077840b1667719467f0d8c6b009625e8f27d
[ "Apache-2.0" ]
null
null
null
35.09447
529
0.625369
[ [ [ "# Rigid registration\n\nThis example should show you how to perform rigid registration between two SIRF images.\n\nSIRF's registration/resampling functionality is provided by wrapping and extending the [NiftyReg](http://cmictig.cs.ucl.ac.uk/wiki/index.php/NiftyReg) code base. Rigid and affine registrations are performed using NiftyReg's symmetric `aladin` algorithm, whereas non-rigid registrations use the symmetric `f3d` algorithm.\n\nAlthough the example of rigid registration is given here, it is trivial to modify it for affine registrations and only slightly trickier to extend to non-rigid registration.\n\nThe images to be registered in this example are `test.nii.gz` and `test2.nii.gz`, which are two T1-weighted MR brain scans taken one year apart.\n\nN.B.: Registration packages use different names for the sets of images they are registering. In NiftyReg (and therefore SIRF), the floating image is moved to match the reference image. In other packages, the floating=moving and reference=fixed. ", "_____no_output_____" ], [ "## Copyright\n\nAuthor: Richard Brown \nFirst version: 3rd April 2019 \nSecond version: 8th June 2020 \n\nCCP PETMR Synergistic Image Reconstruction Framework (SIRF)\nCopyright 2019 University College London.\n\nThis is software developed for the Collaborative Computational Project in Positron Emission Tomography and Magnetic Resonance imaging (http://www.ccppetmr.ac.uk/).\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n", "_____no_output_____" ], [ "## Initial set up", "_____no_output_____" ] ], [ [ "#%% make sure figures appears inline and animations works\n%matplotlib notebook", "_____no_output_____" ], [ "# Standard stuff\nimport numpy\nimport matplotlib.pyplot as plt\n\n# SIRF stuff\nfrom sirf.Utilities import examples_data_path\nimport sirf.Reg as Reg\nexamples_path = examples_data_path('Registration')", "_____no_output_____" ], [ "#%% First define some handy function definitions\n# To make subsequent code cleaner, we have a few functions here. You can\n# ignore them when you first see this demo.\n# They have (minimal) documentation using Python docstrings such that you \n# can do for instance \"help(imshow)\"\n#\n# First a function to display an image\n\ndef imshow(image, title=''):\n \"\"\"Display an image with a colourbar, returning the plot handle. \n\n Arguments:\n image -- a 2D array of numbers\n limits -- colourscale limits as [min,max]. An empty [] uses the full range\n title -- a string for the title of the plot (default \"\")\n \"\"\"\n plt.title(title)\n bitmap=plt.imshow(image)\n limits=[numpy.nanmin(image),numpy.nanmax(image)]\n\n plt.clim(limits[0], limits[1])\n plt.colorbar(shrink=.6)\n plt.axis('off')\n return bitmap", "_____no_output_____" ] ], [ [ "## Engine for loading images\n\nBy default this example uses `sirf.Reg` as the engine to open the images, which handles NIfTI images. \n\nYou might want to register different types of images - perhaps your floating image is a STIR interfile? If so, change the second line such that it reads `import sirf.STIR as eng_flo`.", "_____no_output_____" ] ], [ [ "# In this example, we will use sirf.Reg as the engine to open our images\nimport sirf.Reg as eng_ref\nimport sirf.Reg as eng_flo", "_____no_output_____" ] ], [ [ "## Open and display the images", "_____no_output_____" ] ], [ [ "# Open the images\nref_file = examples_path + \"/test.nii.gz\"\nflo_file = examples_path + \"/test2.nii.gz\"\nref = eng_ref.ImageData(ref_file)\nflo = eng_flo.ImageData(flo_file)", "_____no_output_____" ], [ "# Display the images\nref_slice = ref.get_dimensions()[1] // 2\nflo_slice = flo.get_dimensions()[1] // 2\nplt.subplot(1,2,1)\nimshow(ref.as_array()[ref_slice,:,:], 'Reference image, slice: %i' % ref_slice)\nplt.subplot(1,2,2)\nimshow(flo.as_array()[flo_slice,:,:], 'Floating image, slice: %i' % flo_slice);", "_____no_output_____" ] ], [ [ "## A little word about image orientation\n\nAn image will needs information in order to be able to place it in the real world. This information encodes things such as voxel sizes, orientation and offset or origin (where the image starts). The geometrical information for any SIRF image can be extracted with `get_geometrical_info`.\n\nLet's have a look at the direction matrix and offset for our two example images:", "_____no_output_____" ] ], [ [ "# Ref\nref_geom_info = ref.get_geometrical_info()\nref_direction_matrix = ref_geom_info.get_direction_matrix()\nprint(\"printing ref direction matrix\\n\", ref_direction_matrix)\nref_offset = ref_geom_info.get_offset()\nprint(\"printing ref offset\\n\", ref_offset)\n# Flo\nflo_geom_info = flo.get_geometrical_info()\nflo_direction_matrix = flo_geom_info.get_direction_matrix()\nprint(\"\\nprinting flo direction matrix\\n\", flo_direction_matrix)\nflo_offset = flo_geom_info.get_offset()\nprint(\"printing flo offset\\n\", flo_offset)", "_____no_output_____" ] ], [ [ "So what have we learnt here? Well, if a direction matrix were identity, then our image would be in LPS format (left-posterior-superior). We can see that our first image is therefore RAS, and our second is LSA.\n\nThis means that our `imshow` above is misleading. It uses `as_array`, which returns the underlying data \"as is\", without any regard for the image orientation. If we wanted to display our second image such that it's orientation matched the first (RAS), then we would need permute our 2nd and 3rd axes (such that LSA->LAS), and then flip our first axis (LAS->RAS). Let's give that a go now:", "_____no_output_____" ] ], [ [ "flo_array = flo.as_array()\n# transpose (LSA->LAS)\nflo_array = numpy.transpose(flo_array, (0, 2, 1))\n# flip (LAS->RAS)\nflo_array = numpy.flip(flo_array, 0)\n\n# Display\nplt.figure()\nplt.subplot(1,2,1)\nimshow(ref.as_array()[ref_slice,:,:], 'Reference image, slice: %i' % ref_slice);\nplt.subplot(1,2,2)\nimshow(flo_array[flo_slice,:,:], 'Floating image, slice: %i' % flo_slice);", "_____no_output_____" ] ], [ [ "Great! \n\nHopefully you can convince yourself that, in spite of the misleading orientation of the first `imshow`, the images are actually facing the same direction. \n\nNow have a look at our offsets that we printed further up. These are quite different. We would therefore expect the rigid registration between these two images would result in little rotation, but quite a lot of translation. \n\nLet's have a look!", "_____no_output_____" ], [ "## Back to registration!\n\nOk, let's get back to the registration. Start by setting up the registration object.", "_____no_output_____" ] ], [ [ "# Set to NiftyF3dSym for non-rigid\nalgo = Reg.NiftyAladinSym()\n\n# Set images\nalgo.set_reference_image(ref)\nalgo.set_floating_image(flo)\n\n# What else can we do?\nhelp(algo)", "_____no_output_____" ] ], [ [ "## Setting parameters\n\nFrom the help above, it looks like we can set registration parameters both via a file and directly. Let's try both.", "_____no_output_____" ] ], [ [ "# Setting via parameter file\npar_file = examples_path + \"/paramFiles/niftyreg_aladin.par\"\nalgo.set_parameter_file(par_file)\n\nalgo.set_parameter('SetPerformRigid','1')\nalgo.set_parameter('SetPerformAffine','0')\n#algo.set_parameter('SetWarpedPaddingValue','0') # NaN by default, uncomment to set to 0.", "_____no_output_____" ] ], [ [ "## Register!", "_____no_output_____" ] ], [ [ "algo.process()", "_____no_output_____" ] ], [ [ "## Show the registered image\n\nThe registered image will be the same size as the reference image, so we can use `ref_slice`.", "_____no_output_____" ] ], [ [ "output = algo.get_output()\noutput_arr = output.as_array()\nplt.figure()\nimshow(output_arr[ref_slice,:,:], 'Registered image, slice: %i' % ref_slice);", "_____no_output_____" ] ], [ [ "## Show the transformation matrix", "_____no_output_____" ] ], [ [ "numpy.set_printoptions(precision=3,suppress=True)\nTM = algo.get_transformation_matrix_forward()\nprint(TM.as_array())", "_____no_output_____" ] ], [ [ "So as we predicted earlier, there is little rotation (close to identity in the top 3x3 of the matrix), and there is large translation (final column).", "_____no_output_____" ], [ "## Displacement field image\nThe displacement field image maps the voxels of the floating image to the final warped image. They are particularly interesting for non-rigid registrations, where transformation matrices no longer exist.\n\nEach voxel of the displacement field image contains an (x,y,z) coordinate, so the resulting image is 4D.\n\n(As a small technicality, the NIfTI format stores the time component in the 4th dimension, and the displacement coordinates in the 5th dimension. Therefore the displacement field image is actually a 5D image with a singleton in the 4th dimension.)", "_____no_output_____" ] ], [ [ "displacement = algo.get_displacement_field_forward()\n\nplt.figure()\nfor i in range(3):\n plt.subplot(3, 1, 1 + i)\n imshow(displacement.as_array()[ref_slice,:,:,0,i],\n 'Displacement field %s-direction, slice: %i' % (\"xyz\"[i], ref_slice))", "_____no_output_____" ] ], [ [ "# Resampling\n\nImagine that you got the motion information from another source and wanted to resample an image with it. Easy!\n\nWe just need to create a resampler and set our image to resample as a floating image. As image domains can be different (i.e. images from different modalities, images with different field of view, etc), we also need to give the resampler a \"template\" image to define the resampled space. We can do this by setting the reference image. If we want to resample the image to the same domain as the original, you can set the floating image and the reference image to be the same.\n\nWe would also need to define the type of transformation. We can use transformation matrices here, but it can also be a displacement of a deformation field, if your application requires it. \n\nFinally, we can also define the type of interpolation to use. In this example, we use linear with `set_interpolation_type_to_linear()`, but we can also use `_nearest_neighbour()`, `_cubic_spline()` and `_sinc()` instead of `_linear()`. Or just set it with `set_interpolation_type(int)`, with their respective order of interpolation.\n\n\n", "_____no_output_____" ] ], [ [ "tm = algo.get_transformation_matrix_forward()\n# get the resampler!\nresampler = Reg.NiftyResample()\n# Make sure we know what the resampled image domain looks like (this can be the same as the image to resample)\nresampler.set_reference_image(ref)\n# Set image to resample\nresampler.set_floating_image(flo)\n# Add the desired transformation to apply\nresampler.add_transformation(tm)\nresampler.set_padding_value(0)\n# Use linear interpolation\nresampler.set_interpolation_type_to_linear()\n# Go!\nresampler.process()\n\nplt.figure()\nimshow(resampler.get_output().as_array()[ref_slice,:,:], 'Resampled image, slice: %i' % ref_slice);", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec54c946bf5ace1885fdf816d0d28d6e6a02daee
154,760
ipynb
Jupyter Notebook
tutorials/B_Model_Tutorial_1_Distributions.ipynb
adrien-mogenet/pomegranate
3bda1f0c3ee8651496c2e1d758fcba13ca4b8d06
[ "MIT" ]
2
2021-05-19T00:44:38.000Z
2022-03-28T16:56:51.000Z
tutorials/B_Model_Tutorial_1_Distributions.ipynb
adrien-mogenet/pomegranate
3bda1f0c3ee8651496c2e1d758fcba13ca4b8d06
[ "MIT" ]
null
null
null
tutorials/B_Model_Tutorial_1_Distributions.ipynb
adrien-mogenet/pomegranate
3bda1f0c3ee8651496c2e1d758fcba13ca4b8d06
[ "MIT" ]
null
null
null
122.243286
50,374
0.84023
[ [ [ "## Probability Distributions", "_____no_output_____" ], [ "author: Jacob Schreiber <br>\ncontact: [email protected]", "_____no_output_____" ], [ "This tutorial will cover the various distributions that are implemented in pomegranate. These distributions can be used by themselves, or more typically as a part of a larger compositional model like a hidden Markov model. \n\nThe distributions that are currently available:\n\nUnivariate Distributions\n 1. BernoulliDistribution\n 2. BetaDistribution\n 3. DiscreteDistribution\n 4. ExponentialDistribution\n 5. GammaDistribution\n 6. LogNormalDistribution\n 7. NormalDistribution\n 8. PoissonDistribution\n 9. UniformDistribution\n \nUnivariate Kernel Densities\n 1. GaussianKernelDensity\n 2. UniformKernelDensity\n 3. TriangleKernelDensity\n \nMultivariate Distributions\n 1. IndependentComponentsDistribution\n 2. Dirichlet Distribution\n 3. MultivariateGaussianDistribution\n 4. ConditionalProbabilityTable\n 5. JointProbabilityTable\n\nThe following methods are supported by all distributions:\n\n```\n1. d.probability(X): Return the probability of a sample under the distribution or a vector of samples\n2. d.log_probability(X): Return the log probability of a sample under the distribution or a vector of samples\n3. d.fit(X, weights=None, inertia): Use MLE estimates to update the parameters of the distribution. Optional weight vector is accepted, or inertia that pushes parameters from where they currently are to the update that portion of the way.\n4. d.summarize(X, weights=None): Extract and update the stored sufficient statistics on a data set with optional weights, but don't update the parameters yet\n5. d.from_summaries(X, inertia=0.0): Use the stored sufficient statistics to do a parameter update\n6. d.sample(n=1): Generate a sample, or a vector of samples, from the distribution\n\n7. d.to_json(): Serialize the distribution to a string json\n8. Distribution.from_json(s): Load up a stored distriibution, either from a file if passed a filename that ends in '.json', or from the string passed in itself.\n\n9. d.copy(): Make a deep copy of the distribution\n10. d.freeze(): Freeze the distribution, making 'fit' and 'from_summaries' not change model parameters\n11. d.thaw(): Unfreeze the distribution so that it can be updated agin.\n```\n\nUnivariate distributions also have a `plot(n=1000, **kwargs)` command, where you can plot a histogram of `n` randomly generated samples from the distribution, which will pass matplotlib keyword arguments to the `plt.hist` function. \n\nLets look at a few examples.", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn; seaborn.set_style('whitegrid')\nimport numpy\n\nfrom pomegranate import *\n\nnumpy.random.seed(0)\nnumpy.set_printoptions(suppress=True)\n\n%load_ext watermark\n%watermark -m -n -p numpy,scipy,pomegranate", "Sat Oct 06 2018 \n\nnumpy 1.14.2\nscipy 1.0.0\npomegranate 0.10.0\n\ncompiler : GCC 7.2.0\nsystem : Linux\nrelease : 4.15.0-34-generic\nmachine : x86_64\nprocessor : x86_64\nCPU cores : 4\ninterpreter: 64bit\n" ] ], [ [ "## The API\n\n### Initialization\n\nLet's first look at an example of using the methods in the API. First, we can create probability distributions by passing in the parameters if we know them.", "_____no_output_____" ] ], [ [ "d = NormalDistribution(5, 2)\nd2 = ExponentialDistribution(5)\nd3 = LogNormalDistribution(2, 0.4)", "_____no_output_____" ] ], [ [ "If what you have is data and you'd like to fit your distribution to the data, rather than having parameters beforehand, you can use the `from_samples` class method to pass in the points and optional weights.", "_____no_output_____" ] ], [ [ "x = numpy.random.normal(10, 1, size=100)\n\nd4 = NormalDistribution.from_samples(x)\nd5 = ExponentialDistribution.from_samples(x)\nd6 = LogNormalDistribution.from_samples(x)", "_____no_output_____" ] ], [ [ "If the data is univariate we can pass in a simple vector. If our data is multivariate and we'd like to fit a multivariate distribution we can pass in a matrix.", "_____no_output_____" ] ], [ [ "x = numpy.random.normal(10, 1, size=(1000, 3))\n\nd7 = MultivariateGaussianDistribution.from_samples(x)\nd7.mu, d7.cov", "_____no_output_____" ] ], [ [ "If we want to model our multivariate data with a different distribution on each feature, assuming that each feature is independent of each other, we can use an IndependentComponentsDistribution. This can be done either by passing in the distributions to the initialization, or as `from_samples`.", "_____no_output_____" ] ], [ [ "d8 = IndependentComponentsDistribution([d4, d5, d6])\nd8", "_____no_output_____" ] ], [ [ "If we wanted to learn a multivariate Gaussian distribution but with a forced diagonal covariance matrix we can model each feature are independent normal distributions, like such.", "_____no_output_____" ] ], [ [ "d8.from_samples(x, distributions=NormalDistribution)", "_____no_output_____" ] ], [ [ "Note that the distributions here are displaying the mean and standard deviation, whereas the `MultivariateGaussianDistribution` is showing the mean and ~covariance~, which is the standard deviation squared. When adjusted accordingly, the means here line up with the vector of means from before, and the standard deviations are equal to the square root of the diagonal of the covariance matrix.\n\nLastly, if we wanted to learn an independent components distribution with different distributions on each feature, we can pass in a list of distributions.", "_____no_output_____" ] ], [ [ "d8.from_samples(x, distributions=[NormalDistribution, ExponentialDistribution, LogNormalDistribution])", "_____no_output_____" ] ], [ [ "### Plotting\n\nIf we want to visualize them, we can use the plot command, which randomly draws samples from the model and plots the histogram of those samples.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(12, 4))\nplt.subplot(231)\nplt.title(\"Normal Distribution\", fontsize=14)\nd.plot(1000, edgecolor='c', color='c', bins=20)\n\nplt.subplot(232)\nplt.title(\"Exponential Distribution\", fontsize=14)\nd2.plot(1000, edgecolor='m', color='m', bins=20)\n\nplt.subplot(233)\nplt.title(\"Log Normal Distribution\", fontsize=14)\nd3.plot(1000, edgecolor='g', color='g', bins=20)\n\nplt.subplot(234)\nplt.title(\"Fit Normal Distribution\", fontsize=14)\nd4.plot(1000, edgecolor='c', color='c', bins=20)\n\nplt.subplot(235)\nplt.title(\"Fit Exponential Distribution\", fontsize=14)\nd5.plot(1000, edgecolor='m', color='m', bins=20)\n\nplt.subplot(236)\nplt.title(\"Fit Log Normal Distribution\", fontsize=14)\nd6.plot(1000, edgecolor='g', color='g', bins=20)\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "Naturally, if you wanted smoother probability distributions, you could calculate the probability at each point along a given grid and plot those probabilities.", "_____no_output_____" ] ], [ [ "x1 = numpy.arange(-1, 11.1, 0.1)\nx2 = numpy.arange(0, 2, 0.1)\nx3 = numpy.arange(0, 20, 0.1)\n\nplt.figure(figsize=(14, 3))\nplt.subplot(231)\nplt.title(\"Normal Distribution\", fontsize=14)\nplt.fill_between(x1, 0, d.probability(x1), color='c')\n\nplt.subplot(232)\nplt.title(\"Exponential Distribution\", fontsize=14)\nplt.fill_between(x2, 0, d2.probability(x2), color='m')\n\nplt.subplot(233)\nplt.title(\"Log Normal Distribution\", fontsize=14)\nplt.fill_between(x3, 0, d3.probability(x3), color='g')\n\nplt.subplot(234)\nplt.title(\"Fit Normal Distribution\", fontsize=14)\nplt.fill_between(x3, 0, d4.probability(x3), color='c')\n\nplt.subplot(235)\nplt.title(\"Fit Exponential Distribution\", fontsize=14)\nplt.fill_between(x3, 0, d5.probability(x3), color='m')\n\nplt.subplot(236)\nplt.title(\"Fit Log Normal Distribution\", fontsize=14)\nplt.fill_between(x3, 0, d6.probability(x3), color='g')\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "### Probability / Log Probability\n\nAll distributions can calculate probabilities and log probabilities using those respective methods. Different distributions will give very different probabilities.", "_____no_output_____" ] ], [ [ "d.probability(1), d2.probability(1), d3.probability(1)", "_____no_output_____" ] ], [ [ "A vector of values can also be passed in.", "_____no_output_____" ] ], [ [ "d.probability([1, 5, 7, 8, 3])", "_____no_output_____" ] ], [ [ "The same works for multivariate data.", "_____no_output_____" ] ], [ [ "d7.probability([[9, 10, 11]]), d8.probability([[9, 10, 11]])", "_____no_output_____" ] ], [ [ "For the independent components distribution the probability is the multiplication of the probabilities for all three dimensions.", "_____no_output_____" ] ], [ [ "d8.distributions[0].probability(9) * d8.distributions[1].probability(10) * d8.distributions[2].probability(11)", "_____no_output_____" ] ], [ [ "### Fitting", "_____no_output_____" ], [ "Probability distributions can be fit directly to data, as shown above, using the `from_samples` class method. However, a fit distribution can also be fit to new data using the `fit` method. This method uses maximum likelihood estimates to derive new parameters and is not affected by the current values of the distribution unless an inertia is set, which defines the proportion of the original distribution to use, the default being 0.", "_____no_output_____" ] ], [ [ "X = numpy.random.normal(6, 2, size=1000,)\n\nd = NormalDistribution(100, 1)\nd.fit(X)\nd", "_____no_output_____" ], [ "d = NormalDistribution(100, 1)\nd.fit(X, inertia=0.5)\nd", "_____no_output_____" ] ], [ [ "The fit method can also be given weights, in which case weighted maximum likelihood estimates are used. This is how expectation-maximization is done for compositional models. In this next example we'll give 50 samples with mean 5 and 50 samples with mean 9 and weight those samples with mean 9 as 4 times more than those with weight 5. If the samples were unweighted one would expect the result to be 7. However, with the higher magnitude samples being weighted more heavily, the result will actually be closer to 9.", "_____no_output_____" ] ], [ [ "X = numpy.random.normal(5, 2, size=100,)\nX[50:] += 4\n\nw = numpy.ones(100)\nw[:50] = 0.25\n\nd = NormalDistribution(10, 1)\nd.fit(X, w)\nd", "_____no_output_____" ] ], [ [ "## Discrete Distributions", "_____no_output_____" ], [ "A notable deviant from the numerics logic is the Discrete Distribution. Instead of passing parameters as floats, you instead pass in a dictionary where keys can be any objects and values are the probability of them occurring. Internally the objects that are the keys get converted to integer indices to an array whose values are the probability of that integer occuring. All models store a keymap that converts the inputs to those models to the indices of the discrete distribution. If you try to calculate the log probability of an item not present in the distribution, the default behavior is to return negative infinity, or 0.0 probability.", "_____no_output_____" ] ], [ [ "d = DiscreteDistribution({'A': 0.1, 'C': 0.25, 'G': 0.50, 'T': 0.15})\nprint d.probability( 'A')\nprint d.probability( 'G')\nprint d.probability('????')", "0.10000000000000002\n0.5\n0.0\n" ] ], [ [ "Updating a discrete distributon is the same as updating other distributions.", "_____no_output_____" ] ], [ [ "X = list('ACGATACACTGAATGACAGCAGTCACTGACAGTAGTACGAGTAGTAGCAGAGAGTAATAAAGAATTAATATATGACACTACGAAAAAAATGCATCG')\n\nd.fit(X)\n\nprint d.parameters[0]\nprint 1. * numpy.unique(X, return_counts=True)[1] / len(X)", "{'A': 0.4375, 'C': 0.15625, 'T': 0.19791666666666666, 'G': 0.20833333333333334}\n[0.4375 0.15625 0.20833333 0.19791667]\n" ] ], [ [ "### The Kernel Density", "_____no_output_____" ], [ "The Gaussian Kernel Density is a non-parametric distribution that, instead of parameters, stores the data points that it was trained on directly. When initializing a kernel density you simply pass in the points. These points are converted to a probability distribution by essentially dropping some probability distribution on top of each point and then dividing the density by the number of points, ensuring that the area still integrates to 1. We can see this in action with the Gaussian kernel density which drops a normal distribution on each point with standard deviation equal to the bandwidth.", "_____no_output_____" ] ], [ [ "d = GaussianKernelDensity( [0.5, 1.2, 4.2, 1.9, 5.4, 3.4], bandwidth=1 )\nd.plot(n=100000, edgecolor='c', color='c', bins=50)\nplt.show()", "_____no_output_____" ] ], [ [ "Changing the bandwidth parameter is equivalent to reducing the variance on a Gaussian. It makes the densities more central around the points, but can cause overfitting.", "_____no_output_____" ] ], [ [ "d = GaussianKernelDensity( [0.5, 1.2, 4.2, 1.9, 5.4, 3.4], bandwidth=0.2 )\nd.plot(n=100000, edgecolor='c', color='c', bins=50)", "_____no_output_____" ] ], [ [ "Passing in weights can change the influence of each sample for the final probability distribution.", "_____no_output_____" ] ], [ [ "d = GaussianKernelDensity( [0.5, 1.2, 4.2, 1.9, 5.4, 3.4], weights=[1, 1, 1, 3, 1, 1], bandwidth=0.2 )\nd.plot( n=100000, edgecolor='c', color='c', bins=100 )", "_____no_output_____" ] ], [ [ "## Out-of-core learning\n\nDistributions also have the `summarize` and `from_summaries` method that implement out-of-core learning. More will be available in the out-of-core learning tutorial, but the gist is that you can train on an amount of data that doesn't fit in memory and still yield exact updates. This works for any model in pomegranate, but lets illustrate it for an independent components distribution made up of three very different distributions.", "_____no_output_____" ] ], [ [ "from pomegranate import *\nimport numpy\n\nX = numpy.random.normal(16, 1, size=(1000, 3))\n\nd = IndependentComponentsDistribution([NormalDistribution(5, 1), \n ExponentialDistribution(7), \n LogNormalDistribution(0.6, 0.3)])\n\nd2 = d.copy()\n\nd.summarize(X[:500])\nd.summarize(X[500:])\nd.from_summaries()\nd", "_____no_output_____" ], [ "d2.fit(X)\nd2", "_____no_output_____" ] ], [ [ "We can also take a look at the JSON serialization. JSONs are the perfect way to store these models given their human interpretability, and the ability to recursively store JSONs within other JSONs, such as more complicated models (such as HMMs) will need to store the JSON of each distribution. It is useful to store these models after the computationally intensive task of training them, so that it need not be repeated.", "_____no_output_____" ] ], [ [ "print d.to_json()", "{\n \"frozen\" : false,\n \"class\" : \"Distribution\",\n \"parameters\" : [\n [\n {\n \"frozen\" : false,\n \"class\" : \"Distribution\",\n \"parameters\" : [\n 15.975331623897368,\n 0.9839454537444303\n ],\n \"name\" : \"NormalDistribution\"\n },\n {\n \"frozen\" : false,\n \"class\" : \"Distribution\",\n \"parameters\" : [\n 0.06273786783336632\n ],\n \"name\" : \"ExponentialDistribution\"\n },\n {\n \"frozen\" : false,\n \"class\" : \"Distribution\",\n \"parameters\" : [\n 2.7687181529109472,\n 0.06401250783306929\n ],\n \"name\" : \"LogNormalDistribution\"\n }\n ],\n [\n 1.0,\n 1.0,\n 1.0\n ]\n ],\n \"name\" : \"IndependentComponentsDistribution\"\n}\n" ] ], [ [ "## Serialization", "_____no_output_____" ], [ "Distributions (except tables right now) support serialization to JSONs using `to_json()` and `Distribution.from_json(json)`. We can see a few examples easily.", "_____no_output_____" ] ], [ [ "print(NormalDistribution(5, 2).to_json())", "{\n \"frozen\" :false,\n \"class\" :\"Distribution\",\n \"parameters\" :[\n 5.0,\n 2.0\n ],\n \"name\" :\"NormalDistribution\"\n}\n" ], [ "print(DiscreteDistribution({'A': 0.5, 'B': 0.25, 'C': 0.25}).to_json())", "{\n \"frozen\" :false,\n \"dtype\" :\"str\",\n \"class\" :\"Distribution\",\n \"parameters\" :[\n {\n \"A\" :0.5,\n \"C\" :0.25,\n \"B\" :0.25\n }\n ],\n \"name\" :\"DiscreteDistribution\"\n}\n" ], [ "print(GammaDistribution(5, 2).to_json())", "{\n \"frozen\" :false,\n \"class\" :\"Distribution\",\n \"parameters\" :[\n 5.0,\n 2.0\n ],\n \"name\" :\"GammaDistribution\"\n}\n" ] ], [ [ "We can load them up using the base Distribution class. This is done because, when storing compositional models, they typically don't know what type of distribution is being stored.", "_____no_output_____" ] ], [ [ "NormalDistribution(1, 1).probability(3)", "_____no_output_____" ], [ "Distribution.from_json(NormalDistribution(1, 1).to_json()).probability(3)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ec54cf0b78adf656020eb8f129a2223c459544bb
90,749
ipynb
Jupyter Notebook
CEKmachine02.ipynb
kyagrd/grad-compiler2020
019ce1629803a95bef2db1181abc1bb02939772c
[ "MIT" ]
3
2020-09-02T07:32:40.000Z
2020-12-03T06:22:21.000Z
CEKmachine02.ipynb
hnu-pl/grad-compiler2020
019ce1629803a95bef2db1181abc1bb02939772c
[ "MIT" ]
null
null
null
CEKmachine02.ipynb
hnu-pl/grad-compiler2020
019ce1629803a95bef2db1181abc1bb02939772c
[ "MIT" ]
null
null
null
27.154099
190
0.421151
[ [ [ "# CEK 기계에 기본제공연산 추가\nCEK 기계는 80년대에 Friedman과 Felleisen이 SECD 기계(Landin 1964)를 더 말끔하게 정리한 것이다.\n\n여기서는 지난번 노트북에서 살펴본 CEK 기계에 기본제공연산(pritivmve operation)을 추가해 보자.\n강의 일정상 지나친 복잡함은 피하기 위해 정수값들에 대한 기본연산만을 고려하기로 하자.\n\n###### 참고자료\n* https://www.cs.bham.ac.uk/~hxt/2015/compilers/compiling-functional.pdf\n* https://en.wikipedia.org/wiki/SECD_machine\n* https://www.brics.dk/RS/03/33/\n* https://pages.cpsc.ucalgary.ca/~robin/FMCS/FMCS2014/Prashant_talk.pdf\n* https://github.com/kseo/secd", "_____no_output_____" ] ], [ [ ":opt no-lint", "_____no_output_____" ], [ "type Nm = String\n\ndata Exp = Var Nm -- x\n | App Exp Exp -- e1 e2\n | Lam Nm Exp -- \\x.e\n | Lit Int -- n\n | Prm Prim [Exp] -- f(x1,...,xn)\n deriving Show\n\ndata Prim = Suc -- +1을 하는 인자 1개짜리 기초연산\n | Add -- +를 하는 인자 2개짜리 기초연산\n deriving Show", "_____no_output_____" ], [ "type CEK = (Code,Env,Kont)\n\ndata Code = OpE Exp -- 계산이 끝나지 않은 식\n | OpV Value -- 계산이 끝난 값\n | OpArg -- primitive 연산에 대한 인자를 처리\n | OpCall -- 인자가 다 채워진 상태에서 primtive 연산 발동\n deriving Show\ntype Env = [(Nm,Value)]\ntype Kont = [Frame]\n\ndata Value = Vint Int -- n\n | Clos Exp Env -- < \\x.e, env >\n deriving Show\n\ndata Frame = FrV Value -- (v O)\n | FrE Exp Env -- (O e env)\n | FrP Prim [Value] [Exp] Env -- (f [vi,..] O [ei,...] env)\n deriving Show", "_____no_output_____" ] ], [ [ "$ \\big\\langle x ~\\big|~ \\sigma ~\\big|~ \\kappa \\big\\rangle\n \\longrightarrow\n \\big\\langle \\sigma(x) ~\\big|~ \\sigma ~\\big|~ \\kappa \\big\\rangle $\n\n$ \\big\\langle e_1~e_2 ~\\big|~ \\sigma ~\\big|~ \\kappa \\big\\rangle\n \\longrightarrow\n \\big\\langle e_1 ~\\big|~ \\sigma ~\\big|~ (\\bigcirc\\,e_2\\;\\sigma),\\kappa \\big\\rangle $\n\n$ \\big\\langle \\lambda x.e ~\\big|~ \\sigma ~\\big|~ \\kappa \\big\\rangle\n \\longrightarrow \n \\big\\langle \\langle\\lambda x.e,\\sigma\\rangle ~\\big|~ \\sigma ~\\big|~ \\kappa \\big\\rangle $\n\n$ \\big\\langle v_1 ~\\big|~ \\sigma_1 ~\\big|~ (\\bigcirc\\,e_2\\;\\sigma_2),\\kappa \\big\\rangle\n \\longrightarrow\n \\big\\langle e_2 ~\\big|~ \\sigma_2 ~\\big|~ (v_1\\,\\bigcirc),\\kappa \\big\\rangle $\n\n$ \\big\\langle v_2 ~\\big|~ \\sigma_2 ~\\big|~ (\\langle\\lambda x.e,\\sigma_1\\rangle\\,\\bigcirc),\\kappa \\big\\rangle\n \\longrightarrow\n \\big\\langle e ~\\big|~ [x\\mapsto v_2]\\sigma_1 ~\\big|~ \\kappa \\big\\rangle $", "_____no_output_____" ], [ "$ \\big\\langle f(\\bar{e}) ~\\big|~ \\sigma ~\\big|~ \\kappa \\big\\rangle\n \\longrightarrow \n \\big\\langle OpArg ~\\big|~ \\sigma ~\\big|~ (f~\\bar{e}\\;\\sigma),\\kappa \\big\\rangle\n $\n\n$ \\big\\langle OpArg ~\\big|~ \\sigma' ~\\big|~ (f~\\bar{v}~e~\\bar{e}\\;\\sigma),\\kappa \\big\\rangle\n\\longrightarrow\n\\big\\langle e ~\\big|~ \\sigma ~\\big|~ (f~\\bar{v}\\bigcirc\\bar{e}\\;\\sigma),\\kappa \\big\\rangle $\n\n$\\big\\langle v ~\\big|~ \\sigma' ~\\big|~ (f~\\bar{v}\\bigcirc \\bar{e}\\;\\sigma),\\kappa \\big\\rangle \n\\longrightarrow\n\\big\\langle OpArg ~\\big|~ \\sigma' ~\\big|~ (f~\\bar{v}~v~\\bar{e}\\;\\sigma),\\kappa \\big\\rangle\n$\n\n$\\big\\langle OpArg ~\\big|~ \\sigma' ~\\big|~ (f~\\bar{v}\\;\\sigma),\\kappa \\big\\rangle \n\\longrightarrow\n\\big\\langle OpCall ~\\big|~ \\sigma' ~\\big|~ (f~\\bar{v}\\;\\sigma),\\kappa \\big\\rangle\n$\n\n$\\big\\langle OpCall ~\\big|~ \\sigma' ~\\big|~ (f~\\bar{v}\\;\\sigma),\\kappa \\big\\rangle\n\\longrightarrow\n\\big\\langle \\texttt{callPrim}f(\\bar{v}) ~\\big|~ \\sigma ~\\big|~ \\kappa \\big\\rangle\n$", "_____no_output_____" ] ], [ [ "lookup' x env = case lookup x env of Just v -> v\n Nothing -> error(\"x is unknown\")\n\n-- 기본제공연산이 호출되었을 때 동작 정의\ncallPrim Suc [Vint n] = Vint (n+1)\ncallPrim Add [Vint n2, Vint n1] = Vint (n1+n2)\n\nstep :: CEK -> Maybe CEK\nstep (OpE(Var x), env, k) = Just (OpV(lookup' x env), env, k)\nstep (OpE(App e1 e2), env, k) = Just (OpE e1, env, FrE e2 env : k)\nstep (OpE(e@Lam{}), env, k) = Just (OpV(Clos e env), env, k)\nstep (OpE(Lit n), env, k) = Just (OpV(Vint n), env, k)\nstep (OpE(Prm f es), env, k) = Just (OpArg, env, FrP f [] es env : k) -- 기본제공연산식 처리 시작\nstep (OpV v, env1, FrE e2 env2 : k) = Just (OpE e2, env2, FrV v : k)\nstep (OpV v, env1, FrV(Clos (Lam x e) env2) : k) = Just (OpE e, (x,v) : env2, k)\nstep (OpArg, env1, FrP f vs (e:es) env : k) = Just (OpE e, env, FrP f vs es env : k) -- 다음 인자값 계산\nstep (OpV v, env1, FrP f vs es env : k) = Just (OpArg, env1, FrP f (vs++[v]) es env : k) -- 계산된 인자값 프레임에 추가\nstep (OpArg, env1, FrP f vs [] env : k) = Just (OpCall, env1, FrP f vs [] env : k) -- 다음 인자값 계산 시도하지만 더 이상 인자 없는 경우 처리\nstep (OpCall, env1, FrP f vs [] env : k) = Just (OpV(callPrim f vs), env, k) -- 모든 인자 계산 후 기본제공연산 호출\nstep _ = Nothing", "_____no_output_____" ], [ "{-# LANGUAGE FlexibleInstances #-}\nimport IHaskell.Display\nimport Data.List (intersperse)\n\nclass TeX a where\n toTeX :: a -> String\n\ninstance TeX Exp where\n toTeX (Var x) = x\n toTeX (App e1 e2) = \"(\"++toTeX e1++\"\\\\;\"++toTeX e2++\")\" \n toTeX (Lam x e) = \"(\\\\lambda{}\"++x++\".\"++toTeX e++\")\"\n toTeX (Lit n) = show n\n toTeX (Prm f es) = \"\\\\textsf{\"++show f++\"}\"++toTeX es\n\ninstance TeX Code where\n toTeX (OpE e) = toTeX e\n toTeX (OpV v) = toTeX v\n toTeX (OpArg) = \"\\\\texttt{arg}\"\n toTeX (OpCall) = \"\\\\texttt{call}\"\n\ninstance TeX Value where\n toTeX (Vint n) = show n\n toTeX (Clos e env) = \"\\\\langle{}\" ++ toTeX e ++ \",\" ++ revTeX env ++ \"\\\\rangle{}\"\n\ninstance TeX Frame where\n toTeX (FrV v) = \"(\"++toTeX v++\"\\\\,\\\\bigcirc{})\"\n toTeX (FrE e env) = \"(\\\\bigcirc{}\\\\,\"++toTeX e++\"\\\\;\"++revTeX env++\")\"\n toTeX (FrP f vs es env) = \"(\\\\textsf{\"++show f++\"}\"++revTeX vs++\"\\\\,\\\\bigcirc{}\\\\,\"++toTeX es++\"\\\\;\"++revTeX env++\")\"\n\ninstance TeX (Nm,Value) where\n toTeX (x,v) = x++\"\\\\mapsto{}\"++toTeX v\n\ninstance TeX CEK where\n toTeX (c,env,k) = \"\\\\big\\\\langle{}\"\n ++ toTeX c ++ \"\\\\;\\\\big|\\\\;\" ++ revTeX env ++ \"\\\\;\\\\big|\\\\;\" ++ toTeX k\n ++ \"\\\\big\\\\rangle{}\"\n\ninstance TeX a => TeX (Maybe a) where\n toTeX (Just x)= \"\\\\texttt{Just}(\"++toTeX x++\")\"\n toTeX Nothing = \"\\\\texttt{Nothing}\"\n\ninstance TeX a => TeX [a] where\n toTeX xs = \"[\" ++ (concat . intersperse \",\" $ map toTeX xs) ++ \"]\"\n\nrevTeX = toTeX . reverse\n\nnewtype LaTeX a = LaTeX a\n\nhtmlTeX a = html $ \"$\"++toTeX a++\"$\"\n\ninstance TeX a => IHaskellDisplay (LaTeX a) where\n display (LaTeX a) = return $ Display [htmlTeX a]", "_____no_output_____" ] ], [ [ "이전 예제는 그대로 잘 동작한다.", "_____no_output_____" ] ], [ [ "fst_1_2 = App (App (Lam \"x\" $ Lam \"y\" $ Var \"x\") (Lit 1)) (Lit 2)\nfst_1_2\nLaTeX fst_1_2\nLaTeX (Prm Suc[Lit 3])", "_____no_output_____" ], [ "import Data.Maybe\n\nmapM_ print $ takeWhile isJust $ iterate (step =<<) (Just(OpE fst_1_2,[],[]))", "_____no_output_____" ], [ "map LaTeX . takeWhile isJust $ iterate (step =<<) (Just(OpE fst_1_2,[],[]))", "_____no_output_____" ], [ "Just(OpE(Prm Suc[Lit 3]),[],[])\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\n\nisJust (Just _) = True\nisJust Nothing = False\n\nmap LaTeX . takeWhile isJust . iterate (step =<<) $ Just(OpE(Prm Suc[Lit 3]),[],[])", "_____no_output_____" ], [ "Just(OpE(Prm Add[Lit 3,Lit 4]),[],[])\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\nstep =<< it\n\nisJust (Just _) = True\nisJust Nothing = False\n\nmap LaTeX . takeWhile isJust . iterate (step =<<) $ Just(OpE(Prm Add[Lit 3,Lit 4]),[],[])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
ec54d2371024c2fa5f14beca2f79273a19a6bf35
13,948
ipynb
Jupyter Notebook
udacity_ml/lessons/ObjectOrientedProgramming/JupyterNotebooks/4.OOP_code_magic_methods/magic_methods.ipynb
issagaliyeva/machine_learning
63f4d39a95147cdac4ef760cb47dffc318793a99
[ "MIT" ]
null
null
null
udacity_ml/lessons/ObjectOrientedProgramming/JupyterNotebooks/4.OOP_code_magic_methods/magic_methods.ipynb
issagaliyeva/machine_learning
63f4d39a95147cdac4ef760cb47dffc318793a99
[ "MIT" ]
null
null
null
udacity_ml/lessons/ObjectOrientedProgramming/JupyterNotebooks/4.OOP_code_magic_methods/magic_methods.ipynb
issagaliyeva/machine_learning
63f4d39a95147cdac4ef760cb47dffc318793a99
[ "MIT" ]
null
null
null
39.179775
308
0.493978
[ [ [ "# Magic Methods\n\nBelow you'll find the same code from the previous exercise except two more methods have been added: an __add__ method and a __repr__ method. Your task is to fill out the code and get all of the unit tests to pass. You'll find the code cell with the unit tests at the bottom of this Jupyter notebook.\n\nAs in previous exercises, there is an answer key that you can look at if you get stuck. Click on the \"Jupyter\" icon at the top of this notebook, and open the folder 4.OOP_code_magic_methods. You'll find the answer.py file inside the folder.", "_____no_output_____" ] ], [ [ "import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Gaussian():\n \"\"\" Gaussian distribution class for calculating and \n visualizing a Gaussian distribution.\n \n Attributes:\n mean (float) representing the mean value of the distribution\n stdev (float) representing the standard deviation of the distribution\n data_list (list of floats) a list of floats extracted from the data file\n \n \"\"\"\n def __init__(self, mu = 0, sigma = 1):\n \n self.mean = mu\n self.stdev = sigma\n self.data = []\n\n\n \n def calculate_mean(self):\n \n \"\"\"Method to calculate the mean of the data set.\n \n Args: \n None\n \n Returns: \n float: mean of the data set\n \n \"\"\"\n \n #TODO: Calculate the mean of the data set. Remember that the data set is stored in self.data\n # Change the value of the mean attribute to be the mean of the data set\n # Return the mean of the data set \n self.mean = np.mean(self.data)\n return self.mean \n \n\n def calculate_stdev(self, sample=True):\n\n \"\"\"Method to calculate the standard deviation of the data set.\n \n Args: \n sample (bool): whether the data represents a sample or population\n \n Returns: \n float: standard deviation of the data set\n \n \"\"\"\n\n # TODO:\n # Calculate the standard deviation of the data set\n # \n # The sample variable determines if the data set contains a sample or a population\n # If sample = True, this means the data is a sample. \n # Keep the value of sample in mind for calculating the standard deviation\n #\n # Make sure to update self.stdev and return the standard deviation as well \n N = len(self.data) - 1 if sample else len(self.data) \n mu = self.mean \n sum_part = np.sum((self.data - mu)**2) \n \n self.stdev = np.sqrt(sum_part / N) \n return self.stdev\n \n\n def read_data_file(self, file_name, sample=True):\n \n \"\"\"Method to read in data from a txt file. The txt file should have\n one number (float) per line. The numbers are stored in the data attribute. \n After reading in the file, the mean and standard deviation are calculated\n \n Args:\n file_name (string): name of a file to read from\n \n Returns:\n None\n \n \"\"\"\n \n # This code opens a data file and appends the data to a list called data_list\n with open(file_name) as file:\n data_list = []\n line = file.readline()\n while line:\n data_list.append(int(line))\n line = file.readline()\n file.close()\n \n # TODO: \n # Update the self.data attribute with the data_list\n # Update self.mean with the mean of the data_list. \n # You can use the calculate_mean() method with self.calculate_mean()\n # Update self.stdev with the standard deviation of the data_list. Use the \n # calculate_stdev() method.\n self.data = data_list\n self.mean = self.calculate_mean()\n self.stdev = self.calculate_stdev(sample)\n \n \n def plot_histogram(self):\n \"\"\"Method to output a histogram of the instance variable data using \n matplotlib pyplot library.\n \n Args:\n None\n \n Returns:\n None\n \"\"\"\n \n # TODO: Plot a histogram of the data_list using the matplotlib package.\n # Be sure to label the x and y axes and also give the chart a title\n plt.title('Data distribution')\n plt.hist(self.data)\n plt.xlabel('x')\n plt.ylabel('count')\n plt.show()\n \n \n def pdf(self, x):\n \"\"\"Probability density function calculator for the gaussian distribution.\n \n Args:\n x (float): point for calculating the probability density function\n \n \n Returns:\n float: probability density function output\n \"\"\"\n \n # TODO: Calculate the probability density function of the Gaussian distribution\n # at the value x. You'll need to use self.stdev and self.mean to do the calculation\n mu = self.mean\n sigma = self.stdev\n return (1 / np.sqrt(2 * np.pi * sigma**2)) * np.e**-((x - mu)**2 / (2 * sigma**2))\n\n def plot_histogram_pdf(self, n_spaces = 50):\n\n \"\"\"Method to plot the normalized histogram of the data and a plot of the \n probability density function along the same range\n \n Args:\n n_spaces (int): number of data points \n \n Returns:\n list: x values for the pdf plot\n list: y values for the pdf plot\n \n \"\"\"\n \n #TODO: Nothing to do for this method. Try it out and see how it works.\n \n mu = self.mean\n sigma = self.stdev\n\n min_range = min(self.data)\n max_range = max(self.data)\n \n # calculates the interval between x values\n interval = 1.0 * (max_range - min_range) / n_spaces\n\n x = []\n y = []\n \n # calculate the x values to visualize\n for i in range(n_spaces):\n tmp = min_range + interval*i\n x.append(tmp)\n y.append(self.pdf(tmp))\n\n # make the plots\n fig, axes = plt.subplots(2,sharex=True)\n fig.subplots_adjust(hspace=.5)\n axes[0].hist(self.data, density=True)\n axes[0].set_title('Normed Histogram of Data')\n axes[0].set_ylabel('Density')\n\n axes[1].plot(x, y)\n axes[1].set_title('Normal Distribution for \\n Sample Mean and Sample Standard Deviation')\n axes[0].set_ylabel('Density')\n plt.show()\n\n return x, y\n\n def __add__(self, other):\n \n \"\"\"Magic method to add together two Gaussian distributions\n \n Args:\n other (Gaussian): Gaussian instance\n \n Returns:\n Gaussian: Gaussian distribution\n \n \"\"\"\n \n # TODO: Calculate the results of summing two Gaussian distributions\n # When summing two Gaussian distributions, the mean value is the sum\n # of the means of each Gaussian.\n #\n # When summing two Gaussian distributions, the standard deviation is the\n # square root of the sum of square ie sqrt(stdev_one ^ 2 + stdev_two ^ 2)\n \n # create a new Gaussian object\n result = Gaussian()\n \n # TODO: calculate the mean and standard deviation of the sum of two Gaussians\n result.mean = self.mean + other.mean # change this line to calculate the mean of the sum of two Gaussian distributions\n result.stdev = np.sqrt(self.stdev**2 + other.stdev**2) # change this line to calculate the standard deviation of the sum of two Gaussian distributions\n \n return result\n\n def __repr__(self):\n \n \"\"\"Magic method to output the characteristics of the Gaussian instance\n \n Args:\n None\n \n Returns:\n string: characteristics of the Gaussian\n \n \"\"\"\n \n # TODO: Return a string in the following format - \n # \"mean mean_value, standard deviation standard_deviation_value\"\n # where mean_value is the mean of the Gaussian distribution\n # and standard_deviation_value is the standard deviation of\n # the Gaussian.\n # For example \"mean 3.5, standard deviation 1.3\"\n \n return f'mean {self.mean}, standard deviation {self.stdev}'", "_____no_output_____" ], [ "# Unit tests to check your solution\n\nimport unittest\n\nclass TestGaussianClass(unittest.TestCase):\n def setUp(self):\n self.gaussian = Gaussian(25, 2)\n\n def test_initialization(self): \n self.assertEqual(self.gaussian.mean, 25, 'incorrect mean')\n self.assertEqual(self.gaussian.stdev, 2, 'incorrect standard deviation')\n\n def test_pdf(self):\n self.assertEqual(round(self.gaussian.pdf(25), 5), 0.19947,\\\n 'pdf function does not give expected result') \n\n def test_meancalculation(self):\n self.gaussian.read_data_file('numbers.txt', True)\n self.assertEqual(self.gaussian.calculate_mean(),\\\n sum(self.gaussian.data) / float(len(self.gaussian.data)), 'calculated mean not as expected')\n\n def test_stdevcalculation(self):\n self.gaussian.read_data_file('numbers.txt', True)\n self.assertEqual(round(self.gaussian.stdev, 2), 92.87, 'sample standard deviation incorrect')\n self.gaussian.read_data_file('numbers.txt', False)\n self.assertEqual(round(self.gaussian.stdev, 2), 88.55, 'population standard deviation incorrect')\n\n def test_add(self):\n gaussian_one = Gaussian(25, 3)\n gaussian_two = Gaussian(30, 4)\n gaussian_sum = gaussian_one + gaussian_two\n \n self.assertEqual(gaussian_sum.mean, 55)\n self.assertEqual(gaussian_sum.stdev, 5)\n\n def test_repr(self):\n gaussian_one = Gaussian(25, 3)\n \n self.assertEqual(str(gaussian_one), \"mean 25, standard deviation 3\")\n \ntests = TestGaussianClass()\n\ntests_loaded = unittest.TestLoader().loadTestsFromModule(tests)\n\nunittest.TextTestRunner().run(tests_loaded)", "......\n----------------------------------------------------------------------\nRan 6 tests in 0.007s\n\nOK\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
ec54e455c020073b08bbe336a0972e963696fe6b
77,500
ipynb
Jupyter Notebook
jupyter/Appendix-Low-Level-Concurrency.ipynb
c-Bung/OnJava8
fdca19e5518d3c6c63877ae864561df50306c474
[ "MIT" ]
183
2020-11-25T07:55:03.000Z
2022-03-29T06:58:13.000Z
jupyter/Appendix-Low-Level-Concurrency.ipynb
c-Bung/OnJava8
fdca19e5518d3c6c63877ae864561df50306c474
[ "MIT" ]
null
null
null
jupyter/Appendix-Low-Level-Concurrency.ipynb
c-Bung/OnJava8
fdca19e5518d3c6c63877ae864561df50306c474
[ "MIT" ]
241
2020-10-06T14:16:52.000Z
2022-03-31T15:10:15.000Z
31.671434
433
0.567974
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ec54eb34d070bdb209cf4bda1211dc693980a1cc
2,492
ipynb
Jupyter Notebook
tutorials/Model Weights Conversion(*Optional).ipynb
qywu/Chinese-GPT
bf87ea0b91ea23d614811973793c40790a02746c
[ "MIT" ]
45
2019-04-30T00:30:07.000Z
2022-03-30T09:39:38.000Z
tutorials/Model Weights Conversion(*Optional).ipynb
fancyerii/Chinese-GPT
bf87ea0b91ea23d614811973793c40790a02746c
[ "MIT" ]
6
2019-04-28T08:54:56.000Z
2020-09-02T08:07:57.000Z
tutorials/Model Weights Conversion(*Optional).ipynb
qywu/Chinese-GPT
bf87ea0b91ea23d614811973793c40790a02746c
[ "MIT" ]
6
2019-10-30T02:10:51.000Z
2021-07-29T05:59:54.000Z
23.28972
67
0.563002
[ [ [ "import numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F", "_____no_output_____" ], [ "from chinese_gpt import TransformerEncoder as Encoder\nfrom chinese_gpt import TransformerDecoderLM as Decoder\nfrom pytorch_pretrained_bert import BertModel, BertTokenizer", "_____no_output_____" ], [ "encoder = Encoder()\ndecoder = Decoder()\nbert_model = BertModel.from_pretrained(\"bert-base-chinese\")", "_____no_output_____" ], [ "encoder_state_dict = encoder.state_dict()\nbert_state_dict = bert_model.state_dict()\n\nfor item in encoder_state_dict.keys():\n if item in bert_state_dict:\n encoder_state_dict[item] = bert_state_dict[item]\n else:\n print(item)\nencoder.load_state_dict(encoder_state_dict)\ntorch.save(encoder.state_dict(), \"encoder.pth\")", "_____no_output_____" ], [ "decoder_state_dict = decoder.state_dict()\ntemp_state_dict = torch.load(\"model_state_epoch_62.th\")\n\nfor item in decoder_state_dict.keys():\n if item in temp_state_dict:\n decoder_state_dict[item] = temp_state_dict[item]\n else:\n print(item)\n \ndecoder.load_state_dict(decoder_state_dict)", "_____no_output_____" ], [ "torch.save(decoder.state_dict(), \"decoder.pth\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
ec54fa5461a32f3e53f7c1b11dc89084260a64c1
4,847
ipynb
Jupyter Notebook
examples/reference/elements/bokeh/Points.ipynb
srp3003/holoviews
efaa28203542e9f942662cd87449df40685061d9
[ "BSD-3-Clause" ]
null
null
null
examples/reference/elements/bokeh/Points.ipynb
srp3003/holoviews
efaa28203542e9f942662cd87449df40685061d9
[ "BSD-3-Clause" ]
null
null
null
examples/reference/elements/bokeh/Points.ipynb
srp3003/holoviews
efaa28203542e9f942662cd87449df40685061d9
[ "BSD-3-Clause" ]
null
null
null
40.057851
546
0.621622
[ [ [ "<div class=\"contentcontainer med left\" style=\"margin-left: -50px;\">\n<dl class=\"dl-horizontal\">\n <dt>Title</dt> <dd> Points Element</dd>\n <dt>Dependencies</dt> <dd>Bokeh</dd>\n <dt>Backends</dt>\n <dd><a href='./Points.ipynb'>Bokeh</a></dd>\n <dd><a href='../matplotlib/Points.ipynb'>Matplotlib</a></dd>\n <dd><a href='../plotly/Points.ipynb'>Plotly</a></dd>\n</dl>\n</div>", "_____no_output_____" ] ], [ [ "import numpy as np\nimport holoviews as hv\nfrom holoviews import opts, dim\nhv.extension('bokeh')", "_____no_output_____" ] ], [ [ "The ``Points`` element visualizes as markers placed in a space of two independent variables, traditionally denoted *x* and *y*. In HoloViews, the names ``'x'`` and ``'y'`` are used as the default key dimensions (``kdims``) of the element. We can see this from the default axis labels when visualizing a simple ``Points`` element:", "_____no_output_____" ] ], [ [ "np.random.seed(12)\ncoords = np.random.rand(50,2)\npoints = hv.Points(coords)\n\npoints.opts(color='k', marker='+', size=10)", "_____no_output_____" ] ], [ [ "Here the random x values and random y values are both considered to be the 'data' with no dependency between them (compare this to how [``Scatter``](./Scatter.ipynb) elements are defined). You can think of ``Points`` as simply marking positions in some two-dimensional space that can be sliced by specifying a 2D region-of-interest:", "_____no_output_____" ] ], [ [ "(points + points[0.6:0.8,0.2:0.5]).opts(\n opts.Points(color='k', marker='+', size=10))", "_____no_output_____" ] ], [ [ "Although the simplest ``Points`` element simply mark positions in a two-dimensional space without any associated value this doesn't mean value dimensions (``vdims``) aren't supported. Here is an example with two additional quantities for each point, declared as the ``vdims`` ``'z'`` and ``'size'`` visualized as the color and size of the dots, respectively:", "_____no_output_____" ] ], [ [ "np.random.seed(10)\ndata = np.random.rand(100,4)\n\npoints = hv.Points(data, vdims=['z', 'size'])\nlayout = points + points[0.3:0.7, 0.3:0.7].hist('z')\nlayout.opts(opts.Points(color='z', size=dim('size')*20))", "_____no_output_____" ] ], [ [ "In the right subplot, the ``hist`` method is used to show the distribution of samples along the first value dimension we added (*z*).\n\n\nThe marker shape specified above can be any supported by [matplotlib](http://matplotlib.org/api/markers_api.html), e.g. ``s``, ``d``, or ``o``; the other options select the color and size of the marker. For convenience with the [bokeh backend](../../../user_guide/Plotting_with_Bokeh.ipynb), the matplotlib marker options are supported using a compatibility function in HoloViews.", "_____no_output_____" ], [ "**Note**: Although the ``Scatter`` element is superficially similar to the [``Points``](./Points.ipynb) element (they can generate plots that look identical), the two element types are semantically quite different. The fundamental difference is that [``Points``](./Points.ipynb) are used to visualize data where the *y* variable is *dependent*. This semantic difference also explains why the histogram generated by ``hist`` call above visualizes the distribution of a different dimension than it does for [``Scatter``](./Scatter.ipynb).\n\nThis difference means that ``Points`` naturally combine elements that express independent variables in two-dimensional space, for instance [``Raster``](./Raster.ipynb) types such as [``Image``](./Image.ipynb). Similarly, ``Scatter`` expresses a dependent relationship in two-dimensions and combine naturally with ``Chart`` types such as [``Curve``](./Curve.ipynb).\n\n\nFor full documentation and the available style and plot options, use ``hv.help(hv.Points).``", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec55107bc332a38eeeeca555a0f8acd359268900
30,113
ipynb
Jupyter Notebook
assignments/assignment1/Linear classifier.ipynb
victor-sha/dlcourse_ai
cc2027637812f17d764a109fe2700e9e5a122e98
[ "MIT" ]
null
null
null
assignments/assignment1/Linear classifier.ipynb
victor-sha/dlcourse_ai
cc2027637812f17d764a109fe2700e9e5a122e98
[ "MIT" ]
null
null
null
assignments/assignment1/Linear classifier.ipynb
victor-sha/dlcourse_ai
cc2027637812f17d764a109fe2700e9e5a122e98
[ "MIT" ]
null
null
null
51.212585
2,172
0.660346
[ [ [ "# Задание 1.2 - Линейный классификатор (Linear classifier)\n\nВ этом задании мы реализуем другую модель машинного обучения - линейный классификатор. Линейный классификатор подбирает для каждого класса веса, на которые нужно умножить значение каждого признака и потом сложить вместе.\nТот класс, у которого эта сумма больше, и является предсказанием модели.\n\nВ этом задании вы:\n- потренируетесь считать градиенты различных многомерных функций\n- реализуете подсчет градиентов через линейную модель и функцию потерь softmax\n- реализуете процесс тренировки линейного классификатора\n- подберете параметры тренировки на практике\n\nНа всякий случай, еще раз ссылка на туториал по numpy: \nhttp://cs231n.github.io/python-numpy-tutorial/", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n\n%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "from dataset import load_svhn, random_split_train_val\nfrom gradient_check import check_gradient\nfrom metrics import multiclass_accuracy \nimport linear_classifer", "_____no_output_____" ] ], [ [ "# Как всегда, первым делом загружаем данные\n\nМы будем использовать все тот же SVHN.", "_____no_output_____" ] ], [ [ "def prepare_for_linear_classifier(train_X, test_X):\n train_flat = train_X.reshape(train_X.shape[0], -1).astype(np.float) / 255.0\n test_flat = test_X.reshape(test_X.shape[0], -1).astype(np.float) / 255.0\n \n # Subtract mean\n mean_image = np.mean(train_flat, axis = 0)\n train_flat -= mean_image\n test_flat -= mean_image\n \n # Add another channel with ones as a bias term\n train_flat_with_ones = np.hstack([train_flat, np.ones((train_X.shape[0], 1))])\n test_flat_with_ones = np.hstack([test_flat, np.ones((test_X.shape[0], 1))]) \n return train_flat_with_ones, test_flat_with_ones\n \ntrain_X, train_y, test_X, test_y = load_svhn(\"data\", max_train=10000, max_test=1000) \ntrain_X, test_X = prepare_for_linear_classifier(train_X, test_X)\n# Split train into train and val\ntrain_X, train_y, val_X, val_y = random_split_train_val(train_X, train_y, num_val = 1000)", "_____no_output_____" ] ], [ [ "# Играемся с градиентами!\n\nВ этом курсе мы будем писать много функций, которые вычисляют градиенты аналитическим методом.\n\nВсе функции, в которых мы будем вычислять градиенты, будут написаны по одной и той же схеме. \nОни будут получать на вход точку, где нужно вычислить значение и градиент функции, а на выходе будут выдавать кортеж (tuple) из двух значений - собственно значения функции в этой точке (всегда одно число) и аналитического значения градиента в той же точке (той же размерности, что и вход).\n```\ndef f(x):\n \"\"\"\n Computes function and analytic gradient at x\n \n x: np array of float, input to the function\n \n Returns:\n value: float, value of the function \n grad: np array of float, same shape as x\n \"\"\"\n ...\n \n return value, grad\n```\n\nНеобходимым инструментом во время реализации кода, вычисляющего градиенты, является функция его проверки. Эта функция вычисляет градиент численным методом и сверяет результат с градиентом, вычисленным аналитическим методом.\n\nМы начнем с того, чтобы реализовать вычисление численного градиента (numeric gradient) в функции `check_gradient` в `gradient_check.py`. Эта функция будет принимать на вход функции формата, заданного выше, использовать значение `value` для вычисления численного градиента и сравнит его с аналитическим - они должны сходиться.\n\nНапишите часть функции, которая вычисляет градиент с помощью численной производной для каждой координаты. Для вычисления производной используйте так называемую two-point formula (https://en.wikipedia.org/wiki/Numerical_differentiation):\n\n![image](https://wikimedia.org/api/rest_v1/media/math/render/svg/22fc2c0a66c63560a349604f8b6b39221566236d)\n\nВсе функции приведенные в следующей клетке должны проходить gradient check.", "_____no_output_____" ] ], [ [ "# TODO: Implement check_gradient function in gradient_check.py\n# All the functions below should pass the gradient check\n\ndef square(x):\n return float(x*x), 2*x\n\ncheck_gradient(square, np.array([3.0]))\n\ndef array_sum(x):\n assert x.shape == (2,), x.shape\n return np.sum(x), np.ones_like(x)\n\ncheck_gradient(array_sum, np.array([3.0, 2.0]))\n\ndef array_2d_sum(x):\n assert x.shape == (2,2)\n return np.sum(x), np.ones_like(x)\n\ncheck_gradient(array_2d_sum, np.array([[3.0, 2.0], [1.0, 0.0]]))", "Gradient check passed!\nGradient check passed!\nGradient check passed!\n" ], [ "\n[np.exp(x) for x in np.array([1,2,3])]", "_____no_output_____" ], [ "np.exp(np.array([0, 1, 2]))", "_____no_output_____" ] ], [ [ "## Начинаем писать свои функции, считающие аналитический градиент\n\nТеперь реализуем функцию softmax, которая получает на вход оценки для каждого класса и преобразует их в вероятности от 0 до 1:\n![image](https://wikimedia.org/api/rest_v1/media/math/render/svg/e348290cf48ddbb6e9a6ef4e39363568b67c09d3)\n\n**Важно:** Практический аспект вычисления этой функции заключается в том, что в ней учавствует вычисление экспоненты от потенциально очень больших чисел - это может привести к очень большим значениям в числителе и знаменателе за пределами диапазона float.\n\nК счастью, у этой проблемы есть простое решение -- перед вычислением softmax вычесть из всех оценок максимальное значение среди всех оценок:\n```\npredictions -= np.max(predictions)\n```\n(подробнее здесь - http://cs231n.github.io/linear-classify/#softmax, секция `Practical issues: Numeric stability`)", "_____no_output_____" ] ], [ [ "# TODO Implement softmax and cross-entropy for single sample\nprobs = linear_classifer.softmax(np.array([-10, 0, 10]))\n\n# Make sure it works for big numbers too!\nprobs = linear_classifer.softmax(np.array([1000, 0, 0]))\nassert np.isclose(probs[0], 1.0)", "_____no_output_____" ] ], [ [ "Кроме этого, мы реализуем cross-entropy loss, которую мы будем использовать как функцию ошибки (error function).\nВ общем виде cross-entropy определена следующим образом:\n![image](https://wikimedia.org/api/rest_v1/media/math/render/svg/0cb6da032ab424eefdca0884cd4113fe578f4293)\n\nгде x - все классы, p(x) - истинная вероятность принадлежности сэмпла классу x, а q(x) - вероятность принадлежности классу x, предсказанная моделью. \nВ нашем случае сэмпл принадлежит только одному классу, индекс которого передается функции. Для него p(x) равна 1, а для остальных классов - 0. \n\nЭто позволяет реализовать функцию проще!", "_____no_output_____" ] ], [ [ "probs = linear_classifer.softmax(np.array([-5, 0, 5]))\nlinear_classifer.cross_entropy_loss(probs, 1)", "_____no_output_____" ] ], [ [ "После того как мы реализовали сами функции, мы можем реализовать градиент.\n\nОказывается, что вычисление градиента становится гораздо проще, если объединить эти функции в одну, которая сначала вычисляет вероятности через softmax, а потом использует их для вычисления функции ошибки через cross-entropy loss.\n\nЭта функция `softmax_with_cross_entropy` будет возвращает и значение ошибки, и градиент по входным параметрам. Мы проверим корректность реализации с помощью `check_gradient`.", "_____no_output_____" ] ], [ [ "# TODO Implement combined function or softmax and cross entropy and produces gradient\nloss, grad = linear_classifer.softmax_with_cross_entropy(np.array([1, 0, 0]), 1)\ncheck_gradient(lambda x: linear_classifer.softmax_with_cross_entropy(x, 1), np.array([1, 0, 0], np.float))", "Gradients are different at (1,). Analytic: 0.21194, Numeric: -0.78806\n" ] ], [ [ "В качестве метода тренировки мы будем использовать стохастический градиентный спуск (stochastic gradient descent или SGD), который работает с батчами сэмплов. \n\nПоэтому все наши фукнции будут получать не один пример, а батч, то есть входом будет не вектор из `num_classes` оценок, а матрица размерности `batch_size, num_classes`. Индекс примера в батче всегда будет первым измерением.\n\nСледующий шаг - переписать наши функции так, чтобы они поддерживали батчи.\n\nФинальное значение функции ошибки должно остаться числом, и оно равно среднему значению ошибки среди всех примеров в батче.", "_____no_output_____" ] ], [ [ "# TODO Extend combined function so it can receive a 2d array with batch of samples\nnp.random.seed(42)\n# Test batch_size = 1\nnum_classes = 4\nbatch_size = 1\npredictions = np.random.randint(-1, 3, size=(batch_size, num_classes)).astype(np.float)\ntarget_index = np.random.randint(0, num_classes, size=(batch_size, 1)).astype(np.int)\ncheck_gradient(lambda x: linear_classifer.softmax_with_cross_entropy(x, target_index), predictions)\n\n# Test batch_size = 3\nnum_classes = 4\nbatch_size = 3\npredictions = np.random.randint(-1, 3, size=(batch_size, num_classes)).astype(np.float)\ntarget_index = np.random.randint(0, num_classes, size=(batch_size, 1)).astype(np.int)\ncheck_gradient(lambda x: linear_classifer.softmax_with_cross_entropy(x, target_index), predictions)\n\n# Make sure maximum subtraction for numberic stability is done separately for every sample in the batch\nprobs = linear_classifer.softmax(np.array([[20,0,0], [1000, 0, 0]]))\nassert np.all(np.isclose(probs[:, 0], 1.0))", "_____no_output_____" ] ], [ [ "### Наконец, реализуем сам линейный классификатор!\n\nsoftmax и cross-entropy получают на вход оценки, которые выдает линейный классификатор.\n\nОн делает это очень просто: для каждого класса есть набор весов, на которые надо умножить пиксели картинки и сложить. Получившееся число и является оценкой класса, идущей на вход softmax.\n\nТаким образом, линейный классификатор можно представить как умножение вектора с пикселями на матрицу W размера `num_features, num_classes`. Такой подход легко расширяется на случай батча векторов с пикселями X размера `batch_size, num_features`:\n\n`predictions = X * W`, где `*` - матричное умножение.\n\nРеализуйте функцию подсчета линейного классификатора и градиентов по весам `linear_softmax` в файле `linear_classifer.py`", "_____no_output_____" ] ], [ [ "# TODO Implement linear_softmax function that uses softmax with cross-entropy for linear classifier\nbatch_size = 2\nnum_classes = 2\nnum_features = 3\nnp.random.seed(42)\nW = np.random.randint(-1, 3, size=(num_features, num_classes)).astype(np.float)\nX = np.random.randint(-1, 3, size=(batch_size, num_features)).astype(np.float)\ntarget_index = np.ones(batch_size, dtype=np.int)\n\nloss, dW = linear_classifer.linear_softmax(X, W, target_index)\ncheck_gradient(lambda w: linear_classifer.linear_softmax(X, w, target_index), W)", "_____no_output_____" ] ], [ [ "### И теперь регуляризация\n\nМы будем использовать L2 regularization для весов как часть общей функции ошибки.\n\nНапомним, L2 regularization определяется как\n\nl2_reg_loss = regularization_strength * sum<sub>ij</sub> W[i, j]<sup>2</sup>\n\nРеализуйте функцию для его вычисления и вычисления соотвествующих градиентов.", "_____no_output_____" ] ], [ [ "# TODO Implement l2_regularization function that implements loss for L2 regularization\nlinear_classifer.l2_regularization(W, 0.01)\ncheck_gradient(lambda w: linear_classifer.l2_regularization(w, 0.01), W)", "_____no_output_____" ] ], [ [ "# Тренировка!", "_____no_output_____" ], [ "Градиенты в порядке, реализуем процесс тренировки!", "_____no_output_____" ] ], [ [ "# TODO: Implement LinearSoftmaxClassifier.fit function\nclassifier = linear_classifer.LinearSoftmaxClassifier()\nloss_history = classifier.fit(train_X, train_y, epochs=10, learning_rate=1e-3, batch_size=300, reg=1e1)", "_____no_output_____" ], [ "# let's look at the loss history!\nplt.plot(loss_history)", "_____no_output_____" ], [ "# Let's check how it performs on validation set\npred = classifier.predict(val_X)\naccuracy = multiclass_accuracy(pred, val_y)\nprint(\"Accuracy: \", accuracy)\n\n# Now, let's train more and see if it performs better\nclassifier.fit(train_X, train_y, epochs=100, learning_rate=1e-3, batch_size=300, reg=1e1)\npred = classifier.predict(val_X)\naccuracy = multiclass_accuracy(pred, val_y)\nprint(\"Accuracy after training for 100 epochs: \", accuracy)", "_____no_output_____" ] ], [ [ "### Как и раньше, используем кросс-валидацию для подбора гиперпараметтов.\n\nВ этот раз, чтобы тренировка занимала разумное время, мы будем использовать только одно разделение на тренировочные (training) и проверочные (validation) данные.\n\nТеперь нам нужно подобрать не один, а два гиперпараметра! Не ограничивайте себя изначальными значениями в коде. \nДобейтесь точности более чем **20%** на проверочных данных (validation data).", "_____no_output_____" ] ], [ [ "num_epochs = 200\nbatch_size = 300\n\nlearning_rates = [1e-3, 1e-4, 1e-5]\nreg_strengths = [1e-4, 1e-5, 1e-6]\n\nbest_classifier = None\nbest_val_accuracy = None\n\n# TODO use validation set to find the best hyperparameters\n# hint: for best results, you might need to try more values for learning rate and regularization strength \n# than provided initially\n\nprint('best validation accuracy achieved: %f' % best_val_accuracy)", "_____no_output_____" ] ], [ [ "# Какой же точности мы добились на тестовых данных?", "_____no_output_____" ] ], [ [ "test_pred = best_classifier.predict(test_X)\ntest_accuracy = multiclass_accuracy(test_pred, test_y)\nprint('Linear softmax classifier test set accuracy: %f' % (test_accuracy, ))", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec551b253ceec3b57bc18f845eba4ca2c83b4d4a
11,959
ipynb
Jupyter Notebook
tensorflow_programming_concepts.ipynb
TsundereChen/mlcc_colab
e25b750caf8855cea7129992d1c1ad5dbfb26a1e
[ "Apache-2.0" ]
null
null
null
tensorflow_programming_concepts.ipynb
TsundereChen/mlcc_colab
e25b750caf8855cea7129992d1c1ad5dbfb26a1e
[ "Apache-2.0" ]
null
null
null
tensorflow_programming_concepts.ipynb
TsundereChen/mlcc_colab
e25b750caf8855cea7129992d1c1ad5dbfb26a1e
[ "Apache-2.0" ]
null
null
null
34.364943
707
0.600886
[ [ [ "#### Copyright 2017 Google LLC.", "_____no_output_____" ] ], [ [ "# 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_____" ] ], [ [ "# TensorFlow Programming Concepts", "_____no_output_____" ], [ "**Learning Objectives:**\n * Learn the basics of the TensorFlow programming model, focusing on the following concepts:\n * tensors\n * operations\n * graphs\n * sessions\n * Build a simple TensorFlow program that creates a default graph, and a session that runs the graph", "_____no_output_____" ], [ "**Note:** Please read through this tutorial carefully. The TensorFlow programming model is probably different from others that you have encountered, and thus may not be as intuitive as you'd expect.", "_____no_output_____" ], [ "## Overview of Concepts\n\nTensorFlow gets its name from **tensors**, which are arrays of arbitrary dimensionality. Using TensorFlow, you can manipulate tensors with a very high number of dimensions. That said, most of the time you will work with one or more of the following low-dimensional tensors:\n\n * A **scalar** is a 0-d array (a 0th-order tensor). For example, `\"Howdy\"` or `5`\n * A **vector** is a 1-d array (a 1st-order tensor). For example, `[2, 3, 5, 7, 11]` or `[5]`\n * A **matrix** is a 2-d array (a 2nd-order tensor). For example, `[[3.1, 8.2, 5.9][4.3, -2.7, 6.5]]`\n\nTensorFlow **operations** create, destroy, and manipulate tensors. Most of the lines of code in a typical TensorFlow program are operations.\n\nA TensorFlow **graph** (also known as a **computational graph** or a **dataflow graph**) is, yes, a graph data structure. A graph's nodes are operations (in TensorFlow, every operation is associated with a graph). Many TensorFlow programs consist of a single graph, but TensorFlow programs may optionally create multiple graphs. A graph's nodes are operations; a graph's edges are tensors. Tensors flow through the graph, manipulated at each node by an operation. The output tensor of one operation often becomes the input tensor to a subsequent operation. TensorFlow implements a **lazy execution model,** meaning that nodes are only computed when needed, based on the needs of associated nodes.\n\nTensors can be stored in the graph as **constants** or **variables**. As you might guess, constants hold tensors whose values can't change, while variables hold tensors whose values can change. However, what you may not have guessed is that constants and variables are just more operations in the graph. A constant is an operation that always returns the same tensor value. A variable is an operation that will return whichever tensor has been assigned to it.\n\nTo define a constant, use the `tf.constant` operator and pass in its value. For example:\n\n```\n x = tf.constant(5.2)\n```\n\nSimilarly, you can create a variable like this:\n\n```\n y = tf.Variable([5])\n```\n\nOr you can create the variable first and then subsequently assign a value like this (note that you always have to specify a default value):\n\n```\n y = tf.Variable([0])\n y = y.assign([5])\n```\n\nOnce you've defined some constants or variables, you can combine them with other operations like `tf.add`. When you evaluate the `tf.add` operation, it will call your `tf.constant` or `tf.Variable` operations to get their values and then return a new tensor with the sum of those values.\n\nGraphs must run within a TensorFlow **session**, which holds the state for the graph(s) it runs:\n\n```\nwith tf.Session() as sess:\n initialization = tf.global_variables_initializer()\n print(y.eval())\n```\n\nWhen working with `tf.Variable`s, you must explicitly initialize them by calling `tf.global_variables_initializer` at the start of your session, as shown above.\n\n**Note:** A session can distribute graph execution across multiple machines (assuming the program is run on some distributed computation framework). For more information, see [Distributed TensorFlow](https://www.tensorflow.org/deploy/distributed).\n\n### Summary\n\nTensorFlow programming is essentially a two-step process:\n\n 1. Assemble constants, variables, and operations into a graph.\n 2. Evaluate those constants, variables and operations within a session.\n", "_____no_output_____" ], [ "## Creating a Simple TensorFlow Program\n\nLet's look at how to code a simple TensorFlow program that adds two constants. ", "_____no_output_____" ], [ "### Provide import statements\n\nAs with nearly all Python programs, you'll begin by specifying some `import` statements.\nThe set of `import` statements required to run a TensorFlow program depends, of course, on the features your program will access. At a minimum, you must provide the `import tensorflow` statement in all TensorFlow programs:", "_____no_output_____" ] ], [ [ "import tensorflow as tf", "_____no_output_____" ] ], [ [ "**Don't forget to execute the preceding code block (the `import` statements).**\n\nOther common import statements include the following:\n\n```\n import matplotlib.pyplot as plt # Dataset visualization.\n import numpy as np # Low-level numerical Python library.\n import pandas as pd # Higher-level numerical Python library.\n```", "_____no_output_____" ], [ "TensorFlow provides a **default graph**. However, we recommend explicitly creating your own `Graph` instead to facilitate tracking state (e.g., you may wish to work with a different `Graph` in each cell).", "_____no_output_____" ] ], [ [ "from __future__ import print_function\n\nimport tensorflow as tf\n\n# Create a graph.\ng = tf.Graph()\n\n# Establish the graph as the \"default\" graph.\nwith g.as_default():\n # Assemble a graph consisting of the following three operations:\n # * Two tf.constant operations to create the operands.\n # * One tf.add operation to add the two operands.\n x = tf.constant(8, name=\"x_const\")\n y = tf.constant(5, name=\"y_const\")\n my_sum = tf.add(x, y, name=\"x_y_sum\")\n\n\n # Now create a session.\n # The session will run the default graph.\n with tf.Session() as sess:\n print(my_sum.eval())", "_____no_output_____" ] ], [ [ "## Exercise: Introduce a Third Operand\n\nRevise the above code listing to add three integers, instead of two:\n\n 1. Define a third scalar integer constant, `z`, and assign it a value of `4`.\n 2. Add `z` to `my_sum` to yield a new sum.\n \n **Hint:** See the API docs for [tf.add()](https://www.tensorflow.org/api_docs/python/tf/add) for more details on its function signature.\n \n 3. Re-run the modified code block. Did the program generate the correct grand total?", "_____no_output_____" ], [ "### Solution\n\nClick below for the solution.", "_____no_output_____" ] ], [ [ "# Create a graph.\ng = tf.Graph()\n\n# Establish our graph as the \"default\" graph.\nwith g.as_default():\n # Assemble a graph consisting of three operations. \n # (Creating a tensor is an operation.)\n x = tf.constant(8, name=\"x_const\")\n y = tf.constant(5, name=\"y_const\")\n my_sum = tf.add(x, y, name=\"x_y_sum\")\n \n # Task 1: Define a third scalar integer constant z.\n z = tf.constant(4, name=\"z_const\")\n # Task 2: Add z to `my_sum` to yield a new sum.\n new_sum = tf.add(my_sum, z, name=\"x_y_z_sum\")\n\n # Now create a session.\n # The session will run the default graph.\n with tf.Session() as sess:\n # Task 3: Ensure the program yields the correct grand total.\n print(new_sum.eval())", "_____no_output_____" ] ], [ [ "## Further Information\n\nTo explore basic TensorFlow graphs further, experiment with the following tutorial:\n\n * [Mandelbrot set](https://www.tensorflow.org/tutorials/non-ml/mandelbrot)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]