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
sequence
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
sequence
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
sequence
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
sequence
cell_types
sequence
cell_type_groups
sequence
d00e3ed5fbe73a40b210dcdb24faa94e8aedecfd
118,866
ipynb
Jupyter Notebook
behavioral-cloning/model.ipynb
KOKSANG/Self-Driving-Car
138325444d67f181b3cc38bba4eebf1474255d1c
[ "MIT" ]
null
null
null
behavioral-cloning/model.ipynb
KOKSANG/Self-Driving-Car
138325444d67f181b3cc38bba4eebf1474255d1c
[ "MIT" ]
null
null
null
behavioral-cloning/model.ipynb
KOKSANG/Self-Driving-Car
138325444d67f181b3cc38bba4eebf1474255d1c
[ "MIT" ]
null
null
null
120.066667
35,896
0.80918
[ [ [ "import os\nimport glob\nimport zipfile\nimport pathlib\nimport cv2\nimport math\nimport random\nimport shutil\nimport skimage as sk\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.utils import shuffle\n\nfrom keras.models import Sequential\nfrom keras.activations import softmax, relu\nfrom keras.layers import Activation, Dense, Dropout, Flatten, Lambda, Cropping2D, LSTM\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization\nfrom keras.optimizers import Adam\nfrom keras.regularizers import l2\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint", "Using TensorFlow backend.\n" ] ], [ [ "## Ran the new few blocks for my colab configuration, can be ignored.", "_____no_output_____" ] ], [ [ "from google.colab import drive\n\ndrive.mount('/content/gdrive')", "Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount(\"/content/gdrive\", force_remount=True).\n" ], [ "!wget https://d17h27t6h515a5.cloudfront.net/topher/2016/December/584f6edd_data/data.zip\n", "--2019-04-14 10:46:55-- https://d17h27t6h515a5.cloudfront.net/topher/2016/December/584f6edd_data/data.zip\nResolving d17h27t6h515a5.cloudfront.net (d17h27t6h515a5.cloudfront.net)... 52.85.159.80, 52.85.159.38, 52.85.159.165, ...\nConnecting to d17h27t6h515a5.cloudfront.net (d17h27t6h515a5.cloudfront.net)|52.85.159.80|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 333137665 (318M) [application/zip]\nSaving to: ‘data.zip’\n\ndata.zip 100%[===================>] 317.70M 42.5MB/s in 7.2s \n\n2019-04-14 10:47:03 (43.9 MB/s) - ‘data.zip’ saved [333137665/333137665]\n\n" ], [ "import shutil\n\nshutil.move(\"/content/data.zip\", \"/content/gdrive/My Drive/udacity-behavioural-cloning/\")", "_____no_output_____" ], [ "os.chdir('/content/gdrive/My Drive/udacity-behavioural-cloning/')", "_____no_output_____" ], [ "with zipfile.ZipFile('data.zip') as f:\n f.extractall()", "_____no_output_____" ], [ "os.chdir('/content/gdrive/My Drive/udacity-behavioural-cloning/data/')", "_____no_output_____" ] ], [ [ "## Training code starts here", "_____no_output_____" ] ], [ [ "df = pd.read_csv('driving_log.csv')", "_____no_output_____" ], [ "# Visualizing original distribution\n\nplt.figure(figsize=(15, 3))\nhist, bins = np.histogram(df.steering.values, bins=50)\nplt.hist(df.steering.values, bins=bins)\nplt.title('Steering Distribution Plot')\nplt.xlabel('Steering')\nplt.ylabel('Count')\nplt.show()", "_____no_output_____" ], [ "# create grayscale image\ndef grayscale(img):\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n# normalize image to zero mean\ndef normalize(img):\n mean = np.mean(img)\n std = np.std(img)\n return (img-mean)/std\n# preprocess with grayscale and normalization\ndef preprocess(img):\n return normalize(grayscale(img))\n# augment image, left right flip for now\ndef augment(image, randn):\n return np.flip(image, axis=randn%2).astype(np.uint8)\n# yeo-johnson bias\ndef yeo_johnson_bias(steering):\n if steering >= 0:\n return np.log(steering + 1)\n elif steering < 0:\n return -np.log(-steering + 1)", "_____no_output_____" ], [ "# To separate center, left and right\ndf_center = pd.concat([df.center, df.steering], axis=1).rename(index=str, columns={'center': 'img'})\ndf_left = pd.concat([df.left, df.steering], axis=1).rename(index=str, columns={'left': 'img'})\ndf_right = pd.concat([df.right, df.steering], axis=1).rename(index=str, columns={'right': 'img'})\n\ndf_center.head()", "_____no_output_____" ], [ "# Adjusting the steering value 0 for left and right\n\nfor k, v in df_left.iterrows():\n if v.steering == 0:\n df_left.loc[k, 'steering'] = df_left.loc[k, 'steering'] + random.uniform(0.2, 0.5)\n \nfor k, v in df_right.iterrows():\n if v.steering == 0:\n df_right.loc[k, 'steering'] = df_right.loc[k, 'steering'] + random.uniform(-0.2, -0.5)", "_____no_output_____" ], [ "new_df = pd.concat([df_center, df_left, df_right], axis=0, ignore_index=True, sort=False)", "_____no_output_____" ], [ "new_df.tail()", "_____no_output_____" ], [ "new_df.to_csv('adjusted_log.csv', index=False, encoding='utf-8')", "_____no_output_____" ], [ "df = pd.read_csv('adjusted_log.csv')", "_____no_output_____" ], [ "# Visualizing adjusted distribution\n\nplt.figure(figsize=(15, 3))\nhist, bins = np.histogram(df.steering.values, bins=50)\nplt.hist(df.steering.values, bins=bins)\nplt.title('Steering Distribution Plot')\nplt.xlabel('Steering')\nplt.ylabel('Count')\nplt.show()\n\ndf.plot(figsize=(15, 3))", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "# Grouping all images and steering together, to do a train test splitting\n\nimages = df.img.tolist()\nsteering = df.steering.tolist()\n\nimg_list = []\nfor img, angle in zip(images, steering):\n row = [img, angle]\n img_list.append(row)\n\ntrain_samples, validation_samples = train_test_split(img_list, test_size=0.2)", "_____no_output_____" ], [ "# Data generator\n\ndef generator(samples, batch_size=32):\n cwd = os.getcwd()\n num_samples = len(samples)\n while True: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n angles = []\n\n for batch_sample in batch_samples:\n name = os.path.join(cwd, batch_sample[0].strip())\n try:\n # normalizing image\n image = normalize(mpimg.imread(name))\n # reshaping image into its rgb form\n image = np.reshape(image, (image.shape[0], image.shape[1], 3))\n steering = float(batch_sample[1])\n images.append(image)\n angles.append(steering)\n # if image not found, skip the image\n except FileNotFoundError as msg:\n print(msg)\n continue\n\n # trim image to only see section with road|\n X_train = np.array(images)\n y_train = np.array(angles)\n yield shuffle(X_train, y_train)", "_____no_output_____" ], [ "# Set our batch size\nbatch_size = 32\n\n# compile and train the model using the generator function\ntrain_generator = generator(train_samples, batch_size=batch_size)\nvalidation_generator = generator(validation_samples, batch_size=batch_size)", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "### PART 3: TRAINING ###\n# Training Architecture: inspired by NVIDIA architecture #\nINPUT_SHAPE = (160, 320, 3)\nmodel = Sequential()\nmodel.add(Cropping2D(cropping=((70,25), (0, 0)), input_shape=INPUT_SHAPE))\n\nmodel.add(Conv2D(filters=24, kernel_size=5, strides=(2, 2), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(filters=36, kernel_size=5, strides=(2, 2), activation='relu'))\n#model.add(BatchNormalization())\nmodel.add(Conv2D(filters=48, kernel_size=5, strides=(2, 2), activation='relu'))\n#model.add(BatchNormalization())\nmodel.add(Conv2D(filters=64, kernel_size=3, strides=(1, 1), activation='relu'))\n#model.add(BatchNormalization())\nmodel.add(Conv2D(filters=64, kernel_size=3, strides=(1, 1), activation='relu'))\n\nmodel.add(Flatten())\nmodel.add(Dense(1164, activation='relu'))\nmodel.add(Dropout(rate=0.5))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dropout(rate=0.5))\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dropout(rate=0.5))\nmodel.add(Dense(10, activation='relu'))\nmodel.add(Dense(1))\nadam = Adam(lr = 0.0001)\nmodel.compile(optimizer= adam, loss='mse', metrics=['accuracy'])\nmodel.summary()\n", "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nColocations handled automatically by placer.\nWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ncropping2d_1 (Cropping2D) (None, 65, 320, 3) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 31, 158, 24) 1824 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 31, 158, 24) 96 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 14, 77, 36) 21636 \n_________________________________________________________________\nconv2d_3 (Conv2D) (None, 5, 37, 48) 43248 \n_________________________________________________________________\nconv2d_4 (Conv2D) (None, 3, 35, 64) 27712 \n_________________________________________________________________\nconv2d_5 (Conv2D) (None, 1, 33, 64) 36928 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 2112) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 1164) 2459532 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 1164) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 100) 116500 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 100) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 50) 5050 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 50) 0 \n_________________________________________________________________\ndense_4 (Dense) (None, 10) 510 \n_________________________________________________________________\ndense_5 (Dense) (None, 1) 11 \n=================================================================\nTotal params: 2,713,047\nTrainable params: 2,712,999\nNon-trainable params: 48\n_________________________________________________________________\n" ], [ "history = model.fit_generator(generator=train_generator, steps_per_epoch=math.ceil(len(train_samples)/ batch_size), \\\n epochs=15, verbose=1, validation_data=validation_generator, \\\n validation_steps=math.ceil(len(validation_samples)/ batch_size), use_multiprocessing=False)\n\nprint('Done Training')", "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.cast instead.\nEpoch 1/15\n603/603 [==============================] - 197s 326ms/step - loss: 0.0531 - acc: 0.1800 - val_loss: 0.0418 - val_acc: 0.1839\nEpoch 2/15\n603/603 [==============================] - 193s 320ms/step - loss: 0.0435 - acc: 0.1801 - val_loss: 0.0393 - val_acc: 0.1839\nEpoch 3/15\n603/603 [==============================] - 194s 321ms/step - loss: 0.0407 - acc: 0.1801 - val_loss: 0.0380 - val_acc: 0.1839\nEpoch 4/15\n603/603 [==============================] - 194s 321ms/step - loss: 0.0381 - acc: 0.1801 - val_loss: 0.0363 - val_acc: 0.1839\nEpoch 5/15\n603/603 [==============================] - 193s 320ms/step - loss: 0.0370 - acc: 0.1801 - val_loss: 0.0369 - val_acc: 0.1839\nEpoch 6/15\n603/603 [==============================] - 193s 319ms/step - loss: 0.0349 - acc: 0.1801 - val_loss: 0.0355 - val_acc: 0.1839\nEpoch 7/15\n603/603 [==============================] - 193s 320ms/step - loss: 0.0331 - acc: 0.1802 - val_loss: 0.0353 - val_acc: 0.1839\nEpoch 8/15\n603/603 [==============================] - 191s 318ms/step - loss: 0.0306 - acc: 0.1801 - val_loss: 0.0352 - val_acc: 0.1839\nEpoch 9/15\n603/603 [==============================] - 191s 317ms/step - loss: 0.0279 - acc: 0.1802 - val_loss: 0.0352 - val_acc: 0.1839\nEpoch 10/15\n603/603 [==============================] - 191s 317ms/step - loss: 0.0254 - acc: 0.1802 - val_loss: 0.0358 - val_acc: 0.1839\nEpoch 11/15\n603/603 [==============================] - 192s 318ms/step - loss: 0.0228 - acc: 0.1802 - val_loss: 0.0356 - val_acc: 0.1839\nEpoch 12/15\n603/603 [==============================] - 191s 317ms/step - loss: 0.0204 - acc: 0.1803 - val_loss: 0.0357 - val_acc: 0.1839\nEpoch 13/15\n603/603 [==============================] - 190s 315ms/step - loss: 0.0179 - acc: 0.1803 - val_loss: 0.0364 - val_acc: 0.1839\nEpoch 14/15\n603/603 [==============================] - 189s 314ms/step - loss: 0.0158 - acc: 0.1804 - val_loss: 0.0374 - val_acc: 0.1839\nEpoch 15/15\n603/603 [==============================] - 189s 314ms/step - loss: 0.0141 - acc: 0.1804 - val_loss: 0.0374 - val_acc: 0.1839\nDone Training\n" ], [ "###Saving Model and Weights###\nmodel_json = model.to_json()\nwith open(\"model5.json\", \"w\") as json_file:\n json_file.write(model_json)\nmodel.save('model5.h5')\nmodel.save_weights(\"model_weights5.h5\")\nprint(\"Saved model to disk\")", "Saved model to disk\n" ], [ "### print the keys contained in the history object\nprint(history.history.keys())\n\n### plot the training and validation loss for each epoch\nplt.figure(figsize=(15, 3))\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model mean squared error loss')\nplt.ylabel('mean squared error loss')\nplt.xlabel('epoch')\nplt.legend(['training set', 'validation set'], loc='upper right')\nplt.show()", "dict_keys(['val_loss', 'val_acc', 'loss', 'acc'])\n" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "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", "code", "code", "code" ] ]
d00e42c3682f74b38a0f25b45172a5bdbc43942f
27,895
ipynb
Jupyter Notebook
experiments/entities-search-engine/1. load data from sparql.ipynb
TheScienceMuseum/heritage-connector
c8f0970edfe2c43560949fe46f4d4415f4f8bc0b
[ "MIT" ]
15
2020-03-19T09:13:02.000Z
2022-03-29T16:53:53.000Z
experiments/entities-search-engine/1. load data from sparql.ipynb
TheScienceMuseum/heritage-connector
c8f0970edfe2c43560949fe46f4d4415f4f8bc0b
[ "MIT" ]
311
2020-06-11T10:14:06.000Z
2021-12-03T16:56:11.000Z
experiments/entities-search-engine/1. load data from sparql.ipynb
TheScienceMuseum/heritage-connector
c8f0970edfe2c43560949fe46f4d4415f4f8bc0b
[ "MIT" ]
1
2021-11-20T18:48:43.000Z
2021-11-20T18:48:43.000Z
109.392157
5,026
0.705646
[ [ [ "# entities-search-engine loading\nSPARQL query to `{\"type\": [values]}`", "_____no_output_____" ] ], [ [ "import sys\nsys.path.append(\"..\")\n\nfrom heritageconnector.config import config\nfrom heritageconnector.utils.sparql import get_sparql_results\nfrom heritageconnector.utils.wikidata import url_to_qid\n\nimport json\nimport time\nfrom tqdm import tqdm\n\nendpoint = config.WIKIDATA_SPARQL_ENDPOINT", "_____no_output_____" ] ], [ [ "## humans sample", "_____no_output_____" ] ], [ [ "limit = 10000\n\nquery = f\"\"\"\nSELECT ?item WHERE {{\n ?item wdt:P31 wd:Q5.\n}} LIMIT {limit}\n\"\"\"\n\nres = get_sparql_results(endpoint, query)\n\ndata = {\n \"humans\": [url_to_qid(x['item']['value']) for x in res['results']['bindings']]\n}\n\nwith open(\"./entities-search-engine/data/humans_sample.json\", 'w') as f:\n json.dump(data, f)", "_____no_output_____" ] ], [ [ "## humans sample: paginated\ngot a 500 timeout error nearly all of the way through. Looked like it was going to take around 1h20m. *Better to do with dump?*", "_____no_output_____" ] ], [ [ "# there are 8,011,382 humans in Wikidata so this should take 161 iterations\ntotal_humans = 8011382\npagesize = 40000\nreslen = pagesize\n\npaged_json = []\ni = 0\n\nstart = time.time()\npbar = tqdm(total=total_humans)\n\nwhile reslen == pagesize:\n query = f\"\"\"\n SELECT ?item WHERE {{\n ?item wdt:P31 wd:Q5.\n }} LIMIT {pagesize} OFFSET {i*pagesize}\n \"\"\"\n\n res = get_sparql_results(endpoint, query)['results']['bindings']\n reslen = len(res)\n \n paged_json.append(\n { \"humans\": [url_to_qid(x['item']['value']) for x in res] }\n )\n \n # print total number so far\n #print(i+1, (i+1)*pagesize)\n i+=1\n pbar.update(pagesize)\n \nend = time.time()\npbar.close()\n\nprint(f\"COMPLETED: {round(end-start, 2)} seconds\")\n \n# with open(\"./entities-search-engine/data/humans_sample.json\", 'w') as f:\n# json.dump(data, f)", " 89%|████████▉ | 7120000/8011382 [58:13<12:59, 1143.37it/s]" ], [ "for idx, item in tqdm(enumerate(paged_json)):\n with open(f\"./entities-search-engine/data/humans/humans_{idx}.json\", 'w') as f:\n json.dump(item, f)", "\n0it [00:00, ?it/s]\u001b[A\n3it [00:00, 24.90it/s]\u001b[A\n5it [00:00, 22.01it/s]\u001b[A\n8it [00:00, 23.76it/s]\u001b[A\n11it [00:00, 24.37it/s]\u001b[A\n15it [00:00, 24.48it/s]\u001b[A\n19it [00:00, 26.02it/s]\u001b[A\n22it [00:00, 26.84it/s]\u001b[A\n25it [00:00, 27.48it/s]\u001b[A\n29it [00:01, 28.67it/s]\u001b[A\n32it [00:01, 27.39it/s]\u001b[A\n35it [00:01, 27.23it/s]\u001b[A\n38it [00:01, 25.93it/s]\u001b[A\n41it [00:01, 25.11it/s]\u001b[A\n44it [00:01, 24.59it/s]\u001b[A\n47it [00:01, 23.96it/s]\u001b[A\n50it [00:01, 22.40it/s]\u001b[A\n53it [00:02, 23.28it/s]\u001b[A\n56it [00:02, 24.64it/s]\u001b[A\n59it [00:02, 24.45it/s]\u001b[A\n62it [00:02, 25.65it/s]\u001b[A\n65it [00:02, 25.37it/s]\u001b[A\n68it [00:02, 25.41it/s]\u001b[A\n71it [00:02, 25.86it/s]\u001b[A\n74it [00:02, 26.11it/s]\u001b[A\n77it [00:03, 26.18it/s]\u001b[A\n80it [00:03, 26.45it/s]\u001b[A\n83it [00:03, 26.71it/s]\u001b[A\n86it [00:03, 26.90it/s]\u001b[A\n89it [00:03, 24.88it/s]\u001b[A\n92it [00:03, 25.85it/s]\u001b[A\n95it [00:03, 25.95it/s]\u001b[A\n98it [00:03, 25.79it/s]\u001b[A\n101it [00:03, 25.92it/s]\u001b[A\n104it [00:04, 26.47it/s]\u001b[A\n108it [00:04, 27.56it/s]\u001b[A\n111it [00:04, 27.39it/s]\u001b[A\n114it [00:04, 27.24it/s]\u001b[A\n117it [00:04, 27.55it/s]\u001b[A\n120it [00:04, 27.45it/s]\u001b[A\n123it [00:04, 27.16it/s]\u001b[A\n126it [00:04, 26.65it/s]\u001b[A\n129it [00:04, 26.50it/s]\u001b[A\n132it [00:05, 26.36it/s]\u001b[A\n135it [00:05, 27.20it/s]\u001b[A\n138it [00:05, 27.28it/s]\u001b[A\n141it [00:05, 27.53it/s]\u001b[A\n144it [00:05, 27.68it/s]\u001b[A\n147it [00:05, 27.42it/s]\u001b[A\n150it [00:05, 27.27it/s]\u001b[A\n153it [00:05, 27.94it/s]\u001b[A\n156it [00:05, 26.64it/s]\u001b[A\n159it [00:06, 26.79it/s]\u001b[A\n162it [00:06, 26.72it/s]\u001b[A\n165it [00:06, 26.58it/s]\u001b[A\n168it [00:06, 26.12it/s]\u001b[A\n172it [00:06, 27.28it/s]\u001b[A\n175it [00:06, 27.70it/s]\u001b[A\n178it [00:06, 26.39it/s]\u001b[A\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d00e4ad5d073217bad815536744fb968af87bff6
263,316
ipynb
Jupyter Notebook
plot_figure4_first_half.ipynb
COMP6248-Reproducability-Challenge/hypergradient-descent-reproduction
e54bc17cd5f681a115607f6babd326d30466f8a6
[ "MIT" ]
2
2019-07-23T18:54:05.000Z
2021-10-30T18:01:34.000Z
plot_figure4_first_half.ipynb
COMP6248-Reproducability-Challenge/hypergradient-descent-reproduction
e54bc17cd5f681a115607f6babd326d30466f8a6
[ "MIT" ]
null
null
null
plot_figure4_first_half.ipynb
COMP6248-Reproducability-Challenge/hypergradient-descent-reproduction
e54bc17cd5f681a115607f6babd326d30466f8a6
[ "MIT" ]
1
2019-06-11T18:29:51.000Z
2019-06-11T18:29:51.000Z
968.073529
91,002
0.934782
[ [ [ "from google.colab import drive\ndrive.mount('/content/gdrive')", "Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount(\"/content/gdrive\", force_remount=True).\n" ], [ "import pandas as pd\nimport numpy as np\nimport csv\n\n#DATA_FOLDER = '/content/gdrive/My Drive/101/results/logreg/'\n\nsubfolders = []\nfor a in range(1,7):\n for b in range(6,0,-1):\n subfolders.append('+1e-0'+str(a)+'_+1e-0'+str(b))\n\nclassifiers = ['logreg', 'mlp', 'better_cnn']\nall_results = []\n\nfor clf in classifiers:\n print(clf)\n DATA_FOLDER = '/content/gdrive/My Drive/101/results/' + clf + '/'\n \n results = []\n matrix = np.zeros(36)\n methods = ['sgd', 'sgdn', 'adam', 'sgd_hd', 'sgdn_hd', 'adam_hd']\n for m in methods:\n for i, s in enumerate(subfolders):\n file = DATA_FOLDER + s + '/' + m + '.csv'\n with open(file, 'r') as f:\n loss = list(csv.reader(f))[-1][4] #training loss\n matrix[i] = np.round(float(loss),3)\n results.append(matrix.reshape(6,-1))\n matrix = np.zeros(36)\n \n all_results.append(results)\n \n", "logreg\nmlp\nbetter_cnn\n" ], [ "import seaborn as sns\nimport matplotlib.pyplot as plt\n\nf, ax = plt.subplots(2,3, figsize=(14,7))\nk=0\nf.suptitle(r'Gridsearch for every ${\\alpha}_{0}$ and $\\beta$ with Logistic Regression on MNIST')\nfor i in range(2):\n for j in range(3):\n ax[i,j].set_title(methods[k])\n f = sns.heatmap(all_results[0][k], annot=True ,cmap=\"YlGnBu\",cbar=True, ax=ax[i,j])\n if k > 2:\n f = sns.heatmap(all_results[0][k], annot=True ,cmap=\"YlGnBu\",cbar=False, ax=ax[i,j], \n mask=np.round(all_results[0][k],2) <= np.round(all_results[0][k-3],2) , annot_kws={\"color\": \"red\"})\n k+=1\n f.set_xticklabels([1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1],fontsize='small')\n f.set_yticklabels([1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6],fontsize='small')\n if i==1:\n f.set_xlabel(r'$\\beta_0$')\n f.set_ylabel(r'$\\alpha_0$')\nplt.show()", "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:13: RuntimeWarning: invalid value encountered in less_equal\n del sys.path[0]\n" ], [ "import seaborn as sns\nimport matplotlib.pyplot as plt\n\nf, ax = plt.subplots(2,3, figsize=(14,7))\nk=0\nf.suptitle(r'Gridsearch for every ${\\alpha}_{0}$ and $\\beta$ with MLP on MNIST')\nfor i in range(2):\n for j in range(3):\n ax[i,j].set_title(methods[k])\n f = sns.heatmap(all_results[1][k], annot=True ,cmap=\"YlGnBu\",cbar=True, ax=ax[i,j])\n if k > 2:\n f = sns.heatmap(all_results[1][k], annot=True ,cmap=\"YlGnBu\",cbar=False, ax=ax[i,j], \n mask=np.round(all_results[1][k],2) <= np.round(all_results[1][k-3],2) , annot_kws={\"color\": \"red\"})\n k+=1\n f.set_xticklabels([1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1],fontsize='small')\n f.set_yticklabels([1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6],fontsize='small')\n if i==1:\n f.set_xlabel(r'$\\beta_0$')\n f.set_ylabel(r'$\\alpha_0$') \nplt.show()", "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:13: RuntimeWarning: invalid value encountered in less_equal\n del sys.path[0]\n" ], [ "import seaborn \nimport matplotlib.pyplot as plt\n\nf, ax = plt.subplots(2,3, figsize=(14,7))\nk=0\nf.suptitle(r'Gridsearch for every ${\\alpha}_{0}$ and $\\beta$ with \"\"Better CNN\"\" on MNIST')\nfor i in range(2):\n for j in range(3):\n ax[i,j].set_title(methods[k])\n f = sns.heatmap(all_results[2][k], annot=True ,cmap=\"YlGnBu\",cbar=True, ax=ax[i,j])\n if k > 2:\n f = sns.heatmap(all_results[2][k], annot=True ,cmap=\"YlGnBu\",cbar=False, ax=ax[i,j], \n mask=np.round(all_results[2][k],2) <= np.round(all_results[2][k-3],2) , annot_kws={\"color\": \"red\"})\n k+=1\n f.set_xticklabels([1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1],fontsize='small')\n f.set_yticklabels([1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6],fontsize='small')\n f.set_xlabel(r'$\\beta_0$')\n f.set_ylabel(r'$\\alpha_0$') \nplt.show()", "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:13: RuntimeWarning: invalid value encountered in less_equal\n del sys.path[0]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
d00e5261a5f317159a02a4d2025f4b2f6f643b44
642,483
ipynb
Jupyter Notebook
_ipynb/SchnallSupplement.ipynb
simkovic/simkovic.github.io
98d0e30f5547894ee11925548a4627ad7c28fa68
[ "MIT" ]
2
2015-07-09T13:51:42.000Z
2015-07-27T15:06:48.000Z
_ipynb/SchnallSupplement.ipynb
simkovic/simkovic.github.io
98d0e30f5547894ee11925548a4627ad7c28fa68
[ "MIT" ]
null
null
null
_ipynb/SchnallSupplement.ipynb
simkovic/simkovic.github.io
98d0e30f5547894ee11925548a4627ad7c28fa68
[ "MIT" ]
null
null
null
216.324242
73,798
0.858835
[ [ [ "By now basically everyone ([here](http://datacolada.org/2014/06/04/23-ceiling-effects-and-replications/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+DataColada+%28Data+Colada+Feed%29), [here](http://yorl.tumblr.com/post/87428392426/ceiling-effects), [here](http://www.talyarkoni.org/blog/2014/06/01/there-is-no-ceiling-effect-in-johnson-cheung-donnellan-2014/), [here](http://pigee.wordpress.com/2014/05/24/additional-reflections-on-ceiling-effects-in-recent-replication-research/) and [here](http://www.nicebread.de/reanalyzing-the-schnalljohnson-cleanliness-data-sets-new-insights-from-bayesian-and-robust-approaches/), and there is likely even more out there) who writes a blog and knows how to do a statistical analysis has analysed data from a recent replication study and from the original study (data repository is here). \n\nThe study of two experiments. Let's focus on Experiment 1 here. The experiment consists of a treatment and control group. The performance is measured by six likert-scale items. The scale has 9 levels. All responses are averaged together and we obtain a single composite score for each group. We are interested whether the treatment works, which would show up as a positive difference between the score of the treatment and the control group. Replication study did the same with more subjects.\n\nLet's perform the original analysis to see the results and why this dataset is so \"popular\".", "_____no_output_____" ] ], [ [ "%pylab inline\nimport pystan\nfrom matustools.matusplotlib import *\nfrom scipy import stats", "Populating the interactive namespace from numpy and matplotlib\n" ], [ "il=['dog','trolley','wallet','plane','resume','kitten','mean score','median score']\nD=np.loadtxt('schnallstudy1.csv',delimiter=',')\nD[:,1]=1-D[:,1]\nDtemp=np.zeros((D.shape[0],D.shape[1]+1))\nDtemp[:,:-1]=D\nDtemp[:,-1]=np.median(D[:,2:-2],axis=1)\nD=Dtemp\nDS=D[D[:,0]==0,1:]\nDR=D[D[:,0]==1,1:]\nDS.shape", "_____no_output_____" ], [ "def plotCIttest1(y,x=0,alpha=0.05):\n m=y.mean();df=y.size-1\n se=y.std()/y.size**0.5\n cil=stats.t.ppf(alpha/2.,df)*se\n cii=stats.t.ppf(0.25,df)*se\n out=[m,m-cil,m+cil,m-cii,m+cii]\n _errorbar(out,x=x,clr='k')\n return out\n \ndef plotCIttest2(y1,y2,x=0,alpha=0.05):\n n1=float(y1.size);n2=float(y2.size);\n v1=y1.var();v2=y2.var()\n m=y2.mean()-y1.mean()\n s12=(((n1-1)*v1+(n2-1)*v2)/(n1+n2-2))**0.5\n se=s12*(1/n1+1/n2)**0.5\n df= (v1/n1+v2/n2)**2 / ( (v1/n1)**2/(n1-1)+(v2/n2)**2/(n2-1)) \n cil=stats.t.ppf(alpha/2.,df)*se\n cii=stats.t.ppf(0.25,df)*se\n out=[m,m-cil,m+cil,m-cii,m+cii]\n _errorbar(out,x=x)\n return out\n\nplt.figure(figsize=(4,3))\ndts=[DS[DS[:,0]==0,-2],DS[DS[:,0]==1,-2],\n DR[DR[:,0]==0,-2],DR[DR[:,0]==1,-2]]\nfor k in range(len(dts)):\n plotCIttest1(dts[k],x=k)\nplt.grid(False,axis='x')\nax=plt.gca()\nax.set_xticks(range(len(dts)))\nax.set_xticklabels(['OC','OT','RC','RT'])\nplt.xlim([-0.5,len(dts)-0.5])\nplt.figure(figsize=(4,3))\nplotCIttest2(dts[0],dts[1],x=0,alpha=0.1)\nplotCIttest2(dts[2],dts[3],x=1,alpha=0.1)\nax=plt.gca()\nax.set_xticks([0,1])\nax.set_xticklabels(['OT-OC','RT-RC'])\nplt.grid(False,axis='x')\nplt.xlim([-0.5,1.5]);", "/usr/local/lib/python2.7/dist-packages/matplotlib-1.3.1-py2.7-linux-i686.egg/matplotlib/font_manager.py:1236: UserWarning: findfont: Font family ['Arial'] not found. Falling back to Bitstream Vera Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n/usr/local/lib/python2.7/dist-packages/matplotlib-1.3.1-py2.7-linux-i686.egg/matplotlib/figure.py:1595: UserWarning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect.\n warnings.warn(\"This figure includes Axes that are not \"\n" ] ], [ [ "Legend: OC - original study, control group; OT - original study, treatment group; RC - replication study, control group; RT - replication study, treatment group; \n\nIn the original study the difference between the treatment and control is significantly greater than zero. In the replication, it is not. However the ratings in the replication are higher overall. The author of the original study therefore raised a concern that no difference was obtained in replication because of ceiling effects. \n\nHow do we show that there are ceiling efects in the replication? The authors and bloggers presented various arguments that support some conclusion (mostly that there are no ceiling effects). Ultimately ceiling effects are a matter of degree and since no one knows how to quantify them the whole discussion of the replication's validity is heading into an inferential limbo. \n\nMy point here is that if the analysis computed the proper effect size - the causal effect size, we would avoid these kinds of arguments and discussions.", "_____no_output_____" ] ], [ [ "def plotComparison(A,B,stan=False):\n plt.figure(figsize=(8,16))\n cl=['control','treatment']\n x=np.arange(11)-0.5\n if not stan:assert A.shape[1]==B.shape[1]\n for i in range(A.shape[1]-1):\n for cond in range(2):\n plt.subplot(A.shape[1]-1,2,2*i+cond+1)\n a=np.histogram(A[A[:,0]==cond,1+i],bins=x, normed=True)\n plt.barh(x[:-1],-a[0],ec='w',height=1)\n if stan: a=[B[:,i,cond]]\n else: a=np.histogram(B[B[:,0]==cond,1+i],bins=x, normed=True)\n plt.barh(x[:-1],a[0],ec='w',fc='g',height=1)\n #plt.hist(DS[:,2+i],bins=np.arange(11)-0.5,normed=True,rwidth=0.5)\n plt.xlim([-0.7,0.7]);plt.gca().set_yticks(range(10))\n plt.ylim([-1,10]);#plt.grid(b=False,axis='y')\n if not i: plt.title('condition: '+cl[cond])\n if not cond: plt.ylabel(il[i],size=12)\n if not i and not cond: plt.legend(['original','replication'],loc=4);\nplotComparison(DS,DR)", "_____no_output_____" ], [ "model='''\ndata {\n int<lower=2> K;\n int<lower=0> N;\n int<lower=1> M;\n int<lower=1,upper=K> y[N,M];\n int x[N];\n}\nparameters {\n real beta[M];\n ordered[K-1] c[M];\n}\ntransformed parameters{\n real pt[M,K-1]; real pc[M,K-1];\n for (m in 1:M){\n for (k in 1:(K-1)){\n pt[m,k] <- inv_logit(beta[m]-c[m][k]);\n pc[m,k] <- inv_logit(-c[m][k]);\n}}}\nmodel {\nfor (m in 1:M){\n for (k in 1:(K-1)) c[m][k]~ uniform(-100,100);\n for (n in 1:N) y[n,m] ~ ordered_logistic(x[n] * beta[m], c[m]);\n}}\n'''\nsm1=pystan.StanModel(model_code=model)", "INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_0377c9bb8f1b5b3a8a8d14511c81c630 NOW.\n" ], [ "dat = {'y':np.int32(DS[:,1:7])+1,'x':np.int32(DS[:,0]),'N':DS.shape[0] ,'K':10,'M':6}\nfit = sm1.sampling(data=dat,iter=1000, chains=4,thin=2,warmup=500,njobs=2,seed=4)\nprint fit", "Inference for Stan model: anon_model_0377c9bb8f1b5b3a8a8d14511c81c630.\n4 chains, each with iter=1000; warmup=500; thin=2; \npost-warmup draws per chain=250, total post-warmup draws=1000.\n\n mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat\nbeta[0] 0.9 0.1 0.6 -0.3 0.5 0.8 1.3 2.1 124.0 1.0\nbeta[1] 0.7 0.0 0.5 -0.3 0.3 0.7 1.1 1.9 151.0 1.0\nbeta[2] 0.4 0.1 0.6 -0.7 -0.0 0.4 0.8 1.5 133.0 1.0\nbeta[3] 0.4 0.1 0.6 -0.9 0.0 0.4 0.8 1.6 99.0 1.0\nbeta[4] 0.8 0.1 0.6 -0.4 0.4 0.8 1.2 2.0 128.0 1.0\nbeta[5] 1.6 0.1 0.7 0.2 1.1 1.6 2.1 2.9 145.0 1.0\nc[0,0] -54.7 3.0 26.8-96.2-79.8-54.2-33.5 -7.4 79.0 1.0\nc[1,0] -1.1 0.0 0.5 -2.1 -1.4 -1.1 -0.8 -0.2 117.0 1.0\nc[2,0] -3.6 0.1 0.9 -6.1 -4.1 -3.6 -3.0 -2.1 80.0 1.0\nc[3,0] -5.2 0.2 1.5 -8.9 -6.1 -5.1 -4.2 -2.9 82.0 1.0\nc[4,0] -69.3 2.4 21.9-99.1-88.7-72.7-52.1 -24.4 84.0 1.0\nc[5,0] -69.9 2.7 21.2-98.9-87.4-73.0-55.3 -23.3 61.0 1.1\nc[0,1] -3.6 0.2 1.0 -6.1 -4.1 -3.4 -2.9 -2.0 42.0 1.1\nc[1,1] -0.2 0.0 0.4 -1.0 -0.4 -0.2 0.1 0.6 152.0 1.0\nc[2,1] -2.8 0.1 0.7 -4.2 -3.3 -2.8 -2.4 -1.6 153.0 1.0\nc[3,1] -3.7 0.1 0.9 -5.8 -4.3 -3.6 -3.0 -2.2 98.0 1.0\nc[4,1] -32.0 2.4 22.4-83.5-48.3-24.9-13.2 -5.0 91.0 1.1\nc[5,1] -35.2 2.5 22.6-83.7-50.3-31.9-15.4 -5.7 82.0 1.0\nc[0,2] -3.1 0.1 0.9 -5.0 -3.6 -3.0 -2.4 -1.6 45.0 1.1\nc[1,2] 0.4 0.0 0.4 -0.4 0.2 0.4 0.7 1.3 140.0 1.0\nc[2,2] -2.0 0.0 0.5 -3.2 -2.3 -2.0 -1.6 -1.1 164.0 1.0\nc[3,2] -2.8 0.1 0.7 -4.3 -3.3 -2.8 -2.3 -1.5 94.0 1.0\nc[4,2] -2.5 0.1 0.7 -4.0 -2.9 -2.4 -2.0 -1.2 90.0 1.0\nc[5,2] -4.3 0.1 1.3 -7.5 -5.1 -4.0 -3.4 -2.4 179.0 1.0\nc[0,3] -1.2 0.0 0.5 -2.2 -1.6 -1.2 -0.9 -0.2 145.0 1.0\nc[1,3] 2.1 0.0 0.5 1.1 1.7 2.1 2.4 3.2 162.0 1.0\nc[2,3] -0.8 0.0 0.4 -1.7 -1.1 -0.8 -0.5 0.0 175.0 1.0\nc[3,3] -1.8 0.0 0.6 -2.9 -2.2 -1.8 -1.4 -0.8 135.0 1.0\nc[4,3] -0.1 0.0 0.5 -1.0 -0.4 -0.1 0.2 0.8 170.0 1.0\nc[5,3] -2.1 0.0 0.6 -3.6 -2.5 -2.0 -1.7 -1.0 185.0 1.0\nc[0,4] -0.4 0.0 0.5 -1.4 -0.7 -0.4 -0.1 0.4 131.0 1.0\nc[1,4] 2.6 0.0 0.6 1.5 2.2 2.6 3.1 4.0 151.0 1.0\nc[2,4] -0.4 0.0 0.4 -1.2 -0.6 -0.3 -0.1 0.4 202.0 1.0\nc[3,4] -1.0 0.0 0.5 -2.0 -1.4 -1.0 -0.7 -0.1 134.0 1.0\nc[4,4] 0.4 0.0 0.5 -0.5 0.1 0.3 0.7 1.2 170.0 1.0\nc[5,4] -1.6 0.0 0.6 -2.9 -2.0 -1.6 -1.2 -0.6 216.0 1.0\nc[0,5] -0.2 0.0 0.4 -1.1 -0.5 -0.2 0.1 0.6 162.0 1.0\nc[1,5] 3.6 0.1 0.8 2.2 3.0 3.5 4.0 5.2 175.0 1.0\nc[2,5] 0.6 0.0 0.4 -0.2 0.3 0.6 0.9 1.5 157.0 1.0\nc[3,5] -0.6 0.0 0.5 -1.5 -0.9 -0.6 -0.2 0.4 151.0 1.0\nc[4,5] 0.6 0.0 0.5 -0.2 0.4 0.6 0.9 1.5 214.0 1.0\nc[5,5] -0.8 0.0 0.5 -1.8 -1.1 -0.8 -0.5 0.1 216.0 1.0\nc[0,6] 0.6 0.0 0.4 -0.2 0.3 0.6 0.9 1.4 222.0 1.0\nc[1,6] 5.4 0.1 1.4 3.2 4.5 5.3 6.2 8.6 150.0 1.0\nc[2,6] 1.1 0.0 0.4 0.3 0.8 1.1 1.4 2.0 189.0 1.0\nc[3,6] 0.2 0.0 0.5 -0.8 -0.1 0.2 0.5 1.1 165.0 1.0\nc[4,6] 1.6 0.0 0.5 0.6 1.3 1.6 2.0 2.7 128.0 1.0\nc[5,6] -0.4 0.0 0.4 -1.3 -0.7 -0.4 -0.1 0.5 211.0 1.0\nc[0,7] 1.0 0.0 0.4 0.2 0.7 1.0 1.3 1.9 170.0 1.0\nc[1,7] 6.5 0.1 1.7 3.8 5.3 6.2 7.5 10.5 152.0 1.0\nc[2,7] 1.3 0.0 0.5 0.5 1.1 1.3 1.6 2.2 195.0 1.0\nc[3,7] 0.8 0.0 0.5 -0.2 0.5 0.8 1.1 1.8 149.0 1.0\nc[4,7] 2.2 0.0 0.6 1.1 1.8 2.2 2.6 3.5 153.0 1.0\nc[5,7] -0.0 0.0 0.4 -0.9 -0.3 -0.0 0.2 0.9 206.0 1.0\nc[0,8] 1.9 0.0 0.5 1.0 1.6 1.9 2.2 3.0 154.0 1.0\nc[1,8] 7.5 0.1 1.9 4.5 6.1 7.1 8.6 11.9 159.0 1.0\nc[2,8] 2.3 0.0 0.5 1.2 1.9 2.2 2.6 3.4 213.0 1.0\nc[3,8] 1.5 0.0 0.5 0.4 1.1 1.5 1.8 2.5 161.0 1.0\nc[4,8] 2.8 0.1 0.7 1.6 2.3 2.7 3.2 4.2 156.0 1.0\nc[5,8] 0.6 0.0 0.5 -0.3 0.3 0.6 0.9 1.6 172.0 1.0\npt[0,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 142.0 1.0\npt[1,0] 0.8 0.0 0.1 0.7 0.8 0.9 0.9 0.9 174.0 1.0\npt[2,0] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 147.0 1.0\npt[3,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 82.0 1.0\npt[4,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 306.0 1.0\npt[5,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 325.0 1.0\npt[0,1] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 110.0 1.0\npt[1,1] 0.7 0.0 0.1 0.5 0.6 0.7 0.8 0.9 185.0 1.0\npt[2,1] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 150.0 1.0\npt[3,1] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 150.0 1.0\npt[4,1] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 181.0 1.0\npt[5,1] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 144.0 1.0\npt[0,2] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 146.0 1.0\npt[1,2] 0.6 0.0 0.1 0.4 0.5 0.6 0.6 0.8 234.0 1.0\npt[2,2] 0.9 0.0 0.1 0.8 0.9 0.9 0.9 1.0 155.0 1.0\npt[3,2] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 169.0 1.0\npt[4,2] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 76.0 1.1\npt[5,2] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 216.0 1.0\npt[0,3] 0.9 0.0 0.1 0.7 0.9 0.9 0.9 1.0 169.0 1.0\npt[1,3] 0.2 0.0 0.1 0.1 0.2 0.2 0.3 0.4 165.0 1.0\npt[2,3] 0.8 0.0 0.1 0.5 0.7 0.8 0.8 0.9 174.0 1.0\npt[3,3] 0.9 0.0 0.1 0.8 0.9 0.9 0.9 1.0 160.0 1.0\npt[4,3] 0.7 0.0 0.1 0.5 0.6 0.7 0.8 0.9 157.0 1.0\npt[5,3] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 113.0 1.0\npt[0,4] 0.8 0.0 0.1 0.6 0.7 0.8 0.8 0.9 196.0 1.0\npt[1,4] 0.1 0.0 0.1 0.0 0.1 0.1 0.2 0.3 158.0 1.0\npt[2,4] 0.7 0.0 0.1 0.4 0.6 0.7 0.8 0.9 171.0 1.0\npt[3,4] 0.8 0.0 0.1 0.6 0.7 0.8 0.9 0.9 117.0 1.0\npt[4,4] 0.6 0.0 0.1 0.4 0.5 0.6 0.7 0.8 162.0 1.0\npt[5,4] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 110.0 1.0\npt[0,5] 0.7 0.0 0.1 0.6 0.7 0.7 0.8 0.9 199.0 1.0\npt[1,5] 0.1 0.0 0.0 0.0 0.0 0.1 0.1 0.2 178.0 1.0\npt[2,5] 0.5 0.0 0.1 0.3 0.4 0.5 0.5 0.7 189.0 1.0\npt[3,5] 0.7 0.0 0.1 0.5 0.7 0.7 0.8 0.9 129.0 1.0\npt[4,5] 0.5 0.0 0.1 0.3 0.5 0.5 0.6 0.7 178.0 1.0\npt[5,5] 0.9 0.0 0.0 0.8 0.9 0.9 0.9 1.0 163.0 1.0\npt[0,6] 0.6 0.0 0.1 0.3 0.5 0.6 0.7 0.8 157.0 1.0\npt[1,6] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.1 170.0 1.0\npt[2,6] 0.3 0.0 0.1 0.2 0.3 0.3 0.4 0.5 194.0 1.0\npt[3,6] 0.6 0.0 0.1 0.3 0.5 0.6 0.6 0.7 116.0 1.0\npt[4,6] 0.3 0.0 0.1 0.1 0.2 0.3 0.4 0.5 174.0 1.0\npt[5,6] 0.9 0.0 0.1 0.7 0.8 0.9 0.9 1.0 135.0 1.0\npt[0,7] 0.5 0.0 0.1 0.3 0.4 0.5 0.5 0.7 178.0 1.0\npt[1,7] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 192.0 1.0\npt[2,7] 0.3 0.0 0.1 0.1 0.2 0.3 0.4 0.5 186.0 1.0\npt[3,7] 0.4 0.0 0.1 0.2 0.3 0.4 0.5 0.6 149.0 1.0\npt[4,7] 0.2 0.0 0.1 0.1 0.1 0.2 0.3 0.4 205.0 1.0\npt[5,7] 0.8 0.0 0.1 0.6 0.8 0.8 0.9 0.9 164.0 1.0\npt[0,8] 0.3 0.0 0.1 0.1 0.2 0.3 0.3 0.5 166.0 1.0\npt[1,8] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 208.0 1.0\npt[2,8] 0.2 0.0 0.1 0.0 0.1 0.1 0.2 0.3 146.0 1.0\npt[3,8] 0.3 0.0 0.1 0.1 0.2 0.3 0.3 0.5 120.0 1.0\npt[4,8] 0.1 0.0 0.1 0.0 0.1 0.1 0.2 0.3 232.0 1.0\npt[5,8] 0.7 0.0 0.1 0.5 0.7 0.7 0.8 0.9 196.0 1.0\npc[0,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 152.0 1.0\npc[1,0] 0.7 0.0 0.1 0.6 0.7 0.7 0.8 0.9 123.0 1.0\npc[2,0] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 137.0 1.0\npc[3,0] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 59.0 1.1\npc[4,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 303.0 1.0\npc[5,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 327.0 1.0\npc[0,1] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 86.0 1.0\npc[1,1] 0.5 0.0 0.1 0.4 0.5 0.5 0.6 0.7 152.0 1.0\npc[2,1] 0.9 0.0 0.0 0.8 0.9 0.9 1.0 1.0 153.0 1.0\npc[3,1] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 97.0 1.0\npc[4,1] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 163.0 1.0\npc[5,1] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 172.0 1.0\npc[0,2] 0.9 0.0 0.0 0.8 0.9 1.0 1.0 1.0 86.0 1.0\npc[1,2] 0.4 0.0 0.1 0.2 0.3 0.4 0.5 0.6 139.0 1.0\npc[2,2] 0.9 0.0 0.1 0.7 0.8 0.9 0.9 1.0 163.0 1.0\npc[3,2] 0.9 0.0 0.0 0.8 0.9 0.9 1.0 1.0 87.0 1.0\npc[4,2] 0.9 0.0 0.1 0.8 0.9 0.9 0.9 1.0 95.0 1.0\npc[5,2] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 208.0 1.0\npc[0,3] 0.8 0.0 0.1 0.6 0.7 0.8 0.8 0.9 136.0 1.0\npc[1,3] 0.1 0.0 0.1 0.0 0.1 0.1 0.2 0.3 160.0 1.0\npc[2,3] 0.7 0.0 0.1 0.5 0.6 0.7 0.7 0.8 177.0 1.0\npc[3,3] 0.8 0.0 0.1 0.7 0.8 0.9 0.9 0.9 145.0 1.0\npc[4,3] 0.5 0.0 0.1 0.3 0.5 0.5 0.6 0.7 169.0 1.0\npc[5,3] 0.9 0.0 0.1 0.7 0.8 0.9 0.9 1.0 187.0 1.0\npc[0,4] 0.6 0.0 0.1 0.4 0.5 0.6 0.7 0.8 130.0 1.0\npc[1,4] 0.1 0.0 0.0 0.0 0.0 0.1 0.1 0.2 159.0 1.0\npc[2,4] 0.6 0.0 0.1 0.4 0.5 0.6 0.7 0.8 202.0 1.0\npc[3,4] 0.7 0.0 0.1 0.5 0.7 0.7 0.8 0.9 135.0 1.0\npc[4,4] 0.4 0.0 0.1 0.2 0.3 0.4 0.5 0.6 212.0 1.0\npc[5,4] 0.8 0.0 0.1 0.7 0.8 0.8 0.9 0.9 221.0 1.0\npc[0,5] 0.6 0.0 0.1 0.3 0.5 0.6 0.6 0.7 160.0 1.0\npc[1,5] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.1 171.0 1.0\npc[2,5] 0.4 0.0 0.1 0.2 0.3 0.4 0.4 0.6 168.0 1.0\npc[3,5] 0.6 0.0 0.1 0.4 0.6 0.6 0.7 0.8 156.0 1.0\npc[4,5] 0.3 0.0 0.1 0.2 0.3 0.3 0.4 0.6 214.0 1.0\npc[5,5] 0.7 0.0 0.1 0.5 0.6 0.7 0.7 0.9 228.0 1.0\npc[0,6] 0.4 0.0 0.1 0.2 0.3 0.4 0.4 0.6 224.0 1.0\npc[1,6] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 190.0 1.0\npc[2,6] 0.3 0.0 0.1 0.1 0.2 0.2 0.3 0.4 191.0 1.0\npc[3,6] 0.5 0.0 0.1 0.3 0.4 0.5 0.5 0.7 166.0 1.0\npc[4,6] 0.2 0.0 0.1 0.1 0.1 0.2 0.2 0.3 133.0 1.0\npc[5,6] 0.6 0.0 0.1 0.4 0.5 0.6 0.7 0.8 212.0 1.0\npc[0,7] 0.3 0.0 0.1 0.1 0.2 0.3 0.3 0.5 184.0 1.0\npc[1,7] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 189.0 1.0\npc[2,7] 0.2 0.0 0.1 0.1 0.2 0.2 0.3 0.4 199.0 1.0\npc[3,7] 0.3 0.0 0.1 0.1 0.2 0.3 0.4 0.5 151.0 1.0\npc[4,7] 0.1 0.0 0.1 0.0 0.1 0.1 0.1 0.2 161.0 1.0\npc[5,7] 0.5 0.0 0.1 0.3 0.4 0.5 0.6 0.7 205.0 1.0\npc[0,8] 0.1 0.0 0.1 0.0 0.1 0.1 0.2 0.3 147.0 1.0\npc[1,8] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 196.0 1.0\npc[2,8] 0.1 0.0 0.1 0.0 0.1 0.1 0.1 0.2 206.0 1.0\npc[3,8] 0.2 0.0 0.1 0.1 0.1 0.2 0.2 0.4 164.0 1.0\npc[4,8] 0.1 0.0 0.0 0.0 0.0 0.1 0.1 0.2 166.0 1.0\npc[5,8] 0.4 0.0 0.1 0.2 0.3 0.3 0.4 0.6 176.0 1.0\nlp__ -478.9 0.5 5.4-489.8-482.4-478.7-475.3-468.9 136.0 1.0\n\nSamples were drawn using NUTS(diag_e) at Sat Jun 14 01:33:17 2014.\nFor each parameter, n_eff is a crude measure of effective sample size,\nand Rhat is the potential scale reduction factor on split chains (at \nconvergence, Rhat=1).\n" ], [ "pt=fit.extract()['pt']\npc=fit.extract()['pc']\nDP=np.zeros((pt.shape[2]+2,pt.shape[1],2))\nDP[0,:,:]=1\nDP[1:-1,:,:]=np.array([pc,pt]).T.mean(2)\nDP=-np.diff(DP,axis=0)\nplotComparison(DS[:,:7],DP,stan=True)", "_____no_output_____" ], [ "model='''\ndata {\n int<lower=2> K;\n int<lower=0> N;\n int<lower=1> M;\n int<lower=1,upper=K> y[N,M];\n int x[N];\n}\nparameters {\n real beta;\n ordered[K-1] c[M];\n}\ntransformed parameters{\n real pt[M,K-1]; real pc[M,K-1];\n for (m in 1:M){\n for (k in 1:(K-1)){\n pt[m,k] <- inv_logit(beta-c[m][k]);\n pc[m,k] <- inv_logit(-c[m][k]);\n}}}\nmodel {\nfor (m in 1:M){\n for (k in 1:(K-1)) c[m][k]~ uniform(-100,100);\n for (n in 1:N) y[n,m] ~ ordered_logistic(x[n] * beta, c[m]);\n}}\n'''\nsm2=pystan.StanModel(model_code=model)", "_____no_output_____" ], [ "dat = {'y':np.int32(DS[:,1:7])+1,'x':np.int32(DS[:,0]),'N':DS.shape[0] ,'K':10,'M':6}\nfit2 = sm2.sampling(data=dat,iter=1000, chains=4,thin=2,warmup=500,njobs=2,seed=4)\nprint fit2\nsaveStanFit(fit2,'fit2')", "Inference for Stan model: anon_model_7216e04af35b427b9a410fdc88ae5601.\n4 chains, each with iter=1000; warmup=500; thin=2; \npost-warmup draws per chain=250, total post-warmup draws=1000.\n\n mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat\nbeta 0.7 0.0 0.2 0.3 0.6 0.7 0.9 1.2 132.0 1.0\nc[0,0] -53.7 4.2 26.8-97.1-75.8-55.2-31.5 -8.7 40.0 1.1\nc[1,0] -1.1 0.0 0.4 -1.8 -1.3 -1.1 -0.8 -0.4 103.0 1.0\nc[2,0] -3.6 0.1 1.0 -5.7 -4.2 -3.5 -2.9 -2.0 79.0 1.0\nc[3,0] -5.2 0.2 1.4 -8.5 -5.9 -4.9 -4.1 -3.0 75.0 1.0\nc[4,0] -68.0 2.2 22.1-99.0-86.7-71.2-52.1 -21.5 106.0 1.0\nc[5,0] -71.0 2.3 21.8-99.1-89.1-75.7-54.6 -23.0 88.0 1.0\nc[0,1] -3.5 0.1 0.9 -5.4 -4.1 -3.4 -2.9 -2.0 172.0 1.0\nc[1,1] -0.1 0.0 0.3 -0.8 -0.4 -0.1 0.1 0.5 152.0 1.0\nc[2,1] -2.7 0.1 0.7 -4.2 -3.1 -2.7 -2.2 -1.5 117.0 1.0\nc[3,1] -3.7 0.1 1.1 -6.8 -4.1 -3.5 -3.0 -2.1 64.0 1.1\nc[4,1] -36.2 2.0 21.4-81.5-51.8-33.3-18.3 -5.3 114.0 1.0\nc[5,1] -39.9 2.5 22.3-86.7-56.5-36.6-21.2 -7.3 79.0 1.0\nc[0,2] -3.0 0.1 0.8 -4.8 -3.4 -2.9 -2.5 -1.7 187.0 1.0\nc[1,2] 0.4 0.0 0.3 -0.3 0.2 0.4 0.6 1.1 137.0 1.0\nc[2,2] -1.9 0.0 0.5 -2.9 -2.2 -1.8 -1.5 -0.9 145.0 1.0\nc[3,2] -2.7 0.1 0.7 -4.2 -3.1 -2.6 -2.2 -1.4 109.0 1.0\nc[4,2] -2.5 0.1 0.7 -4.2 -2.9 -2.4 -2.0 -1.2 137.0 1.0\nc[5,2] -4.7 0.1 1.4 -8.1 -5.5 -4.5 -3.7 -2.7 89.0 1.0\nc[0,3] -1.3 0.0 0.4 -2.1 -1.5 -1.3 -1.0 -0.5 153.0 1.0\nc[1,3] 2.0 0.0 0.5 1.2 1.7 2.0 2.3 2.9 159.0 1.0\nc[2,3] -0.7 0.0 0.4 -1.5 -0.9 -0.7 -0.4 0.1 220.0 1.0\nc[3,3] -1.7 0.0 0.5 -2.7 -2.0 -1.7 -1.4 -0.8 154.0 1.0\nc[4,3] -0.1 0.0 0.4 -0.8 -0.4 -0.1 0.1 0.6 221.0 1.0\nc[5,3] -2.4 0.0 0.6 -3.7 -2.8 -2.4 -2.0 -1.4 159.0 1.0\nc[0,4] -0.6 0.0 0.4 -1.3 -0.8 -0.6 -0.3 0.2 152.0 1.0\nc[1,4] 2.6 0.0 0.6 1.6 2.2 2.5 2.9 3.9 148.0 1.0\nc[2,4] -0.2 0.0 0.4 -1.0 -0.5 -0.2 -0.0 0.5 221.0 1.0\nc[3,4] -0.9 0.0 0.4 -1.7 -1.2 -0.9 -0.6 -0.1 78.0 1.0\nc[4,4] 0.4 0.0 0.4 -0.3 0.1 0.3 0.6 1.1 234.0 1.0\nc[5,4] -1.9 0.0 0.5 -3.1 -2.3 -1.9 -1.6 -1.0 196.0 1.0\nc[0,5] -0.3 0.0 0.4 -1.1 -0.6 -0.3 -0.1 0.4 200.0 1.0\nc[1,5] 3.4 0.1 0.7 2.1 2.9 3.4 3.9 4.9 139.0 1.0\nc[2,5] 0.7 0.0 0.4 0.0 0.5 0.7 1.0 1.4 219.0 1.0\nc[3,5] -0.4 0.0 0.4 -1.2 -0.7 -0.4 -0.2 0.3 134.0 1.0\nc[4,5] 0.6 0.0 0.4 -0.0 0.4 0.6 0.9 1.4 267.0 1.0\nc[5,5] -1.1 0.0 0.4 -2.0 -1.4 -1.1 -0.8 -0.3 257.0 1.0\nc[0,6] 0.5 0.0 0.3 -0.2 0.2 0.5 0.7 1.2 246.0 1.0\nc[1,6] 5.3 0.1 1.4 3.1 4.3 5.1 6.1 8.6 153.0 1.0\nc[2,6] 1.3 0.0 0.4 0.5 1.0 1.2 1.5 2.0 223.0 1.0\nc[3,6] 0.3 0.0 0.3 -0.3 0.1 0.3 0.5 1.0 264.0 1.0\nc[4,6] 1.6 0.0 0.4 0.8 1.3 1.6 1.9 2.4 253.0 1.0\nc[5,6] -0.7 0.0 0.4 -1.6 -1.0 -0.7 -0.5 -0.0 287.0 1.0\nc[0,7] 0.9 0.0 0.4 0.2 0.6 0.9 1.1 1.5 228.0 1.0\nc[1,7] 6.3 0.2 1.8 3.7 5.0 5.9 7.4 10.7 139.0 1.0\nc[2,7] 1.5 0.0 0.4 0.7 1.2 1.5 1.8 2.3 207.0 1.0\nc[3,7] 0.9 0.0 0.4 0.2 0.7 0.9 1.2 1.7 170.0 1.0\nc[4,7] 2.2 0.0 0.5 1.3 1.9 2.2 2.5 3.2 232.0 1.0\nc[5,7] -0.4 0.0 0.4 -1.1 -0.6 -0.4 -0.1 0.3 306.0 1.0\nc[0,8] 1.8 0.0 0.4 1.0 1.5 1.8 2.1 2.6 218.0 1.0\nc[1,8] 7.4 0.2 2.2 4.0 5.8 7.1 8.8 12.3 125.0 1.0\nc[2,8] 2.4 0.0 0.5 1.4 2.0 2.4 2.7 3.5 166.0 1.0\nc[3,8] 1.6 0.0 0.4 0.8 1.4 1.6 1.9 2.4 151.0 1.0\nc[4,8] 2.8 0.0 0.6 1.7 2.4 2.7 3.1 4.1 204.0 1.0\nc[5,8] 0.2 0.0 0.4 -0.5 -0.0 0.2 0.5 0.9 279.0 1.0\npt[0,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 290.0 1.0\npt[1,0] 0.9 0.0 0.0 0.7 0.8 0.9 0.9 0.9 137.0 1.0\npt[2,0] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 70.0 1.0\npt[3,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 85.0 1.0\npt[4,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 248.0 1.0\npt[5,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 289.0 1.0\npt[0,1] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 137.0 1.0\npt[1,1] 0.7 0.0 0.1 0.6 0.7 0.7 0.8 0.8 197.0 1.0\npt[2,1] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 92.0 1.0\npt[3,1] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 114.0 1.0\npt[4,1] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 209.0 1.0\npt[5,1] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 202.0 1.0\npt[0,2] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 131.0 1.0\npt[1,2] 0.6 0.0 0.1 0.4 0.5 0.6 0.6 0.7 193.0 1.0\npt[2,2] 0.9 0.0 0.0 0.8 0.9 0.9 0.9 1.0 146.0 1.0\npt[3,2] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 135.0 1.0\npt[4,2] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 155.0 1.0\npt[5,2] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 150.0 1.0\npt[0,3] 0.9 0.0 0.0 0.8 0.8 0.9 0.9 0.9 159.0 1.0\npt[1,3] 0.2 0.0 0.1 0.1 0.2 0.2 0.3 0.4 208.0 1.0\npt[2,3] 0.8 0.0 0.1 0.7 0.8 0.8 0.8 0.9 187.0 1.0\npt[3,3] 0.9 0.0 0.0 0.8 0.9 0.9 0.9 1.0 140.0 1.0\npt[4,3] 0.7 0.0 0.1 0.5 0.6 0.7 0.7 0.8 233.0 1.0\npt[5,3] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 156.0 1.0\npt[0,4] 0.8 0.0 0.1 0.6 0.7 0.8 0.8 0.9 196.0 1.0\npt[1,4] 0.1 0.0 0.1 0.0 0.1 0.1 0.2 0.3 189.0 1.0\npt[2,4] 0.7 0.0 0.1 0.6 0.7 0.7 0.8 0.9 161.0 1.0\npt[3,4] 0.8 0.0 0.1 0.7 0.8 0.8 0.9 0.9 87.0 1.0\npt[4,4] 0.6 0.0 0.1 0.4 0.5 0.6 0.6 0.7 228.0 1.0\npt[5,4] 0.9 0.0 0.0 0.9 0.9 0.9 1.0 1.0 203.0 1.0\npt[0,5] 0.7 0.0 0.1 0.6 0.7 0.7 0.8 0.9 238.0 1.0\npt[1,5] 0.1 0.0 0.0 0.0 0.0 0.1 0.1 0.2 153.0 1.0\npt[2,5] 0.5 0.0 0.1 0.3 0.4 0.5 0.6 0.7 255.0 1.0\npt[3,5] 0.8 0.0 0.1 0.6 0.7 0.8 0.8 0.9 152.0 1.0\npt[4,5] 0.5 0.0 0.1 0.4 0.5 0.5 0.6 0.7 206.0 1.0\npt[5,5] 0.9 0.0 0.1 0.7 0.8 0.9 0.9 0.9 213.0 1.0\npt[0,6] 0.6 0.0 0.1 0.4 0.5 0.6 0.6 0.7 209.0 1.0\npt[1,6] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.1 187.0 1.0\npt[2,6] 0.4 0.0 0.1 0.2 0.3 0.4 0.4 0.6 251.0 1.0\npt[3,6] 0.6 0.0 0.1 0.4 0.5 0.6 0.7 0.7 256.0 1.0\npt[4,6] 0.3 0.0 0.1 0.2 0.2 0.3 0.4 0.5 233.0 1.0\npt[5,6] 0.8 0.0 0.1 0.7 0.8 0.8 0.9 0.9 239.0 1.0\npt[0,7] 0.5 0.0 0.1 0.3 0.4 0.5 0.5 0.6 193.0 1.0\npt[1,7] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 174.0 1.0\npt[2,7] 0.3 0.0 0.1 0.2 0.3 0.3 0.4 0.5 212.0 1.0\npt[3,7] 0.5 0.0 0.1 0.3 0.4 0.4 0.5 0.6 246.0 1.0\npt[4,7] 0.2 0.0 0.1 0.1 0.1 0.2 0.2 0.4 215.0 1.0\npt[5,7] 0.7 0.0 0.1 0.6 0.7 0.8 0.8 0.9 225.0 1.0\npt[0,8] 0.3 0.0 0.1 0.1 0.2 0.3 0.3 0.4 257.0 1.0\npt[1,8] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 180.0 1.0\npt[2,8] 0.2 0.0 0.1 0.1 0.1 0.2 0.2 0.3 159.0 1.0\npt[3,8] 0.3 0.0 0.1 0.2 0.2 0.3 0.3 0.5 167.0 1.0\npt[4,8] 0.1 0.0 0.1 0.0 0.1 0.1 0.2 0.3 203.0 1.0\npt[5,8] 0.6 0.0 0.1 0.5 0.6 0.6 0.7 0.8 253.0 1.0\npc[0,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 288.0 1.0\npc[1,0] 0.7 0.0 0.1 0.6 0.7 0.7 0.8 0.9 100.0 1.0\npc[2,0] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 78.0 1.0\npc[3,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 72.0 1.0\npc[4,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 248.0 1.0\npc[5,0] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 280.0 1.0\npc[0,1] 1.0 0.0 0.0 0.9 0.9 1.0 1.0 1.0 159.0 1.0\npc[1,1] 0.5 0.0 0.1 0.4 0.5 0.5 0.6 0.7 152.0 1.0\npc[2,1] 0.9 0.0 0.0 0.8 0.9 0.9 1.0 1.0 106.0 1.0\npc[3,1] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 101.0 1.0\npc[4,1] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 218.0 1.0\npc[5,1] 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 194.0 1.0\npc[0,2] 0.9 0.0 0.0 0.8 0.9 0.9 1.0 1.0 161.0 1.0\npc[1,2] 0.4 0.0 0.1 0.3 0.3 0.4 0.5 0.6 135.0 1.0\npc[2,2] 0.9 0.0 0.1 0.7 0.8 0.9 0.9 0.9 149.0 1.0\npc[3,2] 0.9 0.0 0.0 0.8 0.9 0.9 1.0 1.0 123.0 1.0\npc[4,2] 0.9 0.0 0.1 0.8 0.9 0.9 0.9 1.0 161.0 1.0\npc[5,2] 1.0 0.0 0.0 0.9 1.0 1.0 1.0 1.0 122.0 1.0\npc[0,3] 0.8 0.0 0.1 0.6 0.7 0.8 0.8 0.9 154.0 1.0\npc[1,3] 0.1 0.0 0.0 0.1 0.1 0.1 0.2 0.2 167.0 1.0\npc[2,3] 0.7 0.0 0.1 0.5 0.6 0.7 0.7 0.8 223.0 1.0\npc[3,3] 0.8 0.0 0.1 0.7 0.8 0.8 0.9 0.9 148.0 1.0\npc[4,3] 0.5 0.0 0.1 0.4 0.5 0.5 0.6 0.7 221.0 1.0\npc[5,3] 0.9 0.0 0.0 0.8 0.9 0.9 0.9 1.0 159.0 1.0\npc[0,4] 0.6 0.0 0.1 0.5 0.6 0.6 0.7 0.8 159.0 1.0\npc[1,4] 0.1 0.0 0.0 0.0 0.1 0.1 0.1 0.2 180.0 1.0\npc[2,4] 0.6 0.0 0.1 0.4 0.5 0.6 0.6 0.7 220.0 1.0\npc[3,4] 0.7 0.0 0.1 0.5 0.6 0.7 0.8 0.8 78.0 1.0\npc[4,4] 0.4 0.0 0.1 0.3 0.4 0.4 0.5 0.6 231.0 1.0\npc[5,4] 0.9 0.0 0.1 0.7 0.8 0.9 0.9 1.0 193.0 1.0\npc[0,5] 0.6 0.0 0.1 0.4 0.5 0.6 0.6 0.8 201.0 1.0\npc[1,5] 0.0 0.0 0.0 0.0 0.0 0.0 0.1 0.1 150.0 1.0\npc[2,5] 0.3 0.0 0.1 0.2 0.3 0.3 0.4 0.5 216.0 1.0\npc[3,5] 0.6 0.0 0.1 0.4 0.5 0.6 0.7 0.8 130.0 1.0\npc[4,5] 0.3 0.0 0.1 0.2 0.3 0.3 0.4 0.5 270.0 1.0\npc[5,5] 0.7 0.0 0.1 0.6 0.7 0.7 0.8 0.9 252.0 1.0\npc[0,6] 0.4 0.0 0.1 0.2 0.3 0.4 0.4 0.6 244.0 1.0\npc[1,6] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 195.0 1.0\npc[2,6] 0.2 0.0 0.1 0.1 0.2 0.2 0.3 0.4 222.0 1.0\npc[3,6] 0.4 0.0 0.1 0.3 0.4 0.4 0.5 0.6 264.0 1.0\npc[4,6] 0.2 0.0 0.1 0.1 0.1 0.2 0.2 0.3 257.0 1.0\npc[5,6] 0.7 0.0 0.1 0.5 0.6 0.7 0.7 0.8 285.0 1.0\npc[0,7] 0.3 0.0 0.1 0.2 0.2 0.3 0.3 0.5 228.0 1.0\npc[1,7] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 182.0 1.0\npc[2,7] 0.2 0.0 0.1 0.1 0.1 0.2 0.2 0.3 208.0 1.0\npc[3,7] 0.3 0.0 0.1 0.2 0.2 0.3 0.3 0.4 166.0 1.0\npc[4,7] 0.1 0.0 0.0 0.0 0.1 0.1 0.1 0.2 236.0 1.0\npc[5,7] 0.6 0.0 0.1 0.4 0.5 0.6 0.6 0.8 306.0 1.0\npc[0,8] 0.2 0.0 0.1 0.1 0.1 0.1 0.2 0.3 222.0 1.0\npc[1,8] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 182.0 1.0\npc[2,8] 0.1 0.0 0.0 0.0 0.1 0.1 0.1 0.2 158.0 1.0\npc[3,8] 0.2 0.0 0.1 0.1 0.1 0.2 0.2 0.3 147.0 1.0\npc[4,8] 0.1 0.0 0.0 0.0 0.0 0.1 0.1 0.1 209.0 1.0\npc[5,8] 0.4 0.0 0.1 0.3 0.4 0.4 0.5 0.6 279.0 1.0\nlp__ -478.0 0.6 6.1-492.6-481.5-477.6-473.6-467.5 109.0 1.0\n\nSamples were drawn using NUTS(diag_e) at Sat Jun 14 10:05:05 2014.\nFor each parameter, n_eff is a crude measure of effective sample size,\nand Rhat is the potential scale reduction factor on split chains (at \nconvergence, Rhat=1).\n" ], [ "w=loadStanFit('fit2')\npt=w['pt']\npc=w['pc']\nDP=np.zeros((pt.shape[2]+2,pt.shape[1],2))\nDP[0,:,:]=1\nDP[1:-1,:,:]=np.array([pc,pt]).T.mean(2)\nDP=-np.diff(DP,axis=0)\nplotComparison(DS[:,:7],DP,stan=True)", "_____no_output_____" ], [ "model='''\ndata {\n int<lower=2> K;\n int<lower=0> N;\n int<lower=1> M;\n int<lower=1,upper=K> y[N,M];\n int x[N];\n}\nparameters {\n // real mb; real<lower=0,upper=100> sb[2];\n vector[2*M-1] bbeta;\n ordered[K-1] c;\n}\ntransformed parameters{\n real pt[M,K-1]; real pc[M,K-1];\n vector[M] beta[2];\n for (m in 1:M){\n if (m==1){beta[1][m]<-0.0; beta[2][m]<-bbeta[2*M-1];}\n else{beta[1][m]<-bbeta[2*(m-1)-1]; beta[2][m]<-bbeta[2*(m-1)];}\n for (k in 1:(K-1)){\n pt[m,k] <- inv_logit(beta[2][m]-c[k]);\n pc[m,k] <- inv_logit(beta[1][m]-c[k]);\n}}}\nmodel {\nfor (k in 1:(K-1)) c[k]~ uniform(-100,100);\n//beta[1]~normal(0.0,sb[1]);\n//beta[2]~normal(mb,sb[2]);\nfor (m in 1:M){\n for (n in 1:N) y[n,m] ~ ordered_logistic(beta[x[n]+1][m], c);\n}}\n'''\nsm3=pystan.StanModel(model_code=model)", "INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_b233c89bb9dd8a0b522a51670536ebd9 NOW.\n" ], [ "dat = {'y':np.int32(DS[:,1:7])+1,'x':np.int32(DS[:,0]),'N':DS.shape[0] ,'K':10,'M':6}\nfit3 = sm3.sampling(data=dat,iter=1000, chains=4,thin=2,warmup=500,njobs=2,seed=4)\n#print fit3\nsaveStanFit(fit3,'fit3')", "_____no_output_____" ], [ "w=loadStanFit('fit3')\npt=w['pt']\npc=w['pc']\nDP=np.zeros((pt.shape[2]+2,pt.shape[1],2))\nDP[0,:,:]=1\nDP[1:-1,:,:]=np.array([pc,pt]).T.mean(2)\nDP=-np.diff(DP,axis=0)\nplotComparison(DS[:,:7],DP,stan=True)", "_____no_output_____" ], [ "model='''\ndata {\n int<lower=2> K;\n int<lower=0> N;\n int<lower=1> M;\n int<lower=1,upper=K> y[N,M];\n int x[N];\n}\nparameters {\n // real mb; real<lower=0,upper=100> sb[2];\n vector[M-1] bbeta;\n real delt;\n ordered[K-1] c;\n}\ntransformed parameters{\n real pt[M,K-1]; real pc[M,K-1];\n vector[M] beta;\n for (m in 1:M){\n if (m==1) beta[m]<-0.0; \n else beta[m]<-bbeta[m-1];\n for (k in 1:(K-1)){\n pt[m,k] <- inv_logit(beta[m]+delt-c[k]);\n pc[m,k] <- inv_logit(beta[m]-c[k]);\n}}}\nmodel {\nfor (k in 1:(K-1)) c[k]~ uniform(-100,100);\nfor (m in 1:M){\n for (n in 1:N) y[n,m] ~ ordered_logistic(beta[m]+delt*x[n], c);\n}}\n'''\nsm4=pystan.StanModel(model_code=model)", "_____no_output_____" ], [ "dat = {'y':np.int32(DS[:,1:7])+1,'x':np.int32(DS[:,0]),'N':DS.shape[0] ,'K':10,'M':6}\nfit4 = sm4.sampling(data=dat,iter=1000, chains=4,thin=2,warmup=500,njobs=2,seed=4)\nprint pystan.misc._print_stanfit(fit4,pars=['delt','bbeta','c'],digits_summary=2)\nsaveStanFit(fit4,'fit4')", "Inference for Stan model: anon_model_ea755999b4327833f97905399d8651f3.\n4 chains, each with iter=1000; warmup=500; thin=2; \npost-warmup draws per chain=250, total post-warmup draws=1000.\n\n mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat\ndelt 0.67 0.01 0.24 0.21 0.51 0.67 0.83 1.14 334.0 1.0\nbbeta[0]-3.16 0.03 0.46-4.04-3.47-3.16-2.85 -2.26 240.0 1.0\nbbeta[1]-0.68 0.02 0.4-1.47-0.95-0.68-0.42 0.11 264.0 1.0\nbbeta[2] 0.1 0.02 0.4-0.67-0.19 0.11 0.36 0.94 288.0 1.0\nbbeta[3]-0.91 0.02 0.4-1.67-1.19-0.91-0.63 -0.14 260.0 1.0\nbbeta[4] 1.24 0.02 0.41 0.4 0.97 1.24 1.51 2.02 302.0 1.0\nc[0] -4.22 0.03 0.46-5.14-4.53-4.22-3.92 -3.28 272.0 1.0\nc[1] -3.32 0.03 0.41-4.13 -3.6-3.34-3.02 -2.46 249.0 1.0\nc[2] -2.65 0.02 0.39-3.37-2.91-2.66-2.39 -1.85 269.0 1.0\nc[3] -1.16 0.02 0.33-1.78-1.38-1.17-0.93 -0.51 256.0 1.0\nc[4] -0.68 0.02 0.32-1.28-0.89-0.68-0.47 -0.04 267.0 1.0\nc[5] -0.2 0.02 0.31-0.79-0.42-0.19-0.01 0.47 271.0 1.0\nc[6] 0.48 0.02 0.31-0.08 0.26 0.48 0.68 1.11 280.0 1.0\nc[7] 0.83 0.02 0.31 0.26 0.61 0.84 1.04 1.5 281.0 1.0\nc[8] 1.49 0.02 0.31 0.91 1.25 1.49 1.69 2.15 286.0 1.0\n\nSamples were drawn using NUTS(diag_e) at Sat Jun 14 13:13:03 2014.\nFor each parameter, n_eff is a crude measure of effective sample size,\nand Rhat is the potential scale reduction factor on split chains (at \nconvergence, Rhat=1).\n" ], [ "w=loadStanFit('fit4')\npt=w['pt']\npc=w['pc']\nDP=np.zeros((pt.shape[2]+2,pt.shape[1],2))\nDP[0,:,:]=1\nDP[1:-1,:,:]=np.array([pc,pt]).T.mean(2)\nDP=-np.diff(DP,axis=0)\nplotComparison(DS[:,:7],DP,stan=True)", "_____no_output_____" ], [ "pystanErrorbar(w,keys=['beta','c','delt'])", "delt 0.673595459215 CI [0.211,1.140]\n" ], [ "dat = {'y':np.int32(DR[:,1:7])+1,'x':np.int32(DR[:,0]),'N':DR.shape[0] ,'K':10,'M':6}\nfit5 = sm4.sampling(data=dat,iter=1000, chains=4,thin=2,warmup=500,njobs=2,seed=4)\nprint pystan.misc._print_stanfit(fit4,pars=['delt','bbeta','c'],digits_summary=2)\nsaveStanFit(fit5,'fit5')", "INFO:pystan:NOW ON CHAIN 1\nINFO:pystan:NOW ON CHAIN 0\nINFO:pystan:NOW ON CHAIN 3\nINFO:pystan:NOW ON CHAIN 2\n" ], [ "w=loadStanFit('fit5')\npt=w['pt']\npc=w['pc']\nDP=np.zeros((pt.shape[2]+2,pt.shape[1],2))\nDP[0,:,:]=1\nDP[1:-1,:,:]=np.array([pc,pt]).T.mean(2)\nDP=-np.diff(DP,axis=0)\nplotComparison(DR[:,:7],DP,stan=True)", "_____no_output_____" ], [ "pystanErrorbar(w,keys=['beta','c','delt'])", "delt -0.0163305817326 CI [-0.220,0.186]\n" ], [ "model='''\ndata {\n int<lower=2> K;\n int<lower=0> N;\n int<lower=1> M;\n int<lower=1,upper=K> y[N,M];\n int x[N,2];\n}\nparameters {\n // real mb; real<lower=0,upper=100> sb[2];\n vector[M-1] bbeta;\n real dd[3];\n ordered[K-1] c;\n}\ntransformed parameters{\n //real pt[M,K-1]; real pc[M,K-1];\n vector[M] beta;\n for (m in 1:M){\n if (m==1) beta[m]<-0.0; \n else beta[m]<-bbeta[m-1];\n //for (k in 1:(K-1)){\n // pt[m,k] <- inv_logit(beta[m]+delt-c[k]);\n // pc[m,k] <- inv_logit(beta[m]-c[k]);}\n}}\nmodel {\nfor (k in 1:(K-1)) c[k]~ uniform(-100,100);\nfor (m in 1:M){\n for (n in 1:N) y[n,m] ~ ordered_logistic(beta[m]\n +dd[2]*x[n,1]*(1-x[n,2]) // rep + control\n +dd[1]*x[n,2]*(1-x[n,1]) // orig + treat\n +dd[3]*x[n,1]*x[n,2], c); // rep + treat\n}}\n'''\nsm5=pystan.StanModel(model_code=model)", "INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_5463f0c280d4ea208ffd631f059de31d NOW.\n" ], [ "dat = {'y':np.int32(D[:,2:8])+1,'x':np.int32(D[:,[0,1]]),'N':D.shape[0] ,'K':10,'M':6}\nfit6 = sm5.sampling(data=dat,iter=1000, chains=4,thin=2,warmup=500,njobs=2,seed=4)\nprint pystan.misc._print_stanfit(fit6,pars=['dd','bbeta','c'],digits_summary=2)\nsaveStanFit(fit6,'fit6')", "Inference for Stan model: anon_model_5463f0c280d4ea208ffd631f059de31d.\n4 chains, each with iter=1000; warmup=500; thin=2; \npost-warmup draws per chain=250, total post-warmup draws=1000.\n\n mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat\ndd[0] 0.67 0.01 0.22 0.22 0.52 0.67 0.82 1.12 307.0 1.0\ndd[1] 1.23 0.01 0.18 0.88 1.11 1.24 1.35 1.58 307.0 1.0\ndd[2] 1.21 0.01 0.18 0.86 1.09 1.21 1.33 1.57 306.0 1.0\nbbeta[0] -3.4 0.01 0.18-3.75-3.53-3.39-3.27 -3.06 317.0 1.0\nbbeta[1]-0.44 0.01 0.16-0.75-0.56-0.43-0.33 -0.11 295.0 1.0\nbbeta[2]-0.24 0.01 0.17-0.59-0.35-0.25-0.12 0.09 309.0 1.0\nbbeta[3]-0.61 0.01 0.17-0.94-0.73-0.62-0.49 -0.28 296.0 1.0\nbbeta[4] 0.57 0.01 0.18 0.23 0.45 0.56 0.69 0.92 293.0 1.01\nc[0] -4.42 0.02 0.27-4.94-4.61-4.43-4.23 -3.94 311.0 1.0\nc[1] -3.41 0.01 0.24-3.89-3.58-3.41-3.25 -2.95 314.0 1.0\nc[2] -2.52 0.01 0.22-2.95-2.67-2.52-2.37 -2.08 303.0 1.0\nc[3] -1.21 0.01 0.21 -1.6-1.35 -1.2-1.07 -0.79 298.0 1.0\nc[4] -0.82 0.01 0.2-1.19-0.96-0.82-0.68 -0.4 294.0 1.01\nc[5] -0.3 0.01 0.2-0.69-0.45-0.31-0.17 0.09 295.0 1.0\nc[6] 0.38 0.01 0.2-0.01 0.24 0.38 0.51 0.8 294.0 1.01\nc[7] 0.79 0.01 0.2 0.4 0.65 0.79 0.92 1.2 296.0 1.0\nc[8] 1.26 0.01 0.2 0.87 1.12 1.26 1.39 1.68 295.0 1.01\n\nSamples were drawn using NUTS(diag_e) at Sat Jun 14 13:46:31 2014.\nFor each parameter, n_eff is a crude measure of effective sample size,\nand Rhat is the potential scale reduction factor on split chains (at \nconvergence, Rhat=1).\n" ], [ "w=loadStanFit('fit6')\npystanErrorbar(w,keys=['beta','c','dd'])", "_____no_output_____" ], [ "plt.figure(figsize=(10,4))\nc=w['c']\nb=w['beta']\nd=w['dd']\nerrorbar(c,x=np.linspace(6.5,8,9))\nax=plt.gca()\nplt.plot([-1,100],[0,0],'k',lw=2)\nax.set_yticks(np.median(c,axis=0))\nax.set_yticklabels(np.arange(1,10)+0.5)\nplt.grid(b=False,axis='x')\nerrorbar(b[:,::-1],x=np.arange(9,15),clr='g')\nerrorbar(d,x=np.arange(15,18),clr='r')\nplt.xlim([6,17.5])\nax.set_xticks(range(9,18))\nax.set_xticklabels(il[:6][::-1]+['OT','RC','RT'])\nfor i in range(d.shape[1]): printCI(d[:,i])\nprintCI(d[:,2]-d[:,1])", "var 0.670, CI 0.225, 1.119\nvar 1.233, CI 0.882, 1.575\nvar 1.213, CI 0.874, 1.566\nvar -0.020, CI -0.212, 0.180\n" ], [ "\nc", "_____no_output_____" ], [ "def ordinalLogitRvs(beta, c,n,size=1):\n assert np.all(np.diff(c)>0) # c must be strictly increasing\n def invLogit(x): return 1/(1+np.exp(-x))\n p=[1]+list(invLogit(beta-c))+[0]\n p=-np.diff(p)\n #return np.random.multinomial(n,p,size)\n return np.int32(np.round(p*n))\ndef reformatData(dat):\n out=[]\n for k in range(dat.size):\n out.extend([k]*dat[k])\n return np.array(out)\nb=np.linspace(-10,7,21)\nd=np.median(w['dd'][:,0])\nc=np.median(w['c'],axis=0)\nS=[];P=[]\nfor bb in b:\n S.append([np.squeeze(ordinalLogitRvs(bb,c,100)),\n np.squeeze(ordinalLogitRvs(bb+d,c,100))])\n P.append([reformatData(S[-1][0]),reformatData(S[-1][1])])", "_____no_output_____" ], [ "model='''\ndata {\n int<lower=2> K;\n int<lower=0> y1[K];\n int<lower=0> y2[K];\n}\nparameters {\n real<lower=-1000,upper=1000> d;\n ordered[K-1] c;\n}\nmodel {\nfor (k in 1:(K-1)) c[k]~ uniform(-200,200);\nfor (k in 1:K){\n for (n in 1:y1[k]) k~ ordered_logistic(0.0,c);\n for (n in 1:y2[k]) k~ ordered_logistic(d ,c);\n}}\n'''\nsm9=pystan.StanModel(model_code=model)", "_____no_output_____" ], [ "#(S[k][0]!=0).sum()+1\nfor k in range(21): \n i1=np.nonzero(S[k][0]!=0)[0]\n i2=np.nonzero(S[k][1]!=0)[0]\n if max((S[k][0]!=0).sum(),(S[k][1]!=0).sum())<9:\n s= max(min(i1[0],i2[0])-1,0)\n e= min(max(i1[-1],i2[-1])+1,10)\n S[k][0]=S[k][0][s:e+1]\n S[k][1]=S[k][1][s:e+1]", "_____no_output_____" ], [ "S[0][0].size", "_____no_output_____" ], [ "ds=[];cs=[]\nfor k in range(len(S)):\n dat = {'y1':S[k][0],'y2':S[k][1],'K':S[k][0].size}\n fit = sm9.sampling(data=dat,iter=1000, chains=4,thin=2,warmup=500,njobs=2,seed=4)\n print fit\n saveStanFit(fit,'dc%d'%k)", "Inference for Stan model: anon_model_cdc057088a7ff9c9329245d2161c83d6.\n4 chains, each with iter=1000; warmup=500; thin=2; \npost-warmup draws per chain=250, total post-warmup draws=1000.\n\n mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat\nd -451.0 25.8311.4-970.4-714.4-435.7-200.2 77.5 146.0 1.0\nc[0] 99.7 4.8 56.2 9.7 52.6100.1146.0 194.5 138.0 1.0\nlp__ 5.7 0.1 0.7 3.4 5.5 6.0 6.2 6.2 147.0 1.0\n\nSamples were drawn using NUTS(diag_e) at Sat Jun 14 21:39:48 2014.\nFor each parameter, n_eff is a crude measure of effective sample size,\nand Rhat is the potential scale reduction factor on split chains (at \nconvergence, Rhat=1).\n" ], [ "for k in range(21): \n i1=np.nonzero(S[k][0]!=0)[0]\n i2=np.nonzero(S[k][1]!=0)[0]\n if max((S[k][0]!=0).sum(),(S[k][1]!=0).sum())<9:\n s= min(i1[0],i2[0])\n e= max(i1[-1],i2[-1])\n S[k][0]=S[k][0][s:e+1]\n S[k][1]=S[k][1][s:e+1]", "_____no_output_____" ], [ "ds=[];cs=[]\nfor k in range(len(S)):\n if S[k][0].size==1: continue\n dat = {'y1':S[k][0],'y2':S[k][1],'K':S[k][0].size}\n fit = sm9.sampling(data=dat,iter=1000, chains=4,thin=2,warmup=500,njobs=2,seed=4)\n #print fit\n saveStanFit(fit,'dd%d'%k)", "Inference for Stan model: anon_model_cdc057088a7ff9c9329245d2161c83d6.\n4 chains, each with iter=1000; warmup=500; thin=2; \npost-warmup draws per chain=250, total post-warmup draws=1000.\n\n mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat\nd 0.0 0.1 1.8 -3.7 -1.0 0.1 1.2 3.4 197.0 1.0\nc[0] 5.2 0.1 1.2 3.3 4.3 5.0 6.0 8.0 181.0 1.0\nlp__ -6.1 0.1 1.1 -9.1 -6.6 -5.8 -5.3 -5.0 221.0 1.0\n\nSamples were drawn using NUTS(diag_e) at Sat Jun 14 23:06:03 2014.\nFor each parameter, n_eff is a crude measure of effective sample size,\nand Rhat is the potential scale reduction factor on split chains (at \nconvergence, Rhat=1).\n" ], [ "ds=[];xs=[]\nfor k in range(b.size):\n try:\n f=loadStanFit('dd%d'%k)['d']\n xs.append(b[k])\n ds.append(f)\n except:pass\nds=np.array(ds);xs=np.array(xs)\nds.shape", "_____no_output_____" ], [ "d1=np.median(w['dd'][:,0])\nd2=DS[DS[:,0]==1,-2].mean()-DS[DS[:,0]==0,-2].mean()\nplt.figure(figsize=(8,4))\nplt.plot([-10,5],[d1,d1],'r',alpha=0.5)\nres1=errorbar(ds.T,x=xs-0.1)\nax1=plt.gca()\nplt.ylim([-2,2])\nplt.xlim([-10,5])\nplt.grid(b=False,axis='x')\nax2 = ax1.twinx()\nres2=np.zeros((b.size,5))\nfor k in range(b.size):\n res2[k,:]=plotCIttest2(y1=P[k][0],y2=P[k][1],x=b[k]+0.1)\nplt.ylim([-2/d1*d2,2/d1*d2])\nplt.xlim([-10,5])\nplt.grid(b=False,axis='y')\nplt.plot(np.median(w['beta'],axis=0),[-0.9]*6,'ob')\nplt.plot(np.median(w['beta']+np.atleast_2d(w['dd'][:,1]).T,axis=0),[-1.1]*6,'og')", "_____no_output_____" ], [ "d1=np.median(w['dd'][:,0])\nd2=DS[DS[:,0]==1,-2].mean()-DS[DS[:,0]==0,-2].mean()\nplt.figure(figsize=(8,4))\nax1=plt.gca()\nplt.plot([-10,5],[d1,d1],'r',alpha=0.5)\ntemp=[list(xs)+list(xs)[::-1],list(res1[:,1])+list(res1[:,2])[::-1]]\nax1.add_patch(plt.Polygon(xy=np.array(temp).T,alpha=0.2,fc='k',ec='k'))\nplt.plot(xs,res1[:,0],'k')\nplt.ylim([-1.5,2])\nplt.xlim([-10,5])\nplt.grid(b=False,axis='x')\nplt.legend(['True ES','Estimate Ordinal Logit'],loc=8)\nplt.ylabel('Estimate Ordinal Logit')\nax2 = ax1.twinx()\ntemp=[list(b)+list(b)[::-1],list(res2[:,1])+list(res2[:,2])[::-1]]\nfor t in range(len(temp[0]))[::-1]:\n if np.isnan(temp[1][t]):\n temp[0].pop(t);temp[1].pop(t)\nax2.add_patch(plt.Polygon(xy=np.array(temp).T,alpha=0.2,fc='m',ec='m'))\nplt.plot(b,res2[:,0],'m')\nplt.ylim([-1.5/d1*d2,2/d1*d2])\nplt.xlim([-10,5])\nplt.grid(b=False,axis='y')\nplt.plot(np.median(w['beta'],axis=0),[-0.3]*6,'ob')\nplt.plot(np.median(w['beta']+np.atleast_2d(w['dd'][:,1]).T,axis=0),[-0.5]*6,'og')\nplt.legend(['Estimate T-C','Item Difficulty Orignal Study','Item Difficulty Replication'],loc=4)\nplt.ylabel('Estimate T - C',color='m')\nfor tl in ax2.get_yticklabels():tl.set_color('m')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d00e56cda28e7500114e1f5d94a8babfba988fcc
119,050
ipynb
Jupyter Notebook
Hackerearth-Predict_condition_and_insurance_amount/train_models.ipynb
chiranjeet14/ML_Projects
6347348b0d7b3a4dbf3e07ece20a7ff39b6bf85d
[ "MIT" ]
null
null
null
Hackerearth-Predict_condition_and_insurance_amount/train_models.ipynb
chiranjeet14/ML_Projects
6347348b0d7b3a4dbf3e07ece20a7ff39b6bf85d
[ "MIT" ]
null
null
null
Hackerearth-Predict_condition_and_insurance_amount/train_models.ipynb
chiranjeet14/ML_Projects
6347348b0d7b3a4dbf3e07ece20a7ff39b6bf85d
[ "MIT" ]
null
null
null
39.802742
5,682
0.370995
[ [ [ "<a href=\"https://colab.research.google.com/github/chiranjeet14/ML_Journey/blob/master/Hackerearth-Predict_condition_and_insurance_amount/train_models.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!pip3 install xgboost > /dev/null", "_____no_output_____" ], [ "import pandas as pd\nimport numpy as np\nimport io\nimport gc\nimport time\nfrom pprint import pprint\n# import PIL.Image as Image\n# import matplotlib.pylab as plt\nfrom datetime import date\n\n# import tensorflow as tf\n# import tensorflow_hub as hub\n\n# settings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ngc.enable()", "_____no_output_____" ], [ "# Calculating Precision, Recall and f1-score\ndef model_score(actual_value,predicted_values):\n from sklearn.metrics import confusion_matrix \n from sklearn.metrics import accuracy_score \n from sklearn.metrics import classification_report \n from sklearn.metrics import recall_score\n \n actual = actual_value\n predicted = predicted_values\n results = confusion_matrix(actual, predicted) \n \n print('Confusion Matrix :')\n print(results) \n print('Accuracy Score :',accuracy_score(actual, predicted))\n print('Report : ')\n print(classification_report(actual, predicted))\n print('Recall Score : ')\n print(recall_score(actual, predicted))", "_____no_output_____" ], [ "# connect to google drive\nfrom google.colab import drive\ndrive.mount('/content/drive')", "Mounted at /content/drive\n" ], [ "gDrivePath = '/content/drive/MyDrive/Datasets/Hackerearth_vehicle_insurance_claim/dataset/'\ngDriveTrainFinal = gDrivePath + 'final_datasets/train_final.csv'\ngDriveTestFinal = gDrivePath + 'final_datasets/test_final.csv'", "_____no_output_____" ], [ "df_train = pd.read_csv(gDriveTrainFinal)\ndf_test = pd.read_csv(gDriveTestFinal)", "_____no_output_____" ], [ "df_train.head()", "_____no_output_____" ], [ "df_train.sample(n = 10)", "_____no_output_____" ], [ "df_train.drop(['image_name'], axis=1, inplace=True)\ndf_test.drop(['image_name'], axis=1, inplace=True)", "_____no_output_____" ], [ "df_train[['Insurance_company', 'Cost_of_vehicle', 'Min_coverage', 'Max_coverage', 'Condition', 'Amount']].isna().any()", "_____no_output_____" ] ], [ [ "### Removing NaN in target variable", "_____no_output_____" ] ], [ [ "# select rows where amount is not NaN\ndf_train = df_train[df_train['Amount'].notna()]\ndf_train[df_train['Amount'].isna()].shape", "_____no_output_____" ], [ "# delete rows where Amount < 0\ndf_train = df_train[df_train['Amount'] >= 0]\ndf_train[['Cost_of_vehicle', 'Min_coverage', 'Max_coverage', 'Amount']].describe()", "_____no_output_____" ], [ "selected_columns = ['Cost_of_vehicle', 'Min_coverage', 'Max_coverage']\n\n# replacing nan values with median\nfrom sklearn.impute import SimpleImputer \nimputer = SimpleImputer(missing_values = np.nan, strategy ='median') \nimputer = imputer.fit(df_train[selected_columns]) \n\n# Imputing the data \ndf_train[selected_columns] = imputer.transform(df_train[selected_columns])\ndf_test[selected_columns] = imputer.transform(df_test[selected_columns])", "_____no_output_____" ], [ "df_train[['Insurance_company', 'Cost_of_vehicle', 'Min_coverage', 'Max_coverage', 'Condition', 'Amount']].isna().any()", "_____no_output_____" ] ], [ [ "### Checking if the dataset is balanced/imbalanced - Condition", "_____no_output_____" ] ], [ [ "# python check if dataset is imbalanced : https://www.kaggle.com/rafjaa/resampling-strategies-for-imbalanced-datasets\n\ntarget_count = df_train['Condition'].value_counts()\nprint('Class 0 (No):', target_count[0])\nprint('Class 1 (Yes):', target_count[1])\nprint('Proportion:', round(target_count[0] / target_count[1], 2), ': 1')\n\ntarget_count.plot(kind='bar', title='Condition')", "Class 0 (No): 99\nClass 1 (Yes): 1288\nProportion: 0.08 : 1\n" ] ], [ [ "### Splitting Data into train-cv", "_____no_output_____" ] ], [ [ "classification_labels = df_train['Condition'].values\n\n# for regresion delete rows where Condition = 0\ndf_train_regression = df_train[df_train['Condition'] == 1]\nregression_labels = df_train_regression['Amount'].values\n######\n\ndf_train_regression.drop(['Condition','Amount'], axis=1, inplace=True)\n\ndf_train.drop(['Condition','Amount'], axis=1, inplace=True)\ndf_test.drop(['Condition','Amount'], axis=1, inplace=True, errors='ignore')", "_____no_output_____" ], [ "# classification split\nfrom sklearn.model_selection import train_test_split\nX_train, X_cv, y_train, y_cv = train_test_split(df_train, classification_labels, test_size=0.1)", "_____no_output_____" ] ], [ [ "### Over Sampling using SMOTE\n", "_____no_output_____" ] ], [ [ "# https://machinelearningmastery.com/smote-oversampling-for-imbalanced-classification/\nfrom imblearn.over_sampling import SMOTE\nsmote_overSampling = SMOTE()\nX_train,y_train = smote_overSampling.fit_resample(X_train,y_train)\nunique, counts = np.unique(y_train, return_counts=True)\ndict(zip(unique, counts))", "_____no_output_____" ] ], [ [ "### Scaling data", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_train_scaled = scaler.fit_transform(X_train)\nX_cv_scaled = scaler.transform(X_cv)\n\nX_test_scaled = scaler.transform(df_test)\nX_train_scaled", "_____no_output_____" ] ], [ [ "## Modelling & Cross-Validation", "_____no_output_____" ], [ "### Classification", "_____no_output_____" ] ], [ [ "%%time\n# Train multiple models : https://www.kaggle.com/tflare/testing-multiple-models-with-scikit-learn-0-79425\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.linear_model import LogisticRegressionCV\nfrom xgboost import XGBClassifier\n\nfrom sklearn.model_selection import cross_val_score\n\nmodels = []\n\nLogisticRegression = LogisticRegression(n_jobs=-1)\nLinearSVC = LinearSVC()\nKNeighbors = KNeighborsClassifier(n_jobs=-1)\nDecisionTree = DecisionTreeClassifier()\nRandomForest = RandomForestClassifier()\nAdaBoost = AdaBoostClassifier()\nBagging = BaggingClassifier()\nExtraTrees = ExtraTreesClassifier()\nGradientBoosting = GradientBoostingClassifier()\nLogisticRegressionCV = LogisticRegressionCV(n_jobs=-1)\nXGBClassifier = XGBClassifier(nthread=-1)\n\n# models.append((\"LogisticRegression\",LogisticRegression))\n# models.append((\"LinearSVC\", LinearSVC))\n# models.append((\"KNeighbors\", KNeighbors))\n# models.append((\"DecisionTree\", DecisionTree))\n# models.append((\"RandomForest\", RandomForest))\nmodels.append((\"AdaBoost\", AdaBoost))\n# models.append((\"Bagging\", Bagging))\n# models.append((\"ExtraTrees\", ExtraTrees))\n# models.append((\"GradientBoosting\", GradientBoosting))\n# models.append((\"LogisticRegressionCV\", LogisticRegressionCV))\n# models.append((\"XGBClassifier\", XGBClassifier))\n\n# metric_names = ['f1', 'average_precision', 'accuracy', 'precision', 'recall']\nmetric_names = ['f1']\nresults = []\nnames = []\n\nnested_dict = {}\n\nfor name,model in models:\n nested_dict[name] = {}\n for metric in metric_names:\n print(\"\\nRunning : {}, with metric : {}\".format(name, metric))\n score = cross_val_score(model, X_train_scaled, y_train, n_jobs=-1, scoring=metric, cv=5)\n nested_dict[name][metric] = score.mean()", "\nRunning : AdaBoost, with metric : f1\nCPU times: user 399 ms, sys: 150 ms, total: 548 ms\nWall time: 1min 13s\n" ], [ "import json\nprint(json.dumps(nested_dict, sort_keys=True, indent=4))", "{\n \"AdaBoost\": {\n \"f1\": 0.9991397849462367\n }\n}\n" ] ], [ [ "### Regression", "_____no_output_____" ] ], [ [ "X_train_regression, X_cv_regression, y_train_regression, y_cv_regression = train_test_split(df_train_regression, regression_labels, test_size=0.1)\n\nscaler = StandardScaler()\nX_train_scaled_regression = scaler.fit_transform(X_train_regression)\nX_cv_scaled_regression = scaler.transform(X_cv_regression)\n\nX_test_scaled_regression = scaler.transform(df_test)\nX_train_scaled_regression", "_____no_output_____" ], [ "%%time\nfrom sklearn.linear_model import LinearRegression, SGDRegressor\nfrom sklearn.svm import SVR, LinearSVR\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.ensemble import BaggingRegressor\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom xgboost import XGBClassifier\n\nfrom sklearn.model_selection import cross_val_score\n\nmodels = []\n\nLinearReg = LinearRegression(n_jobs=-1)\nSGDReg = SGDRegressor()\nSVReg = SVR()\nLinearSVReg = LinearSVR()\nKNeighborsReg = KNeighborsRegressor(n_jobs=-1)\nDecisionTreeReg = DecisionTreeRegressor()\nRandomForestReg = RandomForestRegressor(n_jobs=-1)\nAdaBoostReg = AdaBoostRegressor()\nBaggingReg = BaggingRegressor(n_jobs=-1)\nExtraTreesReg = ExtraTreesRegressor(n_jobs=-1)\nGradientBoostingReg = GradientBoostingRegressor()\n# XGBReg = XGBRegressor(nthread=-1)\n\n# models.append((\"LinearRegression\",LinearReg))\n# models.append((\"SGDRegressor\",SGDReg))\n# models.append((\"SVR\", SVReg))\n# models.append((\"LinearSVR\", LinearSVReg))\n# models.append((\"KNeighborsRegressor\", KNeighborsReg))\n# models.append((\"DecisionTreeRegressor\", DecisionTreeReg))\n# models.append((\"RandomForestRegressor\", RandomForestReg))\n# models.append((\"AdaBoostRegressor\", AdaBoostReg))\n# models.append((\"BaggingRegressor\", BaggingReg))\nmodels.append((\"ExtraTreesRegressor\", ExtraTreesReg))\n# models.append((\"GradientBoostingRegressor\", GradientBoostingReg))\n# models.append((\"XGBReg\", XGBRegressor))\n\n# metric_names = ['f1', 'average_precision', 'accuracy', 'precision', 'recall']\nmetric_names = ['r2']\nresults = []\nnames = []\n\nnested_dict = {}\n\n# for name,model in models:\n# nested_dict[name] = {}\n# for metric in metric_names:\n# print(\"\\nRunning : {}, with metric : {}\".format(name, metric))\n# score = cross_val_score(model, X_train_scaled_regression, y_train_regression, n_jobs=-1, scoring=metric, cv=5)\n# nested_dict[name][metric] = score.mean()", "CPU times: user 426 µs, sys: 0 ns, total: 426 µs\nWall time: 434 µs\n" ], [ "# import json\n# print(json.dumps(nested_dict, sort_keys=True, indent=4))", "_____no_output_____" ], [ "# # Hyperparameter tuning ExtraTreesRegressor\n\n# # ExtraTreesRegressor(bootstrap=True, criterion='mae',n_estimators=100, warm_start=True,\n\n# # max_depth=None, max_features='auto', max_leaf_nodes=None,\n# # max_samples=None, min_impurity_decrease=0.0,\n# # min_impurity_split=None, min_samples_leaf=1,\n# # min_samples_split=2, min_weight_fraction_leaf=0.0,\n# # n_jobs=-1, oob_score=False,\n# # random_state=None, verbose=0)\n\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n\nmodel = ExtraTreesRegressor(n_jobs=-1, bootstrap=True, criterion='mae', warm_start=True, max_depth=9, max_features='auto')\n\nparam_grid = {\n # 'n_estimators': np.arange(100, 3000, 100, dtype=int),\n # 'criterion': ['mse', 'mae'],\n # 'max_depth': np.arange(5, 16, 1, dtype=int),\n # 'bootstrap': [True, False],\n # 'max_features': ['auto', 'sqrt', 'log2'],\n # 'max_features': np.arange(100, 1540, 20, dtype=int),\n # 'warm_start': [True, False],\n}\n \ngsc = GridSearchCV(estimator=model, param_grid=param_grid, scoring='r2', cv=5, n_jobs=-1, verbose=1000)\ngrid_result = gsc.fit(X_train_scaled_regression, y_train_regression)\n\n# n_iter_search = 100\n# random_search = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=n_iter_search, scoring='r2', cv=3, n_jobs=-1, verbose=500)\n# random_search.fit(X_train, y_train)", "Fitting 5 folds for each of 1 candidates, totalling 5 fits\n[Parallel(n_jobs=-1)]: Using backend LokyBackend with 2 concurrent workers.\n[Parallel(n_jobs=-1)]: Done 1 tasks | elapsed: 8.9min\n[Parallel(n_jobs=-1)]: Done 2 tasks | elapsed: 9.0min\n[Parallel(n_jobs=-1)]: Done 3 out of 5 | elapsed: 17.5min remaining: 11.7min\n[Parallel(n_jobs=-1)]: Done 5 out of 5 | elapsed: 22.3min remaining: 0.0s\n[Parallel(n_jobs=-1)]: Done 5 out of 5 | elapsed: 22.3min finished\n" ], [ "print(\"Best: %f using %s\" % (grid_result.best_score_, grid_result.best_params_))", "Best: 0.062463 using {}\n" ] ], [ [ "### Predicting on CV data", "_____no_output_____" ] ], [ [ "classification_alg = AdaBoost\n# regression_alg = ExtraTreesReg\n\n# hypertuned model\nregression_alg = gsc\n\nclassification_alg.fit(X_train_scaled, y_train)\nregression_alg.fit(X_train_scaled_regression, y_train_regression)\n\n\n# predictions_class = classification_alg.predict(X_cv)\n# pprint(classification_alg.get_params())", "Fitting 5 folds for each of 1 candidates, totalling 5 fits\n[Parallel(n_jobs=-1)]: Using backend LokyBackend with 2 concurrent workers.\n[Parallel(n_jobs=-1)]: Done 1 tasks | elapsed: 9.0min\n[Parallel(n_jobs=-1)]: Done 2 tasks | elapsed: 9.1min\n[Parallel(n_jobs=-1)]: Done 3 out of 5 | elapsed: 17.5min remaining: 11.7min\n[Parallel(n_jobs=-1)]: Done 5 out of 5 | elapsed: 22.4min remaining: 0.0s\n[Parallel(n_jobs=-1)]: Done 5 out of 5 | elapsed: 22.4min finished\n" ], [ "# model_score(y_cv,predictions)", "_____no_output_____" ] ], [ [ "### Predicting on test Data", "_____no_output_____" ] ], [ [ "trained_classifier = classification_alg\ntrained_regressor = regression_alg\n\npredictions_trained_classifier_test = trained_classifier.predict(X_test_scaled)\npredictions_trained_regressor_test = trained_regressor.predict(X_test_scaled_regression)", "_____no_output_____" ], [ "read = pd.read_csv(gDrivePath + 'test.csv')\nsubmission = pd.DataFrame({\n \"Image_path\": read[\"Image_path\"],\n \"Condition\": predictions_trained_classifier_test,\n \"Amount\": predictions_trained_regressor_test\n })", "_____no_output_____" ], [ "submission.head()", "_____no_output_____" ], [ "submission['Amount'][submission.Condition == 0] = 0", "_____no_output_____" ], [ "submission[submission['Condition'] == 0].sample(n = 10)", "_____no_output_____" ], [ "submission.Amount = submission.Amount.round()\nsubmission.head()", "_____no_output_____" ], [ "submission.to_csv('./submission.csv', index=False)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
d00e598776ad6e007c754034eb81a3fe6a5e86ee
690,476
ipynb
Jupyter Notebook
traffic_sign_classifier_LeNet_enhanced_trainingdataset_HLS.ipynb
nguyenrobot/Traffic-Sign-Recognition-with-Keras-Tensorflow
327e567304f3c3da4d541ef53af4c837ffb3dbc9
[ "MIT" ]
2
2020-12-14T01:27:48.000Z
2021-01-26T03:34:38.000Z
traffic_sign_classifier_LeNet_enhanced_trainingdataset_HLS.ipynb
nguyenrobot/Traffic-Sign-Recognition-with-Keras-Tensorflow
327e567304f3c3da4d541ef53af4c837ffb3dbc9
[ "MIT" ]
1
2022-01-09T11:31:08.000Z
2022-01-09T11:31:08.000Z
traffic_sign_classifier_LeNet_enhanced_trainingdataset_HLS.ipynb
v-thiennp12/Traffic-Sign-Recognition-with-Keras-Tensorflow
327e567304f3c3da4d541ef53af4c837ffb3dbc9
[ "MIT" ]
1
2021-03-30T18:29:45.000Z
2021-03-30T18:29:45.000Z
397.968876
157,008
0.929776
[ [ [ "# Build a Traffic Sign Recognition Classifier Deep Learning", "_____no_output_____" ], [ "Some improvements are taken :\n- [x] Adding of convolution networks at the same size of previous layer, to get 1x1 layer\n- [x] Activation function use 'ReLU' instead of 'tanh'\n- [x] Adaptative learning rate, so learning rate is decayed along to training phase\n- [x] Enhanced training dataset", "_____no_output_____" ], [ "## Load and Visualize the Enhanced training dataset\n\nFrom the original standard German Traffic Signs dataset, we add some 'generalized' sign to cover cases that the classifier can not well interpret small figures inside. \n`Also`, in our Enhanced training dataset, each figure is taken from standard library - not from road images, so they are very clear and in high-definition.", "_____no_output_____" ], [ "*Enhanced traffic signs &#8595;* \n<img src=\"figures/enhanced_training_dataset_text.png\" alt=\"Drawing\" style=\"width: 600px;\"/>", "_____no_output_____" ] ], [ [ "# load enhanced traffic signs\nimport os\nimport cv2\nimport matplotlib.pyplot as plot\nimport numpy\ndir_enhancedsign = 'figures\\enhanced_training_dataset2'\nfiles_enhancedsign = [os.path.join(dir_enhancedsign, f) for f in os.listdir(dir_enhancedsign)]\n\n# read & resize (32,32) images in enhanced dataset\nimages_enhancedsign = numpy.array([cv2.cvtColor(cv2.resize(cv2.imread(f), (32,32), interpolation = cv2.INTER_AREA), cv2.COLOR_BGR2RGB) for f in files_enhancedsign])\n\n# plot new test images\nfig, axes = plot.subplots(7, 8)\nplot.suptitle('Enhanced training dataset')\nfor i, ax in enumerate(axes.ravel()):\n if i < 50:\n ax.imshow(images_enhancedsign[i])\n# ax.set_title('{}'.format(i))\n plot.setp(ax.get_xticklabels(), visible=False)\n plot.setp(ax.get_yticklabels(), visible=False)\n ax.set_xticks([]), ax.set_yticks([])\n \n ax.axis('off')\nplot.draw()\nfig.savefig('figures/' + 'enhancedsign' + '.jpg', dpi=700)\n\nprint(\"Image Shape : {}\".format(images_enhancedsign[0].shape))\nprint()\nprint(\"Enhanced Training Dataset : {} samples\".format(len(images_enhancedsign)))", "Image Shape : (32, 32, 3)\n\nEnhanced Training Dataset : 50 samples\n" ], [ "# classes of enhanced dataset are taken from their filenames\nimport re\nregex = re.compile(r'\\d+')\n\ny_enhancedsign = [int(regex.findall(f)[0]) for f in os.listdir(dir_enhancedsign)]\nprint(y_enhancedsign)", "[0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 4, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 6, 7, 8, 9]\n" ] ], [ [ "*Enhanced German traffic signs dataset &#8595;* \n<img src=\"figures/enhanced_training_dataset.png\" alt=\"Drawing\" style=\"width: 600px;\"/>", "_____no_output_____" ], [ "**We would have 50 classes in total with new enhanced training dataset :**", "_____no_output_____" ] ], [ [ "n_classes_enhanced = len(numpy.unique(y_enhancedsign))\n\nprint('n_classes enhanced : {}'.format(n_classes_enhanced))", "n_classes enhanced : 50\n" ] ], [ [ "## Load and Visualize the standard German Traffic Signs Dataset", "_____no_output_____" ] ], [ [ "# Load pickled data\nimport pickle\nimport numpy\n\n# TODO: Fill this in based on where you saved the training and testing data\n\ntraining_file = 'traffic-signs-data/train.p'\nvalidation_file = 'traffic-signs-data/valid.p'\ntesting_file = 'traffic-signs-data/test.p'\n\nwith open(training_file, mode='rb') as f:\n train = pickle.load(f)\nwith open(validation_file, mode='rb') as f:\n valid = pickle.load(f)\nwith open(testing_file, mode='rb') as f:\n test = pickle.load(f)\n \nX_train, y_train = train['features'], train['labels'] # training dataset\nX_valid, y_valid = valid['features'], valid['labels'] # validation dataset used in training phase\nX_test, y_test = test['features'], test['labels'] # test dataset\nn_classes_standard = len(numpy.unique(y_train))\n\nassert(len(X_train) == len(y_train))\nassert(len(X_valid) == len(y_valid))\nassert(len(X_test) == len(y_test))\nprint(\"Image Shape : {}\".format(X_train[0].shape))\nprint()\nprint(\"Training Set : {} samples\".format(len(X_train)))\nprint(\"Validation Set : {} samples\".format(len(X_valid)))\nprint(\"Test Set : {} samples\".format(len(X_test)))\nprint('n_classes standard : {}'.format(n_classes_standard))", "Image Shape : (32, 32, 3)\n\nTraining Set : 34799 samples\nValidation Set : 4410 samples\nTest Set : 12630 samples\nn_classes standard : 43\n" ], [ "n_classes = n_classes_enhanced", "_____no_output_____" ] ], [ [ "## Implementation of LeNet\n\n>http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf \nAbove is the original article of Pierre Sermanet and Yann LeCun in 1998 that we can follow to create LeNet convolutional networks with a good accuracy even for very-beginners in deep-learning. \nIt's really excited to see that many years of works now could be implemented in just 9 lines of code thank to Keras high-level API !\n(low-level API implementation with Tensorflow 1 is roughly 20 lines of code) \n\n>Here is also an interesting medium article : \nhttps://medium.com/@mgazar/lenet-5-in-9-lines-of-code-using-keras-ac99294c8086 ", "_____no_output_____" ] ], [ [ "### Import tensorflow and keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\nprint (\"TensorFlow version: \" + tf.__version__)", "TensorFlow version: 2.1.0\n" ] ], [ [ "### 2-stage ConvNet architecture by Pierre Sermanet and Yann LeCun\n\nWe will try to implement the 2-stage ConvNet architecture by Pierre Sermanet and Yann LeCun which is not sequential. \n\nKeras disposes keras.Sequential() API for sequential architectures but it can not handle models with non-linear topology, shared layers or multi-in/output. So the choose of the 2-stage ConvNet architecture by `Pierre Sermanet` and `Yann LeCun` is to challenge us also.\n\n<img src=\"figures/lenet_2.png\" alt=\"Drawing\" style=\"width: 550px;\"/>\n\n>Source: \"Traffic Sign Recognition with Multi-Scale Convolutional Networks\" by `Pierre Sermanet` and `Yann LeCun`\n\nHere in this architecture, the 1st stage's ouput is feed-forward to the classifier (could be considered as a 3rd stage).", "_____no_output_____" ] ], [ [ "#LeNet model\ninputs = keras.Input(shape=(32,32,3), name='image_in')\n\n#0 stage :conversion from normalized RGB [0..1] to HSV\nlayer_HSV = tf.image.rgb_to_hsv(inputs)\n\n#1st stage ___________________________________________________________\n#Convolution with ReLU activation\nlayer1_conv = keras.layers.Conv2D(256, kernel_size=(5,5), strides=1, activation='relu', padding='valid')(layer_HSV)\n#Average Pooling\nlayer1_maxpool = keras.layers.MaxPooling2D(pool_size=(2,2), strides=2, padding='valid')(layer1_conv)\n#Conv 1x1\nlayer1_conv1x1 = keras.layers.Conv2D(256, kernel_size=(14,14), strides=1, activation='relu', padding='valid')(layer1_maxpool)\n\n#2nd stage ___________________________________________________________\n#Convolution with ReLU activation\nlayer2_conv = keras.layers.Conv2D(64, kernel_size=(5,5), strides=1, activation='relu', padding='valid')(layer1_maxpool)\n#MaxPooling 2D\nlayer2_maxpool = keras.layers.MaxPooling2D(pool_size=(2,2), strides=2, padding='valid')(layer2_conv)\n#Conv 1x1\nlayer2_conv1x1 = keras.layers.Conv2D(512, kernel_size=(5,5), strides=1, activation='relu', padding='valid')(layer2_maxpool)\n\n#3rd stage | Classifier ______________________________________________\n#Concate\nlayer3_flatten_1 = keras.layers.Flatten()(layer1_conv1x1)\nlayer3_flatten_2 = keras.layers.Flatten()(layer2_conv1x1)\nlayer3_concat = keras.layers.Concatenate()([layer3_flatten_1, layer3_flatten_2])\n\n#Dense (fully-connected)\nlayer3_dense_1 = keras.layers.Dense(units=129, activation='relu', kernel_initializer=\"he_normal\")(layer3_concat)\n# layer3_dense_2 = keras.layers.Dense(units=129, activation='relu', kernel_initializer=\"he_normal\")(layer3_dense_1)\n#Dense (fully-connected) | logits for 43 categories (n_classes)\noutputs = keras.layers.Dense(units=n_classes)(layer3_dense_1)\n\nLeNet_Model = keras.Model(inputs, outputs, name=\"LeNet_Model_improved\")", "_____no_output_____" ], [ "#Plot model architecture\nLeNet_Model.summary()\nkeras.utils.plot_model(LeNet_Model, \"figures/LeNet_improved_HLS.png\", show_shapes=True)", "Model: \"LeNet_Model_improved\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\nimage_in (InputLayer) [(None, 32, 32, 3)] 0 \n__________________________________________________________________________________________________\ntf_op_layer_RGBToHSV (TensorFlo [(None, 32, 32, 3)] 0 image_in[0][0] \n__________________________________________________________________________________________________\nconv2d (Conv2D) (None, 28, 28, 256) 19456 tf_op_layer_RGBToHSV[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 14, 14, 256) 0 conv2d[0][0] \n__________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 10, 10, 64) 409664 max_pooling2d[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 5, 5, 64) 0 conv2d_2[0][0] \n__________________________________________________________________________________________________\nconv2d_1 (Conv2D) (None, 1, 1, 256) 12845312 max_pooling2d[0][0] \n__________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 1, 1, 512) 819712 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nflatten (Flatten) (None, 256) 0 conv2d_1[0][0] \n__________________________________________________________________________________________________\nflatten_1 (Flatten) (None, 512) 0 conv2d_3[0][0] \n__________________________________________________________________________________________________\nconcatenate (Concatenate) (None, 768) 0 flatten[0][0] \n flatten_1[0][0] \n__________________________________________________________________________________________________\ndense (Dense) (None, 129) 99201 concatenate[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 50) 6500 dense[0][0] \n==================================================================================================\nTotal params: 14,199,845\nTrainable params: 14,199,845\nNon-trainable params: 0\n__________________________________________________________________________________________________\n" ] ], [ [ "### Input preprocessing\n\n#### Color-Space\nPierre Sermanet and Yann LeCun used YUV color space with almost of processings on Y-channel (Y stands for brightness, U and V stand for Chrominance). \n\n#### Normalization\nEach channel of an image is in uint8 scale (0-255), we will normalize each channel to 0-1. \nGenerally, we normalize data to get them center around -1 and 1, to prevent numrical errors due to many steps of matrix operation. Imagine that we have 255x255x255x255xk operation, it could give a huge numerical error if we just have a small error in k. ", "_____no_output_____" ] ], [ [ "import cv2\ndef input_normalization(X_in):\n X = numpy.float32(X_in/255.0) \n return X", "_____no_output_____" ], [ "# normalization of dataset\n# enhanced training dataset is added\nX_train_norm = input_normalization(X_train)\nX_valid_norm = input_normalization(X_valid)\nX_enhancedtrain_norm = input_normalization(images_enhancedsign)\n\n# one-hot matrix\ny_train_onehot = keras.utils.to_categorical(y_train, n_classes)\ny_valid_onehot = keras.utils.to_categorical(y_valid, n_classes)\ny_enhanced_onehot = keras.utils.to_categorical(y_enhancedsign, n_classes)", "_____no_output_____" ], [ "print(X_train_norm.shape)\nprint('{0:.4g}'.format(numpy.max(X_train_norm)))\nprint('{0:.3g}'.format(numpy.min(X_train_norm)))", "(34799, 32, 32, 3)\n1\n0\n" ], [ "print(X_enhancedtrain_norm.shape)\nprint('{0:.4g}'.format(numpy.max(X_enhancedtrain_norm)))\nprint('{0:.3g}'.format(numpy.min(X_enhancedtrain_norm)))", "(50, 32, 32, 3)\n1\n0\n" ] ], [ [ "### Training Pipeline\n_Optimizer : we use Adam optimizer, better than SDG (Stochastic Gradient Descent) \n_Loss function : Cross Entropy by category \n_Metrics : accuracy \n*learning rate 0.001 work well with our network, it's better to try with small laerning rate in the begining.", "_____no_output_____" ] ], [ [ "rate = 0.001\n\nLeNet_Model.compile(\n optimizer=keras.optimizers.Nadam(learning_rate = rate, beta_1=0.9, beta_2=0.999, epsilon=1e-07),\n loss=keras.losses.CategoricalCrossentropy(from_logits=True),\n metrics=[\"accuracy\"])", "_____no_output_____" ] ], [ [ "### Real-time data augmentation", "_____no_output_____" ] ], [ [ "from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndatagen_enhanced = ImageDataGenerator(\n rotation_range=30.0,\n zoom_range=0.5,\n width_shift_range=0.5,\n height_shift_range=0.5,\n featurewise_center=True,\n featurewise_std_normalization=True,\n horizontal_flip=False)\n\ndatagen_enhanced.fit(X_enhancedtrain_norm)", "_____no_output_____" ], [ "from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndatagen = ImageDataGenerator(\n rotation_range=15.0,\n zoom_range=0.2,\n width_shift_range=0.1,\n height_shift_range=0.1,\n featurewise_center=False,\n featurewise_std_normalization=False,\n horizontal_flip=False)\n\ndatagen.fit(X_train_norm)", "_____no_output_____" ] ], [ [ "### Train the Model", "_____no_output_____" ], [ "###### on standard training dataset", "_____no_output_____" ] ], [ [ "EPOCHS = 30\nBATCH_SIZE = 32\nSTEPS_PER_EPOCH = int(len(X_train_norm)/BATCH_SIZE)\n\nhistory_standard_HLS = LeNet_Model.fit(\n datagen.flow(X_train_norm, y_train_onehot, batch_size=BATCH_SIZE,shuffle=True),\n validation_data=(X_valid_norm, y_valid_onehot),\n shuffle=True,\n steps_per_epoch=STEPS_PER_EPOCH,\n epochs=EPOCHS)", "WARNING:tensorflow:sample_weight modes were coerced from\n ...\n to \n ['...']\nTrain for 1087 steps, validate on 4410 samples\nEpoch 1/30\n1087/1087 [==============================] - 310s 285ms/step - loss: 1.5436 - accuracy: 0.5221 - val_loss: 1.1918 - val_accuracy: 0.6120\nEpoch 2/30\n1087/1087 [==============================] - 305s 281ms/step - loss: 0.5978 - accuracy: 0.7973 - val_loss: 0.8420 - val_accuracy: 0.7415\nEpoch 3/30\n1087/1087 [==============================] - 304s 279ms/step - loss: 0.3351 - accuracy: 0.8877 - val_loss: 0.8672 - val_accuracy: 0.7873\nEpoch 4/30\n1087/1087 [==============================] - 304s 279ms/step - loss: 0.2341 - accuracy: 0.9236 - val_loss: 0.7044 - val_accuracy: 0.8091\nEpoch 5/30\n1087/1087 [==============================] - 304s 279ms/step - loss: 0.1861 - accuracy: 0.9395 - val_loss: 0.6862 - val_accuracy: 0.8245\nEpoch 6/30\n1087/1087 [==============================] - 304s 279ms/step - loss: 0.1643 - accuracy: 0.9459 - val_loss: 0.6359 - val_accuracy: 0.8508\nEpoch 7/30\n1087/1087 [==============================] - 308s 284ms/step - loss: 0.1401 - accuracy: 0.9541 - val_loss: 0.7359 - val_accuracy: 0.8365\nEpoch 8/30\n1087/1087 [==============================] - 316s 290ms/step - loss: 0.1286 - accuracy: 0.9591 - val_loss: 0.7600 - val_accuracy: 0.8488\nEpoch 9/30\n1087/1087 [==============================] - 307s 282ms/step - loss: 0.1214 - accuracy: 0.9617 - val_loss: 0.8064 - val_accuracy: 0.8442\nEpoch 10/30\n1087/1087 [==============================] - 306s 282ms/step - loss: 0.1143 - accuracy: 0.9632 - val_loss: 0.7421 - val_accuracy: 0.8528\nEpoch 11/30\n1087/1087 [==============================] - 306s 281ms/step - loss: 0.1024 - accuracy: 0.9677 - val_loss: 0.7401 - val_accuracy: 0.8676\nEpoch 12/30\n1087/1087 [==============================] - 305s 281ms/step - loss: 0.0954 - accuracy: 0.9702 - val_loss: 0.6620 - val_accuracy: 0.8762\nEpoch 13/30\n1087/1087 [==============================] - 306s 281ms/step - loss: 0.1052 - accuracy: 0.9678 - val_loss: 0.7756 - val_accuracy: 0.8617\nEpoch 14/30\n1087/1087 [==============================] - 307s 282ms/step - loss: 0.0925 - accuracy: 0.9714 - val_loss: 0.6852 - val_accuracy: 0.8624\nEpoch 15/30\n1087/1087 [==============================] - 312s 287ms/step - loss: 0.0891 - accuracy: 0.9716 - val_loss: 0.9627 - val_accuracy: 0.8481\nEpoch 16/30\n1087/1087 [==============================] - 310s 285ms/step - loss: 0.0932 - accuracy: 0.9721 - val_loss: 0.7544 - val_accuracy: 0.8637\nEpoch 17/30\n1087/1087 [==============================] - 310s 285ms/step - loss: 0.0862 - accuracy: 0.9751 - val_loss: 0.6120 - val_accuracy: 0.8789\nEpoch 18/30\n1087/1087 [==============================] - 306s 281ms/step - loss: 0.0776 - accuracy: 0.9765 - val_loss: 0.8133 - val_accuracy: 0.8442\nEpoch 19/30\n1087/1087 [==============================] - 305s 280ms/step - loss: 0.0774 - accuracy: 0.9771 - val_loss: 0.6836 - val_accuracy: 0.8807\nEpoch 20/30\n1087/1087 [==============================] - 304s 280ms/step - loss: 0.0822 - accuracy: 0.9755 - val_loss: 0.8578 - val_accuracy: 0.8689\nEpoch 21/30\n1087/1087 [==============================] - 303s 279ms/step - loss: 0.0810 - accuracy: 0.9757 - val_loss: 0.7974 - val_accuracy: 0.8785\nEpoch 22/30\n1087/1087 [==============================] - 303s 279ms/step - loss: 0.0689 - accuracy: 0.9792 - val_loss: 0.8230 - val_accuracy: 0.8522\nEpoch 23/30\n1087/1087 [==============================] - 305s 280ms/step - loss: 0.0785 - accuracy: 0.9757 - val_loss: 0.6689 - val_accuracy: 0.8916\nEpoch 24/30\n1087/1087 [==============================] - 304s 280ms/step - loss: 0.0722 - accuracy: 0.9783 - val_loss: 0.9752 - val_accuracy: 0.8628\nEpoch 25/30\n1087/1087 [==============================] - 303s 279ms/step - loss: 0.0693 - accuracy: 0.9793 - val_loss: 1.0134 - val_accuracy: 0.8583\nEpoch 26/30\n1087/1087 [==============================] - 304s 279ms/step - loss: 0.0753 - accuracy: 0.9786 - val_loss: 0.6858 - val_accuracy: 0.8943\nEpoch 27/30\n1087/1087 [==============================] - 304s 280ms/step - loss: 0.0661 - accuracy: 0.9811 - val_loss: 1.0159 - val_accuracy: 0.8762\nEpoch 28/30\n1087/1087 [==============================] - 303s 279ms/step - loss: 0.0700 - accuracy: 0.9795 - val_loss: 1.0779 - val_accuracy: 0.8639\nEpoch 29/30\n1087/1087 [==============================] - 303s 279ms/step - loss: 0.0731 - accuracy: 0.9785 - val_loss: 0.8449 - val_accuracy: 0.8796\nEpoch 30/30\n1087/1087 [==============================] - 303s 279ms/step - loss: 0.0627 - accuracy: 0.9823 - val_loss: 1.0047 - val_accuracy: 0.8710\n" ] ], [ [ "###### on enhanced training dataset", "_____no_output_____" ] ], [ [ "EPOCHS = 30\nBATCH_SIZE = 1\nSTEPS_PER_EPOCH = int(len(X_enhancedtrain_norm)/BATCH_SIZE)\n\nhistory_enhanced_HLS = LeNet_Model.fit(\n datagen_enhanced.flow(X_enhancedtrain_norm, y_enhanced_onehot, batch_size=BATCH_SIZE,shuffle=True), \n shuffle=True, #validation_data=(X_valid_norm, y_valid_onehot),\n steps_per_epoch=STEPS_PER_EPOCH,\n epochs=EPOCHS)", "WARNING:tensorflow:sample_weight modes were coerced from\n ...\n to \n ['...']\nTrain for 50 steps\nEpoch 1/30\n50/50 [==============================] - 11s 229ms/step - loss: 351.2083 - accuracy: 0.0400\nEpoch 2/30\n50/50 [==============================] - 11s 219ms/step - loss: 142.5382 - accuracy: 0.0000e+00\nEpoch 3/30\n50/50 [==============================] - 11s 218ms/step - loss: 44.1551 - accuracy: 0.0400\nEpoch 4/30\n50/50 [==============================] - 11s 217ms/step - loss: 14.9848 - accuracy: 0.0200\nEpoch 5/30\n50/50 [==============================] - 11s 217ms/step - loss: 131.3266 - accuracy: 0.0000e+00\nEpoch 6/30\n50/50 [==============================] - 11s 217ms/step - loss: 540.1987 - accuracy: 0.0200\nEpoch 7/30\n50/50 [==============================] - 11s 217ms/step - loss: 5.0112 - accuracy: 0.0000e+00\nEpoch 8/30\n50/50 [==============================] - 11s 217ms/step - loss: 16.5539 - accuracy: 0.0200\nEpoch 9/30\n50/50 [==============================] - 11s 217ms/step - loss: 25.3070 - accuracy: 0.0200\nEpoch 10/30\n50/50 [==============================] - 11s 217ms/step - loss: 11.1368 - accuracy: 0.0200\nEpoch 11/30\n50/50 [==============================] - 11s 218ms/step - loss: 4.1143 - accuracy: 0.0000e+00\nEpoch 12/30\n50/50 [==============================] - 11s 218ms/step - loss: 3.9304 - accuracy: 0.0200\nEpoch 13/30\n50/50 [==============================] - 11s 217ms/step - loss: 3.9299 - accuracy: 0.0200\nEpoch 14/30\n50/50 [==============================] - 11s 218ms/step - loss: 3.9296 - accuracy: 0.0200\nEpoch 15/30\n50/50 [==============================] - 11s 217ms/step - loss: 3.9291 - accuracy: 0.0200\nEpoch 16/30\n50/50 [==============================] - 11s 217ms/step - loss: 8.8657 - accuracy: 0.0200\nEpoch 17/30\n50/50 [==============================] - 11s 224ms/step - loss: 3.9287 - accuracy: 0.0200\nEpoch 18/30\n50/50 [==============================] - 12s 231ms/step - loss: 3.9284 - accuracy: 0.0200\nEpoch 19/30\n50/50 [==============================] - 11s 223ms/step - loss: 3.9280 - accuracy: 0.0200\nEpoch 20/30\n50/50 [==============================] - 11s 223ms/step - loss: 3.9278 - accuracy: 0.0200\nEpoch 21/30\n50/50 [==============================] - 11s 221ms/step - loss: 3.9275 - accuracy: 0.0200\nEpoch 22/30\n50/50 [==============================] - 11s 218ms/step - loss: 3.9273 - accuracy: 0.0200\nEpoch 23/30\n50/50 [==============================] - 11s 220ms/step - loss: 3.9095 - accuracy: 0.0200\nEpoch 24/30\n50/50 [==============================] - 11s 221ms/step - loss: 3.9269 - accuracy: 0.0200\nEpoch 25/30\n50/50 [==============================] - 11s 220ms/step - loss: 10.9869 - accuracy: 0.0200\nEpoch 26/30\n50/50 [==============================] - 11s 220ms/step - loss: 3.9265 - accuracy: 0.0200\nEpoch 27/30\n50/50 [==============================] - 11s 219ms/step - loss: 6.8765 - accuracy: 0.0200\nEpoch 28/30\n50/50 [==============================] - 11s 221ms/step - loss: 3.9259 - accuracy: 0.0200\nEpoch 29/30\n50/50 [==============================] - 11s 219ms/step - loss: 3.9259 - accuracy: 0.0200\nEpoch 30/30\n50/50 [==============================] - 11s 218ms/step - loss: 30.3131 - accuracy: 0.0200\n" ], [ "LeNet_Model.save(\"LeNet_enhanced_trainingdataset_HLS.h5\")", "_____no_output_____" ] ], [ [ "### Evaluate the Model\nWe will use the test dataset to evaluate classification accuracy.", "_____no_output_____" ] ], [ [ "#Normalize test dataset\nX_test_norm = input_normalization(X_test)\n#One-hot matrix\ny_test_onehot = keras.utils.to_categorical(y_test, n_classes)", "_____no_output_____" ], [ "#Load saved model\nreconstructed_LeNet_Model = keras.models.load_model(\"LeNet_enhanced_trainingdataset_HLS.h5\")\n\n#Evaluate and display the prediction\nresult = reconstructed_LeNet_Model.evaluate(X_test_norm,y_test_onehot)\ndict(zip(reconstructed_LeNet_Model.metrics_names, result))", "12630/12630 [==============================] - 26s 2ms/sample - loss: 3.9001 - accuracy: 0.0119s - loss: 3.9003 - accuracy: \n" ], [ "pickle.dump(history_enhanced_HLS.history, open( \"history_LeNet_enhanced_trainingdataset_enhanced_HLS.p\", \"wb\" ))\npickle.dump(history_standard_HLS.history, open( \"history_LeNet_enhanced_trainingdataset_standard_HLS.p\", \"wb\" ))", "_____no_output_____" ], [ "with open(\"history_LeNet_enhanced_trainingdataset_standard_HLS.p\", mode='rb') as f:\n history_ = pickle.load(f)", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\n# Plot training error.\nprint('\\nPlot of training error over 30 epochs:')\nfig = plt.figure()\nplt.title('Training error')\nplt.ylabel('Cost')\nplt.xlabel('epoch')\nplt.plot(history_['loss'])\nplt.plot(history_['val_loss'])\n# plt.plot(history.history['loss'])\n# plt.plot(history.history['val_loss'])\nplt.legend(['train loss', 'val loss'], loc='upper right')\nplt.grid()\nplt.show()\nfig.savefig('figures/Training_loss_LeNet_enhanced_trainingdataset_standard_HLS.png', dpi=500)", "\nPlot of training error over 30 epochs:\n" ], [ "# Plot training error.\nprint('\\nPlot of training accuracy over 30 epochs:')\nfig = plt.figure()\nplt.title('Training accuracy')\nplt.ylabel('Accuracy')\nplt.ylim([0.4, 1])\nplt.xlabel('epoch')\nplt.plot(history_['accuracy'])\nplt.plot(history_['val_accuracy'])\nplt.legend(['training_accuracy', 'validation_accuracy'], loc='lower right')\nplt.grid()\nplt.show()\nfig.savefig('figures/Training_accuracy_LeNet_enhanced_trainingdataset_HLS.png', dpi=500)", "\nPlot of training accuracy over 30 epochs:\n" ] ], [ [ "### Prediction of test dataset with trained model\nWe will use the test dataset to test trained model's prediction of instances that it has never seen during training.", "_____no_output_____" ] ], [ [ "print(\"Test Set : {} samples\".format(len(X_test)))\nprint('n_classes : {}'.format(n_classes))\nX_test.shape", "Test Set : 12630 samples\nn_classes : 50\n" ], [ "#Normalize test dataset\nX_test_norm = input_normalization(X_test)\n#One-hot matrix\ny_test_onehot = keras.utils.to_categorical(y_test, n_classes)", "_____no_output_____" ], [ "#Load saved model\nreconstructed = keras.models.load_model(\"LeNet_enhanced_trainingdataset_HLS.h5\")\n\n#Evaluate and display the prediction\nprediction_performance = reconstructed.evaluate(X_test_norm,y_test_onehot)\ndict(zip(reconstructed.metrics_names, prediction_performance))", "12630/12630 [==============================] - 32s 3ms/sample - loss: 3.9001 - accuracy: 0.0119\n" ], [ "import matplotlib.pyplot as plot\n%matplotlib inline\nrows, cols = 4, 12\nfig, axes = plot.subplots(rows, cols)\nfor idx, ax in enumerate(axes.ravel()):\n if idx < n_classes_standard :\n X_test_of_class = X_test[y_test == idx]\n #X_train_0 = X_train_of_class[numpy.random.randint(len(X_train_of_class))]\n X_test_0 = X_test_of_class[0]\n ax.imshow(X_test_0)\n ax.axis('off')\n ax.set_title('{:02d}'.format(idx))\n plot.setp(ax.get_xticklabels(), visible=False)\n plot.setp(ax.get_yticklabels(), visible=False)\n else:\n ax.axis('off')\n#\nplot.draw()\nfig.savefig('figures/' + 'test_representative' + '.jpg', dpi=700)", "_____no_output_____" ], [ "#### Prediction for all instances inside the test dataset\ny_pred_proba = reconstructed.predict(X_test_norm)\ny_pred_class = y_pred_proba.argmax(axis=-1)\n\n### Showing prediction results for 10 first instances\nfor i, pred in enumerate(y_pred_class):\n if i <= 10: \n print('Image {} - Target = {}, Predicted = {}'.format(i, y_test[i], pred))\n else:\n break", "Image 0 - Target = 16, Predicted = 6\nImage 1 - Target = 1, Predicted = 6\nImage 2 - Target = 38, Predicted = 6\nImage 3 - Target = 33, Predicted = 6\nImage 4 - Target = 11, Predicted = 6\nImage 5 - Target = 38, Predicted = 6\nImage 6 - Target = 18, Predicted = 6\nImage 7 - Target = 12, Predicted = 6\nImage 8 - Target = 25, Predicted = 6\nImage 9 - Target = 35, Predicted = 6\nImage 10 - Target = 12, Predicted = 6\n" ] ], [ [ "We will display a confusion matrix on test dataset to figure out our error-rate. \n`X_test_norm` : test dataset \n`y_test` : test dataset ground truth labels \n`y_pred_class` : prediction labels on test dataset ", "_____no_output_____" ] ], [ [ "confusion_matrix = numpy.zeros([n_classes, n_classes])", "_____no_output_____" ] ], [ [ "#### confusion_matrix\n`column` : test dataset ground truth labels \n`row` : prediction labels on test dataset \n`diagonal` : incremented when prediction matches ground truth label ", "_____no_output_____" ] ], [ [ "for ij in range(len(X_test_norm)):\n if y_test[ij] == y_pred_class[ij]:\n confusion_matrix[y_test[ij],y_test[ij]] += 1\n else:\n confusion_matrix[y_pred_class[ij],y_test[ij]] -= 1", "_____no_output_____" ], [ "column_label = [' L % d' % x for x in range(n_classes)]\nrow_label = [' P % d' % x for x in range(n_classes)]", "_____no_output_____" ], [ "# Plot classe representatives\nimport matplotlib.pyplot as plot\n%matplotlib inline\nrows, cols = 1, 43\nfig, axes = plot.subplots(rows, cols)\nfor idx, ax in enumerate(axes.ravel()):\n if idx < n_classes :\n X_test_of_class = X_test[y_test == idx]\n X_test_0 = X_test_of_class[0]\n ax.imshow(X_test_0)\n plot.setp(ax.get_xticklabels(), visible=False)\n plot.setp(ax.get_yticklabels(), visible=False)\n # plot.tick_params(axis='both', which='both', bottom='off', top='off',\n # labelbottom='off', right='off', left='off', labelleft='off')\n ax.axis('off')\nplot.draw()\nfig.savefig('figures/' + 'label_groundtruth' + '.jpg', dpi=3500)", "_____no_output_____" ], [ "numpy.savetxt(\"confusion_matrix_LeNet_enhanced_trainingdataset_HLS.csv\", confusion_matrix, delimiter=\";\")", "_____no_output_____" ] ], [ [ "#### Thank to confusion matrix, we could identify where to enhance \n-[x] training dataset \n-[x] real-time data augmentation \n-[x] preprocessing \n\n*Extract of confusion matrix of classification on test dataset &#8595;* \n<img src=\"figures/confusion_matrix_LeNet_enhanced_trainingdataset_HLS.png\" alt=\"Drawing\" style=\"width: 750px;\"/>", "_____no_output_____" ], [ "### Prediction of new instances with trained model\nWe will use the test dataset to test trained model's prediction of instances that it has never seen during training.\nI didn't 'softmax' activation in the last layer of LeNet architecture, so the output prediction is logits. To have prediction confidence level, we can apply softmax function to output logits.", "_____no_output_____" ] ], [ [ "# load french traffic signs\nimport os\nimport cv2\nimport matplotlib.pyplot as plot\nimport numpy\ndir_frenchsign = 'french_traffic-signs-data'\nimages_frenchsign = [os.path.join(dir_frenchsign, f) for f in os.listdir(dir_frenchsign)]\nimages_frenchsign = numpy.array([cv2.cvtColor(cv2.imread(f), cv2.COLOR_BGR2RGB) for f in images_frenchsign])\n\n# plot new test images\nfig, axes = plot.subplots(3, int(len(images_frenchsign)/3))\nplot.title('French traffic signs')\nfor i, ax in enumerate(axes.ravel()):\n ax.imshow(images_frenchsign[i])\n ax.set_title('{}'.format(i))\n plot.setp(ax.get_xticklabels(), visible=False)\n plot.setp(ax.get_yticklabels(), visible=False)\n ax.set_xticks([]), ax.set_yticks([])\n ax.axis('off')\nplot.draw()\nfig.savefig('figures/' + 'french_sign' + '.jpg', dpi=700)", "_____no_output_____" ] ], [ [ "*Enhanced German traffic signs dataset &#8595;* \n<img src=\"figures/enhanced_training_dataset.png\" alt=\"Drawing\" style=\"width: 700px;\"/>", "_____no_output_____" ] ], [ [ "# manually label for these new images\ny_frenchsign = [13, 31, 29, 24, 26, 27, 33, 17, 15, 34, 12, 2, 2, 4, 2]\nn_classes = n_classes_enhanced\n\n# when a sign doesn't present in our training dataset, we'll try to find a enough 'similar' sign to label it.\n\n# image 2 : class 29 differed \n# image 3 : class 24, double-sens not existed \n# image 5 : class 27 differed\n# image 6 : class 33 not existed \n# image 7 : class 17, halte-péage not existed \n# image 8 : class 15, 3.5t limit not existed \n# image 9 : class 15, turn-left inhibition not existed\n# image 12 : class 2, ending of 50kmh speed-limit not existed\n# image 14 : class 2, 90kmh speed-limit not existed", "_____no_output_____" ] ], [ [ "#### it's really intersting that somes common french traffic signs are not present in INI German traffic signs dataset or differed\nWhatever our input - evenif it's not present in the training dataset, by using softmax activation our classififer can not say that 'this is a new traffic sign that it doesn't recognize' (sum of probability across all classes is 1), it's just try to find class that probably suit for the input.", "_____no_output_____" ] ], [ [ "#Normalize the dataset\nX_frenchsign_norm = input_normalization(images_frenchsign)\n#One-hot matrix\ny_frenchsign_onehot = keras.utils.to_categorical(y_frenchsign, n_classes)\n\n#Load saved model\nreconstructed = keras.models.load_model(\"LeNet_enhanced_trainingdataset_HLS.h5\")\n\n#Evaluate and display the prediction performance\nprediction_performance = reconstructed.evaluate(X_frenchsign_norm, y_frenchsign_onehot)\ndict(zip(reconstructed.metrics_names, prediction_performance))", "\r15/15 [==============================] - 0s 24ms/sample - loss: 3.9201 - accuracy: 0.0000e+00\n" ], [ "#### Prediction for all instances inside the test dataset\ny_pred_logits = reconstructed.predict(X_frenchsign_norm)\ny_pred_proba = tf.nn.softmax(y_pred_logits).numpy()\ny_pred_class = y_pred_proba.argmax(axis=-1)\n\n### Showing prediction results\nfor i, pred in enumerate(y_pred_class): \n print('Image {} - Target = {}, Predicted = {}'.format(i, y_frenchsign[i], pred))", "Image 0 - Target = 13, Predicted = 6\nImage 1 - Target = 31, Predicted = 6\nImage 2 - Target = 29, Predicted = 6\nImage 3 - Target = 24, Predicted = 6\nImage 4 - Target = 26, Predicted = 6\nImage 5 - Target = 27, Predicted = 6\nImage 6 - Target = 33, Predicted = 6\nImage 7 - Target = 17, Predicted = 6\nImage 8 - Target = 15, Predicted = 6\nImage 9 - Target = 34, Predicted = 6\nImage 10 - Target = 12, Predicted = 6\nImage 11 - Target = 2, Predicted = 6\nImage 12 - Target = 2, Predicted = 6\nImage 13 - Target = 4, Predicted = 6\nImage 14 - Target = 2, Predicted = 6\n" ] ], [ [ "*French traffic signs to classsify &#8595;* \n<img src=\"figures/french_sign_compare_german_INI_enhanced.jpg\" alt=\"Drawing\" style=\"width: 750px;\"/>", "_____no_output_____" ] ], [ [ "#### plot softmax probs along with traffic sign examples\nn_img = X_frenchsign_norm.shape[0]\nfig, axarray = plot.subplots(n_img, 2)\nplot.suptitle('Visualization of softmax probabilities', fontweight='bold')\nfor r in range(0, n_img):\n axarray[r, 0].imshow(numpy.squeeze(images_frenchsign[r]))\n axarray[r, 0].set_xticks([]), axarray[r, 0].set_yticks([])\n plot.setp(axarray[r, 0].get_xticklabels(), visible=False)\n plot.setp(axarray[r, 0].get_yticklabels(), visible=False)\n axarray[r, 1].bar(numpy.arange(n_classes), y_pred_proba[r])\n axarray[r, 1].set_ylim([0, 1])\n plot.setp(axarray[r, 1].get_yticklabels(), visible=False)\nplot.draw()\nfig.savefig('figures/' + 'french_sign_softmax_visuali_LeNet_enhanced_trainingdataset_HLS' + '.jpg', dpi=700)\n \nK = 3\n#### print top K predictions of the model for each example, along with confidence (softmax score) \nfor i in range(len(images_frenchsign)):\n print('Top {} model predictions for image {} (Target is {:02d})'.format(K, i, y_frenchsign[i]))\n top_3_idx = numpy.argsort(y_pred_proba[i])[-3:]\n top_3_values = y_pred_proba[i][top_3_idx] \n top_3_logits = y_pred_logits[i][top_3_idx] \n for k in range(K):\n print(' Prediction = {:02d} with probability {:.4f} (logit is {:.4f})'.format(top_3_idx[k], top_3_values[k], top_3_logits[k]))", "Top 3 model predictions for image 0 (Target is 13)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 1 (Target is 31)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 2 (Target is 29)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 3 (Target is 24)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 4 (Target is 26)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 5 (Target is 27)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 6 (Target is 33)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 7 (Target is 17)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 8 (Target is 15)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 9 (Target is 34)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 10 (Target is 12)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 11 (Target is 02)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 12 (Target is 02)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 13 (Target is 04)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\nTop 3 model predictions for image 14 (Target is 02)\n Prediction = 02 with probability 0.0250 (logit is 0.1806)\n Prediction = 31 with probability 0.0262 (logit is 0.2275)\n Prediction = 06 with probability 0.0292 (logit is 0.3377)\n" ] ], [ [ "*Visualization of softmax probabilities &#8595;* \n<img src=\"figures/french_sign_softmax_visuali_LeNet_enhanced_trainingdataset_HLS.jpg\" alt=\"Drawing\" style=\"width: 750px;\"/>", "_____no_output_____" ], [ "## Visualization of layers", "_____no_output_____" ] ], [ [ "### Import tensorflow and keras\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import Model\nimport matplotlib.pyplot as plot\n\nprint (\"TensorFlow version: \" + tf.__version__)", "TensorFlow version: 2.1.0\n" ], [ "# Load pickled data\nimport pickle\nimport numpy\n\ntraining_file = 'traffic-signs-data/train.p'\nwith open(training_file, mode='rb') as f:\n train = pickle.load(f)\n \nX_train, y_train = train['features'], train['labels'] # training dataset\nn_classes = len(numpy.unique(y_train))", "_____no_output_____" ], [ "import cv2\ndef input_normalization(X_in):\n X = numpy.float32(X_in/255.0) \n return X\n\n# normalization of dataset\nX_train_norm = input_normalization(X_train)\n\n# one-hot matrix\ny_train_onehot = keras.utils.to_categorical(y_train, n_classes)", "_____no_output_____" ], [ "#Load saved model\nreconstructed = keras.models.load_model(\"LeNet_enhanced_trainingdataset_HLS.h5\")\n\n#Build model for layer display\nlayers_output = [layer.output for layer in reconstructed.layers]\noutputs_model = Model(inputs=reconstructed.input, outputs=layers_output)\noutputs_history = outputs_model.predict(X_train_norm[900].reshape(1,32,32,3))", "_____no_output_____" ] ], [ [ "#### Display analized input", "_____no_output_____" ] ], [ [ "plot.imshow(X_train[900])", "_____no_output_____" ], [ "def display_layer(outputs_history, col_size, row_size, layer_index): \n activation = outputs_history[layer_index]\n activation_index = 0\n fig, ax = plot.subplots(row_size, col_size, figsize=(row_size*2.5,col_size*1.5))\n for row in range(0,row_size):\n for col in range(0,col_size):\n ax[row][col].axis('off')\n if activation_index < activation.shape[3]:\n ax[row][col].imshow(activation[0, :, :, activation_index]) # , cmap='gray' \n activation_index += 1", "_____no_output_____" ], [ "display_layer(outputs_history, 3, 2, 1)", "_____no_output_____" ], [ "display_layer(outputs_history, 8, 8, 2)", "_____no_output_____" ], [ "display_layer(outputs_history, 8, 8, 3)", "_____no_output_____" ], [ "display_layer(outputs_history, 8, 8, 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", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d00e5b81389e6d21862a5eb9a75ef6d5b9cbeb5c
731,862
ipynb
Jupyter Notebook
.ipynb_checkpoints/Nucleotide metabolism-checkpoint.ipynb
polybiome/PolyEnzyme
2e1e22685d13d6a570e6c73c3a7c16991cab24ce
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Nucleotide metabolism-checkpoint.ipynb
polybiome/PolyEnzyme
2e1e22685d13d6a570e6c73c3a7c16991cab24ce
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Nucleotide metabolism-checkpoint.ipynb
polybiome/PolyEnzyme
2e1e22685d13d6a570e6c73c3a7c16991cab24ce
[ "MIT" ]
null
null
null
1,234.168634
193,991
0.548765
[ [ [ "import escher\nimport escher.urls\nimport cobra\nimport cobra.test\nimport json\nimport os\nfrom IPython.display import HTML\nfrom copy import deepcopy", "_____no_output_____" ], [ "d = escher.urls.root_directory\nprint('Escher directory: %s' % d)", "Escher directory: /Users/joanrue/anaconda/lib/python2.7/site-packages\n" ] ], [ [ "### Embed an Escher map in an IPython notebook", "_____no_output_____" ] ], [ [ "escher.list_available_maps()", "_____no_output_____" ], [ "b = escher.Builder(map_name='e_coli_core.Core metabolism')\nb.display_in_notebook()", "_____no_output_____" ] ], [ [ "### Plot FBA solutions in Escher", "_____no_output_____" ] ], [ [ "model = cobra.io.load_json_model( \"iECW_1372.json\") # E coli metabolic model\nFBA_Solution = model.optimize() # FBA of the original model\n\nprint('Original Growth rate: %.9f' % FBA_Solution.f)\n\n", "Original Growth rate: 0.982478439\n" ], [ "b = escher.Builder(map_name='e_coli_core.Core metabolism',\n reaction_data=FBA_Solution.x_dict,\n # color and size according to the absolute value\n reaction_styles=['color', 'size', 'abs', 'text'],\n # change the default colors\n reaction_scale=[{'type': 'min', 'color': '#cccccc', 'size': 4},\n {'type': 'mean', 'color': '#0000dd', 'size': 20},\n {'type': 'max', 'color': '#ff0000', 'size': 40}],\n # only show the primary metabolites\n hide_secondary_metabolites=True,\n highlight_missing = True)\nb.display_in_notebook()\n#b.display_in_browser()", "_____no_output_____" ], [ "# MAP EDITION\nmodel_knockout = model.copy()\ncobra.manipulation.delete_model_genes(model_knockout, [\"ECW_m3223\"]) #ODC\ncobra.manipulation.delete_model_genes(model_knockout, [\"ECW_m0743\"]) #ODC\ncobra.manipulation.delete_model_genes(model_knockout, [\"ECW_m3196\"]) #Agmatinase. \nknockout_FBA_solution = model_knockout.optimize() # FBA of the knockout\n\nprint('Knockout Growth rate: %.9f' % knockout_FBA_solution.f)", "Knockout Growth rate: 0.982478439\n" ], [ "#PASS THE MODEL TO A NEW BUILDER\nb = escher.Builder(map_name='e_coli_core.Core metabolism',\n reaction_data=knockout_FBA_solution.x_dict,\n # color and size according to the absolute value\n reaction_styles=['color', 'size', 'abs', 'text'],\n # change the default colors\n reaction_scale=[{'type': 'min', 'color': '#cccccc', 'size': 4},\n {'type': 'mean', 'color': '#0000dd', 'size': 20},\n {'type': 'max', 'color': '#ff0000', 'size': 40}],\n # only show the primary metabolites\n hide_secondary_metabolites=True,\n highlight_missing = True)\nb.display_in_notebook()\n#b.display_in_browser()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d00e6798546dcbadb9d9821cef6e8108a866c7ec
15,288
ipynb
Jupyter Notebook
Object Oriented Programming.ipynb
ramsvijay/basic_datatype_python
2aa0db44a839ccc8d12fdd392e1a054dae4c1d30
[ "MIT" ]
null
null
null
Object Oriented Programming.ipynb
ramsvijay/basic_datatype_python
2aa0db44a839ccc8d12fdd392e1a054dae4c1d30
[ "MIT" ]
null
null
null
Object Oriented Programming.ipynb
ramsvijay/basic_datatype_python
2aa0db44a839ccc8d12fdd392e1a054dae4c1d30
[ "MIT" ]
null
null
null
19.675676
111
0.445055
[ [ [ "x =2\nr = lambda x:x**2", "_____no_output_____" ], [ "r(x)", "_____no_output_____" ], [ "r1 = lambda x:x**2 if x>3 else None", "_____no_output_____" ], [ "r1(x)", "_____no_output_____" ], [ "r1(5)", "_____no_output_____" ], [ "#object\n\n#using class keyword\n#creating the attributes\n#creating the methods in class\n#learning about inheritence in python\n#learning about polymorphism", "_____no_output_____" ], [ "lt = [1,2,3,4]", "_____no_output_____" ], [ "lt.count(4)", "_____no_output_____" ], [ "print(type(1))\nprint(type([]))\nprint(type(()))\nprint(type({}))", "<class 'int'>\n<class 'list'>\n<class 'tuple'>\n<class 'dict'>\n" ], [ "#Create a new Object type ca;;ed test_sample\n\nclass TestSample:\n pass\n\n#Instance of the object \nx = TestSample()\nprint(type(x))", "<class '__main__.TestSample'>\n" ], [ "class Dog:\n def __init__(self,breed):\n self.breed = breed\n \ntuku = Dog(breed=\"Dalmi\") ", "_____no_output_____" ], [ "tuku.breed", "_____no_output_____" ], [ "#Init Method is constructor", "_____no_output_____" ], [ "#Self is keyword used for like this keyword ", "_____no_output_____" ] ], [ [ "# Methods", "_____no_output_____" ] ], [ [ "class ourCircle:\n pi = 3.14\n def __init__(self,radius=1):\n self.radius = radius\n self.area = self.getArea(radius)\n \n def setRadius(self,new_radius):\n self.radius = new_radius\n self = new_radius * new_radius * self.pi\n \n def getCircumference(self):\n return self.radius * self.pi * 2\n \n def getArea(self,radius):\n return radius * radius * self.pi\n", "_____no_output_____" ], [ "cir = ourCircle()", "_____no_output_____" ], [ "cir.getCircumference()", "_____no_output_____" ], [ "cir.getArea(2)", "_____no_output_____" ] ], [ [ "# Inheritance", "_____no_output_____" ] ], [ [ "class Animal:\n def __init__(self):\n print(\"Animal Object Cost Created\")\n def whoAmI(self):\n print(\"I am Animal Class\")\n def eat(self):\n print(\"I am eating\")", "_____no_output_____" ], [ "a = Animal()", "Animal Object Cost Created\n" ], [ "a.eat()", "I am eating\n" ], [ "class Man(Animal):\n def __init__(self):\n Animal.__init__(self) ", "_____no_output_____" ], [ "m = Man()", "Animal Object Cost Created\n" ], [ "m.eat()", "I am eating\n" ], [ "#Polymorphism", "_____no_output_____" ], [ "#Exception Handling", "_____no_output_____" ], [ "try:\n f =open('test','w')\n # f.write(\"rams\")\n f.read()\nexcept IOError:\n print('geting error')\nelse:\n print(\"Print CONETENT SUCCESS\")\n f.close()\n \nprint(\"Error Handle by try and catch\")", "geting error\nError Handle by try and catch\n" ], [ "try:\n a='ram'\n b=10\n print(a+b)\nexcept Exception as e:\n print(e.args)\n ", "('can only concatenate str (not \"int\") to str',)\n" ], [ "try:\n a='ram'\n b=10\n print(a+b)\nexcept Exception as e:\n print(e.args)\nfinally:\n print(\"i'm getting error\")", "('can only concatenate str (not \"int\") to str',)\ni'm getting error\n" ], [ "while False:\n print(\"rams\")\nelse:\n print(\"vijay\")", "vijay\n" ], [ "#pip install pylint", "_____no_output_____" ], [ "%%writefile simple.py\n\na=10\nprint(a)", "Writing simple.py\n" ], [ "! pylint simple.py", "************* Module simple\nsimple.py:2:1: C0326: Exactly one space required around assignment\na=10\n\n ^ (bad-whitespace)\nsimple.py:1:0: C0111: Missing module docstring (missing-docstring)\nsimple.py:2:0: C0103: Constant name \"a\" doesn't conform to UPPER_CASE naming style (invalid-name)\n\n------------------------------------\n\nYour code has been rated at -5.00/10\n\n\n\n" ], [ "%%writefile simple.py\n'''\nA very simple script\n'''\ndef fun():\n first = 1\n second = 2 \n print(first)\n print(second)\nfun() ", "Overwriting simple.py\n" ], [ "!pylint simple.py", "************* Module simple\nsimple.py:6:14: C0303: Trailing whitespace (trailing-whitespace)\nsimple.py:9:5: C0303: Trailing whitespace (trailing-whitespace)\nsimple.py:4:0: C0111: Missing function docstring (missing-docstring)\n\n------------------------------------------------------------------\n\nYour code has been rated at 5.00/10 (previous run: 3.33/10, +1.67)\n\n\n\n" ], [ "#UnitTest", "_____no_output_____" ], [ "%%writefile capitalize_text.py\ndef capitalize_test(text):\n return text.capitalize_t()", "Overwriting capitalize_text.py\n" ], [ "%%writefile test_file.py\nimport unittest\nimport capitalize_text\n\nclass TestCap(unittest.TestCase):\n \n def test_one_word(self):\n test = \"python\"\n result = capitalize_text.capitalize_test(text)\n self.assertEqual(result,'python')\n def test_multiple_words(self):\n text = \"my python\"\n result = capitalize_text.capitalize_test(text)\n self.assertEqual(result,'my python')\n \nif __name__ == '__main__':\n unittest.main()", "Overwriting test_file.py\n" ], [ "! python test_file.py", "EE\n======================================================================\nERROR: test_multiple_words (__main__.TestCap)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"test_file.py\", line 12, in test_multiple_words\n result = capitalize_text.capitalize_test(text)\n File \"C:\\Users\\Kumaran\\Documents\\FCS Python\\capitalize_text.py\", line 2, in capitalize_test\n return text.capitalize_t()\nAttributeError: 'str' object has no attribute 'capitalize_t'\n\n======================================================================\nERROR: test_one_word (__main__.TestCap)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"test_file.py\", line 8, in test_one_word\n result = capitalize_text.capitalize_test(text)\nNameError: name 'text' is not defined\n\n----------------------------------------------------------------------\nRan 2 tests in 0.001s\n\nFAILED (errors=2)\n" ], [ "! pylint capitalize_text.py", "************* Module capitalize_text\ncapitalize_text.py:1:0: C0111: Missing module docstring (missing-docstring)\ncapitalize_text.py:1:0: C0111: Missing function docstring (missing-docstring)\n\n-----------------------------------\n\nYour code has been rated at 0.00/10\n\n\n\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "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" ] ]
d00e681d61071342ae7dd3806ccf61a9be66c5cb
21,352
ipynb
Jupyter Notebook
lessons/misc/quantum-computing/grovers-algorthim-2-qubits.ipynb
UAAppComp/studyGroup
642eb769cb2abdce5de3f2f10dd12164ac0dd052
[ "Apache-2.0" ]
105
2015-06-22T15:23:19.000Z
2022-03-30T12:20:09.000Z
lessons/misc/quantum-computing/grovers-algorthim-2-qubits.ipynb
UAAppComp/studyGroup
642eb769cb2abdce5de3f2f10dd12164ac0dd052
[ "Apache-2.0" ]
314
2015-06-18T22:10:34.000Z
2022-02-09T16:47:52.000Z
lessons/misc/quantum-computing/grovers-algorthim-2-qubits.ipynb
UAAppComp/studyGroup
642eb769cb2abdce5de3f2f10dd12164ac0dd052
[ "Apache-2.0" ]
142
2015-06-18T22:11:53.000Z
2022-02-03T16:14:43.000Z
53.783375
4,264
0.736043
[ [ [ "# Simulating Grover's Search Algorithm with 2 Qubits", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom matplotlib import pyplot as plt\n%matplotlib inline", "_____no_output_____" ] ], [ [ "Define the zero and one vectors\nDefine the initial state $\\psi$", "_____no_output_____" ] ], [ [ "zero = np.matrix([[1],[0]]);\none = np.matrix([[0],[1]]);\n\npsi = np.kron(zero,zero);\nprint(psi)", "[[1]\n [0]\n [0]\n [0]]\n" ] ], [ [ "Define the gates we will use:\n\n$\n\\text{Id} = \\begin{pmatrix} \n1 & 0 \\\\\n0 & 1 \n\\end{pmatrix},\n\\quad\nX = \\begin{pmatrix} \n0 & 1 \\\\\n1 & 0 \n\\end{pmatrix},\n\\quad\nZ = \\begin{pmatrix} \n1 & 0 \\\\\n0 & -1 \n\\end{pmatrix},\n\\quad\nH = \\frac{1}{\\sqrt{2}}\\begin{pmatrix} \n1 & 1 \\\\\n1 & -1 \n\\end{pmatrix},\n\\quad\n\\text{CNOT} = \\begin{pmatrix} \n1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 0 \\\\ \n0 & 0 & 0 & 1 \\\\\n0 & 0 & 1 & 0\n\\end{pmatrix},\n\\quad\nCZ = (\\text{Id} \\otimes H) \\text{ CNOT } (\\text{Id} \\otimes H) \n$", "_____no_output_____" ] ], [ [ "Id = np.matrix([[1,0],[0,1]]);\nX = np.matrix([[0,1],[1,0]]);\nZ = np.matrix([[1,0],[0,-1]]);\nH = np.sqrt(0.5) * np.matrix([[1,1],[1,-1]]);\n\nCNOT = np.matrix([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]);\nCZ = np.kron(Id,H).dot(CNOT).dot(np.kron(Id,H));\nprint(CZ)", "[[ 1. 0. 0. 0.]\n [ 0. 1. 0. 0.]\n [ 0. 0. 1. 0.]\n [ 0. 0. 0. -1.]]\n" ] ], [ [ "Define the oracle for Grover's algorithm (take search answer to be \"10\")\n\n$\n\\text{oracle} = \\begin{pmatrix} \n1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 0 \\\\\n0 & 0 & -1 & 0 \\\\\n0 & 0 & 0 & 1\n\\end{pmatrix}\n= (Z \\otimes \\text{Id}) CZ\n$\n\nUse different combinations of $Z \\otimes \\text{Id}$ to change where search answer is. ", "_____no_output_____" ] ], [ [ "oracle = np.kron(Z,Id).dot(CZ);\nprint(oracle)", "[[ 1. 0. 0. 0.]\n [ 0. 1. 0. 0.]\n [ 0. 0. -1. 0.]\n [ 0. 0. 0. 1.]]\n" ] ], [ [ "Act the H gates on the input vector and apply the oracle ", "_____no_output_____" ] ], [ [ "psi0 = np.kron(H,H).dot(psi);\npsi1 = oracle.dot(psi0);\nprint(psi1)", "[[ 0.5]\n [ 0.5]\n [-0.5]\n [ 0.5]]\n" ] ], [ [ "Remember that when we measure the result (\"00\", \"01\", \"10\", \"11\") is chosen randomly with probabilities given by the vector elements squared.", "_____no_output_____" ] ], [ [ "print(np.multiply(psi1,psi1))", "[[ 0.25]\n [ 0.25]\n [ 0.25]\n [ 0.25]]\n" ] ], [ [ "There is no difference between any of the probabilities. It's still just a 25% chance of getting the right answer. \n\nWe need some of gates after the oracle before measuring to converge on the right answer. \n\nThese gates do the operation $W = \\frac{1}{2}\\begin{pmatrix} \n-1 & 1 & 1 & 1 \\\\\n1 & -1 & 1 & 1 \\\\\n1 & 1 & -1 & 1 \\\\\n1 & 1 & 1 & -1\n\\end{pmatrix}\n=\n(H \\otimes H)(Z \\otimes Z) CZ (H \\otimes H)\n$\n\nNotice that if the matrix W is multiplied by the vector after the oracle, W $\\frac{1}{2}\\begin{pmatrix} \n1 \\\\\n1 \\\\\n-1 \\\\\n1\n\\end{pmatrix} \n= \\begin{pmatrix} \n0 \\\\\n0 \\\\\n1 \\\\\n0\n\\end{pmatrix} $,\nevery vector element decreases, except the correct answer element which increases. This would be true if if we chose a different place for the search result originally.", "_____no_output_____" ] ], [ [ "W = np.kron(H,H).dot(np.kron(Z,Z)).dot(CZ).dot(np.kron(H,H));\nprint(W)", "[[-0.5 0.5 0.5 0.5]\n [ 0.5 -0.5 0.5 0.5]\n [ 0.5 0.5 -0.5 0.5]\n [ 0.5 0.5 0.5 -0.5]]\n" ], [ "psif = W.dot(psi1);\nprint(np.multiply(psif,psif))", "[[ 1.23259516e-32]\n [ 3.08148791e-33]\n [ 1.00000000e+00]\n [ 3.08148791e-33]]\n" ], [ "x = [0,1,2,3];\nxb = [0.25,1.25,2.25,3.25];\nlabels=['00', '01', '10', '11'];\nplt.axis([-0.5,3.5,-1.25,1.25]);\nplt.xticks(x,labels);\nplt.bar(x, np.ravel(psi0), 1/1.5, color=\"red\");\nplt.bar(xb, np.ravel(np.multiply(psi0,psi0)), 1/2., color=\"blue\");", "_____no_output_____" ], [ "labels=['00', '01', '10', '11'];\nplt.axis([-0.5,3.5,-1.25,1.25]);\nplt.xticks(x,labels);\nplt.bar(x, np.ravel(psi1), 1/1.5, color=\"red\");\nplt.bar(xb, np.ravel(np.multiply(psi1,psi1)), 1/2., color=\"blue\");", "_____no_output_____" ], [ "labels=['00', '01', '10', '11'];\nplt.axis([-0.5,3.5,-1.25,1.25]);\nplt.xticks(x,labels);\nplt.bar(x, np.ravel(psif), 1/1.5, color=\"red\");\nplt.bar(xb, np.ravel(np.multiply(psif,psif)), 1/2., color=\"blue\");", "_____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", "code", "code", "code", "code" ] ]
d00e6b7a8018e76d445b5f990b4731001148647b
16,052
ipynb
Jupyter Notebook
Visualization/image_color_ramp.ipynb
pberezina/earthengine-py-notebooks
4cbe3c52bcc9ed3f1337bf097aa5799442991a5e
[ "MIT" ]
1
2020-03-20T19:39:34.000Z
2020-03-20T19:39:34.000Z
Visualization/image_color_ramp.ipynb
pberezina/earthengine-py-notebooks
4cbe3c52bcc9ed3f1337bf097aa5799442991a5e
[ "MIT" ]
null
null
null
Visualization/image_color_ramp.ipynb
pberezina/earthengine-py-notebooks
4cbe3c52bcc9ed3f1337bf097aa5799442991a5e
[ "MIT" ]
null
null
null
80.663317
9,052
0.810304
[ [ [ "<table class=\"ee-notebook-buttons\" align=\"left\">\n <td><a target=\"_blank\" href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/Visualization/image_color_ramp.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n <td><a target=\"_blank\" href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Visualization/image_color_ramp.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n <td><a target=\"_blank\" href=\"https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Visualization/image_color_ramp.ipynb\"><img width=58px src=\"https://mybinder.org/static/images/logo_social.png\" />Run in binder</a></td>\n <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Visualization/image_color_ramp.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n</table>", "_____no_output_____" ], [ "## Install Earth Engine API\nInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`.\nThe following script checks if the geehydro package has been installed. If not, it will install geehydro, which automatically install its dependencies, including earthengine-api and folium.", "_____no_output_____" ] ], [ [ "import subprocess\n\ntry:\n import geehydro\nexcept ImportError:\n print('geehydro package not installed. Installing ...')\n subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geehydro'])", "_____no_output_____" ] ], [ [ "Import libraries", "_____no_output_____" ] ], [ [ "import ee\nimport folium\nimport geehydro", "_____no_output_____" ] ], [ [ "Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. ", "_____no_output_____" ] ], [ [ "try:\n ee.Initialize()\nexcept Exception as e:\n ee.Authenticate()\n ee.Initialize()", "_____no_output_____" ] ], [ [ "## Create an interactive map \nThis step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. \nThe optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.", "_____no_output_____" ] ], [ [ "Map = folium.Map(location=[40, -100], zoom_start=4)\nMap.setOptions('HYBRID')", "_____no_output_____" ] ], [ [ "## Add Earth Engine Python script ", "_____no_output_____" ] ], [ [ "# Load SRTM Digital Elevation Model data.\nimage = ee.Image('CGIAR/SRTM90_V4');\n\n# Define an SLD style of discrete intervals to apply to the image.\nsld_intervals = \\\n '<RasterSymbolizer>' + \\\n '<ColorMap type=\"intervals\" extended=\"false\" >' + \\\n '<ColorMapEntry color=\"#0000ff\" quantity=\"0\" label=\"0\"/>' + \\\n '<ColorMapEntry color=\"#00ff00\" quantity=\"100\" label=\"1-100\" />' + \\\n '<ColorMapEntry color=\"#007f30\" quantity=\"200\" label=\"110-200\" />' + \\\n '<ColorMapEntry color=\"#30b855\" quantity=\"300\" label=\"210-300\" />' + \\\n '<ColorMapEntry color=\"#ff0000\" quantity=\"400\" label=\"310-400\" />' + \\\n '<ColorMapEntry color=\"#ffff00\" quantity=\"1000\" label=\"410-1000\" />' + \\\n '</ColorMap>' + \\\n '</RasterSymbolizer>';\n\n# Define an sld style color ramp to apply to the image.\nsld_ramp = \\\n '<RasterSymbolizer>' + \\\n '<ColorMap type=\"ramp\" extended=\"false\" >' + \\\n '<ColorMapEntry color=\"#0000ff\" quantity=\"0\" label=\"0\"/>' + \\\n '<ColorMapEntry color=\"#00ff00\" quantity=\"100\" label=\"100\" />' + \\\n '<ColorMapEntry color=\"#007f30\" quantity=\"200\" label=\"200\" />' + \\\n '<ColorMapEntry color=\"#30b855\" quantity=\"300\" label=\"300\" />' + \\\n '<ColorMapEntry color=\"#ff0000\" quantity=\"400\" label=\"400\" />' + \\\n '<ColorMapEntry color=\"#ffff00\" quantity=\"500\" label=\"500\" />' + \\\n '</ColorMap>' + \\\n '</RasterSymbolizer>';\n\n# Add the image to the map using both the color ramp and interval schemes.\nMap.setCenter(-76.8054, 42.0289, 8);\nMap.addLayer(image.sldStyle(sld_intervals), {}, 'SLD intervals');\nMap.addLayer(image.sldStyle(sld_ramp), {}, 'SLD ramp');", "_____no_output_____" ] ], [ [ "## Display Earth Engine data layers ", "_____no_output_____" ] ], [ [ "Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)\nMap", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d00e73bfdc6bcf44cf90ef04cf7ed87037b621b8
6,373
ipynb
Jupyter Notebook
TESI-IFPI-2018-master/activity02/question03.ipynb
danieldsf/ads-activities
3da8168f685dfdbe146e20023fbdaefd46c21b54
[ "Apache-2.0" ]
1
2021-08-19T12:13:21.000Z
2021-08-19T12:13:21.000Z
TESI-IFPI-2018-master/activity02/question03.ipynb
danieldsf/ads-activities
3da8168f685dfdbe146e20023fbdaefd46c21b54
[ "Apache-2.0" ]
null
null
null
TESI-IFPI-2018-master/activity02/question03.ipynb
danieldsf/ads-activities
3da8168f685dfdbe146e20023fbdaefd46c21b54
[ "Apache-2.0" ]
null
null
null
49.403101
1,686
0.624823
[ [ [ "from sklearn.naive_bayes import MultinomialNB", "_____no_output_____" ], [ "modelo = MultinomialNB()", "_____no_output_____" ], [ "futebol1 = ['Castanho', 'Casado', 'Sexo Masculino', 'Cabelo Curto'];futebol2 = ['Azul', 'Casado', 'Sexo Masculino', 'Cabelo Curto']; futebol3 = ['Azul', 'Casado', 'Sexo Feminino', 'Cabelo Longo']; futebol4 = ['Azul', 'Não casado', 'Sexo Masculino', 'Cabelo Curto']; futebol5 = ['Azul','Não casado','Sexo Masculino','Cabelo Longo']", "_____no_output_____" ], [ "aerobica1 = ['Castanho', 'Casado', 'Sexo Feminino', 'Cabelo Curto'];aerobica2 = ['Castanho', 'Não casado', 'Sexo Feminino', 'Cabelo Curto']; aerobica3 = ['Castanho', 'Não casado', 'Sexo Feminino', 'Cabelo Longo']", "_____no_output_____" ], [ "misterioso1 = ['Castanho','Casado','Sexo Masculino','Cabelo Curto'];misterioso2 = ['Castanho','Não casado','Sexo Masculino','Cabelo Longo'];misterioso3 = ['Azul', 'Não casado', 'Sexo Feminino', 'Cabelo Longo'];misterioso4 = ['Azul', 'Casado', 'Sexo Masculino', 'Cabelo Longo']", "_____no_output_____" ], [ "dados = [futebol1, futebol2, futebol3, futebol4, futebol5, aerobica1, aerobica2, aerobica3]", "_____no_output_____" ], [ "marcacoes = [1,1,1,1,1,-1,-1,-1]", "_____no_output_____" ], [ "modelo.fit(dados, marcacoes)", "_____no_output_____" ], [ "print(modelo.predict([misterioso1, misterioso2, misterioso3, misterioso4]))", "[1 1 1 1]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d00e9188dfb27ae19d7df0a23d52b95beadc4303
84,244
ipynb
Jupyter Notebook
05.04-Feature-Engineering.ipynb
sebaspee/intro_machine_learning
b58cdfb6ab3e685753f3228e4f5b4f652d2da2a3
[ "MIT" ]
12
2018-08-24T23:54:19.000Z
2020-01-25T17:39:34.000Z
05.04-Feature-Engineering.ipynb
sebaspee/intro_machine_learning
b58cdfb6ab3e685753f3228e4f5b4f652d2da2a3
[ "MIT" ]
1
2018-09-07T22:03:18.000Z
2018-09-07T22:03:18.000Z
05.04-Feature-Engineering.ipynb
sebaspee/intro_machine_learning
b58cdfb6ab3e685753f3228e4f5b4f652d2da2a3
[ "MIT" ]
9
2018-08-31T22:13:59.000Z
2019-09-28T16:14:24.000Z
93.293466
30,588
0.837947
[ [ [ "# Ingeniería de Características", "_____no_output_____" ], [ "En las clases previas vimos las ideas fundamentales de machine learning, pero todos los ejemplos asumían que ya teníamos los datos numéricos en un formato ordenado de tamaño ``[n_samples, n_features]``.\nEn la realidad son raras las ocasiones en que los datos vienen así, _llegar y llevar_.\nCon esto en mente, uno de los pasos más importantes en la práctica de machine learging es la _ingeniería de características_ (_feature engineering_), que es tomar cualquier información que tengas sobre tu problema y convertirla en números con los que construirás tu matriz de características.\n\nEn esta sección veremos dos ejemplos comunes de _tareas_ de ingeniería de características: cómo representar _datos categóricos_ y cómo representar _texto_. \nOtras características más avanzandas, como el procesamiento de imágenes, quedarán para el fin del curso.\n\nAdicionalmente, discutiremos _características derivadas_ para incrementar la complejidad del modelo y la _imputación_ de datos perdidos.\nEn ocasiones este proceso se conoce como _vectorización_, ya que se refiere a convertir datos arbitrarios en vectores bien definidos.", "_____no_output_____" ], [ "## Características Categóricas\n\nUn tipo común de datos no numéricos son los datos _categóricos_.\nPor ejemplo, imagina que estás explorando datos de precios de propiedad, y junto a variables numéricas como precio (_price_) y número de habitaciones (_rooms_), también tienes información del barrio (_neighborhood_) de cada propiedad.\nPor ejemplo, los datos podrían verse así:", "_____no_output_____" ] ], [ [ "data = [\n {'price': 850000, 'rooms': 4, 'neighborhood': 'Queen Anne'},\n {'price': 700000, 'rooms': 3, 'neighborhood': 'Fremont'},\n {'price': 650000, 'rooms': 3, 'neighborhood': 'Wallingford'},\n {'price': 600000, 'rooms': 2, 'neighborhood': 'Fremont'}\n]", "_____no_output_____" ] ], [ [ "Podrías estar tentade a codificar estos datos directamente con un mapeo numérico:", "_____no_output_____" ] ], [ [ "{'Queen Anne': 1, 'Fremont': 2, 'Wallingford': 3};", "_____no_output_____" ] ], [ [ "Resulta que esto no es una buena idea. En Scikit-Learn, y en general, los modelos asumen que los datos numéricos reflejan cantidades algebraicas.\nUsar un mapeo así implica, por ejemplo, que *Queen Anne < Fremont < Wallingford*, o incluso que *Wallingford - Queen Anne = Fremont*, lo que no tiene mucho sentido.\n\nUna técnica que funciona en estas situaciones es _codificación caliente_ (_one-hot encoding_), que crea columnas numéricas que indican la presencia o ausencia de la categoría correspondiente, con un valor de 1 o 0 respectivamente.\nCuando tus datos son una lista de diccionarios, la clase ``DictVectorizer`` se encarga de la codificación por ti:", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction import DictVectorizer\nvec = DictVectorizer(sparse=False, dtype=int)\nvec.fit_transform(data)", "_____no_output_____" ] ], [ [ "Nota que la característica `neighborhood` se ha expandido en tres columnas separadas, representando las tres etiquetas de barrio, y que cada fila tiene un 1 en la columna asociada al barrio respectivo.\nTeniendo los datos codificados de esa manera, se puede proceder a ajustar un modelo en Scikit-Learn.\n\nPara ver el significado de cada columna se puede hacer lo siguiente:", "_____no_output_____" ] ], [ [ "vec.get_feature_names()", "_____no_output_____" ] ], [ [ "Hay una clara desventaja en este enfoque: si las categorías tienen muchos valores posibles, el dataset puede crecer demasiado.\nSin embargo, como los datos codificados contienen principalmente ceros, una matriz dispersa puede ser una solucion eficiente:", "_____no_output_____" ] ], [ [ "vec = DictVectorizer(sparse=True, dtype=int)\nvec.fit_transform(data)", "_____no_output_____" ] ], [ [ "Varios (pero no todos) de los estimadores en Scikit-Learn aceptan entradas dispersas. ``sklearn.preprocessing.OneHotEncoder`` y ``sklearn.feature_extraction.FeatureHasher`` son dos herramientas adicionales que permiten trabajar con este tipo de características.", "_____no_output_____" ], [ "## Texto\n\nOtra necesidad común es convertir texto en una serie de números que representen su contenido.\nPor ejemplo, mucho del análisis automático del contenido generado en redes sociales depende de alguna manera de codificar texto como números.\nUno de los métodos más simples es a través de _conteo de palabras_ (_word counts_): tomas cada pedazo del texto, cuentas las veces que aparece cada palabra en él, y pones los resultados en una table.\n\nPor ejemplo, considera las siguientes tres frases:", "_____no_output_____" ] ], [ [ "sample = ['problem of evil',\n 'evil queen',\n 'horizon problem']", "_____no_output_____" ] ], [ [ "Para vectorizar estos datos construiríamos una columna para las palabras \"problem,\" \"evil,\", \"horizon,\" etc.\nHacer esto a mano es posible, pero nos podemos ahorrar el tedio utilizando el ``CountVectorizer`` de Scikit-Learn:", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction.text import CountVectorizer\n\nvec = CountVectorizer()\nX = vec.fit_transform(sample)\nX", "_____no_output_____" ] ], [ [ "El resultado es una matriz dispersa que contiene cada vez que aparece cada palabra en los textos. Para inspeccionarlo fácilmente podemos convertir esto en un ``DataFrame``:", "_____no_output_____" ] ], [ [ "import pandas as pd\npd.DataFrame(X.toarray(), columns=vec.get_feature_names())", "_____no_output_____" ] ], [ [ "Todavía falta algo. Este enfoque puede tener problemas: el conteo de palabras puede hacer que algunas características pesen más que otras debido a la frecuencia con la que utilizamos las palabras, y esto puede ser sub-óptimo en algunos algoritmos de clasificación.\nUna manera de considerar esto es utilizar el modelo _frecuencia de términos-frecuencia inversa de documents_ (_TF-IDF_), que da peso a las palabras de acuerdo a qué tan frecuentemente aparecen en los documentos, pero también qué tan únicas son para cada documento.\nLa sintaxis para aplicar TF-IDF es similar a la que hemos visto antes:", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction.text import TfidfVectorizer\nvec = TfidfVectorizer()\nX = vec.fit_transform(sample)\npd.DataFrame(X.toarray(), columns=vec.get_feature_names())", "_____no_output_____" ] ], [ [ "Esto lo veremos en más detalle en la clase de Naive Bayes.", "_____no_output_____" ], [ "## Características Derivadas\n\nOtro tipo útil de característica es aquella derivada matemáticamente desde otras características en los datos de entrada.\nVimos un ejemplo en la clase de Hiperparámetros cuando construimos características polinomiales desde los datos.\nVimos que se puede convertir una regresión lineal en una polinomial sin usar un modelo distinto, sino que transformando los datos de entrada.\nEsto es conocido como _función de regresión base_ (_basis function regression_), y lo exploraremos en la clase de Regresión Lineal.\n\nPor ejemplo, es claro que los siguientes datos no se pueden describir por una línea recta:", "_____no_output_____" ] ], [ [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.array([1, 2, 3, 4, 5])\ny = np.array([4, 2, 1, 3, 7])\nplt.scatter(x, y);", "_____no_output_____" ] ], [ [ "Si ajustamos una recta a los datos usando ``LinearRegression`` obtendremos un resultado óptimo:", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LinearRegression\nX = x[:, np.newaxis]\nmodel = LinearRegression().fit(X, y)\nyfit = model.predict(X)\nplt.scatter(x, y)\nplt.plot(x, yfit);", "_____no_output_____" ] ], [ [ "Es óptimo, pero también queda claro que necesitamos un modelo más sofisticado para describir la relació entre $x$ e $y$.\n\nUna manera de lograrlo es transformando los datos, agregando columnas o características adicionales que le den más flexibilidad al modelo. Por ejemplo, podemos agregar características polinomiales de la siguiente forma:", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import PolynomialFeatures\npoly = PolynomialFeatures(degree=3, include_bias=False)\nX2 = poly.fit_transform(X)\nprint(X2)", "[[ 1. 1. 1.]\n [ 2. 4. 8.]\n [ 3. 9. 27.]\n [ 4. 16. 64.]\n [ 5. 25. 125.]]\n" ] ], [ [ "Esta matriz de características _derivada_ tiene una columna que representa a $x$, una segunda columna que representa $x^2$, y una tercera que representa $x^3$.\nCalcular una regresión lineal en esta entrada da un ajuste más cercano a nuestros datos:", "_____no_output_____" ] ], [ [ "model = LinearRegression().fit(X2, y)\nyfit = model.predict(X2)\nplt.scatter(x, y)\nplt.plot(x, yfit);", "_____no_output_____" ] ], [ [ "La idea de mejorar un modelo sin cambiarlo, sino que transformando la entrada que recibe, es fundamental para muchas de las técnicas de machine learning más poderosas.\nExploraremos más esta idea en la clase de Regresión Lineal. \nEste camino es motivante y se puede generalizar con las técnicas conocidas como _métodos de kernel_, que exploraremos en la clase de _Support Vector Machines_ (SVM).", "_____no_output_____" ], [ "## Imputación de Datos Faltantes\n\nUna necesidad común en la ingeniería de características es la manipulación de datos faltantes.\nEn clases anteriores es posible que hayan visto el valor `NaN` en un `DataFrame`, utilizado para marcar valores que no existen.\nPor ejemplo, podríamos tener un dataset que se vea así:", "_____no_output_____" ] ], [ [ "from numpy import nan\nX = np.array([[ nan, 0, 3 ],\n [ 3, 7, 9 ],\n [ 3, 5, 2 ],\n [ 4, nan, 6 ],\n [ 8, 8, 1 ]])\ny = np.array([14, 16, -1, 8, -5])", "_____no_output_____" ] ], [ [ "Antes de aplicar un modelo a estos datos necesitamos reemplazar esos datos faltantes con algún valor apropiado de relleno.\nEsto es conocido como _imputación_ de valores faltantes, y las estrategias para hacerlo varían desde las más simples (como rellenar con el promedio de cada columna) hasta las más sofisticadas (como completar la matrix con un modelo robusto para esos casos). Estos últimos enfoques suelen ser específicos para cada aplicación, así que no los veremos en el curso.\n\nLa clase `Imputer` de Scikit-Learn provee en enfoque base de imputación que calcula el promedio, la media, o el valor más frecuente:", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import Imputer\nimp = Imputer(strategy='mean')\nX2 = imp.fit_transform(X)\nX2", "_____no_output_____" ] ], [ [ "Como vemos, al aplicar el imputador los dos valores que faltaban fueron reemplazados por el promedio de los valores presentes en las columnas respectivas. \nAhora que tenemos una matriz sin valores faltantes, podemos usarla con la instancia de un modelo, en este caso, una regresión lineal:", "_____no_output_____" ] ], [ [ "model = LinearRegression().fit(X2, y)\nmodel.predict(X2)", "_____no_output_____" ] ], [ [ "## Cadena de Procesamiento (_Pipeline_)\n\nConsiderando los ejemplos que hemos visto, es posible que sea tedioso hacer cada una de estas transformaciones a mano. En ocasiones querremos automatizar la cadena de procesamiento para un modelo. Imagina una secuencia como la siguiente:\n\n1. Imputar valores usando el promedio.\n2. Transformar las características incluyendo un factor cuadrático.\n3. Ajustar una regresión lineal.\n\nPara encadenar estas etapas Scikit-Learn provee una clase ``Pipeline``, que se usa como sigue:", "_____no_output_____" ] ], [ [ "from sklearn.pipeline import make_pipeline\n\nmodel = make_pipeline(Imputer(strategy='mean'),\n PolynomialFeatures(degree=2),\n LinearRegression())", "_____no_output_____" ] ], [ [ "Esta cadena o _pipeline_ se ve y actúa como un objeto estándar de Scikit-Learn, por lo que podemos utilizarla en todo lo que hemos visto hasta ahora que siga la receta de uso de Scikit-Learn.", "_____no_output_____" ] ], [ [ "model.fit(X, y) # X con valores faltantes\nprint(y)\nprint(model.predict(X))", "[14 16 -1 8 -5]\n[14. 16. -1. 8. -5.]\n" ] ], [ [ "Todos los pasos del modelo se aplican de manera automática.\n\n¡Ojo! Por simplicidad hemos aplicado el modelo a los mismos datos con los que lo hemos entrenado, por eso el resultado es perfecto (vean el material de la clase pasada para recordar por qué esto no es un buen criterio para evaluar el modelo).\n\nEn las próximas clases seguiremos utilizando _Pipelines_ para estructurar nuestro análisis.", "_____no_output_____" ], [ "![](figures/PDSH-cover.png)\n\nEste notebook contiene un extracto del libro [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) por Jake VanderPlas; el contenido también está disponible en [GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).\n\nEl texto se distribuye bajo una licencia [CC-BY-NC-ND](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), y el código se distribuye bajo la licencia [MIT](https://opensource.org/licenses/MIT). Si te parece que este contenido es útil, por favor considera apoyar el trabajo [comprando el libro](http://shop.oreilly.com/product/0636920034919.do).\n\nTraducción al castellano por [Eduardo Graells-Garrido](http://datagramas.cl), liberada bajo las mismas condiciones.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "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" ], [ "code" ], [ "markdown", "markdown" ] ]
d00e99de383f5fb306540ec8d80ba2e5c712c61a
52,646
ipynb
Jupyter Notebook
VGG16_CIFAR10.ipynb
UdbhavPrasad072300/CPS803_Final_Project
8ccf14705026c315fde87bc1e2728e27cf8cf5ff
[ "MIT" ]
2
2021-09-10T01:01:38.000Z
2021-09-20T17:15:06.000Z
VGG16_CIFAR10.ipynb
UdbhavPrasad072300/CPS803_Final_Project
8ccf14705026c315fde87bc1e2728e27cf8cf5ff
[ "MIT" ]
null
null
null
VGG16_CIFAR10.ipynb
UdbhavPrasad072300/CPS803_Final_Project
8ccf14705026c315fde87bc1e2728e27cf8cf5ff
[ "MIT" ]
null
null
null
87.597338
16,556
0.751396
[ [ [ "# Pre-training VGG16 for Distillation", "_____no_output_____" ] ], [ [ "import torch \nimport torch.nn as nn\n\nfrom src.data.dataset import get_dataloader\n\nimport torchvision.transforms as transforms\n\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(DEVICE)", "cuda\n" ], [ "SEED = 0\n\nBATCH_SIZE = 32\nLR = 5e-4\nNUM_EPOCHES = 25", "_____no_output_____" ], [ "np.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.cuda.manual_seed(SEED)\ntorch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.deterministic = True", "_____no_output_____" ] ], [ [ "## Preprocessing", "_____no_output_____" ] ], [ [ "transform = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n #transforms.RandomVerticalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))\n])", "_____no_output_____" ], [ "train_loader, val_loader, test_loader = get_dataloader(\"./data/CIFAR10/\", BATCH_SIZE)", "Files already downloaded and verified\nFiles already downloaded and verified\n" ] ], [ [ "## Model", "_____no_output_____" ] ], [ [ "from src.models.model import VGG16_classifier", "_____no_output_____" ], [ "classes = 10\nhidden_size = 512\ndropout = 0.3\n\nmodel = VGG16_classifier(classes, hidden_size, preprocess_flag=False, dropout=dropout).to(DEVICE)\nmodel", "_____no_output_____" ], [ "for img, label in train_loader:\n img = img.to(DEVICE)\n label = label.to(DEVICE)\n \n print(\"Input Image Dimensions: {}\".format(img.size()))\n print(\"Label Dimensions: {}\".format(label.size()))\n print(\"-\"*100)\n \n out = model(img)\n \n print(\"Output Dimensions: {}\".format(out.size()))\n break", "Input Image Dimensions: torch.Size([32, 3, 32, 32])\nLabel Dimensions: torch.Size([32])\n----------------------------------------------------------------------------------------------------\n" ] ], [ [ "## Training", "_____no_output_____" ] ], [ [ "criterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(params=model.parameters(), lr=LR)", "_____no_output_____" ], [ "loss_hist = {\"train accuracy\": [], \"train loss\": [], \"val accuracy\": []}\n\nfor epoch in range(1, NUM_EPOCHES+1):\n model.train()\n \n epoch_train_loss = 0\n \n y_true_train = []\n y_pred_train = []\n \n for batch_idx, (img, labels) in enumerate(train_loader):\n img = img.to(DEVICE)\n labels = labels.to(DEVICE)\n \n preds = model(img)\n \n loss = criterion(preds, labels)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n y_pred_train.extend(preds.detach().argmax(dim=-1).tolist())\n y_true_train.extend(labels.detach().tolist())\n \n epoch_train_loss += loss.item()\n\n with torch.no_grad():\n model.eval()\n\n y_true_test = []\n y_pred_test = []\n\n for batch_idx, (img, labels) in enumerate(val_loader):\n img = img.to(DEVICE)\n label = label.to(DEVICE)\n\n preds = model(img)\n\n y_pred_test.extend(preds.detach().argmax(dim=-1).tolist())\n y_true_test.extend(labels.detach().tolist())\n\n test_total_correct = len([True for x, y in zip(y_pred_test, y_true_test) if x==y])\n test_total = len(y_pred_test)\n test_accuracy = test_total_correct * 100 / test_total\n \n loss_hist[\"train loss\"].append(epoch_train_loss)\n\n total_correct = len([True for x, y in zip(y_pred_train, y_true_train) if x==y])\n total = len(y_pred_train)\n accuracy = total_correct * 100 / total\n \n loss_hist[\"train accuracy\"].append(accuracy)\n loss_hist[\"val accuracy\"].append(test_accuracy)\n \n print(\"-------------------------------------------------\")\n print(\"Epoch: {} Train mean loss: {:.8f}\".format(epoch, epoch_train_loss))\n print(\" Train Accuracy%: \", accuracy, \"==\", total_correct, \"/\", total)\n print(\" Validation Accuracy%: \", test_accuracy, \"==\", test_total_correct, \"/\", test_total)\n print(\"-------------------------------------------------\")", "-------------------------------------------------\nEpoch: 1 Train mean loss: 2339.36016971\n Train Accuracy%: 39.394 == 19697 / 50000\n Validation Accuracy%: 58.94 == 2947 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 2 Train mean loss: 1438.08532357\n Train Accuracy%: 69.244 == 34622 / 50000\n Validation Accuracy%: 74.02 == 3701 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 3 Train mean loss: 1072.54530132\n Train Accuracy%: 78.84 == 39420 / 50000\n Validation Accuracy%: 72.7 == 3635 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 4 Train mean loss: 907.63304938\n Train Accuracy%: 82.384 == 41192 / 50000\n Validation Accuracy%: 79.96 == 3998 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 5 Train mean loss: 761.87718780\n Train Accuracy%: 85.84 == 42920 / 50000\n Validation Accuracy%: 78.86 == 3943 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 6 Train mean loss: 718.01751248\n Train Accuracy%: 86.67 == 43335 / 50000\n Validation Accuracy%: 80.56 == 4028 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 7 Train mean loss: 648.26146014\n Train Accuracy%: 87.85 == 43925 / 50000\n Validation Accuracy%: 80.4 == 4020 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 8 Train mean loss: 562.79290721\n Train Accuracy%: 89.456 == 44728 / 50000\n Validation Accuracy%: 82.54 == 4127 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 9 Train mean loss: 473.16751064\n Train Accuracy%: 91.106 == 45553 / 50000\n Validation Accuracy%: 80.64 == 4032 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 10 Train mean loss: 464.82368950\n Train Accuracy%: 91.514 == 45757 / 50000\n Validation Accuracy%: 83.52 == 4176 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 11 Train mean loss: 467.99637549\n Train Accuracy%: 91.622 == 45811 / 50000\n Validation Accuracy%: 83.34 == 4167 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 12 Train mean loss: 393.67967687\n Train Accuracy%: 93.106 == 46553 / 50000\n Validation Accuracy%: 81.48 == 4074 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 13 Train mean loss: 472.65135630\n Train Accuracy%: 91.76 == 45880 / 50000\n Validation Accuracy%: 82.14 == 4107 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 14 Train mean loss: 547.69220992\n Train Accuracy%: 90.29 == 45145 / 50000\n Validation Accuracy%: 83.0 == 4150 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 15 Train mean loss: 361.64964305\n Train Accuracy%: 93.574 == 46787 / 50000\n Validation Accuracy%: 83.78 == 4189 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 16 Train mean loss: 363.55912426\n Train Accuracy%: 93.738 == 46869 / 50000\n Validation Accuracy%: 82.42 == 4121 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 17 Train mean loss: 370.34851927\n Train Accuracy%: 93.69 == 46845 / 50000\n Validation Accuracy%: 84.9 == 4245 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 18 Train mean loss: 436.99898854\n Train Accuracy%: 92.502 == 46251 / 50000\n Validation Accuracy%: 84.16 == 4208 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 19 Train mean loss: 416.98351576\n Train Accuracy%: 93.054 == 46527 / 50000\n Validation Accuracy%: 81.48 == 4074 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 20 Train mean loss: 346.36397807\n Train Accuracy%: 93.966 == 46983 / 50000\n Validation Accuracy%: 84.64 == 4232 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 21 Train mean loss: 296.34467645\n Train Accuracy%: 95.288 == 47644 / 50000\n Validation Accuracy%: 83.92 == 4196 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 22 Train mean loss: 310.18968987\n Train Accuracy%: 94.836 == 47418 / 50000\n Validation Accuracy%: 82.22 == 4111 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 23 Train mean loss: 544.12305131\n Train Accuracy%: 90.344 == 45172 / 50000\n Validation Accuracy%: 81.48 == 4074 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 24 Train mean loss: 507.90272054\n Train Accuracy%: 91.288 == 45644 / 50000\n Validation Accuracy%: 84.06 == 4203 / 5000\n-------------------------------------------------\n-------------------------------------------------\nEpoch: 25 Train mean loss: 377.94273479\n Train Accuracy%: 93.646 == 46823 / 50000\n Validation Accuracy%: 80.68 == 4034 / 5000\n-------------------------------------------------\n" ], [ "plt.plot(loss_hist[\"train accuracy\"])\nplt.plot(loss_hist[\"val accuracy\"])\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.show()", "_____no_output_____" ], [ "plt.plot(loss_hist[\"train loss\"])\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.show()", "_____no_output_____" ] ], [ [ "## Testing", "_____no_output_____" ] ], [ [ "with torch.no_grad():\n model.eval()\n \n y_true_test = []\n y_pred_test = []\n \n for batch_idx, (img, labels) in enumerate(test_loader):\n img = img.to(DEVICE)\n label = label.to(DEVICE)\n \n preds = model(img)\n \n y_pred_test.extend(preds.detach().argmax(dim=-1).tolist())\n y_true_test.extend(labels.detach().tolist())\n \n total_correct = len([True for x, y in zip(y_pred_test, y_true_test) if x==y])\n total = len(y_pred_test)\n accuracy = total_correct * 100 / total\n \n print(\"Test Accuracy%: \", accuracy, \"==\", total_correct, \"/\", total)", "Test Accuracy%: 81.04 == 4052 / 5000\n" ] ], [ [ "## Saving Model Weights ", "_____no_output_____" ] ], [ [ "torch.save(model.state_dict(), \"./trained_models/vgg16_cifar10.pt\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d00ea0e586e161630774859f280a662ad1b17a3f
83,220
ipynb
Jupyter Notebook
src/test/datascience/notebook/withOutputForTrust.ipynb
jakebailey/vscode-jupyter
3d558a3e23e4664d8e7b76f01ef9acb258f1c068
[ "MIT" ]
615
2020-11-11T22:55:28.000Z
2022-03-30T21:48:08.000Z
src/test/datascience/notebook/withOutputForTrust.ipynb
jakebailey/vscode-jupyter
3d558a3e23e4664d8e7b76f01ef9acb258f1c068
[ "MIT" ]
8,428
2020-11-11T22:06:43.000Z
2022-03-31T23:42:34.000Z
src/test/datascience/notebook/withOutputForTrust.ipynb
jakebailey/vscode-jupyter
3d558a3e23e4664d8e7b76f01ef9acb258f1c068
[ "MIT" ]
158
2020-11-12T07:49:02.000Z
2022-03-27T20:50:20.000Z
61.598816
26,272
0.621293
[ [ [ "pip list", "Package Version \n-------------------- ----------\nadal 1.2.2 \naltair 4.1.0 \nappdirs 1.4.3 \nappnope 0.1.0 \nattrs 19.3.0 \nazure-common 1.1.25 \nazure-kusto-data 0.0.44 \nazure-kusto-ingest 0.0.44 \nazure-storage-blob 2.1.0 \nazure-storage-common 2.1.0 \nazure-storage-queue 2.1.0 \nbackcall 0.1.0 \nbeakerx 1.4.1 \nblack 19.10b0 \nbleach 3.1.4 \nbqplot 0.12.6 \nbranca 0.3.1 \ncertifi 2020.4.5.1\ncffi 1.14.0 \nchardet 3.0.4 \nclick 7.1.2 \ncryptography 2.9.2 \ncycler 0.10.0 \ndebugpy 1.0.0b7 \ndecorator 4.4.2 \ndefusedxml 0.6.0 \nentrypoints 0.3 \nidna 2.9 \nipydatawidgets 4.0.1 \nipykernel 5.2.1 \nipyleaflet 0.12.4 \nipython 7.13.0 \nipython-genutils 0.2.0 \nipyvolume 0.5.2 \nipywebrtc 0.5.0 \nipywidgets 7.5.1 \nisodate 0.6.0 \njedi 0.17.0 \nJinja2 2.11.2 \njson5 0.9.5 \njsonschema 3.2.0 \njupyter-client 6.1.3 \njupyter-core 4.6.3 \njupyterlab 2.1.3 \njupyterlab-server 1.1.5 \nK3D 2.7.4 \nkiwisolver 1.2.0 \nMarkupSafe 1.1.1 \nmatplotlib 3.2.1 \nmistune 0.8.4 \nmsrest 0.6.13 \nmsrestazure 0.6.3 \nnbconvert 5.6.1 \nnbformat 5.0.5 \nnglview 2.7.5 \nnotebook 6.0.3 \nnumpy 1.18.2 \noauthlib 3.1.0 \npandas 1.0.3 \npandocfilters 1.4.2 \nparso 0.7.0 \npathspec 0.8.0 \npexpect 4.8.0 \npickleshare 0.7.5 \nPillow 7.1.1 \npip 19.2.3 \nprometheus-client 0.7.1 \nprompt-toolkit 3.0.5 \nptyprocess 0.6.0 \npy4j 0.10.9 \npycparser 2.20 \nPygments 2.6.1 \nPyJWT 1.7.1 \npyparsing 2.4.7 \npyrsistent 0.16.0 \npython-dateutil 2.8.1 \npythreejs 2.2.0 \npytz 2019.3 \npyzmq 19.0.0 \nqgrid 1.1.1 \nregex 2020.4.4 \nrequests 2.23.0 \nrequests-oauthlib 1.3.0 \nSend2Trash 1.5.0 \nsetuptools 41.2.0 \nsix 1.14.0 \nterminado 0.8.3 \ntestpath 0.4.4 \ntoml 0.10.0 \ntoolz 0.10.0 \ntornado 6.0.4 \ntraitlets 4.3.3 \ntraittypes 0.2.1 \ntyped-ast 1.4.1 \nurllib3 1.25.9 \nvega-datasets 0.8.0 \nwcwidth 0.1.9 \nwebencodings 0.5.1 \nwidgetsnbextension 3.5.1 \nxarray 0.15.1 \nNote: you may need to restart the kernel to use updated packages.\n" ] ], [ [ "# HELLO WORLD", "_____no_output_____" ] ], [ [ "with Error", "_____no_output_____" ], [ "import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nt = np.arange(0.0, 2.0, 0.01)\ns = 1 + np.sin(2 * np.pi * t)\n\nfig, ax = plt.subplots()\nax.plot(t, s)\n\nax.set(xlabel='time (s)', ylabel='voltage (mV)',\n title='About as simple as it gets, folks')\n\nax.grid()\n\nfig.savefig('test.png')\n\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d00eabf037df9c6b1ff2bc071139e09d138fe737
10,965
ipynb
Jupyter Notebook
SQLLiteDBConnection/workingWithSQLLiteDB.ipynb
Snigdha171/PythonMiniProgramSeries
ce1c734a13362f16278714c9c6ba2a196f9e03b2
[ "Apache-2.0" ]
2
2021-01-21T11:01:30.000Z
2021-05-07T17:13:52.000Z
SQLLiteDBConnection/workingWithSQLLiteDB.ipynb
Snigdha171/PythonMiniProgramSeries
ce1c734a13362f16278714c9c6ba2a196f9e03b2
[ "Apache-2.0" ]
null
null
null
SQLLiteDBConnection/workingWithSQLLiteDB.ipynb
Snigdha171/PythonMiniProgramSeries
ce1c734a13362f16278714c9c6ba2a196f9e03b2
[ "Apache-2.0" ]
8
2020-10-29T18:02:19.000Z
2022-03-06T14:01:07.000Z
40.611111
199
0.61596
[ [ [ "# _Mini Program - Working with SQLLite DB using Python_\n\n### <font color=green>Objective -</font>\n<font color=blue>1. This program gives an idea how to connect with SQLLite DB using Python and perform data manipulation </font><br>\n\n<font color=blue>2. There are 2 ways in which tables are create below to help you understand the robustness of this language</font>", "_____no_output_____" ], [ "### <font color=green>Step 1 - Import required libraries</font>\n#### <font color=blue>In this program we make used of 3 libraries</font>\n#### <font color=blue>1. sqlite3 - This module help to work with sql interface. It helps in performing db operations in sqllite database</font>\n#### <font color=blue>2. pandas - This module provides high performance and easy to use data manipulation and data analysis functionalities</font>\n#### <font color=blue>3. os - This module provides function to interact with operating system with easy use</font>\n \n", "_____no_output_____" ] ], [ [ "#Importing the required modules\nimport sqlite3\nimport pandas as pd\nimport os", "_____no_output_____" ] ], [ [ "### <font color=green>Step 2 - Creating a function to drop the table</font>\n#### <font color=blue>Function helps to re-create a reusable component that can be used conviniently and easily in other part of the code</font>\n#### <font color=blue>In Line 1 - We state the function name and specify the parameter being passed. In this case, the parameter is the table name</font>\n#### <font color=blue>In Line 2 - We write the sql query to be executed</font>\n#### <font color=blue>In Line 3 - We execute the query using the cursor object</font>", "_____no_output_____" ] ], [ [ "#Creating a function to drop the table if it exists\ndef dropTbl(tablename):\n dropTblStmt = \"DROP TABLE IF EXISTS \" + tablename\n c.execute(dropTblStmt)", "_____no_output_____" ] ], [ [ "### <font color=green>Step 3 - We create the database in which our table will reside</font>\n#### <font color=blue>In Line 1 - We are removing the already existing database file</font>\n#### <font color=blue>In Line 2 - We use connect function from the sqlite3 module to create a database studentGrades.db and establish a connection</font>\n#### <font color=blue>In Line 3 - We create a context of the database connection. This help to run all the database queries</font>", "_____no_output_____" ] ], [ [ "#Removing the database file\nos.remove('studentGrades.db')\n\n#Creating a new database - studentGrades.db\nconn = sqlite3.connect(\"studentGrades.db\")\nc = conn.cursor()", "_____no_output_____" ] ], [ [ "### <font color=green>Step 4 - We create a table in sqllite DB using data defined in the excel file</font>\n#### <font color=blue>This is the first method in which you can create a table. You can use to_sql function directly to read a dataframe and dump all it's content to the table</font>\n#### <font color=blue>In Line 1 - We are making use of dropTbl function created above to drop the table</font>\n#### <font color=blue>In Line 2 - We are creating a dataframe from the data read from the csv</font>\n#### <font color=blue>In Line 3 - We use to_sql function to push the data into the table. The first row of the file becomes the column name of the tables</font>\n#### <font color=blue>We repeat the above steps for all the 3 files to create 3 tables - STUDENT, GRADES and SUBJECTS</font>", "_____no_output_____" ] ], [ [ "#Reading data from csv file - student details, grades and subject\ndropTbl('STUDENT')\nstudent_details = pd.read_csv(\"Datafiles/studentDetails.csv\")\nstudent_details.to_sql('STUDENT',conn,index = False)\n\ndropTbl('GRADES')\nstudent_grades = pd.read_csv('Datafiles/studentGrades.csv')\nstudent_grades.to_sql('GRADES',conn,index = False)\n\ndropTbl('SUBJECTS')\nsubjects = pd.read_csv(\"Datafiles/subjects.csv\")\nsubjects.to_sql('SUBJECTS',conn,index = False)", "_____no_output_____" ] ], [ [ "### <font color=green>Step 5 - We create a master table STUDENT_GRADE_MASTER where we can colate the data from the individual tables by performing the joining operations</font>\n#### <font color=blue>In Line 1 - We are making use of dropTbl function created above to drop the table</font>\n#### <font color=blue>In Line 2 - We are writing sql query for table creation</font>\n#### <font color=blue>In Line 3 - We are using the cursor created above to execute the sql statement</font>\n#### <font color=blue>In Line 4 - We are using the second method of inserting data into the table. We are writing a query to insert the data after joining the data from all the tables</font>\n#### <font color=blue>In Line 5 - We are using the cursor created above to execute the sql statement</font>\n#### <font color=blue>In Line 6 - We are doing a commit operation. Since INSERT operation is a ddl, we have to perform a commit operation to register it into the database</font>", "_____no_output_____" ] ], [ [ "#Creating a table to store student master data\ndropTbl('STUDENT_GRADE_MASTER')\ncreateTblStmt = '''CREATE TABLE STUDENT_GRADE_MASTER\n ([Roll_number] INTEGER,\n [Student_Name] TEXT,\n [Stream] TEXT,\n [Subject] TEXT,\n [Marks] INTEGER\n )'''\nc.execute(createTblStmt)\n\n#Inserting data into the master table by joining the tables mentioned above\nqueryMaster = '''INSERT INTO STUDENT_GRADE_MASTER(Roll_number,Student_Name,Stream,Subject,Marks)\n SELECT g.roll_number, s.student_name, stream, sub.subject, marks from GRADES g \n LEFT OUTER JOIN STUDENT s on g.roll_number = s.roll_number\n LEFT OUTER JOIN SUBJECTS sub on g.subject_code = sub.subject_code'''\n\nc.execute(queryMaster)\nc.execute(\"COMMIT\")", "_____no_output_____" ] ], [ [ "### <font color=green>Step 6 - We can perform data fetch like we do in sqls using this sqlite3 module</font>\n#### <font color=blue>In Line 1 - We are writing a query to find the number of records in the master table</font>\n#### <font color=blue>In Line 2 - We are executing the above created query</font>\n#### <font color=blue>In Line 3 - fetchall function is used to get the result returned by the query. The result will be in the form of a list of tuples</font>\n#### <font color=blue>In Line 4 - We are writing another query to find the maximum marks recorded for each subject</font>\n#### <font color=blue>In Line 5 - We are executing the above created query</font>\n#### <font color=blue>In Line 6 - fetchall function is used to get the result returned by the query. The result will be in the form of a list of tuples</font>\n#### <font color=blue>In Line 7 - We are writing another query to find the percentage of marks obtained by each student in the class</font>\n#### <font color=blue>In Line 8 - We are executing the above created query</font>\n#### <font color=blue>In Line 9 - fetchall function is used to get the result returned by the query. The result will be in the form of a list of tuples</font>", "_____no_output_____" ] ], [ [ "#Finding the key data from the master table\n\n#1. Find the number of records in the master table\nquery_count = '''SELECT COUNT(*) FROM STUDENT_GRADE_MASTER'''\nc.execute(query_count)\nnumber_of_records = c.fetchall()\nprint(number_of_records)\n\n#2. Maximum marks for each subject\nquery_max_marks = '''SELECT Subject,max(Marks) as 'Max_Marks' from STUDENT_GRADE_MASTER GROUP BY Subject'''\nc.execute(query_max_marks)\nmax_marks_data = c.fetchall()\nprint(max_marks_data)\n\n#3. Percenatge of marks scored by each student\nquery_percentage = '''SELECT Student_Name, avg(Marks) as 'Percentage' from STUDENT_GRADE_MASTER GROUP BY Student_Name'''\nc.execute(query_percentage)\npercentage_data = c.fetchall()\nprint(percentage_data)\n", "[(20,)]\n[('C', 97), ('C++', 95), ('Environmental studies', 92), ('Java', 96), ('Maths', 98)]\n[('Abhishek', 94.2), ('Anand', 85.2), ('Sourabh', 89.0), ('Vivek', 84.8)]\n" ] ], [ [ "### <font color=green>Step 7 - We are closing the database connection</font>\n#### <font color=blue>It is always a good practice to close the database connection after all the operations are completed</font>", "_____no_output_____" ] ], [ [ "#Closing the connection\nconn.close()", "_____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" ] ]
d00eb5924480c493155c20633690c241ffad153d
8,056
ipynb
Jupyter Notebook
TALLER1.ipynb
AngieCat26/MujeresDigitales
64d0da0a4d31c60f70d4a3209d0fcb54884ea2b6
[ "MIT" ]
null
null
null
TALLER1.ipynb
AngieCat26/MujeresDigitales
64d0da0a4d31c60f70d4a3209d0fcb54884ea2b6
[ "MIT" ]
null
null
null
TALLER1.ipynb
AngieCat26/MujeresDigitales
64d0da0a4d31c60f70d4a3209d0fcb54884ea2b6
[ "MIT" ]
null
null
null
43.311828
231
0.52495
[ [ [ "<a href=\"https://colab.research.google.com/github/AngieCat26/MujeresDigitales/blob/main/TALLER1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "**PUNTO 2 **", "_____no_output_____" ] ], [ [ "premio1 = \"Viaje todo incluído para dos personas a San Andrés\"\npremio2 = \"una pasadía a los termales de San Vicente incluyendo almuerzo\"\npremio3 = \"Viaje todo incluido para dos personas a Santa Marta\"\npremio4 = \"Pasadía al desierto de Tatacoa (Sin incluír alimentación)\"\n\n\nrosada = premio1\nverde = premio2\nazul = premio3\ngris = premio4\nroja = \"No hay premio\"\n\n\ncliente = input(\"por favor digite el nombre del concursante \")\nbalota = input(\"Digite el color de la balota \")\nvalorVariable = int(input(\"Digite un valor variable \"))\n\n\nantiguedad = int(input(\"Digite los años de antiguedad del cliente \"))\nreferidos = int(input(\"Digite los referidos del cliente \"))\nliderazgo = input(\"¿El cliente tiene liderazgo en los programas de cooperación de viajes internos? \")\n\n\n\nif balota == \"rosada\":\n print(\"La empresa VIVAFLY se complace en anunciar que La participante \",cliente,\" ganó un \", rosada, \" en nuestro sorteo de viajes de AMOR y AMISTAD\")\n valorVariable1 = valorVariable * 0.15\n if valorVariable < 120000:\n print(\"El cliente \",cliente,\" también recibirá dos boletas de cine 4D con un combo de palomitas\")\n else :\n print(\"El cliente \", cliente, \" también recibirá un bono de $\",valorVariable1)\n\n \nelif balota == \"verde\":\n print(\"La empresa VIVAFLY se complace en anunciar que La participante \",cliente,\" ganó \", verde, \" en nuestro sorteo de viajes de AMOR y AMISTAD\")\n valorVariable2 = valorVariable * 0.20\n if valorVariable < 120000:\n print(\"El cliente \",cliente,\" también recibirá dos boletas de cine 4D con un combo de palomitas\")\n else :\n print(\"El cliente \", cliente, \" también recibirá un bono de $\",valorVariable2)\n\n\nelif balota == \"azul\":\n print(\"La empresa VIVAFLY se complace en anunciar que La participante \",cliente,\" ganó \", azul, \" en nuestro sorteo de viajes de AMOR y AMISTAD\")\n valorVariable3 = valorVariable * 0.05\n if valorVariable < 120000:\n print(\"El cliente \",cliente,\" también recibirá dos boletas de cine 4D con un combo de palomitas\")\n else :\n print(\"El cliente \", cliente, \" también recibirá un bono de $\",valorVariable3)\n\n\nelif balota == \"gris\":\n print(\"La empresa VIVAFLY se complace en anunciar que La participante \",cliente,\" ganó \", gris, \" en nuestro sorteo de viajes de AMOR y AMISTAD\")\n valorVariable4 = valorVariable * 0.20\n if valorVariable < 120000:\n print(\"El cliente \",cliente,\" también recibirá dos boletas de cine 4D con un combo de palomitas\")\n else :\n print(\"El cliente \", cliente, \" también recibirá un bono de $\",valorVariable4)\n\nelse :\n print(\"La empresa VIVAFLY se complace en anunciar que La participante \",cliente,\" ganó $120.000\")\n\n\n\n#si se cumple los 3:\n\nif antiguedad > 10 and referidos > 10 and liderazgo == \"si\" :\n puntos = valorVariable * 0.50\n print(\"Adicionalmente:\")\n if puntos > 600000 : \n puntos = 500 * 0.20 \n print(\"Se le otorga \",puntos, \" puntos para redimir en un premio a futuro\")\n else :\n puntos = 250 * 0.20 \n print(\"Se le otorga \", puntos, \" puntos para redimir en un premio a futuro\")\n\n#Si se cumple solo dos requisitos:\n\nelif antiguedad > 10 and referidos > 10 :\n puntos = valorVariable * 0.50\n print(\"Adicionalmente: \")\n if puntos > 250000 :\n puntos = 200 * 0.20 \n print(\"Se le otorga \", puntos, \" puntos para redimir en un premio a futuro\")\n else :\n puntos = 50 * 0.20 \n print(\"Se le otorga \", puntos, \" puntos para redimir en un premio a futuro\")\n\nelif antiguedad > 10 and liderazgo == \"si\" :\n puntos = valorVariable * 0.50\n print(\"Adicionalmente: \")\n if puntos > 250000 : \n puntos = 200 * 0.20 \n print(\"Se le otorga \", puntos, \" puntos para redimir en un premio a futuro\")\n else :\n puntos = 50 * 0.20 \n print(\"Se le otorga \", puntos, \"puntos para redimir en un premio a futuro\")\n\nelif referidos > 10 and liderazgo ==\"si\" :\n puntos = valorVariable * 0.30\n print(\"Adicionalmente: \")\n if puntos > 250000 : \n puntos = 200 * 0.20 \n print(\"Se le otorga 200 puntos para redimir en un premio a futuro\")\n else :\n puntos = 50 * 0.20 \n print(\"Se le otorga 50 puntos para redimir en un premio a futuro\")\n\n\n#Solo si se cumple uno\nelse : \n puntos = valorVariable * 0.10\n puntos = puntos * 0.10\n print(\"Adicionalmente se se le otorga\", puntos, \"puntos para redimir en un premio a futuro\")\n", "por favor digite el nombre del concursante Angie\nDigite el color de la balota rosada\nDigite un valor variable 2000000\nDigite los años de antiguedad del cliente 14\nDigite los referidos del cliente 1\n¿El cliente tiene liderazgo en los programas de cooperación de viajes internos? si\nLa empresa VIVAFLY se complace en anunciar que La participante Angie ganó un Viaje todo incluído para dos personas a San Andrés en nuestro sorteo de viajes de AMOR y AMISTAD\nEl cliente Angie también recibirá un bono de $ 300000.0\nAdicionalmente: \nSe le otorga 40.0 puntos para redimir en un premio a futuro\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ] ]
d00ec1040dad5fbae7939a2dd7285d06d8f75e9c
79,526
ipynb
Jupyter Notebook
tutorial/tutorial.ipynb
piotrfratczak/fifa_preprocessing
18f0cd25b0b7ec4812237816129ee5f0f92c8546
[ "MIT" ]
null
null
null
tutorial/tutorial.ipynb
piotrfratczak/fifa_preprocessing
18f0cd25b0b7ec4812237816129ee5f0f92c8546
[ "MIT" ]
null
null
null
tutorial/tutorial.ipynb
piotrfratczak/fifa_preprocessing
18f0cd25b0b7ec4812237816129ee5f0f92c8546
[ "MIT" ]
null
null
null
31.125636
320
0.315658
[ [ [ "# Tutorial\n#### This tutorial will introduce you to the *fifa_preprocessing*'s functionality!\nIn general, the following functions will alow you to preprocess your data to be able to perform machine learning or statistical data analysis by reformatting, casting or deleting certain values.", "_____no_output_____" ], [ "The data used in these examples comes from https://www.kaggle.com/karangadiya/fifa19, a webpage this package was inspired by. The module's functions work best with this data set, however, they will work with any data structured in a similar manner.", "_____no_output_____" ], [ "## Prerequisites", "_____no_output_____" ], [ "First, import the fifa_preprocessing, pandas and math modules:", "_____no_output_____" ] ], [ [ "import fifa_preprocessing as fp\nimport pandas as pd\nimport math", "_____no_output_____" ] ], [ [ "Load your data:", "_____no_output_____" ] ], [ [ "data = pd.read_csv('data.csv')", "_____no_output_____" ], [ "data", "_____no_output_____" ] ], [ [ "## Exclude goalkeepers\nBefore any preprocessing, the data contains all the players.", "_____no_output_____" ] ], [ [ "data[['Name', 'Position']]", "_____no_output_____" ] ], [ [ "This command will exclude goalkeepers from your data set (i.e. delete all the rows where column 'Position' is equal to 'GK'):", "_____no_output_____" ] ], [ [ "data = fp.exclude_goalkeepers(data)", "_____no_output_____" ] ], [ [ "As you may notice, the row number 3 was deleted.", "_____no_output_____" ] ], [ [ "data[['Name', 'Position']]", "_____no_output_____" ] ], [ [ "## Format currencies\nTo remove unnecessary characters form a monetary value use:", "_____no_output_____" ] ], [ [ "money = '€23.4M'\nfp.money_format(money)", "_____no_output_____" ] ], [ [ "The value will be expressed in thousands of euros:", "_____no_output_____" ] ], [ [ "money = '€7K'\nfp.money_format(money)", "_____no_output_____" ] ], [ [ "## Format players' rating\nIn FIFA players get a ranking on they skills on the pitch. The ranking is represented as a sum of two integers.\nThe following function lets you take in a string containing two numbers separated by a '+' and get the actual sum:", "_____no_output_____" ] ], [ [ "rating = '81+3'\nfp.rating_format(rating)", "_____no_output_____" ] ], [ [ "## Format players' work rate\nThe next function takes in a qualitative parameter that could be expressed as a quantitive value.\nIf you have a data set where one category is expressed as 'High', 'Medium' or 'Low', this function will assign numbers to these values (2, 1 and 0 respectively):", "_____no_output_____" ] ], [ [ "fp.work_format('High')", "_____no_output_____" ], [ "fp.work_format('Medium')", "_____no_output_____" ], [ "fp.work_format('Low')", "_____no_output_____" ] ], [ [ "In fact, the function returns 0 in every case where the passed in parameter id different than 'High' and 'Medium':\n", "_____no_output_____" ] ], [ [ "fp.work_format('Mediocre')", "_____no_output_____" ] ], [ [ "## Cast to int\nThis simple function casts a float to int, but also adds extra flexibility and returns 0 when it encounters a NaN (Not a Number):", "_____no_output_____" ] ], [ [ "fp.to_int(3.24)", "_____no_output_____" ], [ "import numpy\nnan = numpy.nan\nfp.to_int(nan)", "_____no_output_____" ] ], [ [ "## Apply format of choice\nThis generic function lets you choose what format to apply to every value in the columns of the data frame you specify.", "_____no_output_____" ] ], [ [ "data[['Name', 'Jersey Number', 'Skill Moves', 'Weak Foot']]", "_____no_output_____" ] ], [ [ "By format, is meant a function that operates on the values in the specified columns:", "_____no_output_____" ] ], [ [ "columns = ['Jersey Number', 'Skill Moves', 'Weak Foot']\nformat_fun = fp.to_int\n\ndata = fp.apply_format(data, columns, format_fun)\n\ndata[['Name', 'Jersey Number', 'Skill Moves', 'Weak Foot']]", "_____no_output_____" ] ], [ [ "## Dummy variables\nIf we intend to build machine learning models to explore our data, we usually are not able to extract any information from qualitative data. Here 'Club' and 'Preferred Foot' are categories that could bring interesting information. To be able to use it in our machine learning algorithms we can get dummy variables.", "_____no_output_____" ] ], [ [ "data[['Name', 'Preferred Foot']]", "_____no_output_____" ] ], [ [ "If we choose 'Preferred Foot', new columns will be aded, their titles will be the same as the values in 'Preferred Foot' column: 'Left' and 'Right'. So now instead of seeing 'Left' in the column 'Preferred Foot' we will see 1 in 'Left' column (and 0 in 'Right').", "_____no_output_____" ] ], [ [ "data = fp.to_dummy(data, ['Preferred Foot'])\ndata[['Name', 'Left', 'Right']]", "_____no_output_____" ] ], [ [ "Learn more about [dummy variables](https://en.wikiversity.org/wiki/Dummy_variable_(statistics)).", "_____no_output_____" ], [ "The data frame will no longer contain the columns we transformed:", "_____no_output_____" ] ], [ [ "'Preferred Foot' in data", "_____no_output_____" ] ], [ [ "We can get dummy variables for multiple columns at once.", "_____no_output_____" ] ], [ [ "data[['Name', 'Club', 'Position']]", "_____no_output_____" ], [ "data = fp.to_dummy(data, ['Club', 'Nationality'])\ndata[['Name', 'Paris Saint-Germain', 'Manchester City', 'Brazil', 'Portugal']]", "_____no_output_____" ] ], [ [ "## Split work rate column\nIn FIFA the players' work rate is saved in a special way, two qualiative values are split with a slash:", "_____no_output_____" ] ], [ [ "data[['Name', 'Work Rate']]", "_____no_output_____" ] ], [ [ "This next function allows you to split column 'Work Rate' into 'Defensive Work Rate' and 'Offensive Work Rate':", "_____no_output_____" ] ], [ [ "data = fp.split_work_rate(data)\ndata[['Name', 'Defensive Work Rate', 'Offensive Work Rate']]", "_____no_output_____" ] ], [ [ "## Default preprocessing\nTo perform all the basic preprocessing (optimized for the FIFA 19 data set) on your data, simply go:", "_____no_output_____" ] ], [ [ "data = pd.read_csv('data.csv')\nfp.preprocess(data)", "_____no_output_____" ] ], [ [ "## Let's get coding\nNow it is your turn to try out our functions and preprocess your data!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d00ecd7439262a9e0fc908a32217504a2f9dc8d2
32,248
ipynb
Jupyter Notebook
12-Bias.ipynb
pedro-abundio-wang/GANs
85de1c4ec740539800f7cef8c2174f2f22674881
[ "Apache-2.0" ]
null
null
null
12-Bias.ipynb
pedro-abundio-wang/GANs
85de1c4ec740539800f7cef8c2174f2f22674881
[ "Apache-2.0" ]
null
null
null
12-Bias.ipynb
pedro-abundio-wang/GANs
85de1c4ec740539800f7cef8c2174f2f22674881
[ "Apache-2.0" ]
null
null
null
43.402423
545
0.608069
[ [ [ "# Bias", "_____no_output_____" ], [ "### Goals\nIn this notebook, you're going to explore a way to identify some biases of a GAN using a classifier, in a way that's well-suited for attempting to make a model independent of an input. Note that not all biases are as obvious as the ones you will see here.\n\n### Learning Objectives\n1. Be able to distinguish a few different kinds of bias in terms of demographic parity, equality of odds, and equality of opportunity (as proposed [here](http://m-mitchell.com/papers/Adversarial_Bias_Mitigation.pdf)).\n2. Be able to use a classifier to try and detect biases in a GAN by analyzing the generator's implicit associations.", "_____no_output_____" ], [ "\n## Challenges\n\nOne major challenge in assessing bias in GANs is that you still want your generator to be able to generate examples of different values of a protected class—the class you would like to mitigate bias against. While a classifier can be optimized to have its output be independent of a protected class, a generator which generates faces should be able to generate examples of various protected class values. \n\nWhen you generate examples with various values of a protected class, you don’t want those examples to correspond to any properties that aren’t strictly a function of that protected class. This is made especially difficult since many protected classes (e.g. gender or ethnicity) are social constructs, and what properties count as “a function of that protected class” will vary depending on who you ask. It’s certainly a hard balance to strike.\n\nMoreover, a protected class is rarely used to condition a GAN explicitly, so it is often necessary to resort to somewhat post-hoc methods (e.g. using a classifier trained on relevant features, which might be biased itself). \n\nIn this assignment, you will learn one approach to detect potential bias, by analyzing correlations in feature classifications on the generated images. ", "_____no_output_____" ], [ "## Getting Started\n\nAs you have done previously, you will start by importing some useful libraries and defining a visualization function for your images. You will also use the same generator and basic classifier from previous weeks.", "_____no_output_____" ], [ "#### Packages and Visualization", "_____no_output_____" ] ], [ [ "import torch\nimport numpy as np\nfrom torch import nn\nfrom tqdm.auto import tqdm\nfrom torchvision import transforms\nfrom torchvision.utils import make_grid\nfrom torchvision.datasets import CelebA\nfrom torch.utils.data import DataLoader\nimport matplotlib.pyplot as plt\ntorch.manual_seed(0) # Set for our testing purposes, please do not change!\n\ndef show_tensor_images(image_tensor, num_images=16, size=(3, 64, 64), nrow=3):\n '''\n Function for visualizing images: Given a tensor of images, number of images,\n size per image, and images per row, plots and prints the images in an uniform grid.\n '''\n image_tensor = (image_tensor + 1) / 2\n image_unflat = image_tensor.detach().cpu()\n image_grid = make_grid(image_unflat[:num_images], nrow=nrow)\n plt.imshow(image_grid.permute(1, 2, 0).squeeze())\n plt.show()", "_____no_output_____" ] ], [ [ "#### Generator and Noise", "_____no_output_____" ] ], [ [ "class Generator(nn.Module):\n '''\n Generator Class\n Values:\n z_dim: the dimension of the noise vector, a scalar\n im_chan: the number of channels in the images, fitted for the dataset used, a scalar\n (CelebA is rgb, so 3 is your default)\n hidden_dim: the inner dimension, a scalar\n '''\n def __init__(self, z_dim=10, im_chan=3, hidden_dim=64):\n super(Generator, self).__init__()\n self.z_dim = z_dim\n # Build the neural network\n self.gen = nn.Sequential(\n self.make_gen_block(z_dim, hidden_dim * 8),\n self.make_gen_block(hidden_dim * 8, hidden_dim * 4),\n self.make_gen_block(hidden_dim * 4, hidden_dim * 2),\n self.make_gen_block(hidden_dim * 2, hidden_dim),\n self.make_gen_block(hidden_dim, im_chan, kernel_size=4, final_layer=True),\n )\n\n def make_gen_block(self, input_channels, output_channels, kernel_size=3, stride=2, final_layer=False):\n '''\n Function to return a sequence of operations corresponding to a generator block of DCGAN;\n a transposed convolution, a batchnorm (except in the final layer), and an activation.\n Parameters:\n input_channels: how many channels the input feature representation has\n output_channels: how many channels the output feature representation should have\n kernel_size: the size of each convolutional filter, equivalent to (kernel_size, kernel_size)\n stride: the stride of the convolution\n final_layer: a boolean, true if it is the final layer and false otherwise \n (affects activation and batchnorm)\n '''\n if not final_layer:\n return nn.Sequential(\n nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride),\n nn.BatchNorm2d(output_channels),\n nn.ReLU(inplace=True),\n )\n else:\n return nn.Sequential(\n nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride),\n nn.Tanh(),\n )\n\n def forward(self, noise):\n '''\n Function for completing a forward pass of the generator: Given a noise tensor, \n returns generated images.\n Parameters:\n noise: a noise tensor with dimensions (n_samples, z_dim)\n '''\n x = noise.view(len(noise), self.z_dim, 1, 1)\n return self.gen(x)\n\ndef get_noise(n_samples, z_dim, device='cpu'):\n '''\n Function for creating noise vectors: Given the dimensions (n_samples, z_dim)\n creates a tensor of that shape filled with random numbers from the normal distribution.\n Parameters:\n n_samples: the number of samples to generate, a scalar\n z_dim: the dimension of the noise vector, a scalar\n device: the device type\n '''\n return torch.randn(n_samples, z_dim, device=device)", "_____no_output_____" ] ], [ [ "#### Classifier", "_____no_output_____" ] ], [ [ "class Classifier(nn.Module):\n '''\n Classifier Class\n Values:\n im_chan: the number of channels in the images, fitted for the dataset used, a scalar\n (CelebA is rgb, so 3 is your default)\n n_classes: the total number of classes in the dataset, an integer scalar\n hidden_dim: the inner dimension, a scalar\n '''\n def __init__(self, im_chan=3, n_classes=2, hidden_dim=64):\n super(Classifier, self).__init__()\n self.classifier = nn.Sequential(\n self.make_classifier_block(im_chan, hidden_dim),\n self.make_classifier_block(hidden_dim, hidden_dim * 2),\n self.make_classifier_block(hidden_dim * 2, hidden_dim * 4, stride=3),\n self.make_classifier_block(hidden_dim * 4, n_classes, final_layer=True),\n )\n\n def make_classifier_block(self, input_channels, output_channels, kernel_size=4, stride=2, final_layer=False):\n '''\n Function to return a sequence of operations corresponding to a classifier block; \n a convolution, a batchnorm (except in the final layer), and an activation (except in the final layer).\n Parameters:\n input_channels: how many channels the input feature representation has\n output_channels: how many channels the output feature representation should have\n kernel_size: the size of each convolutional filter, equivalent to (kernel_size, kernel_size)\n stride: the stride of the convolution\n final_layer: a boolean, true if it is the final layer and false otherwise \n (affects activation and batchnorm)\n '''\n if not final_layer:\n return nn.Sequential(\n nn.Conv2d(input_channels, output_channels, kernel_size, stride),\n nn.BatchNorm2d(output_channels),\n nn.LeakyReLU(0.2, inplace=True),\n )\n else:\n return nn.Sequential(\n nn.Conv2d(input_channels, output_channels, kernel_size, stride),\n )\n\n def forward(self, image):\n '''\n Function for completing a forward pass of the classifier: Given an image tensor, \n returns an n_classes-dimension tensor representing classes.\n Parameters:\n image: a flattened image tensor with im_chan channels\n '''\n class_pred = self.classifier(image)\n return class_pred.view(len(class_pred), -1)", "_____no_output_____" ] ], [ [ "## Specifying Parameters\nYou will also need to specify a few parameters before you begin training:\n * z_dim: the dimension of the noise vector\n * batch_size: the number of images per forward/backward pass\n * device: the device type", "_____no_output_____" ] ], [ [ "z_dim = 64\nbatch_size = 128\ndevice = 'cuda'", "_____no_output_____" ] ], [ [ "## Train a Classifier (Optional)\n\nYou're welcome to train your own classifier with this code, but you are provide a pre-trained one based on this architecture here which you can load and use in the next section. ", "_____no_output_____" ] ], [ [ "# You can run this code to train your own classifier, but there is a provided pre-trained one \n# If you'd like to use this, just run \"train_classifier(filename)\"\n# To train and save a classifier on the label indices to that filename\ndef train_classifier(filename):\n import seaborn as sns\n import matplotlib.pyplot as plt\n\n # You're going to target all the classes, so that's how many the classifier will learn\n label_indices = range(40)\n\n n_epochs = 3\n display_step = 500\n lr = 0.001\n beta_1 = 0.5\n beta_2 = 0.999\n image_size = 64\n\n transform = transforms.Compose([\n transforms.Resize(image_size),\n transforms.CenterCrop(image_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n\n dataloader = DataLoader(\n CelebA(\".\", split='train', download=True, transform=transform),\n batch_size=batch_size,\n shuffle=True)\n\n classifier = Classifier(n_classes=len(label_indices)).to(device)\n class_opt = torch.optim.Adam(classifier.parameters(), lr=lr, betas=(beta_1, beta_2))\n criterion = nn.BCEWithLogitsLoss()\n\n cur_step = 0\n classifier_losses = []\n # classifier_val_losses = []\n for epoch in range(n_epochs):\n # Dataloader returns the batches\n for real, labels in tqdm(dataloader):\n real = real.to(device)\n labels = labels[:, label_indices].to(device).float()\n\n class_opt.zero_grad()\n class_pred = classifier(real)\n class_loss = criterion(class_pred, labels)\n class_loss.backward() # Calculate the gradients\n class_opt.step() # Update the weights\n classifier_losses += [class_loss.item()] # Keep track of the average classifier loss\n\n ### Visualization code ###\n if cur_step % display_step == 0 and cur_step > 0:\n class_mean = sum(classifier_losses[-display_step:]) / display_step\n print(f\"Step {cur_step}: Classifier loss: {class_mean}\")\n step_bins = 20\n x_axis = sorted([i * step_bins for i in range(len(classifier_losses) // step_bins)] * step_bins)\n sns.lineplot(x_axis, classifier_losses[:len(x_axis)], label=\"Classifier Loss\")\n plt.legend()\n plt.show()\n torch.save({\"classifier\": classifier.state_dict()}, filename)\n cur_step += 1\n\n# Uncomment the last line to train your own classfier - this line will not work in Coursera.\n# If you'd like to do this, you'll have to download it and run it, ideally using a GPU.\n# train_classifier(\"filename\")", "_____no_output_____" ] ], [ [ "## Loading the Pre-trained Models\n\nYou can now load the pre-trained generator (trained on CelebA) and classifier using the following code. If you trained your own classifier, you can load that one here instead. However, it is suggested that you first go through the assignment using the pre-trained one.", "_____no_output_____" ] ], [ [ "import torch\ngen = Generator(z_dim).to(device)\ngen_dict = torch.load(\"pretrained_celeba.pth\", map_location=torch.device(device))[\"gen\"]\ngen.load_state_dict(gen_dict)\ngen.eval()\n\nn_classes = 40\nclassifier = Classifier(n_classes=n_classes).to(device)\nclass_dict = torch.load(\"pretrained_classifier.pth\", map_location=torch.device(device))[\"classifier\"]\nclassifier.load_state_dict(class_dict)\nclassifier.eval()\nprint(\"Loaded the models!\")\n\nopt = torch.optim.Adam(classifier.parameters(), lr=0.01)", "_____no_output_____" ] ], [ [ "## Feature Correlation\nNow you can generate images using the generator. By also using the classifier, you will be generating images with different amounts of the \"male\" feature.\n\nYou are welcome to experiment with other features as the target feature, but it is encouraged that you initially go through the notebook as is before exploring.", "_____no_output_____" ] ], [ [ "# First you generate a bunch of fake images with the generator\nn_images = 256\nfake_image_history = []\nclassification_history = []\ngrad_steps = 30 # How many gradient steps to take\nskip = 2 # How many gradient steps to skip in the visualization\n\nfeature_names = [\"5oClockShadow\", \"ArchedEyebrows\", \"Attractive\", \"BagsUnderEyes\", \"Bald\", \"Bangs\",\n\"BigLips\", \"BigNose\", \"BlackHair\", \"BlondHair\", \"Blurry\", \"BrownHair\", \"BushyEyebrows\", \"Chubby\",\n\"DoubleChin\", \"Eyeglasses\", \"Goatee\", \"GrayHair\", \"HeavyMakeup\", \"HighCheekbones\", \"Male\", \n\"MouthSlightlyOpen\", \"Mustache\", \"NarrowEyes\", \"NoBeard\", \"OvalFace\", \"PaleSkin\", \"PointyNose\", \n\"RecedingHairline\", \"RosyCheeks\", \"Sideburn\", \"Smiling\", \"StraightHair\", \"WavyHair\", \"WearingEarrings\", \n\"WearingHat\", \"WearingLipstick\", \"WearingNecklace\", \"WearingNecktie\", \"Young\"]\n\nn_features = len(feature_names)\n# Set the target feature\ntarget_feature = \"Male\"\ntarget_indices = feature_names.index(target_feature)\nnoise = get_noise(n_images, z_dim).to(device)\nnew_noise = noise.clone().requires_grad_()\nstarting_classifications = classifier(gen(new_noise)).cpu().detach()\n\n# Additive direction (more of a feature)\nfor i in range(grad_steps):\n opt.zero_grad()\n fake = gen(new_noise)\n fake_image_history += [fake]\n classifications = classifier(fake)\n classification_history += [classifications.cpu().detach()]\n fake_classes = classifications[:, target_indices].mean()\n fake_classes.backward()\n new_noise.data += new_noise.grad / grad_steps\n\n# Subtractive direction (less of a feature)\nnew_noise = noise.clone().requires_grad_()\nfor i in range(grad_steps):\n opt.zero_grad()\n fake = gen(new_noise)\n fake_image_history += [fake]\n classifications = classifier(fake)\n classification_history += [classifications.cpu().detach()]\n fake_classes = classifications[:, target_indices].mean()\n fake_classes.backward()\n new_noise.data -= new_noise.grad / grad_steps\n\nclassification_history = torch.stack(classification_history)", "_____no_output_____" ], [ "print(classification_history.shape)\nprint(starting_classifications[None, :, :].shape)", "_____no_output_____" ] ], [ [ "You've now generated image samples, which have increasing or decreasing amounts of the target feature. You can visualize the way in which that affects other classified features. The x-axis will show you the amount of change in your target feature and the y-axis shows how much the other features change, as detected in those images by the classifier. Together, you will be able to see the covariance of \"male-ness\" and other features.\n\nYou are started off with a set of features that have interesting associations with \"male-ness\", but you are welcome to change the features in `other_features` with others from `feature_names`.", "_____no_output_____" ] ], [ [ "import seaborn as sns\n# Set the other features\nother_features = [\"Smiling\", \"Bald\", \"Young\", \"HeavyMakeup\", \"Attractive\"]\nclassification_changes = (classification_history - starting_classifications[None, :, :]).numpy()\nfor other_feature in other_features:\n other_indices = feature_names.index(other_feature)\n with sns.axes_style(\"darkgrid\"):\n sns.regplot(\n classification_changes[:, :, target_indices].reshape(-1), \n classification_changes[:, :, other_indices].reshape(-1), \n fit_reg=True,\n truncate=True,\n ci=99,\n x_ci=99,\n x_bins=len(classification_history),\n label=other_feature\n )\nplt.xlabel(target_feature)\nplt.ylabel(\"Other Feature\")\nplt.title(f\"Generator Biases: Features vs {target_feature}-ness\")\nplt.legend(loc=1)\nplt.show()", "_____no_output_____" ] ], [ [ "This correlation detection can be used to reduce bias by penalizing this type of correlation in the loss during the training of the generator. However, currently there is no rigorous and accepted solution for debiasing GANs. A first step that you can take in the right direction comes before training the model: make sure that your dataset is inclusive and representative, and consider how you can mitigate the biases resulting from whatever data collection method you used—for example, getting a representative labelers for your task. \n\nIt is important to note that, as highlighted in the lecture and by many researchers including [Timnit Gebru and Emily Denton](https://sites.google.com/view/fatecv-tutorial/schedule), a diverse dataset alone is not enough to eliminate bias. Even diverse datasets can reinforce existing structural biases by simply capturing common social biases. Mitigating these biases is an important and active area of research.\n\n#### Note on CelebA\nYou may have noticed that there are obvious correlations between the feature you are using, \"male\", and other seemingly unrelates features, \"smiling\" and \"young\" for example. This is because the CelebA dataset labels had no serious consideration for diversity. The data represents the biases their labelers, the dataset creators, the social biases as a result of using a dataset based on American celebrities, and many others. Equipped with knowledge about bias, we trust that you will do better in the future datasets you create.", "_____no_output_____" ], [ "## Quantification\nFinally, you can also quantitatively evaluate the degree to which these factors covary. Given a target index, for example corresponding to \"male,\" you'll want to return the other features that covary with that target feature the most. You'll want to account for both large negative and positive covariances, and you'll want to avoid returning the target feature in your list of covarying features (since a feature will often have a high covariance with itself).\n\n<details>\n\n<summary>\n<font size=\"3\" color=\"green\">\n<b>Optional hints for <code><font size=\"4\">get_top_covariances</font></code></b>\n</font>\n</summary>\n\n1. You will likely find the following function useful: [np.cov](https://numpy.org/doc/stable/reference/generated/numpy.cov.html).\n2. You will probably find it useful to [reshape](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html) the input.\n3. The target feature should not be included in the outputs.\n4. Feel free to use any reasonable method to get the top-n elements.\n5. It may be easiest to solve this if you find the `relevant_indices` first.\n6. You want to sort by absolute value but return the actual values.\n</details>", "_____no_output_____" ] ], [ [ "# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED CELL: get_top_covariances\ndef get_top_covariances(classification_changes, target_index, top_n=10):\n '''\n Function for getting the top n covariances: Given a list of classification changes\n and the index of the target feature, returns (1) a list or tensor (numpy or torch) of the indices\n corresponding to the n features that covary most with the target in terms of absolute covariance\n and (2) a list or tensor (numpy or torch) of the degrees to which they covary.\n Parameters:\n classification_changes: relative changes in classifications of each generated image \n resulting from optimizing the target feature (see above for a visualization)\n target_index: the index of the target feature, a scalar\n top_n: the top most number of elements to return, default is 10\n '''\n # Hint: Don't forget you also care about negative covariances!\n # Note that classification_changes has a shape of (2 * grad_steps, n_images, n_features) \n # where n_features is the number of features measured by the classifier, and you are looking\n # for the covariance of the features based on the (2 * grad_steps * n_images) samples\n #### START CODE HERE ####\n relevant_indices = None\n highest_covariances = None\n #### END CODE HERE ####\n return relevant_indices, highest_covariances", "_____no_output_____" ], [ "# UNIT TEST\nfrom torch.distributions import MultivariateNormal\nmean = torch.Tensor([0, 0, 0, 0]) \ncovariance = torch.Tensor( \n [[10, 2, -0.5, -5],\n [2, 11, 5, 4],\n [-0.5, 5, 10, 2],\n [-5, 4, 2, 11]]\n)\nindependent_dist = MultivariateNormal(mean, covariance)\nsamples = independent_dist.sample((60 * 128,))\nfoo = samples.reshape(60, 128, samples.shape[-1])\n\nrelevant_indices, highest_covariances = get_top_covariances(foo, 1, top_n=3)\nassert (tuple(relevant_indices) == (2, 3, 0)), \"Make sure you're getting the greatest, not the least covariances\"\nassert np.all(np.abs(highest_covariances - [5, 4, 2]) < 0.5 )\n\nrelevant_indices, highest_covariances = get_top_covariances(foo, 0, top_n=3)\nassert (tuple(relevant_indices) == (3, 1, 2)), \"Make sure to consider the magnitude of negative covariances\"\nassert np.all(np.abs(highest_covariances - [-5, 2, -0.5]) < 0.5 )\n\nrelevant_indices, highest_covariances = get_top_covariances(foo, 2, top_n=2)\nassert (tuple(relevant_indices) == (1, 3))\nassert np.all(np.abs(highest_covariances - [5, 2]) < 0.5 )\n\nrelevant_indices, highest_covariances = get_top_covariances(foo, 3, top_n=2)\nassert (tuple(relevant_indices) == (0, 1))\nassert np.all(np.abs(highest_covariances - [-5, 4]) < 0.5 )\n\nprint(\"All tests passed\")", "_____no_output_____" ], [ "relevant_indices, highest_covariances = get_top_covariances(classification_changes, target_indices, top_n=10)\nprint(relevant_indices)\nassert relevant_indices[9] == 34\nassert len(relevant_indices) == 10\nassert highest_covariances[8] - (-1.2418) < 1e-3\nfor index, covariance in zip(relevant_indices, highest_covariances):\n print(f\"{feature_names[index]} {covariance:f}\")", "_____no_output_____" ] ], [ [ "One of the major sources of difficulty with identifying bias and fairness, as discussed in the lectures, is that there are many ways you might reasonably define these terms. Here are three ways that are computationally useful and [widely referenced](http://m-mitchell.com/papers/Adversarial_Bias_Mitigation.pdf). They are, by no means, the only definitions of fairness (see more details [here](https://developers.google.com/machine-learning/glossary/fairness)):\n\n\n1. Demographic parity: the overall distribution of the predictions made by a predictor is the same for different values of a protected class. \n2. Equality of odds: all else being equal, the probability that you predict correctly or incorrectly is the same for different values of a protected class. \n2. Equality of opportunity: all else being equal, the probability that you predict correctly is the same for different valus of a protected class (weaker than equality of odds).\n\nWith GANs also being used to help downstream classifiers (you will see this firsthand in future assignments), these definitions of fairness will impact, as well as depend on, your downstream task. It is important to work towards creating a fair GAN according to the definition you choose. Pursuing any of them is virtually always better than blindly labelling data, creating a GAN, and sampling its generations.", "_____no_output_____" ] ] ]
[ "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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
d00ecdafca8a0cfe128eb5926784e2e130b9a0ef
29,406
ipynb
Jupyter Notebook
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations.ipynb
smartestrobotdai/training-data-analyst
c633ad902f2a4a1d6d7cd40e4a15cd1eb862d7bc
[ "Apache-2.0" ]
7
2019-05-10T14:13:40.000Z
2022-01-19T16:59:04.000Z
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations.ipynb
smartestrobotdai/training-data-analyst
c633ad902f2a4a1d6d7cd40e4a15cd1eb862d7bc
[ "Apache-2.0" ]
11
2020-01-28T22:39:21.000Z
2022-03-11T23:43:39.000Z
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations.ipynb
smartestrobotdai/training-data-analyst
c633ad902f2a4a1d6d7cd40e4a15cd1eb862d7bc
[ "Apache-2.0" ]
8
2020-02-03T18:31:37.000Z
2021-08-13T13:58:54.000Z
38.641261
444
0.606441
[ [ [ "# Neural network hybrid recommendation system on Google Analytics data model and training\n\nThis notebook demonstrates how to implement a hybrid recommendation system using a neural network to combine content-based and collaborative filtering recommendation models using Google Analytics data. We are going to use the learned user embeddings from [wals.ipynb](../wals.ipynb) and combine that with our previous content-based features from [content_based_using_neural_networks.ipynb](../content_based_using_neural_networks.ipynb)\n\nNow that we have our data preprocessed from BigQuery and Cloud Dataflow, we can build our neural network hybrid recommendation model to our preprocessed data. Then we can train locally to make sure everything works and then use the power of Google Cloud ML Engine to scale it out.", "_____no_output_____" ], [ "We're going to use TensorFlow Hub to use trained text embeddings, so let's first pip install that and reset our session.", "_____no_output_____" ] ], [ [ "!pip install tensorflow_hub", "_____no_output_____" ] ], [ [ "Now reset the notebook's session kernel! Since we're no longer using Cloud Dataflow, we'll be using the python3 kernel from here on out so don't forget to change the kernel if it's still python2.", "_____no_output_____" ] ], [ [ "# Import helpful libraries and setup our project, bucket, and region\nimport os\nimport tensorflow as tf\nimport tensorflow_hub as hub\n\nPROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID\nBUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME\nREGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1\n\n# do not change these\nos.environ['PROJECT'] = PROJECT\nos.environ['BUCKET'] = BUCKET\nos.environ['REGION'] = REGION\nos.environ['TFVERSION'] = '1.8'", "_____no_output_____" ], [ "%%bash\ngcloud config set project $PROJECT\ngcloud config set compute/region $REGION", "_____no_output_____" ], [ "%%bash\nif ! gsutil ls | grep -q gs://${BUCKET}/hybrid_recommendation/preproc; then\n gsutil mb -l ${REGION} gs://${BUCKET}\n # copy canonical set of preprocessed files if you didn't do preprocessing notebook\n gsutil -m cp -R gs://cloud-training-demos/courses/machine_learning/deepdive/10_recommendation/hybrid_recommendation gs://${BUCKET}\nfi", "_____no_output_____" ] ], [ [ "<h2> Create hybrid recommendation system model using TensorFlow </h2>\n\nNow that we've created our training and evaluation input files as well as our categorical feature vocabulary files, we can create our TensorFlow hybrid recommendation system model.", "_____no_output_____" ], [ "Let's first get some of our aggregate information that we will use in the model from some of our preprocessed files we saved in Google Cloud Storage.", "_____no_output_____" ] ], [ [ "from tensorflow.python.lib.io import file_io", "_____no_output_____" ], [ "# Get number of content ids from text file in Google Cloud Storage\nwith file_io.FileIO(tf.gfile.Glob(filename = \"gs://{}/hybrid_recommendation/preproc/vocab_counts/content_id_vocab_count.txt*\".format(BUCKET))[0], mode = 'r') as ifp:\n number_of_content_ids = int([x for x in ifp][0])\nprint(\"number_of_content_ids = {}\".format(number_of_content_ids))", "_____no_output_____" ], [ "# Get number of categories from text file in Google Cloud Storage\nwith file_io.FileIO(tf.gfile.Glob(filename = \"gs://{}/hybrid_recommendation/preproc/vocab_counts/category_vocab_count.txt*\".format(BUCKET))[0], mode = 'r') as ifp:\n number_of_categories = int([x for x in ifp][0])\nprint(\"number_of_categories = {}\".format(number_of_categories))", "_____no_output_____" ], [ "# Get number of authors from text file in Google Cloud Storage\nwith file_io.FileIO(tf.gfile.Glob(filename = \"gs://{}/hybrid_recommendation/preproc/vocab_counts/author_vocab_count.txt*\".format(BUCKET))[0], mode = 'r') as ifp:\n number_of_authors = int([x for x in ifp][0])\nprint(\"number_of_authors = {}\".format(number_of_authors))", "_____no_output_____" ], [ "# Get mean months since epoch from text file in Google Cloud Storage\nwith file_io.FileIO(tf.gfile.Glob(filename = \"gs://{}/hybrid_recommendation/preproc/vocab_counts/months_since_epoch_mean.txt*\".format(BUCKET))[0], mode = 'r') as ifp:\n mean_months_since_epoch = float([x for x in ifp][0])\nprint(\"mean_months_since_epoch = {}\".format(mean_months_since_epoch))", "_____no_output_____" ], [ "# Determine CSV and label columns\nNON_FACTOR_COLUMNS = 'next_content_id,visitor_id,content_id,category,title,author,months_since_epoch'.split(',')\nFACTOR_COLUMNS = [\"user_factor_{}\".format(i) for i in range(10)] + [\"item_factor_{}\".format(i) for i in range(10)]\nCSV_COLUMNS = NON_FACTOR_COLUMNS + FACTOR_COLUMNS\nLABEL_COLUMN = 'next_content_id'\n\n# Set default values for each CSV column\nNON_FACTOR_DEFAULTS = [[\"Unknown\"],[\"Unknown\"],[\"Unknown\"],[\"Unknown\"],[\"Unknown\"],[\"Unknown\"],[mean_months_since_epoch]]\nFACTOR_DEFAULTS = [[0.0] for i in range(10)] + [[0.0] for i in range(10)] # user and item\nDEFAULTS = NON_FACTOR_DEFAULTS + FACTOR_DEFAULTS", "_____no_output_____" ] ], [ [ "Create input function for training and evaluation to read from our preprocessed CSV files.", "_____no_output_____" ] ], [ [ "# Create input function for train and eval\ndef read_dataset(filename, mode, batch_size = 512):\n def _input_fn():\n def decode_csv(value_column):\n columns = tf.decode_csv(records = value_column, record_defaults = DEFAULTS)\n features = dict(zip(CSV_COLUMNS, columns)) \n label = features.pop(LABEL_COLUMN) \n return features, label\n\n # Create list of files that match pattern\n file_list = tf.gfile.Glob(filename = filename)\n\n # Create dataset from file list\n dataset = tf.data.TextLineDataset(filenames = file_list).map(map_func = decode_csv)\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n num_epochs = None # indefinitely\n dataset = dataset.shuffle(buffer_size = 10 * batch_size)\n else:\n num_epochs = 1 # end-of-input after this\n\n dataset = dataset.repeat(count = num_epochs).batch(batch_size = batch_size)\n return dataset.make_one_shot_iterator().get_next()\n return _input_fn", "_____no_output_____" ] ], [ [ "Next, we will create our feature columns using our read in features.", "_____no_output_____" ] ], [ [ "# Create feature columns to be used in model\ndef create_feature_columns(args):\n # Create content_id feature column\n content_id_column = tf.feature_column.categorical_column_with_hash_bucket(\n key = \"content_id\",\n hash_bucket_size = number_of_content_ids)\n\n # Embed content id into a lower dimensional representation\n embedded_content_column = tf.feature_column.embedding_column(\n categorical_column = content_id_column,\n dimension = args['content_id_embedding_dimensions'])\n\n # Create category feature column\n categorical_category_column = tf.feature_column.categorical_column_with_vocabulary_file(\n key = \"category\",\n vocabulary_file = tf.gfile.Glob(filename = \"gs://{}/hybrid_recommendation/preproc/vocabs/category_vocab.txt*\".format(args['bucket']))[0],\n num_oov_buckets = 1)\n\n # Convert categorical category column into indicator column so that it can be used in a DNN\n indicator_category_column = tf.feature_column.indicator_column(categorical_column = categorical_category_column)\n\n # Create title feature column using TF Hub\n embedded_title_column = hub.text_embedding_column(\n key = \"title\", \n module_spec = \"https://tfhub.dev/google/nnlm-de-dim50-with-normalization/1\",\n trainable = False)\n\n # Create author feature column\n author_column = tf.feature_column.categorical_column_with_hash_bucket(\n key = \"author\",\n hash_bucket_size = number_of_authors + 1)\n\n # Embed author into a lower dimensional representation\n embedded_author_column = tf.feature_column.embedding_column(\n categorical_column = author_column,\n dimension = args['author_embedding_dimensions'])\n\n # Create months since epoch boundaries list for our binning\n months_since_epoch_boundaries = list(range(400, 700, 20))\n\n # Create months_since_epoch feature column using raw data\n months_since_epoch_column = tf.feature_column.numeric_column(\n key = \"months_since_epoch\")\n\n # Create bucketized months_since_epoch feature column using our boundaries\n months_since_epoch_bucketized = tf.feature_column.bucketized_column(\n source_column = months_since_epoch_column,\n boundaries = months_since_epoch_boundaries)\n\n # Cross our categorical category column and bucketized months since epoch column\n crossed_months_since_category_column = tf.feature_column.crossed_column(\n keys = [categorical_category_column, months_since_epoch_bucketized],\n hash_bucket_size = len(months_since_epoch_boundaries) * (number_of_categories + 1))\n\n # Convert crossed categorical category and bucketized months since epoch column into indicator column so that it can be used in a DNN\n indicator_crossed_months_since_category_column = tf.feature_column.indicator_column(categorical_column = crossed_months_since_category_column)\n\n # Create user and item factor feature columns from our trained WALS model\n user_factors = [tf.feature_column.numeric_column(key = \"user_factor_\" + str(i)) for i in range(10)]\n item_factors = [tf.feature_column.numeric_column(key = \"item_factor_\" + str(i)) for i in range(10)]\n\n # Create list of feature columns\n feature_columns = [embedded_content_column,\n embedded_author_column,\n indicator_category_column,\n embedded_title_column,\n indicator_crossed_months_since_category_column] + user_factors + item_factors\n\n return feature_columns", "_____no_output_____" ] ], [ [ "Now we'll create our model function", "_____no_output_____" ] ], [ [ "# Create custom model function for our custom estimator\ndef model_fn(features, labels, mode, params):\n # TODO: Create neural network input layer using our feature columns defined above\n\n # TODO: Create hidden layers by looping through hidden unit list\n\n # TODO: Compute logits (1 per class) using the output of our last hidden layer\n\n # TODO: Find the predicted class indices based on the highest logit (which will result in the highest probability)\n predicted_classes = \n\n # Read in the content id vocabulary so we can tie the predicted class indices to their respective content ids\n with file_io.FileIO(tf.gfile.Glob(filename = \"gs://{}/hybrid_recommendation/preproc/vocabs/content_id_vocab.txt*\".format(BUCKET))[0], mode = 'r') as ifp:\n content_id_names = tf.constant(value = [x.rstrip() for x in ifp])\n\n # Gather predicted class names based predicted class indices\n predicted_class_names = tf.gather(params = content_id_names, indices = predicted_classes)\n\n # If the mode is prediction\n if mode == tf.estimator.ModeKeys.PREDICT:\n # Create predictions dict\n predictions_dict = {\n 'class_ids': tf.expand_dims(input = predicted_classes, axis = -1),\n 'class_names' : tf.expand_dims(input = predicted_class_names, axis = -1),\n 'probabilities': tf.nn.softmax(logits = logits),\n 'logits': logits\n }\n\n # Create export outputs\n export_outputs = {\"predict_export_outputs\": tf.estimator.export.PredictOutput(outputs = predictions_dict)}\n\n return tf.estimator.EstimatorSpec( # return early since we're done with what we need for prediction mode\n mode = mode,\n predictions = predictions_dict,\n loss = None,\n train_op = None,\n eval_metric_ops = None,\n export_outputs = export_outputs)\n\n # Continue on with training and evaluation modes\n\n # Create lookup table using our content id vocabulary\n table = tf.contrib.lookup.index_table_from_file(\n vocabulary_file = tf.gfile.Glob(filename = \"gs://{}/hybrid_recommendation/preproc/vocabs/content_id_vocab.txt*\".format(BUCKET))[0])\n\n # Look up labels from vocabulary table\n labels = table.lookup(keys = labels)\n\n # TODO: Compute loss using the correct type of softmax cross entropy since this is classification and our labels (content id indices) and probabilities are mutually exclusive\n loss = \n\n # Compute evaluation metrics of total accuracy and the accuracy of the top k classes\n accuracy = tf.metrics.accuracy(labels = labels, predictions = predicted_classes, name = 'acc_op')\n top_k_accuracy = tf.metrics.mean(values = tf.nn.in_top_k(predictions = logits, targets = labels, k = params['top_k']))\n map_at_k = tf.metrics.average_precision_at_k(labels = labels, predictions = predicted_classes, k = params['top_k'])\n\n # Put eval metrics into a dictionary\n eval_metrics = {\n 'accuracy': accuracy,\n 'top_k_accuracy': top_k_accuracy,\n 'map_at_k': map_at_k}\n\n # Create scalar summaries to see in TensorBoard\n tf.summary.scalar(name = 'accuracy', tensor = accuracy[1])\n tf.summary.scalar(name = 'top_k_accuracy', tensor = top_k_accuracy[1])\n tf.summary.scalar(name = 'map_at_k', tensor = map_at_k[1])\n\n # Create scalar summaries to see in TensorBoard\n tf.summary.scalar(name = 'accuracy', tensor = accuracy[1])\n tf.summary.scalar(name = 'top_k_accuracy', tensor = top_k_accuracy[1])\n\n # If the mode is evaluation\n if mode == tf.estimator.ModeKeys.EVAL:\n return tf.estimator.EstimatorSpec( # return early since we're done with what we need for evaluation mode\n mode = mode,\n predictions = None,\n loss = loss,\n train_op = None,\n eval_metric_ops = eval_metrics,\n export_outputs = None)\n\n # Continue on with training mode\n\n # If the mode is training\n assert mode == tf.estimator.ModeKeys.TRAIN\n\n # Create a custom optimizer\n optimizer = tf.train.AdagradOptimizer(learning_rate = params['learning_rate'])\n\n # Create train op\n train_op = optimizer.minimize(loss = loss, global_step = tf.train.get_global_step())\n\n return tf.estimator.EstimatorSpec( # final return since we're done with what we need for training mode\n mode = mode,\n predictions = None,\n loss = loss,\n train_op = train_op,\n eval_metric_ops = None,\n export_outputs = None)", "_____no_output_____" ] ], [ [ "Now create a serving input function", "_____no_output_____" ] ], [ [ "# Create serving input function\ndef serving_input_fn(): \n feature_placeholders = {\n colname : tf.placeholder(dtype = tf.string, shape = [None]) \\\n for colname in NON_FACTOR_COLUMNS[1:-1]\n }\n feature_placeholders['months_since_epoch'] = tf.placeholder(dtype = tf.float32, shape = [None])\n \n for colname in FACTOR_COLUMNS:\n feature_placeholders[colname] = tf.placeholder(dtype = tf.float32, shape = [None])\n\n features = {\n key: tf.expand_dims(tensor, -1) \\\n for key, tensor in feature_placeholders.items()\n }\n \n return tf.estimator.export.ServingInputReceiver(features, feature_placeholders)", "_____no_output_____" ] ], [ [ "Now that all of the pieces are assembled let's create and run our train and evaluate loop", "_____no_output_____" ] ], [ [ "# Create train and evaluate loop to combine all of the pieces together.\ntf.logging.set_verbosity(tf.logging.INFO)\ndef train_and_evaluate(args):\n estimator = tf.estimator.Estimator(\n model_fn = model_fn,\n model_dir = args['output_dir'],\n params={\n 'feature_columns': create_feature_columns(args),\n 'hidden_units': args['hidden_units'],\n 'n_classes': number_of_content_ids,\n 'learning_rate': args['learning_rate'],\n 'top_k': args['top_k'],\n 'bucket': args['bucket']\n })\n\n train_spec = tf.estimator.TrainSpec(\n input_fn = read_dataset(filename = args['train_data_paths'], mode = tf.estimator.ModeKeys.TRAIN, batch_size = args['batch_size']),\n max_steps = args['train_steps'])\n\n exporter = tf.estimator.LatestExporter('exporter', serving_input_fn)\n\n eval_spec = tf.estimator.EvalSpec(\n input_fn = read_dataset(filename = args['eval_data_paths'], mode = tf.estimator.ModeKeys.EVAL, batch_size = args['batch_size']),\n steps = None,\n start_delay_secs = args['start_delay_secs'],\n throttle_secs = args['throttle_secs'],\n exporters = exporter)\n\n tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)", "_____no_output_____" ] ], [ [ "Run train_and_evaluate!", "_____no_output_____" ] ], [ [ "# Call train and evaluate loop\nimport shutil\n\noutdir = 'hybrid_recommendation_trained'\nshutil.rmtree(outdir, ignore_errors = True) # start fresh each time\n\narguments = {\n 'bucket': BUCKET,\n 'train_data_paths': \"gs://{}/hybrid_recommendation/preproc/features/train.csv*\".format(BUCKET),\n 'eval_data_paths': \"gs://{}/hybrid_recommendation/preproc/features/eval.csv*\".format(BUCKET),\n 'output_dir': outdir,\n 'batch_size': 128,\n 'learning_rate': 0.1,\n 'hidden_units': [256, 128, 64],\n 'content_id_embedding_dimensions': 10,\n 'author_embedding_dimensions': 10,\n 'top_k': 10,\n 'train_steps': 1000,\n 'start_delay_secs': 30,\n 'throttle_secs': 30\n}\n\ntrain_and_evaluate(arguments)", "_____no_output_____" ] ], [ [ "## Run on module locally\n\nNow let's place our code into a python module with model.py and task.py files so that we can train using Google Cloud's ML Engine! First, let's test our module locally.", "_____no_output_____" ] ], [ [ "%writefile requirements.txt\ntensorflow_hub", "_____no_output_____" ], [ "%%bash\necho \"bucket=${BUCKET}\"\nrm -rf hybrid_recommendation_trained\nexport PYTHONPATH=${PYTHONPATH}:${PWD}/hybrid_recommendations_module\npython -m trainer.task \\\n --bucket=${BUCKET} \\\n --train_data_paths=gs://${BUCKET}/hybrid_recommendation/preproc/features/train.csv* \\\n --eval_data_paths=gs://${BUCKET}/hybrid_recommendation/preproc/features/eval.csv* \\\n --output_dir=${OUTDIR} \\\n --batch_size=128 \\\n --learning_rate=0.1 \\\n --hidden_units=\"256 128 64\" \\\n --content_id_embedding_dimensions=10 \\\n --author_embedding_dimensions=10 \\\n --top_k=10 \\\n --train_steps=1000 \\\n --start_delay_secs=30 \\\n --throttle_secs=60", "_____no_output_____" ] ], [ [ "# Run on Google Cloud ML Engine\nIf our module locally trained fine, let's now use of the power of ML Engine to scale it out on Google Cloud.", "_____no_output_____" ] ], [ [ "%%bash\nOUTDIR=gs://${BUCKET}/hybrid_recommendation/small_trained_model\nJOBNAME=hybrid_recommendation_$(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)/hybrid_recommendations_module/trainer \\\n --job-dir=$OUTDIR \\\n --staging-bucket=gs://$BUCKET \\\n --scale-tier=STANDARD_1 \\\n --runtime-version=$TFVERSION \\\n -- \\\n --bucket=${BUCKET} \\\n --train_data_paths=gs://${BUCKET}/hybrid_recommendation/preproc/features/train.csv* \\\n --eval_data_paths=gs://${BUCKET}/hybrid_recommendation/preproc/features/eval.csv* \\\n --output_dir=${OUTDIR} \\\n --batch_size=128 \\\n --learning_rate=0.1 \\\n --hidden_units=\"256 128 64\" \\\n --content_id_embedding_dimensions=10 \\\n --author_embedding_dimensions=10 \\\n --top_k=10 \\\n --train_steps=1000 \\\n --start_delay_secs=30 \\\n --throttle_secs=30", "_____no_output_____" ] ], [ [ "Let's add some hyperparameter tuning!", "_____no_output_____" ] ], [ [ "%%writefile hyperparam.yaml\ntrainingInput:\n hyperparameters:\n goal: MAXIMIZE\n maxTrials: 5\n maxParallelTrials: 1\n hyperparameterMetricTag: accuracy\n params:\n - parameterName: batch_size\n type: INTEGER\n minValue: 8\n maxValue: 64\n scaleType: UNIT_LINEAR_SCALE\n - parameterName: learning_rate\n type: DOUBLE\n minValue: 0.01\n maxValue: 0.1\n scaleType: UNIT_LINEAR_SCALE\n - parameterName: hidden_units\n type: CATEGORICAL\n categoricalValues: ['1024 512 256', '1024 512 128', '1024 256 128', '512 256 128', '1024 512 64', '1024 256 64', '512 256 64', '1024 128 64', '512 128 64', '256 128 64', '1024 512 32', '1024 256 32', '512 256 32', '1024 128 32', '512 128 32', '256 128 32', '1024 64 32', '512 64 32', '256 64 32', '128 64 32']\n - parameterName: content_id_embedding_dimensions\n type: INTEGER\n minValue: 5\n maxValue: 250\n scaleType: UNIT_LOG_SCALE\n - parameterName: author_embedding_dimensions\n type: INTEGER\n minValue: 5\n maxValue: 30\n scaleType: UNIT_LINEAR_SCALE", "_____no_output_____" ], [ "%%bash\nOUTDIR=gs://${BUCKET}/hybrid_recommendation/hypertuning\nJOBNAME=hybrid_recommendation_$(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)/hybrid_recommendations_module/trainer \\\n --job-dir=$OUTDIR \\\n --staging-bucket=gs://$BUCKET \\\n --scale-tier=STANDARD_1 \\\n --runtime-version=$TFVERSION \\\n --config=hyperparam.yaml \\\n -- \\\n --bucket=${BUCKET} \\\n --train_data_paths=gs://${BUCKET}/hybrid_recommendation/preproc/features/train.csv* \\\n --eval_data_paths=gs://${BUCKET}/hybrid_recommendation/preproc/features/eval.csv* \\\n --output_dir=${OUTDIR} \\\n --batch_size=128 \\\n --learning_rate=0.1 \\\n --hidden_units=\"256 128 64\" \\\n --content_id_embedding_dimensions=10 \\\n --author_embedding_dimensions=10 \\\n --top_k=10 \\\n --train_steps=1000 \\\n --start_delay_secs=30 \\\n --throttle_secs=30", "_____no_output_____" ] ], [ [ "Now that we know the best hyperparameters, run a big training job!", "_____no_output_____" ] ], [ [ "%%bash\nOUTDIR=gs://${BUCKET}/hybrid_recommendation/big_trained_model\nJOBNAME=hybrid_recommendation_$(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)/hybrid_recommendations_module/trainer \\\n --job-dir=$OUTDIR \\\n --staging-bucket=gs://$BUCKET \\\n --scale-tier=STANDARD_1 \\\n --runtime-version=$TFVERSION \\\n -- \\\n --bucket=${BUCKET} \\\n --train_data_paths=gs://${BUCKET}/hybrid_recommendation/preproc/features/train.csv* \\\n --eval_data_paths=gs://${BUCKET}/hybrid_recommendation/preproc/features/eval.csv* \\\n --output_dir=${OUTDIR} \\\n --batch_size=128 \\\n --learning_rate=0.1 \\\n --hidden_units=\"256 128 64\" \\\n --content_id_embedding_dimensions=10 \\\n --author_embedding_dimensions=10 \\\n --top_k=10 \\\n --train_steps=10000 \\\n --start_delay_secs=30 \\\n --throttle_secs=30", "_____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", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
d00ed6c8d24e790b7dbb09ecba4dd52352703388
66,026
ipynb
Jupyter Notebook
notebooks/19_ExceptionsDebugging.ipynb
johnpfay/PythonBootcamp
7191c7dbe95a16831d8e222a172320f61ec637f6
[ "Apache-2.0" ]
74
2015-02-24T22:24:30.000Z
2022-01-30T09:57:24.000Z
notebooks/19_ExceptionsDebugging.ipynb
johnpfay/PythonBootcamp
7191c7dbe95a16831d8e222a172320f61ec637f6
[ "Apache-2.0" ]
null
null
null
notebooks/19_ExceptionsDebugging.ipynb
johnpfay/PythonBootcamp
7191c7dbe95a16831d8e222a172320f61ec637f6
[ "Apache-2.0" ]
66
2015-01-24T02:43:28.000Z
2021-08-15T07:19:02.000Z
36.060076
1,403
0.53126
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d00ed8e7df352c0ffc0cadbb915896c37ed03a27
583,797
ipynb
Jupyter Notebook
Brain MRI Segmentation.ipynb
shahidhj/Deep-Learning-notebooks
fd9b8f6357b5a7c5cac4595ed3a3fb3b104049e0
[ "Apache-2.0" ]
null
null
null
Brain MRI Segmentation.ipynb
shahidhj/Deep-Learning-notebooks
fd9b8f6357b5a7c5cac4595ed3a3fb3b104049e0
[ "Apache-2.0" ]
null
null
null
Brain MRI Segmentation.ipynb
shahidhj/Deep-Learning-notebooks
fd9b8f6357b5a7c5cac4595ed3a3fb3b104049e0
[ "Apache-2.0" ]
null
null
null
262.971622
304,644
0.893446
[ [ [ "from fastai import *\nfrom fastai.vision import *\nfrom fastai.metrics import error_rate\nimport matplotlib.pyplot as plt\nfrom fastai.utils.mem import *\n%matplotlib inline", "_____no_output_____" ] ], [ [ "###### Setting the path", "_____no_output_____" ] ], [ [ "path = Path(\"C:/Users/shahi/.fastai/data/lgg-mri-segmentation/kaggle_3m\")", "_____no_output_____" ], [ "path", "_____no_output_____" ], [ "getMask = lambda x: x.parents[0] / (x.stem + '_mask' + x.suffix)\ntempImgFile = path/\"TCGA_CS_4941_19960909/TCGA_CS_4941_19960909_1.tif\"\ntempMaskFile = getMask(tempImgFile)", "_____no_output_____" ], [ "image = open_image(tempImgFile)\nimage", "_____no_output_____" ], [ "image.shape", "_____no_output_____" ], [ "mask = open_mask(getMask(tempImgFile),div=True)\nmask", "_____no_output_____" ], [ "\nclass SegmentationLabelListWithDiv(SegmentationLabelList):\n def open(self, fn): return open_mask(fn, div=True)\nclass SegmentationItemListWithDiv(SegmentationItemList):\n _label_cls = SegmentationLabelListWithDiv", "_____no_output_____" ], [ "codes = [0,1]", "_____no_output_____" ], [ "np.random.seed(42)\nsrc = (SegmentationItemListWithDiv.from_folder(path)\n .filter_by_func(lambda x:not x.name.endswith('_mask.tif'))\n .split_by_rand_pct(0.2)\n .label_from_func(getMask, classes=codes))\n", "_____no_output_____" ], [ "data = (src.transform(get_transforms(),size=256,tfm_y=True)\n .databunch(bs=8,num_workers=0)\n .normalize(imagenet_stats))\n", "_____no_output_____" ], [ "data.train_ds", "_____no_output_____" ], [ "data.valid_ds", "_____no_output_____" ], [ "data.show_batch(2)", "_____no_output_____" ] ], [ [ "##### Building the model", "_____no_output_____" ], [ "#### Pretrained resnet 34 used for downsampling", "_____no_output_____" ] ], [ [ "learn = unet_learner(data,models.resnet34,metrics=[dice])", "_____no_output_____" ], [ "learn.lr_find()", "_____no_output_____" ], [ "learn.recorder.plot()", "_____no_output_____" ], [ "learn.fit_one_cycle(4,1e-4)", "_____no_output_____" ], [ "learn.unfreeze()\nlearn.fit_one_cycle(4,1e-4,wd=1e-2)", "_____no_output_____" ] ], [ [ "#### Resnet 34 without pretrained weights with dialation ", "_____no_output_____" ] ], [ [ "learn.save('ResnetWithPrettrained')", "_____no_output_____" ], [ "learn.summary()", "_____no_output_____" ], [ "def conv(ni,nf):\n return nn.Conv2d(ni, nf, kernel_size=3, stride=2, padding=1,dilation=2)", "_____no_output_____" ], [ "def conv2(ni,nf): return conv_layer(ni,nf)", "_____no_output_____" ], [ "models.resnet34", "_____no_output_____" ], [ "model = nn.Sequential(\n conv2(3,8),\n res_block(8),\n conv2(8,16),\n res_block(16),\n conv2(16,32),\n res_block(32),\n \n\n)", "_____no_output_____" ], [ "act_fn = nn.ReLU(inplace=True)", "_____no_output_____" ], [ "\ndef presnet(block, n_layers, name, pre=False, **kwargs):\n model = PResNet(block, n_layers, **kwargs)\n #if pre: model.load_state_dict(model_zoo.load_url(model_urls[name]))\n if pre: model.load_state_dict(torch.load(model_urls[name]))\n return model\n\n\ndef presnet18(pretrained=False, **kwargs):\n return presnet(BasicBlock, [2, 2, 2, 2], 'presnet18', pre=pretrained, **kwargs)", "_____no_output_____" ], [ "class ResBlock(nn.Module):\n def __init__(self, nf):\n super().__init__()\n self.conv1 = conv_layer(nf,nf)\n self.conv2 = conv_layer(nf,nf)\n \n def forward(self, x): return x + self.conv2(self.conv1(x))", "_____no_output_____" ], [ "model3 = nn.Sequential(\n conv2(3, 8),\n res_block(8),\n conv2(8, 16),\n res_block(16),\n conv2(16, 32),\n res_block(32),\n conv2(32, 16),\n res_block(16),\n conv2(16, 10),\n )", "_____no_output_____" ], [ "model3", "_____no_output_____" ], [ "class ResBlock(nn.Module):\n def __init__(self, nf):\n super().__init__()\n self.conv1 = conv_layer(nf,nf)\n self.conv2 = conv_layer(nf,nf)\n \n def forward(self, x): return x + self.conv2(self.conv1(x))", "_____no_output_____" ], [ "learn3 = unet_learner(data,drn_d_38,metrics=[dice],pretrained=True)", "_____no_output_____" ], [ "learn3.lr_find()", "_____no_output_____" ], [ "learn3.recorder.plot()", "_____no_output_____" ], [ "learn3.fit_one_cycle(4,1e-4,wd=1e-1)", "_____no_output_____" ], [ "learn3.unfreeze()\nlearn3.fit_one_cycle(4,1e-4,wd=1e-2)", "_____no_output_____" ], [ "learn3.save('ResnetWithPretrainedDilation')", "_____no_output_____" ], [ "learn3.summary()", "_____no_output_____" ], [ "import pdb\n\nimport torch.nn as nn\nimport math\nimport torch.utils.model_zoo as model_zoo\n\nBatchNorm = nn.BatchNorm2d\n\n\n# __all__ = ['DRN', 'drn26', 'drn42', 'drn58']\n\n\nwebroot = 'http://dl.yf.io/drn/'\n\nmodel_urls = {\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'drn-c-26': webroot + 'drn_c_26-ddedf421.pth',\n 'drn-c-42': webroot + 'drn_c_42-9d336e8c.pth',\n 'drn-c-58': webroot + 'drn_c_58-0a53a92c.pth',\n 'drn-d-22': webroot + 'drn_d_22-4bd2f8ea.pth',\n 'drn-d-38': webroot + 'drn_d_38-eebb45f0.pth',\n 'drn-d-54': webroot + 'drn_d_54-0e0534ff.pth',\n 'drn-d-105': webroot + 'drn_d_105-12b40979.pth'\n}\n\n\ndef conv3x3(in_planes, out_planes, stride=1, padding=1, dilation=1):\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=padding, bias=False, dilation=dilation)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None,\n dilation=(1, 1), residual=True):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride,\n padding=dilation[0], dilation=dilation[0])\n self.bn1 = BatchNorm(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes,\n padding=dilation[1], dilation=dilation[1])\n self.bn2 = BatchNorm(planes)\n self.downsample = downsample\n self.stride = stride\n self.residual = residual\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n if self.residual:\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None,\n dilation=(1, 1), residual=True):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = BatchNorm(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=dilation[1], bias=False,\n dilation=dilation[1])\n self.bn2 = BatchNorm(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = BatchNorm(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass DRN(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000,\n channels=(16, 32, 64, 128, 256, 512, 512, 512),\n out_map=False, out_middle=False, pool_size=28, arch='D'):\n super(DRN, self).__init__()\n self.inplanes = channels[0]\n self.out_map = out_map\n self.out_dim = channels[-1]\n self.out_middle = out_middle\n self.arch = arch\n\n if arch == 'C':\n self.conv1 = nn.Conv2d(3, channels[0], kernel_size=7, stride=1,\n padding=3, bias=False)\n self.bn1 = BatchNorm(channels[0])\n self.relu = nn.ReLU(inplace=True)\n\n self.layer1 = self._make_layer(\n BasicBlock, channels[0], layers[0], stride=1)\n self.layer2 = self._make_layer(\n BasicBlock, channels[1], layers[1], stride=2)\n elif arch == 'D':\n self.layer0 = nn.Sequential(\n nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3,\n bias=False),\n BatchNorm(channels[0]),\n nn.ReLU(inplace=True)\n )\n\n self.layer1 = self._make_conv_layers(\n channels[0], layers[0], stride=1)\n self.layer2 = self._make_conv_layers(\n channels[1], layers[1], stride=2)\n\n self.layer3 = self._make_layer(block, channels[2], layers[2], stride=2)\n self.layer4 = self._make_layer(block, channels[3], layers[3], stride=2)\n self.layer5 = self._make_layer(block, channels[4], layers[4],\n dilation=2, new_level=False)\n self.layer6 = None if layers[5] == 0 else \\\n self._make_layer(block, channels[5], layers[5], dilation=4,\n new_level=False)\n\n if arch == 'C':\n self.layer7 = None if layers[6] == 0 else \\\n self._make_layer(BasicBlock, channels[6], layers[6], dilation=2,\n new_level=False, residual=False)\n self.layer8 = None if layers[7] == 0 else \\\n self._make_layer(BasicBlock, channels[7], layers[7], dilation=1,\n new_level=False, residual=False)\n elif arch == 'D':\n self.layer7 = None if layers[6] == 0 else \\\n self._make_conv_layers(channels[6], layers[6], dilation=2)\n self.layer8 = None if layers[7] == 0 else \\\n self._make_conv_layers(channels[7], layers[7], dilation=1)\n\n if num_classes > 0:\n self.avgpool = nn.AvgPool2d(pool_size)\n self.fc = nn.Conv2d(self.out_dim, num_classes, kernel_size=1,\n stride=1, padding=0, bias=True)\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, BatchNorm):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1, dilation=1,\n new_level=True, residual=True):\n assert dilation == 1 or dilation % 2 == 0\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n BatchNorm(planes * block.expansion),\n )\n\n layers = list()\n layers.append(block(\n self.inplanes, planes, stride, downsample,\n dilation=(1, 1) if dilation == 1 else (\n dilation // 2 if new_level else dilation, dilation),\n residual=residual))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, residual=residual,\n dilation=(dilation, dilation)))\n\n return nn.Sequential(*layers)\n\n def _make_conv_layers(self, channels, convs, stride=1, dilation=1):\n modules = []\n for i in range(convs):\n modules.extend([\n nn.Conv2d(self.inplanes, channels, kernel_size=3,\n stride=stride if i == 0 else 1,\n padding=dilation, bias=False, dilation=dilation),\n BatchNorm(channels),\n nn.ReLU(inplace=True)])\n self.inplanes = channels\n return nn.Sequential(*modules)\n\n def forward(self, x):\n y = list()\n\n if self.arch == 'C':\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n elif self.arch == 'D':\n x = self.layer0(x)\n\n x = self.layer1(x)\n y.append(x)\n x = self.layer2(x)\n y.append(x)\n\n x = self.layer3(x)\n y.append(x)\n\n x = self.layer4(x)\n y.append(x)\n\n x = self.layer5(x)\n y.append(x)\n\n if self.layer6 is not None:\n x = self.layer6(x)\n y.append(x)\n\n if self.layer7 is not None:\n x = self.layer7(x)\n y.append(x)\n\n if self.layer8 is not None:\n x = self.layer8(x)\n y.append(x)\n\n if self.out_map:\n x = self.fc(x)\n else:\n x = self.avgpool(x)\n x = self.fc(x)\n x = x.view(x.size(0), -1)\n\n if self.out_middle:\n return x, y\n else:\n return x\n\n\nclass DRN_A(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000):\n self.inplanes = 64\n super(DRN_A, self).__init__()\n self.out_dim = 512 * block.expansion\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=1,\n dilation=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=1,\n dilation=4)\n self.avgpool = nn.AvgPool2d(28, stride=1)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, BatchNorm):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n # for m in self.modules():\n # if isinstance(m, nn.Conv2d):\n # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n # elif isinstance(m, nn.BatchNorm2d):\n # nn.init.constant_(m.weight, 1)\n # nn.init.constant_(m.bias, 0)\n\n def _make_layer(self, block, planes, blocks, stride=1, dilation=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes,\n dilation=(dilation, dilation)))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\n\ndef drn_a_50(pretrained=False, **kwargs):\n model = DRN_A(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n return model\n\n\ndef drn_c_26(pretrained=False, **kwargs):\n model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch='C', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-c-26']))\n return model\n\n\ndef drn_c_42(pretrained=False, **kwargs):\n model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch='C', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-c-42']))\n return model\n\n\ndef drn_c_58(pretrained=False, **kwargs):\n model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch='C', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-c-58']))\n return model\n\n\ndef drn_d_22(pretrained=False, **kwargs):\n model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch='D', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-d-22']))\n return model\n\n\ndef drn_d_24(pretrained=False, **kwargs):\n model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 2, 2], arch='D', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-d-24']))\n return model\n\n\ndef drn_d_38(pretrained=False, **kwargs):\n model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch='D', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-d-38']))\n return model\n\n\ndef drn_d_40(pretrained=False, **kwargs):\n model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 2, 2], arch='D', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-d-40']))\n return model\n\n\ndef drn_d_54(pretrained=False, **kwargs):\n model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch='D', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-d-54']))\n return model\n\n\ndef drn_d_56(pretrained=False, **kwargs):\n model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 2, 2], arch='D', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-d-56']))\n return model\n\n\ndef drn_d_105(pretrained=False, **kwargs):\n model = DRN(Bottleneck, [1, 1, 3, 4, 23, 3, 1, 1], arch='D', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-d-105']))\n return model\n\n\ndef drn_d_107(pretrained=False, **kwargs):\n model = DRN(Bottleneck, [1, 1, 3, 4, 23, 3, 2, 2], arch='D', **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['drn-d-107']))\n return model", "_____no_output_____" ], [ "import torch.nn as nn\nimport torch.utils.model_zoo as model_zoo\n\n\n__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',\n 'resnet152']\n\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\n\ndef conv3x3(in_planes, out_planes, stride=1,padding=1,dilation=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False,dilation=dilation)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None,dilation=(1,1)):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride,padding=dilation[0],dilation=dilation[1])\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes,padding=dilation[1],dilation=dilation[1])\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n \n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None,dilation=(1,1)):\n super(Bottleneck, self).__init__()\n self.conv1 = conv1x1(inplanes, planes)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = conv3x3(planes, planes, stride)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = conv1x1(planes, planes * self.expansion)\n self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000, zero_init_residual=False):\n super(ResNet, self).__init__()\n self.inplanes = 64\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n elif isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0)\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\n\ndef resnet18(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\n return model\n\n\ndef resnet34(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-34 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))\n return model\n\n\ndef resnet50(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n return model\n\n\ndef resnet101(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))\n return model\n\n\ndef resnet152(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))\n return model\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "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" ] ]
d00ee5dbde43cd3d5af4ecf610aa3f3dec799d12
241,408
ipynb
Jupyter Notebook
p2_sl_finding_donors/p2_sl_finding_donors.ipynb
superkley/udacity-mlnd
2038110e6bebad6e4290441cf4da618059a02a04
[ "Apache-2.0" ]
4
2017-10-27T14:12:33.000Z
2018-02-19T21:50:15.000Z
p2_sl_finding_donors/p2_sl_finding_donors.ipynb
superkley/udacity-mlnd
2038110e6bebad6e4290441cf4da618059a02a04
[ "Apache-2.0" ]
null
null
null
p2_sl_finding_donors/p2_sl_finding_donors.ipynb
superkley/udacity-mlnd
2038110e6bebad6e4290441cf4da618059a02a04
[ "Apache-2.0" ]
null
null
null
144.642301
80,096
0.856811
[ [ [ "# Supervised Learning: Finding Donors for *CharityML*\n\n> Udacity Machine Learning Engineer Nanodegree: _Project 2_\n>\n> Author: _Ke Zhang_\n>\n> Submission Date: _2017-04-30_ (Revision 3)", "_____no_output_____" ], [ "## Content\n\n- [Getting Started](#Getting-Started)\n- [Exploring the Data](#Exploring-the-Data)\n- [Preparing the Data](#Preparing-the-Data)\n- [Evaluating Model Performance](#Evaluating-Model-Performance)\n- [Improving Results](#Improving-Results)\n- [Feature Importance](#Feature-Importance)\n- [References](#References)\n- [Reproduction Environment](#Reproduction-Environment)", "_____no_output_____" ], [ "## Getting Started\n\nIn this project, you will employ several supervised algorithms of your choice to accurately model individuals' income using data collected from the 1994 U.S. Census. You will then choose the best candidate algorithm from preliminary results and further optimize this algorithm to best model the data. Your goal with this implementation is to construct a model that accurately predicts whether an individual makes more than $50,000. This sort of task can arise in a non-profit setting, where organizations survive on donations. Understanding an individual's income can help a non-profit better understand how large of a donation to request, or whether or not they should reach out to begin with. While it can be difficult to determine an individual's general income bracket directly from public sources, we can (as we will see) infer this value from other publically available features. \n\nThe dataset for this project originates from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Census+Income). The datset was donated by Ron Kohavi and Barry Becker, after being published in the article _\"Scaling Up the Accuracy of Naive-Bayes Classifiers: A Decision-Tree Hybrid\"_. You can find the article by Ron Kohavi [online](https://www.aaai.org/Papers/KDD/1996/KDD96-033.pdf). The data we investigate here consists of small changes to the original dataset, such as removing the `'fnlwgt'` feature and records with missing or ill-formatted entries.", "_____no_output_____" ], [ "----\n## Exploring the Data\nRun the code cell below to load necessary Python libraries and load the census data. Note that the last column from this dataset, `'income'`, will be our target label (whether an individual makes more than, or at most, $50,000 annually). All other columns are features about each individual in the census database.", "_____no_output_____" ] ], [ [ "# Import libraries necessary for this project\nimport numpy as np\nimport pandas as pd\nfrom time import time\nfrom IPython.display import display # Allows the use of display() for DataFrames\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Import supplementary visualization code visuals.py\nimport visuals as vs\n\n#sklearn makes lots of deprecation warnings...\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n# Pretty display for notebooks\n%matplotlib inline\nsns.set(style='white', palette='muted', color_codes=True)\nsns.set_context('notebook', font_scale=1.2, rc={'lines.linewidth': 1.2})\n\n# Load the Census dataset\ndata = pd.read_csv(\"census.csv\")\n\n# Success - Display the first record\ndisplay(data.head(n=1))", "_____no_output_____" ] ], [ [ "### Implementation: Data Exploration\nA cursory investigation of the dataset will determine how many individuals fit into either group, and will tell us about the percentage of these individuals making more than \\$50,000. In the code cell below, you will need to compute the following:\n- The total number of records, `'n_records'`\n- The number of individuals making more than \\$50,000 annually, `'n_greater_50k'`.\n- The number of individuals making at most \\$50,000 annually, `'n_at_most_50k'`.\n- The percentage of individuals making more than \\$50,000 annually, `'greater_percent'`.\n\n**Hint:** You may need to look at the table above to understand how the `'income'` entries are formatted. ", "_____no_output_____" ] ], [ [ "# Total number of records\nn_records = data.shape[0]\n\n# Number of records where individual's income is more than $50,000\nn_greater_50k = data[data['income'] == '>50K'].shape[0]\n\n# Number of records where individual's income is at most $50,000\nn_at_most_50k = data[data['income'] == '<=50K'].shape[0]\n\n# Percentage of individuals whose income is more than $50,000\ngreater_percent = n_greater_50k / (n_records / 100.0)\n\n# Print the results\nprint \"Total number of records: {}\".format(n_records)\nprint \"Individuals making more than $50,000: {}\".format(n_greater_50k)\nprint \"Individuals making at most $50,000: {}\".format(n_at_most_50k)\nprint \"Percentage of individuals making more than $50,000: {:.2f}%\".format(greater_percent)", "Total number of records: 45222\nIndividuals making more than $50,000: 11208\nIndividuals making at most $50,000: 34014\nPercentage of individuals making more than $50,000: 24.78%\n" ] ], [ [ "----\n## Preparing the Data\nBefore data can be used as input for machine learning algorithms, it often must be cleaned, formatted, and restructured — this is typically known as **preprocessing**. Fortunately, for this dataset, there are no invalid or missing entries we must deal with, however, there are some qualities about certain features that must be adjusted. This preprocessing can help tremendously with the outcome and predictive power of nearly all learning algorithms.", "_____no_output_____" ], [ "### Transforming Skewed Continuous Features\nA dataset may sometimes contain at least one feature whose values tend to lie near a single number, but will also have a non-trivial number of vastly larger or smaller values than that single number. Algorithms can be sensitive to such distributions of values and can underperform if the range is not properly normalized. With the census dataset two features fit this description: '`capital-gain'` and `'capital-loss'`. \n\nRun the code cell below to plot a histogram of these two features. Note the range of the values present and how they are distributed.", "_____no_output_____" ] ], [ [ "# Split the data into features and target label\nincome_raw = data['income']\nfeatures_raw = data.drop('income', axis = 1)\n\n# Visualize skewed continuous features of original data\nvs.distribution(data)", "_____no_output_____" ] ], [ [ "For highly-skewed feature distributions such as `'capital-gain'` and `'capital-loss'`, it is common practice to apply a <a href=\"https://en.wikipedia.org/wiki/Data_transformation_(statistics)\">logarithmic transformation</a> on the data so that the very large and very small values do not negatively affect the performance of a learning algorithm. Using a logarithmic transformation significantly reduces the range of values caused by outliers. Care must be taken when applying this transformation however: The logarithm of `0` is undefined, so we must translate the values by a small amount above `0` to apply the the logarithm successfully.\n\nRun the code cell below to perform a transformation on the data and visualize the results. Again, note the range of values and how they are distributed. ", "_____no_output_____" ] ], [ [ "# Log-transform the skewed features\nskewed = ['capital-gain', 'capital-loss']\nfeatures_raw[skewed] = data[skewed].apply(lambda x: np.log(x + 1))\n\n# Visualize the new log distributions\nvs.distribution(features_raw, transformed = True)", "_____no_output_____" ] ], [ [ "### Normalizing Numerical Features\nIn addition to performing transformations on features that are highly skewed, it is often good practice to perform some type of scaling on numerical features. Applying a scaling to the data does not change the shape of each feature's distribution (such as `'capital-gain'` or `'capital-loss'` above); however, normalization ensures that each feature is treated equally when applying supervised learners. Note that once scaling is applied, observing the data in its raw form will no longer have the same original meaning, as exampled below.\n\nRun the code cell below to normalize each numerical feature. We will use [`sklearn.preprocessing.MinMaxScaler`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html) for this.", "_____no_output_____" ] ], [ [ "# Import sklearn.preprocessing.StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\n\n# Initialize a scaler, then apply it to the features\nscaler = MinMaxScaler()\nnumerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']\nfeatures_raw[numerical] = scaler.fit_transform(data[numerical])\n\n# Show an example of a record with scaling applied\ndisplay(features_raw.head(n = 1))", "_____no_output_____" ] ], [ [ "### Implementation: Data Preprocessing\n\nFrom the table in **Exploring the Data** above, we can see there are several features for each record that are non-numeric. Typically, learning algorithms expect input to be numeric, which requires that non-numeric features (called *categorical variables*) be converted. One popular way to convert categorical variables is by using the **one-hot encoding** scheme. One-hot encoding creates a _\"dummy\"_ variable for each possible category of each non-numeric feature. For example, assume `someFeature` has three possible entries: `A`, `B`, or `C`. We then encode this feature into `someFeature_A`, `someFeature_B` and `someFeature_C`.\n\n| | someFeature | | someFeature_A | someFeature_B | someFeature_C |\n| :-: | :-: | | :-: | :-: | :-: |\n| 0 | B | | 0 | 1 | 0 |\n| 1 | C | ----> one-hot encode ----> | 0 | 0 | 1 |\n| 2 | A | | 1 | 0 | 0 |\n\nAdditionally, as with the non-numeric features, we need to convert the non-numeric target label, `'income'` to numerical values for the learning algorithm to work. Since there are only two possible categories for this label (\"<=50K\" and \">50K\"), we can avoid using one-hot encoding and simply encode these two categories as `0` and `1`, respectively. In code cell below, you will need to implement the following:\n - Use [`pandas.get_dummies()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html?highlight=get_dummies#pandas.get_dummies) to perform one-hot encoding on the `'features_raw'` data.\n - Convert the target label `'income_raw'` to numerical entries.\n - Set records with \"<=50K\" to `0` and records with \">50K\" to `1`.", "_____no_output_____" ] ], [ [ "# One-hot encode the 'features_raw' data using pandas.get_dummies()\nfeatures = pd.get_dummies(features_raw)\n\n# Encode the 'income_raw' data to numerical values\nincome = income_raw.apply(lambda x: 1 if x == '>50K' else 0)\n\n# Print the number of features after one-hot encoding\nencoded = list(features.columns)\nprint \"{} total features after one-hot encoding.\".format(len(encoded))\n\n# Uncomment the following line to see the encoded feature names\nprint encoded", "103 total features after one-hot encoding.\n['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week', 'workclass_ Federal-gov', 'workclass_ Local-gov', 'workclass_ Private', 'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc', 'workclass_ State-gov', 'workclass_ Without-pay', 'education_level_ 10th', 'education_level_ 11th', 'education_level_ 12th', 'education_level_ 1st-4th', 'education_level_ 5th-6th', 'education_level_ 7th-8th', 'education_level_ 9th', 'education_level_ Assoc-acdm', 'education_level_ Assoc-voc', 'education_level_ Bachelors', 'education_level_ Doctorate', 'education_level_ HS-grad', 'education_level_ Masters', 'education_level_ Preschool', 'education_level_ Prof-school', 'education_level_ Some-college', 'marital-status_ Divorced', 'marital-status_ Married-AF-spouse', 'marital-status_ Married-civ-spouse', 'marital-status_ Married-spouse-absent', 'marital-status_ Never-married', 'marital-status_ Separated', 'marital-status_ Widowed', 'occupation_ Adm-clerical', 'occupation_ Armed-Forces', 'occupation_ Craft-repair', 'occupation_ Exec-managerial', 'occupation_ Farming-fishing', 'occupation_ Handlers-cleaners', 'occupation_ Machine-op-inspct', 'occupation_ Other-service', 'occupation_ Priv-house-serv', 'occupation_ Prof-specialty', 'occupation_ Protective-serv', 'occupation_ Sales', 'occupation_ Tech-support', 'occupation_ Transport-moving', 'relationship_ Husband', 'relationship_ Not-in-family', 'relationship_ Other-relative', 'relationship_ Own-child', 'relationship_ Unmarried', 'relationship_ Wife', 'race_ Amer-Indian-Eskimo', 'race_ Asian-Pac-Islander', 'race_ Black', 'race_ Other', 'race_ White', 'sex_ Female', 'sex_ Male', 'native-country_ Cambodia', 'native-country_ Canada', 'native-country_ China', 'native-country_ Columbia', 'native-country_ Cuba', 'native-country_ Dominican-Republic', 'native-country_ Ecuador', 'native-country_ El-Salvador', 'native-country_ England', 'native-country_ France', 'native-country_ Germany', 'native-country_ Greece', 'native-country_ Guatemala', 'native-country_ Haiti', 'native-country_ Holand-Netherlands', 'native-country_ Honduras', 'native-country_ Hong', 'native-country_ Hungary', 'native-country_ India', 'native-country_ Iran', 'native-country_ Ireland', 'native-country_ Italy', 'native-country_ Jamaica', 'native-country_ Japan', 'native-country_ Laos', 'native-country_ Mexico', 'native-country_ Nicaragua', 'native-country_ Outlying-US(Guam-USVI-etc)', 'native-country_ Peru', 'native-country_ Philippines', 'native-country_ Poland', 'native-country_ Portugal', 'native-country_ Puerto-Rico', 'native-country_ Scotland', 'native-country_ South', 'native-country_ Taiwan', 'native-country_ Thailand', 'native-country_ Trinadad&Tobago', 'native-country_ United-States', 'native-country_ Vietnam', 'native-country_ Yugoslavia']\n" ] ], [ [ "### Shuffle and Split Data\nNow all _categorical variables_ have been converted into numerical features, and all numerical features have been normalized. As always, we will now split the data (both features and their labels) into training and test sets. 80% of the data will be used for training and 20% for testing.\n\nRun the code cell below to perform this split.", "_____no_output_____" ] ], [ [ "# Import train_test_split\nfrom sklearn.cross_validation import train_test_split\n\n# Split the 'features' and 'income' data into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(features, income, test_size = 0.2, random_state = 0)\n\n# Show the results of the split\nprint \"Training set has {} samples.\".format(X_train.shape[0])\nprint \"Testing set has {} samples.\".format(X_test.shape[0])", "Training set has 36177 samples.\nTesting set has 9045 samples.\n" ] ], [ [ "----\n## Evaluating Model Performance\nIn this section, we will investigate four different algorithms, and determine which is best at modeling the data. Three of these algorithms will be supervised learners of your choice, and the fourth algorithm is known as a *naive predictor*.", "_____no_output_____" ], [ "### Metrics and the Naive Predictor\n*CharityML*, equipped with their research, knows individuals that make more than \\$50,000 are most likely to donate to their charity. Because of this, *CharityML* is particularly interested in predicting who makes more than \\$50,000 accurately. It would seem that using **accuracy** as a metric for evaluating a particular model's performace would be appropriate. Additionally, identifying someone that *does not* make more than \\$50,000 as someone who does would be detrimental to *CharityML*, since they are looking to find individuals willing to donate. Therefore, a model's ability to precisely predict those that make more than \\$50,000 is *more important* than the model's ability to **recall** those individuals. We can use **F-beta score** as a metric that considers both precision and recall:\n\n$$ F_{\\beta} = (1 + \\beta^2) \\cdot \\frac{precision \\cdot recall}{\\left( \\beta^2 \\cdot precision \\right) + recall} $$\n\nIn particular, when $\\beta = 0.5$, more emphasis is placed on precision. This is called the **F$_{0.5}$ score** (or F-score for simplicity).\n\nLooking at the distribution of classes (those who make at most \\$50,000, and those who make more), it's clear most individuals do not make more than \\$50,000. This can greatly affect **accuracy**, since we could simply say *\"this person does not make more than \\$50,000\"* and generally be right, without ever looking at the data! Making such a statement would be called **naive**, since we have not considered any information to substantiate the claim. It is always important to consider the *naive prediction* for your data, to help establish a benchmark for whether a model is performing well. That been said, using that prediction would be pointless: If we predicted all people made less than \\$50,000, *CharityML* would identify no one as donors. ", "_____no_output_____" ], [ "### Question 1 - Naive Predictor Performace\n*If we chose a model that always predicted an individual made more than \\$50,000, what would that model's accuracy and F-score be on this dataset?* \n**Note:** You must use the code cell below and assign your results to `'accuracy'` and `'fscore'` to be used later.", "_____no_output_____" ] ], [ [ "# Calculate accuracy\naccuracy = 1.0 * n_greater_50k / n_records\n\n# Calculate F-score using the formula above for beta = 0.5\nrecall = 1.0\nfscore = (\n (1 + 0.5**2) * accuracy * recall\n) / (\n 0.5**2 * accuracy + recall\n)\n\n# Print the results \nprint \"Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]\".format(accuracy, fscore)", "Naive Predictor: [Accuracy score: 0.2478, F-score: 0.2917]\n" ] ], [ [ "### Supervised Learning Models\n**The following supervised learning models are currently available in** [`scikit-learn`](http://scikit-learn.org/stable/supervised_learning.html) **that you may choose from:**\n- Gaussian Naive Bayes (GaussianNB)\n- Decision Trees\n- Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)\n- K-Nearest Neighbors (KNeighbors)\n- Stochastic Gradient Descent Classifier (SGDC)\n- Support Vector Machines (SVM)\n- Logistic Regression", "_____no_output_____" ], [ "### Question 2 - Model Application\nList three of the supervised learning models above that are appropriate for this problem that you will test on the census data. For each model chosen\n- *Describe one real-world application in industry where the model can be applied.* (You may need to do research for this — give references!)\n- *What are the strengths of the model; when does it perform well?*\n- *What are the weaknesses of the model; when does it perform poorly?*\n- *What makes this model a good candidate for the problem, given what you know about the data?*", "_____no_output_____" ], [ "**Answer: **\nTotal number of records: 45222\n\nThe algorithms we're searching here is for a supervised classification problem predicting a category using labeled data with less than 100K samples.\n* **Support Vector Machine** (SVM):\n * Real-world application: classifying proteins, protein-protein interaction\n * References: [Bioinformatics - Semi-Supervised Multi-Task Learning for Predicting Interactions between HIV-1 and Human Proteins](https://static.googleusercontent.com/media/research.google.com/de//pubs/archive/35765.pdf)\n * Strengths of the model:\n * effective in high dimensional spaces and with nonlinear relationships\n * robust to noise (because margins maximized and theoretical bounds on overfitting)\n * Weaknesses of the model:\n * requires to select a good kernel function and a number of hyperparameters such as the regularization parameter and the number of iterations\n * sensitive to feature scaling\n * model parameters are difficult to interpret\n * requires significant memory and processing power\n * tuning the regularization parameters required to avoid overfitting\n * Reasoning: *Linear SVC* is the optimal estimator following the [Scikit-Learn - Choosing the right estimator](http://scikit-learn.org/stable/tutorial/machine_learning_map/) when using less than 100K samples to solve to classification problem.\n* **Logistic Regression**:\n * Real-world application: media and advertising campaigns optimization and decision making\n * References: [Evaluating Online Ad Campaigns in a Pipeline: Causal Models At Scale](https://static.googleusercontent.com/media/research.google.com/de//pubs/archive/36552.pdf)\n * Strengths of the model:\n * simple, no user-defined parameters to experiment with unless you regularize, β is intuitive\n * fast to train and to predict\n * easy to interpret: output can be interpreted as a probability\n * pretty robust to noise with low variance and less prone to over-fitting\n * lots of ways to regularize the model\n * Weaknesses of the model:\n * unstable when one predictor could almost explain the response variable\n * often less accurate than the newer methods\n * Interpreting θ isn't straightforward\n * Reasoning: It's similar to *linear SVC*, is widely used and can be easyly implemented.\n* **K-Nearest Neighbors (KNeighbors)**:\n * Real-world application: image and video content classification\n * References: [Clustering billions of images with large scale nearest neighbor search](https://static.googleusercontent.com/media/research.google.com/de//pubs/archive/32616.pdf)\n * Strengths of the model: \n * simple and powerful\n * easy to explain\n * no training involved (\"lazy\")\n * naturally handles multiclass classification and regression\n * learns nonlinear boundaries\n * Weaknesses of the model:\n * expensive and slow to predict new instances (\"lazy\")\n * must define a meaningful distance function (preference bias)\n * need to decide on a good distance metric\n * performs poorly on high-dimensionality datasets (curse of high dimensionality) \n * Reasoning: *KNeighbors* classifier is the next option suggested on the machine learning map when *linear SVC* does work poor. Since our dataset is low-dimensional and it should generate reasonable results.\n ", "_____no_output_____" ], [ "### Implementation - Creating a Training and Predicting Pipeline\nTo properly evaluate the performance of each model you've chosen, it's important that you create a training and predicting pipeline that allows you to quickly and effectively train models using various sizes of training data and perform predictions on the testing data. Your implementation here will be used in the following section.\nIn the code block below, you will need to implement the following:\n - Import `fbeta_score` and `accuracy_score` from [`sklearn.metrics`](http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics).\n - Fit the learner to the sampled training data and record the training time.\n - Perform predictions on the test data `X_test`, and also on the first 300 training points `X_train[:300]`.\n - Record the total prediction time.\n - Calculate the accuracy score for both the training subset and testing set.\n - Calculate the F-score for both the training subset and testing set.\n - Make sure that you set the `beta` parameter!", "_____no_output_____" ] ], [ [ "# Import two metrics from sklearn - fbeta_score and accuracy_score\nfrom sklearn.metrics import fbeta_score, accuracy_score\n\ndef train_predict(learner, sample_size, X_train, y_train, X_test, y_test): \n '''\n inputs:\n - learner: the learning algorithm to be trained and predicted on\n - sample_size: the size of samples (number) to be drawn from training set\n - X_train: features training set\n - y_train: income training set\n - X_test: features testing set\n - y_test: income testing set\n '''\n \n results = {}\n \n # Fit the learner to the training data using slicing with 'sample_size'\n start = time() # Get start time\n learner = learner.fit(X_train[:sample_size], y_train[:sample_size])\n end = time() # Get end time\n \n # Calculate the training time\n results['train_time'] = end - start\n \n # Get the predictions on the test set,\n # then get predictions on the first 300 training samples\n start = time() # Get start time\n predictions_test = learner.predict(X_test)\n predictions_train = learner.predict(X_train[:300])\n end = time() # Get end time\n \n # Calculate the total prediction time\n results['pred_time'] = end - start\n \n # Compute accuracy on the first 300 training samples\n results['acc_train'] = accuracy_score(y_train[:300], predictions_train)\n \n # Compute accuracy on test set\n results['acc_test'] = accuracy_score(y_test, predictions_test)\n \n # Compute F-score on the the first 300 training samples\n results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=.5)\n \n # Compute F-score on the test set\n results['f_test'] = fbeta_score(y_test, predictions_test, beta=.5)\n \n # Success\n print \"{} trained on {} samples.\".format(learner.__class__.__name__, sample_size)\n \n # Return the results\n return results", "_____no_output_____" ] ], [ [ "### Implementation: Initial Model Evaluation\nIn the code cell, you will need to implement the following:\n- Import the three supervised learning models you've discussed in the previous section.\n- Initialize the three models and store them in `'clf_A'`, `'clf_B'`, and `'clf_C'`.\n - Use a `'random_state'` for each model you use, if provided.\n - **Note:** Use the default settings for each model — you will tune one specific model in a later section.\n- Calculate the number of records equal to 1%, 10%, and 100% of the training data.\n - Store those values in `'samples_1'`, `'samples_10'`, and `'samples_100'` respectively.\n\n**Note:** Depending on which algorithms you chose, the following implementation may take some time to run!", "_____no_output_____" ] ], [ [ "# Import the three supervised learning models from sklearn\nfrom sklearn.svm import LinearSVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\n\n# Initialize the three models\nclf_A = LinearSVC(random_state=42)\nclf_B = LogisticRegression(random_state=42)\nclf_C = KNeighborsClassifier()\n\n# Calculate the number of samples for 1%, 10%, and 100% of the training data\nn = len(y_train)\nsamples_1 = int(round(n / 100.0))\nsamples_10 = int(round(n / 10.0))\nsamples_100 = n\n\n# Collect results on the learners\nresults = {}\nfor clf in [clf_A, clf_B, clf_C]:\n clf_name = clf.__class__.__name__\n results[clf_name] = {}\n for i, samples in enumerate([samples_1, samples_10, samples_100]):\n results[clf_name][i] = \\\n train_predict(clf, samples, X_train, y_train, X_test, y_test)\n\n# Run metrics visualization for the three supervised learning models chosen\nvs.evaluate(results, accuracy, fscore)", "LinearSVC trained on 362 samples.\nLinearSVC trained on 3618 samples.\nLinearSVC trained on 36177 samples.\nLogisticRegression trained on 362 samples.\nLogisticRegression trained on 3618 samples.\nLogisticRegression trained on 36177 samples.\nKNeighborsClassifier trained on 362 samples.\nKNeighborsClassifier trained on 3618 samples.\nKNeighborsClassifier trained on 36177 samples.\n" ] ], [ [ "----\n## Improving Results\nIn this final section, you will choose from the three supervised learning models the *best* model to use on the student data. You will then perform a grid search optimization for the model over the entire training set (`X_train` and `y_train`) by tuning at least one parameter to improve upon the untuned model's F-score. ", "_____no_output_____" ], [ "### Question 3 - Choosing the Best Model\n*Based on the evaluation you performed earlier, in one to two paragraphs, explain to *CharityML* which of the three models you believe to be most appropriate for the task of identifying individuals that make more than \\$50,000.* \n**Hint:** Your answer should include discussion of the metrics, prediction/training time, and the algorithm's suitability for the data.", "_____no_output_____" ], [ "**Answer: **\n\n| | training time | predicting time | training set scores | testing set scores |\n|----------------------|----------------------------|-----------------|----------------|\n| **LinearSVC** | ++ | +++ | +++ | **+++** |\n| LogisticRegression | +++ | +++ | ++ | ++ |\n| KNeighborsClassifier | + | --- | +++ | + |\n\nBased on the evaluation the *linear SVC* model is the most appropriate for the task. Compared to the other two models in testing, it's both fast and has the highest scores. While *linear SVC* and *logistic regression* have almost the same accuracy, its *f-score* is slightly higher indicating that *linear SVC* has more correct positive predictions on actual positive observations.\n\nAlthough *logistic regression* has a shorter training time, it has worse *f-score* when applied to the testing set. In a real-world setting the testing scores are the metrics that do matter. The moderate longer training time can be ignored. *K-neighbors* outperforms the other two only when predicting the training scores. But with an even poorer testing score it actually shows that the model has an overfitting problem.", "_____no_output_____" ], [ "### Question 4 - Describing the Model in Layman's Terms\n*In one to two paragraphs, explain to *CharityML*, in layman's terms, how the final model chosen is supposed to work. Be sure that you are describing the major qualities of the model, such as how the model is trained and how the model makes a prediction. Avoid using advanced mathematical or technical jargon, such as describing equations or discussing the algorithm implementation.*", "_____no_output_____" ], [ "**Answer: ** \n\nAs the final model we used a classifier called *linear SVC* which assumes that the underlying data are linearly separable. In a simplified 2-dimensional space this technique attemps to find the best line that separates the two classes of points with the largest margin. In higher dimensional space, the algorithm searches for the best hyperplane following the same principle by maximizing the margin (e.g. a plane in 3-dimensional space).\n\nIn our case, in the training phase the algorithm calculates the best model to separate the different classes in the training data by a maximum margin. And with the trained model the algorithm is able to predict the unseen examples.\n", "_____no_output_____" ], [ "### Implementation: Model Tuning\nFine tune the chosen model. Use grid search (`GridSearchCV`) with at least one important parameter tuned with at least 3 different values. You will need to use the entire training set for this. In the code cell below, you will need to implement the following:\n- Import [`sklearn.grid_search.GridSearchCV`](http://scikit-learn.org/0.17/modules/generated/sklearn.grid_search.GridSearchCV.html) and [`sklearn.metrics.make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html).\n- Initialize the classifier you've chosen and store it in `clf`.\n - Set a `random_state` if one is available to the same state you set before.\n- Create a dictionary of parameters you wish to tune for the chosen model.\n - Example: `parameters = {'parameter' : [list of values]}`.\n - **Note:** Avoid tuning the `max_features` parameter of your learner if that parameter is available!\n- Use `make_scorer` to create an `fbeta_score` scoring object (with $\\beta = 0.5$).\n- Perform grid search on the classifier `clf` using the `'scorer'`, and store it in `grid_obj`.\n- Fit the grid search object to the training data (`X_train`, `y_train`), and store it in `grid_fit`.\n\n**Note:** Depending on the algorithm chosen and the parameter list, the following implementation may take some time to run!", "_____no_output_____" ] ], [ [ "# Import 'GridSearchCV', 'make_scorer', and any other necessary libraries\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.metrics import make_scorer\n\n# Initialize the classifier\nclf = LinearSVC(random_state=42)\n\n# Create the parameters list you wish to tune\nparameters = {\n 'C': [.1, .5, 1.0, 5.0, 10.0],\n 'loss': ['hinge', 'squared_hinge'],\n 'tol': [1e-3, 1e-4, 1e-5],\n 'random_state': [0, 42, 10000]\n}\n\n# Make an fbeta_score scoring object\nscorer = make_scorer(fbeta_score, beta=.5)\n\n# Perform grid search on the classifier using 'scorer' as the scoring method\ngrid_obj = GridSearchCV(clf, parameters, scoring=scorer)\n\n# Fit the grid search object to the training data and find the optimal parameters\ngrid_fit = grid_obj.fit(X_train, y_train)\n\n# Get the estimator\nbest_clf = grid_fit.best_estimator_\n\n# Make predictions using the unoptimized and model\npredictions = (clf.fit(X_train, y_train)).predict(X_test)\nbest_predictions = best_clf.predict(X_test)\n\n# Report the before-and-afterscores\nprint \"Unoptimized model\\n------\"\nprint \"Accuracy score on testing data: {:.4f}\".format(accuracy_score(y_test, predictions))\nprint \"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, predictions, beta = 0.5))\nprint \"\\nOptimized Model\\n------\"\nprint \"Final accuracy score on the testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions))\nprint \"Final F-score on the testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5))", "Unoptimized model\n------\nAccuracy score on testing data: 0.8507\nF-score on testing data: 0.7054\n\nOptimized Model\n------\nFinal accuracy score on the testing data: 0.8514\nFinal F-score on the testing data: 0.7063\n" ], [ "# print optimized parameters\nprint(\"Optimized params for Linear SVM: {}\".format(\n grid_fit.best_params_\n))", "Optimized params for Linear SVM: {'loss': 'squared_hinge', 'C': 10.0, 'random_state': 0, 'tol': 0.001}\n" ] ], [ [ "### Question 5 - Final Model Evaluation\n_What is your optimized model's accuracy and F-score on the testing data? Are these scores better or worse than the unoptimized model? How do the results from your optimized model compare to the naive predictor benchmarks you found earlier in **Question 1**?_ \n**Note:** Fill in the table below with your results, and then provide discussion in the **Answer** box.", "_____no_output_____" ], [ "#### Results:\n\n| Metric | Benchmark Predictor | Unoptimized Model | Optimized Model |\n| :------------: | :-----------------: | :---------------: | :-------------: | \n| Accuracy Score | .2478 | .8507 | .8514 |\n| F-score | .2917 | .7054 | .7063 |\n", "_____no_output_____" ], [ "**Answer: **\n\nThe scores of the *optimized model* are a bit better than the *unoptimized model* showing that the defaults were actually very good in the first place. Compared to the *benchmark predictor*, the optimized model is by manifold better with larger accuracy and f-scores.", "_____no_output_____" ], [ "----\n## Feature Importance\n\nAn important task when performing supervised learning on a dataset like the census data we study here is determining which features provide the most predictive power. By focusing on the relationship between only a few crucial features and the target label we simplify our understanding of the phenomenon, which is most always a useful thing to do. In the case of this project, that means we wish to identify a small number of features that most strongly predict whether an individual makes at most or more than \\$50,000.\n\nChoose a scikit-learn classifier (e.g., adaboost, random forests) that has a `feature_importance_` attribute, which is a function that ranks the importance of features according to the chosen classifier. In the next python cell fit this classifier to training set and use this attribute to determine the top 5 most important features for the census dataset.", "_____no_output_____" ], [ "### Question 6 - Feature Relevance Observation\nWhen **Exploring the Data**, it was shown there are thirteen available features for each individual on record in the census data. \n_Of these thirteen records, which five features do you believe to be most important for prediction, and in what order would you rank them and why?_", "_____no_output_____" ], [ "**Answer:**\nOf the thirteen available features we believe that the following five features are the most important for prediction and ordered them by their importance with the most important at top. From looking at the data and following the rules of our society:\n* *occupation*: different occupations have usually different salary ranges\n* *capital-gain*: the rich get richer. Capital gain is an indicator of the personal wealth.\n* *education-level*: when employed, people with higher education gets better paid\n* *hours-per-week*: part time jobs are often less paid\n* *age*: older people tends to earn more", "_____no_output_____" ], [ "### Implementation - Extracting Feature Importance\nChoose a `scikit-learn` supervised learning algorithm that has a `feature_importance_` attribute availble for it. This attribute is a function that ranks the importance of each feature when making predictions based on the chosen algorithm.\n\nIn the code cell below, you will need to implement the following:\n - Import a supervised learning model from sklearn if it is different from the three used earlier.\n - Train the supervised model on the entire training set.\n - Extract the feature importances using `'.feature_importances_'`.", "_____no_output_____" ] ], [ [ "# Import a supervised learning model that has 'feature_importances_'\nfrom sklearn.ensemble import AdaBoostClassifier\n\n# Train the supervised model on the training set \nmodel = AdaBoostClassifier(random_state=42).fit(X_train, y_train)\n\n# Extract the feature importances\nimportances = model.feature_importances_\n\n# Plot\nvs.feature_plot(importances, X_train, y_train)", "_____no_output_____" ] ], [ [ "### Question 7 - Extracting Feature Importance\n\nObserve the visualization created above which displays the five most relevant features for predicting if an individual makes at most or above \\$50,000. \n_How do these five features compare to the five features you discussed in **Question 6**? If you were close to the same answer, how does this visualization confirm your thoughts? If you were not close, why do you think these features are more relevant?_", "_____no_output_____" ] ], [ [ "# print top 10 features importances\ndef rank_features(features, scores, descending=True, n=10):\n \"\"\"\n sorts and cuts features by scores.\n :return: array of [feature name, score] tuples\n \"\"\"\n return sorted(\n [[f, s] for f, s in zip(features, scores) if s],\n key=lambda x: x[1],\n reverse=descending\n )[:n]\n\nrank_features(\n features.columns,\n importances\n)", "_____no_output_____" ], [ "# capital-loss and income have a positive correlation\nfeatures['capital-loss'].corr(income)", "_____no_output_____" ] ], [ [ "**Answer:**\n\nFrom the top 5 features selected by *AdaBoostClassifier* we got 4 hits (*age*, *capital-gain*, *hours-per-week* and *education-level*). That *capital-loss* has a such big influence is really surprising and by looking at the cell above, *income* and *capital-loss* are even positively correlated. Our top one guess *occupation* hasn't made into top 10 in the feature importances.\n\nThe visualization of the feature importances confirms our guess that our observation in the society is actually true that older and higher educated people with money (big *capital-loss* or *capital-gain*) would have higher salaries. These thoughts are now quantified and explained by the classfier.", "_____no_output_____" ], [ "### Feature Selection\nHow does a model perform if we only use a subset of all the available features in the data? With less features required to train, the expectation is that training and prediction time is much lower — at the cost of performance metrics. From the visualization above, we see that the top five most important features contribute more than half of the importance of **all** features present in the data. This hints that we can attempt to *reduce the feature space* and simplify the information required for the model to learn. The code cell below will use the same optimized model you found earlier, and train it on the same training set *with only the top five important features*. ", "_____no_output_____" ] ], [ [ "# Import functionality for cloning a model\nfrom sklearn.base import clone\n\n# Reduce the feature space\nX_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]\nX_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]\n\n# Train on the \"best\" model found from grid search earlier\nstart = time()\nclf = (clone(best_clf)).fit(X_train_reduced, y_train)\ntraining_time_reduced = time() - start\n\n# Make new predictions\nreduced_predictions = clf.predict(X_test_reduced)\n\n# Report scores from the final model using both versions of data\nprint \"Final Model trained on full data\\n------\"\nprint \"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions))\nprint \"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5))\nprint \"\\nFinal Model trained on reduced data\\n------\"\nprint \"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, reduced_predictions))\nprint \"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, reduced_predictions, beta = 0.5))", "Final Model trained on full data\n------\nAccuracy on testing data: 0.8514\nF-score on testing data: 0.7063\n\nFinal Model trained on reduced data\n------\nAccuracy on testing data: 0.8096\nF-score on testing data: 0.5983\n" ], [ "# compare scores\ndef relative_diff_pct(x, y):\n \"\"\"\n returns the relative difference between x and y in percent.\n \"\"\"\n return 100 * ((y - x) / x)\n\nprint('Relative Diff. of accuracy-scores: {0:.2f}%'.format(\n relative_diff_pct(.8514, .8096)\n))\nprint('Relative Diff. of f-scores: {0:.2f}%'.format(\n relative_diff_pct(.7063, .5983)\n))", "Relative Diff. of accuracy-scores: -4.91%\nRelative Diff. of f-scores: -15.29%\n" ], [ "# Train with full data\nstart = time()\nclf = (clone(best_clf)).fit(X_train, y_train)\ntraining_time_full = time() - start\n\nprint('Relative Diff. of training times: {0:.2f}%'.format(\n relative_diff_pct(training_time_reduced, training_time_full)\n))", "Relative Diff. of training times: 94.68%\n" ] ], [ [ "### Question 8 - Effects of Feature Selection\n*How does the final model's F-score and accuracy score on the reduced data using only five features compare to those same scores when all features are used?* \n*If training time was a factor, would you consider using the reduced data as your training set?*", "_____no_output_____" ], [ "**Answer:**", "_____no_output_____" ], [ "Both the accuracy and f-scores dropped down when using only the top 5 features. The f-scores have an **over 15% difference**, while the difference between the accuracy scores is at about 5%.\n\nThe training time with reduced data was more than **2 times faster** than the training time of the full data set. In some other scenarios when the training time or the computation power if of high priority, we would consider to use the reduced data. But since the difference between the f-scores are considerably large we would use the full training set for this problem.", "_____no_output_____" ], [ "## References\n\n* [Udacity - Machine Learning](https://classroom.udacity.com/courses/ud262)\n* [Laurad Hamilton - ML Cheat Sheet](http://www.lauradhamilton.com/machine-learning-algorithm-cheat-sheet)\n* [Scikit-Learn - ML Modules](http://scikit-learn.org/stable/modules/sgd.html)\n* [Scikit-Learn - AdaBoostClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html)\n* [rcompton - Supervised Learning Superstitions](https://github.com/rcompton/ml_cheat_sheet)\n* [Wikipedia - Support Vector Machine](https://en.wikipedia.org/wiki/Support_vector_machine#Definition)\n* [Quora - SVM in layman's terms](https://www.quora.com/What-does-support-vector-machine-SVM-mean-in-laymans-terms)", "_____no_output_____" ], [ "## Reproduction Environment", "_____no_output_____" ] ], [ [ "import IPython\nprint IPython.sys_info()", "{'commit_hash': u'5c9c918',\n 'commit_source': 'installation',\n 'default_encoding': 'cp936',\n 'ipython_path': 'C:\\\\dev\\\\anaconda\\\\lib\\\\site-packages\\\\IPython',\n 'ipython_version': '5.1.0',\n 'os_name': 'nt',\n 'platform': 'Windows-7-6.1.7601-SP1',\n 'sys_executable': 'C:\\\\dev\\\\anaconda\\\\python.exe',\n 'sys_platform': 'win32',\n 'sys_version': '2.7.13 |Anaconda custom (32-bit)| (default, Dec 19 2016, 13:36:02) [MSC v.1500 32 bit (Intel)]'}\n" ], [ "!pip freeze", "alabaster==0.7.9\nanaconda-client==1.6.0\nanaconda-navigator==1.4.3\nargcomplete==1.0.0\nastroid==1.4.9\nastropy==1.3\nBabel==2.3.4\nbackports-abc==0.5\nbackports.shutil-get-terminal-size==1.0.0\nbackports.ssl-match-hostname==3.4.0.2\nbeautifulsoup4==4.5.3\nbitarray==0.8.1\nblaze==0.10.1\nbokeh==0.12.4\nboto==2.45.0\nBottleneck==1.2.0\ncdecimal==2.3\ncffi==1.9.1\nchardet==2.3.0\nchest==0.2.3\nclick==6.7\ncloudpickle==0.2.2\nclyent==1.2.2\ncolorama==0.3.7\ncomtypes==1.1.2\nconda==4.3.16\nconfigobj==5.0.6\nconfigparser==3.5.0\ncontextlib2==0.5.4\ncookies==2.2.1\ncryptography==1.7.1\ncycler==0.10.0\nCython==0.25.2\ncytoolz==0.8.2\ndask==0.13.0\ndatashape==0.5.4\ndecorator==4.0.11\ndill==0.2.5\ndocutils==0.13.1\nenum34==1.1.6\net-xmlfile==1.0.1\nfastcache==1.0.2\nFlask==0.12\nFlask-Cors==3.0.2\nfuncsigs==1.0.2\nfunctools32==3.2.3.post2\nfutures==3.0.5\ngevent==1.2.1\nglueviz==0.9.1\ngreenlet==0.4.11\ngrin==1.2.1\nh5py==2.6.0\nHeapDict==1.0.0\nidna==2.2\nimagesize==0.7.1\nipaddress==1.0.18\nipykernel==4.5.2\nipython==5.1.0\nipython-genutils==0.1.0\nipywidgets==5.2.2\nisort==4.2.5\nitsdangerous==0.24\njdcal==1.3\njedi==0.9.0\nJinja2==2.9.4\njsonschema==2.5.1\njupyter==1.0.0\njupyter-client==4.4.0\njupyter-console==5.0.0\njupyter-core==4.2.1\nlazy-object-proxy==1.2.2\nllvmlite==0.15.0\nlocket==0.2.0\nlxml==3.7.2\nMarkupSafe==0.23\nmatplotlib==2.0.0\nmenuinst==1.4.4\nmistune==0.7.3\nmpmath==0.19\nmultipledispatch==0.4.9\nnbconvert==4.2.0\nnbformat==4.2.0\nnetworkx==1.11\nnltk==3.2.2\nnose==1.3.7\nnotebook==4.4.1\nnumba==0.30.1+0.g8c1033f.dirty\nnumexpr==2.6.1\nnumpy==1.11.3\nnumpydoc==0.6.0\nodo==0.5.0\nopenpyxl==2.4.1\npandas==0.19.2\npartd==0.3.7\npath.py==0.0.0\npathlib2==2.2.0\npatsy==0.4.1\npep8==1.7.0\npickleshare==0.7.4\nPillow==4.0.0\nply==3.9\nprompt-toolkit==1.0.9\npsutil==5.0.1\npy==1.4.32\npyasn1==0.1.9\npycosat==0.6.1\npycparser==2.17\npycrypto==2.6.1\npycurl==7.43.0\npyflakes==1.5.0\npygame==1.9.3\nPygments==2.1.3\npylint==1.6.4\npymongo==3.3.0\npyOpenSSL==16.2.0\npyparsing==2.1.4\npytest==3.0.5\npython-dateutil==2.6.0\npytz==2016.10\npywin32==220\nPyYAML==3.12\npyzmq==16.0.2\nQtAwesome==0.4.3\nqtconsole==4.2.1\nQtPy==1.2.1\nrequests==2.12.4\nrequests-file==1.4.1\nresponses==0.5.1\nrope==0.9.4\nscandir==1.4\nscikit-image==0.12.3\nscikit-learn==0.18.1\nscipy==0.18.1\nseaborn==0.7.1\nsimplegeneric==0.8.1\nsingledispatch==3.4.0.3\nsix==1.10.0\nsnowballstemmer==1.2.1\nsockjs-tornado==1.0.3\nsphinx==1.5.1\nspyder==3.1.2\nSQLAlchemy==1.1.5\nstatsmodels==0.6.1\nsubprocess32==3.2.7\nsympy==1.0\ntables==3.2.2\ntoolz==0.8.2\ntornado==4.4.2\ntraitlets==4.3.1\nunicodecsv==0.14.1\nwcwidth==0.1.7\nWerkzeug==0.11.15\nwidgetsnbextension==1.2.6\nwin-unicode-console==0.5\nwrapt==1.10.8\nxlrd==1.0.0\nXlsxWriter==0.9.6\nxlwings==0.10.2\nxlwt==1.2.0\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ] ]
d00eeb3072a4f4802f5cecbec4e1d4646745521e
13,899
ipynb
Jupyter Notebook
module_9_statistics_probability/probability_density_function_test.ipynb
wiplane/foundations-of-datascience-ml
289f8cddd8e91bc6ef7827c57e9e5ecdd574e596
[ "MIT" ]
3
2021-08-31T14:31:18.000Z
2021-09-16T07:30:32.000Z
module_9_statistics_probability/probability_density_function_test.ipynb
wiplane/foundations-of-datascience-ml
289f8cddd8e91bc6ef7827c57e9e5ecdd574e596
[ "MIT" ]
null
null
null
module_9_statistics_probability/probability_density_function_test.ipynb
wiplane/foundations-of-datascience-ml
289f8cddd8e91bc6ef7827c57e9e5ecdd574e596
[ "MIT" ]
3
2021-09-03T13:13:56.000Z
2022-02-23T22:32:01.000Z
75.538043
5,704
0.85999
[ [ [ "# Describing continuous variables using Probability Density Functions", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "data = np.random.normal(0.5, 0.1, 1000)", "_____no_output_____" ], [ "histogram = plt.hist(data, bins=10, range=(0.1, 1.5))", "_____no_output_____" ], [ "histogram = plt.hist(data, bins=20, range=(0.1, 1.5), density=True)", "_____no_output_____" ], [ "height = histogram[0][6].round(4)", "_____no_output_____" ], [ "x1 = histogram[1][6].round(4)", "_____no_output_____" ], [ "x2 = histogram[1][7].round(4)", "_____no_output_____" ], [ "3.24 * 0.07", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d00eec3f3f2747ff3d582562f692a3ebec6d2b1f
177,575
ipynb
Jupyter Notebook
Iris/Iris.ipynb
sachin032/Supervised-Machin-Learning
33c59673b6185eacfce52cfb147dd3ec8bd6ac67
[ "Apache-2.0" ]
null
null
null
Iris/Iris.ipynb
sachin032/Supervised-Machin-Learning
33c59673b6185eacfce52cfb147dd3ec8bd6ac67
[ "Apache-2.0" ]
null
null
null
Iris/Iris.ipynb
sachin032/Supervised-Machin-Learning
33c59673b6185eacfce52cfb147dd3ec8bd6ac67
[ "Apache-2.0" ]
null
null
null
237.717537
157,176
0.897536
[ [ [ "# __General basic approach for applying Data Science.__\n- Collect Data.<br>\n- Extract features.<br>\n- Extract the target(label).<br>\n- Select the Estimator for learning.<br>\n- Tune the parameters.<br>\n- Fit the train data set.<br> \n- Test against testing_data_set.<br>\n- Check accuracy.<br>\n- Deploy to production.<br>\n- Write unit test cases for model.<br>\n- write live notification for model.<br>\n- Keep trainig the model with new data(fresh data).<br>", "_____no_output_____" ], [ "__Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.__", "_____no_output_____" ] ], [ [ "#Import Seaborn\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "__Seaborn comes with the iris data set , all we need is to load it. After loading we can do some spy things over data__\n", "_____no_output_____" ], [ "<img src=\"iris-machinelearning.png\" />", "_____no_output_____" ] ], [ [ "#Load iris data set from Sea born\niris = sns.load_dataset(\"iris\")\niris.head(4)", "_____no_output_____" ], [ "%matplotlib inline\nimport seaborn as sns; \nsns.set()\nsns.pairplot(iris, hue='species', size=3.5);", "_____no_output_____" ] ], [ [ "__Drop 'Species' feature from feature matrix, and look at the shape.__", "_____no_output_____" ] ], [ [ "iris.shape", "_____no_output_____" ], [ "#Perform basic EDA \niris.describe()", "_____no_output_____" ], [ "#Spy over how many outcomes are present in the Dataset\niris.species.unique()", "_____no_output_____" ] ], [ [ "__Time to split the iris dataset into Training:Tesing datset. Remember there is no standard approach fro this dividation even though we divide, Based on suggestions from ML/Data science leaders 70:30 approach is good.__", "_____no_output_____" ] ], [ [ "#Import train_test_split\nfrom sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "#Split iris dataset into training and testing datset\ntrainIris , testIris = train_test_split(iris,test_size = 0.3)", "_____no_output_____" ], [ "#Look over training set\ntrainIris.head()", "_____no_output_____" ], [ "#Look over testing set\ntestIris.head()", "_____no_output_____" ] ], [ [ "__Testing dataset must not hold the target variable/outcomes, so that we can predict the outcome \nusing our trained regression model from trainig datset__ ", "_____no_output_____" ] ], [ [ "#Drop Species from testing dataset\ntestIris = testIris.drop(['species'],axis=1)", "_____no_output_____" ], [ "#Test set after dropping target/outcome column\ntestIris.head()", "_____no_output_____" ] ], [ [ "__As we have our training and testing datset ready, we have observed the Iris dataset,\nand have performed basic EDA over it. We can clearly see that this supervised learning problem.__", "_____no_output_____" ], [ "__TIme to pick some ML classifier, Train it , Test it__ &#9684;", "_____no_output_____" ], [ "__TO BE CONTINUED . . . .__", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
d00f151aa9061242e04714e878e85ed5b5067975
99,400
ipynb
Jupyter Notebook
notebooks/StructuralT1.ipynb
jhconning/DevII
fc9c9e91dae79eea3e55beb67b2de01d8c375b04
[ "MIT" ]
null
null
null
notebooks/StructuralT1.ipynb
jhconning/DevII
fc9c9e91dae79eea3e55beb67b2de01d8c375b04
[ "MIT" ]
null
null
null
notebooks/StructuralT1.ipynb
jhconning/DevII
fc9c9e91dae79eea3e55beb67b2de01d8c375b04
[ "MIT" ]
null
null
null
145.961821
24,828
0.875976
[ [ [ "# Structural Transformation Notes\n\nBelow some brief notes on general equilibrium modeling of structural transformation. Some of the presentation illustrates and expands upon this short useful survey:\n\n> Matsuyama, K., 2008. Structural change. in Durlauf and Blume eds. *The new Palgrave dictionary of economics* 2, pp.\n\nThe note is organized around the following sections:\n\n- Market Clearing Neo-Classical Models\n - Push out of agriculture vs. Pull into Manufacturing\n - Pull in an Open Economy Model\n - Push in Closed Economy with Non-homothetic preferences\n- Productivity growth caused by structural change\n- Impediments to structural change\n- Spillovers, Complementarities, and Multiple Equilibria \n \n---\n", "_____no_output_____" ], [ "## Market Clearing Neo-Classical Models\n\nHere we seek to explain structural transformation and the accompanying movement of labor out of agriculture and into other sectors in a market-clearing neo-classical model with no market failures. In these model the marginal value product of labor is the same in both agriculture and manufacturing, hence there is no 'dualism' due to market frictions of one kind or another.\n\nMatsuyama builds a very simple neo-classical model with two sectors (in effect a specific factors model). \n\n**Production**\n\nSector $j \\in (1,2)$ is given by $Y_j = A_j \\cdot F_j(n_j)$. Let $j=1$ be the primary (agricultural) sector and $j=2$ the secondary (manufacturing) sector, where $A_j$ represents Total Factor Productivity (TFP) in each sector. We normalize the size of the population to 1. Then, if $n$ is the share (and total) labor used in sector 1 then $1-n$ is the amount left to be in sector two. \n\nMatsuyama refers to $F$ only as a generic increasing concave function, but for purposes of the graph examples, let's specify:\n\n$$\nA_1 F_1(n) = A_1 n^\\alpha \\\\\nA_2 F_2(1-n) = A_2 (1-n)^\\nu \n$$", "_____no_output_____" ], [ "Competitive markets will insure that labor is efficiently allocated across sectors such that the marginal value product of labor be equalized in each sector:\n \n$$\nA_1 F_1^\\prime (n) = p A_2 F_2^\\prime (1-n)\n$$", "_____no_output_____" ], [ "where $p=P_2/P_1$ is the relative price of sector 2 goods.", "_____no_output_____" ], [ "We can trace out a production possibility frontier (PPF) by simply plotting $\\left( A_1 F_1(n), A F_2(1-n) \\right)$ as we vary $n$ from 0 to 1. Below we draw two PPFs. One with $A_1=A_2=1$ and another afteragricultural TFP has improved to $A_1=1.2$ (we are setting $\\alpha=\\nu=1/2$)", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import fsolve", "_____no_output_____" ], [ "def F(n, a):\n return n ** a\n\ndef Fprime(n, a):\n return a* n ** (a-1)\n\n\ndef PPF(A1=1, A2=1, a1=0.5, a2=0.5, ax=None): \n if ax is None:\n ax = plt.gca()\n n = np.linspace(0,1,50)\n plt.plot( A1*F(n, a1), A2*F(1-n, a2) )\n plt.xlabel(r'$Y_1$'), plt.ylabel(r'$Y_2$')", "_____no_output_____" ], [ "fig, ax = plt.subplots(1)\nPPF(A1=1, A2=1, ax=ax)\nPPF(A1=1.3, A2=1, ax=ax)\nax.set_xlim(left=0), ax.set_ylim(bottom=0)\nax.set_aspect('equal')", "_____no_output_____" ] ], [ [ "### Push and/or Pull\n\nThe large literature on structural transformation often distinguishes between forces that 'Push' or 'Pull' labor out of agriculture. \n\n'Pull' could come about, for example, via an increase over time of the relative price of manufactures $p$, or an increase in relative TFP $A_2/A_1$. These have the effect of shifting out the demand for labor (the marginal value product or labor curve $p A_2 F_2^\\prime (1-n)$ relative to that in agriculture, leading to an incipient rise in the manufacturing wage that transforms the economy by attracting labor to that sector.\n\nAs demonstrated below, it's easy to illustrate Pull effects in this economy with standard homothetic preferences in either the open or closed economy.\n\nThe 'Push' argument is associated the idea that rises in agricultural productivity $A_1$ will mean that more food can be produced with fewer workers and therefore that labor can be 'released' from agriculture to other sectors. A related prevalent view is than an 'agricultural revolution' is often a prior and necessary condition for an industrial revolution. \n\nIt turns out one has to be a bit harder to get this effect to emerge in this standard neo-classical model because, as we've just argued, raising the relative productivity in a sector tends *increase* demand for labor unless the relative price of the good happens to simultaneously fall by enough to reverse that effect. As we'll show one way to engineer such an effect is to assume non-homothetic preferences to rise to a form of Engel's law or that manufactures have a higher income elasticity of demand, such that the agricultural terms of trade deteriorate against agriculture as incomes expand.", "_____no_output_____" ], [ "### The Open Economy with Homothetic Preferences\n\nIn the open-economy version of this model, the relative price of manufactured goods $p$ is set and fixed on world markets and hence does not change during the period of analysis. We can focus on the optimum production allocation without worrying about preferences, because agents first maximize the value of income at world prices and then choose optimum consumption baskets.\n\nWe can plot labor demand in each sector and solve for the equilibrium labor allocation $n^*$ that solves:\n\n$$\nA_1 F_1^\\prime (n) = p A_2 F_2^\\prime (1-n)\n$$", "_____no_output_____" ] ], [ [ "def weq(A1=1, A2=1, a1=0.5, a2=0.5, p=1):\n \n def foc(n):\n return p * A2 * Fprime(1-n, a2) - A1 * Fprime(n, a1) \n \n n = 0.75 # guess\n ne = fsolve(foc, n)[0]\n we = A1 * Fprime(ne, a1)\n return ne, we\n\n\ndef sfm(A1=1, A2=1, a1=0.5, a2=0.5, p=1, ax=None):\n if ax is None:\n ax = plt.gca()\n nn = np.linspace(0.01, 0.99, 100)\n ax.plot(nn, A1 * Fprime(nn, a1))\n ax.plot(nn, p * A2 * Fprime(1-nn, a2))\n ne, we = weq(A1, A2, a1, a2, p)\n ax.scatter(ne, we)\n ax.axhline(we, linestyle =':')\n ax.vlines(x = ne, ymin=0, ymax=we, linestyle =':')\n ax.set_ylim(0,2)\n ax.set_xlim(0,1)\n ax.set_xlabel(r'$n$')\n ax.text(0.8, 0.9*A1 *Fprime(1,a1), r'$L_1^d$')\n ax.text(0.1, 0.9*p*A2 *Fprime(0.999, a2), r'$L_2^d$')", "_____no_output_____" ] ], [ [ "**Pull: Impact of increase in relative price of manufactures in open Economy**\n\nExactly like a specific factors model diagram. A very similar diagram would depict effect of increase in sector 2 relative TFP $A_2/A_1$", "_____no_output_____" ] ], [ [ "sfm(p=1)\nsfm(p=1.5)", "_____no_output_____" ] ], [ [ "Exogenously driven increases in the relative productivity of manufactures drives this 'pull' effect. As Matsuyama explains, this is the sort of mechanism envisioned by Lewis (1954) although the Lewis model also has a form of dualism not captured here. In particular, we can see (from the diagram above) that in these models the expansion of one sector can be choked off by a rising wage. Lewis' assumption of \"unlimited supplies of labor\" in agriculture amounts to saying that there will be a very elastic supply of labor aso wages will not be fast to rise.\n", "_____no_output_____" ], [ "### Non-homothetic preferences", "_____no_output_____" ], [ "In a closed economy the relative price $p$ is determined endogenously by a tangency between the PPF and the representative indifference curve. As mentioned above, we'll need non-homothetic preferences in order to get the kind of 'Push' effect used in Gollin et al (2002):\n\nThe consumer has Stone-Geary preferences of the form:\n\n$$\nU(C_1, C_2) = \\beta \\cdot \\log(C_1 - \\gamma) + \\log(C_2)\n$$\n\nIf $\\gamma=0$ these would be standard homothetic preferences with linear income expansion paths (i.e. consumers maintain consumption ratio $C_2/C_1$ as income expands). When $\\gamma>0$ preferences are non-homothetic. We interpret $\\gamma$ as a minimum agricultural (food) consumption requirement. At low levels of income, all income is devoted to satisfying the requirement, but once that level is reached, remaining income will be spent in constant expenditure shares:", "_____no_output_____" ], [ "$$\nC_1 - \\gamma = \\frac{\\beta}{1+\\beta} \\frac{Y}{P_1} \\\\\nC_2 = \\frac{1}{1+\\beta} \\frac{Y}{P_2}\n$$", "_____no_output_____" ], [ "Define $p=P_2/P_1$ as the relative price of good 2, then $C_1$ and $C_2$ will be consumed proportional to each other following: \n\n$$\nC_1 =\\gamma + (\\beta p) C_2\n$$", "_____no_output_____" ], [ "Below is a plot of the optimum $C_2/C_1$ ratio for homothetic (blue, $\\gamma=0$) and non-homothetic (orange, $\\gamma=1$) preferences. In the latter case, after income reaches the level at which subsistence food needs are satisfied, the $C_2/C_1$ ratio (think of a ray from origin to a point on orange line) increases as incomes expand.", "_____no_output_____" ] ], [ [ "c1 = np.linspace(0,4,100)\ndef c2(c1, gam, beta, p):\n return (c1 - gam)/(beta * p)\n\nplt.plot(c1, c2(c1, 0, 0.5, 1))\nplt.plot(c1, c2(c1, 1, 0.5, 1))\nplt.ylim(0, 4), plt.xlim(0, 4)\nplt.xlabel(r'$C_1$'), plt.ylabel(r'$C_2$')\nplt.grid()\nplt.gca().set_aspect('equal')", "_____no_output_____" ] ], [ [ "### Closed Economy\n\n We're looking for a tangency between the PPF and the representative agent's indifference curve, equal to the common price ratio. This $MRS = p= MPT$ condition can be written:\n\n$$\n\\frac{1}{\\beta} \\frac{C_1 - \\gamma}{C_2} = p = \\frac{A_1 F_1^\\prime (n)}{A_2 F_2^\\prime (1-n)} \n$$\n\nUsing the fact that a closed economy must produce what it consumes we can substitute $C_1 = A_1 F_1(n)$ and $C_2 = A_2 F_2(1-n)$ and manipulate to obtain condition (2) in Matsuyama:\n\n$$\nF_1(n) - \\frac{\\beta F_2(1-n) F_1 ^\\prime (n)}{F_2 ^\\prime (1-n)} = \\frac{\\gamma}{A_1}\n$$\n", "_____no_output_____" ], [ "This implicitly defines $n$ as a decreasing function of $A_1$. Two things are striking here (both partly consequences of the Cobb-Douglas):\n\n1) $A_2$ plays no role. As $A_2$ rises $p$ falls by just enough to offset, leaving relative demand for labor unchanged.\n\n2) At any $\\gamma >0$ the agricultural labor share $n$ will fall with $A_1$. This is the Push effect.\n\nIn the plot below we plot this left hand side in red. The dashed line represents a value of $\\frac{\\gamma}{A_1}$. We can see that if $A_1$ rises (the dashed line moves down) the new equilibrium will involve less agricultural labor $n$.", "_____no_output_____" ] ], [ [ "def lhs(n, a1, a2, beta):\n F1 = F(n, a1)\n dF1 = Fprime(n, a1)\n F2 = F(1-n, a2)\n dF2 = Fprime(1-n, a2)\n return F1 - (beta*F2*dF1)/dF2 ", "_____no_output_____" ], [ "n = np.linspace(0.2,0.7,50)\nplt.plot(n, lhs(n, 0.5, 0.5, 0.5), color='r')\nplt.axhline(0);\nplt.axhline(0.5, linestyle='--')\nplt.xlabel(r'$n$');", "_____no_output_____" ] ], [ [ "We can solve for the closed economy equilibrium and plot things on a PPF diagram.", "_____no_output_____" ] ], [ [ "def neq(A1=1, a1=0.5, a2=0.5, beta=0.5, gamma= 0.5):\n '''Closed economy eqn from MRS=MPT'''\n def foc(n):\n return lhs(n, a1, a2, beta) - gamma/A1\n \n n = 0.7 # guess\n ne = fsolve(foc, n)[0]\n return ne", "_____no_output_____" ], [ "def plot_opt(A1, A2, a1, a2, beta, gamma):\n ne = neq(A1, a1, a2, beta, gamma)\n Y1 = A1 * F(ne, a1)\n Y2 = A2 * F(1-ne, a2)\n p = (1/beta) * (Y1-gamma)/Y2\n print(f'A1={A1}, n={ne:0.2f}, p={p:0.2f}')\n plt.scatter(Y1, Y2)\n ax =plt.gca()\n PPF(A1=A1, A2=A2, a1=a1, a2=a2, ax=ax)", "_____no_output_____" ] ], [ [ "Here we see structural transformation and a rise in the relative price of manufactures as TFP in agriculture increases:", "_____no_output_____" ] ], [ [ "plot_opt(1, 1, 0.5, 0.75, 1, 0.4)\nplot_opt(2, 1, 0.5, 0.75, 1, 0.4)\nplt.xlim(left=0)\nplt.ylim(bottom=0);", "A1=1, n=0.58, p=0.70\nA1=2, n=0.48, p=1.63\n" ] ], [ [ "### Productivity growth caused by Structural Change", "_____no_output_____" ], [ "Matsuyama adds dynamics to the sort of model described above by assuming that TFP growth in manufacturing might respond to \"the stock of experience accumulated [in that sector]... through learning-by-doing.\" He captures this by positing that TFP in the sector in period $t$ is given by:\n\n$$\nA_{2t} = A(Q_t)\n$$\n\nwhere $Q_t$ is the stock of experience which follows this law of motion:\n\n$$\n\\frac{dQ_t}{dt} = H(1-n_t)\n$$", "_____no_output_____" ], [ "where $H(\\cdot)$ is an increasing function. He assumes a critical level of manufacturing employment $(1-n_c)$ at which H(1-n_c)=0 (and negative at values below). With these assumptions and if $n<n_c$ so the critical threshold is surpassed, this plus the earlier closed economy model leads to a version of the **'Staple Theory of Growth'** whereby growth in the agricultural sector releases labor to manufacturing which over time generates productivity growth there. \n\nThe **Staples Thesis** of Growth (Innis, Watkins, others) emphasizes the role of the expansion of frontiers and the growth of traditional 'staple' products such as wheat in a resource-rich economies. This has been used to explain growth and development in regions of the world including Canada, northern United States, and to some extent Australia, New Zealand and Argentina. These countries benefited from an extraordinary rise in commodity prices in the late 19th century which, by many accounts led to the growth of supporting manufacturing industries, in a manner similar to that captured by this account.\n\nMatsuyama points out however that a variation on the same model can explain a version of the **resource curse**. For example in the small open economy the equilibrium condition is as above:\n\n$$\nA_1 F_1^\\prime (n_t) = p A(Q_t) F_2^\\prime (1-n_t)\n$$\n\nAs discussed before, raising $A_1$ implies higher $n_t$ for any level of $Q_t$. If the economy is already passed the threshold $H(1-n_t)>0$ which leads to growth in manufacturing and hence pull out of agriculture, and the effect is self-reinforcing.\n\nHowever if below the threshold (i.e. $n_t>n_c$) and hence $H(1-n_t)<0$ anything that stimulates agriculture, be it productivity growth or a rise in the relative price of agricultural products, will lead to productivity *decline* in industry and a steady increase in agricultural employment $n_t$.\n\nThis is a version of the so called *staple-trap,* *resource curse,* or *dutch disease*. Matsuyama (1992) models this type of possibility in richer detail.", "_____no_output_____" ], [ "### Impediments to structural change", "_____no_output_____" ], [ "Many studies have modeled impediments to the re-allocation of labor across sectors. \n\nThe most famous of these is the Lewis model which assumes workers in the agricultural sector earn an average product of labor there, leading to overemployment in the sector. We'll see several models that try to make sense of this, for example models that attribute this to land property rights insecurity. \n\nHayashi and Prescott (2008) argue that agricultural employment in Japan remained virtually constant at 14 million persons from 1885 to WWII (see image below) despite significant expansion in industrial technology capacity in that period. They argue that labor could not easily leave agriculture due to patriarchal customs and norms that made it hard for children of agricultural households to leave the parental household). Using a calibrated general equilibrium model, the authors argue that the lifting of that barrier in the post-war era (due to various factors including legislation surrounding deep land reforms) explains a good part of the post-war Japanese miracle. ", "_____no_output_____" ], [ "<img src=\"../media/Japan_agemp.png\" alt=\"Japan Ag employment\" class=\"bg-primary\" width=\"600px\">", "_____no_output_____" ], [ "There are many other models with barriers or frictions in the structural transformation. One famous model that received a lot of attentiun is the Harris and Todaro (1970) model. See the separate notebook on this model. ", "_____no_output_____" ], [ "### Spillovers, Complementarities, and Multiple Equilibria \n\nComing soon.", "_____no_output_____" ], [ "## References Cited\n\nHarris, J.R., Todaro, M.P., 1970. Migration, unemployment and development: a two-sector analysis. *The American economic review* 126–142.\n\nHayashi, F., Prescott, E.C., 2008. The depressing effect of agricultural institutions on the prewar Japanese economy. *Journal of political Economy* 116, 573–632.\n\nLewis, W.A., 1954. Economic development with unlimited supplies of labour. *The Manchester School* 22, 139–191.\n\nMatsuyama, K., 2008. Structural change. *The new Palgrave dictionary of economics* 2.\n\nMatsuyama, K., 1992. Agricultural productivity, comparative advantage, and economic growth. *Journal of economic theory* 58, 317–334.\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d00f3c747872b4a0f4a5987a69c25479305ef0d3
1,935
ipynb
Jupyter Notebook
README.ipynb
jfdahl/Advent-of-Code-2019
3e5100e77eddc09f361c07a3c860a0fd97ecaa78
[ "MIT" ]
null
null
null
README.ipynb
jfdahl/Advent-of-Code-2019
3e5100e77eddc09f361c07a3c860a0fd97ecaa78
[ "MIT" ]
null
null
null
README.ipynb
jfdahl/Advent-of-Code-2019
3e5100e77eddc09f361c07a3c860a0fd97ecaa78
[ "MIT" ]
null
null
null
32.25
320
0.621705
[ [ [ "# Advent-of-Code-2019\n\n## About Advent of Code\n\n Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like. People use them as a speed contest, interview prep, company training, university coursework, practice problems, or to challenge each other.\n\n## Websites\n\n https://adventofcode.com/\n ServiceNow Leaderboard: https://adventofcode.com/2019/leaderboard/private/view/109388]\n PySlackers Leaderboard: https://adventofcode.com/2019/leaderboard/private/view/52704]\n\n## 2019 theme\n\n Santa has become stranded at the edge of the Solar System while delivering presents to other planets! \n To accurately calculate his position in space, safely align his warp drive, and \n return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.\n\n Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; \n the second puzzle is unlocked when you complete the first. \n Each puzzle grants one star. Good luck!\n", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
d00f45ac1c19a706c9177a247573b0a345e5aaa7
8,089
ipynb
Jupyter Notebook
JNotebooks/feats-CC-hand-conv.ipynb
rmsouza01/ML101
ca2e5d25ab3dc26079719a3755dc78827935e42e
[ "MIT" ]
17
2018-01-29T19:23:34.000Z
2021-10-06T08:03:04.000Z
JNotebooks/feats-CC-hand-conv.ipynb
rmsouza01/ML101
ca2e5d25ab3dc26079719a3755dc78827935e42e
[ "MIT" ]
null
null
null
JNotebooks/feats-CC-hand-conv.ipynb
rmsouza01/ML101
ca2e5d25ab3dc26079719a3755dc78827935e42e
[ "MIT" ]
5
2018-01-03T19:30:58.000Z
2021-03-11T19:06:40.000Z
56.566434
504
0.59142
[ [ [ "# Feature Extraction\nIn machine learning, feature extraction aims to compute values (features) from images, intended to be informative and non-redundant, facilitating the subsequent learning and generalization steps, and in some cases leading to better human interpretations. These features may be handcrafted (manually computed features based on a-priori information ) or convolutional features (detect patterns within the data without the prior definition of features or characteristics):\n\n## Handcrafted: \n- Histogram features: Statistical moments extracted from the histogram describe image characteristics and provide a quantitative analysis of the image intensity distribution (entropy, intensity mean, standard deviation, skewness, kurtosis, and values at 0, 10, 50 (median) and 90 percentiles).\n<img src=\"../Figures/histogram_sample.jpg\" alt=\"Drawing\" style=\"width: 500px;\"/>\n- The gradient examines directional changes in the image gray level, and can extract relevant information (such as edges) within an image. Moments extracted from the image gradient are more robust to acquisition conditions, such as contrast variation, and properties of the acquisition equipment . Ten features were extracted from the gray level and morphological gradients (five from each): intensity mean, standard deviation, skewness, kurtosis and percentage of non-zero values.\n<img src=\"../Figures/gradient.png\" alt=\"Drawing\" style=\"width: 300px;\"/>\n- Local binary pattern (LBP) is a texture spectrum model that may be used to identify patterns in an image. The LBP histogram comprises the frequency of occurrence of different patterns within an image. Ten features were extracted from the LBP by using a 10-bin LBP histogram.\n<img src=\"../Figures/lbp.png\" alt=\"Drawing\" style=\"width: 400px;\"/>\n- The Haar wavelet is a multi-resolution technique that transforms images into a domain where both spatial and frequency information is present. Features separately extracted from each sub-image present desired scale-dependent properties. When considering two decomposition levels, eight sub-images are generated. The mean value within each sub-image were computed and used as features (total of eight features). <img src=\"../Figures/wavelet-haar.png\" alt=\"Drawing\" style=\"width: 400px;\"/>\n\n\n## Convolutional features\nComputed by using a very deep convolutional network (VGG16) with pre-trained imagenet weights. For each MR volume, the convolutional features were computed in the central 2D axial, sagittal and coronal slices. For each of these three views, 25,088 convolutional features were computed and combined. \n<img src=\"../Figures/viz_initial_layers.png\" alt=\"Drawing\" style=\"width: 700px;\"/>\n\nBesides the image and patient information (MR vendor, magnetic field, age, gender), a total of 75,300 features were extracted and combined for each image: 8 features from the image histogram, 10 features from the image gradient, 10 features from the LBP histogra, 8 features from the Haar wavelet subimages and 75,264 convolutional features. \n\n<img src=\"../Figures/data.png\" alt=\"Drawing\" style=\"width: 800px;\"/>\n", "_____no_output_____" ], [ "## Reading the data file containing patients information and features", "_____no_output_____" ] ], [ [ "## data: vendor; magnetic field; age; gender; feats (65300) \n # vendor: ge -> 10; philips -> 11; siemens -> 12\n # gender: female -> 10; male -> 11\n # feats: fs1 - histogram (8); fs2 - gradient (10); fs3 - lbp (10); fs4 - haar (8); fs5 - convolutional (75264)\nimport numpy as np\n\ndata = np.load('../Data/feats_cc359.npy.zip')['feats_cc359']\nprint '#samples, #info: ',data.shape\n\nprint 'patients age:', data[:,2]", "#samples, #info: (359, 75304)\npatients age: [ 55. 56. 63. 67. 62. 63. 62. 60. 69. 69. 49. 43. 66. 62. 44.\n 55. 50. 41. 57. 65. 48. 43. 43. 65. 51. 65. 41. 63. 51. 42.\n 65. 44. 67. 43. 49. 49. 41. 41. 41. 55. 61. 67. 58. 36. 49.\n 42. 54. 53. 43. 45. 44. 51. 39. 46. 44. 39. 61. 64. 55. 29.\n 55. 52. 53. 49. 42. 46. 57. 49. 56. 80. 56. 31. 49. 53. 41.\n 44. 43. 42. 47. 55. 67. 64. 66. 46. 71. 42. 42. 51. 46. 37.\n 51. 60. 60. 45. 43. 36. 45. 48. 51. 60. 52. 50. 56. 34. 52.\n 41. 38. 51. 57. 44. 51. 60. 45. 60. 49. 50. 49. 49. 53. 58.\n 61. 53. 58. 57. 65. 54. 58. 54. 54. 57. 41. 71. 64. 54. 52.\n 64. 65. 56. 56. 57. 53. 59. 55. 43. 62. 38. 58. 58. 53. 47.\n 71. 51. 52. 55. 57. 55. 54. 53. 54. 57. 55. 39. 64. 54. 44.\n 39. 55. 38. 44. 55. 51. 52. 51. 41. 50. 45. 57. 55. 53. 39.\n 36. 60. 58. 60. 52. 62. 63. 55. 66. 63. 59. 51. 64. 67. 55.\n 48. 54. 59. 64. 37. 58. 54. 56. 49. 64. 58. 58. 56. 57. 60.\n 65. 67. 65. 51. 46. 56. 45. 61. 49. 61. 61. 56. 56. 62. 47.\n 64. 58. 66. 55. 60. 56. 56. 52. 57. 61. 50. 59. 58. 56. 60.\n 60. 55. 58. 56. 48. 60. 53. 51. 58. 60. 41. 44. 58. 57. 57.\n 42. 57. 55. 56. 51. 59. 54. 51. 59. 56. 57. 60. 57. 59. 59.\n 60. 44. 56. 47. 50. 52. 42. 61. 49. 57. 56. 57. 44. 41. 56.\n 55. 53. 56. 59. 56. 48. 60. 50. 51. 55. 57. 57. 58. 37. 58.\n 53. 56. 53. 57. 59. 52. 57. 52. 42. 51. 50. 49. 34. 54. 59.\n 57. 45. 52. 45. 57. 51. 59. 56. 56. 55. 55. 50. 56. 58. 57.\n 61. 53. 41. 45. 54. 53. 59. 51. 59. 49. 60. 50. 54. 43. 53.\n 43. 52. 60. 60. 62. 52. 55. 58. 61. 55. 61. 55. 52. 58.]\n" ] ], [ [ "## Activities List\n\n - Print the vendor for all the images\n - Identify images acquired from patients with age > 30\n - Identify images acquired using GE vendor scanner\n - Access this simple demo of a convnet trained on MNIST dataset: https://transcranial.github.io/keras-js/#/mnist-cnn\n - draw a number (between 0-9)\n - Visualize classification and intermediate outputs at each layer", "_____no_output_____" ], [ "## References\n- Histogram basics: https://docs.opencv.org/3.1.0/d1/db7/tutorial_py_histogram_begins.html\n- Local binary patterns: http://scikit-image.org/docs/dev/auto_examples/features_detection/plot_local_binary_pattern.html\n- Wavelet haar to MRI: https://www.researchgate.net/figure/The-procedures-of-3-level-2D-DWT-a-normal-brain-MRI-b-level-3-wavelet-coefficients_258104202\n- Extracting convolutional features using Vgg16: https://keras.io/applications/", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d00f5d3b7ec97f610ca6738be499be9aa6f0e6be
505,469
ipynb
Jupyter Notebook
jupyter notebook/Dota2 new data.ipynb
alykkehoy/Dota-2-winning-team-predictor
58b051d4b33a56c5b9f6107d52cba02e06a624ed
[ "MIT" ]
null
null
null
jupyter notebook/Dota2 new data.ipynb
alykkehoy/Dota-2-winning-team-predictor
58b051d4b33a56c5b9f6107d52cba02e06a624ed
[ "MIT" ]
null
null
null
jupyter notebook/Dota2 new data.ipynb
alykkehoy/Dota-2-winning-team-predictor
58b051d4b33a56c5b9f6107d52cba02e06a624ed
[ "MIT" ]
null
null
null
352.243206
148,424
0.666496
[ [ [ "# Imports", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import ensemble\nfrom sklearn import metrics\nfrom io import StringIO\nfrom csv import writer", "_____no_output_____" ] ], [ [ "# Read in csv files", "_____no_output_____" ] ], [ [ "matches = pd.read_csv('../csv/matches.csv')\nplayers = pd.read_csv('../csv/players.csv')\nhero_names = pd.read_json('../json/heroes.json')\ncluster_regions = pd.read_csv('./Data/cluster_regions.csv')", "_____no_output_____" ], [ "matches", "_____no_output_____" ], [ "players.head()", "_____no_output_____" ], [ "hero_names.head()", "_____no_output_____" ] ], [ [ "# Data info\n", "_____no_output_____" ], [ "## Hero Info\nMost and least popular heroes", "_____no_output_____" ] ], [ [ "num_heroes = len(hero_names)\nplt.hist(players['hero_id'], num_heroes)\nplt.show()", "_____no_output_____" ], [ "hero_counts = players['hero_id'].value_counts().rename_axis('hero_id').reset_index(name='num_matches')\npd.merge(hero_counts, hero_names, left_on='hero_id', right_on='id')", "_____no_output_____" ] ], [ [ "## Server Info\nWhere the most and least games are played", "_____no_output_____" ] ], [ [ "plt.hist(matches['cluster'], bins=np.arange(matches['cluster'].min(), matches['cluster'].max()+1))\nplt.show()", "_____no_output_____" ], [ "cluster_counts = matches['cluster'].value_counts().rename_axis('cluster').reset_index(name='num_matches')\npd.merge(cluster_counts, cluster_regions, on='cluster')", "_____no_output_____" ], [ "short_players = players.iloc[:, :11]\nshort_players.insert(short_players.shape[1], 'win', value=False)\nshort_players", "_____no_output_____" ], [ "# short_matches = matches.iloc[:1000]\nfor index, row in matches.iterrows():\n offset = 10 * index\n short_players.at[0 + offset, 'win'] = row.radiant_win\n short_players.at[1 + offset, 'win'] = row.radiant_win\n short_players.at[2 + offset, 'win'] = row.radiant_win\n short_players.at[3 + offset, 'win'] = row.radiant_win\n short_players.at[4 + offset, 'win'] = row.radiant_win\n\n short_players.at[5 + offset, 'win'] = not row.radiant_win\n short_players.at[6 + offset, 'win'] = not row.radiant_win\n short_players.at[7 + offset, 'win'] = not row.radiant_win\n short_players.at[8 + offset, 'win'] = not row.radiant_win\n short_players.at[9 + offset, 'win'] = not row.radiant_win\n # print(index)\n\nshort_players.head(20)", "_____no_output_____" ], [ "short_players.tail()", "_____no_output_____" ], [ "hero_match_wins = short_players.groupby(by='hero_id').sum()['win']\nhero_match_count = players['hero_id'].value_counts().rename_axis('hero_id').reset_index(name='total_matches')\nhero_match_count = hero_match_count.merge(hero_match_wins, on='hero_id')\nhero_match_count", "_____no_output_____" ], [ "hero_match_count['win_percent'] = hero_match_count['win'] / hero_match_count['total_matches'] * 100\nhero_match_count", "_____no_output_____" ], [ "hero_match_count = pd.merge(hero_match_count, hero_names, left_on='hero_id', right_on='id')\nhero_match_count", "_____no_output_____" ], [ "fig_size = plt.rcParams[\"figure.figsize\"]\nfig_size[0] = 10\nfig_size[1] = 8\nplt.rcParams[\"figure.figsize\"] = fig_size\n\n\nx = hero_match_count['total_matches']\ny = hero_match_count['win_percent']\nlabels = hero_match_count['localized_name']\n\n\nplt.scatter(x, y)\nplt.title('Win Percent vs Number of Games Played', fontsize=18)\nplt.xlabel('Number of Games Played', fontsize=18)\nplt.ylabel('Percent Won', fontsize=18)\n\nfor i, label in enumerate(labels):\n plt.annotate(label, (x[i], y[i]))", "_____no_output_____" ] ], [ [ "# Data cleaning\nWe start with an empty list of DataFrams and add to it as we create DataFrames of bad match ids. In the end we combine all the DataFrames and remove their match ids from the Matches DataFrame.", "_____no_output_____" ] ], [ [ "dfs_bad_matches = []", "_____no_output_____" ] ], [ [ "## Abandons\nremove games were a player has abandoned the match", "_____no_output_____" ] ], [ [ "abandoned_matches = players[players.leaver_status > 1][['match_id']]\nabandoned_matches = abandoned_matches.drop_duplicates().reset_index(drop=True)\ndfs_bad_matches.append(abandoned_matches)\nabandoned_matches", "_____no_output_____" ] ], [ [ "## Missing Hero id\nremove games where a player is not assigned a hero id, but didnt get flaged for an abandon", "_____no_output_____" ] ], [ [ "player_no_hero = players[players.hero_id == 0][['match_id']].reset_index(drop=True)\ndfs_bad_matches.append(player_no_hero)\nplayer_no_hero", "_____no_output_____" ] ], [ [ "## Wrong Game Mode\nremove games not played in \"Ranked All Pick\" (22)", "_____no_output_____" ] ], [ [ "wrong_mode = matches[matches.game_mode != 22].reset_index()[['match_id']]\ndfs_bad_matches.append(wrong_mode)\nwrong_mode", "_____no_output_____" ] ], [ [ "## Game length (short)\nremove games we deem too short (< 15 min)", "_____no_output_____" ] ], [ [ "short_length = 15 * 60\nshort_matches = matches[matches.duration < short_length].reset_index()[['match_id']]\ndfs_bad_matches.append(short_matches)\nshort_matches", "_____no_output_____" ] ], [ [ "## Game length (long)\nNext we want to get matches with a too long duration (>90 min)", "_____no_output_____" ] ], [ [ "long_length = 90 * 60\nlong_matches = matches[matches.duration > long_length].reset_index()[['match_id']]\ndfs_bad_matches.append(long_matches)\nlong_matches", "_____no_output_____" ] ], [ [ "## Combine all our lists of bad matches\ncombine matches and create a filtered match dataframe with only good matches", "_____no_output_____" ] ], [ [ "bad_match_ids = pd.concat(dfs_bad_matches, ignore_index=True).drop_duplicates()\nbad_match_ids", "_____no_output_____" ] ], [ [ "## Remove bad matches", "_____no_output_____" ] ], [ [ "filtered_matches = matches[~matches['match_id'].isin(bad_match_ids['match_id'])]\nfiltered_matches.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 115823 entries, 0 to 145324\nData columns (total 22 columns):\n # Column Non-Null Count Dtype\n--- ------ -------------- -----\n 0 radiant_win 115823 non-null bool \n 1 duration 115823 non-null int64\n 2 pre_game_duration 115823 non-null int64\n 3 start_time 115823 non-null int64\n 4 match_id 115823 non-null int64\n 5 match_seq_num 115823 non-null int64\n 6 tower_status_radiant 115823 non-null int64\n 7 tower_status_dire 115823 non-null int64\n 8 barracks_status_radiant 115823 non-null int64\n 9 barracks_status_dire 115823 non-null int64\n 10 cluster 115823 non-null int64\n 11 first_blood_time 115823 non-null int64\n 12 lobby_type 115823 non-null int64\n 13 human_players 115823 non-null int64\n 14 leagueid 115823 non-null int64\n 15 positive_votes 115823 non-null int64\n 16 negative_votes 115823 non-null int64\n 17 game_mode 115823 non-null int64\n 18 flags 115823 non-null int64\n 19 engine 115823 non-null int64\n 20 radiant_score 115823 non-null int64\n 21 dire_score 115823 non-null int64\ndtypes: bool(1), int64(21)\nmemory usage: 19.6 MB\n" ] ], [ [ "## Remove duplicate matches", "_____no_output_____" ] ], [ [ "filtered_matches = filtered_matches.drop_duplicates(subset=['match_id'])\nfiltered_matches.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 114686 entries, 0 to 145324\nData columns (total 22 columns):\n # Column Non-Null Count Dtype\n--- ------ -------------- -----\n 0 radiant_win 114686 non-null bool \n 1 duration 114686 non-null int64\n 2 pre_game_duration 114686 non-null int64\n 3 start_time 114686 non-null int64\n 4 match_id 114686 non-null int64\n 5 match_seq_num 114686 non-null int64\n 6 tower_status_radiant 114686 non-null int64\n 7 tower_status_dire 114686 non-null int64\n 8 barracks_status_radiant 114686 non-null int64\n 9 barracks_status_dire 114686 non-null int64\n 10 cluster 114686 non-null int64\n 11 first_blood_time 114686 non-null int64\n 12 lobby_type 114686 non-null int64\n 13 human_players 114686 non-null int64\n 14 leagueid 114686 non-null int64\n 15 positive_votes 114686 non-null int64\n 16 negative_votes 114686 non-null int64\n 17 game_mode 114686 non-null int64\n 18 flags 114686 non-null int64\n 19 engine 114686 non-null int64\n 20 radiant_score 114686 non-null int64\n 21 dire_score 114686 non-null int64\ndtypes: bool(1), int64(21)\nmemory usage: 19.4 MB\n" ], [ "filtered_players = players[~players['match_id'].isin(bad_match_ids['match_id'])]\nfiltered_players.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 1158370 entries, 0 to 1453439\nData columns (total 31 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 account_id 1158308 non-null float64\n 1 player_slot 1158370 non-null int64 \n 2 hero_id 1158370 non-null int64 \n 3 item_0 1158370 non-null int64 \n 4 item_1 1158370 non-null int64 \n 5 item_2 1158370 non-null int64 \n 6 item_3 1158370 non-null int64 \n 7 item_4 1158370 non-null int64 \n 8 item_5 1158370 non-null int64 \n 9 backpack_0 1158370 non-null int64 \n 10 backpack_1 1158370 non-null int64 \n 11 backpack_2 1158370 non-null int64 \n 12 item_neutral 1158370 non-null int64 \n 13 kills 1158370 non-null int64 \n 14 deaths 1158370 non-null int64 \n 15 assists 1158370 non-null int64 \n 16 leaver_status 1158308 non-null float64\n 17 last_hits 1158370 non-null int64 \n 18 denies 1158370 non-null int64 \n 19 gold_per_min 1158370 non-null int64 \n 20 xp_per_min 1158370 non-null int64 \n 21 level 1158370 non-null int64 \n 22 hero_damage 1158370 non-null int64 \n 23 tower_damage 1158370 non-null int64 \n 24 hero_healing 1158370 non-null int64 \n 25 gold 1158370 non-null int64 \n 26 gold_spent 1158370 non-null int64 \n 27 scaled_hero_damage 1158370 non-null int64 \n 28 scaled_tower_damage 1158370 non-null int64 \n 29 scaled_hero_healing 1158370 non-null int64 \n 30 match_id 1158370 non-null int64 \ndtypes: float64(2), int64(29)\nmemory usage: 282.8 MB\n" ], [ "filtered_players = filtered_players.drop_duplicates(subset=['match_id', 'player_slot'])\nfiltered_players.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 1146860 entries, 0 to 1453439\nData columns (total 31 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 account_id 1146801 non-null float64\n 1 player_slot 1146860 non-null int64 \n 2 hero_id 1146860 non-null int64 \n 3 item_0 1146860 non-null int64 \n 4 item_1 1146860 non-null int64 \n 5 item_2 1146860 non-null int64 \n 6 item_3 1146860 non-null int64 \n 7 item_4 1146860 non-null int64 \n 8 item_5 1146860 non-null int64 \n 9 backpack_0 1146860 non-null int64 \n 10 backpack_1 1146860 non-null int64 \n 11 backpack_2 1146860 non-null int64 \n 12 item_neutral 1146860 non-null int64 \n 13 kills 1146860 non-null int64 \n 14 deaths 1146860 non-null int64 \n 15 assists 1146860 non-null int64 \n 16 leaver_status 1146801 non-null float64\n 17 last_hits 1146860 non-null int64 \n 18 denies 1146860 non-null int64 \n 19 gold_per_min 1146860 non-null int64 \n 20 xp_per_min 1146860 non-null int64 \n 21 level 1146860 non-null int64 \n 22 hero_damage 1146860 non-null int64 \n 23 tower_damage 1146860 non-null int64 \n 24 hero_healing 1146860 non-null int64 \n 25 gold 1146860 non-null int64 \n 26 gold_spent 1146860 non-null int64 \n 27 scaled_hero_damage 1146860 non-null int64 \n 28 scaled_tower_damage 1146860 non-null int64 \n 29 scaled_hero_healing 1146860 non-null int64 \n 30 match_id 1146860 non-null int64 \ndtypes: float64(2), int64(29)\nmemory usage: 280.0 MB\n" ], [ "filtered_players.to_csv('../csv/players_filtered.csv', index=False)", "_____no_output_____" ], [ "filtered_matches.to_csv('../csv/matches_filtered.csv', index=False)", "_____no_output_____" ] ], [ [ "# Convert our match list\n\nConvert our match list to the form of :\nr_1, r_2, r_3, r_4, r_5, d_1, d_2, d_3, d_4, d_5, r_win\n", "_____no_output_____" ] ], [ [ "r_names = []\nd_names = []\nfor slot in range(1, 6):\n r_name = 'r_' + str(slot)\n d_name = 'd_' + str(slot)\n r_names.append(r_name)\n d_names.append(d_name)\n\ncolumns = (r_names + d_names + ['r_win'])\n\nnew_row = [-1] * (5 + 5 + 1)\n\n# test_players = players.iloc[:500, :]\n# test_matches = matches.iloc[:50, :]\n\ncolumns = (r_names + d_names + ['r_win'])\nnew_match_list = pd.DataFrame(data=None, columns=columns)\n\noutput = StringIO()\ncsv_writer = writer(output)\nfor index, row in filtered_matches.iterrows():\n match_players = players.loc[players['match_id'] == row['match_id']]\n\n if match_players.shape[0] == 10:\n\n new_row[0] = match_players[match_players['player_slot'] == 0].iloc[0]['hero_id']\n new_row[1] = match_players[match_players['player_slot'] == 1].iloc[0]['hero_id']\n new_row[2] = match_players[match_players['player_slot'] == 2].iloc[0]['hero_id']\n new_row[3] = match_players[match_players['player_slot'] == 3].iloc[0]['hero_id']\n new_row[4] = match_players[match_players['player_slot'] == 4].iloc[0]['hero_id']\n\n new_row[5] = match_players[match_players['player_slot'] == 128].iloc[0]['hero_id']\n new_row[6] = match_players[match_players['player_slot'] == 129].iloc[0]['hero_id']\n new_row[7] = match_players[match_players['player_slot'] == 130].iloc[0]['hero_id']\n new_row[8] = match_players[match_players['player_slot'] == 131].iloc[0]['hero_id']\n new_row[9] = match_players[match_players['player_slot'] == 132].iloc[0]['hero_id']\n\n # add if radiant win\n new_row[10] = row['radiant_win']\n \n # append new row onto match list\n csv_writer.writerow(new_row)\n\n # gives us some idea about how far into the data we are\n if index % 1000 == 0:\n print(index / 1000)\n\noutput.seek(0)\nnew_match_list = pd.read_csv(output, names=columns)\nnew_match_list.to_csv('./Data_new/new_match_list_filtered_ids.csv', index=False)", "_____no_output_____" ] ], [ [ "# Stats", "_____no_output_____" ] ], [ [ "players", "_____no_output_____" ], [ "player_stats = players.drop(columns=['account_id', 'match_id', 'leaver_status'])", "_____no_output_____" ], [ "player_stats_short = player_stats.drop(columns=['item_0','item_1','item_2','item_3','item_4','item_5','backpack_0','backpack_1','backpack_2','item_neutral', 'player_slot']).groupby(['hero_id']).mean()\nplayer_stats_short", "_____no_output_____" ], [ "player_stats_short.reset_index().to_json('../json/hero_stats.json', orient='records', indent=4)", "_____no_output_____" ], [ "player_items = player_stats.melt(id_vars=['hero_id'], value_vars=['item_0', 'item_1', 'item_2', 'item_3', 'item_4', 'item_5'], var_name='item_slot', value_name='item_id')\nplayer_items", "_____no_output_____" ], [ "item_counts = player_items.groupby(['hero_id']).item_id.value_counts().reset_index(name=\"count\")\nitem_counts", "_____no_output_____" ], [ "j = (item_counts.groupby(['hero_id'], as_index=True)\n .apply(lambda x: x[['item_id','count']].to_dict('r'))\n .reset_index()\n .rename(columns={0:'item_data'})\n .to_json('../json/item_stats.json', orient='records', indent=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", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
d00f67c8ea79928d7b21b7fe3b034e1aa2d867d9
1,354
ipynb
Jupyter Notebook
src/Untitled.ipynb
RanWangTilburg/TextTransformer
07b51bc92ca9f0e8e89a613b6c37568a49a442e8
[ "CC0-1.0" ]
null
null
null
src/Untitled.ipynb
RanWangTilburg/TextTransformer
07b51bc92ca9f0e8e89a613b6c37568a49a442e8
[ "CC0-1.0" ]
null
null
null
src/Untitled.ipynb
RanWangTilburg/TextTransformer
07b51bc92ca9f0e8e89a613b6c37568a49a442e8
[ "CC0-1.0" ]
null
null
null
21.83871
125
0.514771
[ [ [ "from enchant.tokenize import get_tokenizer\nimport enchant\n\ndic = enchant.Dict(\"en_US\")\ntknzr = get_tokenizer(\"en_US\")\n\nimport re\n\n# di\n# text = \"this's a sent tokenize, test. this is sent two. is this sent three? sent 4 is cool! Now it's your turn.\"\n# sent_tokenize_list = sent_tokenize(text)\n# print sent_tokenize_list\ndic.check(\".\")\n\" \".join(re.findall(r\"[\\w']+|[.,!?;]\", \"Hello, I'm a string!\"))", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
d00f6d0efbf4c33f2d3105097f932304b26092df
1,336
ipynb
Jupyter Notebook
2021 Осенний семестр/Практическое задание 3_5/Романенков_Задание 3_5 Контрольные вопросы 1 и 2.ipynb
mosalov/Notebook_For_AI_Main
a693d29bf0bdcf824cb4f1eca86ff54b67ba7428
[ "MIT" ]
6
2021-09-20T10:28:18.000Z
2022-03-14T18:39:17.000Z
2021 Осенний семестр/Практическое задание 3_5/Романенков_Задание 3_5 Контрольные вопросы 1 и 2.ipynb
mosalov/Notebook_For_AI_Main
a693d29bf0bdcf824cb4f1eca86ff54b67ba7428
[ "MIT" ]
122
2020-09-07T11:57:57.000Z
2022-03-22T06:47:03.000Z
2021 Осенний семестр/Практическое задание 3_5/Романенков_Задание 3_5 Контрольные вопросы 1 и 2.ipynb
mosalov/Notebook_For_AI_Main
a693d29bf0bdcf824cb4f1eca86ff54b67ba7428
[ "MIT" ]
97
2020-09-07T11:32:19.000Z
2022-03-31T10:27:38.000Z
19.940299
57
0.40494
[ [ [ "#Д\n#\n\nn = int(input('Количество вводимых значений: '))\n\nx = {}\n\nfor i in range(1, n + 1):\n \n y = []\n a = int(input('Значение: '))\n \n for j in range(2, a + 1):\n \n k = 0\n \n for d in range(1, j+1):\n \n if j % d == 0: k += 1\n \n if k == 2: y.append(d)\n \n x[i] = y\n \nfor key, value in x.items():\n print(\"{0}: {1}\".format(key,value))", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
d00f7764639786a4c60a9e6dad7e7e2e2110eb6c
15,536
ipynb
Jupyter Notebook
notebooks/Welcome to Spark with Scala.ipynb
marchub/docker-demo-images
f0fc1347e0bda5a93af71c8cf9260cf198430bf2
[ "BSD-3-Clause" ]
null
null
null
notebooks/Welcome to Spark with Scala.ipynb
marchub/docker-demo-images
f0fc1347e0bda5a93af71c8cf9260cf198430bf2
[ "BSD-3-Clause" ]
null
null
null
notebooks/Welcome to Spark with Scala.ipynb
marchub/docker-demo-images
f0fc1347e0bda5a93af71c8cf9260cf198430bf2
[ "BSD-3-Clause" ]
null
null
null
27.066202
541
0.552137
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d00f7b0cb517a7d350347bb331fc434c30030a10
179,031
ipynb
Jupyter Notebook
0.Project/3. Machine Learning Practice/2. Football/2. K-NN Regression parctice.ipynb
jskim0406/Study
07b559b95f8f658303ee53114107ae35940a6080
[ "MIT" ]
null
null
null
0.Project/3. Machine Learning Practice/2. Football/2. K-NN Regression parctice.ipynb
jskim0406/Study
07b559b95f8f658303ee53114107ae35940a6080
[ "MIT" ]
null
null
null
0.Project/3. Machine Learning Practice/2. Football/2. K-NN Regression parctice.ipynb
jskim0406/Study
07b559b95f8f658303ee53114107ae35940a6080
[ "MIT" ]
null
null
null
38.010828
25,372
0.42148
[ [ [ "data = pd.read_csv(\"/Users/kimjeongseob/Desktop/Study/0.Project/3. Machine Learning Practice/2. Football/dataset_football.csv\")\n", "_____no_output_____" ], [ "data = data.drop(columns = 'Unnamed: 0')", "_____no_output_____" ], [ "data_origin = data.copy()", "_____no_output_____" ], [ "data", "_____no_output_____" ], [ "data.follower = data.follower + 10\ndata.follower = np.log(data.follower)", "_____no_output_____" ], [ "# data = data.drop(columns='player_name')", "_____no_output_____" ], [ "col_name = list(data.columns)\ncol_name.remove('player_name')", "_____no_output_____" ], [ "# from patsy import *", "_____no_output_____" ], [ "# col_names = [\"scale({})\".format(name) for name in col_name]", "_____no_output_____" ], [ "# col_names", "_____no_output_____" ], [ "# data_scaled = dmatrix(\"0+\"+\"+\".join(col_names),data=data)", "_____no_output_____" ], [ "# data_scaled = pd.DataFrame(data_scaled,columns = [col_name])", "_____no_output_____" ], [ "# data_scaled", "_____no_output_____" ], [ "# from sklearn.preprocessing import MinMaxScaler\n\n# scaler = MinMaxScaler()\n# scaler.fit(data)\n# scaled = scaler.transform(data)", "_____no_output_____" ], [ "# from sklearn.preprocessing import StandardScaler\n\n# scaler = StandardScaler()\n# scaler.fit(data)\n# data_scaled = scaler.transform(data)", "_____no_output_____" ], [ "from sklearn.neighbors import KNeighborsClassifier", "_____no_output_____" ], [ "classifier = KNeighborsClassifier(n_neighbors = 100)", "_____no_output_____" ], [ "data_X = data.drop(columns='value')", "_____no_output_____" ], [ "data_y = data.value", "_____no_output_____" ], [ "data_y = map(int,data_y)", "_____no_output_____" ], [ "data_y = list(data_y)", "_____no_output_____" ], [ "# data_y", "_____no_output_____" ], [ "data_X", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(data_X, data_y, test_size=0.4, random_state=0)", "_____no_output_____" ], [ "X_train.shape", "_____no_output_____" ], [ "X_test.shape", "_____no_output_____" ], [ "len(y_train)", "_____no_output_____" ], [ "len(y_test)", "_____no_output_____" ], [ "classifier.fit(X_train.drop(columns='player_name'), y_train)", "_____no_output_____" ], [ "X_train", "_____no_output_____" ], [ "len(y_train)", "_____no_output_____" ], [ "print(classifier.score(X_test.drop(columns='player_name'),y_test))", "0.08743169398907104\n" ], [ "import matplotlib.pyplot as plt\nk_list = range(1,101)\naccuracies = []\nfor k in k_list:\n classifier = KNeighborsClassifier(n_neighbors = k)\n classifier.fit(X_train.drop(columns='player_name'), y_train)\n accuracies.append(classifier.score(X_test.drop(columns='player_name'), y_test))\nplt.plot(k_list, accuracies)\nplt.xlabel(\"k\")\nplt.ylabel(\"Validation Accuracy\")\nplt.title(\"Breast Cancer Classifier Accuracy\")\nplt.show()", "_____no_output_____" ] ], [ [ "# K-NN regression 알고리즘", "_____no_output_____" ] ], [ [ "from sklearn.neighbors import KNeighborsRegressor\n", "_____no_output_____" ], [ "regressor = KNeighborsRegressor(n_neighbors = 10, weights = \"distance\")", "_____no_output_____" ], [ "regressor.fit(X_train.drop(columns='player_name'), y_train)\n", "_____no_output_____" ], [ "y_pred = regressor.predict(X_test.drop(columns='player_name'))\ny_pred_train = regressor.predict(X_train.drop(columns='player_name'))", "_____no_output_____" ], [ "result = []\n\nfor i in range(len(y_pred)):\n if y_test[i] < y_pred[i]:\n result.append(\"overpaid\")\n else:\n result.append(\"underpaid\")\n ", "_____no_output_____" ], [ "result", "_____no_output_____" ], [ "len(y_pred)", "_____no_output_____" ], [ "# X_train = X_train.reset_index().drop(columns='index')\nX_test = X_test.reset_index().drop(columns='index')", "_____no_output_____" ], [ "X_train", "_____no_output_____" ], [ "X_test", "_____no_output_____" ], [ "X_test.loc[1]['player_name']", "_____no_output_____" ], [ "underpaid = []\n\nfor i in range(len(y_pred)):\n if result[i] == 'underpaid':\n underpaid.append(X_test.loc[i]['player_name'])", "_____no_output_____" ], [ "len(underpaid)", "_____no_output_____" ], [ "underpaid", "_____no_output_____" ] ], [ [ "# K-NN regression 알고리즘 -> 전체를 다 학습시킴..", "_____no_output_____" ] ], [ [ "from sklearn.neighbors import KNeighborsRegressor\n", "_____no_output_____" ], [ "regressor = KNeighborsRegressor(n_neighbors = 10, weights = \"distance\")", "_____no_output_____" ], [ "regressor.fit(data.drop(columns=['player_name','value']), data.value)\n", "_____no_output_____" ], [ "y_pred = regressor.predict(data.drop(columns=['player_name','value']))", "_____no_output_____" ], [ "result = []\n\nfor i in range(len(y_pred)):\n if data.value[i] < y_pred[i]:\n result.append(\"underpaid\")\n else:\n result.append(\"overpaid\")\n ", "_____no_output_____" ], [ "data.value[1]", "_____no_output_____" ], [ "y_pred[1]", "_____no_output_____" ], [ "result", "_____no_output_____" ], [ "len(y_pred)", "_____no_output_____" ], [ "# X_train = X_train.reset_index().drop(columns='index')\nX_test = X_test.reset_index().drop(columns='index')", "_____no_output_____" ], [ "X_train", "_____no_output_____" ], [ "X_test", "_____no_output_____" ], [ "X_test.loc[1]['player_name']", "_____no_output_____" ], [ "underpaid = []\n\nfor i in range(len(y_pred)):\n if result[i] == 'underpaid':\n underpaid.append(X_test.loc[i]['player_name'])", "_____no_output_____" ], [ "len(underpaid)", "_____no_output_____" ], [ "X_test", "_____no_output_____" ] ] ]
[ "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", "code", "code", "code", "code" ], [ "markdown" ], [ "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" ] ]
d00f823ec2ce94f341004dacc386a31ab8a33093
64,804
ipynb
Jupyter Notebook
LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb
Skantastico/DS-Unit-2-Applied-Modeling
cb602e2ad6948cf5156faef66a46bb8f552db0bd
[ "MIT" ]
null
null
null
LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb
Skantastico/DS-Unit-2-Applied-Modeling
cb602e2ad6948cf5156faef66a46bb8f552db0bd
[ "MIT" ]
null
null
null
LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb
Skantastico/DS-Unit-2-Applied-Modeling
cb602e2ad6948cf5156faef66a46bb8f552db0bd
[ "MIT" ]
null
null
null
37.963679
287
0.325073
[ [ [ "<a href=\"https://colab.research.google.com/github/Skantastico/DS-Unit-2-Applied-Modeling/blob/master/LS_DSPT3_231_Updated_assignment_applied_modeling_1.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\n\n*Unit 2, Sprint 3, Module 1*\n\n---\n\n\n# Define ML problems\n\nYou will use your portfolio project dataset for all assignments this sprint.\n\n## Assignment\n\nComplete these tasks for your project, and document your decisions.\n\n- [x] Choose your target. Which column in your tabular dataset will you predict?\n- [x] Is your problem regression or classification?\n- [x] How is your target distributed?\n - Classification: How many classes? Are the classes imbalanced?\n - Regression: Is the target right-skewed? If so, you may want to log transform the target.\n- [x] Choose which observations you will use to train, validate, and test your model.\n - Are some observations outliers? Will you exclude them?\n - Will you do a random split or a time-based split?\n- [x] Choose your evaluation metric(s).\n - Classification: Is your majority class frequency > 50% and < 70% ? If so, you can just use accuracy if you want. Outside that range, accuracy could be misleading. What evaluation metric will you choose, in addition to or instead of accuracy?\n- [ ] Begin to clean and explore your data.\n- [ ] Begin to choose which features, if any, to exclude. Would some features \"leak\" future information?", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nurl = 'https://raw.githubusercontent.com/Skantastico/DS-Unit-2-Applied-Modeling/master/data/Anime.csv'\n\ndf = pd.read_csv(url)", "_____no_output_____" ] ], [ [ "# My Dataset\n\nAnime Ratings from the 'iMDB\" of Anime, called myanimelist.net", "_____no_output_____" ] ], [ [ "df.head(7)", "_____no_output_____" ] ], [ [ "## Summary of numeric and non-numeric columns at a glance", "_____no_output_____" ] ], [ [ "df.describe().T", "_____no_output_____" ], [ "df.describe(exclude='number').T", "_____no_output_____" ], [ "col_list = df.columns.values.tolist()\ncol_list", "_____no_output_____" ] ], [ [ "## I was running into trouble during data exploration, there seems to be a space after every column", "_____no_output_____" ] ], [ [ "## I found this piece of code on medium that seems like a catch-all for fixing columns\n\ndf.columns = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '')\n\ndf", "_____no_output_____" ], [ "col_list = df.columns.values.tolist()\ncol_list", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "df.columns.map(lambda x: x.strip())\ndf.columns", "_____no_output_____" ], [ "df.genre.value_counts()", "_____no_output_____" ] ], [ [ "## Ok that seems to have fixed it.\n\nThere seem to be at least around 900 'adult themed' anime which I will probably remove from the dataset, or at least from any public portions just to be safe.\n\nIf it affects the model accuracy at all or is relevant, I will include it for calculations and just make a note.", "_____no_output_____" ], [ "# Choose Your Target", "_____no_output_____" ] ], [ [ "# My Target will be involving the 'score' column\n\ndf.score.value_counts(ascending=False)", "_____no_output_____" ] ], [ [ "## As I will be using the entire spectrum of score, this will be a regression.", "_____no_output_____" ], [ "# How is my target distributed?", "_____no_output_____" ] ], [ [ "# The mean seems to be around 6.3, with only 25% of the dataset above a 7.05\n\ndf.score.describe()", "_____no_output_____" ], [ "df['mean'] = df['score'] >= 6.2845\ndf['mean'].value_counts(normalize=True)", "_____no_output_____" ] ], [ [ "### So there are about 51% anime that are above average (before cleaning)", "_____no_output_____" ], [ "## Which Observations will I use to train?", "_____no_output_____" ], [ "### There's lots of options, but at the very least these look interesting:\n\nNumeric:\n* Episodes\n* Airing\n*Aired\n*Duration\n*Score\n*Popularity\n*Rank\n\nNon-numeric:\n\n* Type\n*Source\n*Producer\n*Genre\n*Studio\n*Rating\n\n", "_____no_output_____" ], [ "## On my old dataset, it was a lot less complete than this one, and I was already thinking of making my own features similar to \"popularity\" and \"# of episodes\".\n\n## I was also going to try and figure out how to scrape and match air dates, but someone other magical person already has! Hooray.", "_____no_output_____" ], [ "## I will continue to clean the dataset on a new notebook", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
d00f84ac56e2524164e338ad5634d51cec40ca0c
60,706
ipynb
Jupyter Notebook
Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb
matpalm/PSST
df795a83270716e5ddb7c859171ba5d6253d01a6
[ "MIT" ]
null
null
null
Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb
matpalm/PSST
df795a83270716e5ddb7c859171ba5d6253d01a6
[ "MIT" ]
null
null
null
Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb
matpalm/PSST
df795a83270716e5ddb7c859171ba5d6253d01a6
[ "MIT" ]
null
null
null
95.902054
18,420
0.810546
[ [ [ "## Day 5: Optimal Mind Control\n\nWelcome to Day 6! Now that we can simulate a model network of conductance-based neurons, we discuss the limitations of our approach and attempts to work around these issues.", "_____no_output_____" ], [ "### Memory Management\n\nUsing Python and TensorFlow allowed us to write code that is readable, parallizable and scalable across a variety of computational devices. However, our implementation is very memory intensive. The iterators in TensorFlow do not follow the normal process of memory allocation and garbage collection. Since, TensorFlow is designed to work on diverse hardware like GPUs, TPUs and distributed platforms, memory allocation is done adaptively during the TensorFlow session and not cleared until the Python kernel has stopped execution. The memory used increases linearly with time as the state matrix is computed recursively by the tf.scan function. The maximum memory used by the computational graph is 2 times the total state matrix size at the point when the computation finishes and copies the final data into the memory. The larger the network and longer the simulation, the larger the solution matrix. Each run is limited by the total available memory. For a system with a limited memory of K bytes, The length of a given simulation (L timesteps) of a given network (N differential equations) with 64-bit floating-point precision will follow:\n\n$$2\\times64\\times L\\times N=K$$ \n\nThat is, for any given network, our maximum simulation length is limited. One way to improve our maximum length is to divide the simulation into smaller batches. There will be a small queuing time between batches, which will slow down our code by a small amount but we will be able to simulate longer times. Thus, if we split the simulation into K sequential batches, the maximum memory for the simulation becomes $(1+\\frac{1}{K})$ times the total matrix size. Thus the memory relation becomes: \n\n$$\\Big(1+\\frac{1}{K}\\Big)\\times64\\times L\\times N=K$$ \n\nThis way, we can maximize the length of out simulation that we can run in a single python kernel.\n\nLet us implement this batch system for our 3 neuron feed-forward model.\n\n### Implementing the Model\n\nTo improve the readability of our code we separate the integrator into a independent import module. The integrator code was placed in a file called tf integrator.py. The file must be present in the same directory as the implementation of the model.\n\nNote: If you are using Jupyter Notebook, remember to remove the %matplotlib inline command as it is specific to jupyter.\n\n#### Importing tf_integrator and other requirements\n\nOnce the Integrator is saved in tf_integrator.py in the same directory as the Notebook, we can start importing the essentials including the integrator.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport tf_integrator as tf_int\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport tensorflow as tf\n## OR ##\n# import tensorflow.compat.v1 as tf\n# tf.disable_v2_behavior()", "_____no_output_____" ] ], [ [ "### Recall the Model\n\nFor implementing a Batch system, we do not need to change how we construct our model only how we execute it.\n\n#### Step 1: Initialize Parameters and Dynamical Equations; Define Input", "_____no_output_____" ] ], [ [ "n_n = 3 # number of simultaneous neurons to simulate\n\nsim_res = 0.01 # Time Resolution of the Simulation\nsim_time = 700 # Length of the Simulation\nt = np.arange(0,sim_time,sim_res) \n\n# Acetylcholine\n\nach_mat = np.zeros((n_n,n_n)) # Ach Synapse Connectivity Matrix\nach_mat[1,0]=1\n\n## PARAMETERS FOR ACETYLCHLOLINE SYNAPSES ##\n\nn_ach = int(np.sum(ach_mat)) # Number of Acetylcholine (Ach) Synapses \nalp_ach = [10.0]*n_ach # Alpha for Ach Synapse\nbet_ach = [0.2]*n_ach # Beta for Ach Synapse\nt_max = 0.3 # Maximum Time for Synapse\nt_delay = 0 # Axonal Transmission Delay\nA = [0.5]*n_n # Synaptic Response Strength\ng_ach = [0.35]*n_n # Ach Conductance\nE_ach = [0.0]*n_n # Ach Potential\n\n# GABAa\n\ngaba_mat = np.zeros((n_n,n_n)) # GABAa Synapse Connectivity Matrix\ngaba_mat[2,1] = 1\n\n## PARAMETERS FOR GABAa SYNAPSES ##\n\nn_gaba = int(np.sum(gaba_mat)) # Number of GABAa Synapses\nalp_gaba = [10.0]*n_gaba # Alpha for GABAa Synapse\nbet_gaba = [0.16]*n_gaba # Beta for GABAa Synapse\nV0 = [-20.0]*n_n # Decay Potential\nsigma = [1.5]*n_n # Decay Time Constant\ng_gaba = [0.8]*n_n # fGABA Conductance\nE_gaba = [-70.0]*n_n # fGABA Potential\n\n## Storing Firing Thresholds ##\n\nF_b = [0.0]*n_n # Fire threshold\n\ndef I_inj_t(t):\n return tf.constant(current_input.T,dtype=tf.float64)[tf.to_int32(t/sim_res)] # Turn indices to integer and extract from matrix\n\n## Acetylcholine Synaptic Current ##\n\ndef I_ach(o,V):\n o_ = tf.Variable([0.0]*n_n**2,dtype=tf.float64)\n ind = tf.boolean_mask(tf.range(n_n**2),ach_mat.reshape(-1) == 1)\n o_ = tf.scatter_update(o_,ind,o)\n o_ = tf.transpose(tf.reshape(o_,(n_n,n_n)))\n return tf.reduce_sum(tf.transpose((o_*(V-E_ach))*g_ach),1)\n\n## GABAa Synaptic Current ##\n\ndef I_gaba(o,V):\n o_ = tf.Variable([0.0]*n_n**2,dtype=tf.float64)\n ind = tf.boolean_mask(tf.range(n_n**2),gaba_mat.reshape(-1) == 1)\n o_ = tf.scatter_update(o_,ind,o)\n o_ = tf.transpose(tf.reshape(o_,(n_n,n_n)))\n return tf.reduce_sum(tf.transpose((o_*(V-E_gaba))*g_gaba),1)\n\n## Other Currents ##\n\ndef I_K(V, n):\n return g_K * n**4 * (V - E_K)\n\ndef I_Na(V, m, h):\n return g_Na * m**3 * h * (V - E_Na)\n\ndef I_L(V):\n return g_L * (V - E_L)\n\ndef dXdt(X, t):\n V = X[:1*n_n] # First n_n values are Membrane Voltage\n m = X[1*n_n:2*n_n] # Next n_n values are Sodium Activation Gating Variables\n h = X[2*n_n:3*n_n] # Next n_n values are Sodium Inactivation Gating Variables\n n = X[3*n_n:4*n_n] # Next n_n values are Potassium Gating Variables\n o_ach = X[4*n_n : 4*n_n + n_ach] # Next n_ach values are Acetylcholine Synapse Open Fractions\n o_gaba = X[4*n_n + n_ach : 4*n_n + n_ach + n_gaba] # Next n_ach values are GABAa Synapse Open Fractions\n fire_t = X[-n_n:] # Last n_n values are the last fire times as updated by the modified integrator\n \n dVdt = (I_inj_t(t) - I_Na(V, m, h) - I_K(V, n) - I_L(V) - I_ach(o_ach,V) - I_gaba(o_gaba,V)) / C_m \n \n ## Updation for gating variables ##\n \n m0,tm,h0,th = Na_prop(V)\n n0,tn = K_prop(V)\n\n dmdt = - (1.0/tm)*(m-m0)\n dhdt = - (1.0/th)*(h-h0)\n dndt = - (1.0/tn)*(n-n0)\n \n ## Updation for o_ach ##\n \n A_ = tf.constant(A,dtype=tf.float64)\n Z_ = tf.zeros(tf.shape(A_),dtype=tf.float64)\n \n T_ach = tf.where(tf.logical_and(tf.greater(t,fire_t+t_delay),tf.less(t,fire_t+t_max+t_delay)),A_,Z_) \n T_ach = tf.multiply(tf.constant(ach_mat,dtype=tf.float64),T_ach)\n T_ach = tf.boolean_mask(tf.reshape(T_ach,(-1,)),ach_mat.reshape(-1) == 1)\n \n do_achdt = alp_ach*(1.0-o_ach)*T_ach - bet_ach*o_ach\n \n ## Updation for o_gaba ##\n \n T_gaba = 1.0/(1.0+tf.exp(-(V-V0)/sigma))\n T_gaba = tf.multiply(tf.constant(gaba_mat,dtype=tf.float64),T_gaba)\n T_gaba = tf.boolean_mask(tf.reshape(T_gaba,(-1,)),gaba_mat.reshape(-1) == 1)\n \n do_gabadt = alp_gaba*(1.0-o_gaba)*T_gaba - bet_gaba*o_gaba\n \n ## Updation for fire times ##\n \n dfdt = tf.zeros(tf.shape(fire_t),dtype=fire_t.dtype) # zero change in fire_t\n \n\n out = tf.concat([dVdt,dmdt,dhdt,dndt,do_achdt,do_gabadt,dfdt],0)\n return out\n\ndef K_prop(V):\n T = 22\n phi = 3.0**((T-36.0)/10)\n V_ = V-(-50)\n \n alpha_n = 0.02*(15.0 - V_)/(tf.exp((15.0 - V_)/5.0) - 1.0)\n beta_n = 0.5*tf.exp((10.0 - V_)/40.0)\n \n t_n = 1.0/((alpha_n+beta_n)*phi)\n n_0 = alpha_n/(alpha_n+beta_n)\n \n return n_0, t_n\n\n\ndef Na_prop(V):\n T = 22\n phi = 3.0**((T-36)/10)\n V_ = V-(-50)\n \n alpha_m = 0.32*(13.0 - V_)/(tf.exp((13.0 - V_)/4.0) - 1.0)\n beta_m = 0.28*(V_ - 40.0)/(tf.exp((V_ - 40.0)/5.0) - 1.0)\n \n alpha_h = 0.128*tf.exp((17.0 - V_)/18.0)\n beta_h = 4.0/(tf.exp((40.0 - V_)/5.0) + 1.0)\n \n t_m = 1.0/((alpha_m+beta_m)*phi)\n t_h = 1.0/((alpha_h+beta_h)*phi)\n \n m_0 = alpha_m/(alpha_m+beta_m)\n h_0 = alpha_h/(alpha_h+beta_h)\n \n return m_0, t_m, h_0, t_h\n\n\n# Initializing the Parameters\n\nC_m = [1.0]*n_n\ng_K = [10.0]*n_n\nE_K = [-95.0]*n_n\n\ng_Na = [100]*n_n\nE_Na = [50]*n_n \n\ng_L = [0.15]*n_n\nE_L = [-55.0]*n_n\n\n# Creating the Current Input\ncurrent_input= np.zeros((n_n,t.shape[0]))\ncurrent_input[0,int(100/sim_res):int(200/sim_res)] = 2.5\ncurrent_input[0,int(300/sim_res):int(400/sim_res)] = 5.0\ncurrent_input[0,int(500/sim_res):int(600/sim_res)] = 7.5", "_____no_output_____" ] ], [ [ "#### Step 2: Define the Initial Condition of the Network and Add some Noise to the initial conditions", "_____no_output_____" ] ], [ [ "# Initializing the State Vector and adding 1% noise\nstate_vector = [-71]*n_n+[0,0,0]*n_n+[0]*n_ach+[0]*n_gaba+[-9999999]*n_n\nstate_vector = np.array(state_vector)\nstate_vector = state_vector + 0.01*state_vector*np.random.normal(size=state_vector.shape)", "_____no_output_____" ] ], [ [ "#### Step 3: Splitting Time Series into independent batches and Run Each Batch Sequentially\n\nSince we will be dividing the computation into batches, we have to split the time array such that for each new call, the final state vector of the last batch will be the initial condition for the current batch. The function $np.array\\_split()$ splits the array into non-overlapping vectors. Therefore, we append the last time of the previous batch to the beginning of the current time array batch.", "_____no_output_____" ] ], [ [ "# Define the Number of Batches\nn_batch = 2\n\n# Split t array into batches using numpy\nt_batch = np.array_split(t,n_batch)\n\n# Iterate over the batches of time array\nfor n,i in enumerate(t_batch):\n \n # Inform start of Batch Computation\n print(\"Batch\",(n+1),\"Running...\",end=\"\")\n \n # In np.array_split(), the split edges are present in only one array and since \n # our initial vector to successive calls is corresposnding to the last output\n # our first element in the later time array should be the last element of the \n # previous output series, Thus, we append the last time to the beginning of \n # the current time array batch.\n if n>0:\n i = np.append(i[0]-sim_res,i)\n \n # Set state_vector as the initial condition\n init_state = tf.constant(state_vector, dtype=tf.float64)\n # Create the Integrator computation graph over the current batch of t array\n tensor_state = tf_int.odeint(dXdt, init_state, i, n_n, F_b)\n \n # Initialize variables and run session\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n state = sess.run(tensor_state)\n sess.close()\n \n # Reset state_vector as the last element of output\n state_vector = state[-1,:]\n \n # Save the output of the simulation to a binary file\n np.save(\"part_\"+str(n+1),state)\n\n # Clear output\n state=None\n \n print(\"Finished\")", "Batch 1 Running...Finished\nBatch 2 Running...Finished\n" ] ], [ [ "#### Putting the Output Together\n\nThe output from our batch implementation is a set of binary files that store parts of our total simulation. To get the overall output we have to stitch them back together.", "_____no_output_____" ] ], [ [ "overall_state = []\n\n# Iterate over the generated output files\nfor n,i in enumerate([\"part_\"+str(n+1)+\".npy\" for n in range(n_batch)]):\n \n # Since the first element in the series was the last output, we remove them\n if n>0:\n overall_state.append(np.load(i)[1:,:])\n else:\n overall_state.append(np.load(i))\n\n# Concatenate all the matrix to get a single state matrix\noverall_state = np.concatenate(overall_state)", "_____no_output_____" ] ], [ [ "#### Visualizing the Overall Data\nFinally, we plot the voltage traces of the 3 neurons as a Voltage vs Time heatmap.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(12,6))\n \nsns.heatmap(overall_state[::100,:3].T,xticklabels=100,yticklabels=5,cmap='RdBu_r')\n\nplt.xlabel(\"Time (in ms)\")\nplt.ylabel(\"Neuron Number\")\nplt.title(\"Voltage vs Time Heatmap for Projection Neurons (PNs)\")\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "By this method, we have maximized the usage of our available memory but we can go further and develop a method to allow indefinitely long simulation. The issue behind this entire algorithm is that the memory is not cleared until the python kernel finishes. One way to overcome this is to save the parameters of the model (such as connectivity matrix) and the state vector in a file, and start a new python kernel from a python script to compute successive batches. This way after each large batch, the memory gets cleaned. By combining the previous batch implementation and this system, we can maximize our computability.\n\n### Implementing a Runner and a Caller\n\nFirstly, we have to create an implementation of the model that takes in previous input as current parameters. Thus, we create a file, which we call \"run.py\" that takes an argument ie. the current batch number. The implementation for \"run.py\" is mostly same as the above model but there is a small difference.\n\nWhen the batch number is 0, we initialize all variable parameters and save them, but otherwise we use the saved values. The parameters we save include: Acetylcholine Matrix, GABAa Matrix and Final/Initial State Vector. It will also save the files with both batch number and sub-batch number listed.\n\nThe time series will be created and split initially by the caller, which we call \"call.py\", and stored in a file. Each execution of the Runner will extract its relevant time series and compute on it.", "_____no_output_____" ], [ "#### Implementing the Caller code\n\nThe caller will create the time series, split it and use python subprocess module to call \"run.py\" with appropriate arguments. The code for \"call.py\" is given below.", "_____no_output_____" ] ], [ [ "from subprocess import call\nimport numpy as np\n\ntotal_time = 700\nn_splits = 2\ntime = np.split(np.arange(0,total_time,0.01),n_splits)\n\n# Append the last time point to the beginning of the next batch\nfor n,i in enumerate(time):\n if n>0:\n time[n] = np.append(i[0]-0.01,i)\n\nnp.save(\"time\",time)\n\n# call successive batches with a new python subprocess and pass the batch number\nfor i in range(n_splits):\n call(['python','run.py',str(i)])\n\nprint(\"Simulation Completed.\")", "_____no_output_____" ] ], [ [ "#### Implementing the Runner code\n\n\"run.py\" is essentially identical to the batch-implemented model we developed above with the changes described below:", "_____no_output_____" ] ], [ [ "# Additional Imports #\n\nimport sys\n\n# Duration of Simulation #\n\n# t = np.arange(0,sim_time,sim_res) \nt = np.load(\"time.npy\")[int(sys.argv[1])] # get first argument to run.py\n\n# Connectivity Matrix Definitions #\n\nif sys.argv[1] == '0':\n ach_mat = np.zeros((n_n,n_n)) # Ach Synapse Connectivity Matrix\n ach_mat[1,0]=1 # If connectivity is random, once initialized it will be the same.\n np.save(\"ach_mat\",ach_mat)\nelse:\n ach_mat = np.load(\"ach_mat.npy\")\n \nif sys.argv[1] == '0':\n gaba_mat = np.zeros((n_n,n_n)) # GABAa Synapse Connectivity Matrix\n gaba_mat[2,1] = 1 # If connectivity is random, once initialized it will be the same.\n np.save(\"gaba_mat\",gaba_mat)\nelse:\n gaba_mat = np.load(\"gaba_mat.npy\")\n\n# Current Input Definition #\n \nif sys.argv[1] == '0':\n current_input= np.zeros((n_n,int(sim_time/sim_res)))\n current_input[0,int(100/sim_res):int(200/sim_res)] = 2.5\n current_input[0,int(300/sim_res):int(400/sim_res)] = 5.0\n current_input[0,int(500/sim_res):int(600/sim_res)] = 7.5\n np.save(\"current_input\",current_input)\nelse:\n current_input = np.load(\"current_input.npy\")\n \n# State Vector Definition #\n\nif sys.argv[1] == '0':\n sstate_vector = [-71]*n_n+[0,0,0]*n_n+[0]*n_ach+[0]*n_gaba+[-9999999]*n_n\n state_vector = np.array(state_vector)\n state_vector = state_vector + 0.01*state_vector*np.random.normal(size=state_vector.shape)\n np.save(\"state_vector\",state_vector)\nelse:\n state_vector = np.load(\"state_vector.npy\")\n\n# Saving of Output #\n\n# np.save(\"part_\"+str(n+1),state)\nnp.save(\"batch\"+str(int(sys.argv[1])+1)+\"_part_\"+str(n+1),state)", "_____no_output_____" ] ], [ [ "#### Combining all Data\n\nJust like we merged all the batches, we merge all the sub-batches and batches.", "_____no_output_____" ] ], [ [ "overall_state = []\n\n# Iterate over the generated output files\nfor n,i in enumerate([\"batch\"+str(x+1) for x in range(n_splits)]):\n for m,j in enumerate([\"_part_\"+str(x+1)+\".npy\" for x in range(n_batch)]):\n \n # Since the first element in the series was the last output, we remove them\n if n>0 and m>0:\n overall_state.append(np.load(i+j)[1:,:])\n else:\n overall_state.append(np.load(i+j))\n\n# Concatenate all the matrix to get a single state matrix\noverall_state = np.concatenate(overall_state)", "_____no_output_____" ], [ "plt.figure(figsize=(12,6))\n \nsns.heatmap(overall_state[::100,:3].T,xticklabels=100,yticklabels=5,cmap='RdBu_r')\n\nplt.xlabel(\"Time (in ms)\")\nplt.ylabel(\"Neuron Number\")\nplt.title(\"Voltage vs Time Heatmap for Projection Neurons (PNs)\")\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d00f9276f807f3f989f17eec0ca4d135ffd3ced7
131,580
ipynb
Jupyter Notebook
notebooks/L0_norm.ipynb
rmporsch/ML_genetic_risk
4e1a0510c94260e69f93639ff4104c5f85080d9f
[ "MIT" ]
null
null
null
notebooks/L0_norm.ipynb
rmporsch/ML_genetic_risk
4e1a0510c94260e69f93639ff4104c5f85080d9f
[ "MIT" ]
2
2020-11-13T18:04:51.000Z
2021-11-10T19:40:45.000Z
notebooks/L0_norm.ipynb
rmporsch/ML_genetic_risk
4e1a0510c94260e69f93639ff4104c5f85080d9f
[ "MIT" ]
1
2018-11-23T05:57:04.000Z
2018-11-23T05:57:04.000Z
266.896552
39,196
0.916788
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "Using $L_0$ regularization in predicting genetic risk\n====================================\n\nThe main aim of this document is to outline the code and theory of using the $L_0$ norm in a regularized regression with the objective to predict disease risk from genetic data.\n\nThis document contains my thought process and understanding of the implementation of $L_0$.\nI will aim to integrate the code into existing tools so it can be easily used.\nIdeally I will also compare the performance again $L_1$ as well as $L_2$ norm (aka Lasso and Ridge regression) in predicting simulated data.\n\n## Literature used\n\nI made use of the following papers:\n\n- Learning Sparse Neural Networks through $L_0$ Regularization [link](http://arxiv.org/abs/1712.01312)\n- The Variational Garrote [link](http://link.springer.com/10.1007/s10994-013-5427-7)\n\n# Introduction\n\nLet $\\mathcal{D}$ the dataset consisting of $N$ input-output pairs $\\{(x_1, y_1), \\ldots, (x_N, y_N)\\}$ and consider the regularized minimization procedure with $L_p$ regularization of the parameters $\\omega$\n\n$$\n\\mathcal{R}(\\theta) = \\frac{1}{N} ( \\sum^N_{i=1} \\mathcal{L}(h(x_i; \\theta), y_i)) + \\lambda ||\\theta||_p\n$$\n\nwith $\\theta^* = arg \\min_{\\theta}\\{\\mathcal{R}(\\theta)\\}$.\n\nWhile $L_1$ and $L_2$ are well defined the definition of $L_0$ varies.\nHence I will define it as:\n$$\n||\\theta||_0 = \\sum^{|\\theta|}_{j=1} I[\\theta_j \\neq 0]\n$$\n\nHere it is important that, in contrast to $L_1$ and $L_2$, the $L_0$ norm does not shrink the parameters value but sets it wither to 0 or not 0.\nThis effect might be desirable in genetic data due to high correlations among SNPs.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('fivethirtyeight')", "_____no_output_____" ], [ "def l0(x):\n return(np.sum(x!=0))\n\ndef l1(x):\n return(np.sum(np.abs(x)))\n\ndef l2(x):\n return(np.sum(np.power(x, 2)))", "_____no_output_____" ], [ "x = np.linspace(-2, 2, 50)\nx = np.append(x, 0)\nx = np.sort(x)\n\nfig, (axs0, axs1, axs2) = plt.subplots(1, 3, sharex='all', sharey='all')\nfig.set_size_inches((10, 3))\n\naxs0.set_title('L0 norm')\naxs1.set_title('L1 norm')\naxs2.set_title('L2 norm')\n\n[k.set_xlabel(r'$\\theta$') for k in [axs0, axs1, axs2]]\n[k.set_ylabel('Penalty') for k in [axs0, axs1, axs2]]\n\naxs0.plot(x, [l0(k) for k in x])\naxs1.plot(x, [l1(k) for k in x])\naxs2.plot(x, [l2(k) for k in x])", "_____no_output_____" ] ], [ [ "The plot above demonstrates nicely the penalty for different norms.\nAs one can see both $p=1$ and $p=2$ allow shrinkage for large values of $\\theta$, while $p=0$ the penalty is constant.", "_____no_output_____" ], [ "## Minimizing $L_0$ norm for parametric models\n\nOptimization under the $L_0$ penalty is computational difficult due to the non-differentiability as well as the comninatorial nature of $2^{|\\theta|}$ (the number of possible states of the $L_0$ penalty function).\n\nHence @Author relaxed the discrete nature of $L_0$ to allow for efficient computations.\nHere I will outline their approach first in order to understand it better.\n\nThe first step is to reformulate the $L_0$ norm under the parameters $\\theta$.\nHence let,\n$$\n\\begin{matrix}\n\\theta_j = \\tilde{\\theta_j}z_j, & z_j \\in \\{0, 1\\}, & \\tilde{\\theta}_j \\neq 0, & ||\\theta||_0 = \\sum^{|\\theta|}_{j=1} z_j\n\\end{matrix}\n$$\n\nTherefore $z_j$ can be considered as binary gates, and the $L_0$ norm can be seen as the amount of gates being turned on.\nThen we can reformulate the minimization from Eq. 1 by letting $q(z_j|\\pi_j) = Bern(\\pi_j)$\n$$\n\\mathcal{R}(\\tilde{\\theta}, \\pi) = \\mathbb{E}_{q(z|\\pi)} [\\frac{1}{N} ( \\sum^N_{i=1} \\mathcal{L}(h(x_i; \\tilde{\\theta} \\otimes z), y_i)] + \\lambda \\sum^{|\\theta|}_{j=1} \\pi_j \\\\\n\\quad \\textrm{with} \\quad \n\\theta^*, \\pi^* = arg \\min_{\\tilde{\\theta}, \\pi} \\{\\mathcal{R}(\\tilde{\\theta}, \\pi)\\}\n$$\n\nHere we encounter the problem of non-differentiability of the left hand side of the previous equation size z is discrete (the penalty term is straight forward to minimize).\nIt seems there are methods to optimize this functions but they are supposed to suffer from high variance and biased gradients.\nTherefore @Author used an alternative to smooth the objective function for efficient gradient based optimization.\n\nLet $s$ be a continuous random variable with distribution $q(s)$ that has the parameter $\\phi$ we can then let $z$ be given a hard sigmoid function:\n$$\ns \\sim q(s|\\phi) \\\\\nz = min(1, max(0, s))\n$$\nThis allows the gate to still be $0$ as well as the computation of the probability of non-zero parameters (number of active gates) with a simple cdf ($Q(\\cdot)$ of s:\n$$\nq(z\\neq 0 | \\phi) = 1 - Q(s \\leq 0 | \\phi)\n$$\nThen we can reformulate the previous equation as\n$$\n\\mathcal{R}(\\tilde{\\theta}, \\phi) = \\mathbb{E}_{q(s|\\phi)} [\\frac{1}{N} ( \\sum^N_{i=1} \\mathcal{L}(h(x_i; \\tilde{\\theta} \\otimes g(s)), y_i)] + \\lambda \\sum^{|\\theta|}_{j=1} (1 - Q(s_j \\leq 0 | \\phi_j)) \\\\\n\\quad \\textrm{with} \\quad \n\\theta^*, \\phi^* = arg \\min_{\\tilde{\\theta}, \\phi} \\{\\mathcal{R}(\\tilde{\\theta}, \\phi)\\},\n\\quad \ng(\\cdot) = min(1, max(0, \\cdot))\n$$\nHowever, it is still necessary to define the distribution for $s$.\nHere it is suggested to use a hard concrete distribution.", "_____no_output_____" ], [ "### The hard concrete distribution\n\nLets assume that $s$ is a random variable distributed in the (0, 1) interval with probability density $q_s(s|\\phi)$ and cdf $Q_s(s|\\phi)$.\nThe parameters of the distribution are $\\phi = (\\log \\alpha, \\beta)$, where $\\log\\alpha$ is the mean and $\\beta$ the temperature (???).\nWe can then stretch this distribution to the $(\\gamma, \\delta$) interval with $\\gamma < 0$ and $\\delta > 1$:\n$$\nu\\sim U(0, 1), \n\\quad\ns = Sigmoid((\\log u - \\log(1 - u) + \\log\\alpha) / \\beta), \\quad\n\\bar{s} = s(\\delta - \\gamma) + \\gamma, \\quad\nz = \\min(1, \\max(0, \\bar{s})\n$$\n\nSince these formulas are a bit difficult to visualize I have plotted them below to gain a better understanding of that they are doing and how these functions behave.", "_____no_output_____" ] ], [ [ "def hard_sigmoid(x):\n return np.min([1, np.max([0, x])])\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef hard_concrete_dist(loc, temp, gamma, zeta):\n u = np.random.random()\n s = sigmoid((np.log(u) - np.log(1 - u) + np.log(loc)) / temp)\n shat = s*(zeta - gamma) + gamma\n return hard_sigmoid(shat)\n\ndef plot_hard_concreate(loc, temp, gamma, zeta, num=10000, bins=100, **kwargs):\n plt.hist([hard_concrete_dist(loc, temp, gamma, zeta) for _ in range(num)], bins=bins, density=True, **kwargs)", "_____no_output_____" ], [ "x = np.arange(-6, 6, 0.1)\ny1 = sigmoid(x)\ny2 = [hard_sigmoid(k) for k in x]", "_____no_output_____" ], [ "fig, axs = plt.subplots(1, 2)\nfig.set_size_inches((10, 3))\naxs[0].set_title('Comparision of Sigmoids')\naxs[1].set_title('Hard Concreate Distribution')\n\naxs[0].plot(x, y1, label='Sigmoid')\naxs[0].plot(x, y2, label='Hard-Sigmoid')\nhandles, labels = axs[0].get_legend_handles_labels()\naxs[0].legend(handles, labels)\nvalues = [hard_concrete_dist(loc=1, temp=0.5, gamma=-0.1, zeta=1.1) for _ in range(1000)]\nn, bins, patches = axs[1].hist(values, bins=100, density=True)\n#fig.show()", "_____no_output_____" ], [ "fig, axs = plt.subplots()\nfig.set_size_inches((10, 8))\naxs.set_title('Comparision of Sigmoids')\n\naxs.plot(x, y1, label='Sigmoid')\naxs.plot(x, y2, label='Hard-Sigmoid')\nhandles, labels = axs.get_legend_handles_labels()\naxs.legend(handles, labels)", "_____no_output_____" ], [ "fig, axs = plt.subplots()\nfig.set_size_inches((10, 5))\naxs.set_title('Hard Concreate Distribution')\n\nvalues = [hard_concrete_dist(loc=1, temp=0.5, gamma=-0.1, zeta=1.1) for _ in range(5000)]\nn, bins, patches = axs.hist(values, bins=100, density=True)", "_____no_output_____" ] ], [ [ "# Implementation of the $L_0$ norm\n\nThe next step is to implement the theory into practice.\nI will therefore make use of Google's tensorflow to implement the $L_0$ norm.\nHere its good to know that this has been implemented before in PyTorch.\nI will compare my and their implementation to assure I have done it correctly.\nThe reason why I am not directly using PyTorch is that I don't want to learn yet again another library.\nFurthermore, implementing $L_0$ into tensorflow gives me hopefully a better understanding of the library itself as well as the $L_0$ norm.\nIn addition, tensorflow can compute the derivatives for me, so I don't have to take care of this.\n\nThe data I am going to use was simulated by Tim.\nThis includes non-linear effects, binary and continous phenotypes.\nI will first compute only penalized linear models (that is $L_0$ to $L_2$ norm) with tensorflow and validate the results (of $L_1$ and $L_2$ with already implemented libraries (sklearn).\nThe main objective is to improve prediction accuracy.", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom pyplink import PyPlink\nimport sys\nimport os", "_____no_output_____" ], [ "DATAFOLDER = os.path.realpath(filename='../data')\nPLINKDATA = '1kgb'\nFILEPATH = os.path.join(DATAFOLDER, PLINKDATA)\n\ndef count_lines(filepath, header=False):\n \"\"\"Count the number of rows in a file\"\"\"\n with open(filepath, 'r') as f:\n count = sum(1 for line in f)\n if header:\n count -= 1\n return count\n\nprint('Number of subjects:', count_lines(os.path.join(FILEPATH, '.fam'), True))\nprint('Number of SNPs:', count_lines(os.path.join(FILEPATH, '.bim'), False))", "_____no_output_____" ], [ "def get_matrix(pfile, max_block):\n \"\"\"Extract a genotype matrix from plink file.\"\"\"\n with PyPlink(pfile) as bed:\n bim = bed.get_bim()\n fam = bed.get_fam()\n n = fam.shape[0]\n p = bim.shape[0]\n assert(max_block <= p)\n genotypemat = np.zeros((n, max_block), dtype=np.int64)\n u = 0\n for loci_name, genotypes in bed:\n genotypemat[:, u] = np.array(genotypes)\n u += 1\n if u >= max_block:\n break\n return genotypemat", "_____no_output_____" ], [ "# define size of training, validation and testing data\nsample_fractions = (0.8, 0.15, 0.05)\nassert sum(sample_fractions) == 1.0\ntraining_size, validation_size, testing_size = sample_fractions\ndata_training, data_testing, label_training, label_testing = train_test_split(pheno, genotypemat, train_size=training_size)\ndata_validataion, data_testing, label_validation, label_testing = train_test_split(data_testing, label_testing, train_size=2/3)\nprint(\"Samples in training:\", len(label_training))\nprint(\"Samples in validation:\", len(label_validation))\nprint(\"Samples in testing:\", len(label_testing))", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d00f98c01b60a4319e6194ce04e701c5f5895ea1
23,239
ipynb
Jupyter Notebook
Regular Expression/PY0101EN-Regular Expressions.ipynb
reddyprasade/PYTHON-BASIC-FOR-ALL
4fa4bf850f065e9ac1cea0365b93257e1f04e2cb
[ "MIT" ]
21
2019-06-28T05:11:17.000Z
2022-03-16T02:02:28.000Z
Regular Expression/PY0101EN-Regular Expressions.ipynb
shrikant9793/Python-Basic-For-All-3.x
584500acdba7b46dfa7086b0bffe0c54adcaa2cd
[ "MIT" ]
2
2021-12-28T14:15:58.000Z
2021-12-28T14:16:02.000Z
Regular Expression/PY0101EN-Regular Expressions.ipynb
shrikant9793/Python-Basic-For-All-3.x
584500acdba7b46dfa7086b0bffe0c54adcaa2cd
[ "MIT" ]
18
2019-07-07T03:20:33.000Z
2021-05-08T10:44:18.000Z
28.584256
443
0.517922
[ [ [ "### Regular Expressions\n\nRegular expressions are `text matching patterns` described with a formal syntax. You'll often hear regular expressions referred to as 'regex' or 'regexp' in conversation. Regular expressions can include a variety of rules, for finding repetition, to text-matching, and much more. As you advance in Python you'll see that a lot of your parsing problems can be solved with regular expressions (they're also a common interview question!).\n", "_____no_output_____" ], [ "## Searching for Patterns in Text\n\nOne of the most common uses for the re module is for finding patterns in text. Let's do a quick example of using the search method in the re module to find some text:", "_____no_output_____" ] ], [ [ "import re", "_____no_output_____" ], [ "# List of patterns to search for\npatterns = [ 'term1', 'term2' ]\n\n# Text to parse\ntext = 'This is a string with term1, but it does not have the other term.'\n", "_____no_output_____" ], [ "for p in patterns:\n print ('Searching for \"%s\" in Sentence: \\n\"%s\"' % (p, text))\n \n #Check for match\n if re.search(p, text):\n print ('Match was found. \\n')\n else:\n print ('No Match was found. \\n')", "Searching for \"term1\" in Sentence: \n\"This is a string with term1, but it does not have the other term.\"\nMatch was found. \n\nSearching for \"term2\" in Sentence: \n\"This is a string with term1, but it does not have the other term.\"\nNo Match was found. \n\n" ] ], [ [ "Now we've seen that re.search() will take the pattern, scan the text, and then returns a **Match** object. If no pattern is found, a **None** is returned. To give a clearer picture of this match object, check out the cell below:", "_____no_output_____" ] ], [ [ "# List of patterns to search for\npattern = 'term1'\n\n# Text to parse\ntext = 'This is a string with term1, but it does not have the other term.'\n\nmatch = re.search(pattern, text)\n\ntype(match)", "_____no_output_____" ], [ "match", "_____no_output_____" ] ], [ [ "This **Match** object returned by the search() method is more than just a Boolean or None, it contains information about the match, including the original input string, the regular expression that was used, and the location of the match. Let's see the methods we can use on the match object:", "_____no_output_____" ] ], [ [ "# Show start of match\nmatch.start()", "_____no_output_____" ], [ "# Show end\nmatch.end()", "_____no_output_____" ], [ "s = \"abassabacdReddyceaabadjfvababaReddy\"\nr = re.compile(\"Reddy\")\nr", "_____no_output_____" ], [ "l = re.findall(r,s)\nprint(l)", "['Reddy', 'Reddy']\n" ], [ "import re\ns = \"abcdefg1234\"\nr = re.compile(\"^[a-z][0-9]$\")\nl = re.findall(r,s)\nprint(l)", "[]\n" ], [ "s = \"ABCDE1234a\"\nr = re.compile(r\"^[A-Z]{5}[0-9]{4}[a-z]$\")\nl = re.findall(r,s)\nprint(l)", "['ABCDE1234a']\n" ], [ "s = \"+917123456789\"\ns1 = \"07123456789\"\ns2 = \"7123456789\"\nr = re.compile(r\"[6-9][0-9]{9}\")\nl = re.findall(r,s)\nprint(l)", "['9171234567']\n" ], [ "l = re.findall(r,s1)\nprint(l)", "['7123456789']\n" ], [ "l = re.findall(r,s2)\nprint(l)", "['7123456789']\n" ], [ "s = \"+917234567891\"\ns1 = \"07123456789\"\ns2 = \"7123456789\"\nr = re.compile(r\"^(\\+91)?[0]?([6-9][0-9]{9})$\")\nm = re.search(r,s1)\nif m:\n print(m.group())\nelse:\n print(\"Invalid string\")", "07123456789\n" ], [ "for _ in range(int(input(\"No of Test Cases:\"))):\n line = input(\"Mobile Number\")\n if re.match(r\"^[789]{1}\\d{9}$\", line):\n print(\"YES\")\n else:\n print(\"NO\")", "No of Test Cases: 2\nMobile Number 9666302750\n" ], [ "#Named groups\ns = \"12-02-2017\" # DD-MM-YYYY\n# dd-mm-yyyy\nr = re.compile(r\"^(?P<day>\\d{2})-(?P<month>[0-9]{2})-(?P<year>[0-9]{4})\")\nm = re.search(r,s)\nif m:\n print(m.group('year'))\n print(m.group('month'))\n print(m.group('day'))", "_____no_output_____" ] ], [ [ "## Split with regular expressions\n\nLet's see how we can split with the re syntax. This should look similar to how you used the split() method with strings.", "_____no_output_____" ] ], [ [ "# Term to split on\nsplit_term = '@'\n\nphrase = 'What is the domain name of someone with the email: hello@gmail.com'\n\n# Split the phrase\nre.split(split_term,phrase)", "_____no_output_____" ] ], [ [ "Note how re.split() returns a list with the term to spit on removed and the terms in the list are a split up version of the string. Create a couple of more examples for yourself to make sure you understand!\n\n## Finding all instances of a pattern\n\nYou can use re.findall() to find all the instances of a pattern in a string. For example:", "_____no_output_____" ] ], [ [ "# Returns a list of all matches\nre.findall('is','test phrase match is in middle')", "_____no_output_____" ], [ "a = \" a list with the term to spit on removed and the terms in the list are a split up version of the string. Create a couple of more examples for yourself to make sure you understand!\"\ncopy = re.findall(\"to\",a)\ncopy", "_____no_output_____" ], [ "len(copy)", "_____no_output_____" ] ], [ [ "## Pattern re Syntax\n\nThis will be the bulk of this lecture on using re with Python. Regular expressions supports a huge variety of patterns the just simply finding where a single string occurred. \n\nWe can use *metacharacters* along with re to find specific types of patterns. \n\nSince we will be testing multiple re syntax forms, let's create a function that will print out results given a list of various regular expressions and a phrase to parse:", "_____no_output_____" ] ], [ [ "def multi_re_find(patterns,phrase):\n '''\n Takes in a list of regex patterns\n Prints a list of all matches\n '''\n for pattern in patterns:\n print ('Searching the phrase using the re check: %r' %pattern)\n print (re.findall(pattern,phrase))", "_____no_output_____" ] ], [ [ "### Repetition Syntax\n\nThere are five ways to express repetition in a pattern:\n\n 1.) A pattern followed by the meta-character * is repeated zero or more times. \n 2.) Replace the * with + and the pattern must appear at least once. \n 3.) Using ? means the pattern appears zero or one time. \n 4.) For a specific number of occurrences, use {m} after the pattern, where m is replaced with the number of times the pattern should repeat. \n 5.) Use {m,n} where m is the minimum number of repetitions and n is the maximum. Leaving out n ({m,}) means the value appears at least m times, with no maximum.\n \nNow we will see an example of each of these using our multi_re_find function:", "_____no_output_____" ] ], [ [ "test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'\n\ntest_patterns = [ 'sd*', # s followed by zero or more d's\n 'sd+', # s followed by one or more d's\n 'sd?', # s followed by zero or one d's\n 'sd{3}', # s followed by three d's\n 'sd{2,3}', # s followed by two to three d's\n ]\n\nmulti_re_find(test_patterns,test_phrase)", "Searching the phrase using the re check: 'sd*'\n['sd', 'sd', 's', 's', 'sddd', 'sddd', 'sddd', 'sd', 's', 's', 's', 's', 's', 's', 'sdddd']\nSearching the phrase using the re check: 'sd+'\n['sd', 'sd', 'sddd', 'sddd', 'sddd', 'sd', 'sdddd']\nSearching the phrase using the re check: 'sd?'\n['sd', 'sd', 's', 's', 'sd', 'sd', 'sd', 'sd', 's', 's', 's', 's', 's', 's', 'sd']\nSearching the phrase using the re check: 'sd{3}'\n['sddd', 'sddd', 'sddd', 'sddd']\nSearching the phrase using the re check: 'sd{2,3}'\n['sddd', 'sddd', 'sddd', 'sddd']\n" ] ], [ [ "## Character Sets\n\nCharacter sets are used when you wish to match any one of a group of characters at a point in the input. Brackets are used to construct character set inputs. For example: the input [ab] searches for occurrences of either a or b.\nLet's see some examples:", "_____no_output_____" ] ], [ [ "test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'\n\ntest_patterns = [ '[sd]', # either s or d\n 's[sd]+'] # s followed by one or more s or d\n \n\nmulti_re_find(test_patterns,test_phrase)", "Searching the phrase using the re check: '[sd]'\n['s', 'd', 's', 'd', 's', 's', 's', 'd', 'd', 'd', 's', 'd', 'd', 'd', 's', 'd', 'd', 'd', 'd', 's', 'd', 's', 'd', 's', 's', 's', 's', 's', 's', 'd', 'd', 'd', 'd']\nSearching the phrase using the re check: 's[sd]+'\n['sdsd', 'sssddd', 'sdddsddd', 'sds', 'sssss', 'sdddd']\n" ] ], [ [ "It makes sense that the first [sd] returns every instance. Also the second input will just return any thing starting with an s in this particular case of the test phrase input.", "_____no_output_____" ], [ "## Exclusion\n\nWe can use ^ to exclude terms by incorporating it into the bracket syntax notation. For example: [^...] will match any single character not in the brackets. Let's see some examples:", "_____no_output_____" ] ], [ [ "test_phrase = 'This is a string! But it has punctuation. How can we remove it?'", "_____no_output_____" ] ], [ [ "Use [^!.? ] to check for matches that are not a !,.,?, or space. Add the + to check that the match appears at least once, this basically translate into finding the words.", "_____no_output_____" ] ], [ [ "re.findall('[^!.? ]+',test_phrase)", "_____no_output_____" ] ], [ [ "## Character Ranges\n\nAs character sets grow larger, typing every character that should (or should not) match could become very tedious. A more compact format using character ranges lets you define a character set to include all of the contiguous characters between a start and stop point. The format used is [start-end].\n\nCommon use cases are to search for a specific range of letters in the alphabet, such [a-f] would return matches with any instance of letters between a and f. \n\nLet's walk through some examples:", "_____no_output_____" ] ], [ [ "\ntest_phrase = 'This is an example sentence. Lets see if we can find some letters.'\n\ntest_patterns=[ '[a-z]+', # sequences of lower case letters\n '[A-Z]+', # sequences of upper case letters\n '[a-zA-Z]+', # sequences of lower or upper case letters\n '[A-Z][a-z]+'] # one upper case letter followed by lower case letters\n \nmulti_re_find(test_patterns,test_phrase)", "Searching the phrase using the re check: '[a-z]+'\n['his', 'is', 'an', 'example', 'sentence', 'ets', 'see', 'if', 'we', 'can', 'find', 'some', 'letters']\nSearching the phrase using the re check: '[A-Z]+'\n['T', 'L']\nSearching the phrase using the re check: '[a-zA-Z]+'\n['This', 'is', 'an', 'example', 'sentence', 'Lets', 'see', 'if', 'we', 'can', 'find', 'some', 'letters']\nSearching the phrase using the re check: '[A-Z][a-z]+'\n['This', 'Lets']\n" ] ], [ [ "## Escape Codes\n\nYou can use special escape codes to find specific types of patterns in your data, such as digits, non-digits,whitespace, and more. For example:\n\n<table border=\"1\" class=\"docutils\">\n<colgroup>\n<col width=\"14%\" />\n<col width=\"86%\" />\n</colgroup>\n<thead valign=\"bottom\">\n<tr class=\"row-odd\"><th class=\"head\">Code</th>\n<th class=\"head\">Meaning</th>\n</tr>\n</thead>\n<tbody valign=\"top\">\n<tr class=\"row-even\"><td><tt class=\"docutils literal\"><span class=\"pre\">\\d</span></tt></td>\n<td>a digit</td>\n</tr>\n<tr class=\"row-odd\"><td><tt class=\"docutils literal\"><span class=\"pre\">\\D</span></tt></td>\n<td>a non-digit</td>\n</tr>\n<tr class=\"row-even\"><td><tt class=\"docutils literal\"><span class=\"pre\">\\s</span></tt></td>\n<td>whitespace (tab, space, newline, etc.)</td>\n</tr>\n<tr class=\"row-odd\"><td><tt class=\"docutils literal\"><span class=\"pre\">\\S</span></tt></td>\n<td>non-whitespace</td>\n</tr>\n<tr class=\"row-even\"><td><tt class=\"docutils literal\"><span class=\"pre\">\\w</span></tt></td>\n<td>alphanumeric</td>\n</tr>\n<tr class=\"row-odd\"><td><tt class=\"docutils literal\"><span class=\"pre\">\\W</span></tt></td>\n<td>non-alphanumeric</td>\n</tr>\n</tbody>\n</table>\n\nEscapes are indicated by prefixing the character with a backslash (\\). Unfortunately, a backslash must itself be escaped in normal Python strings, and that results in expressions that are difficult to read. Using raw strings, created by prefixing the literal value with r, for creating regular expressions eliminates this problem and maintains readability.\n\nPersonally, I think this use of r to escape a backslash is probably one of the things that block someone who is not familiar with regex in Python from being able to read regex code at first. Hopefully after seeing these examples this syntax will become clear.", "_____no_output_____" ] ], [ [ "test_phrase = 'This is a string with some numbers 1233 and a symbol #hashtag'\n\ntest_patterns=[ r'\\d+', # sequence of digits\n r'\\D+', # sequence of non-digits\n r'\\s+', # sequence of whitespace\n r'\\S+', # sequence of non-whitespace\n r'\\w+', # alphanumeric characters\n r'\\W+', # non-alphanumeric\n ]\n\nmulti_re_find(test_patterns,test_phrase)", "Searching the phrase using the re check: '\\\\d+'\n['1233']\nSearching the phrase using the re check: '\\\\D+'\n['This is a string with some numbers ', ' and a symbol #hashtag']\nSearching the phrase using the re check: '\\\\s+'\n[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\nSearching the phrase using the re check: '\\\\S+'\n['This', 'is', 'a', 'string', 'with', 'some', 'numbers', '1233', 'and', 'a', 'symbol', '#hashtag']\nSearching the phrase using the re check: '\\\\w+'\n['This', 'is', 'a', 'string', 'with', 'some', 'numbers', '1233', 'and', 'a', 'symbol', 'hashtag']\nSearching the phrase using the re check: '\\\\W+'\n[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' #']\n" ] ], [ [ "## Conclusion\n\nYou should now have a solid understanding of how to use the regular expression module in Python. There are a ton of more special character instances, but it would be unreasonable to go through every single use case. Instead take a look at the full [documentation](https://docs.python.org/2.4/lib/re-syntax.html) if you ever need to look up a particular case.\n\nYou can also check out the nice summary tables at this [source](http://www.tutorialspoint.com/python/python_reg_expressions.htm).\n\nGood job!\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" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d00fa12675dbc01bf2d3a1496159fdf65239d7da
24,944
ipynb
Jupyter Notebook
homework/homework-for-week-5-SOLUTION.ipynb
jchapamalacara/fall21-students-practical-python
3a1f4613b46933d3ab1d0741177f0d4ec6b6b600
[ "MIT" ]
null
null
null
homework/homework-for-week-5-SOLUTION.ipynb
jchapamalacara/fall21-students-practical-python
3a1f4613b46933d3ab1d0741177f0d4ec6b6b600
[ "MIT" ]
null
null
null
homework/homework-for-week-5-SOLUTION.ipynb
jchapamalacara/fall21-students-practical-python
3a1f4613b46933d3ab1d0741177f0d4ec6b6b600
[ "MIT" ]
1
2021-11-01T01:41:39.000Z
2021-11-01T01:41:39.000Z
29.801673
177
0.42852
[ [ [ "You will scrape this <a href=\"https://sandeepmj.github.io/scrape-example-page/homework-site.html\">mockup site</a> that lists a few data points for addiction centers.", "_____no_output_____" ] ], [ [ "pip install icecream", "Collecting icecream\n Downloading icecream-2.1.1-py2.py3-none-any.whl (8.1 kB)\nCollecting colorama>=0.3.9\n Downloading colorama-0.4.4-py2.py3-none-any.whl (16 kB)\nCollecting executing>=0.3.1\n Downloading executing-0.8.1-py2.py3-none-any.whl (16 kB)\nRequirement already satisfied: pygments>=2.2.0 in /usr/local/lib/python3.7/dist-packages (from icecream) (2.6.1)\nCollecting asttokens>=2.0.1\n Downloading asttokens-2.0.5-py2.py3-none-any.whl (20 kB)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from asttokens>=2.0.1->icecream) (1.15.0)\nInstalling collected packages: executing, colorama, asttokens, icecream\nSuccessfully installed asttokens-2.0.5 colorama-0.4.4 executing-0.8.1 icecream-2.1.1\n" ], [ "## import library(ies)\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom icecream import ic ", "_____no_output_____" ], [ "## capture the contents of the site in a response object\n\nurl = \"https://sandeepmj.github.io/scrape-example-page/homework-site.html\"\nresponse = requests.get(url)\nic(response.status_code)", "ic| response.status_code: 200\n" ], [ "## generate and print soup\nsoup = BeautifulSoup(response.text, 'html.parser')\nsoup", "_____no_output_____" ], [ "## check data type of soup\ntype(soup)", "_____no_output_____" ], [ "### Return the name of the first center (including the html)\nsoup.find(\"a\")", "_____no_output_____" ], [ "## if there were another a tag that did not have our target, we coud be more specific.\nsoup.find(\"div\", class_=\"wrap\").find(\"h4\").find(\"a\") ", "_____no_output_____" ], [ "### Return only the name of the first center (remove all the html)\nsoup.find(\"a\").get_text()", "_____no_output_____" ], [ "### Return only the URL of the first center\nsoup.find(\"a\").get(\"href\")", "_____no_output_____" ], [ "### Find first instance of ALL a center's data\n### Think of this as the first group of data associated with a company\nsoup.find(\"div\", class_=\"wrap\")", "_____no_output_____" ], [ "#### Find all the instances of every centers' data points.\nsoup.find_all(\"div\", class_=\"wrap\")", "_____no_output_____" ], [ "### Find all the registration data\nsoup.find_all(\"p\", class_=\"registration\")", "_____no_output_____" ] ], [ [ "### Place all the registration data into a list with only the numbers in the format.\nIt should look like this:\n\n```['4235', '4234', '4231']```", "_____no_output_____" ] ], [ [ "## for loop\nregs = soup.find_all(\"p\", class_=\"registration\")\nreg_list_fl = []\nfor item in regs:\n reg_list_fl.append(item.get_text().replace(\"Registration# \", \"\"))\n\nreg_list_fl\n", "_____no_output_____" ], [ "## do it here (create more cells if you need them)\n## via list comprehension\nregs = soup.find_all(\"p\", class_=\"registration\")\nreg_list_lc = [item.get_text().replace(\"Registration# \", \"\") for item in regs]\nreg_list_lc", "_____no_output_____" ] ], [ [ "### Place all the company names into a list.\nIt should look like this:\n\n```['Recovery Foundation','New Horizons','Renewable Light']```", "_____no_output_____" ] ], [ [ "## do it here (create more cells if you need them)\ncos = soup.find_all(\"a\")\ncos", "_____no_output_____" ], [ "### lc\nco_names_list = [item.get_text() for item in cos]\nco_names_list", "_____no_output_____" ] ], [ [ "### Place all the URLS into a list.\n", "_____no_output_____" ] ], [ [ "## do it here (create more cells if you need them)\nco_urls = [item.get(\"href\") for item in cos]\nco_urls", "_____no_output_____" ] ], [ [ "### Place all the status into a list.\nIt should look like this:\n\n```['Passed', 'Failed', 'Passed']```", "_____no_output_____" ] ], [ [ "## do it here (create more cells if you need them)\ncenter_status = soup.find_all(\"p\", class_=\"status\")\ncenter_status", "_____no_output_____" ], [ "status_list = [status.get_text().replace(\"Inspection: \", \"\") for status in center_status ]\nstatus_list", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "### Turn these lists into dataframes and export to a csv", "_____no_output_____" ] ], [ [ "### use pandas DataFrame method to zip files into a dataframe\ndf = pd.DataFrame(list(zip(co_names_list, reg_list, status_list, co_urls)), \n columns =['center_name', \"registration_number\",'status', 'link'])\n\ndf", "_____no_output_____" ], [ "## export to csv\nfilename = \"recovery_center_list.csv\"\ndf.to_csv(filename, encoding='utf-8', index=False) ## export to csv as utf-8 coding (it just has to be this)\n", "_____no_output_____" ], [ "", "_____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" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d00fa575d7e6aaa5738e9a6c4e089bf111520e4d
9,821
ipynb
Jupyter Notebook
1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb
shijiansu/coursera-applied-data-science-with-python
a0f2bbd0b9201805f26d18b73a25183cf0b3a0e9
[ "MIT" ]
1
2019-05-09T21:18:16.000Z
2019-05-09T21:18:16.000Z
1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb
shijiansu/coursera-applied-data-science-with-python
a0f2bbd0b9201805f26d18b73a25183cf0b3a0e9
[ "MIT" ]
null
null
null
1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb
shijiansu/coursera-applied-data-science-with-python
a0f2bbd0b9201805f26d18b73a25183cf0b3a0e9
[ "MIT" ]
null
null
null
29.760606
508
0.593626
[ [ [ "---\n\n_You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._\n\n---", "_____no_output_____" ], [ "# Assignment 2 - Pandas Introduction\nAll questions are weighted the same in this assignment.\n## Part 1\nThe following code loads the olympics dataset (olympics.csv), which was derrived from the Wikipedia entry on [All Time Olympic Games Medals](https://en.wikipedia.org/wiki/All-time_Olympic_Games_medal_table), and does some basic data cleaning. \n\nThe columns are organized as # of Summer games, Summer medals, # of Winter games, Winter medals, total # number of games, total # of medals. Use this dataset to answer the questions below.", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ndf = pd.read_csv('olympics.csv', index_col=0, skiprows=1)\n\nfor col in df.columns:\n if col[:2]=='01':\n df.rename(columns={col:'Gold'+col[4:]}, inplace=True)\n if col[:2]=='02':\n df.rename(columns={col:'Silver'+col[4:]}, inplace=True)\n if col[:2]=='03':\n df.rename(columns={col:'Bronze'+col[4:]}, inplace=True)\n if col[:1]=='№':\n df.rename(columns={col:'#'+col[1:]}, inplace=True)\n\nnames_ids = df.index.str.split('\\s\\(') # split the index by '('\n\ndf.index = names_ids.str[0] # the [0] element is the country name (new index) \ndf['ID'] = names_ids.str[1].str[:3] # the [1] element is the abbreviation or ID (take first 3 characters from that)\n\ndf = df.drop('Totals')\ndf.head()", "_____no_output_____" ] ], [ [ "### Question 0 (Example)\n\nWhat is the first country in df?\n\n*This function should return a Series.*", "_____no_output_____" ] ], [ [ "# You should write your whole answer within the function provided. The autograder will call\n# this function and compare the return value against the correct solution value\ndef answer_zero():\n # This function returns the row for Afghanistan, which is a Series object. The assignment\n # question description will tell you the general format the autograder is expecting\n return df.iloc[0]\n\n# You can examine what your function returns by calling it in the cell. If you have questions\n# about the assignment formats, check out the discussion forums for any FAQs\nanswer_zero() ", "_____no_output_____" ] ], [ [ "### Question 1\nWhich country has won the most gold medals in summer games?\n\n*This function should return a single string value.*", "_____no_output_____" ] ], [ [ "def answer_one():\n return \"YOUR ANSWER HERE\"", "_____no_output_____" ] ], [ [ "### Question 2\nWhich country had the biggest difference between their summer and winter gold medal counts?\n\n*This function should return a single string value.*", "_____no_output_____" ] ], [ [ "def answer_two():\n return \"YOUR ANSWER HERE\"", "_____no_output_____" ] ], [ [ "### Question 3\nWhich country has the biggest difference between their summer gold medal counts and winter gold medal counts relative to their total gold medal count? \n\n$$\\frac{Summer~Gold - Winter~Gold}{Total~Gold}$$\n\nOnly include countries that have won at least 1 gold in both summer and winter.\n\n*This function should return a single string value.*", "_____no_output_____" ] ], [ [ "def answer_three():\n return \"YOUR ANSWER HERE\"", "_____no_output_____" ] ], [ [ "### Question 4\nWrite a function to update the dataframe to include a new column called \"Points\" which is a weighted value where each gold medal counts for 3 points, silver medals for 2 points, and bronze mdeals for 1 point. The function should return only the column (a Series object) which you created.\n\n*This function should return a Series named `Points` of length 146*", "_____no_output_____" ] ], [ [ "def answer_four():\n return \"YOUR ANSWER HERE\"", "_____no_output_____" ] ], [ [ "## Part 2\nFor the next set of questions, we will be using census data from the [United States Census Bureau](http://www.census.gov/popest/data/counties/totals/2015/CO-EST2015-alldata.html). Counties are political and geographic subdivisions of states in the United States. This dataset contains population data for counties and states in the US from 2010 to 2015. [See this document](http://www.census.gov/popest/data/counties/totals/2015/files/CO-EST2015-alldata.pdf) for a description of the variable names.\n\nThe census dataset (census.csv) should be loaded as census_df. Answer questions using this as appropriate.\n\n### Question 5\nWhich state has the most counties in it? (hint: consider the sumlevel key carefully! You'll need this for future questions too...)\n\n*This function should return a single string value.*", "_____no_output_____" ] ], [ [ "census_df = pd.read_csv('census.csv')\ncensus_df.head()", "_____no_output_____" ], [ "def answer_five():\n return \"YOUR ANSWER HERE\"", "_____no_output_____" ] ], [ [ "### Question 6\nOnly looking at the three most populous counties for each state, what are the three most populous states (in order of highest population to lowest population)?\n\n*This function should return a list of string values.*", "_____no_output_____" ] ], [ [ "def answer_six():\n return \"YOUR ANSWER HERE\"", "_____no_output_____" ] ], [ [ "### Question 7\nWhich county has had the largest absolute change in population within the period 2010-2015? (Hint: population values are stored in columns POPESTIMATE2010 through POPESTIMATE2015, you need to consider all six columns.)\n\ne.g. If County Population in the 5 year period is 100, 120, 80, 105, 100, 130, then its largest change in the period would be |130-80| = 50.\n\n*This function should return a single string value.*", "_____no_output_____" ] ], [ [ "def answer_seven():\n return \"YOUR ANSWER HERE\"", "_____no_output_____" ] ], [ [ "### Question 8\nIn this datafile, the United States is broken up into four regions using the \"REGION\" column. \n\nCreate a query that finds the counties that belong to regions 1 or 2, whose name starts with 'Washington', and whose POPESTIMATE2015 was greater than their POPESTIMATE 2014.\n\n*This function should return a 5x2 DataFrame with the columns = ['STNAME', 'CTYNAME'] and the same index ID as the census_df (sorted ascending by index).*", "_____no_output_____" ] ], [ [ "def answer_eight():\n return \"YOUR ANSWER HERE\"", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d00fb831f89db8a684ae3b7793a761f4ac336e24
589,283
ipynb
Jupyter Notebook
Image-Processing/image-understanding-in-Details.ipynb
TUCchkul/ComputerVision-ObjectDetection
15f8de191cee667061dcfb014bdb1a98ca3c220f
[ "MIT" ]
null
null
null
Image-Processing/image-understanding-in-Details.ipynb
TUCchkul/ComputerVision-ObjectDetection
15f8de191cee667061dcfb014bdb1a98ca3c220f
[ "MIT" ]
null
null
null
Image-Processing/image-understanding-in-Details.ipynb
TUCchkul/ComputerVision-ObjectDetection
15f8de191cee667061dcfb014bdb1a98ca3c220f
[ "MIT" ]
null
null
null
472.181891
153,844
0.945186
[ [ [ "car=\"car1.jpeg\"", "_____no_output_____" ], [ "import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg", "_____no_output_____" ], [ "car1=mpimg.imread('car1.jpeg')", "_____no_output_____" ], [ "car1.shape", "_____no_output_____" ], [ "type(car1)", "_____no_output_____" ], [ "plt.imshow(car1)", "_____no_output_____" ], [ "#plt.imshow(car)", "_____no_output_____" ], [ "car1_cv2=cv2.imread('car1.jpeg')\ncolor_car_cv2=cv2.cvtColor(car1_cv2, cv2.COLOR_BGR2RGB)", "_____no_output_____" ], [ "plt.imshow(color_car_cv2)", "_____no_output_____" ], [ "car1_cv2_BGR_Gray=cv2.cvtColor(car1,cv2.COLOR_BGR2GRAY)\nplt.imshow(car1_cv2_BGR_Gray, cmap=\"gray\")", "_____no_output_____" ], [ "car1_cv2_BGR_Gray.shape", "_____no_output_____" ], [ "car1_cv2_BGR_Gray.min(), car1_cv2_BGR_Gray.max()", "_____no_output_____" ], [ "car1_cv2_BGR_Gray[0][0]", "_____no_output_____" ], [ "cv2.imwrite(\"car_gray.jpeg\",car1_cv2_BGR_Gray)", "_____no_output_____" ], [ "car1_cv2_BGR_Gray[0][200]", "_____no_output_____" ] ], [ [ "# Visualize all the RGB channel", "_____no_output_____" ] ], [ [ "def visualize_RGB_Channels(imgArray=None, fig_size=(10,7)):\n # spliting the RGB components\n B,G,R=cv2.split(imgArray)\n #zero matrix\n Z=np.zeros(B.shape,dtype=B.dtype)\n #initilize subplot\n fig,ax=plt.subplots(2,2, figsize=fig_size)\n [axi.set_axis_off() for axi in ax.ravel()]\n ax[0,0].set_title(\"Original image\")\n ax[0,0].imshow(cv2.merge((R,G,B)))\n ax[0,1].set_title(\"Red Chanel\")\n ax[0,1].imshow(cv2.merge((R,Z,Z)))\n ax[1,0].set_title(\"Green Chanel\")\n ax[1,0].imshow(cv2.merge((Z,G,Z)))\n ax[1,1].set_title(\"Blue Chanel\")\n ax[1,1].imshow(cv2.merge((Z,Z,B)))", "_____no_output_____" ], [ "visualize_RGB_Channels(imgArray=car1_cv2)", "_____no_output_____" ], [ "random_colored_image=np.random.randint(0,255,(6,6,3))\nrandom_colored_image.shape", "_____no_output_____" ], [ "visualize_RGB_Channels(imgArray=random_colored_image)", "_____no_output_____" ], [ "random_colored_image[0,0:]", "_____no_output_____" ], [ "random_colored_image[0,0,:]", "_____no_output_____" ], [ "random_colored_image[-1,-1,:]", "_____no_output_____" ] ], [ [ "# Filters", "_____no_output_____" ] ], [ [ "sobel=np.array([[1,0,-1],[2,0,-2],[1,0,-1]])\nprint(sobel)", "[[ 1 0 -1]\n [ 2 0 -2]\n [ 1 0 -1]]\n" ], [ "sobel.T", "_____no_output_____" ], [ "example1=[[0,0,0,255,255,255],\n [0,0,0,255,255,255],\n [0,0,0,255,255,255],\n [0,0,0,255,255,255],\n [0,0,0,255,255,255],\n [0,0,0,255,255,255]]", "_____no_output_____" ], [ "example1=np.array(example1)", "_____no_output_____" ], [ "plt.imshow(example1, cmap=\"gray\")", "_____no_output_____" ] ], [ [ "# Apply filter on this image", "_____no_output_____" ] ], [ [ "def find_edges(imgFilter=None, picture=None):\n # extract row and column of an input picture\n p_row,p_col=picture.shape\n k=imgFilter.shape[0]\n temp=list()\n strides=1\n #resultant rows and columns\n final_columns=(p_col -k)//strides +1\n \n final_rows=(p_row -k)//strides +1\n #take vertically down sr´tride accross row by row\n for v_stride in range(final_rows):\n for h_stride in range(final_columns):\n target_area_of_pic=picture[v_stride:v_stride +k, h_stride:h_stride+k]\n temp.append(sum(sum(imgFilter* target_area_of_pic)))\n #print(temp)\n return np.array(temp).reshape(final_rows,final_columns)\n ", "_____no_output_____" ], [ "result=find_edges(sobel, example1)\nresult\nsum(sum(result))", "[0, -1020, -1020, 0, 0, -1020, -1020, 0, 0, -1020, -1020, 0, 0, -1020, -1020, 0]\n" ], [ "example1", "_____no_output_____" ], [ "sum(example1)", "_____no_output_____" ], [ "sum(sum(example1))", "_____no_output_____" ], [ "plt.imshow(result, cmap=\"gray\")", "_____no_output_____" ], [ "sobel.T", "_____no_output_____" ], [ "result_T=find_edges(sobel.T, example1)\nresult_T", "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n" ], [ "plt.imshow(result_T, cmap=\"gray\")", "_____no_output_____" ], [ "example1", "_____no_output_____" ], [ "example_T=example1.T\nplt.imshow(example_T,cmap=\"gray\")", "_____no_output_____" ], [ "result_T1=find_edges(sobel.T, example_T)\nresult_T1", "[0, 0, 0, 0, -1020, -1020, -1020, -1020, -1020, -1020, -1020, -1020, 0, 0, 0, 0]\n" ], [ "plt.imshow(result_T1, cmap=\"gray\")", "_____no_output_____" ], [ "result_car=find_edges(sobel,car1_cv2_BGR_Gray)\nresult_car", "_____no_output_____" ], [ "plt.imshow(result_car, cmap=\"gray\")", "_____no_output_____" ] ], [ [ "# lets now apply horizontal edges", "_____no_output_____" ] ], [ [ "result_car_hor=find_edges(sobel.T, car1_cv2_BGR_Gray)", "_____no_output_____" ], [ "plt.imshow(result_car, cmap=\"gray\")", "_____no_output_____" ], [ "example1", "_____no_output_____" ], [ "example1=[[255,0,0,0,255,255,255,255,0,0,0,255],\n [0,0,0,0,255,255,255,255,0,0,0,0],\n [0,0,0,0,255,255,255,255,255,255,255,255],\n [0,0,0,0,255,255,255,255,255,255,255,255],\n [0,0,0,0,255,255,255,255,255,255,255,255],\n [0,0,0,0,255,255,255,255,255,255,255,255],\n [0,0,0,0,255,255,255,255,255,255,255,255],\n [0,0,0,0,255,255,255,255,0,0,0,0],\n [0,0,0,0,255,255,255,255,0,0,0,0],\n [255,0,0,0,255,255,255,255,0,0,0,255]]", "_____no_output_____" ], [ "example1=np.array(example1)", "_____no_output_____" ], [ "plt.imshow(example1, cmap=\"gray\")", "_____no_output_____" ], [ "result=find_edges(sobel.T, example1)\nplt.imshow(result, cmap=\"gray\")", "_____no_output_____" ], [ "result.shape", "_____no_output_____" ] ] ]
[ "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", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d00fd3a3a5b3f9f1117e48404d99d2db6e9eaa1b
64,923
ipynb
Jupyter Notebook
processamento-de-linguagem-natural/aula1.ipynb
andredarcie/my-data-science-notebooks
7d3c82f546819a5e503b39e1d2e06aa3b5f41ff0
[ "MIT" ]
1
2021-05-19T02:01:45.000Z
2021-05-19T02:01:45.000Z
processamento-de-linguagem-natural/aula1.ipynb
andredarcie/my-data-science-notebooks
7d3c82f546819a5e503b39e1d2e06aa3b5f41ff0
[ "MIT" ]
null
null
null
processamento-de-linguagem-natural/aula1.ipynb
andredarcie/my-data-science-notebooks
7d3c82f546819a5e503b39e1d2e06aa3b5f41ff0
[ "MIT" ]
1
2022-01-16T21:58:55.000Z
2022-01-16T21:58:55.000Z
45.56
4,293
0.628976
[ [ [ "pip install nltk", "Requirement already satisfied: nltk in c:\\python38\\lib\\site-packages (3.5)Note: you may need to restart the kernel to use updated packages.\nWARNING: You are using pip version 20.2.2; however, version 21.0.1 is available.\nYou should consider upgrading via the 'C:\\Python38\\python.exe -m pip install --upgrade pip' command.\n\nRequirement already satisfied: click in c:\\python38\\lib\\site-packages (from nltk) (7.1.2)\nRequirement already satisfied: joblib in c:\\python38\\lib\\site-packages (from nltk) (1.0.1)\nRequirement already satisfied: regex in c:\\python38\\lib\\site-packages (from nltk) (2021.3.17)\nRequirement already satisfied: tqdm in c:\\python38\\lib\\site-packages (from nltk) (4.59.0)\n" ], [ "import nltk\nimport string\nimport re", "_____no_output_____" ], [ "texto_original = \"\"\"Algoritmos inteligentes de aprendizados correndo supervisionados utilizam dados coletados. A partir dos dados coletados, um conjunto de característica é extraído. As características podem ser estruturais ou estatísticas. Correr correste corrida inteligente. As característica estruturais estabelecem relações entre os dados, inteligência enquanto que as estatísticas são características quantitativas. A partir das corrido características, os modelos de aprendizado de máquina corremos são construídos para o reconhecimento de atividades humanas.\"\"\"", "_____no_output_____" ], [ "texto_original", "_____no_output_____" ], [ "#texto_original = re.sub(r'\\s+', '', texto_original)\n#texto_original", "_____no_output_____" ], [ "def converte_para_minusculas(texto):\n texto_formatado = texto.lower()\n return texto_formatado", "_____no_output_____" ], [ "texto_formatado = converte_para_minusculas(texto_original)\ntexto_formatado", "_____no_output_____" ], [ "nltk.download('stopwords')", "[nltk_data] Downloading package stopwords to\n[nltk_data] C:\\Users\\andre\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n" ], [ "stopwords = nltk.corpus.stopwords.words('portuguese')", "_____no_output_____" ], [ "print(stopwords)", "['de', 'a', 'o', 'que', 'e', 'é', 'do', 'da', 'em', 'um', 'para', 'com', 'não', 'uma', 'os', 'no', 'se', 'na', 'por', 'mais', 'as', 'dos', 'como', 'mas', 'ao', 'ele', 'das', 'à', 'seu', 'sua', 'ou', 'quando', 'muito', 'nos', 'já', 'eu', 'também', 'só', 'pelo', 'pela', 'até', 'isso', 'ela', 'entre', 'depois', 'sem', 'mesmo', 'aos', 'seus', 'quem', 'nas', 'me', 'esse', 'eles', 'você', 'essa', 'num', 'nem', 'suas', 'meu', 'às', 'minha', 'numa', 'pelos', 'elas', 'qual', 'nós', 'lhe', 'deles', 'essas', 'esses', 'pelas', 'este', 'dele', 'tu', 'te', 'vocês', 'vos', 'lhes', 'meus', 'minhas', 'teu', 'tua', 'teus', 'tuas', 'nosso', 'nossa', 'nossos', 'nossas', 'dela', 'delas', 'esta', 'estes', 'estas', 'aquele', 'aquela', 'aqueles', 'aquelas', 'isto', 'aquilo', 'estou', 'está', 'estamos', 'estão', 'estive', 'esteve', 'estivemos', 'estiveram', 'estava', 'estávamos', 'estavam', 'estivera', 'estivéramos', 'esteja', 'estejamos', 'estejam', 'estivesse', 'estivéssemos', 'estivessem', 'estiver', 'estivermos', 'estiverem', 'hei', 'há', 'havemos', 'hão', 'houve', 'houvemos', 'houveram', 'houvera', 'houvéramos', 'haja', 'hajamos', 'hajam', 'houvesse', 'houvéssemos', 'houvessem', 'houver', 'houvermos', 'houverem', 'houverei', 'houverá', 'houveremos', 'houverão', 'houveria', 'houveríamos', 'houveriam', 'sou', 'somos', 'são', 'era', 'éramos', 'eram', 'fui', 'foi', 'fomos', 'foram', 'fora', 'fôramos', 'seja', 'sejamos', 'sejam', 'fosse', 'fôssemos', 'fossem', 'for', 'formos', 'forem', 'serei', 'será', 'seremos', 'serão', 'seria', 'seríamos', 'seriam', 'tenho', 'tem', 'temos', 'tém', 'tinha', 'tínhamos', 'tinham', 'tive', 'teve', 'tivemos', 'tiveram', 'tivera', 'tivéramos', 'tenha', 'tenhamos', 'tenham', 'tivesse', 'tivéssemos', 'tivessem', 'tiver', 'tivermos', 'tiverem', 'terei', 'terá', 'teremos', 'terão', 'teria', 'teríamos', 'teriam']\n" ], [ "len(stopwords)", "_____no_output_____" ], [ "stopwords.append('ola')\nprint(stopwords)\nstopwords.remove('ola')\nprint(stopwords)", "['de', 'a', 'o', 'que', 'e', 'é', 'do', 'da', 'em', 'um', 'para', 'com', 'não', 'uma', 'os', 'no', 'se', 'na', 'por', 'mais', 'as', 'dos', 'como', 'mas', 'ao', 'ele', 'das', 'à', 'seu', 'sua', 'ou', 'quando', 'muito', 'nos', 'já', 'eu', 'também', 'só', 'pelo', 'pela', 'até', 'isso', 'ela', 'entre', 'depois', 'sem', 'mesmo', 'aos', 'seus', 'quem', 'nas', 'me', 'esse', 'eles', 'você', 'essa', 'num', 'nem', 'suas', 'meu', 'às', 'minha', 'numa', 'pelos', 'elas', 'qual', 'nós', 'lhe', 'deles', 'essas', 'esses', 'pelas', 'este', 'dele', 'tu', 'te', 'vocês', 'vos', 'lhes', 'meus', 'minhas', 'teu', 'tua', 'teus', 'tuas', 'nosso', 'nossa', 'nossos', 'nossas', 'dela', 'delas', 'esta', 'estes', 'estas', 'aquele', 'aquela', 'aqueles', 'aquelas', 'isto', 'aquilo', 'estou', 'está', 'estamos', 'estão', 'estive', 'esteve', 'estivemos', 'estiveram', 'estava', 'estávamos', 'estavam', 'estivera', 'estivéramos', 'esteja', 'estejamos', 'estejam', 'estivesse', 'estivéssemos', 'estivessem', 'estiver', 'estivermos', 'estiverem', 'hei', 'há', 'havemos', 'hão', 'houve', 'houvemos', 'houveram', 'houvera', 'houvéramos', 'haja', 'hajamos', 'hajam', 'houvesse', 'houvéssemos', 'houvessem', 'houver', 'houvermos', 'houverem', 'houverei', 'houverá', 'houveremos', 'houverão', 'houveria', 'houveríamos', 'houveriam', 'sou', 'somos', 'são', 'era', 'éramos', 'eram', 'fui', 'foi', 'fomos', 'foram', 'fora', 'fôramos', 'seja', 'sejamos', 'sejam', 'fosse', 'fôssemos', 'fossem', 'for', 'formos', 'forem', 'serei', 'será', 'seremos', 'serão', 'seria', 'seríamos', 'seriam', 'tenho', 'tem', 'temos', 'tém', 'tinha', 'tínhamos', 'tinham', 'tive', 'teve', 'tivemos', 'tiveram', 'tivera', 'tivéramos', 'tenha', 'tenhamos', 'tenham', 'tivesse', 'tivéssemos', 'tivessem', 'tiver', 'tivermos', 'tiverem', 'terei', 'terá', 'teremos', 'terão', 'teria', 'teríamos', 'teriam', 'ola']\n['de', 'a', 'o', 'que', 'e', 'é', 'do', 'da', 'em', 'um', 'para', 'com', 'não', 'uma', 'os', 'no', 'se', 'na', 'por', 'mais', 'as', 'dos', 'como', 'mas', 'ao', 'ele', 'das', 'à', 'seu', 'sua', 'ou', 'quando', 'muito', 'nos', 'já', 'eu', 'também', 'só', 'pelo', 'pela', 'até', 'isso', 'ela', 'entre', 'depois', 'sem', 'mesmo', 'aos', 'seus', 'quem', 'nas', 'me', 'esse', 'eles', 'você', 'essa', 'num', 'nem', 'suas', 'meu', 'às', 'minha', 'numa', 'pelos', 'elas', 'qual', 'nós', 'lhe', 'deles', 'essas', 'esses', 'pelas', 'este', 'dele', 'tu', 'te', 'vocês', 'vos', 'lhes', 'meus', 'minhas', 'teu', 'tua', 'teus', 'tuas', 'nosso', 'nossa', 'nossos', 'nossas', 'dela', 'delas', 'esta', 'estes', 'estas', 'aquele', 'aquela', 'aqueles', 'aquelas', 'isto', 'aquilo', 'estou', 'está', 'estamos', 'estão', 'estive', 'esteve', 'estivemos', 'estiveram', 'estava', 'estávamos', 'estavam', 'estivera', 'estivéramos', 'esteja', 'estejamos', 'estejam', 'estivesse', 'estivéssemos', 'estivessem', 'estiver', 'estivermos', 'estiverem', 'hei', 'há', 'havemos', 'hão', 'houve', 'houvemos', 'houveram', 'houvera', 'houvéramos', 'haja', 'hajamos', 'hajam', 'houvesse', 'houvéssemos', 'houvessem', 'houver', 'houvermos', 'houverem', 'houverei', 'houverá', 'houveremos', 'houverão', 'houveria', 'houveríamos', 'houveriam', 'sou', 'somos', 'são', 'era', 'éramos', 'eram', 'fui', 'foi', 'fomos', 'foram', 'fora', 'fôramos', 'seja', 'sejamos', 'sejam', 'fosse', 'fôssemos', 'fossem', 'for', 'formos', 'forem', 'serei', 'será', 'seremos', 'serão', 'seria', 'seríamos', 'seriam', 'tenho', 'tem', 'temos', 'tém', 'tinha', 'tínhamos', 'tinham', 'tive', 'teve', 'tivemos', 'tiveram', 'tivera', 'tivéramos', 'tenha', 'tenhamos', 'tenham', 'tivesse', 'tivéssemos', 'tivessem', 'tiver', 'tivermos', 'tiverem', 'terei', 'terá', 'teremos', 'terão', 'teria', 'teríamos', 'teriam']\n" ], [ "def remove_stopwords(texto):\n texto_formatado = converte_para_minusculas(texto)\n tokens = [] # Lista de tokens\n for token in nltk.word_tokenize(texto_formatado): # token é cada uma das palavras\n tokens.append(token) # Insere na lista de tokens\n \n # Pega apenas os tokens que não estão nas stopwords\n tokens = [cada_token for cada_token in tokens if cada_token not in stopwords and cada_token not in string.punctuation]\n\n texto_formatado = ' '.join([str(cada_token) for cada_token in tokens if not cada_token.isdigit()])\n\n return texto_formatado", "_____no_output_____" ], [ "texto_formatado = remove_stopwords(texto_original)", "_____no_output_____" ], [ "string.punctuation", "_____no_output_____" ], [ "frequencia_palavras = nltk.FreqDist(nltk.word_tokenize(texto_formatado))\nfrequencia_palavras", "_____no_output_____" ], [ "frequencia_palavras.keys()", "_____no_output_____" ], [ "frequencia_maxima = max(frequencia_palavras.values())\nfrequencia_maxima", "_____no_output_____" ], [ "for cada_palavra in frequencia_palavras.keys():\n frequencia_palavras[cada_palavra] = frequencia_palavras[cada_palavra]/frequencia_maxima", "_____no_output_____" ], [ "frequencia_palavras", "_____no_output_____" ], [ "sentencas = nltk.sent_tokenize(texto_original)\nsentencas", "_____no_output_____" ], [ "notas_das_sentencas = {}\nfor cada_sentenca in sentencas:\n # print(cada_sentenca)\n for cada_palavra in nltk.word_tokenize(cada_sentenca.lower()):\n # print(cada_palavra)\n if cada_palavra in frequencia_palavras.keys():\n if cada_sentenca not in notas_das_sentencas:\n notas_das_sentencas[cada_sentenca] = frequencia_palavras[cada_palavra]\n else:\n notas_das_sentencas[cada_sentenca] += frequencia_palavras[cada_palavra]", "_____no_output_____" ], [ "notas_das_sentencas", "_____no_output_____" ], [ "import heapq", "_____no_output_____" ], [ "melhores_sentencas = heapq.nlargest(3, notas_das_sentencas, key = notas_das_sentencas.get)\nmelhores_sentencas", "_____no_output_____" ], [ "resumo = ''.join(melhores_sentencas)\nresumo", "_____no_output_____" ], [ "from IPython.core.display import HTML", "_____no_output_____" ], [ "texto_final = ''\ndisplay(HTML(f'<h1> RESUMO GERADO AUTOMATICAMENTE </h1>'))\n\nfor cada_sentenca in sentencas:\n #texto_final = ''\n #texto_final += cada_sentenca\n if cada_sentenca in melhores_sentencas:\n texto_final += str(cada_sentenca).replace(cada_sentenca, f\"<mark>{cada_sentenca}</mark>\")\n else:\n texto_final += str(cada_sentenca)\n texto_final += ' '\n\ndisplay(HTML(f\"\"\"{texto_final}\"\"\"))", "_____no_output_____" ], [ "pip install goose3", "Requirement already satisfied: goose3 in c:\\python38\\lib\\site-packages (3.1.8)\nRequirement already satisfied: Pillow in c:\\python38\\lib\\site-packages (from goose3) (8.1.0)\nRequirement already satisfied: jieba in c:\\python38\\lib\\site-packages (from goose3) (0.42.1)\nRequirement already satisfied: beautifulsoup4 in c:\\python38\\lib\\site-packages (from goose3) (4.9.1)\nNote: you may need to restart the kernel to use updated packages.\nWARNING: You are using pip version 20.2.2; however, version 21.0.1 is available.\nYou should consider upgrading via the 'C:\\Python38\\python.exe -m pip install --upgrade pip' command.\nRequirement already satisfied: nltk in c:\\python38\\lib\\site-packages (from goose3) (3.5)\nRequirement already satisfied: requests in c:\\python38\\lib\\site-packages (from goose3) (2.24.0)\nRequirement already satisfied: lxml in c:\\python38\\lib\\site-packages (from goose3) (4.6.3)\nRequirement already satisfied: python-dateutil in c:\\users\\andre\\appdata\\roaming\\python\\python38\\site-packages (from goose3) (2.8.1)\nRequirement already satisfied: cssselect in c:\\python38\\lib\\site-packages (from goose3) (1.1.0)\nRequirement already satisfied: soupsieve>1.2 in c:\\python38\\lib\\site-packages (from beautifulsoup4->goose3) (2.0.1)\nRequirement already satisfied: click in c:\\python38\\lib\\site-packages (from nltk->goose3) (7.1.2)\nRequirement already satisfied: joblib in c:\\python38\\lib\\site-packages (from nltk->goose3) (1.0.1)\nRequirement already satisfied: regex in c:\\python38\\lib\\site-packages (from nltk->goose3) (2021.3.17)\nRequirement already satisfied: tqdm in c:\\python38\\lib\\site-packages (from nltk->goose3) (4.59.0)\nRequirement already satisfied: chardet<4,>=3.0.2 in c:\\python38\\lib\\site-packages (from requests->goose3) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in c:\\python38\\lib\\site-packages (from requests->goose3) (2020.6.20)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\python38\\lib\\site-packages (from requests->goose3) (1.25.10)\nRequirement already satisfied: idna<3,>=2.5 in c:\\python38\\lib\\site-packages (from requests->goose3) (2.10)\nRequirement already satisfied: six>=1.5 in c:\\users\\andre\\appdata\\roaming\\python\\python38\\site-packages (from python-dateutil->goose3) (1.15.0)\n" ] ], [ [ "# Tarefa 1", "_____no_output_____" ], [ "## 1. Stemizacao", "_____no_output_____" ] ], [ [ "from nltk.stem.snowball import SnowballStemmer\n\n# É importante definir a lingua\nstemizador = SnowballStemmer('portuguese')", "_____no_output_____" ], [ "palavras_stemizadas = []\nfor palavra in nltk.word_tokenize(texto_formatado):\n print(palavra, ' = ', stemizador.stem(palavra))\n palavras_stemizadas.append(stemizador.stem(palavra))", "algoritmos = algoritm\ninteligentes = inteligent\naprendizados = aprendiz\ncorrendo = corr\nsupervisionados = supervision\nutilizam = utiliz\ndados = dad\ncoletados = colet\npartir = part\ndados = dad\ncoletados = colet\nconjunto = conjunt\ncaracterística = característ\nextraído = extraíd\ncaracterísticas = característ\npodem = pod\nser = ser\nestruturais = estrutur\nestatísticas = estatíst\ncorrer = corr\ncorreste = corr\ncorrida = corr\ninteligente = inteligent\ncaracterística = característ\nestruturais = estrutur\nestabelecem = estabelec\nrelações = relaçõ\ndados = dad\ninteligência = inteligent\nenquanto = enquant\nestatísticas = estatíst\ncaracterísticas = característ\nquantitativas = quantit\npartir = part\ncorrido = corr\ncaracterísticas = característ\nmodelos = model\naprendizado = aprendiz\nmáquina = máquin\ncorremos = corr\nconstruídos = construíd\nreconhecimento = reconhec\natividades = ativ\nhumanas = human\n" ], [ "print(palavras_stemizadas)", "['algoritm', 'inteligent', 'aprendiz', 'corr', 'supervision', 'utiliz', 'dad', 'colet', 'part', 'dad', 'colet', 'conjunt', 'característ', 'extraíd', 'característ', 'pod', 'ser', 'estrutur', 'estatíst', 'corr', 'corr', 'corr', 'inteligent', 'característ', 'estrutur', 'estabelec', 'relaçõ', 'dad', 'inteligent', 'enquant', 'estatíst', 'característ', 'quantit', 'part', 'corr', 'característ', 'model', 'aprendiz', 'máquin', 'corr', 'construíd', 'reconhec', 'ativ', 'human']\n" ], [ "resultado = ' '.join([str(cada_token) for cada_token in palavras_stemizadas if not cada_token.isdigit()])\nprint(resultado)", "algoritm inteligent aprendiz corr supervision utiliz dad colet part dad colet conjunt característ extraíd característ pod ser estrutur estatíst corr corr corr inteligent característ estrutur estabelec relaçõ dad inteligent enquant estatíst característ quantit part corr característ model aprendiz máquin corr construíd reconhec ativ human\n" ], [ "frequencia_palavras = nltk.FreqDist(nltk.word_tokenize(resultado))\nfrequencia_palavras", "_____no_output_____" ], [ "frequencia_maxima = max(frequencia_palavras.values())\nfrequencia_maxima", "_____no_output_____" ], [ "for cada_palavra in frequencia_palavras.keys():\n frequencia_palavras[cada_palavra] = frequencia_palavras[cada_palavra]/frequencia_maxima", "_____no_output_____" ], [ "frequencia_palavras", "_____no_output_____" ], [ "notas_das_sentencas = {}\nfor cada_sentenca in sentencas:\n # print(cada_sentenca)\n for cada_palavra in nltk.word_tokenize(cada_sentenca.lower()):\n # print(cada_palavra)\n aux = stemizador.stem(cada_palavra)\n if aux in frequencia_palavras.keys():\n if cada_sentenca not in notas_das_sentencas:\n notas_das_sentencas[cada_sentenca] = frequencia_palavras[aux]\n else:\n notas_das_sentencas[cada_sentenca] += frequencia_palavras[aux]", "_____no_output_____" ], [ "notas_das_sentencas", "_____no_output_____" ], [ "melhores_sentencas = heapq.nlargest(3, notas_das_sentencas, key = notas_das_sentencas.get)\nmelhores_sentencas", "_____no_output_____" ], [ "resumo = ''.join(melhores_sentencas)\nresumo", "_____no_output_____" ], [ "texto_final = ''\ndisplay(HTML(f'<h1> RESUMO GERADO AUTOMATICAMENTE (Stemizadas)</h1>'))\n\nfor cada_sentenca in sentencas:\n #texto_final = ''\n #texto_final += cada_sentenca\n if cada_sentenca in melhores_sentencas:\n texto_final += str(cada_sentenca).replace(cada_sentenca, f\"<mark>{cada_sentenca}</mark>\")\n else:\n texto_final += str(cada_sentenca)\n texto_final += ' '\n\ndisplay(HTML(f\"\"\"{texto_final}\"\"\"))", "_____no_output_____" ] ], [ [ "## 2. Lematizacao", "_____no_output_____" ] ], [ [ "import spacy", "_____no_output_____" ], [ "!python -m spacy download pt_core_news_sm", "Requirement already satisfied: pt-core-news-sm==3.0.0 from https://github.com/explosion/spacy-models/releases/download/pt_core_news_sm-3.0.0/pt_core_news_sm-3.0.0-py3-none-any.whl#egg=pt_core_news_sm==3.0.0 in c:\\python38\\lib\\site-packages (3.0.0)\nRequirement already satisfied: spacy<3.1.0,>=3.0.0 in c:\\python38\\lib\\site-packages (from pt-core-news-sm==3.0.0) (3.0.5)\nRequirement already satisfied: wasabi<1.1.0,>=0.8.1 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (0.8.2)\nRequirement already satisfied: requests<3.0.0,>=2.13.0 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.24.0)\nRequirement already satisfied: pydantic<1.8.0,>=1.7.1 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (1.7.3)\nRequirement already satisfied: preshed<3.1.0,>=3.0.2 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (3.0.5)\nRequirement already satisfied: typer<0.4.0,>=0.3.0 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (0.3.2)\nRequirement already satisfied: jinja2 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.11.3)\nRequirement already satisfied: setuptools in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (47.1.0)\nRequirement already satisfied: thinc<8.1.0,>=8.0.2 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (8.0.2)\nRequirement already satisfied: packaging>=20.0 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (20.9)\nRequirement already satisfied: catalogue<2.1.0,>=2.0.1 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.0.1)\nRequirement already satisfied: srsly<3.0.0,>=2.4.0 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.4.0)\nRequirement already satisfied: cymem<2.1.0,>=2.0.2 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.0.5)\nRequirement already satisfied: pathy>=0.3.5 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (0.4.0)\nRequirement already satisfied: spacy-legacy<3.1.0,>=3.0.0 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (3.0.1)\nRequirement already satisfied: blis<0.8.0,>=0.4.0 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (0.7.4)\nRequirement already satisfied: tqdm<5.0.0,>=4.38.0 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (4.59.0)\nRequirement already satisfied: murmurhash<1.1.0,>=0.28.0 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (1.0.5)\nRequirement already satisfied: numpy>=1.15.0 in c:\\python38\\lib\\site-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (1.20.1)\nRequirement already satisfied: idna<3,>=2.5 in c:\\python38\\lib\\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.10)\nRequirement already satisfied: chardet<4,>=3.0.2 in c:\\python38\\lib\\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (3.0.4)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\python38\\lib\\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (1.25.10)\nRequirement already satisfied: certifi>=2017.4.17 in c:\\python38\\lib\\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2020.6.20)\nRequirement already satisfied: click<7.2.0,>=7.1.1 in c:\\python38\\lib\\site-packages (from typer<0.4.0,>=0.3.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (7.1.2)\nRequirement already satisfied: MarkupSafe>=0.23 in c:\\python38\\lib\\site-packages (from jinja2->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (1.1.1)\nRequirement already satisfied: pyparsing>=2.0.2 in c:\\python38\\lib\\site-packages (from packaging>=20.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.4.7)\nRequirement already satisfied: smart-open<4.0.0,>=2.2.0 in c:\\python38\\lib\\site-packages (from pathy>=0.3.5->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (3.0.0)\n✔ Download and installation successful\nYou can now load the package via spacy.load('pt_core_news_sm')\nWARNING: You are using pip version 20.2.2; however, version 21.0.1 is available.\nYou should consider upgrading via the 'C:\\Python38\\python.exe -m pip install --upgrade pip' command.\n" ], [ "pln = spacy.load('pt_core_news_sm')\npln", "_____no_output_____" ], [ "palavras = pln(texto_formatado)", "_____no_output_____" ], [ "# Spacy já separa as palavras em tokens\npalavras_lematizadas = []\nfor palavra in palavras:\n #print(palavra.text, ' = ', palavra.lemma_)\n palavras_lematizadas.append(palavra.lemma_)\n\nprint(palavras_lematizadas)", "['algoritmo', 'inteligente', 'aprendizado', 'correr', 'supervisionar', 'utilizar', 'dar', 'coletados', 'partir', 'dar', 'coletados', 'conjuntar', 'característico', 'extrair', 'característico', 'poder', 'ser', 'estruturar', 'estatístico', 'correr', 'correr', 'corrido', 'inteligente', 'característico', 'estruturar', 'estabelecer', 'relação', 'dar', 'inteligência', 'enquanto', 'estatístico', 'característico', 'quantitativo', 'partir', 'correr', 'característico', 'modelo', 'aprendizado', 'máquina', 'correr', 'construir', 'reconhecimento', 'atividades', 'humano']\n" ], [ "resultado = ' '.join([str(cada_token) for cada_token in palavras_lematizadas if not cada_token.isdigit()])\nprint(resultado)", "algoritmo inteligente aprendizado correr supervisionar utilizar dar coletados partir dar coletados conjuntar característico extrair característico poder ser estruturar estatístico correr correr corrido inteligente característico estruturar estabelecer relação dar inteligência enquanto estatístico característico quantitativo partir correr característico modelo aprendizado máquina correr construir reconhecimento atividades humano\n" ], [ "frequencia_palavras = nltk.FreqDist(nltk.word_tokenize(resultado))\nfrequencia_palavras", "_____no_output_____" ], [ "frequencia_maxima = max(frequencia_palavras.values())\nfrequencia_maxima", "_____no_output_____" ], [ "for cada_palavra in frequencia_palavras.keys():\n frequencia_palavras[cada_palavra] = frequencia_palavras[cada_palavra]/frequencia_maxima\n\nfrequencia_palavras", "_____no_output_____" ], [ "notas_das_sentencas = {}\nfor cada_sentenca in sentencas:\n # print(cada_sentenca)\n \n for cada_palavra in pln(cada_sentenca):\n # print(cada_palavra)\n aux = cada_palavra.lemma_\n if aux in frequencia_palavras.keys():\n if cada_sentenca not in notas_das_sentencas:\n notas_das_sentencas[cada_sentenca] = frequencia_palavras[aux]\n else:\n notas_das_sentencas[cada_sentenca] += frequencia_palavras[aux]", "_____no_output_____" ], [ "notas_das_sentencas", "_____no_output_____" ], [ "melhores_sentencas = heapq.nlargest(3, notas_das_sentencas, key = notas_das_sentencas.get)\nmelhores_sentencas", "_____no_output_____" ], [ "resumo = ''.join(melhores_sentencas)\nresumo", "_____no_output_____" ], [ "texto_final = ''\ndisplay(HTML(f'<h1> RESUMO GERADO AUTOMATICAMENTE (Lematizacao)</h1>'))\n\nfor cada_sentenca in sentencas:\n #texto_final = ''\n #texto_final += cada_sentenca\n if cada_sentenca in melhores_sentencas:\n texto_final += str(cada_sentenca).replace(cada_sentenca, f\"<mark>{cada_sentenca}</mark>\")\n else:\n texto_final += str(cada_sentenca)\n texto_final += ' '\n\ndisplay(HTML(f\"\"\"{texto_final}\"\"\"))", "_____no_output_____" ] ], [ [ "# Fim da Tarefa 1", "_____no_output_____" ], [ "## Uso da lib Goose3", "_____no_output_____" ] ], [ [ "from goose3 import Goose", "_____no_output_____" ], [ "g = Goose()\nurl = 'https://www.techtudo.com.br/noticias/2017/08/o-que-e-replika-app-usa-inteligencia-artificial-para-criar-um-clone-seu.ghtml'\nmateria = g.extract(url)", "_____no_output_____" ], [ "materia.title", "_____no_output_____" ], [ "materia.tags", "_____no_output_____" ], [ "materia.infos", "_____no_output_____" ], [ "materia.cleaned_text", "_____no_output_____" ] ], [ [ "# Tarefa 2", "_____no_output_____" ] ], [ [ "frequencia_palavras.keys()", "_____no_output_____" ], [ "frequencia_palavras", "_____no_output_____" ], [ "frase = \"\"\"Algoritmos de aprendizados supervisionados utilizam dados coletados\"\"\".split(' ')\nfrequencia_palavras_frase = []\n\nfor palavra in frase:\n for freq_palavra in frequencia_palavras:\n if palavra in freq_palavra:\n frequencia_palavras_frase.append([palavra, 1])\n\nfrequencia_palavras_frase", "_____no_output_____" ], [ "for x in frequencia_palavras:\n print(x)", "correr\ncaracterístico\ndar\ninteligente\naprendizado\ncoletados\npartir\nestruturar\nestatístico\nalgoritmo\nsupervisionar\nutilizar\nconjuntar\nextrair\npoder\nser\ncorrido\nestabelecer\nrelação\ninteligência\nenquanto\nquantitativo\nmodelo\nmáquina\nconstruir\nreconhecimento\natividades\nhumano\n" ] ] ]
[ "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", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d00ff5a738951f827533adbeb294ae77d3d736a1
8,871
ipynb
Jupyter Notebook
styling/bullet_graph.ipynb
TillMeineke/machine_learning
689ca5e9e4450266786fab73299e1f8bdad7a473
[ "MIT" ]
null
null
null
styling/bullet_graph.ipynb
TillMeineke/machine_learning
689ca5e9e4450266786fab73299e1f8bdad7a473
[ "MIT" ]
null
null
null
styling/bullet_graph.ipynb
TillMeineke/machine_learning
689ca5e9e4450266786fab73299e1f8bdad7a473
[ "MIT" ]
null
null
null
45.260204
3,054
0.760455
[ [ [ "# https://pbpython.com/bullet-graph.html", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib.ticker import FuncFormatter\n\n%matplotlib inline", "_____no_output_____" ], [ "# display a palette of 5 shades of green\nsns.palplot(sns.light_palette(\"green\", 5))", "_____no_output_____" ], [ "# 8 different shades of purple in reverse order\nsns.palplot(sns.light_palette(\"purple\", 8, reverse=True))", "_____no_output_____" ], [ "# define the values we want to plot\nlimits = [80, 100, 150] # 3 ranges: 0-80, 81-100, 101-150\ndata_to_plot = (\"Example 1\", 105, 120) #“Example” line with a value of 105 and target line of 120", "_____no_output_____" ], [ "# blues color palette\npalette = sns.color_palette(\"Blues_r\", len(limits))", "_____no_output_____" ], [ "# build the stacked bar chart of the ranges\nfig, ax = plt.subplots()\nax.set_aspect('equal')\nax.set_yticks([1])\nax.set_yticklabels([data_to_plot[0]])\nax.axvline(data_to_plot[2], color=\"gray\", ymin=0.10, ymax=0.9)\n\nprev_limit = 0\nfor idx, lim in enumerate(limits):\n ax.barh([1], lim-prev_limit, left=prev_limit, height=15, color=palette[idx])\n prev_limit = lim", "_____no_output_____" ], [ "# Draw the value we're measuring\nax.barh([1], data_to_plot[1], color='black', height=5)", "_____no_output_____" ], [ "ax.axvline(data_to_plot[2], color=\"gray\", ymin=0.10, ymax=0.9)\n", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0100213ac847dcdff3580a4302d6be248dfd4ae
344,831
ipynb
Jupyter Notebook
docs/team-projects/Summer-2021/B2-Team2-Analyzing-Air-Quality-During-COVID19-Pandemic.ipynb
JQmiracle/Business-Analytics-Toolbox
b37995e0621d2ff66de32ccaef84762a5c018c68
[ "MIT" ]
35
2019-07-30T02:48:07.000Z
2021-08-10T14:34:22.000Z
docs/team-projects/Summer-2021/B2-Team2-Analyzing-Air-Quality-During-COVID19-Pandemic.ipynb
JQmiracle/Business-Analytics-Toolbox
b37995e0621d2ff66de32ccaef84762a5c018c68
[ "MIT" ]
1
2020-02-14T18:16:27.000Z
2020-02-14T18:16:27.000Z
docs/team-projects/Summer-2021/B2-Team2-Analyzing-Air-Quality-During-COVID19-Pandemic.ipynb
JQmiracle/Business-Analytics-Toolbox
b37995e0621d2ff66de32ccaef84762a5c018c68
[ "MIT" ]
77
2019-07-30T15:42:04.000Z
2021-11-06T09:01:04.000Z
70.691062
182,146
0.696045
[ [ [ "# Was Air Quality Affected in Countries or Regions Where COVID-19 was Most Prevalent?\n**By: Arpit Jain, Maria Stella Vardanega, Tingting Cao, Christopher Chang, Mona Ma, Fusu Luo**", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "## Outline \n\n#### I. Problem Definition & Data Source Description \n\n 1. Project Objectives \n 2. Data Source\n 3. Dataset Preview\n\n#### II. What are the most prevalent pollutants? \n\n#### III. What were the pollutant levels in 2019 and 2020 globally, and their averages?\n\n 1. Selecting Data from 2019 and 2020 with air pollutant information\n 2. Monthly Air Pollutant Data from 2019 \n 3. Monthly Air Pollutant Data from 2020 \n\n#### IV: What cities had the highest changes in pollutant air quality index during COVID-19?\n\n 1. 10 cities with most air quality index reduction for each pollutant \n 2. Cities with more than 50 percent AQI decrease and 50 AQI decrease for each air pollutants\n\n#### V: Regression analysis on COVID-19 cases and pollutant Air Quality Index Globally\n\n#### VI: When were lockdowns implemented for each country?\n\n#### VII: How did Air Quality change in countries with low COVID-19 cases (NZ, AUS, TW) and high COVID-19 cases (US, IT,CN)?\n 1. Countries with high COVID cases\n 2. Countries with low COVID cases\n\n#### VIII: Conclusion\n\n#### IX: Public Tableau Dashboards", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "## I. Problem Definition & Data Source Description", "_____no_output_____" ], [ "#### 1. Project Objectives", "_____no_output_____" ], [ "Air pollution, as one of the most serious environmental problems confronting our civilization, is the presence of toxic gases and particles in the air at levels that pose adverse effects on global climate and lead to public health risk and disease. Exposure to elevated levels of air pollutants has been implicated in a diverse set of medical conditions including cardiovascular and respiratory mortality, lung cancer and autism. \n\nAir pollutants come from natural sources such as wildfires and volcanoes, as well as are highly related to human activities from mobile sources (such as cars, buses and planes) or stationary sources (such as industrial factories, power plants and wood burning fireplaces). However, in the past year, the COVID-19 pandemic has caused unprecedented changes to the our work, study and daily activities, subsequently led to major reductions in air pollutant emissions. And our team would like take this opportunity to examine the air quality in the past two years and look on how the air quality was impacted in countries and cities where the corona-virus was prevalent.", "_____no_output_____" ], [ "#### 2. Data Source", "_____no_output_____" ], [ "**Data Source Description:** In this project, we downloaded worldwide air quality data for Year 2019 and 2020 from the Air Quality Open Data Platform (https://aqicn.org/data-platform/covid19/), which provides historical air quality index and meteorological data for more than 380 major cities across the world. We used air quality index data in 2019 as baseline to find the air quality changes during COVID in 2020. In addition we joined the data with geographic location information from https://aqicn.org/data-platform/covid19/airquality-covid19-cities.json to get air quality index for each pollutant at city-level. According to the data source provider, the data for each major cities is based on the average (median) of several stations. The data set provides min, max, median and standard deviation for each of the air pollutant species in the form of Air Quality Index (AQI) that are converted from raw concentration based on the US Environmental Protection Agency (EPA) standard.", "_____no_output_____" ], [ "The United States EPA list the following as the criteria at this website (https://www.epa.gov/criteria-air-pollutants/naaqs-table): Carbon Monoxide (CO), Nitrogen Dioxide (NO2), Ozone (O3), Particle Pollution (PM2.5) + (PM10), and finally Sulfur Dioxide (SO2). For the particle pollution the numbers stand for the size of the particles. PM2.5 means particles that are 2.5 micrometers and smaller, while PM10 means particles that are 10 micrometers and smaller. https://www.epa.gov/pm-pollution/particulate-matter-pm-basics. Particle Pollution typically includes Dust, Dirt, and Smoke. Our dataset covers most of the criteria pollutants (PM2.5, PM10, Ozone, SO2, NO2 and CO), and meteorological parameters such as temperature, wind speed, dew point, relative humidity. Air quality index basics are shown in the figure below. ", "_____no_output_____" ], [ "<img src=\"https://github.com/ttcao63/775team_project_b2_t2/blob/main/AQI%20basics.PNG?raw=true\" align=\"center\"/>", "_____no_output_____" ], [ "(source: https://www.airnow.gov/aqi/aqi-basics/)", "_____no_output_____" ], [ "#### 3. Preview of the Dataset", "_____no_output_____" ] ], [ [ "%%bigquery\nSELECT * FROM `ba775-team2-b2.AQICN.air_quality_data` LIMIT 10", "Query complete after 0.00s: 100%|██████████| 1/1 [00:00<00:00, 485.85query/s] \nDownloading: 100%|██████████| 10/10 [00:01<00:00, 6.05rows/s]\n" ] ], [ [ "---\n### II. What are the most prevalent pollutants?\n\nThis question focuses on the prevalence of the pollutants. From the dataset, the prevalence can be defined geographically from the cities and countries that had recorded the parameters detected times. \n\nTo find the prevalence, our team selected the parameters from situations in how many distinct cities and countries detected the parameter appeared. ", "_____no_output_____" ] ], [ [ "%%bigquery\nSELECT \nParameter,COUNT(distinct(City)) AS number_of_city,\nCOUNT(distinct(Country)) AS number_of_country,string_agg(distinct(Country)) AS list_country\nFROM `ba775-team2-b2.AQICN.air_quality_data`\nGROUP BY Parameter\nORDER BY number_of_city DESC", "Query complete after 0.00s: 100%|██████████| 1/1 [00:00<00:00, 918.39query/s] \nDownloading: 100%|██████████| 20/20 [00:01<00:00, 13.28rows/s]\n" ] ], [ [ "From the result, top 6 parameters are meteorological parameters. And the first air pollutants (which can be harmful to the public health and environment) is PM2.5, followed by NO2 and PM10.\n\nPM2.5 has been detected in 548 cities and 92 countries. \nNO2 has been detected in 528 cities and 64 countries. \nPM10 has been detected in 527 cities and 71 countries.\n\nWe conclude PM2.5, NO2 and PM10 are the most prevalent criteria pollutants from the dataset. All of them are considered criteria pollutants set by EPA.", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "### III. What were the pollutant levels in 2019 and 2020 globally, and their averages? \n\nThe purpose of this question is to determine the air pollutant levels in 2019 and 2020. The air pollutant levels in 2019 serve as a baseline for the air pollutant levels in 2020. In the previous question we observe the distinct parameters that are within the Air Quality Database. Since the meteorological parameters are not needed for the project, we can exclude them, and only focus on the air pollutants. \n\nThe first step is create a table where the parameters are only air pollutants and from the years 2019 and 2020. The next step was to select all the rows from each year, that had a certain parameter, and to union them all. This process was done for all six parameters for both years. ", "_____no_output_____" ], [ "#### 1. Selecting Data from 2019 and 2020 with air pollutant information ", "_____no_output_____" ] ], [ [ "%%bigquery\nSELECT Date, Country, City, lat as Latitude, lon as Longitude, pop as Population, Parameter as Pollutant, median as Pollutant_level\nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE (extract(year from date) = 2019 OR extract(year from date) = 2020) AND parameter IN ('co', 'o3','no2','so2','pm10',\n'pm25')\nORDER BY Country, Date;", "Query complete after 0.00s: 100%|██████████| 2/2 [00:00<00:00, 1175.70query/s] \nDownloading: 100%|██████████| 1968194/1968194 [00:02<00:00, 804214.66rows/s] \n" ] ], [ [ "As we can see after filtering the tables for only the air pollutants we have 1.9 million rows. From here we split the data into 2019 data and 2020 data. ", "_____no_output_____" ], [ "#### 2. Monthly Air Pollutant Data from 2019 ", "_____no_output_____" ] ], [ [ "%%bigquery\nSELECT extract(month from date) Month, Parameter as Pollutant,Round(avg(median),2) as Avg_Pollutant_Level_2019\nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2019 AND parameter IN ('co')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2)\nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2019 AND parameter IN ('o3')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2) \nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2019 AND parameter IN ('no2')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2) \nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2019 AND parameter IN ('so2')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2) \nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2019 AND parameter IN ('pm10')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2) \nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2019 AND parameter IN ('pm25')\nGROUP BY Month, Parameter\n\n\nORDER BY Month; ", "Query complete after 0.00s: 100%|██████████| 8/8 [00:00<00:00, 4930.85query/s] \nDownloading: 100%|██████████| 72/72 [00:01<00:00, 64.20rows/s] \n" ] ], [ [ "This query represents the average pollutant level for each air pollutant globally for each month. We do this again for the 2020 data. ", "_____no_output_____" ], [ "#### 3. Monthly Air Pollutant Data from 2020 ", "_____no_output_____" ] ], [ [ "%%bigquery\nSELECT extract(month from date) Month, Parameter as Pollutant,Round(avg(median),2) as Avg_Pollutant_Level_2020\nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2020 AND parameter IN ('co')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2)\nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2020 AND parameter IN ('o3')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2) \nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2020 AND parameter IN ('no2')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2) \nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2020 AND parameter IN ('so2')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2) \nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2020 AND parameter IN ('pm10')\nGROUP BY Month, Parameter\n\nUNION ALL \n\nSELECT extract(month from date) Month, Parameter ,Round(avg(median),2) \nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE extract(year from date) = 2020 AND parameter IN ('pm25')\nGROUP BY Month, Parameter\n\n\nORDER BY Month; ", "Query complete after 0.00s: 100%|██████████| 8/8 [00:00<00:00, 4959.27query/s] \nDownloading: 100%|██████████| 72/72 [00:01<00:00, 51.38rows/s]\n" ] ], [ [ "When comparing the data there isn't a noticeable difference in global pollutant levels from 2019 to 2020, which leads to the hypothesis of pollutant levels being regional rather than global. This might also mean that whatever effects might be occurring from COVID-19 cases, and lockdowns are short-term enough that the average monthly air pollutant is not capturing small intricacies in the data. We can further narrow down the data by analyzing data from when lockdowns were occurring in different countries, regions, and even cities. ", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "### IV: What cities had the highest changes in pollutant air quality index during COVID-19? ", "_____no_output_____" ], [ "In this question, we are trying to find cities with most air quality improvement during COVID, and cities with longest time of certain level AQI reduction.", "_____no_output_____" ], [ "#### 1. 10 cities with most air quality index reduction for each pollutant\nMaking queries and creating tables to find monthly average air quality index (AQI) for all pollutants at city level", "_____no_output_____" ], [ "We are using data in 2019 as a baseline and computing AQI differences and percent differences. Negative difference values indicates air quality index decrease, corresponding to an air quality improvement, and positive difference values indicate air quality index increases, corresponding to an air quality deterioration.", "_____no_output_____" ] ], [ [ "%%bigquery \nCREATE OR REPLACE TABLE AQICN.pollutant_diff_daily_aqi_less_than_500\nAS\n(\nSELECT A.Date AS Date_2020,B.Date AS Date_2019,A.Country,A.City,A.lat,A.lon,A.Parameter,A.pop,A.median AS aqi_2020,B.median AS aqi_2019,(A.median-B.median) AS aqi_diff, ROUND((A.median-B.median)/B.median*100,2) AS aqi_percent_diff\nFROM\n(SELECT * FROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE Parameter in ('pm25','pm10','o3','no2','co','so2') AND EXTRACT(Year FROM Date) = 2020 AND median > 0 AND median < 500) AS A\nINNER JOIN\n(SELECT * FROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE Parameter in ('pm25','pm10','o3','no2','co','so2') AND EXTRACT(Year FROM Date) = 2019 AND median > 0 AND median < 500) AS B\nON A.City = B.City\nWHERE EXTRACT(MONTH FROM A.Date) = EXTRACT(MONTH FROM B.Date) AND EXTRACT(DAY FROM A.Date) = EXTRACT(DAY FROM B.Date) AND A.Parameter = B.Parameter\nORDER BY City,Date_2020\n)", "Query complete after 0.00s: 100%|██████████| 4/4 [00:00<00:00, 2424.10query/s] \n" ], [ "%%bigquery \nCREATE OR REPLACE TABLE AQICN.pollutant_diff_monthly_aqi\nAS\nSELECT EXTRACT(month FROM Date_2020) AS month_2020,EXTRACT(month FROM Date_2019) AS month_2019,\n Country,City,lat,lon,Parameter,ROUND(AVG(aqi_2020),1) AS monthly_avg_aqi_2020,\n ROUND(AVG(aqi_2019),1) AS monthly_avg_aqi_2019,(ROUND(AVG(aqi_2020),1)-ROUND(AVG(aqi_2019),1)) AS aqi_diff_monthly,\n ROUND((AVG(aqi_2020)-AVG(aqi_2019))/AVG(aqi_2019)*100,2) AS aqi_percent_diff_monthly\nFROM AQICN.pollutant_diff_daily_aqi_less_than_500\nGROUP BY month_2020,month_2019,Country,City,lat,lon,Parameter\n", "Query complete after 0.00s: 100%|██████████| 4/4 [00:00<00:00, 1818.67query/s] \n" ], [ "%%bigquery\nSELECT *\nFROM AQICN.pollutant_diff_monthly_aqi\nORDER BY Parameter,month_2020,Country\nLIMIT 10", "Query complete after 0.00s: 100%|██████████| 1/1 [00:00<00:00, 368.89query/s] \nDownloading: 100%|██████████| 10/10 [00:01<00:00, 6.39rows/s]\n" ] ], [ [ "Order by monthly average AQI difference to find cities having top 10 air quality index reduction for each pollutant", "_____no_output_____" ] ], [ [ "%%bigquery \n\nCREATE OR REPLACE TABLE AQICN.top_10_cites_most_pollutant_percent_diff_monthly\nAS\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'co'\nORDER BY aqi_percent_diff_monthly\nLIMIT 10)\nUNION ALL\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'o3'\nORDER BY aqi_percent_diff_monthly\nLIMIT 10)\nUNION ALL\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'no2'\nORDER BY aqi_percent_diff_monthly\nLIMIT 10)\nUNION ALL\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'pm25'\nORDER BY aqi_percent_diff_monthly\nLIMIT 10)\nUNION ALL\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'pm10'\nORDER BY aqi_percent_diff_monthly\nLIMIT 10)", "Query complete after 0.00s: 100%|██████████| 3/3 [00:00<00:00, 1727.47query/s] \n" ], [ "%%bigquery \nSELECT *\nFROM AQICN.top_10_cites_most_pollutant_percent_diff_monthly\nORDER BY Parameter,aqi_percent_diff_monthly\nLIMIT 10", "Query complete after 0.00s: 100%|██████████| 1/1 [00:00<00:00, 494.55query/s] \nDownloading: 100%|██████████| 10/10 [00:01<00:00, 5.25rows/s]\n" ] ], [ [ "Order by monthly average percent AQI difference to find cities having top 10 most air quality index reduction for each pollutant", "_____no_output_____" ] ], [ [ "%%bigquery \n\nCREATE OR REPLACE TABLE AQICN.top_10_cites_most_pollutant_diff_monthly\nAS\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'pm25'\nORDER BY aqi_diff_monthly\nLIMIT 10)\nUNION ALL\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'o3'\nORDER BY aqi_diff_monthly\nLIMIT 10)\nUNION ALL\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'pm10'\nORDER BY aqi_diff_monthly\nLIMIT 10)\nUNION ALL\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'no2'\nORDER BY aqi_diff_monthly\nLIMIT 10)\nUNION ALL\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'so2'\nORDER BY aqi_diff_monthly\nLIMIT 10)\nUNION ALL\n(SELECT * \nFROM AQICN.pollutant_diff_monthly_aqi\nWHERE Parameter = 'co'\nORDER BY aqi_diff_monthly\nLIMIT 10)", "Query complete after 0.00s: 100%|██████████| 3/3 [00:00<00:00, 1556.52query/s] \n" ], [ "%%bigquery \nSELECT *\nFROM AQICN.top_10_cites_most_pollutant_diff_monthly\nORDER BY Parameter,aqi_diff_monthly\nLIMIT 10", "Query complete after 0.00s: 100%|██████████| 1/1 [00:00<00:00, 446.25query/s] \nDownloading: 100%|██████████| 10/10 [00:01<00:00, 6.48rows/s]\n" ] ], [ [ "#### 2. Cities with more than 50 percent AQI decrease and 50 AQI decrease for each air pollutants", "_____no_output_____" ], [ "Reason: the higher the AQI, the unhealthier the air will be, especially for sensitive groups such as people with heart and lung disease, elders and children. A major reduction or percent reduction in AQI for long period of time implies a high air quality impact from the COIVD pandemic.", "_____no_output_____" ] ], [ [ "%%bigquery\n\nSELECT City,Country,Parameter,COUNT(*) AS num_month_mt_50_per_decrease FROM AQICN.pollutant_diff_monthly_aqi\nWHERE aqi_percent_diff_monthly < -50 AND aqi_diff_monthly < -50\nGROUP BY City,Country,Parameter\nORDER BY Parameter,COUNT(*) DESC\nLIMIT 10", "Query complete after 0.00s: 100%|██████████| 1/1 [00:00<00:00, 881.71query/s] \nDownloading: 100%|██████████| 10/10 [00:01<00:00, 6.79rows/s]\n" ] ], [ [ "---", "_____no_output_____" ], [ "Results\n\nDuring the pandemic, cities getting most air qualities improvements in terms of percent AQI differences for each pollutant are:\n\nCO: United States Portland, Chile Talca and Mexico Aguascalientes;\nNO2: Iran Qom, South Africa Middelburg and Philippines Butuan;\nSO2: Greece Athens, Mexico Mérida and Mexico San Luis Potosí;\nOzone: Mexico Aguascalientes, United States Queens and United States The Bronx;\nPM 10: India Gandhinagar, China Hohhot and Israel Tel Aviv;\nPM 2.5: Mexico Mérida, Tajikistan Dushanbe, Bosnia and Herzegovina Sarajevo, Turkey Erzurum, China Qiqihar and India Gandhinagar;\n\n\nCities getting at least 50% and 50 AQI reduction with longest time:\n\nCO: United States Portland, 3 out of 12 months;\nNO2: Iran Qom, 5 out of 12 months;\nO3: Mexico Aguascalientes, 5 out of 12 months;\nPM25: several cities including Iran Kermanshah, Singapore Singapore, AU Sydney and Canberra, 1 out of 12 months;\nPM10: India Gandhinagar and Bhopal, 2 out of 12 months;\nSO2: Mexico Mérida 5 out of 12 months.\n", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "### V: Regression analysis on COVID-19 cases and pollutant Air Quality Index Globally", "_____no_output_____" ], [ "The purpose of this part is to find the differences in AQI between 2019 and 2020, also the percentage changes for four parameters which include (NO,NO2,PM2.5 and O3), then join with the COVID confirmed table to find the regression between the AQI and the new confirmed case for each air pollutant.", "_____no_output_____" ] ], [ [ "%%bigquery\nselect A.month,A.month_n, A.country,A.parameter,round((B.avg_median_month- A.avg_median_month),2) as diff_avg,\n(B.avg_median_month - A.avg_median_month)/A.avg_median_month as diff_perc\nfrom \n(SELECT FORMAT_DATETIME(\"%B\", date) month,EXTRACT(year FROM date) year, EXTRACT(month FROM date) month_n, country,parameter,round(avg(median),2) as avg_median_month \nFROM `AQICN.Arpit_Cleaned_Data2`\nWHERE Parameter IN ('co','no2','o3','pm25') AND EXTRACT(year FROM date) = 2019\nGROUP by 1,2,3,4,5\nORDER BY country, parameter) A\nleft join \n(SELECT FORMAT_DATETIME(\"%B\", date) month,EXTRACT(year FROM date) year, EXTRACT(month FROM date) month_n, country,parameter,round(avg(median),2) as avg_median_month \nFROM `AQICN.Arpit_Cleaned_Data2`\nWHERE Parameter IN ('co','no2','o3','pm25') AND EXTRACT(year FROM date) = 2020\nGROUP by 1,2,3,4,5\nORDER BY country, parameter) B\nusing (month,country,parameter,month_n)\nwhere A.avg_median_month >0", "Query complete after 0.00s: 100%|██████████| 5/5 [00:00<00:00, 2448.51query/s] \nDownloading: 100%|██████████| 2906/2906 [00:01<00:00, 1788.29rows/s]\n" ], [ "%%bigquery\nselect A.*,confirmed,B.country as country_name\nfrom `all_para_20_19.all_para_20_19_diff` as A\ninner join `covid_population.covid _pop` as B\non A.country = B.country_code2 and A.month = B.month and A.month_n = B.month_n\nwhere B.year = 2020\norder by A.country,A.month_n", "Query complete after 0.00s: 100%|██████████| 3/3 [00:00<00:00, 1451.15query/s] \nDownloading: 100%|██████████| 2789/2789 [00:01<00:00, 1960.44rows/s]\n" ] ], [ [ "Using Bigquery ML to find liner regression between diff_avg for each parameter and confirmed cases\n\n(Example showing below is that parameter = co; x = confirmed; y=diff_avg --AQI changes)", "_____no_output_____" ] ], [ [ "%%bigquery\nCREATE OR REPLACE MODEL `all_para_20_19.all_para_20_19_diff_covid_model`\n# Specify options\nOPTIONS\n (model_type='linear_reg',\n input_label_cols=['diff_avg']) AS\n# Provide training data\nSELECT\nconfirmed,\ndiff_avg\nFROM\n `all_para_20_19.all_para_20_19_diff_covid`\nWHERE\n parameter = 'co'\nand diff_avg is not null\n", "_____no_output_____" ] ], [ [ "Evaluating the model to find out r2_score for each monthly average air pollutant AQI changes vs monthly confirmed new cases linear regression model.\nExample showing below is Evaluation for country level monthly average CO AQI vs monthly new confirmed COVID cases model: ", "_____no_output_____" ] ], [ [ "%%bigquery\nSELECT * FROM\nML.EVALUATE(\n MODEL `all_para_20_19.all_para_20_19_diff_covid_model`, # Model name\n # Table to evaluate against\n (SELECT\nconfirmed,\ndiff_avg\nFROM\n `all_para_20_19.all_para_20_19_diff_covid`\nWHERE\n parameter = 'co'\nand diff_avg is not null\n \n )\n)", "Query complete after 0.00s: 100%|██████████| 3/3 [00:00<00:00, 1508.20query/s] \nDownloading: 100%|██████████| 1/1 [00:01<00:00, 1.86s/rows]\n" ] ], [ [ "Evaluation for country level monthly average PM2.5 AQI changes vs monthly new confirmed COVID cases model: ", "_____no_output_____" ], [ "<img src=\"https://github.com/ttcao63/775team_project_b2_t2/blob/main/pm25_aqi_confirmed_case.png?raw=true\" align=\"center\" width=\"800\"/>", "_____no_output_____" ], [ "Evaluation for country level monthly average NO2 AQI changes vs monthly new confirmed COVID cases model: ", "_____no_output_____" ], [ "<img src=\"https://github.com/ttcao63/775team_project_b2_t2/blob/main/no2_aqi_confirmed_case.png?raw=true\" align=\"center\" width=\"800\"/>", "_____no_output_____" ], [ "Evaluation for country level monthly average O3 AQI changes vs monthly new confirmed COVID cases model: ", "_____no_output_____" ], [ "<img src=\"https://github.com/ttcao63/775team_project_b2_t2/blob/main/o3_aqi_confirmed_case.png?raw=true\" align=\"center\" width=\"800\"/>", "_____no_output_____" ], [ "We have also conducted log transformation of x-variables for linear regression, the most correlated data is PM 2.5 AQI changes vs LOG(confirmed case). Visualization is shown below.", "_____no_output_____" ], [ "<img src=\"https://github.com/ttcao63/775team_project_b2_t2/blob/main/Viz_PM25_Regression.png?raw=true\" align=\"center\" width=\"800\"/>", "_____no_output_____" ], [ "We can see an overall AQI changes from 2019 to 2020. However, after running regression for four air pollutants, model R-squares are less than 0.02, indicating a weak linear relationship between the air quality index changes and the numbers of new confirmed COVID cases. The result makes sense because there are complicated physical and chemical process involved in formation and transportation of air pollution, thus factors such as the weather, energy source, and terrain could also impact the AQI changes. Also, the dramatic increase of new COVID cases might not affect people's response in a way reducing outdoor activities, especially when \"stay at home order\" is partially lifted.\n\nIn this case, we decide to specifically study some countries during their lockdown period and examine the AQI changes.", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "### VI: When were lockdowns implemented for each country? ", "_____no_output_____" ], [ "Lockdown Dates per Country\n\nChina: Jan 23 - April 8, 2020 (Wuhan 76 day lockdown)\n\nUSA: March 19 - April 7, 2020 \n\nItaly: March 9 - May 18, 2020\n\nTaiwan: No lockdowns in 2020. Lockdown started in July 2021. \n\nAustralia: March 18 - May/June 2020\n\nNew Zealand: March 25 - May/June 2020", "_____no_output_____" ], [ "From the previous regression model we can see that the there was very little correlation between AQI and confirmed cases, and one of the main reasons is that confirmed cases could not accurately capture human activity. To compensate for this, we narrowed down the dates of our pollutant data in order to compare the pollutant levels only during lockdown periods in 2019 and 2020 for the countries where COVID-19 was most prevalent: China, USA, Italy, and those that COVID-19 wasn't as prevalent: Taiwan, Australia, and New Zealand. We came to a conclusion that most lockdown periods started from mid March to April, May, or June, except for China, which started their lockdown late January until April of 2020. To generalize the lockdown dates for countries other than China, the SQL query included dates from the beginning of March to the end of June. As for China, the query included specific dates from January 23 to April 8th of 2020, which is the Wuhan 76 day lockdown. ", "_____no_output_____" ] ], [ [ "%%bigquery\nSELECT country, date, parameter, AVG(count) AS air_quality\nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE date BETWEEN '2020-03-01' AND '2020-06-30'\nAND country in ('US','IT','AU','NZ','TW')\nGROUP BY country, parameter, date\nORDER BY date", "Query complete after 0.00s: 100%|██████████| 1/1 [00:00<00:00, 866.23query/s] \nDownloading: 100%|██████████| 7741/7741 [00:01<00:00, 4628.58rows/s]\n" ], [ "%%bigquery\nSELECT country, date, parameter, AVG(count) AS air_quality\nFROM `ba775-team2-b2.AQICN.air_quality_data`\nWHERE date BETWEEN '2020-01-23' AND '2020-04-08'\nAND country = 'CN'\nGROUP BY country, parameter, date\nORDER BY date", "Query complete after 0.00s: 100%|██████████| 1/1 [00:00<00:00, 1015.32query/s]\nDownloading: 100%|██████████| 900/900 [00:01<00:00, 558.11rows/s]\n" ] ], [ [ "---", "_____no_output_____" ], [ "### VII: How did Air Quality change in countries with low COVID-19 cases (NZ, AUS, TW) and high COVID-19 cases (US, IT,CN)?\nThis question was answered by creating separate tables that encompassed the equivalent lockdown periods per country for 2019. Then, the two tables were joined using the parameter and grouped according to country and parameter to create a subsequent table illustrating the percentage change in average pollution from 2019 to 2020 (during the respective lockdown periods). ", "_____no_output_____" ], [ "#### 1. Countries with high COVID cases", "_____no_output_____" ] ], [ [ "%%bigquery\nCREATE OR REPLACE TABLE AQICN.air_quality2019_Italy AS\n SELECT country, parameter, median AS air_quality2019 FROM `ba775-team2-b2.AQICN.air_quality_data`\n WHERE date BETWEEN '2019-03-09' AND '2019-05-18'\n AND country = 'IT'", "Query complete after 0.01s: 100%|██████████| 3/3 [00:00<00:00, 1165.08query/s] \n" ], [ "%%bigquery\nSELECT a2020.country, a2020.parameter, AVG(a2020.median) AS air_quality2020, AVG(air_quality2019) AS air_quality2019,\n (AVG(a2020.median)-AVG(air_quality2019))/AVG(air_quality2019) AS percentage_change\nFROM `ba775-team2-b2.AQICN.air_quality_data` AS a2020\nLEFT JOIN AQICN.air_quality2019_Italy AS a2019\nUSING(parameter)\nWHERE a2020.date BETWEEN '2020-03-09' AND '2020-05-18'\nAND a2020.country = 'IT'\nAND Parameter in ('pm25','pm10','o3','no2','co','so2')\nGROUP BY a2020.country, a2020.parameter\nORDER BY percentage_change", "Query complete after 0.00s: 100%|██████████| 4/4 [00:00<00:00, 2174.90query/s] \nDownloading: 100%|██████████| 6/6 [00:01<00:00, 3.91rows/s]\n" ] ], [ [ "Here we can see that the only pollutant that decreased during the 2020 lockdown in Italy, compared to the respective time period in 2019, was NO2, which decreased by 35.74%.", "_____no_output_____" ] ], [ [ "%%bigquery\nCREATE OR REPLACE TABLE AQICN.air_quality2019_US AS\n SELECT country, parameter, median AS air_quality2019 FROM `ba775-team2-b2.AQICN.air_quality_data`\n WHERE date BETWEEN '2019-03-19' AND '2019-04-07'\n AND country = 'US'", "Query complete after 0.00s: 100%|██████████| 3/3 [00:00<00:00, 1557.48query/s] \n" ], [ "%%bigquery\nSELECT a2020.country, a2020.parameter, AVG(a2020.median) AS air_quality2020, AVG(air_quality2019) AS air_quality2019,\n (AVG(a2020.median)-AVG(air_quality2019))/AVG(air_quality2019) AS percentage_change\nFROM `ba775-team2-b2.AQICN.air_quality_data` AS a2020\nLEFT JOIN AQICN.air_quality2019_US AS a2019\nUSING(parameter)\nWHERE a2020.date BETWEEN '2020-03-19' AND '2020-04-07'\nAND a2020.country = 'US'\nAND Parameter in ('pm25','pm10','o3','no2','co','so2')\nGROUP BY a2020.country, a2020.parameter\nORDER BY percentage_change", "Query complete after 0.00s: 100%|██████████| 4/4 [00:00<00:00, 2138.31query/s] \nDownloading: 100%|██████████| 6/6 [00:01<00:00, 3.36rows/s]\n" ] ], [ [ "In the United States, all the pollutants decreased in 2020 compared to 2019. The largest changes occurred in O3, NO2 and SO2, which decreased by 36.69%, 30.22%, and 27.10% respectively. This indicates that the lockdowns during the COVID-19 pandemic may have positively affected the emission of pollutants in the United States. ", "_____no_output_____" ] ], [ [ "%%bigquery\nCREATE OR REPLACE TABLE AQICN.air_quality2019_China AS\n SELECT country, parameter, median AS air_quality2019 FROM `ba775-team2-b2.AQICN.air_quality_data`\n WHERE date BETWEEN '2019-01-23' AND '2019-04-08'\n AND country = 'CN'", "Query complete after 0.00s: 100%|██████████| 3/3 [00:00<00:00, 1746.17query/s] \n" ], [ "%%bigquery\nSELECT a2020.country, a2020.parameter, AVG(a2020.median) AS air_quality2020, AVG(air_quality2019) AS air_quality2019,\n (AVG(a2020.median)-AVG(air_quality2019))/AVG(air_quality2019) AS percentage_change\nFROM `ba775-team2-b2.AQICN.air_quality_data` AS a2020\nLEFT JOIN AQICN.air_quality2019_China AS a2019\nUSING(parameter)\nWHERE a2020.date BETWEEN '2020-01-23' AND '2020-04-08'\nAND a2020.country = 'CN'\nAND Parameter in ('pm25','pm10','o3','no2','co','so2')\nGROUP BY a2020.country, a2020.parameter\nORDER BY percentage_change", "Query complete after 0.00s: 100%|██████████| 4/4 [00:00<00:00, 1981.72query/s] \nDownloading: 100%|██████████| 6/6 [00:01<00:00, 4.01rows/s]\n" ] ], [ [ "In China, most pollutants decreased in 2020 compared to the same period in 2019. The largest change was in NO2 which decreased by 30.88% compared to the previous year.", "_____no_output_____" ], [ "#### 2. Countries with low COVID cases", "_____no_output_____" ] ], [ [ "%%bigquery\nCREATE OR REPLACE TABLE AQICN.air_quality2019_Taiwan AS\n SELECT country, parameter, median AS air_quality2019 FROM `ba775-team2-b2.AQICN.air_quality_data`\n WHERE EXTRACT(month FROM date) = 07\n AND EXTRACT(year FROM date) = 2019\n AND country = 'TW'", "Query complete after 0.00s: 100%|██████████| 3/3 [00:00<00:00, 1918.71query/s] \n" ], [ "%%bigquery\nSELECT a2020.country, a2020.parameter, AVG(a2020.median) AS air_quality2020, AVG(air_quality2019) AS air_quality2019,\n (AVG(a2020.median)-AVG(air_quality2019))/AVG(air_quality2019) AS percentage_change\nFROM `ba775-team2-b2.AQICN.air_quality_data` AS a2020\nLEFT JOIN AQICN.air_quality2019_Taiwan AS a2019\nUSING(parameter)\nWHERE EXTRACT(month FROM a2020.date) = 07\nAND EXTRACT(year FROM a2020.date) = 2020\nAND a2020.country = 'TW'\nAND Parameter in ('pm25','pm10','o3','no2','co','so2')\nGROUP BY a2020.country, a2020.parameter\nORDER BY percentage_change", "Query complete after 0.00s: 100%|██████████| 4/4 [00:00<00:00, 1830.37query/s] \nDownloading: 100%|██████████| 6/6 [00:01<00:00, 4.02rows/s]\n" ] ], [ [ "Taiwan, which did not experience lockdowns due to COVID-19, also shows a decrease in all pollutant levels. This contradicts our initially hypothesis that countries who experienced more COVID-19 and therefore more lockdowns would have better air quality. ", "_____no_output_____" ] ], [ [ "%%bigquery\nCREATE OR REPLACE TABLE AQICN.air_quality2019_AUS AS\n SELECT country, parameter, median AS air_quality2019 FROM `ba775-team2-b2.AQICN.air_quality_data`\n WHERE date BETWEEN '2019-03-25' AND '2019-05-31'\n AND country = 'NZ'", "Query complete after 0.00s: 100%|██████████| 3/3 [00:00<00:00, 1679.29query/s] \n" ], [ "%%bigquery\nSELECT a2020.country, a2020.parameter, AVG(a2020.median) AS air_quality2020, AVG(air_quality2019) AS air_quality2019,\n (AVG(a2020.median)-AVG(air_quality2019))/AVG(air_quality2019) AS percentage_change\nFROM `ba775-team2-b2.AQICN.air_quality_data` AS a2020\nLEFT JOIN AQICN.air_quality2019_NZ AS a2019\nUSING(parameter)\nWHERE a2020.date BETWEEN '2020-03-25' AND '2020-05-31'\nAND Parameter in ('pm25','pm10','o3','no2','co','so2')\nAND a2020.country = 'NZ'\nGROUP BY a2020.country, a2020.parameter\nORDER BY percentage_change", "Query complete after 0.00s: 100%|██████████| 4/4 [00:00<00:00, 2199.14query/s] \nDownloading: 100%|██████████| 5/5 [00:01<00:00, 3.27rows/s]\n" ] ], [ [ "New Zealand also shows a decrease in all pollutant levels. Nevertheless, New Zealand did go into lockdown for a period and these numbers may reflect the lessened activity due to COVID-19 during that time compared to the equivalent in 2019. ", "_____no_output_____" ] ], [ [ "%%bigquery\nCREATE OR REPLACE TABLE AQICN.air_quality2019_AUS AS\n SELECT country, parameter, median AS air_quality2019 FROM `ba775-team2-b2.AQICN.air_quality_data`\n WHERE date BETWEEN '2019-03-18' AND '2019-05-31'\n AND country = 'AU'", "Query complete after 0.00s: 100%|██████████| 3/3 [00:00<00:00, 1443.66query/s] \n" ], [ "%%bigquery\nSELECT a2020.country, a2020.parameter, AVG(a2020.median) AS air_quality2020, AVG(air_quality2019) AS air_quality2019,\n (AVG(a2020.median)-AVG(air_quality2019))/AVG(air_quality2019) AS percentage_change\nFROM `ba775-team2-b2.AQICN.air_quality_data` AS a2020\nLEFT JOIN AQICN.air_quality2019_AUS AS a2019\nUSING(parameter)\nWHERE a2020.date BETWEEN '2020-03-18' AND '2020-05-31'\nAND Parameter in ('pm25','pm10','o3','no2','co','so2')\nAND a2020.country = 'AU'\nGROUP BY a2020.country, a2020.parameter\nORDER BY percentage_change", "Query complete after 0.00s: 100%|██████████| 4/4 [00:00<00:00, 2131.79query/s] \nDownloading: 100%|██████████| 6/6 [00:01<00:00, 4.52rows/s]\n" ] ], [ [ "Australia shows decreases in most pollutant parameter levels in 2020 compared to respective periods in 2019. ", "_____no_output_____" ], [ "The fact that all tables illustrate decrease in most pollutant parameter levels, except for Italy, seems to contradict our initial hypothesis. Initially, we hypothesized that in countries where COVID-19 was more prevalent, and therefore where there were more lockdowns and less human activity, there would be better pollutant levels. However, when looking at the results of the analysis, one can see that the extent to which COVID-19 was prevalent does not seem to largely affect the pollutant parameter levels considering that regardless of the country they seem to have decreased in 2020 compared to 2019. This may be due to various governmental and public policies regarding climate change that have pushed countries to improve the air quality as well as the general decrease in human activity worldwide due to the pandemic.", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "### VIII: Conclusion", "_____no_output_____" ], [ "In this project, we used air quality index (AQI) dataset among 380 major cities across the world from 2019 to 2020 to study criteria air pollutant level changes during the COVID pandemic. According to the result, we conclude that the COVID impacts air quality more at regional-level than at global-level, more in a relative short period of time than in a relative long-term. Even though we don't see a strong relationship between air quality changes versus numbers of confirmed COIVD case, we find that lockdowns during the pandemic do make effects on air pollutant levels in different countries due to reduced outdoor human activities.", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "### IX: Public Tableau Dashboards\n\nTo interact with our public Tableau dashboards please visit: https://public.tableau.com/app/profile/arpit.jain7335/viz/AnalyzingAirQualityDuringCOVID19Pandemic/AirQualityGlobalLevel?publish=yes", "_____no_output_____" ], [ "<img src=\"https://github.com/arp-jain/BA775-team2-b2/blob/main/Air%20Quality%20Global%20Level.png?raw=true\" align=\"center\"/>", "_____no_output_____" ], [ "<img src=\"https://github.com/arp-jain/BA775-team2-b2/blob/main/Air%20Quality%20City%20Level.png?raw=true\" align=\"center\"/>", "_____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", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d0100f5d02d7e88034b069abce704f40aae7a1e9
24,480
ipynb
Jupyter Notebook
content/post/pandas-categories/pandas-categories.ipynb
fabiangunzinger/wowchemy
f0c7d09d550f353b2852f4775eb7a0507955150b
[ "MIT" ]
null
null
null
content/post/pandas-categories/pandas-categories.ipynb
fabiangunzinger/wowchemy
f0c7d09d550f353b2852f4775eb7a0507955150b
[ "MIT" ]
null
null
null
content/post/pandas-categories/pandas-categories.ipynb
fabiangunzinger/wowchemy
f0c7d09d550f353b2852f4775eb7a0507955150b
[ "MIT" ]
null
null
null
27.755102
420
0.451389
[ [ [ "import numpy as np\nimport pandas as pd\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "## Basics\n\n- All values of a categorical valiable are either in `categories` or `np.nan`.\n\n- Order is defined by the order of `categories`, not the lexical order of the values.\n\n- Internally, the data structure consists of a `categories` array and an integer arrays of `codes`, which point to the values in the `categories` array.\n\n- The memory usage of a categorical variable is proportional to the number of categories plus the length of the data, while that for an object dtype is a constant times the length of the data. As the number of categories approaches the length of the data, memory usage approaches that of object type.\n\n- Categories can be useful in the following scenarios:\n\n - To save memory (if number of categories small relative to number of rows)\n \n - If logical order differs from lexical order (e.g. 'small', 'medium', 'large')\n \n - To signal to libraries that column should be treated as a category (e.g. for plotting)", "_____no_output_____" ], [ "## General best practices\n\nBased on [this](https://towardsdatascience.com/staying-sane-while-adopting-pandas-categorical-datatypes-78dbd19dcd8a) useful article.\n\n- Operate on category values rather than column elements. E.g. to rename categories use `df.catvar.cat.rename_rategories(*args, **kwargs)`, if there is no `cat` method available,\nconsider operating on categories directly with `df.catvar.cat.categories`.\n\n- Merging on categories: the two key things to remember are that 1) Pandas treats categorical variables with different categories as different data types, and 2) category merge keys will only be categories in the merged dataframe if they are of the same data types (i.e. have the same categories), otherwise they will be converted back to objects.\n\n- Grouping on categories: remember that by default we group on all categories, not just those present in the data. More often than not, you'll want to use `df.groupby(catvar, observed=True)` to only use categories observed in the data.", "_____no_output_____" ] ], [ [ "titanic = sns.load_dataset(\"titanic\")\ntitanic.head(2)", "_____no_output_____" ] ], [ [ "## Operations I frequently use", "_____no_output_____" ], [ "### Renaming categories", "_____no_output_____" ] ], [ [ "titanic[\"class\"].cat.rename_categories(str.upper)[:2]", "_____no_output_____" ] ], [ [ "### Appending new categories", "_____no_output_____" ] ], [ [ "titanic[\"class\"].cat.add_categories([\"Fourth\"]).cat.categories", "_____no_output_____" ] ], [ [ "### Removing categories", "_____no_output_____" ] ], [ [ "titanic[\"class\"].cat.remove_categories([\"Third\"]).cat.categories", "_____no_output_____" ] ], [ [ "### Remove unused categories", "_____no_output_____" ] ], [ [ "titanic_small = titanic.iloc[:2]\ntitanic_small", "_____no_output_____" ], [ "titanic_small[\"class\"].cat.remove_unused_categories().cat.categories", "_____no_output_____" ] ], [ [ "### Remove and add categories simultaneously", "_____no_output_____" ] ], [ [ "titanic[\"class\"].value_counts(dropna=False)", "_____no_output_____" ], [ "titanic[\"class\"].cat.set_categories([\"First\", \"Third\", \"Fourth\"]).value_counts(\n dropna=False\n)", "_____no_output_____" ] ], [ [ "### Using string and datetime accessors\n\nThis works as expected, and if the number of distinct categories is small relative to the number of rows, then operating on the categories is faster (because under the hood, pandas applies the change to `categories` and constructs a new series (see [here](https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#string-and-datetime-accessors)) so no need to do this manually as I was inclined to).", "_____no_output_____" ] ], [ [ "cat_class = titanic[\"class\"]\n%timeit cat_class.str.contains('d')\n\nstr_class = titanic[\"class\"].astype(\"object\")\n%timeit str_class.str.contains('d')", "149 µs ± 7.84 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n398 µs ± 16.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ] ], [ [ "## Object creation", "_____no_output_____" ], [ "Convert *sex* and *class* to the same categorical type, with categories being the union of all unique values of both columns.", "_____no_output_____" ] ], [ [ "cols = [\"sex\", \"who\"]\nunique_values = np.unique(titanic[cols].to_numpy().ravel())\ncategories = pd.CategoricalDtype(categories=unique_values)\ntitanic[cols] = titanic[cols].astype(categories)\nprint(titanic.sex.cat.categories)\nprint(titanic.who.cat.categories)", "Index(['child', 'female', 'male', 'man', 'woman'], dtype='object')\nIndex(['child', 'female', 'male', 'man', 'woman'], dtype='object')\n" ], [ "# restore sex and who to object types\ntitanic[cols] = titanic[cols].astype(\"object\")", "_____no_output_____" ] ], [ [ "## Custom order ", "_____no_output_____" ] ], [ [ "df = pd.DataFrame({\"quality\": [\"good\", \"excellent\", \"very good\"]})\ndf.sort_values(\"quality\")", "_____no_output_____" ], [ "ordered_quality = pd.CategoricalDtype([\"good\", \"very good\", \"excellent\"], ordered=True)\ndf.quality = df.quality.astype(ordered_quality)\ndf.sort_values(\"quality\")", "_____no_output_____" ] ], [ [ "## Unique values", "_____no_output_____" ] ], [ [ "small_titanic = titanic.iloc[:2]\nsmall_titanic", "_____no_output_____" ] ], [ [ "`Series.unique` returns values in order appearance, and only returns values that are present in the data.", "_____no_output_____" ] ], [ [ "small_titanic[\"class\"].unique()", "_____no_output_____" ] ], [ [ "`Series.cat.categories` returns all category values.", "_____no_output_____" ] ], [ [ "small_titanic[\"class\"].cat.categories", "_____no_output_____" ] ], [ [ "## References\n\n- [Docs](https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#object-creation)\n\n- [Useful Medium article](https://towardsdatascience.com/staying-sane-while-adopting-pandas-categorical-datatypes-78dbd19dcd8a)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d0101242ccdabafae8396f4420ed5b27a69cec50
6,089
ipynb
Jupyter Notebook
Learning Notes/Learning Notes ML - 1 Basics.ipynb
k21k/Python-Notes
fe59a52664e911c5cdbc19f77e94f1f892dcaa0b
[ "BSD-2-Clause" ]
null
null
null
Learning Notes/Learning Notes ML - 1 Basics.ipynb
k21k/Python-Notes
fe59a52664e911c5cdbc19f77e94f1f892dcaa0b
[ "BSD-2-Clause" ]
null
null
null
Learning Notes/Learning Notes ML - 1 Basics.ipynb
k21k/Python-Notes
fe59a52664e911c5cdbc19f77e94f1f892dcaa0b
[ "BSD-2-Clause" ]
null
null
null
21.669039
142
0.552472
[ [ [ "# Machine Learning 1", "_____no_output_____" ], [ "# Some Concepts", "_____no_output_____" ] ], [ [ "Mean Absolute Error (MAE) is the mean of the absolute value of the errors\nMean Squared Error (MSE) is the mean of the squared errors:\nRoot Mean Squared Error (RMSE) is the square root of the mean of the squared errors\n\nComparing these metrics:\n\nMAE is the easiest to understand because it’s the average error.\nMSE is more popular than MAE because MSE “punishes” larger errors, which tends to be useful in the real world.\nRMSE is even more popular than MSE because RMSE is interpretable in the “y” units.", "_____no_output_____" ], [ "# to get the metrics\n\nfrom sklearn import metrics\n\nprint('MAE:', metrics.mean_absolute_error(y_test, y_pred)) \nprint('MSE:', metrics.mean_squared_error(y_test, y_pred)) \nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, y_pred))) \n\n# Different way, just for illustration\ny_pred = linreg.predict(X_test) \n\nfrom sklearn.metrics import mean_squared_error\nMSE = mean_squared_error(y_test, y_pred)\nprint(MSE)\n\n", "_____no_output_____" ] ], [ [ "#### Predictions", "_____no_output_____" ] ], [ [ "# Lets say that the model inputs are\nX = df[['Weight', 'Volume']]\ny = df['CO2']\n\nregr = linear_model.LinearRegression()\nregr.fit(X, y)\n\n# Simply do that for predicting the CO2 emission of a car where the weight is 2300kg, and the volume is 1300ccm:\npredictedCO2 = regr.predict([[2300, 1300]])\n\nprint(predictedCO2)\n", "_____no_output_____" ] ], [ [ "#### OLS Regression", "_____no_output_____" ] ], [ [ "https://docs.w3cub.com/statsmodels/generated/statsmodels.regression.linear_model.ols.fit_regularized/", "_____no_output_____" ], [ "est=sm.OLS(y, X)\nest = est.fit()\nest.summary()", "_____no_output_____" ] ], [ [ "#### Plotting Errors", "_____no_output_____" ] ], [ [ "# provided that y_test and y_pred have been called (example below)\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)\n# y_pred = linreg.predict(X_test)\n\nsns.distplot((y_test-y_pred),bins=50) ", "_____no_output_____" ] ], [ [ "# Interpretation of Outputs", "_____no_output_____" ], [ "## Multiple Linear Regression", "_____no_output_____" ] ], [ [ "Almost all the real-world problems that you are going to encounter will have more than two variables. \nLinear regression involving multiple variables is called “multiple linear regression” or multivariate linear regression. \nThe steps to perform multiple linear regression are almost similar to that of simple linear regression. \n\nThe difference lies in the evaluation. \nYou can use it to find out which factor has the highest impact on the predicted output and how different variables relate to each other.", "_____no_output_____" ] ], [ [ "# Logistic Regression", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
d01018f62c69c109f129fab0c7bfe93ee8f24a6f
13,277
ipynb
Jupyter Notebook
docs/notebooks/perf_analysis/benchmark_perf_timeline_analysis.ipynb
yinghu5/models
d726b04078e5c7ced6019bc0a6d9a15d76a529c7
[ "Apache-2.0" ]
1
2022-03-13T17:53:51.000Z
2022-03-13T17:53:51.000Z
docs/notebooks/perf_analysis/benchmark_perf_timeline_analysis.ipynb
sejnii/cloudsystem
d33fe9f9463f79c307f6c53c6a0ba38459427be9
[ "Apache-2.0" ]
null
null
null
docs/notebooks/perf_analysis/benchmark_perf_timeline_analysis.ipynb
sejnii/cloudsystem
d33fe9f9463f79c307f6c53c6a0ba38459427be9
[ "Apache-2.0" ]
null
null
null
25.931641
663
0.573172
[ [ [ "# Tensorflow Timeline Analysis on Model Zoo Benchmark between Intel optimized and stock Tensorflow\n\nThis jupyter notebook will help you evaluate performance benefits from Intel-optimized Tensorflow on the level of Tensorflow operations via several pre-trained models from Intel Model Zoo. The notebook will show users a bar chart like the picture below for the Tensorflow operation level performance comparison. The red horizontal line represents the performance of Tensorflow operations from Stock Tensorflow, and the blue bars represent the speedup of Intel Tensorflow operations. The operations marked as \"mkl-True\" are accelerated by MKL-DNN a.k.a oneDNN, and users should be able to see a good speedup for those operations accelerated by MKL-DNN. \n> NOTE : Users need to get Tensorflow timeline json files from other Jupyter notebooks like benchmark_perf_comparison\n first to proceed this Jupyter notebook.", "_____no_output_____" ], [ "<img src=\"images\\compared_tf_op_duration_ratio_bar.png\" width=\"700\">", "_____no_output_____" ], [ "The notebook will also show users two pie charts like the picture below for elapsed time percentage among different Tensorflow operations. \nUsers can easily find the Tensorflow operation hotspots in these pie charts among Stock and Intel Tensorflow.", "_____no_output_____" ], [ "<img src=\"images\\compared_tf_op_duration_pie.png\" width=\"700\">", "_____no_output_____" ], [ "# Get Platform Information ", "_____no_output_____" ] ], [ [ "from profiling.profile_utils import PlatformUtils\nplat_utils = PlatformUtils()\nplat_utils.dump_platform_info()", "_____no_output_____" ] ], [ [ "# Section 1: TensorFlow Timeline Analysis\n## Prerequisites", "_____no_output_____" ] ], [ [ "!pip install cxxfilt\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport tensorflow as tf", "_____no_output_____" ], [ "import pandas as pd\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1500)", "_____no_output_____" ] ], [ [ "## List out the Timeline folders", "_____no_output_____" ], [ "First, list out all Timeline folders from previous runs.", "_____no_output_____" ] ], [ [ "import os\nfilenames= os.listdir (\".\") \nresult = []\nkeyword = \"Timeline\"\nfor filename in filenames: \n if os.path.isdir(os.path.join(os.path.abspath(\".\"), filename)): \n if filename.find(keyword) != -1:\n result.append(filename)\nresult.sort()\n\nindex =0 \nfor folder in result:\n print(\" %d : %s \" %(index, folder))\n index+=1", "_____no_output_____" ] ], [ [ "## Select a Timeline folder from previous runs\n#### ACTION: Please select one Timeline folder and change FdIndex accordingly", "_____no_output_____" ] ], [ [ "FdIndex = 3", "_____no_output_____" ] ], [ [ "List out all Timeline json files inside Timeline folder.", "_____no_output_____" ] ], [ [ "import os\nTimelineFd = result[FdIndex]\nprint(TimelineFd)\ndatafiles = [TimelineFd +os.sep+ x for x in os.listdir(TimelineFd) if '.json' == x[-5:]]\nprint(datafiles)\nif len(datafiles) is 0:\n print(\"ERROR! No json file in the selected folder. Please select other folder.\")\nelif len(datafiles) is 1:\n print(\"WARNING! There is only 1 json file in the selected folder. Please select other folder to proceed Section 1.2.\")", "_____no_output_____" ] ], [ [ "> **Users can bypass below Section 1.1 and analyze performance among Stock and Intel TF by clicking the link : [Section 1_2](#section_1_2).**", "_____no_output_____" ], [ "<a id='section_1_1'></a>\n## Section 1.1: Performance Analysis for one TF Timeline result\n### Step 1: Pick one of the Timeline files\n#### List out all the Timeline files first\n", "_____no_output_____" ] ], [ [ "index = 0\nfor file in datafiles:\n print(\" %d : %s \" %(index, file))\n index+=1", "_____no_output_____" ] ], [ [ "#### ACTION: Please select one timeline json file and change file_index accordingly", "_____no_output_____" ] ], [ [ "## USER INPUT\nfile_index=0\n\nfn = datafiles[file_index]\ntfile_prefix = fn.split('_')[0]\ntfile_postfix = fn.strip(tfile_prefix)[1:]\nfn", "_____no_output_____" ] ], [ [ "### Step 2: Parse timeline into pandas format", "_____no_output_____" ] ], [ [ "from profiling.profile_utils import TFTimelinePresenter\ntfp = TFTimelinePresenter(True)\ntimeline_pd = tfp.postprocess_timeline(tfp.read_timeline(fn))\ntimeline_pd = timeline_pd[timeline_pd['ph'] == 'X']", "_____no_output_____" ] ], [ [ "### Step 3: Sum up the elapsed time of each TF operation", "_____no_output_____" ] ], [ [ "tfp.get_tf_ops_time(timeline_pd,fn,tfile_prefix)", "_____no_output_____" ] ], [ [ "### Step 4: Draw a bar chart for elapsed time of TF ops ", "_____no_output_____" ] ], [ [ "filename= tfile_prefix +'_tf_op_duration_bar.png'\ntitle_=tfile_prefix +'TF : op duration bar chart'\nax=tfp.summarize_barh(timeline_pd, 'arg_op', title=title_, topk=50, logx=True, figsize=(10,10))\ntfp.show(ax,'bar')", "_____no_output_____" ] ], [ [ "### Step 5: Draw a pie chart for total time percentage of TF ops ", "_____no_output_____" ] ], [ [ "filename= tfile_prefix +'_tf_op_duration_pie.png'\ntitle_=tfile_prefix +'TF : op duration pie chart'\ntimeline_pd_known = timeline_pd[ ~timeline_pd['arg_op'].str.contains('unknown') ]\nax=tfp.summarize_pie(timeline_pd_known, 'arg_op', title=title_, topk=50, logx=True, figsize=(10,10))\ntfp.show(ax,'pie')\nax.figure.savefig(filename,bbox_inches='tight')", "_____no_output_____" ] ], [ [ "<a id='section_1_2'></a>\n## Section 1.2: Analyze TF Timeline results between Stock and Intel Tensorflow\n### Speedup from MKL-DNN among different TF operations", "_____no_output_____" ], [ "### Step 1: Select one Intel and one Stock TF timeline files for analysis\n#### List out all timeline files in the selected folder", "_____no_output_____" ] ], [ [ "if len(datafiles) is 1:\n print(\"ERROR! There is only 1 json file in the selected folder.\")\n print(\"Please select other Timeline folder from beginnning to proceed Section 1.2.\")\n\nfor i in range(len(datafiles)):\n print(\" %d : %s \" %(i, datafiles[i]))", "_____no_output_____" ] ], [ [ "#### ACTION: Please select one timeline file as a perfomance baseline and the other as a comparison target\nput the related index for your selected timeline file.\nIn general, please put stock_timeline_xxxxx as the baseline.", "_____no_output_____" ] ], [ [ "# perfomance baseline \nBaseline_Index=1\n# comparison target\nComparison_Index=0", "_____no_output_____" ] ], [ [ "#### List out two selected timeline files", "_____no_output_____" ] ], [ [ "selected_datafiles = []\nselected_datafiles.append(datafiles[Baseline_Index])\nselected_datafiles.append(datafiles[Comparison_Index])\nprint(selected_datafiles)", "_____no_output_____" ] ], [ [ "### Step 2: Parsing timeline results into CSV files", "_____no_output_____" ] ], [ [ "%matplotlib agg\nfrom profiling.profile_utils import TFTimelinePresenter\ncsvfiles=[]\n\ntfp = TFTimelinePresenter(True)\nfor fn in selected_datafiles:\n if fn.find('/'):\n fn_nofd=fn.split('/')[1]\n else:\n fn_nofd=fn\n tfile_name= fn_nofd.split('.')[0]\n tfile_prefix = fn_nofd.split('_')[0]\n tfile_postfix = fn_nofd.strip(tfile_prefix)[1:]\n csvpath = TimelineFd +os.sep+tfile_name+'.csv'\n print(csvpath)\n csvfiles.append(csvpath)\n timeline_pd = tfp.postprocess_timeline(tfp.read_timeline(fn))\n timeline_pd = timeline_pd[timeline_pd['ph'] == 'X']\n tfp.get_tf_ops_time(timeline_pd,fn,tfile_prefix)", "_____no_output_____" ] ], [ [ "### Step 3: Pre-processing for the two CSV files", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\n\ncsvarray=[]\nfor csvf in csvfiles:\n print(\"read into pandas :\",csvf)\n a = pd.read_csv(csvf)\n csvarray.append(a)\n\na = csvarray[0]\nb = csvarray[1]", "_____no_output_____" ] ], [ [ "### Step 4: Merge two CSV files and caculate the speedup accordingly", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\nfdir='merged'\nif not os.path.exists(fdir):\n os.mkdir(fdir)\n \nfpath=fdir+os.sep+'merged.csv'\nmerged=tfp.merge_two_csv_files(fpath,a,b)\nmerged", "_____no_output_____" ] ], [ [ "### Step 5: Draw a bar chart for elapsed time of TF ops among stock TF and Intel TF", "_____no_output_____" ] ], [ [ "%matplotlib inline\nprint(fpath)\ntfp.plot_compare_bar_charts(fpath)\ntfp.plot_compare_ratio_bar_charts(fpath, tags=['','oneDNN ops'])", "_____no_output_____" ] ], [ [ "### Step 6: Draw pie charts for elapsed time of TF ops among stock TF and Intel TF", "_____no_output_____" ] ], [ [ "tfp.plot_compare_pie_charts(fpath)", "_____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" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0101d7f29ceee849f6a59f20b8679a73efb447e
2,926
ipynb
Jupyter Notebook
sec04-1_LabIntro/My_Lab_Diagram.ipynb
codered-by-ec-council/Network-Automation-in-Python
c8efba489d22db4e488b0c4c1145517bdb629b22
[ "MIT" ]
null
null
null
sec04-1_LabIntro/My_Lab_Diagram.ipynb
codered-by-ec-council/Network-Automation-in-Python
c8efba489d22db4e488b0c4c1145517bdb629b22
[ "MIT" ]
null
null
null
sec04-1_LabIntro/My_Lab_Diagram.ipynb
codered-by-ec-council/Network-Automation-in-Python
c8efba489d22db4e488b0c4c1145517bdb629b22
[ "MIT" ]
2
2022-01-18T12:26:38.000Z
2022-01-22T16:07:40.000Z
21.674074
138
0.520848
[ [ [ "diagrams.generic.network.Firewall\ndiagrams.generic.network.Router\ndiagrams.generic.network.Subnet\ndiagrams.generic.network.Switch\ndiagrams.generic.network.VPN\n\ndiagrams.generic.virtualization.Virtualbox\n\ndiagrams.generic.os.Windows", "_____no_output_____" ] ], [ [ "from diagrams import Cluster, Diagram\nfrom diagrams.generic.network import Firewall\nfrom diagrams.generic.network import Router\nfrom diagrams.generic.network import Subnet\nfrom diagrams.generic.network import Switch\nfrom diagrams.generic.virtualization import Virtualbox\nfrom diagrams.generic.os import Windows", "_____no_output_____" ], [ "graph_attr = {\n \"fontsize\": \"28\",\n \"bgcolor\": \"grey\"\n}\n\nwith Diagram(\"My Network Automation with Python Lab\", filename=\"MyLab\", outformat=\"jpg\", graph_attr=graph_attr, show=True):\n my_computer = Windows(\"My Computer\")\n my_home_subnet = Subnet(\"My Home Subnet\")\n \n \n with Cluster(\"Virtualbox\"):\n lab_devs = [Switch(\"sw01\"),\n Switch(\"sw02\"),\n Switch(\"sw03 optional\")]\n\n my_computer >> my_home_subnet >> lab_devs", "_____no_output_____" ], [ "ls", "MyLab.jpg Untitled.ipynb my_lab.png\r\n" ], [ "rm my_lab.png", "_____no_output_____" ], [ "ls", "MyLab.jpg Untitled.ipynb\r\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
d01025db39607a9e679b182448f26919f592ea40
6,117
ipynb
Jupyter Notebook
P33_Test_Trained_Model/Test_Trained_Model.ipynb
Chia-Feng/Pytorch_Learning
3954294ce825076d75adf550be999890dceac9d7
[ "MIT" ]
null
null
null
P33_Test_Trained_Model/Test_Trained_Model.ipynb
Chia-Feng/Pytorch_Learning
3954294ce825076d75adf550be999890dceac9d7
[ "MIT" ]
null
null
null
P33_Test_Trained_Model/Test_Trained_Model.ipynb
Chia-Feng/Pytorch_Learning
3954294ce825076d75adf550be999890dceac9d7
[ "MIT" ]
null
null
null
50.975
2,970
0.750041
[ [ [ "import torchvision, torch\nfrom PIL import Image\nfrom IPython.display import display\nfrom torch import nn\nfrom model import *\nfrom torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential", "_____no_output_____" ], [ "image_path = \"cat.jpg\"\nimage = Image.open(image_path)\n\ntransform = torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),torchvision.transforms.ToTensor()])\nimage = transform(image)\n\ndisplay(torchvision.transforms.ToPILImage()(image))", "_____no_output_____" ], [ "CIFAR10Model = torch.load(\"CIFAR10Model_trained.pth\")\nprint(CIFAR10Model)", "CIFAR10model(\n (model1): Sequential(\n (0): Conv2d(3, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n (1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (2): Conv2d(32, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n (3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (4): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n (5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (6): Flatten(start_dim=1, end_dim=-1)\n (7): Linear(in_features=1024, out_features=64, bias=True)\n (8): Linear(in_features=64, out_features=10, bias=True)\n )\n)\n" ], [ "image = torch.reshape(image, (1,3,32,32))\noutput = CIFAR10Model(image)\nprint(output.argmax(1))\nClassSet= ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']", "tensor([3])\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
d01049078cdab202f77bd4c8b4329a56f4331778
185,914
ipynb
Jupyter Notebook
SupervisedLearning/Problem2_SupervisedLearning_Gaiceanu.ipynb
TheodoraG/FRTN65
dc3849ed449ac7a7889014d759469f7744801306
[ "MIT" ]
null
null
null
SupervisedLearning/Problem2_SupervisedLearning_Gaiceanu.ipynb
TheodoraG/FRTN65
dc3849ed449ac7a7889014d759469f7744801306
[ "MIT" ]
null
null
null
SupervisedLearning/Problem2_SupervisedLearning_Gaiceanu.ipynb
TheodoraG/FRTN65
dc3849ed449ac7a7889014d759469f7744801306
[ "MIT" ]
null
null
null
111.459233
36,366
0.797041
[ [ [ "The data is from a number of patients. The 12 first columns (age, an, ..., time) are features that should be used to predict the outcome in the last column (DEATH_EVENT).\n", "_____no_output_____" ] ], [ [ "# Loading some functionality you might find useful. You might want other than this...\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV\nfrom pandas.plotting import scatter_matrix\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier, plot_tree\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import KMeans\n\n", "_____no_output_____" ], [ "# Downloading data \nurl = 'https://raw.githubusercontent.com/BoBernhardsson/frtn65_exam2022/main/data.csv'\ndata = pd.read_csv(url)\ndata.head()", "_____no_output_____" ], [ "# Picking out features and labels\nX = data.iloc[:,:-1].values\ny = data.iloc[:,-1].values\n(X.shape,y.shape)", "_____no_output_____" ], [ "# select which features to use\n\nX = data.drop(columns=['DEATH_EVENT'])\ny = data.loc[:,'DEATH_EVENT'].values", "_____no_output_____" ], [ "# Creating some initial KNN models and evaluating accuracy \nNdata = data.shape[0]\nfor nr in range(1,10):\n knnmodel = KNeighborsClassifier(n_neighbors = nr)\n knnmodel.fit(X=X,y=y)\n predictions = knnmodel.predict(X=X)\n print('neighbors = {0}: accuracy = {1:.3f}'.format(nr,1-sum(abs(predictions-y))/Ndata))", "neighbors = 1: accuracy = 1.000\nneighbors = 2: accuracy = 0.779\nneighbors = 3: accuracy = 0.779\nneighbors = 4: accuracy = 0.726\nneighbors = 5: accuracy = 0.749\nneighbors = 6: accuracy = 0.719\nneighbors = 7: accuracy = 0.722\nneighbors = 8: accuracy = 0.702\nneighbors = 9: accuracy = 0.709\n" ], [ "features = ['age', 'cr', 'ej', 'pl', 'se1', 'se2', 'time']\nfeatures_categ = ['an','di', 'hi', 'sex', 'sm']\n\n#scale the dataset\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\n\nnumerical_preprocessor = StandardScaler()\n\n#do one-hot encoding for categorical features\ncategorical_preprocessor = OneHotEncoder(handle_unknown=\"ignore\")\npreprocessor = ColumnTransformer([\n ('one-hot-encoder', categorical_preprocessor, features_categ),\n ('standard-scaler', numerical_preprocessor, features)])", "_____no_output_____" ], [ "from sklearn.pipeline import Pipeline\n\n#try Random Forest\nclf = Pipeline(steps = [('preprocessor', preprocessor), ('classifier', RandomForestClassifier(n_estimators=100,max_depth=3))])", "_____no_output_____" ], [ "#split the dataset into trainig and testing\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)", "_____no_output_____" ], [ "clf.fit(x_train, np.ravel(y_train))\nprint(clf.score(x_train,np.ravel(y_train)))\nprint('model score: %.3f' % clf.score(x_test,np.ravel(y_test)))", "0.9121338912133892\nmodel score: 0.733\n" ], [ "#evaluate the model using cross-validation\nscore = cross_val_score(clf, X, np.ravel(y), cv=25)\nprint(\"%0.2f accuracy with a standard deviation of %0.2f\" % (score.mean()*100, score.std()))\nscore_test = clf.score(x_test, np.ravel(y_test))\nprint('Test score: ', '{0:.4f}'.format(score_test*100))", "82.58 accuracy with a standard deviation of 0.15\nTest score: 73.3333\n" ], [ "clf = RandomForestClassifier()\n#find the best model using GridSearch\nparam_grid = {\n 'n_estimators': [100, 1000],\n 'max_depth': [3, 4, 5],\n }\n\nsearch = GridSearchCV(clf, param_grid, cv=4, verbose=1,n_jobs=-1)\n\nsearch.fit(x_train, np.ravel(y_train))\nscore = search.score(x_test, np.ravel(y_test))\nprint(\"Best CV score: {} using {}\".format(search.best_score_, search.best_params_))\nprint(\"Test accuracy: {}\".format(score))", "Fitting 4 folds for each of 6 candidates, totalling 24 fits\nBest CV score: 0.8703389830508474 using {'max_depth': 4, 'n_estimators': 100}\nTest accuracy: 0.75\n" ], [ "randomForestModel = RandomForestClassifier(n_estimators=100,max_depth=5)\n\n#evaluate using cross-validation\nscore=cross_val_score(randomForestModel, X, y, cv=20)", "_____no_output_____" ], [ "randomForestModel.fit(x_train,np.ravel(y_train))\nprint('Training score: ', randomForestModel.score(x_train,np.ravel(y_train)))\nprint('Test score: ', randomForestModel.score(x_test,np.ravel(y_test)))", "Training score: 0.9623430962343096\nTest score: 0.7666666666666667\n" ], [ "#make a prediction and evaluate the performance\ny_pred = randomForestModel.predict(x_test)\n\nscore_new = randomForestModel.score(x_test, y_test)\nprint('Test score: ', score_new)", "Test score: 0.7666666666666667\n" ], [ "import seaborn as sns\nfrom sklearn import metrics\n#confusion matrix\ncm = metrics.confusion_matrix(y_test, y_pred)\nplt.figure(figsize=(10,10))\nsns.heatmap(cm, annot=True, fmt=\".0f\", linewidths=1, square = True);\nplt.ylabel('Actual label');\nplt.xlabel('Predicted label');\nplt.title('Accuracy Score: {0}'.format(score.mean()), size = 15);", "_____no_output_____" ], [ "from sklearn import metrics\n#AUC\nmetrics.plot_roc_curve(randomForestModel, x_test, y_test)", "/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_roc_curve is deprecated; Function :func:`plot_roc_curve` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: :meth:`sklearn.metric.RocCurveDisplay.from_predictions` or :meth:`sklearn.metric.RocCurveDisplay.from_estimator`.\n warnings.warn(msg, category=FutureWarning)\n" ], [ "from sklearn.metrics import classification_report\n\nprint(classification_report(y_test, randomForestModel.predict(x_test)))", " precision recall f1-score support\n\n 0 0.72 0.97 0.83 35\n 1 0.92 0.48 0.63 25\n\n accuracy 0.77 60\n macro avg 0.82 0.73 0.73 60\nweighted avg 0.81 0.77 0.75 60\n\n" ], [ "from pandas import DataFrame\nfeature_df = DataFrame(data.columns.delete(0))\nfeature_df.columns = ['Features']\nfeature_df[\"Feature Importance\"] = pd.Series(randomForestModel.feature_importances_)\n\n#view feature importance according to Random Forest model\nfeature_df", "_____no_output_____" ], [ "#KNN model\n\nclf = Pipeline(steps = [('preprocessor', preprocessor), ('classifier', KNeighborsClassifier(n_neighbors=3))])", "_____no_output_____" ], [ "clf.fit(x_train,np.ravel(y_train))", "_____no_output_____" ], [ "#evaluate the model using cross-validation\nscore = cross_val_score(clf, X, np.ravel(y), cv=25)\nprint(\"%0.2f accuracy with a standard deviation of %0.2f\" % (scores.mean()*100, scores.std()))\nscore_test = clf.score(x_test, np.ravel(y_test))\nprint('Test score: ', '{0:.4f}'.format(score_test*100))", "71.58 accuracy with a standard deviation of 0.08\nTest score: 75.0000\n" ], [ "#make a prediction and evaluate the performance\ny_pred = clf.predict(x_test)\n\nscore_new = clf.score(x_test, y_test)\nprint('Test score: ', score_new)", "Test score: 0.75\n" ], [ "import seaborn as sns\nfrom sklearn import metrics\n\n#confusion matrix\ncm = metrics.confusion_matrix(y_test, y_pred)\nplt.figure(figsize=(10,10))\nsns.heatmap(cm, annot=True, fmt=\".0f\", linewidths=1, square = True);\nplt.ylabel('Actual label');\nplt.xlabel('Predicted label');\nplt.title('Accuracy Score: {0}'.format(score.mean()), size = 15);", "_____no_output_____" ], [ "from sklearn import metrics\n#AUC\nmetrics.plot_roc_curve(clf, x_test, y_test)", "/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_roc_curve is deprecated; Function :func:`plot_roc_curve` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: :meth:`sklearn.metric.RocCurveDisplay.from_predictions` or :meth:`sklearn.metric.RocCurveDisplay.from_estimator`.\n warnings.warn(msg, category=FutureWarning)\n" ], [ "from sklearn.metrics import classification_report\nprint(classification_report(y_test, clf.predict(x_test)))", " precision recall f1-score support\n\n 0 0.70 1.00 0.82 35\n 1 1.00 0.40 0.57 25\n\n accuracy 0.75 60\n macro avg 0.85 0.70 0.70 60\nweighted avg 0.82 0.75 0.72 60\n\n" ], [ "#Boosting model\n\nfrom sklearn.ensemble import GradientBoostingClassifier\n#find the best learning rate\nlearning_rates = [0.05, 0.1, 0.25, 0.5, 0.75, 1]\nfor learning_rate in learning_rates:\n gb = Pipeline(steps = [('preprocessor', preprocessor), ('Classifier', GradientBoostingClassifier(n_estimators=30, learning_rate = learning_rate, max_features=13, max_depth = 3, random_state = 0))])\n gb.fit(x_train, y_train)\n print(\"Learning rate: \", learning_rate)\n print(\"Accuracy score (training): {0:.3f}\".format(gb.score(x_train, y_train)))\n print(\"Accuracy score (validation): {0:.3f}\".format(gb.score(x_test, y_test)))", "Learning rate: 0.05\nAccuracy score (training): 0.946\nAccuracy score (validation): 0.733\nLearning rate: 0.1\nAccuracy score (training): 0.950\nAccuracy score (validation): 0.750\nLearning rate: 0.25\nAccuracy score (training): 0.996\nAccuracy score (validation): 0.800\nLearning rate: 0.5\nAccuracy score (training): 1.000\nAccuracy score (validation): 0.767\nLearning rate: 0.75\nAccuracy score (training): 1.000\nAccuracy score (validation): 0.683\nLearning rate: 1\nAccuracy score (training): 1.000\nAccuracy score (validation): 0.750\n" ], [ "clf = Pipeline(steps = [('preprocessor', preprocessor), ('Classifier', GradientBoostingClassifier(n_estimators= 30, learning_rate = 0.25, max_features=13, max_depth = 3, random_state = 0))])", "_____no_output_____" ], [ "clf.fit(x_train,np.ravel(y_train))", "_____no_output_____" ], [ "#evaluate the models using cross-validation\n\nfrom sklearn.model_selection import cross_val_score\nscores = cross_val_score(clf, X, np.ravel(y), cv=25)\nprint(\"%0.2f accuracy with a standard deviation of %0.2f\" % (scores.mean()*100, scores.std()))\nscore = clf.score(x_test, np.ravel(y_test))\nprint('Test score (Validation): ', '{0:.4f}'.format(score*100))", "79.91 accuracy with a standard deviation of 0.14\nTest score (Validation): 80.0000\n" ], [ "#make a prediction and evaluate the performance\ny_pred = clf.predict(x_test)\n\nscore_test = clf.score(x_test, y_test)\nprint('Test score: ', score_test )", "Test score: 0.8\n" ], [ "import seaborn as sns\nfrom sklearn import metrics\n\n#confusion matrix\ncm = metrics.confusion_matrix(y_test, y_pred)\nplt.figure(figsize=(10,10))\nsns.heatmap(cm, annot=True, fmt=\".0f\", linewidths=1, square = True);\nplt.ylabel('Actual label');\nplt.xlabel('Predicted label');\nplt.title('Accuracy Score: {0}'.format(score.mean()), size = 15);", "_____no_output_____" ], [ "from sklearn import metrics\n#AUC\nmetrics.plot_roc_curve(clf, X, y)", "/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_roc_curve is deprecated; Function :func:`plot_roc_curve` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: :meth:`sklearn.metric.RocCurveDisplay.from_predictions` or :meth:`sklearn.metric.RocCurveDisplay.from_estimator`.\n warnings.warn(msg, category=FutureWarning)\n" ], [ "from sklearn.metrics import classification_report\nprint(classification_report(y_test, clf.predict(x_test)))\n", " precision recall f1-score support\n\n 0 0.77 0.94 0.85 35\n 1 0.88 0.60 0.71 25\n\n accuracy 0.80 60\n macro avg 0.82 0.77 0.78 60\nweighted avg 0.82 0.80 0.79 60\n\n" ] ], [ [ "## Death vs time\nThe boxplot below illustrates the relationship between death and how long time it was between the measurements were taken and the followup event, when the patient health was checked (female=blue, male=orange).\n\nIt is noted that short followup time is highly related to high probability of death, for both sexes. An explanation could be that severly unhealthy patients were followed up earlier, based on medical expert decisions.", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(figsize = (8, 8))\nsurvive = data.loc[(data.DEATH_EVENT == 0)].time\ndeath = data.loc[(data.DEATH_EVENT == 1)].time\nprint('time_survived = {:.1f}'.format(survive.mean()))\nprint('time_dead = {:.1f}'.format(death.mean()))\n\nsns.boxplot(data = data, x = 'DEATH_EVENT', y = 'time', hue = 'sex', width = 0.4, ax = ax, fliersize = 3, palette=sns.color_palette(\"pastel\"))\nsns.stripplot(data = data, x = 'DEATH_EVENT', y = 'time', hue = 'sex', size = 3, palette=sns.color_palette())\nax.set(xlabel = 'DEATH', ylabel = \"time [days] \", title = 'The relationship between death and time')\nplt.show()", "time_survived = 158.3\ntime_dead = 70.9\n" ], [ "# If we want to drop time as feature, we can use\nXnew = data.iloc[:,:-2].values", "_____no_output_____" ], [ "# select which features to use\n\nXnew = data.drop(columns=['DEATH_EVENT', 'time', 'sm', 'ej','age','cr','pl','se1','an','di','sex'])\ny = data.loc[:,'DEATH_EVENT'].values", "_____no_output_____" ], [ "features = ['se2','hi']\n#features_categ = ['an','di', 'hi', 'sex']\n\n#scale the dataset\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\n\nnumerical_preprocessor = StandardScaler()\n\n#do one-hot encoding for categorical features\ncategorical_preprocessor = OneHotEncoder(handle_unknown=\"ignore\")\npreprocessor = ColumnTransformer([\n #('one-hot-encoder', categorical_preprocessor, features_categ),\n ('standard-scaler', numerical_preprocessor, features)])", "_____no_output_____" ], [ "from sklearn.pipeline import Pipeline\n\n#try Random Forest\nclf = Pipeline(steps = [('preprocessor', preprocessor), ('classifier', RandomForestClassifier(n_estimators=1000,max_depth=3))])", "_____no_output_____" ], [ "#split the dataset into trainig and testing\nx_train_new, x_test_new, y_train_new, y_test_new = train_test_split(Xnew, y, test_size=0.2, random_state=42)", "_____no_output_____" ], [ "clf.fit(x_train_new, np.ravel(y_train_new))\nprint(clf.score(x_train_new,np.ravel(y_train_new)))\nprint('model score: %.3f' % clf.score(x_test_new,np.ravel(y_test_new)))", "0.7280334728033473\nmodel score: 0.617\n" ], [ "clf = RandomForestClassifier()\n\nparam_grid = {\n 'n_estimators': [100, 1000],\n 'max_depth': [3, 4, 5],\n }\n\nsearch = GridSearchCV(clf, param_grid, cv=4, verbose=1,n_jobs=-1)\n\nsearch.fit(x_train_new, np.ravel(y_train_new))\nscore = search.score(x_test_new, np.ravel(y_test_new))\nprint(\"Best CV score: {} using {}\".format(search.best_score_, search.best_params_))\nprint(\"Test accuracy: {}\".format(score))", "Fitting 4 folds for each of 6 candidates, totalling 24 fits\nBest CV score: 0.6903954802259887 using {'max_depth': 4, 'n_estimators': 100}\nTest accuracy: 0.5666666666666667\n" ], [ "randomForestModel = RandomForestClassifier(n_estimators=100,max_depth=4)\n\n#cross-val score\nscore=cross_val_score(randomForestModel, Xnew, y, cv=20)", "_____no_output_____" ], [ "randomForestModel.fit(x_train_new,np.ravel(y_train_new))\nprint('Training score: ', randomForestModel.score(x_train_new,np.ravel(y_train_new)))\nprint('Test score: ', randomForestModel.score(x_test_new,np.ravel(y_test_new)))", "Training score: 0.7364016736401674\nTest score: 0.6166666666666667\n" ] ] ]
[ "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", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0104df9d54bebe2cd7c3ecf6c4c4442fe585899
89,275
ipynb
Jupyter Notebook
modeling/modeling-1-KNN-SGD.ipynb
lucaseo/content-worth-debut-artist-classification-project
fa3924209f7ddf448d9fe1e24db8eeae75a44a88
[ "MIT" ]
null
null
null
modeling/modeling-1-KNN-SGD.ipynb
lucaseo/content-worth-debut-artist-classification-project
fa3924209f7ddf448d9fe1e24db8eeae75a44a88
[ "MIT" ]
null
null
null
modeling/modeling-1-KNN-SGD.ipynb
lucaseo/content-worth-debut-artist-classification-project
fa3924209f7ddf448d9fe1e24db8eeae75a44a88
[ "MIT" ]
null
null
null
102.733026
41,008
0.810697
[ [ [ "import pandas as pd\ndf = pd.read_csv(\"../data/df_baseline.csv\")", "_____no_output_____" ] ], [ [ "## Load Data", "_____no_output_____" ] ], [ [ "print(df.shape)\ndf.head()", "(1083, 18)\n" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1083 entries, 0 to 1082\nData columns (total 18 columns):\nlabel 1083 non-null int64\nartist 1083 non-null object\nalbum 1083 non-null object\ngenre 1083 non-null object\nsingle_count 1083 non-null int64\nfreq_billboard 1083 non-null int64\nfreq_genius 1083 non-null int64\nfreq_theSource 1083 non-null int64\nfreq_xxl 1083 non-null int64\nrating_AOTY 61 non-null float64\nrating_meta 324 non-null float64\nrating_pitch 220 non-null float64\ntwitter 1083 non-null int64\ninstagram 1083 non-null int64\nfacebook 1083 non-null int64\nspotify 1083 non-null int64\nsoundcloud 1083 non-null int64\nyoutube 1083 non-null int64\ndtypes: float64(3), int64(12), object(3)\nmemory usage: 152.4+ KB\n" ] ], [ [ "**Note**\n- 온라인매체 기사의 양, 평론가 평점은 Null Value가 있기 때문에, 당장 Decision Tree를 통해 학습을 시킬 수 없어, Feature에서 제외를 한다.", "_____no_output_____" ], [ "## Data Preparation for Modeling", "_____no_output_____" ], [ "#### 장르 `hiphop`, `R&B`, `Soul`, `Funk`, `Pop`", "_____no_output_____" ] ], [ [ "df = pd.get_dummies(df, columns=['genre'])", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ] ], [ [ "#### Split train & test data ", "_____no_output_____" ] ], [ [ "feature_names = ['single_count', 'freq_billboard',\n 'freq_genius', 'freq_theSource', 'freq_xxl',\n 'twitter', 'instagram', 'facebook',\n 'spotify', 'soundcloud', 'youtube',\n 'genre_funk', 'genre_hiphop', 'genre_pop', 'genre_rnb', 'genre_soul']\ndfX = df[feature_names].copy()\ndfy = df['label'].copy()", "_____no_output_____" ], [ "dfX.tail()", "_____no_output_____" ], [ "dfy.tail()", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(dfX, dfy, test_size=0.25, random_state=0)", "_____no_output_____" ] ], [ [ "# KNN", "_____no_output_____" ] ], [ [ "from sklearn.neighbors import KNeighborsClassifier", "_____no_output_____" ], [ "model = KNeighborsClassifier(n_neighbors=10).fit(X_train, y_train)", "_____no_output_____" ], [ "from sklearn.metrics import confusion_matrix", "_____no_output_____" ], [ "confusion_matrix(y_test, model.predict(X_test))", "_____no_output_____" ], [ "from sklearn.metrics import classification_report", "_____no_output_____" ], [ "print(classification_report(y_test, model.predict(X_test)))", " precision recall f1-score support\n\n 0 0.85 0.97 0.91 210\n 1 0.79 0.43 0.55 61\n\navg / total 0.84 0.85 0.83 271\n\n" ], [ "from sklearn.metrics import roc_curve\nimport matplotlib.pyplot as plt\n\nfpr, tpr, thresholds = roc_curve(y_test, model.predict_proba(X_test)[:, 1])\n\nplt.plot(fpr, tpr, label=\"KNN\")\nplt.legend()\nplt.plot([0, 1], [0, 1], 'k--', label=\"random guess\")\nplt.xlabel('False Positive Rate (Fall-Out)')\nplt.ylabel('True Positive Rate (Recall)')\nplt.title('Receiver operating characteristic example')\nplt.show()", "_____no_output_____" ], [ "from sklearn.metrics import auc\nauc(fpr, tpr)", "_____no_output_____" ] ], [ [ "# SGD", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import SGDClassifier", "_____no_output_____" ], [ "model_SGD = SGDClassifier(random_state=0).fit(X_train, y_train)", "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/linear_model/stochastic_gradient.py:128: FutureWarning: max_iter and tol parameters have been added in <class 'sklearn.linear_model.stochastic_gradient.SGDClassifier'> in 0.19. If both are left unset, they default to max_iter=5 and tol=None. If tol is not None, max_iter defaults to max_iter=1000. From 0.21, default max_iter will be 1000, and default tol will be 1e-3.\n \"and default tol will be 1e-3.\" % type(self), FutureWarning)\n" ], [ "confusion_matrix(y_train, model_SGD.predict(X_train))", "_____no_output_____" ], [ "confusion_matrix(y_test, model_SGD.predict(X_test))", "_____no_output_____" ], [ "print(classification_report(y_test, model_SGD.predict(X_test)))", " precision recall f1-score support\n\n 0 0.94 0.40 0.57 210\n 1 0.31 0.92 0.46 61\n\navg / total 0.80 0.52 0.54 271\n\n" ], [ "fpr, tpr, thresholds = roc_curve(y_test, model_SGD.predict(X_test))", "_____no_output_____" ], [ "plt.figure(figsize=(10, 10))\n\nplt.plot(fpr, tpr, label=\"roc curve\")\nplt.legend()\nplt.plot([0, 1], [0, 1], 'k--', label=\"random guess\")\nplt.xlabel('False Positive Rate (Fall-Out)')\nplt.ylabel('True Positive Rate (Recall)')\nplt.title('Receiver operating characteristic example')\nplt.show()", "_____no_output_____" ], [ "auc(fpr, tpr)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0105412e27d0ed232116837433cdc6244d5dea3
145,967
ipynb
Jupyter Notebook
demo/IHaskell.ipynb
rpglover64/IHaskell
4968a2838e9fce7559903520f0cb3c7028fdbeae
[ "MIT" ]
1
2016-12-25T11:24:37.000Z
2016-12-25T11:24:37.000Z
demo/IHaskell.ipynb
wellposed/IHaskell
e6affe2699b97ece1b65719105324e4d301d962f
[ "MIT" ]
null
null
null
demo/IHaskell.ipynb
wellposed/IHaskell
e6affe2699b97ece1b65719105324e4d301d962f
[ "MIT" ]
null
null
null
102.721323
18,521
0.75217
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d010598126498ec894fb28fd1d12a823070b7c5c
8,247
ipynb
Jupyter Notebook
concepts/lifesupport/vasopressors_inotropes.ipynb
AKI-Group-ukmuenster/AmsterdamUMCdb
5541e908181526e184ce17d78c0da371ea2b9d00
[ "MIT" ]
79
2019-11-18T08:43:37.000Z
2021-12-23T09:21:14.000Z
concepts/lifesupport/vasopressors_inotropes.ipynb
AKI-Group-ukmuenster/AmsterdamUMCdb
5541e908181526e184ce17d78c0da371ea2b9d00
[ "MIT" ]
45
2020-01-28T09:27:13.000Z
2022-03-29T13:19:00.000Z
concepts/lifesupport/vasopressors_inotropes.ipynb
AKI-Group-ukmuenster/AmsterdamUMCdb
5541e908181526e184ce17d78c0da371ea2b9d00
[ "MIT" ]
24
2019-11-19T04:23:39.000Z
2022-01-20T09:52:03.000Z
29.880435
151
0.475688
[ [ [ "<img src=\"../../img/logo_amds.png\" alt=\"Logo\" style=\"width: 128px;\"/>\n\n# AmsterdamUMCdb - Freely Accessible ICU Database\n\nversion 1.0.2 March 2020 \nCopyright &copy; 2003-2020 Amsterdam UMC - Amsterdam Medical Data Science", "_____no_output_____" ], [ "# Vasopressors and inotropes\nShows medication for artificially increasing blood pressure (vasopressors) or stimulating heart function (inotropes), if any, a patient received.", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport amsterdamumcdb\nimport psycopg2\nimport pandas as pd\nimport numpy as np\nimport re\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport matplotlib as mpl\n\nimport io\nfrom IPython.display import display, HTML, Markdown", "_____no_output_____" ] ], [ [ "## Display settings", "_____no_output_____" ] ], [ [ "#matplotlib settings for image size\n#needs to be in a different cell from %matplotlib inline\nplt.style.use('seaborn-darkgrid')\nplt.rcParams[\"figure.dpi\"] = 288\nplt.rcParams[\"figure.figsize\"] = [16, 12]\nplt.rcParams[\"font.size\"] = 12\n\npd.options.display.max_columns = None\npd.options.display.max_rows = None\npd.options.display.max_colwidth = 1000", "_____no_output_____" ] ], [ [ "## Connection settings", "_____no_output_____" ] ], [ [ "#Modify config.ini in the root folder of the repository to change the settings to connect to your postgreSQL database\nimport configparser\nimport os\nconfig = configparser.ConfigParser()\n\nif os.path.isfile('../../config.ini'):\n config.read('../../config.ini')\nelse:\n config.read('../../config.SAMPLE.ini')\n\n#Open a connection to the postgres database:\ncon = psycopg2.connect(database=config['psycopg2']['database'], \n user=config['psycopg2']['username'], password=config['psycopg2']['password'], \n host=config['psycopg2']['host'], port=config['psycopg2']['port'])\ncon.set_client_encoding('WIN1252') #Uses code page for Dutch accented characters.\ncon.set_session(autocommit=True)\n\ncursor = con.cursor()\ncursor.execute('SET SCHEMA \\'amsterdamumcdb\\''); #set search_path to amsterdamumcdb schema", "_____no_output_____" ] ], [ [ "## Vasopressors and inotropes\nfrom drugitems", "_____no_output_____" ] ], [ [ "sql_vaso_ino = \"\"\"\nWITH vasopressor_inotropes AS (\n SELECT\n admissionid,\n CASE \n WHEN COUNT(*) > 0 THEN TRUE\n ELSE FALSE\n END AS vasopressors_inotropes_bool,\n STRING_AGG(DISTINCT item, '; ') AS vasopressors_inotropes_given\n FROM drugitems\n WHERE \n ordercategoryid = 65 -- continuous i.v. perfusor\n AND itemid IN (\n 6818, -- Adrenaline (Epinefrine)\n 7135, -- Isoprenaline (Isuprel)\n 7178, -- Dobutamine (Dobutrex)\n 7179, -- Dopamine (Inotropin)\n 7196, -- Enoximon (Perfan)\n 7229, -- Noradrenaline (Norepinefrine)\n 12467, -- Terlipressine (Glypressin)\n 13490, -- Methyleenblauw IV (Methylthionide cloride)\n 19929 -- Fenylefrine\n )\n AND rate > 0.1\n GROUP BY admissionid\n)\nSELECT\n a.admissionid, location, \n CASE \n WHEN vi.vasopressors_inotropes_bool Then TRUE\n ELSE FALSE\n END AS vasopressors_inotropes_bool,\n vasopressors_inotropes_given\nFROM admissions a\nLEFT JOIN vasopressor_inotropes vi ON\n a.admissionid = vi.admissionid\n\"\"\"\nvaso_ino = pd.read_sql(sql_vaso_ino,con)\nvaso_ino.tail()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01068fb23c6c7da3a18e3e058f018d071a86855
73,781
ipynb
Jupyter Notebook
notebooks/process/masstransferMeOH.ipynb
EvenSol/NeqSim-Colab
261e4444c2c9ebbd296d118412c67582cf8cecd7
[ "Apache-2.0" ]
10
2020-10-06T23:03:36.000Z
2022-03-09T03:28:12.000Z
notebooks/process/masstransferMeOH.ipynb
EvenSol/NeqSim-Colab
261e4444c2c9ebbd296d118412c67582cf8cecd7
[ "Apache-2.0" ]
1
2020-02-25T09:33:08.000Z
2020-02-25T09:33:08.000Z
notebooks/process/masstransferMeOH.ipynb
EvenSol/NeqSim-Colab
261e4444c2c9ebbd296d118412c67582cf8cecd7
[ "Apache-2.0" ]
1
2021-02-22T10:31:17.000Z
2021-02-22T10:31:17.000Z
211.406877
38,857
0.834104
[ [ [ "<a href=\"https://colab.research.google.com/github/EvenSol/NeqSim-Colab/blob/master/notebooks/process/masstransferMeOH.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "#@title Calculation of mass transfer and hydrate inhibition of a wet gas by injection of methanol\n#@markdown Demonstration of mass transfer calculation using the NeqSim software in Python\n#@markdown <br><br>This document is part of the module [\"Introduction to Gas Processing using NeqSim in Colab\"](https://colab.research.google.com/github/EvenSol/NeqSim-Colab/blob/master/notebooks/examples_of_NeqSim_in_Colab.ipynb#scrollTo=_eRtkQnHpL70).\n%%capture\n!pip install neqsim\nimport neqsim\nfrom neqsim.thermo.thermoTools import *\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom neqsim.thermo import fluid, fluid_df\nimport pandas as pd\nfrom neqsim.process import gasscrubber, clearProcess, run,nequnit, phasemixer, splitter, clearProcess, stream, valve, separator, compressor, runProcess, viewProcess, heater,saturator, mixer\n\nplt.style.use('classic')\n%matplotlib inline", "_____no_output_____" ] ], [ [ "#Mass transfer calculations\nModel for mass transfer calculation in NeqSim based on Solbraa (2002):\n\nhttps://ntnuopen.ntnu.no/ntnu-xmlui/handle/11250/231326", "_____no_output_____" ], [ "In the following calculations we assume a water saturated gas the is mixed with pure liquid methanol. These phases are not in equiibrium when they enter the pipeline. When the gas and methanol liquid comes in contact in the pipeline, methanol will vaporize into the gas, and water (and other comonents from the gas) will be absorbed into the liquid methanol. The focus of the following calculations will be to evaluate the mass transfer as function of contanct length with gas and methanol. It also evaluates the hydrate temperature of the gas leaving the pipe section.\n\n\n\n\n", "_____no_output_____" ], [ "Figure 1 Illustration of mass transfer process\n\n![masstransfer.GIF](data:image/gif;base64,R0lGODlh3wmIAvcAAAAAAAAAMwAAZgAAmQAAzAAA/wArAAArMwArZgArmQArzAAr/wBVAABVMwBVZgBVmQBVzABV/wCAAACAMwCAZgCAmQCAzACA/wCqAACqMwCqZgCqmQCqzACq/wDVAADVMwDVZgDVmQDVzADV/wD/AAD/MwD/ZgD/mQD/zAD//zMAADMAMzMAZjMAmTMAzDMA/zMrADMrMzMrZjMrmTMrzDMr/zNVADNVMzNVZjNVmTNVzDNV/zOAADOAMzOAZjOAmTOAzDOA/zOqADOqMzOqZjOqmTOqzDOq/zPVADPVMzPVZjPVmTPVzDPV/zP/ADP/MzP/ZjP/mTP/zDP//2YAAGYAM2YAZmYAmWYAzGYA/2YrAGYrM2YrZmYrmWYrzGYr/2ZVAGZVM2ZVZmZVmWZVzGZV/2aAAGaAM2aAZmaAmWaAzGaA/2aqAGaqM2aqZmaqmWaqzGaq/2bVAGbVM2bVZmbVmWbVzGbV/2b/AGb/M2b/Zmb/mWb/zGb//5kAAJkAM5kAZpkAmZkAzJkA/5krAJkrM5krZpkrmZkrzJkr/5lVAJlVM5lVZplVmZlVzJlV/5mAAJmAM5mAZpmAmZmAzJmA/5mqAJmqM5mqZpmqmZmqzJmq/5nVAJnVM5nVZpnVmZnVzJnV/5n/AJn/M5n/Zpn/mZn/zJn//8wAAMwAM8wAZswAmcwAzMwA/8wrAMwrM8wrZswrmcwrzMwr/8xVAMxVM8xVZsxVmcxVzMxV/8yAAMyAM8yAZsyAmcyAzMyA/8yqAMyqM8yqZsyqmcyqzMyq/8zVAMzVM8zVZszVmczVzMzV/8z/AMz/M8z/Zsz/mcz/zMz///8AAP8AM/8AZv8Amf8AzP8A//8rAP8rM/8rZv8rmf8rzP8r//9VAP9VM/9VZv9Vmf9VzP9V//+AAP+AM/+AZv+Amf+AzP+A//+qAP+qM/+qZv+qmf+qzP+q///VAP/VM//VZv/Vmf/VzP/V////AP//M///Zv//mf//zP///wAAAAAAAAAAAAAAACH5BAEAAPwALAAAAADfCYgCAAifAPcJHEiwoMGDCBMqXMiwocOHECNKnEixosWLGDNq3Mixo8ePIEOKHEmypMmTKFOqXMmypcuXMGPKnEmzps2bOHPq3Mmzp8+fQIMKHUq0qNGjSJMqXcq0qdOnUKNKnUq1qtWrWLNq3cq1q9evYMOKHUu2rNmzaNOqXcu2rdu3cOPKnUu3rt27ePPq3cu3r9+/gAMLHky4sOHDiBMrXsy4Q7Hjx5AjS55MubLly5gza97MubPnz6BDix5NurTp06hTq17NurXr17Bjy55Nu7bt27hz697Nu7fv38CDCx9OvLjx48gykytfzry58+fQo0ufTr269evYs2vfzr279+/gw4sfT768+fPo06tfz769+/fw48ufT78vvv37+PPr38+/v///AAYo4IAEFmjggQgmqOCCDDbo4IMQRijhhBRWaOGFGGao4YYqHHbo4YcghijiiCSWaOKJKKao4oostujiizDGKOOMNNZo44045qjjjjz2Jujjj0AGKeSQRBZp5JFIJqnkkkw26eSTUEYp5ZRUVmnllVhmqeWWI1x26eWXYIYp5phklmnmmWimqeaabLbp5ptwxinnnHTWaeedIHjmqeeefPbp55+ABirooIQWauihiCaq6KKMNuroo5BGHyrppJRWaumlmGaq6aacdurpp6CGKuqopJZq6qmopqod6qqsturqq7DGKuustNZq66245qrrrrz26uuvwAYcK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttRrYZqvtttx26+234IYr7rjklmvuueimq+667Bm26+678MYr77z01mvvvfjmq+++/Pbr778AGAcs8MAEF2zwwQgnrPDCDDfs8MMQRyzxxBcUV2zxxRhnrPHGHHfs8ccghyzyyCSXbBfyySinrPLKLLfs8sswxyzzzDTXbPPNOBXnrPPOPPfs889ABy300EQXbfTRSCcVrfTSTDft9NNQRy311FRXbfXVWGetFvXWXHft9ddghy322GSXbfbZaKet9toUbLft9ttwxy333HTXbffdeOet994UfPft99+ABy744IQXbvjhiCeu+OISjDfu+OOQRy755JRXbvnlmGeuE/nmnHfu+eeghy766KSXbvrpqKcTrvrqrLfu+uuwxy777LTXbvvtuKrnXqcyAPSuDEk39D7JVLz73lHxAPxOUfAA3ODSJMw3P7yCxNwQ/STKo9Q7ALp3X/Mk208fEjHhTwW+8B2dD4D4Em3PPUvRu5+9gci773xK5Xuv/8vqozES8/dDyiTQwL6B9C992/MfRdwHP/e5r4ADIp8Dt6cS9e3vgsGK3lnQkL+QdNAo1zMIB9HHkRGuryIMVIkEhacMYmQiBvMjUPRugD0XxkAlyIMgBqF3aKsUlkV9OtyIBZMSP4MAEYEknIgPUaK+GCZoewF0yRJ5SEVaTXEqGlSI+jIhEigqJQZeLMgWkQgALi6Qgiq5Ymly6JUjwqSJVYzjrNQYleg5kSCZSGBI3IgU5BHDIHnsnQI3EkgADLJ9aMRfIlGzwihqhY8uQd4h5UjJVdERKmDs3R8TYsIgZiSLVOlkR0R5xt7hMIypQZ4js2JHmVyykv+wFNUrnSKG7d3RgB/sCCrNl0uMQDIis/zICm+ommF6JXqbfOP2khnLZo4qmEzJJACYacReauSXUSGlEK3pEGgeb3tiWA3ywtkVad7ylL0zozPXCSpvKqWVCTngR7AJFXluU5AoXKRJGrkafnallpqciTvZSdBHDZQgxFBf82LgSYEwT3wJhSIxGVI9aU6wd85b4UWXSRATqhMNM6RmRECpxRtYlIYiVZ9IDdJL6J10EisdyAqdOEaEgPSlMRWIRwcCUijCVCGzVIZCTdrQeG6Ujje1308V8lCBEMOEq0zICjt6PSdW74HnlGlPJVpUp5oQow3daviyWpD4bdSRTd0kx1N36dX4EXUhaVUrVCeqkLUqtSBHtaZdMcrQhWRyenuNKjIL/0rYTB1UrWa1X071eNWLRpUgiT3qPhR61PkV0n+UdV9OF/LKxh7VkfVbiD09e9aEXBaQeiwIaR1rWj1m1pYJueRq3QfDkeY1oAiNLBQXi8/6JXEhhXToRumq25y+1oGb1a0pDeJbB04ytrcFAF33ocfmiu+4moWuIRFb2oQo9337aO4EHTnb3WrXf9atpvEKy15KHVS8E7zlWG/72H1YlL7hjS54dRq+7yZPIv5EiH6bh1fYeneRA36sNnnaywTbtL+3jSkd4YtciNz3ovPzr4FZysKLdpW/pryw/dR62zt+Na+39G8MNcrahmi4gPOd4PROXFkBdzivjxVxdkmMX/+Z6le+N3YgBOnZ3iIraqAavUH2oLfjAjfPfZkghlArbJAZiq9+Sk5mC7Es5S6L0bE1jN90G1LIhip1y5Rlnz3VS+CBnFnKaT4INrH55ik/UM4XjUGU7bxhgqhRo7UVCJP7TFFlxK/LLSRImvc8aI5y+MnhYzJZcdk7gEqPz8KDMpwdiOexwtmsnW7e/JhMzTsPZMpjTkgLD71lKTs5fpOQtKCx+mlOHwSKmsb0NNmsZEUHL3tbtl+rCYLlJR/61hh9oKwLokojO7tRA5XfQWaI7BGXla0CAWe19wtZQn/ZgTGs36QLsmCW0hAhRTz1JUPo5nNPW43YLDd13V1leMdMl9nWdjK3s+3tfVA7IgFWbb4ROnA3O7C+CznxDUo9Xnw7uqPru2P9IOhNeVOk2UA9OELAh72DTHzbGK13yPUNkcFu+47/1vfI63rYZ/+7/E7uJLK/9cnvhyv6ivT047txu/GCGxyfJU9tKbndZJJDxN5Av3nSH4L0lTuc5z/ft8xJ6hCMi7zNHi96zZ0ekaFm3eeTFfpD1lxzhCv9vxkJOMjNrkWxR33XbN43tpna76nTnLpg3/bL914od76SztzE+3K7PXiBp/Mg5lTIV43624YkviLwnPXheW3b9UK88WGffNAtz2Cu65viNP974BGyQnI+et/XxnzeHaJQ7WL96WxnLra13RCVamScnJ37Q6zu58BfkfYOkeZKRa963eud78gHlDd5X+1VvtLkA6F677drEEtvVubMZ4j1LWL76aOe3WO3uUBOWxDyQ6Sw+2dvqPqcr8/svzoiyEv1+hei0dNvliF2h/r7ESndq99fIO43EcaUcfrHf6n2fOIHfdrnbQH4c+xXgK73f8k3gXDiTStUVLN3dwPxeBuogYKnQxx4EBbnVMaHECEoEXCUfo8We9+GdpdXRiI0ej3HeSB2Qqr2e/p0gbn3eg2hdsKFeacXhBYxgvbVb1unRJUWd7EHbhjRgEd4EcDnfQpxgl7neOLHYzaoXQ+Ieq43bhT/+IVr4k3YdVRj9kqFRE0p2II6pICotXSPlmp0B4FyFgPKRU2hpYLxRIdHlVItNXqToIcbxYduaHiF94SUNmC9A4c36HkzJ4fex3CFKBHmV31XGHUKIVTKJVgH11DNhQYSSHrbo4iGyBCY+FnHhxBneHVgBVfeNobDJYTdVIlgOIttUnGIGIWjyGbhhm13eHVZJXOCZ3oOEXmkp2EuGHUZpoHldW9qGINAuIxM2IwEKHf6RGPRJYw9iIsCcYInZ3QVQYTE6I3kpl851mIHwWJGuBC4N40NYY0NB4uhdkciVl9suA/umFfYKHhcaGM0SIv+GIYe2IKIKFLEB3eE1zzJ0VSFlOiImZeF1SaKB7F9i6hfgkh9Zfd1FMlmz0V2+TVgIlVmO0iNheiKF/WJ6paI2/Z/WtdyeIh4sqiPOxddohhZOSVeEHmOJQiTrKhfBxiQ6KeKlWhpNHWLBRhtAfmPSDkmtgiEsRiJLziUPeaS/fiC6tR8EcGNPuZTMZSGJzl42JRkHXd2TiRvvwSWW+ltO8WO4tiQHyaAcxeOp2iJ3Lc9VZl6x7iWRehpTpaPRmRWWeVCGgcRTqiTCWFRNbSXcemMd9mX0UgQwqeYbZmYIZmU/5SZJt4EkkPXdvqHjhM0k3SpmRZplZsXmnb5WD8ZdZskfY3Ig4dYkc81iatpmlfIkcSWgYWImR4RfxH5knIphXM5iAMhkYkpbvx4k06VbqJlag4xgK53idL2kJJ5dhJIWr7Yhg4JTEeJl5W5nV9igTmpljN4lwA0WVbGEFjZedfpZFzQdb7ngSZ0RzU1d5f0nopZl/b4mb4pgmg5elAFj1jIggCmjfepeeG5hRdBhOdJmJKXng44mhI4mE/Hl/kZap4knz6Zjv5XEI9JiADqnyzHiNwZolrid9nZnK2lf7ypEMJJoQTYoQ35XL1pnfbZkaZET5eUiuXXh413o7NZgpmWBnqRyJKkOHe9iG4NVqKgCaM/aJD+SZsXGX5TCZ0PwZz8uI8vqoXRORA4WnuEJpRZ2hDupJsiOqZc4k4ph51OiZ7zM1PLg6HA+J0RaqIG4Vm3ZE7SVKXF2Iq9VG50RKdK+GB3d0VnuhE+uHWeVH8eGhEImo5TNILqs55QyqQEKKEIMZiv5KjbA6naqaaRSk31GJuZ6RBpSab/pHolRomSM/ilDQmJksp6JQibTmacm6qPIuVbMaVKuqd1NEqgC7qRbqervmWfmUVNSRadtMV4EiGmcQejH5eoEIGbC9mqMdqQmshW0KNDRWpIKxU9ShqB4Blq1cqIBclM14qR+3aex5qqzhqTkVmq7mokD0RAAzSvBIQGo7aJW0ZAanSphEZhJiUGnihViqUMIMVMRBiM/LeYCxpxx8mMIJemDcmw3NWY6DlkuaRQYTlbY+lhypAJjZamTQdW+dp6ACegSyo8xPAJT+VWePqbMGikUaqgW+duUvaO6IlSLfRV7ENrBGtREgFrOetIs3RXatVcUcWvnAdVMJWzyhl93rJIWTQ0svuKpHlppe96tUiCiNNljKwpsy1YkbelpDV2iN0qeLIqnQeGYy8JtXH4WT06iNjkX/V4hv4lYRrItS5Ko54ZXfUlpL2attKai7t6Vqh6iKbofWN7fq84oeZKuP23rqt6dodbEF4Ks3yrqrOKtZpbJIiYj9DIlAW5YrcYVfA1jry6f4I5eso1POnoW0W1uoK3sZg3qgcpY7GrmCcrbHI6p/7Vrlqak65oZlQLqAy6jYx6d5yJUREFAPn4XatEYTG7k0KWuSR4VsvLl6Frl+aoobz5ucXrnSC6uf/iKyTQm3eTIAZuFZYwi3BbOrOtJlSxRmVKWEA6h6UJq45DJT5HOX+kmL8/h5FOVL/M5b8193UBxGfW87rhK2joe2YWEVeq9rHo21XjaRHIc07ng3DG97FheT7Y+rF6ZlwKNcEXQVrq+4MsyMHK48E7x75XWIqhGGUTWXsNrJVxyILQOr46XCg0tMDBw3E6wZUFc6c7XMQ+4g4DYQ5JvMQCcQ5MvA9KLBBRvA9OLMVPPMVYfMVaHF6vwEFQrMVS1sXOk8VWXMZfbMZkfMZqPMVIrI5uNxBtvA9xPMdwPBDtYMd1LBB0rMd5LMd9vMd+zMeCHMiEDMiG/MeIPMiHrMj/iVzIjRzHSnHH+0APbewObdwObUzJAqHJ+4DJAuHJk1zJbTwPmVzKm2zK+0DKeozKnMzJqjzJktzKojzIpAGnRnzLLmIOTpwN56DEvOzLvbwP2aDLwhzMv1zMvkzMx7zMxtzMwPzMyBzNqEAFtbAMzKzE39DL0TDN1XzN0ezN4OzM32zMTblf7pANUPwN6GwO6pzO69zO7PzO8uzO9BzP9QzP+DzP9rzP+XzP+tzP/PzPAu3PBB3QBQ3QAD3FSvENlpwNDD0P6kzJ38DQ7eDQ7kAPFo3RDE0PEV3RGx3R5/zQFu0OHW3R8zDSID3R7uDRF23R7QDSLg3TFN3RKv3SBKZxsLj/nNO5nA30QMU87dM9fQ4/bQ4/LdRBXdRDjdRHvdRA3dRG7dRIrQIA4AeoMAxOzdBULA1STQXYgMRP/dVKDdVMDdZBjdVPzaVQRw/S4MRqzdZrPclv3dZw7dZ0Pdd2Ldd4Hdd6Xdd5zdd7fdd/3deA7deEPdiGLdiIHdhv7RQOLRDtvA+P3diQjc6T7diULdmR/Q2WLRCSjdmXrdmVLcygndmcDdqdbdqj/dmnYWk63do20tObPBCwPcmyXduxfdu0jduzHcezvdu2nduTfD5SjT1WrccECwBSzby8/du9zdy/vdyDPNtDypT/IoOufd1twrVdexOq+S/djd3g7SYkCVm8N8GmBGPd4SCd3mcCv2aVwELBPGWrLxKUt+pd3/Z93/id3/q93/zd3xP+/d8AHuACPuAEXuAGfuAInuAKFL7gDN7gDv7gEB7hEj7hFF7hFn7hEhie4Rq+4Rze4R7+4SAe4iI+4hIkXuImfuIonuIqvuIs3uIu/uISMB7jMj7jNF7jNn7jOJ7jOr7jKDze4z7+40Ce3l4Y5KShCTqgCUSuN0aO5Em+GpoABFDO5E1uN5sA5UdmPuWm8eQ6AAQ6oAZSjuVzowlqkANqEOVgDhpGDgRk8ANqsOVffuZw8+RcPuZc/uZwXhlaXuZA0OZsvgl3LjdPTgZQLuhtDgR2/ueOkeZrDgRjMOdcDgqIDjeboAY/0OWVDgRpsOVX/x7pjZHnP7Dnmk7pXX7onH42oLDlhZ7qXW7mpX4YyhDqc47qlV7mmg4EOcDlt64Dla7rW54DvY7rXL7rl+7rtg7svM7rtv7rOpDrwt7rys7sOoDsxJ7r0C7tzx7s0T7s137s2l7sy47t1u7t1d7t1A7u5G7szZ7s4m7uzr7u3N7u5f7u6h7v6T7t6J7t8H7v4U7v+D7v+n7u3y7v9h7w9b7tBe/uB8/v+/7v+U7w/T7w497wEe/vDr/wFQ/wEw/x7E7xGW/wD+/xFt/xCP/xIx/yG6/xAg/yGH/yKi/xLF/yK5/yMO/yMq/wMZ/wDM/xL2/zNI/zF9/zJM/zOl/zOYaP8j4v8kJv9EFf9C0/9Ee/80w/806/9D8/9SZP9FWv9Ff/9FiP9FGf9E2v9TdP9V6f9WF/9lIv9kC/9WQP9Waf9mgP9nA/96FO5rrO53yu5lwOBEPe6nhRDJ++5pa+6qtukn7PNXIO6opf5mRO6ocfGHKu6mx+647/+GAj5jqQ6Zi+5Zpv+EaWvxfFcOt0nup+/vlmg/mDnvqVb/qD8eSFruY/sPqsrzVVnumi7uWz/xhizuhQXvq5HzavbuWG/vuR4fo60PfEHzWunwPLGpD8k/Hksu/8UwP90l8ZzV/92J/92r/93N/9Et7//eAf/uI//uRf/uZ//uif/hDqv/7s3/7u//7wH//yP//0V1//9n//+J//+r///N//ALFP4ECCBQ0eRJhQ4UKGDR0+hBhR4kSKFS1exJhR40aOHT1+BBlS5EiSJU2eRJlS5UqWLV2+hBlT5kyaNW3exJlT506ePX3+BGYaVOhQokWNHkWaVOlSpk2dPoUaVepUqlWtXsWaVetWrl29fgUbVuxYsmXNnkWbVu1atm3dvoUbV+5cunXt3sWbV+9evn39/gUcWPBgwoUNH0acWPFixo0dP4YcWfJkypUtX8acWfM+Zs6dPX8GHVr0aNKlTZ9GnVr1atatXb+GHVv2bNq1bd/GnVv3bt69ff8GHlz4cOLFjR9Hnlz5cubNnT+HHl0y+nTq1a1fx55d+3bu3b1/Bx9e/Hjy5c2fR59e/Xr27d2/hx9f/nz69e3fx59f/37+/f0u/wcwQAEHJLBAAw9EMEEFF2SwQQcfhDBCCSeksEILL8QwQw035LBDDz8EMUQRRygksUQTT0QxRRVXZLFFF1+EMUYZZ6SxRhtvxDFHHXfksUcffwQySCGHJSSySCOPRDJJJZdkskknn4QySimnpLJKK6/EMkstt+SySy+/BDMjTDHHJLNMM89EM00112SzTTffhDNOOeeks04778QzTz335LMgTz//BDRQQQcltFBDD0U0UUUXZbRRRx+FNFJJJ6W0UkseL8U0U0035bRTTz8FNVRRRyW1VFNPRTVVVVdltVVXHF+FNVZZZ6W1VltvxTVXXXfltVdffwU2WGGHJbYcWGOPRTZZZZdltllnn4U2WmmnpbZaa6/FNltttxrltltvvwU3XHHHJbdcc89FN11112W3XXffhRk3Xnnnpbdee+/FN1999+W3X3//BThggQcmGLhggw9GOGGFF2a4YYcfhjhiiSemuGKLLxbGOGONN+a4Y48/BjlkkUcmuWSTT0Y5F2WVV2a5ZZdfhjlmmWemuWabb8Y5Z513Fua5Z59/BjpooYcmumijj0Y6aaWXZroWaaefhjpqqaemumqrr8Y6a6235rprrxS/Bjtssccmu2yzz0Y7bbXXZrtttxTfhjtuueemu26778Y7b7335rtvvxT/BjxwwQcnvHDDD0c8ccUXZ7xxx/8fhzxyycF2IAccHsAhh8ovz3xzzDW3/HPPOw+ddM5BP3101EUvfXXTWU+9ddVnl7322G+HPffXd3e9d9px5/133X23fXjhgy8eeeCJX/545o1P/nnloW8+euevtz776renvvvpv5c+fOy5B39878XX/nzzy0+fffLRf399+NVvf3736Y+/fvn317///P/HXwDvN0D7FZB/ACTgAQVoQP8tUIEJbCAEEcjACT6Qgg6MYA4mZ6Qc5GAGHfygB0E4QhGWMIQnJCEKTZhCFq7QhSqEYQtj+EIZ1pCGN5xhDm2oQxzu0Ic9BCIPhfjDIQaRiEc0YhKLuEQkMlGJTYTiE6W66EQqRrGKU7RiFrG4xSt2UYte5OIXxRhGMoLRjGM8YxnRuEY1tjGNb2QjHN0YRzrO0Y5yxGMdr5iADRbJch3M3B8FGUhCAtKQgzxkIRG5SEU2MpGPZCQkHRlJSk7SkpLEZCUzeUlNdpKTn9xkKD0pSlCO0pSlRCUpVXnKVaaSla90ZSxbOUtY0lKWtcTlLXVpS17mspe79GUwgTnMXxZTmMYk5jGVmUxmItOZy3xmM6E5TWlWM5rXpGYxLftIpA5qcJvflA4gwRkkBHRwnOdsTjfR6SNxrtOdxsmBDB7wzh11cJ70xCdw1CiZzxv9kZ//3M0DLAfQGomQoAetTSARKiPOLdShrwHhQ1+0T4lW9DShOLMoi2aQuYx2dDTt9OiJBOrNkJZ0MyE0qYlAmlKWUgZ0CSEGAGSaiZZWKHMzqGlOI0NRg6BBpgCYs4ROJWRPoRZ1MZmTQUIm8VM0LAUNk2jqVp4a1cgQ46k0NVzmcGBUriYFDTG4wU8BEINJEIMmORBoQnwq06AmJQY/bStW3srWyGRCrP6K6UwJg9Ku9jUoypirWAULADSYFSb+RMhS6ZqUsP5UK42VaWSUIVaqHuirPyUrQeYaA6fYdbCVTQxkJeJZABj2JYHFbE1G6lfW9gS1g/0sTPh6EMUCAKtICewNtJJbwZAWtAXJq0yV/5Gg1+pVIHdtSm3FylnG/FS3Eantb1cC29LSRKutxe5NgivWG0zCu5OA7E9NyxKBbhUhvlXKZGU6Xquot7qBcS9zE9JY+RoovGK9LXKZslbB3jYxgY3rQ/gb4JYo96fDnUlEs7vgmGwXAN1FiDJqS2CVKBQhA4ZRcMWwnExMArU3iIF0d7LdTBBDwjcwrX6XUlsEH8TB9YUIf8e6kA5/OMQzAS9qJ+HfiKj4IdGtSW3Z+xKMMtjILHHvYhWijLCK+CQd5GNimQqj+CZHxtTNrE/422KD+DgpQlbrYJ8LEQcDFSHEuO9gYayS4gp2yAzBsERqy2OYbPms5jxynlGCWg0uL+TNKUHsQeLsouCO/5k4ZaauTG9A55t4mSCOPgqLlQpbicBWuogWc0swPVhGK0QMjp3IhGtC2k6z5IPm1XOqRaJcCu9kpQUR9Yvca2jhtNm7T73Bp8W6YZ5A+rig3q94wzzYVsMUthQmLVuVYWLw6prWKAlvd5edbOFCxLkUGbRMJD2TypFU1d/uCGSfbRGrohasxQbulbNMEBngmbZwXchlMbvjhnw1vGSlM3///GiZVja4QyYtQeQ91j6fF6yJlumaFRLwgQycsPv+t0EYLhCHF9YhHV4uhC+C8eVKAs7mloQmBAxykQ+kzYKF8VzHTZAaZxzdApn4PgYeg4IH5r6TqPk+wAvsnMxaIf++Lsq2381WoEscrlMuCGlvUHPwvnwkjW11eJ1skFiPFuk4FnaC3Q1urmdErPuGLsLXq5A0+5ioUu73sKnrZMCKHcbbXUjVdX71gdSW4oku9T7KTl2I2F3miR4G2glLdVBfWayBVwiaE73oiuw9shdG+NQFcvKED0Tsii4I0A0cW8Hfnbp518uHc04QxfKk0D/nuVL0PWm2QtbpAyHtJNwA78xn3SbgJXvRCSJabNN+JnZOMA5w2nXiW4S/K5eI4an7Z8qPfSCfU3unm4/5g1ye+pa3/UECWxD+5tuxjne+QabP3Rh/X+xpEPRPvR9Z8AMA/ee1PtgTMv03jx/5+xgRf1vbb2Z+P97o1le4v2M/sZP/v7tIsvsziAKEiSpLCN0TCqH7P6DyuYZgMSAjCLgjCuV6iGujCAvEuvCLibMrvhGMCF3jP4xgtWU7McEaOoIjvbDiMp6CNbobiPCKKwlbrupzLpxjNsEKMA8kvOsTCCAcQufawWWLtoMQtxvkrmULO0XDrBLDwcMLwsGbQShMOCk0MMQriCSjuboLL9Crwi8EQwAABYOwwYGYwspTwuWSQmJQOjVUPPFSQROrPf+7wyxkNgNTuNpaQiQkv8BgwabQMNTDQ9XLPu6DN95jiLuSu32YwKHAQDjzPTmrxJgAPpm4LhLkRIcQq9dzCJ/CORf7xC5LvYQQPlTrqUsUwAc7/4gkG7IHK7bwIogkm69LfMS5E6w+265YlCley8NQG6w+SzIAWEUlq7th7MJBzMOaE7ceO0W1GzdYPMZqIzwCi0SEcDQ+a8MDq0JvvMCvA4xe5IgcWy56+zgfFMOGu7xgXDgP464bI8W0OzP1M7ZDZAgIvMLBq60ADMdqe8RJhIi5oiqrwizpkjF5pIg4bAhGVCoQ+6k0QLxcBENzQ8eC2CxKxMd9IC0FPInZ6sSQ1EZwJAki3AcOZAgZZDlW9DX3kjwdPERxhElj3EcKU66Vo6yafMVEpMBANAhqJD1WvMkIk8lkRMaCMEFodEVPjEaBcEmDMEF0K7jTM0SarMWiRKvD1NrHpTRFevSL49OITGi/+9u0E1yI8eMyoFO+nFREIcxDdMPKfORJdjQu3UOu7utKs2RKM9s008I0f2QI3mIIqjyvvdMtvEy6sczKo8zLFhy9leg2kZTMmfwzApSIbPw1AADGhXgpwSMwisS+jVwIyOKyOUs/t2xFCpMx1tPL7ZtH20q+n9rMvOSxXOSv2cxDHtM8VjRE3PTMquxKBPxJ2VwIL0PMejzF1fz/zb+Iy4qwvhl7TeoSToEwwUQbL0gryxx0xwT0ycbsO5KsQv2jwWVcLJMMr8eESTQoxsEyK/CbzuGcy8XUy39cPJN8Thjzw8TjTdPUOlWczMkUq5rLzpeEyTWDLAU0KMEDLdJUCDD7ThA8yWh0vQj8LdCERJQUCIe8QwLVSdaEMfTqUMGrL8IcSa5syPgsCAZlzfGyUOSEzgY8xeZMURq0UMzUC4G8CO7iwTVkzAhFRhx8T0icQ+EyMTvsP6vMQ1mcNgOjtQmFz6YMLlAUOBSNNRKtRgTLRQcLUh+1wRV0LnFjtjQsPww1xPsTLGmDw2PLSzTlUb0EugA9TQBAT0Dz/6D/tFMffS/yTDQpvUPcHMqFsLA4JTDXVLs53cc+y0Uy9bz5zDbgIlMN7T8+pcv5vMrUa9TUXDIVcy+nU9QG7U6EIFTIs8YM5c1MRc3tFAgcbUECu9SBsFK9SLaNkEWEoMUQvQgbPdJuHNXdw8r8rEavDMpd7UmZ+gTWpKoDhVGuBNEZPVMFJLatTETIAsw6xLVPZU10Cy/2Ws/fmlVdRVK9G0+nhDQHlYkiu1PJhNNXLFIVNMkL3Dks89ZuPYjyMtYkfc598zDH01Yfo0iTXNYC3cc3qy2Pe0IrdNFv9ddwdVUVW0uEA8x41biZfM48xT/wbIjgelgfw9V9pLV/7ZXKh6ULsDQJ47TYinjVXHXUkq1BMnW0wfJNB2xLio3ZuPLVajStVgVXMePUdGVWlfW1hkWxh4DUI805MbW2GG1KnM3EENy6c+1Etqw3e4xThFu5Nhs3lZxU3ZzYkh1ShCs4rBxaXYRNW+3K2XxVVR1WSkXZrA3P4uS5zbs83zxL2Bq3rQVPZIUI95Lb0PzWk41ZWmtR4v/0i34UPNgCWV1lL3K9Va0s0W8V25fDUcgCrUI7xU21RGFdSWSENBWz0K51rn0rxRaU2ZWFUKM03BLbS+SrWV2VVFKFUMmdyZzrSJpoN/90WhLUQIegyP07VdJ1s4KwnChbVXu9vGdbT+uswsrq1Mdt22Q10M81XRN9iNhz20PMxRbF02DdWo+Uz7i0W+nlWYfwW77dR5AlXO19Ocbli9ukVbETRmHdWIkoxGR13PBlXfSd2UtcWt1F0ePM2fmM0int0Rek28ZNiPjVx4UVu9fD2f99Oex1zH3ETbQtQsx1idW63ZBMMkPFVIz8RCfsv70tw/DF2gp206YcTB1F1JL/tcVFLbZL9d/g/Ebp7D3jol+y7eAbntTW7cD7SksUHk0UJcreJd9K1Uy5PMoYvsMtfYvV5VWEe9/R/d3FZUMDNmLHTd4lZtagYlkgZs3RA0In/t99JFDPfdG15U4iblcXa9OHDVvXlVNPBVb+LV0vU9yAPSuOyuCQ1E6G8NgNLtHD3YeuJYhNPAiPhVn5XLk7zsz3SkoFzeJkpbXjPdOKWGMTBtzxvGSxNTQI3ghCLmKJMEEOVuAznsmUld5DxkWFzUxBjgsxdtU6XLaiM0fqmkpi4940TmU0HuTl1d7Z1FBvdMgAjs3SNV0Cw9tUXWUbPtHQ5WUj3tsGHmKVDU0zWPViaa5l2Co4Jw3lOCXlkoCyPQ5J5TLUR2xgX0bcgQDJme3Zb+7mmGU6qfVl2yzVzJxNldO5JbwIaRbZHa7GvOvnCyVikEhmFY0I/uJQNRRcHX7mvOwzaV7/aL7I3b3E4kHmXUaj5FxW6IHWWPUV0RB1LxPWXnc2YTBeZhPVR49liGL0ztf0x02eZtFkXoaG5ATk3SFbXctlzXV8soESZ04sxgIkwkv26LgjSXON5GOeCF8jtZ10LAtV6YE1RBgTYktGZ26GufEkLcDE6uxFCaHz5CetaFdF5Yw9xa5GZccN3IG2C2duxGjMTvu9YnR2URH2MfaNN0VFScUaM9/jrxoeXX9GVZIdYP28xJac53qWY2MeY+BcbDqLa5/luf2FZ+tq2p8mPgdDz0YFzdoS4So0rRLOYXGlZse2aWoOrLaT6dE24fQVwuAi6ahd3okWbO3dZbF13Gc8/wlyBeRKo2axJLBPoGs7Bjq0XmtT3gvdbggvO8BR1F75a+OIYEAr3mjkbt4ntkrfa6y+LmyjJtZ67dmoYuSwDm9ULeuEoN7LhFr6REBavsTmXmFj9kD3ZmxTSyvM5sT7Clra6mpYvjdYi9grJgiBSqrltO0/UzyC5dshC+ppVu7hTbqInOo81Oi0TcQDvO7ohVAMz8uXXm2qWzcBP/AzCyubbE6+zkuwa1no7V5VnmMt/gvl8kgvE8wq5GBWgwiGpG5lZuuZxl/YNl3SjuMo3jcl9lVHk+ZbPErE/kW14+FGjrqqlmsBbs3ZpmbBJeYvtmzbxe+uK7vumqo0ozMdTWbV9aS14yurZZOxAAvUKmQ0YlPBaj3KFEzVNBs9SlMIJYboJp/reBQDi4tiylLz+2rB9RMs9bQqQhddJTWxp0rkVuyuIl3zvFS2Rn9XSj3THVMGNHhwOJbADqM1RyvGSP8Eg5zyPT//YsCw1h1v5BV9iPh1aut+Z6+uypq7tpCu7qbyuygevfTuWZzbT1b2NBr0tfGFafq19R6HXfQmdhSeXV0taRqrajr1ti4vPkpGOAYvXreE20omCNFuV2xXxp6VTir1dvDW3qlT1G7nvAcFqvYTWE2GK3hX8uJ198WL9curOXHnyW6n6qbk9/jc5KJO7lVv6Vmf1G+ma1S267NW7BZuzLUiMOJU7Lyu7351rtQu9KW2WCa/7Vbk6ZjF4iQXWxEGMPOm8pwTNd2j7AsWPmsfZ+sL8LRuVsXigu7NNOC9HCdnTen8M8fjYgsW8u72cbaVZJoXOybGMMPMORheROlETzP2/0GJcM/F9nmYcrz9xvklR2Gpd67RU+L+Y+K4+O/qrV+AT+blruKGgHXiBmK0hmP36rMDLW0kHvIWFLECdnGDPa6Hpe1Wd1EPn2NOl79Vf+SFAMruBS3sTPtmrHixrXCREG2Y5zovlc2Zf0j8MizPajXLHyvUNYgEjfXH9PwbwPyfvMm48mJY1tOCcy8VX3s8Xbp1/a4ppmP+W0MxOP3qLrhYy/3dpy3dV+GK8PwYAP0lu/QHA/4uTP3BlLq5Z+tJEP4ohG4hJvi9KLNiI4bZQ1rM1ezMA/RfJzN0XnFFqz9f88NEhNvIX9QiL9U0+7NGXd5JR/nq3ttHVCz1dLFshYDJ9wSIGAAGAlC27+BBYgQJTkJ4cKFBh/uULSwo0eGNigMjXnSIhiDHjiJHkizpEEeOHCZXsmzp8iXMmDJn0qxp8ybOnDp38uzp8yfQoEKHEi1q9CjSpEqXMm3q9CnUqFKnUq1q9SJKHFe3dsw0EA0xkpkmbXT5cWBDnmTRcm3r9v8tXJcUNca4gWbSXY0ALq79GnYfsYwVM0lcOCmTMmKTBA98ORdADJILOz4eaJfYJ8UVQ17U29HzzL6cHfZFI7IvwZF90yKsWBfv4oo3PqcWqXBg5NMMJaIGADZx7IWz+e5eWRnAYcWMGbM+iBpsQsYE/3bsDXllX8JRZ+RwEPc7+PDix5Mvb/48+vTq17Nv7/49/PjgczxQKdHcwXP49+k/aG7/f/nt1x9/AxooIIIFJhjgPgwySCCEAB7Y4IQEOljhgK9IksYrEvoHoIZp1LIfOCZ59VVPJ/omlTnu7OOONC7C6CI9Mb5oI4zt3Cgjjj3yqOOMO+5TI480+ihkkET/InlkkE3aqKSTRQoJ5ZFUAlmifEdJp5dGw0m0ZZcgFcYlRC/dBoAYktV20ZlklkXSls0hFCdNZwFA3UV2akdbcR3ZKSeYXHo5ZmMiPTaoRH9KdJybiM65JnZuAjAbQXs+2qiYI205WnWZQpWSfVmKOiqppZp66kSoqroqq626+iqssUqVA0oXmaPfrbnqd86ut+LaK7C5CturrsUGy6uuxxr7H7C/Jvvfssju6myw5lBRyyuFTPvsOYVc+8ofvZqUXU+KSvWNOd/sg6666GazbrrwtntOu/GyKy++39Cbrznv3usuv/XW66+9BQscMLwEH/xvwQrz67C+6sqKU2CS/w6UCZ5fktnQdItKmrFxBOUm0mSGBkrQDSATV+bKnsbU1yeq9dmyRbqhyNvJMxO6l20oj6SiaYtaJ5ucDvks18YP3awxlxwPpDJCvbHUF9RK0RrqxFlrvTXXrerQNdhhiz022WWb7VNKM3R0a4IWnuPf2wrKzXaDcdMdYdsY5g33gnb7vXfdfM/9NgBUUFEQ3gWKUTgVhBFY0mo9RT5V3PwhVDnmCO1neX6Xe+7f55yLnnnnpY8eOumnm54666i7DvrZLi22uHCTcMqmipOyBilpqN0gRtEtCWbpRYI5ijPtltku/NEdLVcT1SM9dvtBglE/kcu9x3n9PsareafMb01epAxeRAePkLkuEZOJQMobLb5E69feWqHfI8eSndwfVZ/asfv/PwADmBNNAEETAjwgAhOowAUysCk4qM8BUWM7AyJEGXaa1EvSpxM9Nf+wgx4km2g+eJDkjad9aNDfQVRUtaRkRYQufCEM5aMDIHwthja8IQ5zqMP4pEQrB8wZXWBSGskRJGg7POLZXHQQJe5DR0tECBOjCMUpPrGKL6LiFa0oRS0ixIlN7KJJ7LTCA9rpeBJxhxNb5B8lqrFBbHzjGuPoRjm2sY5s7MUNJvEKetBRiV7M36xSgsRBErKQQSGgGgpoyEUyspGOfGRJcsCdBA5NI+criQZzMjlIcnJU7nhXukD5jXfRS5SmbNAoUXnKUPInlax8pStTWUpV0pKVs7ylLDcXvpp5kDFjPMg33HGrYA5TmPQyJjGPWcxlKrOZyXxmO/QTzHPUAhWmwyhELbKBzGimy5hR69h2HtjJcZKTkGQAQg7UUMNysrOd7nxn1x5QqwSSLzgoy+NMptcTfcKzn+OZhzTeBiOBSgM/Ax1SQG/0thoRtKEIxQ9DEerQiNbIoAk9KEULeiOLcnQlYhRh80yiL2DGbaTrKmncsoFSkrL0pC1FV0uzYY6BoMIPBjGpSlvqnOw1BVT+/ClQz0ZAIKhTkUE9KlKTqtSr+HSpTr59alJD6MFNfqcvaZBdpQLpQ6hytavuoaE6f5BIVlHQq2Y9K1pLhRLvIHUZaX1rJ4dmxAQyZjwsI0n7NiMVB0gSrn79K1UISIYfAOGcOijrqdYJ2MUytrFS4Q7WgKqJwzq2sjEcmhkB6L3wVGYlXPqlUZpq2dGS9iY6SORp0TlWVQGhtK59LWxjcrWkaiKRRo0tbs32Cb1ccrFp4GmnZDOVtea2uMUlYDppSNQZIrZUkTUudKPLWNEGlYCnZa50m7Or3adCdrveBWxqCytWHYyXtd89L3qTmhIE0JaoOVjubdMr3/kWcrb0vS9SrauG94IVrM0dlWLxK+ABIxElz/XnJoq6X/j+l8AOfvD/6HNgCFN4kTRMAxAKC980zBBVra0wiEOMwPpMGJ4EHK97GSziFbP4VSjpX4tjbENEznCwqlWuGhosnxLLuMc+PtUM5nnU2s5Qw+LVMGV/7azkJZenh0x+MgKvCwQMpza1Y6DhqT4M5S1zuSPWfa8OwExeHcwwBzMMMw3HXOYzi/kHZKahmNF5ZjXDOc1yTrObi8xmPL/ZzHV+M5oBPWc7C5rQgy40oJV7ZkUzetGObjSkHy3pSFN60pbO8539rOk9LxrMjN5vIpN7XbFm2K1dPjWql0LiVLOaa8rQBCg0UQxNbEIZOgAFMTQRCl3rOD4BbjWwg+1AWtG2qEiecobP2WthM7vZLQkyj50tbVJpmVXVnja2s20T6ko2w0C48pRrHF9tk1vb3C43utvza1StO93ufrd9h6xO1Cp42WXvvneXiYvvfZfn2qr6Ab8DTu5z+3MZ5D1yjgWu8C6nbeEOb0u7TRXxh1P8yQZu7zkLa++KcxzC8e44yJcCcFf5O+Qmb3EOErDVoIJihgk/OcwhvOqY0zwoEyfVzWuu8/kSvJ+13VT4zoMOXe6sXOhGl0nJTzXyozMdvR9vOtSjnp6LS73qI8m5qLBu9a1PV5Bc/zrYmUqfsHM96aYyO9nTjtYHFl3tbn97UFAiA7hDPdoApjvevSpJu+dMve9+J0nP/25ytJNq6YI/fD+fjvjFL16efGe8wrUuQ8hTnpyBrzzm097dzHec8KPyPOdDH8OUsFX0pgc7Sh5w+odL3terf/0NZeB12EfTnulOrj2/Db8q3eO+9wi8vO+DT/GGC9/drYfP8YuvfFk5fvnOHz5fn09u0GeJ+tK//qqIj/3tuxv43D918t0T/u+Tvz0tLFA/+qUt+7an/9S8R9X72y//96RE9fO/P6pnjv8uj589/d8/AF4FtAUgASqZ4hWgj1lffCggAjZgID2eA0agfGmfBMrY/6nHBVagBgYFX0HgBlJ+IHSRHgi2WPyZSgmOIAoWRUrMXQq2oHZRnQtSWAaixwzGoA2uhPfdoA4u1ubt4IAx4HsAoQ8OIUnoGxEe4WLxFfuRCgohIdnUoHlAoRPeYA9OXKEVmlUOwscmJNkV+s8JFl4XhiHgCZkYliFS0QqMocpQcaEZho0UkscbtqEG6p8c1uE71R9ZzRsNAZ0dmhfJ9aEYriAgDiI5waAaZlhy7SEhxkocikcjLiIAGiIksU4iIREdq7QcvYkaH1Kie3zhqHgiJ6IgHoYiKeoQHZ5KgolasmUYG5bi5LnKI7pi+Q2gLNaiCx0gqbRcso2XWGmiLcKHELZHMP7i/mUhMSLhZIHZe21anrmZMmaamjljnTEjmUkjmlHjmD0jNlrjMq5ZMwZaN8rZN2qjN1YjOELjN0bjobWZOaqjO6YjPLZjPL6jPNYjPd4jpokbh62isWWcDjThMcJFLH7HQAak8ymhQWwmZACdn6ro1w9k3HuF1csp5HmAYpZYJEXiHwVmJEeCjTG6R23hWHLZWDF05HkUpECapATiokq2ZKt8ZHu0HIb5Y4Ztgkv226sM400+3yjupE+uCkOiyiaAlZupQRps4k9SBUq+xVImZebJngdYOqVUmgdMsocmUFkiIeVURgVGxkdXbqXy3R5YjiV7SBirDKWykSVBvkpTqqXgnaJbxmV44ECQsYqtgYJcwoVOqsde5mXoyZ1fBmZcVKVg4lBbcsVhFqbaEUumYjbmUDCmY7rQV77HZEYm5tGK/VmmZjIF223mIiXmVYCmZ0pdFY6maQoFZJ5mAvUlerCmasKdWL6mbO5EDsjebOqQaFZFbt6mznVFIG/+pk3AJXB+UGW2R3EO52L2FXIuZ0tIInM20G5ORXQ+J8exJHVSZ2xe5wK5pnlwp3ba3th9p3juA3dk5nhGGVue59+tPp96aqd1tmfZHOd6yCd8Gl1q1mdj3id+wmJ67ufbNZ9/DucDsWCAno13kseBFmjHbaSCvqZ+NqjE9SeEfp1zRk7oaL6nhcYKfabHhmZodXaHh6pmaYZo1kxnVJgoiQrbiKaoY4ogi2pNgopHjL7ouyEkjVpmhd4oq6DoU/DoTZzJXOnoeT2hqJC2JP/kZV49TUwoQ5JqJU0sRpIiB3SsRF6xRPuMDFF0aEWmx2NgaZF6Fxp+qWJiaFLqBWhJRJTyDFBoAhBZxi+VTEm0yVH4aFPQaU2oSJqI6XeZpZ4GJpEmpF4E6biAxk+0aUUI6s6EDO8IxYyCR6MiRZf2KZgSm6TmpeyVnltyyUsEClCkaR5NQvl0if2shJwahZ0uxanOxJlkVqXGFlTutqpc/qlBGkYRuQRDwClPSAc+jU9vXBXJLCpl4OpQaKl5EKtTHAqsSldPJutYAmhcQoSw4lVqRCtOSMJChEFJHAfUUOtFaAK3/kSqJkXrVelIXKm0rkie1MVCxMBhdESaBpFIoEGSsivxxM+ayCs4MavlkaG+TiWDjuVk+BJL+My31sS6KurSJKpJdJZRPGpcKOBCQA1q7BKWMqmkeOk+WAwG5YmbXJKdHESa9qvlKafITmWObuVknElvoc9uFOxM/Baw2gz80E/9kMQwuCxPhCtStB5VYUTExmtW0aykIIqhFs27Cldw7QWnliwn2f8o0zpldpJlySxEvV4E7QwHzk7CvErCshlGS1QGouIs9sTsTxgreXQlwxbPQiBq9/BO7SQG+VSEnCSGdMAtMSQG07DFQcStyCTtcoDqxj6tI8mq4HLiDECQXJYMuZCEuRTsBWmEJIyE2DpEXgWP2JZqUejsnL7Ez3ZGRfxq4D7ErqotsCLrLh1PZYDM4/JS4UISLbbuTpLpT5ZM2opEXSlNzaKpxWDsPvQFq3YFtYpt7Q6Fw+rlSwwRb2gEyPSsSVDrmfCu0EpPrSZv58IuJC2r9aok4R4jnAqs5FpG9Lqr1+6t75Bu6JJq8JKtQ2AuUWiuqTpGtBpP0Pps7q6E9zoPxGPkqZ/ojMJ6xF1lryOd9iwAJ+SA5iWcruouUQe1+m6w5ivI8m+2pi9a3AUFw0YFS8dRmO14TGa03uqihtTU8BQCi0TyXE/0kAYID/AiCaIKm+T2EiOuVi+hDIoEqymb6AxzwIQM467GasTm8ufxusyZ9K4DZ1KkKKnHgK9IkOtIABIK620LM5JwRnFAyq5P4iryUu/9hO8TbzHo2nDGAldJ/C8P9/Dk5kTxvgUQPsZcrcVssLFDkBBJaG3OjMbzfq8ZIzFCqMjKUjEOBaUfG2R5GjCkDG/1uO2iMoYJu8wOe5YDl3Eeg7FQuG/mxgSuCkZazEwKR4fGgkz+4nEec4YRB/IODeQyKSdk1AIsIutxQuhM/KovEbPy2uowsArvGeOEBotHZZ5wGNdMX7yPF+OvGdtx335xDztKFp/yEVmxMkOibyYu74zwpUhyB0cy6zJG1ZIE+3KxNt+yaUko0ujtx+5tpoyzvaLM8nSxJ28yD8/EKDezDb0wPDvhv4JlNcuyEgMzNVsznuAABM9xDSOsJAdFGrtFMJbM1QJz0CS0+ZqRVK0vO/fyQIcwFM8zDtEHgVq0LAKy1C7q4u6DEd+zGSOKteYz/mzy5XqzTVBy+8pECLVPc9wuBH/rRyUxmmiKGA/qxWh0DgnwME8vojzbYrSmLUp/MCyPxDabRA57bv02cFMDRS6HR3EOEe+Ixi/zyUTHMgDEzDlfh8z2scyy7U97UFCP9Q2qXFS6ZA2HBfNKNFNndQQ/cjfHbEof9U6w9FCM324NBPCYNGAwxGa9tcnI9V6frzDnNOP+s1k3EAJQ6mJzIvZ2dFN31u0Kdt4C5M7Add6akS3btU4UdFsMo3DgxlsX81uDTJuwrtBWDWpATcUIKtA89guVtWynoE87JbfSql9z805VtPqML+Q0cjubRFLbHDgH8WDQjG9/E0NERMVUhMpIh+2MBaJYEtzexVL773LX9gIxzjN3XyELP2vMDs22LmrqygR0x6lwgLJAZ/CrHCejOLX6tqkiJ61r2LTFjEZbf/fvpRx/A/XsZWrMMkpmLTAZI0TFBM9xpIztfi57E7dK1wReTzJNIG1p/27OOA34OA9v2bdeMHjLgPV/n81tjzh4Rx80P7VEb/dwl7ZvwC2oMgbbMopvwMYNpOn1dLaK+wRoc4VOnrd8/xLfug/uarN0nJCh2NOkjK5TY7aJi00qP7kYrqg9k63UPPj4DDNS5zGIY/lc73hPTLhxS7mSJUCAq5N5GXK0Ku/4enu5cnfJGA05mTC5mxtKhNNEVINHnqN5dKk5n1shn8ZlYDcwhu+20Ogq8DiGkv8OqDKPYYPu7+bscf/5itE25ZI2paNfmGY6UfT4Vng6p1sWrSRAUdx5qL+epVOiNjWIjZhDq7+6i7h6rMM6q8+6rdc6rst6rtO6rvc6r//6rft6sAN7rjORT4g5UCD7qQdVqre4eWTChgzDqUB7Gkg7IaHBhuUsO1DQxxI65Si9zbevS06FO7mPu7mD+7mLO7qvu7q3e7mze7hnw0jF+7yn+7u3u7y/Tb67u7nrkk/seVwAvLbDRZtAbwDVR7fzhKlPRXHHR8PfUF6J9cDTxKu6JRPx0UFg/JAghMZ3PMd/fMZjkceHPMlvfMmPfBaZfMqjPMtj0cWDfMon+6RPvKn4MANV/FAsvFRUhohzKXDvEAbTvE40O6eDulUYvdBDRWqjqwIRvc5HRZtk83tEvQcxsUiEgWknvU10ptbnhLIfe9ebyupG+tl0R1rPxNNHxaCPytov0P12xJk4b3nYd0Q9z/1LCPxb4L3dQwVBiEFlJ1DdK7xnxxxjcPXebzu/Hv5LfH2YK77DT8d+/4+f90TaO1xenanjyxbiZv5LID1VeD7nB4WK4C7Zl01k/0TlL1wJhz5P4DzrrwTjS/rrq0dxZPcBva5QpL7CXf/+7OdElPe+ROh9Wwg/8ANF3Pe2V6/EWORVDBjRbfBu1nMsmPfuvLbr1Nz4ulo/Hht8DiAA2RLD4za/JcMy+AuH+BM3vqLM+ROKwbNs7goG75oQgpdR+3vE0VKtS8h/QlzQ+nM4QACIsY9gwX0xAABAU5AYmoQJYyw0OHEiGoQPY0jKRJFjx4IWHybU6JFgw5A3IpKcaPIhSoklQ8YMuZHhQ2IqJaEMmZGmx4svWQJAqZJoUaNHkSZVupRpU6dPoUaVOpVqVatXsWbVejXHgxxbwYYVO5ZsWbNn0aZVu5atWB1t276FO5duXbt38ebVu5dv36I3HhoMadShTIHK9hX/BsCxJcmLAG52VGx4EtFMgA0nvBGZsWaPOALY5PjYsNLBHS9nPuxxcmbOBB9LUnm6IG3BCSsPwyxzoMdhqmVWPvow9+6YvTsnTF48M3LWwIUv/a06+sTUzRGTzAQcMsHWmbN7J+7xeubNHsfrbu6XfXv37+HHl582B44Z8/Hn17+ff3//V4H4j6kABSzQwAMRTFDBBZUiZryCdnvJI+MMU2aSwCjCiCQxHvqkI9LWm5C7h3qaSMOOcggtofAg5G6YpGwzyMERSyxIkhETKnE7zzyaEYDq9omRoIfQUIY752TE8SEWiSLSSO46EjLIhIoc0bERkTTKxxBXwrHGJK3c0udJKA3aUaGOKFTtyyGpHJNLBuGMU8456aQqhzvrzFPPPfnsUy259gTUz0EJLdTQQ+FTjMULeXwupEmUISYTEJXLMCExrkzotYJIi87CkySLaRJIJQWRSTYBwLQjHA4QzSDFzitoEsBOnQ1D607ibNaQNt0njUcjtZBCE29NDgAmpXwIB2AljelUM38Mz7hgYUxoWeIinRRUSyslFoBrccuWtBs+fLSgTxurFjeDPiUX15Z0Na7XfaCNlhhhlywp0lyD3VQxIMV7lFRtQ6pVWWbrrf8V0YUZzsvHNRt2D4cHcIjY4osxzri9H/rkWOOPQQ5Z5D6FlLKmdA1KM7ksU853IkaF4sjNXrd0dyI3WT6RoxQ79HYxqZJ1eaIwUJY1WplDkq1FKjvaktuffW50aYEoMvNUmCUcLiabpz7TZ2OlJsi4rPeBmetzeUXqxnWNKpij3c5GNWaKiAGMot0UJghrure9eSew524ZopEvBgmil8ycly9KoSYocbp2K9NVrShlmfB9ZsDz8s0579zzggTNM/TPSS/d9NOz8hHg3QD+6CFV+Q468Lcnr63YLtkWPNUe0/Y27oJy6N322Z8S8l+fbi8K5upgrpij479++liOYG7/XG40L13KWeyzjz5qhXcL42neRULq1xUJe3C05J3u8e7aKVr+/e452rLX7eM3GXU5GY9s7/dcY5D/waVoA8xKAD9Xn6/sj4ENdGCCCLSnCD6QghW0oOeslr+w3UZTHnHTykjCBaHpTX3GGh9JIsQty+0jB61CHwdXaJrk6Y9eRErKmM5mMrd5j4M/Qs/tVMc967UNfgIsWfKm1MGOVG8ia/PhD7ulvCJGCYkFMVPWMDHConDohUt8iNJ6qJIU+qx117sggxgHAJpAzz2ZqUgJ1/KY6rAxK9XT4ua6ssAz7pGPfVzL6OgESD8OkpCFVJAOq9g+KA4xibCjnRKnlreyUtUOVipR5PAcORHQwA9vQANi0ZIjPnWdTX64i+LwGEnD3bwmGXA02imJCEufbUp2jOzhazrpEZgpjiOt3GD9QMktUaJSKY/hZWJI9MZfggmWqpz/YoG2RLWlTCaGVWkIiGIwCbI1zYZEedhS3JSJe83Kf91s4zInyTQC3s6AYIHZixKYAxkYkp71tGdSPLanfN6Tn/30J16CSD2dsSuYPBze7yI5kciRBGYs4uITSXJE4hmEZ10k4UCbEqMxlXF41QShQfeRRUiG8YRCZJGPtplOW9pKlrrLWi3FaM59gEslMAMFUmJyTDG50lvOuaRRcunFhKRhIg/lKDFBqrtkMOg7CCVJNAEAxqx8xzApfRVP5wdRpChKqFplz+t0iVWz0FGlR7UKVz+HA839k61t5aMg5QRXt86VrnV1ClpNSBGylhSGmepOD5X0V9jc8WnIGhyK/wxQRArdwKwstR5VueO8+qEhTWBV6BeTmsRUVvGigkUVQmm4SJXIMamhJS0qA6tTU2IrVIG1FkHRibyR6hWOj5Gk3Azb0s6qlj921O0iH0LU1Ln2BvDsqlVdqj3OmkmqXz0sR5gLl4VKrnxjMZMmSJdHu26Xu52bYJ6+213xjle8vFJGJvoVrJCQrZSi5ZZT9/HQ3LrWQ1NTrfA+65GKTo8iD/2bck/pWyw9D0dZMhszywjTsCakvvbNamPzSh7MkjSzVgwuYJW0VKS4Cb+dDaxPMbpFwlpYnQ52LC05q9KbLoiqED6ZqLJSL9xoc1cy4eVe15c7nHJWMRDbS0EDpnXGdU60x2RpKOlkUB/yLpnJC5MrnJ7cZClPmY+QBU4mkanjCHMQywYxZtRwlMMR9zC3XSbIJmeruw4XJUYC5s6pKmuY39kGr6VNsWI2taXo1G2H6lppZ2uk4AULGbVhZgqHw+Zm4LBIMWZG4TM7C6Q+L3K+JMH/M4OWF1pl/kimVOEwpKg3rOOKuLpI8ZFTYSbcc070lQBQtVra2+pXuxPSIruTHqmca10raJ956vWugR1s1LlWSO3ka0cfbVHNMmWVTZrhcynSwjHrjULY3XGAxTramdzLd490NVK3DG6BKluzquFtuDX4bQqve9xRZTdW0DXQWB8Fh0rZTYPb3dxmO/bYL5u2f/7FOi0Rxw3Zdgr+RARkJ0L4tBsGcpa96hfLEljLaJmuESuulTpzLgcOwLWwQR7y90R5QSQX+clRfiioKglIB44oEmn45XcbxbbObiZng1drhhjHz5t28WoV9hAutNtdAUX3sge9qThPuucvV7ag/6loUU1TpXrRwbE3Hy5bz9JWyzXnd4VVem79mAlSWafusYwdlerxFly2JPtfLpwUH60w7XwJcauRO5aC1h0r78xuDu6TcsEPfi7hpZPhCZ94xdNp3kT3W4qRDnb5XpbcUixxV+Omv/3eVndijzxB6q2Ut0cdtBjKYNQ3+9sjvzhSN2Ad57++SBTLMrT4DWpYQr/T2Dr9zx2Z/KBnzffOZj7FMNOwguR3cd6X9SrmiiWrz0dobedIKb7cXVd/TpeHN36sPL06Vja+ObV+fPHlN39VTJ6g9J+f/e0H4L/NSGYPSkn5zNw694nywWRHvP4FabvYV+/5+q0ovg/IBI6GoCeO6zzrfODr4Mbspz4PlfLmp/DvgKRm6rztqHpF5lpL+kAvtAQO7C7/bUH2BmY8ykcQowJLYjJcgiScqPcoT5aEryAeKu+uikwcZ8I8IidII5sg5jEyJYZ+QoUGrblADwjrRyeAw6P2gWha6ops5DFiwMf2wUc+4jHW5HESiGLcrwvZIxrqARrqIRqUYRmUoQzvJVJAgRg0oQ3dsA3hQBPSQA7lUA3SwA7vMA30UA/H4Af68A9vLRAFcRDHT4EMcWLkqSvGrxAH8U78MAfSABL/cA/1UA3egBLe4A3dUBk04QzLsAz1YRmc4tfohBS98BRRUS/0jyjGaGosJ5q8bZs4jElmBsAi7sUYaTeMsAoRjij8TmtgCW6Uou5MkJsgYqOWbwBbjUWc/5AJbXHrUAlgagka5QZIalHvoE0Yh/HhbiSrJAlmjND5gAnmig/++KPIIjCvvq88eENhoi/7IBDiICwEiyKN+uz7NGHphOJ+nmkyHGWiJk4BAQZafsceZQLrlul4os/GOnCwYqLdYE9jMof8UrEiPSIa6IEMzfAMiWENNVETMkENQjIP+fARA1GtEMAQVTKPvEIQ1Uqtksw+XLIRW7IRD1GBXhInZ7IlZ6AmGfEkb9ImhXImh/LWJibJbi0SKzEk39ATlyEayKBP1s8iqbIqNc7gWi2TaiarkGjt3mXNqkdh+AxgqkcWxRHjZms68IuyWmcVBfBpUO2UnOh3jMPR4P9m2hJw014j+hzNAfuma05lGidqWtKNv+gGMLLP1eaFHuUmLlNvovjMMIePoVypembtA3mKhkYQ+R6kFZGGbepu5WRiTZjO5rwGLW3wIHSQKPwLgVTqMsVGSWqk7uQF+95Lwi6PF+9OH7eGFbFqeXhzTWBmHyqr3azNcxTIKk8uDM3QDDuSDd9QJO0QDwHx1ihmIgOxJoGyKLdzJrEzJ+vDK35SOz3uJ18SO2/yJ4vyJXlSJ5HyTmCy44YyJxfxTrRzESeSPu1TJ4mSEFeyPnSgPJMyD92QDcswIwUE8ZRzQRnUKkpzkbLGOG4ADcbJjcBmQokhMnux0IpknGrsNNX/7EeI4ROI4UNZTW6EokMra1EwokPj7RaT0d9CIgxcFA2YyGfEQCL25TgGrdMGkIZOryCcUCZQogWZwjAiIlLsaJsEUyA6dElRr0081DNNUxI0IRlKlOdk9HVq9Ea3VCTSYBiUYSE3BWcihbJew0xgk0IkYUSz9C9njsQAYMUUBHpOzdJcBmayMFdkpTbtz/OI05UWDu4yrkeUYVruhdtch/oUcMbEpRfd0suSRog+iuI8UC1Z7TEYC23gBfa2T85IRUItNXwm4Vd+J/wuR7salJ8Q4xM5ETrbcCSp0yTDkxHN8z9v1VZxFT6tUz/VSjxXUj1z4Ady4A/x0A4pIQ3gtgATKQEOMkETYZUTOXEZNGEjz3AZmhNbyVBM9gEjo2EfRBEMv3UM96EemIJcMzIU1VVbm9NVOdIjNXFZ4WA6+TAS+zMoBdEBsBMIbLI+jdIr3nMPRbIN72UZoKE9pnJVFXZhjfG3sor4Fs1kRBNepgjRVAN8DI18VCMAwOU1FM3sji5QMxa2gAMz4Esmbisv0ZIfsSQiyYw7So/2lgRm509JXLbcwMPbaFZnzQNwRujqeBOdaGiX/zDNnPYtOWwGCgvL284mUkkt4syGxmx0aqXWMhvkU3NTN38JZ2YJcEgPaYGvh2J2ziCv1TjKt8oULFHWF3UOZGCSYT9HFD/xXj6SJGk1B1IyjxpRWLuzK2aAESlmJgsRWPu2WP0wDy1RDegQWqu1YMvwKUPxjKIhFNs1XicBDyORDIBSPQP3XgWxPYd1DO7wWdvwE+HCFOE2dVV3S7PPS0M0XfTHYjtoTPLmY/eRMqEj/y5WnrRIHxsQ9Xqk7SijI2T3MBgFvkQtRuO0s5gkaEPCuASweDkKpqSXbUsWUIs3zXaOO47qY8tIdrfUqmz3qIbWHPdjUCfTUjljr74PCf8LQhMw8AYnaiGJLfsw80SZLwaHKXYsSk8Lk9xwLCBZd2oQCn0fTzIT7s9YEPUA5gURuANv9mJubXX9pFXNUBNgVVb5cHOzk1dxIAHU01/tgz1VMnBF2ChvrQ8lMQ/hYBLi8A2f83GVAQzPb4Kw9QzfcA71sFhdElgFFDyF0l9Hl2DL0C0o+IiRWGRhMKvmxURBLf6WCG6qo9bwpSXEwMWqWDM29Sg+dIvvpIhK5SSe2N52b1bajrE4z4mzg1E08Pa4hy5jazNV6lgS1UJGRVSvDWq6eIwfiWy7ZY8jMouF4oqdYlROgpB90fXEOCLV2Ho1wxqnTZBdr7FMFk+1t0D/Rg+K183YgFSm5nIboc3DiC01TYnuVlOTs0pCnNZkffShos6Uq0sbOYKmxhFGu61HB4291gw1HgJ6Oc7jkng/5pYT3VA69ZBWx49weTWIP9dfiZJvDZcMKhEO5rApO7E5o0EUk5gijYJyI8UNk1UNxmA7JwY8tfNz+fMOM7F0I9gjFDSY4Tmeo0JTSNlANGGtDOkYeWlHnVHcqCJ+5Tkroq9EGBMmdIys7tTpHCn6fjfdsMzKRsR+de/6LBVIKumpYkSiXDe/wLYDK2M3JCvHVgorv08ea3Z+QXYZSWciA3otZvhdc5ia00CF4ROErdOD+/VO/vYkfZI/C7EQx6AP/wlUcQs0FD4RI1vaKd5ZKm4YVqdznG/S4wzxPgcxcCuRnbW5KBI2qbka5dzBHAgiG8B6H8Q6rMe6rMn6HMJarcn6rNk6G97arYsEFWrBrO06rdc6r9v6rtG6r986rvn6rN1ar/tasPn6r8PaFjqxsAkbsfd6H8a6I9qBINwhGyjbsvfBHb6Bsjc7sztbsy87tDMbs0Hbszn7tE17tFG7tCubINqBtEn7s2F7tWc7tUu7HV6hbnoBG1a7s+kBFZQhBoYBs9shst3LQcu2LMCBIMxhrM2BrZubuaF7uqW7uiGbuiHbubH7ua07uq+7u6Fbu8F7vL+7vLk7u8nbu897vQPHern/C8SAXE53BphkzUreALqzyCaT928XLenucnCoigor26x2rJBozfaVB+1Dq2lIocgG++/sOGruqgYrWw1QLQY+u/op3PUNR3Km7dUQ0ROF/ZOc93aZBXGcp9OFYdioizirM3wstvoqNBI6LxeZSfxex2+IMXiGDQJ1X/zHBe+5s4EehJzIz2HIizzJzWHIz2HJjZzJnTzJz+Eb3OEcagEVVIAKpvyrj/zJidzJmxzKkbzLpXzMxfzLzdzLz4HMuzzMvfy5qRzOuTzN3by5h7wQbCEV3pzMwbzP4/zI3YEkNHvQqbzQBz0bCP3QD50ehtzQHV3RHz3SKzvRqXzILZ3S/zG90jMd0jc90hkBFYYBFXrB0C2d0TVbBUBd1CudzZLbFuviuZ+7yWUd1tec1mHd1mc912+9yWld13W9uXld1mcd13ed2IO92I3d1ou91n9d2Imd2A2ErI5Wa1sOjiC6ZznVYTOQIgzYryQ69wRyIryO914DGReVXMw9NnVLgOX3IVUi+mpFBTk6wRU63NOn8ggHEX/cVTvSDXV4ponVxPfzP0VcJZ3ZmVVSqO1QEwa2dIuhDL0VyPtiqeeiHsqwmGe6b6W6cBXoDsmgE4tY4kU+5cyBHpjb5CEb5Uv+5AniHFT+5Vk+5Zk70PeBClQgIcyB5lde5vfB5WN+54Ee5v95fud9vueFPuh/XuV1XuePHuV9PgcKQVWQ3uh/numJorQZHbXp4bN927dju7cJYuvBPrXFnuwxO+ttm+vDXu3J3uvHHrQnAdWFAuvPPhuMRO5T2zSx4r7DYr23G7ubPL3ZOvB7XrzNe/AH3/AJ/7wJf/ETv+XH2vGtu/ENn/Er//HL+73hKL5VikmUttUCi2vi0bHI0kc54qFgs7/RqZ2mHfUqbWmEQ6Ye7uHMBI9POkucNt3MSviCaQbR8jg7R6cZljmDBZzfAHML3nNFvCVlMpmnWlgPdzrfEBQefhnowcVH3j9i3C6wlQ1bWJz5s6eNkl+Z/0700A3NMPvVf2H/+d4/VJWeTiINyl1DHzj2qqL91//eI842jCeZAGKfwH1oABg8iDDhQWIDBSJU1jCiRIcHIUZMczDTRIk3Mm78uE/ZQTEfJ3ls+BAkRYMMG5o0aHFfRYEvAaA0OOnjwRglD04S6VNljIM3WhJEeEPlvqEGlRY0qFGnwaQRJQVVKvApgJhYu3r9CjasWKU4cuAYizat2rVs27pVqmyZMmWaiGm6m0ZNmjQ5xuQw+/fvg79lAxsu/KAw4MBlExvOISPwXr2U7t4lNnfZMn3L3nr+DDq06NGkS5sO++O06o1y72bS+ziHjrKKDy/+m8Zy3NW8e/v+DTy48OHEixs/jvw3FMLkvAszf84bqMLpW8MuB30duvbt/9x710TD8SD4fTWNDvwesWZOsR0Nju8q3aZE9VjbA3jvldjOngYlRbRv3kbZDSTdeDUROBN5B4FEFH8A5FQTAAFGlAl1SMHVoEr0SQUAT+ldhVVNw3RHYkM5DFZiiszFNZdlmry2F1+C1XYiYbEhtlhttDkWWw6TTaKGZcQUExdnKh6JZJJKeqbDkmzJRQwQmqjhl4003qZYYXvdNZeTXn4JZphijjlRNCGFJJdcyoCCmSZ0uehiJprAMQmdcOQ1WYx68pXGGD/4CeifPg7KJ6GA7qlXGpS8QQkccsJJ11xx0WNmiQOSiVVgmIJJjH0WFiXWpW6JummppnpmFVTzZf9IqlbrnQciWEwBQJJXs77akKtY3RrWJxlOpGtDs3Il4IISXdceVSutlyyDBtUK7FWeEjuQfhZOtetCTsV67LMSYaRqVzVRe+ppM5RVLqYs0mXXi4nKSFgCjzU2w7y2AZaljfr6iacmb1xGpFz1VJpuwQYfTBoQCH/UZEStTbmXbYNdaVhiY6QBB5edLcxxxx5/HBZE67b4ZpxqwKjnoPdGFhljsQ2m744zPHCuvS/3iHPON/eYr8441PwXv3k9WheLwTX7MWQPgMzdJJPc4CkAN/yEFtKfWc101qZWiNNE9v3ELU3cSqcsWFy7B19Kq6KtlBgH+QeWtR06mMaHbDv/WDasLO3THq72Levs3Buht5Lg4UlNnn1Te/UrSGfj163het/n1dkTaq2WppgHF1ebriUqqL4V46wjljm6HPRecAR5mSZyRbPx5rLPrnXDTCvcVTTKFOMuvIX9bjNgY6jxLzFy0Y588sqPFQ2l6xLDJpy54Rmx738hoLNtDmQvemOGbY868KQHL3oO9cZsJb7qi0+j+IKljxiO5c/4fo2S5WVZmsuvpfn+/v8PwCOB60ETqckNhlXAsJGqK7OSj1IuNJFUEVApvAKLdKAlkWAhyFgf+Vq0VMVBscFEKyppXEQ0GJ+8reRyXtEgSDZULMSdMGwf0Qq5ArgRHKAIh1jZkwyUXEQ9xiRAfhQr3frutZgxAKFfujHeZurBwyhKUUy4Y5rt0rKMdkUMdaYr35bctJkpinGMwWme7tQEPelpQk+AclnLbAQz9SGRZ+l7n/vqyMXuGaZKfKESnvRyskC+CE4ugp4hQ2FISbEoTXFJk2Ya6chFSrJNJbOMnBrVKED2CV63ydH5jngjmzFxN2SkDRlPif/KVI6FcJGDoEQedzgZhuVsktuIp1h4Nlx9BAcHqVvcTNgQWEYEIbpsiNwcGBHpxOAleSuQ22QZQw8lsGsb3JsxEzSWMITwheIJnAqFGSJtqVIgf5HB/6CBRkvq5WLhi+Md7XUlI+ImL6yrCxgHNs586pNEOdBaakKjO97ByF4w65lhvtilfSp0edHgDIsMCcQ1JkplhAEaYOI4v1DWr30Vo00oPYqzTf6RUYSsC5sYeabYyS4aA+tcyWAEmznKMWeFuZhuAlijhep0pzh0YUOiJqGNaCUqwwSm3jbSwAlK5JhK/dZJVKJNan5FmQ4qZoR8mUxickhq3ipqQlToVQz/2g0ARBVIAwOktlBhCytDDRwXJCLBYtYQm6rsH8Kep869+Ckwbyyo/bh4viJ20keAfM1lQKE/nip2sc+pIsiueBp0WqZPL6PYY76IGcZqVjvNY2Qa1YmyNlZUphxFIszeONPBlnaPeSJeZeCUSM10RqWbDQvslNEuiNkGeBh9jLwIyyXkQaaftS2ucdPFyrFu0yXdXNtI0IBbZaAhQh+JKlKmO92kQtO5kLNlc78iN7CKsKkDiZokiPEJYjzNldNESHcjJNUYincf4CzvpeLzVS7cAA0sHK9c2/vflagQhkqpiSb0qcOzgGldJtNrRn0Wvnvl6weEHZqQEnvcDGs49ziQ9ZhjhfMwSsjIoD2LI0JvuGENd2Zd0bNMIGMUOrNYdLXjw+NfwJfaTtbmUIBcI6TAGBdo4DPFz3nkXdapPh4ZVDJcgiLI7ErkKEtZOxIsq1fjO0Ms2/daRt0yl2mYKzBHpIJTHclcwxXLa81XIPhFZjWXGzlpZpCG7FXQl8nr5RaKWSZrbcgAA+xcFIvxfNDxIW6BqFcKDzZeNL0xHil2Mb24aE2aEfKUL43p1XzYYx1OzqHXWKW/gvRmF8sYGDP9P0O3KLf+EnGM+uKy2gQ2x6Lz64k4Cj734Rg3hK1TPQ+7SCOh2mCa0SInH2y/3LhuYc4ZtrP/n20aAisXxdI2JlATAmiaXBvbgh5vdyfyTADADbz7Gdx3nUudbBduuwP56gP77Fy5xudVTOWynNsNbw2dO87c9YqI9AmY1dQDnZ7r3RZz5M7svbMxo440/u7CpkkRDNoUrzhoiHu7JNXjTXmJ8Ex7djIuddvihUbTXFp8ZJQdnNZ51GhglNxb9LV8k5JWdusWCTuSS/FhcKgS++6l7JF7ySxL07nRj44VUND1cIKWTref5qmpCd0lUEOK06bu9HDChD1armbT10uUxXXlmCwk+7tp9ZGsTyS8+J4KZt6eCaclhFg+BYnaYyjWkCwdJDYE+A7RwmDLMCpiVdp1zAH7/2CPfrJPrtWN/iaO9MhLXi2b7hjGwZRFvIS6i4u+n8gn3xYhM7iSg3+19Sw76uD5dWKEYX3LceyXPC3qtZdB5OuGDPraLuPInLSsvJQN+S8ROvfEL77xVVNutygOJPaB3N+4YzmAQ0YiDv20wX1OR5d7dPvzo3CeLBPxZeD++OQvv1c6zbHKY2r37tr86TqPPR9hNqHOXjEaK5mJRSWKnYz5ZPZr7Eblw1vylDp5QVKT5jpBRlvmZ3HRYBdqEBjbk3qRgT9Ttx0Tw4AZSGTuMBAcKBAeuA8gKIID0Q4daIIfeIIhmIIjiIItqIIuyIL7UIIuOIMvaIMxiIMk+BE1aK0OA9GDAvGD+xCEQ+iDRQiEA3EORiiESkiER+iES/iETaiCXYYWC1QtjWNAWOGB5rCFXQiEXiiEYMiFX0iGUJgVe3dKzSYQQ/RbBUUzNVY6PPIYw5MXjeJ4pKSBeaiHX6F+C4N+BRMXd3Enm/dOOOMYqnMZQSZGIqMmkWIyKrdX8PNyqHN4t+EYIEWAOhZHP9BaB5iIAQMRTraHozgQmRdTpfUAY5AxFogcUEaKr/+oSu6QDUL4DbNoDrVIi7aIi7eoi7N4DrsIjL2Yi8PIi/vwi8JYjMmYDd8ghMtojM5YjMc4jNKYjMFIjNYYjUEoEefQg9lgDkmYDdy4D+HYjeLojeBojt84jup4jutYju84juaYjuDIjvO4jugIj7PIZ7W0FlQoEGcjZwCCFd/gDt9IkAZZkL+YkAepkAbZDtzIkAQJkQv5kNpYHn53eR7nMpd4UD3GJUSiO7AokiPZFZf3MX34Mej0JqeIJa4XGDUzMf4XI5NmNEliaI0IUWpEPdXjMkOkcD+ZfT3jUXLYSYBSWL9GF4zEUiTJlGkRDXjRRbURJKwoHDLWlFcpRfP/IA1J6A5bGYJeSQ9g6ZVdmYRh2YNhWZZimZZruQ9o2ZbScJZjKZdsSZZf2YN1aZZvyZVwqZd96ZZ1iZdqaZcqYQ7ZQA/NeJjnYJiI+YyHWZiJuZiPyZiSqZiQaZmMWZm0yIGUGZmRSZCNCZr7mHdqgRD9tRSx4o8R8Q1JuA+rKRCu2ZqsCZuzKZuy+YPhKBC4yVxbl0+RoWDkFDScKGl3uIBYaZzHGREoeTAmuT8PAzGhtlqCFTwzaWqYsQyW9hZ4lVcxEomgdFG71Xnk82jwlFHeIxl0KGm05yagaEbI6Z6qQRdUImGGcRfBdxw59Z75qZ+ncZgC0Z9tmYL/mYMwuTgQArqCBXqgLmigBCpgnhEh0GUenxAhZVNtz1ETVoZKrrifG8qh+/CHCKOcOPRDEtV7AqhHL7kj9+JwQhJsajJZByedAGg+LhlYGOVXo0ZjsNZadVJICVgkxdmhQToc8Uk+ZaFsyWFKQqqkSzo71NEW2zYdefN80HFtVPk/ObA9TKqlxhmiBfOh+ZQmlkEnMSWeNiZznRedt0Za89JbfPIjjUdIxRB+P7qldRomRIqmObCKxDF8duqnwX+6KdRhml8BX+l2OGtGHIIKcPUCqI2ah8zZMV26WYwERGRaiL0FUvVClKmjF3eCgC3qqKG6OXRhPaKTG3jIGwEnqqvKqtxxbdnpNFEDNeq2HYWKqFOkhq2qq0cnqeXypcN2RiVTerExnEAGpLuKrMjzJoYIGKe6GjCTrNEqrdNaIhhIrdd6ab9aMP+Erd3qrZ62RoCBWoJhU8Rgn25RTt+qruvKruj6F+0Kr4rVq6eirfFqr/eKFlCZPblhrp7RGPiACrABy65WKbAFO0X1Wi7zarALa7B0kQkauRjBlTnvyrAVa7GNip8Xq7Gzw62PtbEfu7F00XNwpC8PQIF3cawfUTMgy7It655J6rIxezAIeyodK7M3e6/sBy8WhToSqxIZi7NBK7TH16dDa7RforClQrNHy7St2hosmUf8uktm0bR2VWu1z6aqV6u13LG0pZK0Wwu2dvqU4Wpaf+EmEfEXMxC2a8u2jAWtbQu3wmGznBa3dduqdjFig3W2+0B0duu3fxtF5vObgEu4oNG1mzK3hau4SuqAI5tkY6AJGrq4k0u5BvOvlYu5YvG1mHK4meu5rzgnXIQun2BLuqU7dBRruqnbEJ1LJpuruq97fMoAgYDBqLBru7drHDCLu5+buBzDursLvEenCRNTdMFrvMcbGoOhtshbub8rJr3LvNEbecQgudJrvde7EVmLvX/rumPivNsLvsYlgeFQS77hW73lu7XfCybdi77tu1Np677xe7wy8HfyC7bQizDqa7/7O0bny7//S7mEAcBaq79egr8DjMCqpLsJzMCF678N3LLsGyYFDMEVnDVvaMFmGVy3WLq8ynNgGkxxFLwkEgzCJbwwfWvCKWy1D2xFd6HCmXbABiPCL0zDYcLCNYzDFbvAtAMEPezCObxhM5wkMQzERWwqAmzESXyxmro/OkAGQKADUvLBSqxZJPwlQkzFWYwcLaPFfl0MsNqLPEDwA2oABGoQxT/sxQuFxUdixWnsxsMBtG8sx9f6tsqjA2b8A3cMxVI8x+NExOmyxn0syBf3M4NsyMiarsuTBlH8xD/wxGbMx4d8sP4kyZWcHDdsyZm8obmKPFFMxk8MBEoEBE+sA2isyfvTxk4SyKfMyiBRFg7QyvyxnCKaEMWykcc6kMc5AMW6LBtAYMs6gMs6oMvC7Mu1HMzBPMy8bMy3nMu7XMzFzMzETMy9/MvI7MzUfMzNPM3LDMzarMzQ3M3S/M3YDMVRnM3AnMzGfMzpXMzrvMvqfMvsLBvuLMzwjM7v3M7xjM/zrM/1nM/3TMyjnMc/MMo9LMpkDARWKssyrDWpvNAPLRFFC9ETfZWczMMFDckZrctqIIoUTclZs8oefcpgLNIlPYokPTsCDcVknANkXMopa9L5yzElpQagQEgKHdOyHMeRh9M5vdCYzGllrANpsNJlfK4+vTAOTSI9jNAuXdBlDMVILdUDURYdPHm0PMWLU+3TSKw8Kn3HOgAHPa3VE8wxxMDIRQ3KkJzVY23SXH3VPVzKbB3TQN0xBP3IYS3XIPPHrQvJiyzGpEzGeZ3TO410mxDKcL3Wgq3TWbo8Xw0HMK3Y9NoxmvDXcO3SRJ3Ykf3Qvkl8U9LDZEDQca3ZsUzX6YfXox2pnHbZRX3HqO3RpY1qlK3HdxzamcLt2oP8M4OLPJB925sS0tABCrhsxixNxrbd25rsGJ2tBnlM1F/t0sZ93GkM29HNgHuNKU/d0ntM3T9tPsRn2KAM2j2c3b4M3dutxFgKqeYNi5vwMZQ93Ctd3uoNu5oQzeds3/WN3+F83/qd3/ttzr7szOIMzsrczL9M4Ntc4NZs4APO4Avu4AoO4Qku4QhO4Qdu4Q0e4RWO4RNexrr81I+My6CsA2It3xY83SWOs7gMxUSt1Cj+whaNdO690boM3j08qF0uXsOCi+NtGyXgHd87Lt2jC3pT4sme7MvFDeRaDONJXrUG3cNMLsknfmmG7dd+fcc/DuUpLBhZvrVmXcZYzuVJ7NaSBwo1PsqgEOZUjNJpPrQFzeZ9vOZGJ9vNTeJFb47AymvnTUvZYJ7nOV6/kqcMesznfW7BO0zoN9vihw7AP5PeRmfYg67oECzlkQ6wvE3pKjzpl67p3XEuxbvpnw7qxhfnOaFO6iqS6aWO6qm+WYSt6q0OHUvu6rEu67Vl6LNu68IxGOZ067vO6zplPo3e68FOGqcu7MVu7JYn5DfHruyEDOzL7uzPbnl/Du3TLhYz0+zUju3ZLiawru3dHhG17u3hLu4pksjjbu7Aee3nru7rDhxbMM7u4k6w7y7v8+4bo07vyl7H967v+/4ZEs3vy35j/y7wA48WCUbwzs7FB6/wC5+9qCzL8MFO7A8v8doe7xO/6+Bu8Rn/7hGv8W9+Ilbd8SHP7gEv8rJu7yWP8tQefysp7+ocz/Ivn+ouD/M4HhmePvM3D/DJjvObPuY77/O9Dr8/v+n5LvRFP+sGLG/0lF4Wup70Td/qMu/0rg31UU/18r2yVZ/nJ4/1W5/mRM/1Wf5bXy/2hM7tKmOP4iRv9mnP5dej9lBe9m0P99Q99XE/191N93cv3xiP972t9Xvv92zt7/9/f9ysLviFP9YobPjR7Zs5gD044JON//hmEfmOXxaQX/mSf/mUz/iYv/mab/mdP/mhn/miD/qjb/qlj/qfr/qcv/qez/qv7/qxT/qtP/uwX/uyf/q0n/u2v/u4n/q8//u+r/vBf/vF3/vGT/zHr/zJz/zD7/zA//zCD/3TL/3Vj/zRf/3Un/3Wv/zY3/3a//3c3/zgP/7i7/3lv/3pH/7qj/7r7/7tD//nL//kP//mT//3b//5z/71v//4DxAJcORAkAOHQIIGERY8OJDhQoUOIyZsSBFixYcSMU7MaFHjRZAfRXok2dEkR5QbVYYsmZLlyZUjYb50KbMmxQc5dObt2NfT50+gQYUOJVrU6FGkSZUuZdrU6VOoUaVOpVrV6lWsWbVu5drV61ewYcWOJVvWrNidadWuZdvW7Vu4ceXOpVvX7l28efXu5dvX71/AgQUPJlzY8GHEiRUvZtzY8WPIkSVPplzZ8mXMmTVv5jxjYA4ZZ0WPJl3a9GnUqVWvZt3a9WvYsWWPNajz8+3aA3Xn5r3bd2/gv4UHJz7ceHHkx5UnZ77ceXPoz6VHpz7denXs17Vn577de3fw38WHJz/efHn059WnZ7/efXv47+XHpz/ffn389/Xn57/ff38A/8OttrQc4Gk2BBNUcEEGcBt08EEII5RwQgortPBCDDPUcEMOO/TwQxBDFHFEEks08UQUU1RxRRZbdPFFGGOUcUYaa7TxRhxz1HFHHnv08UcggxRySCKLNPJIJJNUckkmm3TySSijlHJKKqu08koss9RySy679PJLMMMUc0wyyzRE80w001RzTTbbdPNNOOOUc04667TzTjzz1HNPPvv0809AAxV0UEILNfRQRBNVdFFGG3X0UUgjlXRSSiu19FJMM9V0U043O/X0U1BDFXVUUks19VRUU1V1VVZbdfVVWGOVdVZaa7X1Vlxz1XVXXnv19VdggxV2WGKLNfZYZC2TVXZZZpt19lloo5V2WmqrtfZabLPVdltuu/X2W3DDFXdccss191x001V3XXYp23X3XXjjlXdeeuu1915889V3X3779fdfgAMWeGCCCzb4YIQTVnhhhhsldvhhiCOWeGKKK7b4Yowz1nhjjjv2+GOQQxZ5ZJJLNvlklFNWeSJlllt2+WWYY5Z5ZpprtvlmnHPWeWeee/b5Z6CDFnpooos2IfpopJNWemmmm3b6aaijlnpqqqu2+mqss9Z6a6679vprsB7DFntssss2+2y001Z7bbbbdvttuOOWe26667b7brwc89Z7b7779vtvwAMXfHDCCzf8cMQTV3xxxht3/BtxyCOXfHLKK7f8cswz13xzzjv3/HPQQxd9dNIaSzf9dNRTV3111lt3/XXYY5d9dtprt/123HMZ13133nv3/Xfggxd+eOKLN/545JNXfnnmmxh3/nnoo5d+euqrt/567LPXfnvuu/f+e/AXwxd/fPLLN/989NNXf33223f/ffjjl38Yfvrrt/9+/PPXf3/++/f/fwAGUIADJGABFw14QAQmUIELZGADHfhACEZQghOkYAUtF3hBDGZQgxvkYAc9+EEQhlCEIyRhCU14GEIUplCFK2RhC134QhjGUIYzpGENbXhDHBbmUIc75GEPffhDIAZRiEMkYhGNeEQkGCZRiUtkYhOd+EQoRlGKU6RiFa14RbcFBAA7)", "_____no_output_____" ], [ "**The parameters for the model are:**\n\nTemperature and pressure of the pipe (mass transfer calculated at constant temperature and pressure).\n\nLength and diameter of pipe where gas and liquid will be in contact and mass transfer can occur.\n\nFlow rate of the gas in MSm3/day, flow rate of methanol (kg/hr).", "_____no_output_____" ], [ "#Calculation of compostion of aqueous phase and gas leaving pipe section\nIn the following script we will simulate the composition of the gas leaving pipe section at a given pipe lengt.", "_____no_output_____" ] ], [ [ "# Input parameters\npressure = 52.21 # bara\ntemperature = 15.2 #C\ngasFlow = 1.23 #MSm3/day\nmethanolFlow = 6000.23 # kg/day\n\npipelength = 10.0 #meter\npipeInnerDiameter = 0.5 #meter\n\n# Create a gas-condensate fluid\nfeedgas = {'ComponentName': [\"nitrogen\",\"CO2\",\"methane\", \"ethane\" , \"propane\", \"i-butane\", \"n-butane\", \"water\", \"methanol\"], \n 'MolarComposition[-]': [0.01, 0.01, 0.8, 0.06, 0.01,0.005,0.005, 0.0, 0.0]\n} \n\nnaturalgasFluid = fluid_df(pd.DataFrame(feedgas)).setModel(\"CPAs-SRK-EOS-statoil\")\nnaturalgasFluid.setTotalFlowRate(gasFlow, \"MSm3/day\")\nnaturalgasFluid.setTemperature(temperature, \"C\")\nnaturalgasFluid.setPressure(pressure, \"bara\")\n\n# Create a liquid methanol fluid\nfeedMeOH = {'ComponentName': [\"nitrogen\",\"CO2\",\"methane\", \"ethane\" , \"propane\", \"i-butane\", \"n-butane\", \"water\", \"methanol\"], \n 'MolarComposition[-]': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,1.0]\n} \nmeOHFluid = fluid_df(pd.DataFrame(feedMeOH) ).setModel(\"CPAs-SRK-EOS-statoil\")\nmeOHFluid.setTotalFlowRate(methanolFlow, \"kg/hr\");\nmeOHFluid.setTemperature(temperature, \"C\");\nmeOHFluid.setPressure(pressure, \"bara\");\n\nclearProcess()\ndryinjectiongas = stream(naturalgasFluid)\nMeOHFeed = stream(meOHFluid)\nwatersaturator = saturator(dryinjectiongas)\nwaterSaturatedFeedGas = stream(watersaturator.getOutStream())\n\nmainMixer = phasemixer(\"gas MeOH mixer\")\nmainMixer.addStream(waterSaturatedFeedGas)\nmainMixer.addStream(MeOHFeed)\n\t\t\npipeline = nequnit(mainMixer.getOutStream(), equipment=\"pipeline\", flowpattern=\"stratified\") #alternative flow patterns are: stratified, annular and droplet\npipeline.setLength(pipelength)\npipeline.setID(pipeInnerDiameter)\n\nscrubber = gasscrubber(pipeline.getOutStream())\ngasFromScrubber = stream(scrubber.getGasOutStream())\naqueousFromScrubber = stream(scrubber.getLiquidOutStream())\nrun()\nprint('Composition of gas leaving pipe section after ', pipelength, ' meter')\nprintFrame(gasFromScrubber.getFluid())\nprint('Composition of aqueous phase leaving pipe section after ', pipelength, ' meter')\nprintFrame(aqueousFromScrubber.getFluid())\n\nprint('Interface contact area ', pipeline.getInterfacialArea(), ' m^2')\nprint('Volume fraction aqueous phase ', pipeline.getOutStream().getFluid().getVolumeFraction(1), ' -')", "Composition of gas leaving pipe section after 10.0 meter\n total gas \n nitrogen 1.11418E-2 1.11418E-2 [mole fraction]\n CO2 1.08558E-2 1.08558E-2 [mole fraction]\n methane 8.89321E-1 8.89321E-1 [mole fraction]\n ethane 6.59386E-2 6.59386E-2 [mole fraction]\n propane 1.10391E-2 1.10391E-2 [mole fraction]\n i-butane 5.4792E-3 5.4792E-3 [mole fraction]\n n-butane 5.48529E-3 5.48529E-3 [mole fraction]\n water 3.42883E-4 3.42883E-4 [mole fraction]\n methanol 3.96384E-4 3.96384E-4 [mole fraction]\n \n Density 4.51425E1 [kg/m^3]\n PhaseFraction 1E0 [mole fraction]\n MolarMass 1.8183E1 1.8183E1 [kg/kmol]\n Z factor 8.7716E-1 [-]\n Heat Capacity (Cp) 2.54484E0 [kJ/kg*K]\n Heat Capacity (Cv) 1.65968E0 [kJ/kg*K]\n Speed of Sound 3.96268E2 [m/sec]\n Enthalpy -3.29472E1 -3.29472E1 [kJ/kg]\n Entropy -1.62974E0 -1.62974E0 [kJ/kg*K]\n JT coefficient 5.03748E-1 [K/bar]\n \n Viscosity 1.22106E-5 [kg/m*sec]\n Conductivity 3.74742E-2 [W/m*K]\n SurfaceTension [N/m]\n \n \n \n Pressure 52.21 [bar]\n Temperature 288.34999999999997 [K]\n \n Model CPAs-SRK-EOS-statoil -\n Mixing Rule classic-CPA_T -\n \n Stream -\n \n \n \n \nComposition of aqueous phase leaving pipe section after 10.0 meter\n total aqueous \n nitrogen 1.53381E-4 1.53381E-4 [mole fraction]\n CO2 3.28961E-3 3.28961E-3 [mole fraction]\n methane 3.44647E-2 3.44647E-2 [mole fraction]\n ethane 1.09255E-2 1.09255E-2 [mole fraction]\n propane 1.28029E-3 1.28029E-3 [mole fraction]\n i-butane 1.08241E-3 1.08241E-3 [mole fraction]\n n-butane 1.01559E-3 1.01559E-3 [mole fraction]\n water 8.18682E-4 8.18682E-4 [mole fraction]\n methanol 9.4697E-1 9.4697E-1 [mole fraction]\n \n Density 7.82709E2 [kg/m^3]\n PhaseFraction 1E0 [mole fraction]\n MolarMass 3.15665E1 3.15665E1 [kg/kmol]\n Z factor 8.7826E-2 [-]\n Heat Capacity (Cp) 2.26412E0 [kJ/kg*K]\n Heat Capacity (Cv) 1.885E0 [kJ/kg*K]\n Speed of Sound 1.07486E3 [m/sec]\n Enthalpy -1.14087E3 -1.14087E3 [kJ/kg]\n Entropy -3.37618E0 -3.37618E0 [kJ/kg*K]\n JT coefficient -3.74052E-2 [K/bar]\n \n Viscosity 5.85317E-4 [kg/m*sec]\n Conductivity 5.89686E-1 [W/m*K]\n SurfaceTension [N/m]\n \n \n \n Pressure 52.21 [bar]\n Temperature 288.34999999999997 [K]\n \n Model CPAs-SRK-EOS-statoil -\n Mixing Rule classic-CPA_T -\n \n Stream -\n \n \n \n \nInterface contact area 2.641129854675618 m^2\nVolume fraction aqueous phase 0.011201474850165916 -\n" ] ], [ [ "# Calculation of hydrate equilibrium temperature of gas leaving pipe section\nIn the following script we will simulate the composition of the gas leaving pipe section as well as hydrate equilibrium temperature of this gas as function of pipe length.", "_____no_output_____" ] ], [ [ "maxpipelength = 10.0\n\ndef hydtemps(length):\n pipeline.setLength(length)\n run();\n return gasFromScrubber.getHydrateEquilibriumTemperature()-273.15\n\nlength = np.arange(0.01, maxpipelength, (maxpipelength)/10.0)\nhydtem = [hydtemps(length2) for length2 in length]\n\nplt.figure()\nplt.plot(length, hydtem)\nplt.xlabel('Length available for mass transfer [m]')\nplt.ylabel('Hydrate eq.temperature [C]')\nplt.title('Hydrate eq.temperature of gas leaving pipe section')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0108f0bf340e898e4dbdfdd3c5c850793364945
43,385
ipynb
Jupyter Notebook
notebooks/6.Incorporating_Related_Time_Series_dataset_to_your_Predictor.ipynb
ardilacarlosh/amazon-forecast-samples
3a516e5b9b2af745546784178fcea115eda3008c
[ "MIT-0" ]
null
null
null
notebooks/6.Incorporating_Related_Time_Series_dataset_to_your_Predictor.ipynb
ardilacarlosh/amazon-forecast-samples
3a516e5b9b2af745546784178fcea115eda3008c
[ "MIT-0" ]
null
null
null
notebooks/6.Incorporating_Related_Time_Series_dataset_to_your_Predictor.ipynb
ardilacarlosh/amazon-forecast-samples
3a516e5b9b2af745546784178fcea115eda3008c
[ "MIT-0" ]
null
null
null
31.257205
1,024
0.569575
[ [ [ "# Amazon Forecast: predicting time-series at scale\n\nForecasting is used in a variety of applications and business use cases: For example, retailers need to forecast the sales of their products to decide how much stock they need by location, Manufacturers need to estimate the number of parts required at their factories to optimize their supply chain, Businesses need to estimate their flexible workforce needs, Utilities need to forecast electricity consumption needs in order to attain an efficient energy network, and \nenterprises need to estimate their cloud infrastructure needs.", "_____no_output_____" ], [ "<img src=\"BlogImages/amazon_forecast.png\">\n\n\n# Table of Contents\n\n* Step 0: [Setting up](#setup)\n* Step 1: [Preparing the Datasets](#prepare)\n* Step 2: [Importing the Data](#import)\n * Step 2a: [Creating a Dataset Group](#create)\n * Step 2b: [Creating a Target Dataset](#target)\n * Step 2c: [Creating a Related Dataset](#related)\n * Step 2d: [Update the Dataset Group](#update)\n * Step 2e: [Creating a Target Time Series Dataset Import Job](#targetImport)\n * Step 2f: [Creating a Related Time Series Dataset Import Job](#relatedImport)\n* Step 3: [Choosing an Algorithm and Evaluating its Performance](#algo)\n * Step 3a: [Choosing DeepAR+](#DeepAR)\n * Step 3b: [Choosing Prophet](#prophet)\n* Step 4: [Computing Error Metrics from Backtesting](#error)\n* Step 5: [Creating a Forecast](#forecast)\n* Step 6: [Querying the Forecasts](#query)\n* Step 7: [Exporting the Forecasts](#export)\n* Step 8: [Clearning up your Resources](#cleanup)\n", "_____no_output_____" ], [ "# First let us setup Amazon Forecast<a class=\"anchor\" id=\"setup\">\n\nThis section sets up the permissions and relevant endpoints.", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2\nfrom util.fcst_utils import *\nimport warnings\nimport boto3\nimport s3fs\nplt.rcParams['figure.figsize'] = (15.0, 5.0)\nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "Although, we have set the region to us-west-2 below, you can choose any of the 6 regions that the service is available in.", "_____no_output_____" ] ], [ [ "region = 'us-west-2'\nbucket = 'bike-demo'\nversion = 'prod'", "_____no_output_____" ], [ "session = boto3.Session(region_name=region) \nforecast = session.client(service_name='forecast') \nforecast_query = session.client(service_name='forecastquery')", "_____no_output_____" ], [ "role_arn = get_or_create_role_arn()", "_____no_output_____" ] ], [ [ "# Overview\n\n<img src=\"BlogImages/outline.png\">\n\n<img src=\"BlogImages/forecast_workflow.png\">\n\nThe above figure summarizes the key workflow of using Forecast. ", "_____no_output_____" ], [ "# Step 1: Preparing the Datasets<a class=\"anchor\" id=\"prepare\">", "_____no_output_____" ] ], [ [ "bike_df = pd.read_csv(\"../data/train.csv\", dtype = object)\nbike_df.head()", "_____no_output_____" ], [ "bike_df['count'] = bike_df['count'].astype('float')\nbike_df['workingday'] = bike_df['workingday'].astype('float')", "_____no_output_____" ] ], [ [ "We take about two and a half week's of hourly data for demonstration, just for the purpose that there's no missing data in the whole range.", "_____no_output_____" ] ], [ [ "bike_df_small = bike_df[-2*7*24-24*3:]\nbike_df_small['item_id'] = \"bike_12\"", "_____no_output_____" ] ], [ [ "Let us plot the time series first.", "_____no_output_____" ] ], [ [ "bike_df_small.plot(x='datetime', y='count', figsize=(15, 8))", "_____no_output_____" ] ], [ [ "We can see that the target time series seem to have a drop over weekends. Next let's plot both the target time series and the related time series that indicates whether today is a `workday` or not. More precisely, $r_t = 1$ if $t$ is a work day and 0 if not.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(15, 8))\nax = plt.gca()\nbike_df_small.plot(x='datetime', y='count', ax=ax);\nax2 = ax.twinx()\nbike_df_small.plot(x='datetime', y='workingday', color='red', ax=ax2);", "_____no_output_____" ] ], [ [ "Notice that to use the related time series, we need to ensure that the related time series covers the whole target time series, as well as the future values as specified by the forecast horizon. More precisely, we need to make sure:\n```\nlen(related time series) >= len(target time series) + forecast horizon\n```\nBasically, all items need to have data start at or before the item start date, and have data until the forecast horizon (i.e. the latest end date across all items + forecast horizon). Additionally, there should be no missing values in the related time series. The following picture illustrates the desired logic. \n\n<img src=\"BlogImages/rts_viz.png\">\n\nFor more details regarding how to prepare your Related Time Series dataset, please refer to the public documentation <a href=\"https://docs.aws.amazon.com/forecast/latest/dg/related-time-series-datasets.html\">here</a>. \n\nSuppose in this particular example, we wish to forecast for the next 24 hours, and thus we generate the following dataset.", "_____no_output_____" ] ], [ [ "target_df = bike_df_small[['item_id', 'datetime', 'count']][:-24]\nrts_df = bike_df_small[['item_id', 'datetime', 'workingday']]", "_____no_output_____" ], [ "target_df.head(5)", "_____no_output_____" ] ], [ [ "As we can see, the length of the related time series is equal to the length of the target time series plus the forecast horizon. ", "_____no_output_____" ] ], [ [ "print(len(target_df), len(rts_df))\nassert len(target_df) + 24 == len(rts_df), \"length doesn't match\"", "_____no_output_____" ] ], [ [ "Next we check whether there are \"holes\" in the related time series. ", "_____no_output_____" ] ], [ [ "assert len(rts_df) == len(pd.date_range(\n start=list(rts_df['datetime'])[0],\n end=list(rts_df['datetime'])[-1],\n freq='H'\n)), \"missing entries in the related time series\"", "_____no_output_____" ] ], [ [ "Everything looks fine, and we plot both time series again. As it can be seen, the related time series (indicator of whether the current day is a workday or not) is longer than the target time series. The binary working day indicator feature is a good example of a related time series, since it is known at all future time points. Other examples of related time series include holiday and promotion features.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(15, 10))\nax = plt.gca()\ntarget_df.plot(x='datetime', y='count', ax=ax);\nax2 = ax.twinx()\nrts_df.plot(x='datetime', y='workingday', color='red', ax=ax2);", "_____no_output_____" ], [ "target_df.to_csv(\"../data/bike_small.csv\", index= False, header = False)\nrts_df.to_csv(\"../data/bike_small_rts.csv\", index= False, header = False)", "_____no_output_____" ], [ "s3 = session.client('s3')\naccount_id = boto3.client('sts').get_caller_identity().get('Account')", "_____no_output_____" ] ], [ [ "If you don't have this bucket `amazon-forecast-data-{account_id}`, create it first on S3.", "_____no_output_____" ] ], [ [ "bucket_name = f\"amazon-forecast-data-{account_id}\"\nkey = \"bike_small\"\n\ns3.upload_file(Filename=\"../data/bike_small.csv\", Bucket = bucket_name, Key = f\"{key}/bike.csv\")\ns3.upload_file(Filename=\"../data/bike_small_rts.csv\", Bucket = bucket_name, Key = f\"{key}/bike_rts.csv\")", "_____no_output_____" ] ], [ [ "# Step 2. Importing the Data<a class=\"anchor\" id=\"import\">\n\n\nNow we are ready to import the datasets into the Forecast service. Starting from the raw data, Amazon Forecast automatically extracts the dataset that is suitable for forecasting. As an example, a retailer normally records the transaction record such as\n<img src=\"BlogImages/data_format.png\">\n<img src=\"BlogImages/timestamp.png\">\n\n", "_____no_output_____" ] ], [ [ "project = \"bike_rts_demo\"\nidx = 4", "_____no_output_____" ], [ "s3_data_path = f\"s3://{bucket_name}/{key}\"", "_____no_output_____" ] ], [ [ "Below, we specify key input data and forecast parameters", "_____no_output_____" ] ], [ [ "freq = \"H\"\nforecast_horizon = 24\ntimestamp_format = \"yyyy-MM-dd HH:mm:ss\"\ndelimiter = ','", "_____no_output_____" ] ], [ [ "## Step 2a. Creating a Dataset Group<a class=\"anchor\" id=\"create\">\nFirst let's create a dataset group and then update it later to add our datasets.", "_____no_output_____" ] ], [ [ "dataset_group = f\"{project}_gp_{idx}\"\ndataset_arns = []\ncreate_dataset_group_response = forecast.create_dataset_group(Domain=\"RETAIL\",\n DatasetGroupName=dataset_group,\n DatasetArns=dataset_arns)", "_____no_output_____" ], [ "logging.info(f'Creating dataset group {dataset_group}')", "_____no_output_____" ], [ "dataset_group_arn = create_dataset_group_response['DatasetGroupArn']", "_____no_output_____" ], [ "forecast.describe_dataset_group(DatasetGroupArn=dataset_group_arn)", "_____no_output_____" ] ], [ [ "## Step 2b. Creating a Target Dataset<a class=\"anchor\" id=\"target\">\nIn this example, we will define a target time series. This is a required dataset to use the service.", "_____no_output_____" ], [ "Below we specify the target time series name af_demo_ts_4.", "_____no_output_____" ] ], [ [ "ts_dataset_name = f\"{project}_ts_{idx}\"\nprint(ts_dataset_name)", "_____no_output_____" ] ], [ [ "Next, we specify the schema of our dataset below. Make sure the order of the attributes (columns) matches the raw data in the files. We follow the same three attribute format as the above example.", "_____no_output_____" ] ], [ [ "ts_schema_val = [{\"AttributeName\": \"item_id\", \"AttributeType\": \"string\"},\n {\"AttributeName\": \"timestamp\", \"AttributeType\": \"timestamp\"},\n {\"AttributeName\": \"demand\", \"AttributeType\": \"float\"}]\nts_schema = {\"Attributes\": ts_schema_val}", "_____no_output_____" ], [ "logging.info(f'Creating target dataset {ts_dataset_name}')", "_____no_output_____" ], [ "response = forecast.create_dataset(Domain=\"RETAIL\",\n DatasetType='TARGET_TIME_SERIES',\n DatasetName=ts_dataset_name,\n DataFrequency=freq,\n Schema=ts_schema\n )", "_____no_output_____" ], [ "ts_dataset_arn = response['DatasetArn']", "_____no_output_____" ], [ "forecast.describe_dataset(DatasetArn=ts_dataset_arn)", "_____no_output_____" ] ], [ [ "## Step 2c. Creating a Related Dataset<a class=\"anchor\" id=\"related\">\nIn this example, we will define a related time series.", "_____no_output_____" ], [ "Specify the related time series name af_demo_rts_4.", "_____no_output_____" ] ], [ [ "rts_dataset_name = f\"{project}_rts_{idx}\"\nprint(rts_dataset_name)", "_____no_output_____" ] ], [ [ "Specify the schema of your dataset here. Make sure the order of columns matches the raw data files. We follow the same three column format as the above example.", "_____no_output_____" ] ], [ [ "rts_schema_val = [{\"AttributeName\": \"item_id\", \"AttributeType\": \"string\"},\n {\"AttributeName\": \"timestamp\", \"AttributeType\": \"timestamp\"},\n {\"AttributeName\": \"price\", \"AttributeType\": \"float\"}]\nrts_schema = {\"Attributes\": rts_schema_val}", "_____no_output_____" ], [ "logging.info(f'Creating related dataset {rts_dataset_name}')", "_____no_output_____" ], [ "response = forecast.create_dataset(Domain=\"RETAIL\",\n DatasetType='RELATED_TIME_SERIES',\n DatasetName=rts_dataset_name,\n DataFrequency=freq,\n Schema=rts_schema\n )", "_____no_output_____" ], [ "rts_dataset_arn = response['DatasetArn']", "_____no_output_____" ], [ "forecast.describe_dataset(DatasetArn=rts_dataset_arn)", "_____no_output_____" ] ], [ [ "## Step 2d. Updating the dataset group with the datasets we created<a class=\"anchor\" id=\"update\">\nYou can have multiple datasets under the same dataset group. Update it with the datasets we created before.", "_____no_output_____" ] ], [ [ "dataset_arns = []\ndataset_arns.append(ts_dataset_arn)\ndataset_arns.append(rts_dataset_arn)\nforecast.update_dataset_group(DatasetGroupArn=dataset_group_arn, DatasetArns=dataset_arns)", "_____no_output_____" ], [ "forecast.describe_dataset_group(DatasetGroupArn=dataset_group_arn)", "_____no_output_____" ] ], [ [ "## Step 2e. Creating a Target Time Series Dataset Import Job<a class=\"anchor\" id=\"targetImport\">", "_____no_output_____" ] ], [ [ "ts_s3_data_path = f\"{s3_data_path}/bike.csv\"", "_____no_output_____" ], [ "ts_dataset_import_job_response = forecast.create_dataset_import_job(DatasetImportJobName=dataset_group,\n DatasetArn=ts_dataset_arn,\n DataSource= {\n \"S3Config\" : {\n \"Path\": ts_s3_data_path,\n \"RoleArn\": role_arn\n } \n },\n TimestampFormat=timestamp_format)", "_____no_output_____" ], [ "ts_dataset_import_job_arn=ts_dataset_import_job_response['DatasetImportJobArn']", "_____no_output_____" ], [ "status = wait(lambda: forecast.describe_dataset_import_job(DatasetImportJobArn=ts_dataset_import_job_arn))\nassert status", "_____no_output_____" ] ], [ [ "## Step 2f. Creating a Related Time Series Dataset Import Job<a class=\"anchor\" id=\"relatedImport\">", "_____no_output_____" ] ], [ [ "rts_s3_data_path = f\"{s3_data_path}/bike_rts.csv\"", "_____no_output_____" ], [ "rts_dataset_import_job_response = forecast.create_dataset_import_job(DatasetImportJobName=dataset_group,\n DatasetArn=rts_dataset_arn,\n DataSource= {\n \"S3Config\" : {\n \"Path\": rts_s3_data_path,\n \"RoleArn\": role_arn\n } \n },\n TimestampFormat=timestamp_format)", "_____no_output_____" ], [ "rts_dataset_import_job_arn=rts_dataset_import_job_response['DatasetImportJobArn']", "_____no_output_____" ], [ "status = wait(lambda: forecast.describe_dataset_import_job(DatasetImportJobArn=rts_dataset_import_job_arn))\nassert status", "_____no_output_____" ] ], [ [ "# Step 3. Choosing an algorithm and evaluating its performance<a class=\"anchor\" id=\"algo\">\n\nOnce the datasets are specified with the corresponding schema, Amazon Forecast will automatically aggregate all the relevant pieces of information for each item, such as sales, price, promotions, as well as categorical attributes, and generate the desired dataset. Next, one can choose an algorithm (forecasting model) and evaluate how well this particular algorithm works on this dataset. The following graph gives a high-level overview of the forecasting models.\n<img src=\"BlogImages/recipes.png\">\n<img src=\"BlogImages/pred_details.png\">\n\n\nAmazon Forecast provides several state-of-the-art forecasting algorithms including classic forecasting methods such as ETS, ARIMA, Prophet and deep learning approaches such as DeepAR+. Classical forecasting methods, such as Autoregressive Integrated Moving Average (ARIMA) or Exponential Smoothing (ETS), fit a single model to each individual time series, and then use that model to extrapolate the time series into the future. Amazon's Non-Parametric Time Series (NPTS) forecaster also fits a single model to each individual time series. Unlike the naive or seasonal naive forecasters that use a fixed time index (the previous index $T-1$ or the past season $T - \\tau$) as the prediction for time step $T$, NPTS randomly samples a time index $t \\in \\{0, \\dots T-1\\}$ in the past to generate a sample for the current time step $T$.\n\nIn many applications, you may encounter many similar time series across a set of cross-sectional units. Examples of such time series groupings are demand for different products, server loads, and requests for web pages. In this case, it can be beneficial to train a single model jointly over all of these time series. DeepAR+ takes this approach, outperforming the standard ARIMA and ETS methods when your dataset contains hundreds of related time series. The trained model can also be used for generating forecasts for new time series that are similar to the ones it has been trained on. While deep learning approaches can outperform standard methods, this is only possible when there is sufficient data available for training. It is not true for example when one trains a neural network with a time-series contains only a few dozens of observations. Amazon Forecast provides the best of two worlds allowing users to either choose a specific algorithm or let Amazon Forecast automatically perform model selection. \n\n## How to evaluate a forecasting model?\n\nBefore moving forward, let's first introduce the notion of *backtest* when evaluating forecasting models. The key difference between evaluating forecasting algorithms and standard ML applications is that we need to make sure there is no future information gets used in the past. In other words, the procedure needs to be causal. \n\n<img src=\"BlogImages/backtest.png\">\n\n\nIn this notebook, let's compare the neural network based method, DeepAR+ with Facebook's open-source Bayesian method Prophet. \n", "_____no_output_____" ] ], [ [ "algorithm_arn = 'arn:aws:forecast:::algorithm/'", "_____no_output_____" ] ], [ [ "## Step 3a. Choosing DeepAR+<a class=\"anchor\" id=\"DeepAR\">", "_____no_output_____" ] ], [ [ "algorithm = 'Deep_AR_Plus'\nalgorithm_arn_deep_ar_plus = algorithm_arn + algorithm\npredictor_name_deep_ar = f'{project}_{algorithm.lower()}_{idx}'", "_____no_output_____" ], [ "logging.info(f'[{predictor_name_deep_ar}] Creating predictor {predictor_name_deep_ar} ...')", "_____no_output_____" ], [ "create_predictor_response = forecast.create_predictor(PredictorName=predictor_name_deep_ar,\n AlgorithmArn=algorithm_arn_deep_ar_plus,\n ForecastHorizon=forecast_horizon,\n PerformAutoML=False,\n PerformHPO=False,\n InputDataConfig= {\"DatasetGroupArn\": dataset_group_arn},\n FeaturizationConfig= {\"ForecastFrequency\": freq}\n )", "_____no_output_____" ], [ "predictor_arn_deep_ar = create_predictor_response['PredictorArn']", "_____no_output_____" ], [ "status = wait(lambda: forecast.describe_predictor(PredictorArn=predictor_arn_deep_ar))\nassert status", "_____no_output_____" ], [ "forecast.describe_predictor(PredictorArn=predictor_arn_deep_ar)", "_____no_output_____" ] ], [ [ "## Step 3b. Choosing Prophet<a class=\"anchor\" id=\"prophet\">", "_____no_output_____" ] ], [ [ "algorithm = 'Prophet'\nalgorithm_arn_prophet = algorithm_arn + algorithm\npredictor_name_prophet = f'{project}_{algorithm.lower()}_{idx}'", "_____no_output_____" ], [ "algorithm_arn_prophet", "_____no_output_____" ], [ "logging.info(f'[{predictor_name_prophet}] Creating predictor %s ...' % predictor_name_prophet)", "_____no_output_____" ], [ "create_predictor_response = forecast.create_predictor(PredictorName=predictor_name_prophet,\n AlgorithmArn=algorithm_arn_prophet,\n ForecastHorizon=forecast_horizon,\n PerformAutoML=False,\n PerformHPO=False,\n InputDataConfig= {\"DatasetGroupArn\": dataset_group_arn},\n FeaturizationConfig= {\"ForecastFrequency\": freq}\n )", "_____no_output_____" ], [ "predictor_arn_prophet = create_predictor_response['PredictorArn']", "_____no_output_____" ], [ "status = wait(lambda: forecast.describe_predictor(PredictorArn=predictor_arn_prophet))\nassert status", "_____no_output_____" ], [ "forecast.describe_predictor(PredictorArn=predictor_arn_prophet)", "_____no_output_____" ] ], [ [ "# Step 4. Computing Error Metrics from Backtesting<a class=\"anchor\" id=\"error\">", "_____no_output_____" ], [ "After creating the predictors, we can query the forecast accuracy given by the backtest scenario and have a quantitative understanding of the performance of the algorithm. Such a process is iterative in nature during model development. When an algorithm with satisfying performance is found, the customer can deploy the predictor into a production environment, and query the forecasts for a particular item to make business decisions. The figure below shows a sample plot of different quantile forecasts of a predictor.", "_____no_output_____" ] ], [ [ "logging.info('Done creating predictor. Getting accuracy numbers for DeepAR+ ...')", "_____no_output_____" ], [ "error_metrics_deep_ar_plus = forecast.get_accuracy_metrics(PredictorArn=predictor_arn_deep_ar)\nerror_metrics_deep_ar_plus", "_____no_output_____" ], [ "logging.info('Done creating predictor. Getting accuracy numbers for Prophet ...')", "_____no_output_____" ], [ "error_metrics_prophet = forecast.get_accuracy_metrics(PredictorArn=predictor_arn_prophet)\nerror_metrics_prophet", "_____no_output_____" ], [ "def extract_summary_metrics(metric_response, predictor_name):\n df = pd.DataFrame(metric_response['PredictorEvaluationResults']\n [0]['TestWindows'][0]['Metrics']['WeightedQuantileLosses'])\n df['Predictor'] = predictor_name\n return df", "_____no_output_____" ], [ "deep_ar_metrics = extract_summary_metrics(error_metrics_deep_ar_plus, \"DeepAR\")\nprophet_metrics = extract_summary_metrics(error_metrics_prophet, \"Prophet\")", "_____no_output_____" ], [ "pd.concat([deep_ar_metrics, prophet_metrics]) \\\n .pivot(index='Quantile', columns='Predictor', values='LossValue').plot.bar();", "_____no_output_____" ] ], [ [ "As we mentioned before, if you only have a handful of time series (in this case, only 1) with a small number of examples, the neural network models (DeepAR+) are not the best choice. Here, we clearly see that DeepAR+ behaves worse than Prophet in the case of a single time series. ", "_____no_output_____" ], [ "# Step 5. Creating a Forecast<a class=\"anchor\" id=\"forecast\">\n\nNext we re-train with the full dataset, and create the forecast.", "_____no_output_____" ] ], [ [ "logging.info(f\"Done fetching accuracy numbers. Creating forecaster for DeepAR+ ...\")", "_____no_output_____" ], [ "forecast_name_deep_ar = f'{project}_deep_ar_plus_{idx}'", "_____no_output_____" ], [ "create_forecast_response_deep_ar = forecast.create_forecast(ForecastName=forecast_name_deep_ar,\n PredictorArn=predictor_arn_deep_ar)", "_____no_output_____" ], [ "forecast_arn_deep_ar = create_forecast_response_deep_ar['ForecastArn']", "_____no_output_____" ], [ "status = wait(lambda: forecast.describe_forecast(ForecastArn=forecast_arn_deep_ar))\nassert status", "_____no_output_____" ], [ "forecast.describe_forecast(ForecastArn=forecast_arn_deep_ar)", "_____no_output_____" ], [ "logging.info(f\"Done fetching accuracy numbers. Creating forecaster for Prophet ...\")", "_____no_output_____" ], [ "forecast_name_prophet = f'{project}_prophet_{idx}'", "_____no_output_____" ], [ "create_forecast_response_prophet = forecast.create_forecast(ForecastName=forecast_name_prophet,\n PredictorArn=predictor_arn_prophet)", "_____no_output_____" ], [ "forecast_arn_prophet = create_forecast_response_prophet['ForecastArn']", "_____no_output_____" ], [ "status = wait(lambda: forecast.describe_forecast(ForecastArn=forecast_arn_prophet))\nassert status", "_____no_output_____" ], [ "forecast.describe_forecast(ForecastArn=forecast_arn_prophet)", "_____no_output_____" ] ], [ [ "# Step 6. Querying the Forecasts<a class=\"anchor\" id=\"query\">", "_____no_output_____" ] ], [ [ "item_id = 'bike_12'", "_____no_output_____" ], [ "forecast_response_deep = forecast_query.query_forecast(\n ForecastArn=forecast_arn_deep_ar,\n Filters={\"item_id\": item_id})", "_____no_output_____" ], [ "forecast_response_prophet = forecast_query.query_forecast(ForecastArn=forecast_arn_prophet,\n Filters={\"item_id\":item_id})", "_____no_output_____" ], [ "fname = f'../data/bike_small.csv'\nexact = load_exact_sol(fname, item_id)", "_____no_output_____" ], [ "plot_forecasts(forecast_response_deep, exact)\nplt.title(\"DeepAR Forecast\");", "_____no_output_____" ], [ "plot_forecasts(forecast_response_prophet,exact)\nplt.title(\"Prophet Forecast\");", "_____no_output_____" ] ], [ [ "# Step 7. Exporting your Forecasts<a class=\"anchor\" id=\"export\">", "_____no_output_____" ] ], [ [ "forecast_export_name_deep_ar = f'{project}_forecast_export_deep_ar_plus_{idx}'\nforecast_export_name_deep_ar_path = f\"{s3_data_path}/{forecast_export_name_deep_ar}\"", "_____no_output_____" ], [ "create_forecast_export_response_deep_ar = forecast.create_forecast_export_job(ForecastExportJobName=forecast_export_name_deep_ar,\n ForecastArn=forecast_arn_deep_ar,\n Destination={\n \"S3Config\" : {\n \"Path\": forecast_export_name_deep_ar_path,\n \"RoleArn\": role_arn\n }\n })\nforecast_export_arn_deep_ar = create_forecast_export_response_deep_ar['ForecastExportJobArn']", "_____no_output_____" ], [ "status = wait(lambda: forecast.describe_forecast_export_job(ForecastExportJobArn = forecast_export_arn_deep_ar))\nassert status", "_____no_output_____" ], [ "forecast_export_name_prophet = f'{project}_forecast_export_prophet_{idx}'\nforecast_export_name_prophet_path = f\"{s3_data_path}/{forecast_export_name_prophet}\"", "_____no_output_____" ], [ "create_forecast_export_response_prophet = forecast.create_forecast_export_job(ForecastExportJobName=forecast_export_name_prophet,\n ForecastArn=forecast_arn_prophet,\n Destination={\n \"S3Config\" : {\n \"Path\": forecast_export_name_prophet_path,\n \"RoleArn\": role_arn\n }\n })\nforecast_export_arn_prophet = create_forecast_export_response_prophet['ForecastExportJobArn']", "_____no_output_____" ], [ "status = wait(lambda: forecast.describe_forecast_export_job(ForecastExportJobArn = forecast_export_arn_prophet))\nassert status", "_____no_output_____" ] ], [ [ "# Step 8. Cleaning up your Resources<a class=\"anchor\" id=\"cleanup\">", "_____no_output_____" ], [ "Once we have completed the above steps, we can start to cleanup the resources we created. All delete jobs, except for `delete_dataset_group` are asynchronous, so we have added the helpful `wait_till_delete` function. \nResource Limits documented <a href=\"https://docs.aws.amazon.com/forecast/latest/dg/limits.html\">here</a>. ", "_____no_output_____" ] ], [ [ "# Delete forecast export for both algorithms\nwait_till_delete(lambda: forecast.delete_forecast_export_job(ForecastExportJobArn = forecast_export_arn_deep_ar))\nwait_till_delete(lambda: forecast.delete_forecast_export_job(ForecastExportJobArn = forecast_export_arn_prophet))", "_____no_output_____" ], [ "# Delete forecast for both algorithms\nwait_till_delete(lambda: forecast.delete_forecast(ForecastArn = forecast_arn_deep_ar))\nwait_till_delete(lambda: forecast.delete_forecast(ForecastArn = forecast_arn_prophet))", "_____no_output_____" ], [ "# Delete predictor for both algorithms\nwait_till_delete(lambda: forecast.delete_predictor(PredictorArn = predictor_arn_deep_ar))\nwait_till_delete(lambda: forecast.delete_predictor(PredictorArn = predictor_arn_prophet))", "_____no_output_____" ], [ "# Delete the target time series and related time series dataset import jobs\nwait_till_delete(lambda: forecast.delete_dataset_import_job(DatasetImportJobArn=ts_dataset_import_job_arn))\nwait_till_delete(lambda: forecast.delete_dataset_import_job(DatasetImportJobArn=rts_dataset_import_job_arn))", "_____no_output_____" ], [ "# Delete the target time series and related time series datasets\nwait_till_delete(lambda: forecast.delete_dataset(DatasetArn=ts_dataset_arn))\nwait_till_delete(lambda: forecast.delete_dataset(DatasetArn=rts_dataset_arn))", "_____no_output_____" ], [ "# Delete dataset group\nforecast.delete_dataset_group(DatasetGroupArn=dataset_group_arn)", "_____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", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d010a03c84b208f351e5fda95c1999b11c77618b
13,465
ipynb
Jupyter Notebook
notebooks/scratchpad.ipynb
nkrishnaswami/census-data-aggregator
27bc8aae25473604aa48f26b8b038e366685d566
[ "MIT" ]
null
null
null
notebooks/scratchpad.ipynb
nkrishnaswami/census-data-aggregator
27bc8aae25473604aa48f26b8b038e366685d566
[ "MIT" ]
2
2021-02-02T23:29:34.000Z
2021-06-02T03:52:38.000Z
notebooks/scratchpad.ipynb
nkrishnaswami/census-data-aggregator
27bc8aae25473604aa48f26b8b038e366685d566
[ "MIT" ]
null
null
null
29.082073
163
0.540364
[ [ [ "# Census aggregation scratchpad\n\nBy [Ben Welsh](https://palewi.re/who-is-ben-welsh/)", "_____no_output_____" ] ], [ [ "import math", "_____no_output_____" ] ], [ [ "### Approximation", "_____no_output_____" ], [ "![](https://assets.documentcloud.org/documents/6162551/pages/20180418-MOE-p50-normal.gif)\n![](https://assets.documentcloud.org/documents/6162551/pages/20180418-MOE-p51-normal.gif)", "_____no_output_____" ] ], [ [ "males_under_5, males_under_5_moe = 10154024, 3778", "_____no_output_____" ], [ "females_under_5, females_under_5_moe = 9712936, 3911", "_____no_output_____" ], [ "total_under_5 = males_under_5 + females_under_5", "_____no_output_____" ], [ "total_under_5", "_____no_output_____" ], [ "total_under_5_moe = math.sqrt(males_under_5_moe**2 + females_under_5_moe**2)", "_____no_output_____" ], [ "total_under_5_moe", "_____no_output_____" ] ], [ [ "![](https://assets.documentcloud.org/documents/6162551/pages/20180418-MOE-p52-normal.gif?1561126109)", "_____no_output_____" ] ], [ [ "def approximate_margin_of_error(*pairs):\n \"\"\"\n Returns the approximate margin of error after combining all of the provided Census Bureau estimates, taking into account each value's margin of error.\n \n Expects a series of arguments, each a paired list with the estimated value first and the margin of error second.\n \"\"\"\n # According to the Census Bureau, when approximating a sum use only the largest zero estimate margin of error, once\n # https://www.documentcloud.org/documents/6162551-20180418-MOE.html#document/p52\n zeros = [p for p in pairs if p[0] == 0]\n if len(zeros) > 1:\n max_zero_margin = max([p[1] for p in zeros])\n not_zero_margins = [p[1] for p in pairs if p[0] != 0]\n margins = [max_zero_margin] + not_zero_margins\n else:\n margins = [p[1] for p in pairs]\n return math.sqrt(sum([m**2 for m in margins])) ", "_____no_output_____" ], [ "approximate_margin_of_error(\n (males_under_5, males_under_5_moe),\n (females_under_5, females_under_5_moe)\n)", "_____no_output_____" ], [ "approximate_margin_of_error(\n [0, 22],\n [0, 22],\n [0, 29],\n [41, 37]\n)", "_____no_output_____" ] ], [ [ "### Aggregating totals", "_____no_output_____" ] ], [ [ "def total(*pairs):\n \"\"\"\n Returns the combined value of all the provided Census Bureau estimates, along with an approximated margin of error.\n \n Expects a series of arguments, each a paired list with the estimated value first and the margin of error second.\n \"\"\"\n return sum([p[0] for p in pairs]), approximate_margin_of_error(*pairs)", "_____no_output_____" ], [ "total(\n (males_under_5, males_under_5_moe),\n (females_under_5, females_under_5_moe)\n)", "_____no_output_____" ], [ "total(\n [0, 22],\n [0, 22],\n [0, 29],\n [41, 37]\n)", "_____no_output_____" ] ], [ [ "### Aggregating medians", "_____no_output_____" ], [ "![](https://assets.documentcloud.org/documents/6165014/pages/How-to-Recalculate-a-Median-p1-normal.gif?1561138970)\n![](https://assets.documentcloud.org/documents/6165014/pages/How-to-Recalculate-a-Median-p2-normal.gif?1561138970)\n![](https://assets.documentcloud.org/documents/6165014/pages/How-to-Recalculate-a-Median-p3-normal.gif?1561138970)\n![](https://assets.documentcloud.org/documents/6165014/pages/How-to-Recalculate-a-Median-p4-normal.gif?1561138970)", "_____no_output_____" ] ], [ [ "def approximate_median(range_list, design_factor=1.5):\n \"\"\"\n Returns the estimated median from a set of ranged totals.\n\n Useful for generated medians for measures like median household income and median agn when aggregating census geographies.\n\n Expects a list of dictionaries with three keys:\n\n min: The minimum value in the range\n max: The maximum value in the range\n n: The number of people, households or other universe figure in the range\n \"\"\"\n # Sort the list\n range_list.sort(key=lambda x: x['min'])\n\n # For each range calculate its min and max value along the universe's scale\n cumulative_n = 0\n for range_ in range_list:\n range_['n_min'] = cumulative_n\n cumulative_n += range_['n']\n range_['n_max'] = cumulative_n\n\n # What is the total number of observations in the universe?\n n = sum([d['n'] for d in range_list])\n \n # What is the estimated midpoint of the n?\n n_midpoint = n / 2.0\n\n # Now use those to determine which group contains the midpoint.\n try:\n n_midpoint_range = next(d for d in range_list if n_midpoint >= d['n_min'] and n_midpoint <= d['n_max'])\n except StopIteration:\n raise StopIteration(\"The n's midpoint does not fall within a data range.\")\n\n # How many households in the midrange are needed to reach the midpoint?\n n_midrange_gap = n_midpoint - n_midpoint_range['n_min']\n\n # What is the proportion of the group that would be needed to get the midpoint?\n n_midrange_gap_percent = n_midrange_gap / n_midpoint_range['n']\n\n # Apply this proportion to the width of the midrange\n n_midrange_gap_adjusted = (n_midpoint_range['max'] - n_midpoint_range['min']) * n_midrange_gap_percent\n\n # Estimate the median\n estimated_median = n_midpoint_range['min'] + n_midrange_gap_adjusted\n \n # Get the standard error for this dataset\n standard_error = (design_factor * math.sqrt((99/n)*(50**2))) / 100\n \n # Use the standard error to calculate the p values\n p_lower = (.5 - standard_error)\n p_upper = (.5 + standard_error)\n \n # Estimate the p_lower and p_upper n values\n p_lower_n = n * p_lower\n p_upper_n = n * p_upper\n \n # Find the ranges the p values fall within\n try:\n p_lower_range_i, p_lower_range = next(\n (i, d) for i, d in enumerate(range_list)\n if p_lower_n >= d['n_min'] and p_lower_n <= d['n_max']\n )\n except StopIteration:\n raise StopIteration(\"The n's lower p value does not fall within a data range.\")\n\n try:\n p_upper_range_i, p_upper_range = next(\n (i, d) for i, d in enumerate(range_list)\n if p_upper_n >= d['n_min'] and p_upper_n <= d['n_max']\n )\n except StopIteration:\n raise StopIteration(\"The n's higher p value does not fall within a data range.\")\n \n # Use these values to estimate the lower bound of the confidence interval\n p_lower_a1 = p_lower_range['min']\n try:\n p_lower_a2 = range_list[p_lower_range_i+1]['min']\n except IndexError:\n p_lower_a2 = p_lower_range['max']\n p_lower_c1 = p_lower_range['n_min'] / n\n try:\n p_lower_c2 = range_list[p_lower_range_i+1]['n_min'] / n\n except IndexError:\n p_lower_c2 = p_lower_range['n_max'] / n\n lower_bound = ((p_lower - p_lower_c1) / (p_lower_c2 - p_lower_c1)) * (p_lower_a2 - p_lower_a1) + p_lower_a1\n\n # Same for the upper bound\n p_upper_a1 = p_upper_range['min']\n try:\n p_upper_a2 = range_list[p_upper_range_i+1]['min']\n except IndexError:\n p_upper_a2 = p_upper_range['max']\n p_upper_c1 = p_upper_range['n_min'] / n\n try:\n p_upper_c2 = range_list[p_upper_range_i+1]['n_min'] / n\n except IndexError:\n p_upper_c2 = p_upper_range['n_max'] / n\n upper_bound = ((p_upper - p_upper_c1) / (p_upper_c2 - p_upper_c1)) * (p_upper_a2 - p_upper_a1) + p_upper_a1\n \n # Calculate the standard error of the median\n standard_error_median = 0.5 * (upper_bound - lower_bound)\n \n # Calculate the margin of error at the 90% confidence level\n margin_of_error = 1.645 * standard_error_median\n \n # Return the result\n return estimated_median, margin_of_error", "_____no_output_____" ], [ "income = [\n dict(min=-2500, max=9999, n=186),\n dict(min=10000, max=14999, n=78),\n dict(min=15000, max=19999, n=98),\n dict(min=20000, max=24999, n=287),\n dict(min=25000, max=29999, n=142),\n dict(min=30000, max=34999, n=90),\n dict(min=35000, max=39999, n=107),\n dict(min=40000, max=44999, n=104),\n dict(min=45000, max=49999, n=178),\n dict(min=50000, max=59999, n=106),\n dict(min=60000, max=74999, n=177),\n dict(min=75000, max=99999, n=262),\n dict(min=100000, max=124999, n=77),\n dict(min=125000, max=149999, n=100),\n dict(min=150000, max=199999, n=58),\n dict(min=200000, max=250001, n=18)\n]", "_____no_output_____" ], [ "approximate_median(income)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
d010ae027d69e80c99561eaf401df1f282ff32ca
4,220
ipynb
Jupyter Notebook
pyTorch_PS/PT08-InstallAndSetupTensorflowHiddenLayer.ipynb
rsunderscore/learning
423b4f3a0eb131549dbdb85a5972426482ddfda6
[ "MIT" ]
null
null
null
pyTorch_PS/PT08-InstallAndSetupTensorflowHiddenLayer.ipynb
rsunderscore/learning
423b4f3a0eb131549dbdb85a5972426482ddfda6
[ "MIT" ]
null
null
null
pyTorch_PS/PT08-InstallAndSetupTensorflowHiddenLayer.ipynb
rsunderscore/learning
423b4f3a0eb131549dbdb85a5972426482ddfda6
[ "MIT" ]
null
null
null
27.94702
139
0.49455
[ [ [ "## Install and setup", "_____no_output_____" ], [ "# use conda instead\nmax python version 3.7\n\n!pip install tensorflow", "_____no_output_____" ], [ "# use conda install graphviz instead\n* also rqeuires conda install python-graphviz\n\n!pip install graphviz", "_____no_output_____" ], [ "# must use pip here - no conda package\n!pip install hiddenlayer", "_____no_output_____" ] ], [ [ "import graphviz", "_____no_output_____" ], [ "d= graphviz.Digraph()\nd.edge('hello','world')\nd", "_____no_output_____" ], [ "!conda env list", "# conda environments:\n#\nbase C:\\ProgramData\\Anaconda3\nmyenv * C:\\Users\\Rob.DESKTOP-HBG5EOT\\.conda\\envs\\myenv\ntf37 C:\\Users\\Rob.DESKTOP-HBG5EOT\\.conda\\envs\\tf37\n\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ] ]
d010b510d1d3711ea81ea408b3a20bc98cb42c97
71,319
ipynb
Jupyter Notebook
notebooks/community/gapic/automl/showcase_automl_tabular_binary_classification_batch.ipynb
nayaknishant/vertex-ai-samples
3ce120b953f1cdc2ec2c5a3f4509cfeab106b7d0
[ "Apache-2.0" ]
213
2021-06-10T20:05:20.000Z
2022-03-31T16:09:29.000Z
notebooks/community/gapic/automl/showcase_automl_tabular_binary_classification_batch.ipynb
nayaknishant/vertex-ai-samples
3ce120b953f1cdc2ec2c5a3f4509cfeab106b7d0
[ "Apache-2.0" ]
343
2021-07-25T22:55:25.000Z
2022-03-31T23:58:47.000Z
notebooks/community/gapic/automl/showcase_automl_tabular_binary_classification_batch.ipynb
nayaknishant/vertex-ai-samples
3ce120b953f1cdc2ec2c5a3f4509cfeab106b7d0
[ "Apache-2.0" ]
143
2021-07-21T17:27:47.000Z
2022-03-29T01:20:43.000Z
40.044357
418
0.552237
[ [ [ "# Copyright 2020 Google LLC\n#\n# 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_____" ] ], [ [ "# Vertex client library: AutoML tabular binary classification model for batch prediction\n\n<table align=\"left\">\n <td>\n <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_tabular_binary_classification_batch.ipynb\">\n <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n </a>\n </td>\n <td>\n <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_tabular_binary_classification_batch.ipynb\">\n <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n View on GitHub\n </a>\n </td>\n</table>\n<br/><br/><br/>", "_____no_output_____" ], [ "## Overview\n\n\nThis tutorial demonstrates how to use the Vertex client library for Python to create tabular binary classification models and do batch prediction using Google Cloud's [AutoML](https://cloud.google.com/vertex-ai/docs/start/automl-users).", "_____no_output_____" ], [ "### Dataset\n\nThe dataset used for this tutorial is the [Bank Marketing](gs://cloud-ml-tables-data/bank-marketing.csv). This dataset does not require any feature engineering. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket.", "_____no_output_____" ], [ "### Objective\n\nIn this tutorial, you create an AutoML tabular binary classification model from a Python script, and then do a batch prediction using the Vertex client library. You can alternatively create and deploy models using the `gcloud` command-line tool or online using the Google Cloud Console.\n\nThe steps performed include:\n\n- Create a Vertex `Dataset` resource.\n- Train the model.\n- View the model evaluation.\n- Make a batch prediction.\n\nThere is one key difference between using batch prediction and using online prediction:\n\n* Prediction Service: Does an on-demand prediction for the entire set of instances (i.e., one or more data items) and returns the results in real-time.\n\n* Batch Prediction Service: Does a queued (batch) prediction for the entire set of instances in the background and stores the results in a Cloud Storage bucket when ready.", "_____no_output_____" ], [ "### Costs\n\nThis tutorial uses billable components of Google Cloud (GCP):\n\n* Vertex AI\n* Cloud Storage\n\nLearn about [Vertex AI\npricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\npricing](https://cloud.google.com/storage/pricing), and use the [Pricing\nCalculator](https://cloud.google.com/products/calculator/)\nto generate a cost estimate based on your projected usage.", "_____no_output_____" ], [ "## Installation\n\nInstall the latest version of Vertex client library.", "_____no_output_____" ] ], [ [ "import os\nimport sys\n\n# Google Cloud Notebook\nif os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n USER_FLAG = \"--user\"\nelse:\n USER_FLAG = \"\"\n\n! pip3 install -U google-cloud-aiplatform $USER_FLAG", "_____no_output_____" ] ], [ [ "Install the latest GA version of *google-cloud-storage* library as well.", "_____no_output_____" ] ], [ [ "! pip3 install -U google-cloud-storage $USER_FLAG", "_____no_output_____" ] ], [ [ "### Restart the kernel\n\nOnce you've installed the Vertex client library and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages.", "_____no_output_____" ] ], [ [ "if not os.getenv(\"IS_TESTING\"):\n # Automatically restart kernel after installs\n import IPython\n\n app = IPython.Application.instance()\n app.kernel.do_shutdown(True)", "_____no_output_____" ] ], [ [ "## Before you begin\n\n### GPU runtime\n\n*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\n\n### Set up your Google Cloud project\n\n**The following steps are required, regardless of your notebook environment.**\n\n1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n\n2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n\n3. [Enable the Vertex APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\n\n4. [The Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebook.\n\n5. Enter your project ID in the cell below. Then run the cell to make sure the\nCloud SDK uses the right project for all the commands in this notebook.\n\n**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.", "_____no_output_____" ] ], [ [ "PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}", "_____no_output_____" ], [ "if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n # Get your GCP project id from gcloud\n shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n PROJECT_ID = shell_output[0]\n print(\"Project ID:\", PROJECT_ID)", "_____no_output_____" ], [ "! gcloud config set project $PROJECT_ID", "_____no_output_____" ] ], [ [ "#### Region\n\nYou can also change the `REGION` variable, which is used for operations\nthroughout the rest of this notebook. Below are regions supported for Vertex. We recommend that you choose the region closest to you.\n\n- Americas: `us-central1`\n- Europe: `europe-west4`\n- Asia Pacific: `asia-east1`\n\nYou may not use a multi-regional bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see the [Vertex locations documentation](https://cloud.google.com/vertex-ai/docs/general/locations)", "_____no_output_____" ] ], [ [ "REGION = \"us-central1\" # @param {type: \"string\"}", "_____no_output_____" ] ], [ [ "#### Timestamp\n\nIf you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial.", "_____no_output_____" ] ], [ [ "from datetime import datetime\n\nTIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")", "_____no_output_____" ] ], [ [ "### Authenticate your Google Cloud account\n\n**If you are using Google Cloud Notebook**, your environment is already authenticated. Skip this step.\n\n**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n\n**Otherwise**, follow these steps:\n\nIn the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n\n**Click Create service account**.\n\nIn the **Service account name** field, enter a name, and click **Create**.\n\nIn the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex\" into the filter box, and select **Vertex Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n\nClick Create. A JSON file that contains your key downloads to your local environment.\n\nEnter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.", "_____no_output_____" ] ], [ [ "# If you are running this notebook in Colab, run this cell and follow the\n# instructions to authenticate your GCP account. This provides access to your\n# Cloud Storage bucket and lets you submit training jobs and prediction\n# requests.\n\n# If on Google Cloud Notebook, then don't execute this code\nif not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n if \"google.colab\" in sys.modules:\n from google.colab import auth as google_auth\n\n google_auth.authenticate_user()\n\n # If you are running this notebook locally, replace the string below with the\n # path to your service account key and run this cell to authenticate your GCP\n # account.\n elif not os.getenv(\"IS_TESTING\"):\n %env GOOGLE_APPLICATION_CREDENTIALS ''", "_____no_output_____" ] ], [ [ "### Create a Cloud Storage bucket\n\n**The following steps are required, regardless of your notebook environment.**\n\nThis tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.\n\nSet the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization.", "_____no_output_____" ] ], [ [ "BUCKET_NAME = \"gs://[your-bucket-name]\" # @param {type:\"string\"}", "_____no_output_____" ], [ "if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"gs://[your-bucket-name]\":\n BUCKET_NAME = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP", "_____no_output_____" ] ], [ [ "**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.", "_____no_output_____" ] ], [ [ "! gsutil mb -l $REGION $BUCKET_NAME", "_____no_output_____" ] ], [ [ "Finally, validate access to your Cloud Storage bucket by examining its contents:", "_____no_output_____" ] ], [ [ "! gsutil ls -al $BUCKET_NAME", "_____no_output_____" ] ], [ [ "### Set up variables\n\nNext, set up some variables used throughout the tutorial.\n### Import libraries and define constants", "_____no_output_____" ], [ "#### Import Vertex client library\n\nImport the Vertex client library into our Python environment.", "_____no_output_____" ] ], [ [ "import time\n\nfrom google.cloud.aiplatform import gapic as aip\nfrom google.protobuf import json_format\nfrom google.protobuf.struct_pb2 import Struct, Value", "_____no_output_____" ] ], [ [ "#### Vertex constants\n\nSetup up the following constants for Vertex:\n\n- `API_ENDPOINT`: The Vertex API service endpoint for dataset, model, job, pipeline and endpoint services.\n- `PARENT`: The Vertex location root path for dataset, model, job, pipeline and endpoint resources.", "_____no_output_____" ] ], [ [ "# API service endpoint\nAPI_ENDPOINT = \"{}-aiplatform.googleapis.com\".format(REGION)\n\n# Vertex location root path for your dataset, model and endpoint resources\nPARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION", "_____no_output_____" ] ], [ [ "#### AutoML constants\n\nSet constants unique to AutoML datasets and training:\n\n- Dataset Schemas: Tells the `Dataset` resource service which type of dataset it is.\n- Data Labeling (Annotations) Schemas: Tells the `Dataset` resource service how the data is labeled (annotated).\n- Dataset Training Schemas: Tells the `Pipeline` resource service the task (e.g., classification) to train the model for.", "_____no_output_____" ] ], [ [ "# Tabular Dataset type\nDATA_SCHEMA = \"gs://google-cloud-aiplatform/schema/dataset/metadata/tables_1.0.0.yaml\"\n# Tabular Labeling type\nLABEL_SCHEMA = (\n \"gs://google-cloud-aiplatform/schema/dataset/ioformat/table_io_format_1.0.0.yaml\"\n)\n# Tabular Training task\nTRAINING_SCHEMA = \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_tables_1.0.0.yaml\"", "_____no_output_____" ] ], [ [ "#### Hardware Accelerators\n\nSet the hardware accelerators (e.g., GPU), if any, for prediction.\n\nSet the variable `DEPLOY_GPU/DEPLOY_NGPU` to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 Nvidia Telsa K80 GPUs allocated to each VM, you would specify:\n\n (aip.AcceleratorType.NVIDIA_TESLA_K80, 4)\n\nFor GPU, available accelerators include:\n - aip.AcceleratorType.NVIDIA_TESLA_K80\n - aip.AcceleratorType.NVIDIA_TESLA_P100\n - aip.AcceleratorType.NVIDIA_TESLA_P4\n - aip.AcceleratorType.NVIDIA_TESLA_T4\n - aip.AcceleratorType.NVIDIA_TESLA_V100\n\nOtherwise specify `(None, None)` to use a container image to run on a CPU.", "_____no_output_____" ] ], [ [ "if os.getenv(\"IS_TESTING_DEPOLY_GPU\"):\n DEPLOY_GPU, DEPLOY_NGPU = (\n aip.AcceleratorType.NVIDIA_TESLA_K80,\n int(os.getenv(\"IS_TESTING_DEPOLY_GPU\")),\n )\nelse:\n DEPLOY_GPU, DEPLOY_NGPU = (aip.AcceleratorType.NVIDIA_TESLA_K80, 1)", "_____no_output_____" ] ], [ [ "#### Container (Docker) image\n\nFor AutoML batch prediction, the container image for the serving binary is pre-determined by the Vertex prediction service. More specifically, the service will pick the appropriate container for the model depending on the hardware accelerator you selected.", "_____no_output_____" ], [ "#### Machine Type\n\nNext, set the machine type to use for prediction.\n\n- Set the variable `DEPLOY_COMPUTE` to configure the compute resources for the VM you will use for prediction.\n - `machine type`\n - `n1-standard`: 3.75GB of memory per vCPU.\n - `n1-highmem`: 6.5GB of memory per vCPU\n - `n1-highcpu`: 0.9 GB of memory per vCPU\n - `vCPUs`: number of \\[2, 4, 8, 16, 32, 64, 96 \\]\n\n*Note: You may also use n2 and e2 machine types for training and deployment, but they do not support GPUs*", "_____no_output_____" ] ], [ [ "if os.getenv(\"IS_TESTING_DEPLOY_MACHINE\"):\n MACHINE_TYPE = os.getenv(\"IS_TESTING_DEPLOY_MACHINE\")\nelse:\n MACHINE_TYPE = \"n1-standard\"\n\nVCPU = \"4\"\nDEPLOY_COMPUTE = MACHINE_TYPE + \"-\" + VCPU\nprint(\"Deploy machine type\", DEPLOY_COMPUTE)", "_____no_output_____" ] ], [ [ "# Tutorial\n\nNow you are ready to start creating your own AutoML tabular binary classification model.", "_____no_output_____" ], [ "## Set up clients\n\nThe Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex server.\n\nYou will use different clients in this tutorial for different steps in the workflow. So set them all up upfront.\n\n- Dataset Service for `Dataset` resources.\n- Model Service for `Model` resources.\n- Pipeline Service for training.\n- Job Service for batch prediction and custom training.", "_____no_output_____" ] ], [ [ "# client options same for all services\nclient_options = {\"api_endpoint\": API_ENDPOINT}\n\n\ndef create_dataset_client():\n client = aip.DatasetServiceClient(client_options=client_options)\n return client\n\n\ndef create_model_client():\n client = aip.ModelServiceClient(client_options=client_options)\n return client\n\n\ndef create_pipeline_client():\n client = aip.PipelineServiceClient(client_options=client_options)\n return client\n\n\ndef create_job_client():\n client = aip.JobServiceClient(client_options=client_options)\n return client\n\n\nclients = {}\nclients[\"dataset\"] = create_dataset_client()\nclients[\"model\"] = create_model_client()\nclients[\"pipeline\"] = create_pipeline_client()\nclients[\"job\"] = create_job_client()\n\nfor client in clients.items():\n print(client)", "_____no_output_____" ] ], [ [ "## Dataset\n\nNow that your clients are ready, your first step is to create a `Dataset` resource instance. This step differs from Vision, Video and Language. For those products, after the `Dataset` resource is created, one then separately imports the data, using the `import_data` method.\n\nFor tabular, importing of the data is deferred until the training pipeline starts training the model. What do we do different? Well, first you won't be calling the `import_data` method. Instead, when you create the dataset instance you specify the Cloud Storage location of the CSV file or BigQuery location of the data table, which contains your tabular data as part of the `Dataset` resource's metadata.\n\n#### Cloud Storage\n\n`metadata = {\"input_config\": {\"gcs_source\": {\"uri\": [gcs_uri]}}}`\n\nThe format for a Cloud Storage path is:\n\n gs://[bucket_name]/[folder(s)/[file]\n\n#### BigQuery\n\n`metadata = {\"input_config\": {\"bigquery_source\": {\"uri\": [gcs_uri]}}}`\n\nThe format for a BigQuery path is:\n\n bq://[collection].[dataset].[table]\n\nNote that the `uri` field is a list, whereby you can input multiple CSV files or BigQuery tables when your data is split across files.", "_____no_output_____" ], [ "### Data preparation\n\nThe Vertex `Dataset` resource for tabular has a couple of requirements for your tabular data.\n\n- Must be in a CSV file or a BigQuery query.", "_____no_output_____" ], [ "#### CSV\n\nFor tabular binary classification, the CSV file has a few requirements:\n\n- The first row must be the heading -- note how this is different from Vision, Video and Language where the requirement is no heading.\n- All but one column are features.\n- One column is the label, which you will specify when you subsequently create the training pipeline.", "_____no_output_____" ], [ "#### Location of Cloud Storage training data.\n\nNow set the variable `IMPORT_FILE` to the location of the CSV index file in Cloud Storage.", "_____no_output_____" ] ], [ [ "IMPORT_FILE = \"gs://cloud-ml-tables-data/bank-marketing.csv\"", "_____no_output_____" ] ], [ [ "#### Quick peek at your data\n\nYou will use a version of the Bank Marketing dataset that is stored in a public Cloud Storage bucket, using a CSV index file.\n\nStart by doing a quick peek at the data. You count the number of examples by counting the number of rows in the CSV index file (`wc -l`) and then peek at the first few rows.\n\nYou also need for training to know the heading name of the label column, which is save as `label_column`. For this dataset, it is the last column in the CSV file.", "_____no_output_____" ] ], [ [ "count = ! gsutil cat $IMPORT_FILE | wc -l\nprint(\"Number of Examples\", int(count[0]))\n\nprint(\"First 10 rows\")\n! gsutil cat $IMPORT_FILE | head\n\nheading = ! gsutil cat $IMPORT_FILE | head -n1\nlabel_column = str(heading).split(\",\")[-1].split(\"'\")[0]\nprint(\"Label Column Name\", label_column)\nif label_column is None:\n raise Exception(\"label column missing\")", "_____no_output_____" ] ], [ [ "## Dataset\n\nNow that your clients are ready, your first step in training a model is to create a managed dataset instance, and then upload your labeled data to it.\n\n### Create `Dataset` resource instance\n\nUse the helper function `create_dataset` to create the instance of a `Dataset` resource. This function does the following:\n\n1. Uses the dataset client service.\n2. Creates an Vertex `Dataset` resource (`aip.Dataset`), with the following parameters:\n - `display_name`: The human-readable name you choose to give it.\n - `metadata_schema_uri`: The schema for the dataset type.\n - `metadata`: The Cloud Storage or BigQuery location of the tabular data.\n3. Calls the client dataset service method `create_dataset`, with the following parameters:\n - `parent`: The Vertex location root path for your `Database`, `Model` and `Endpoint` resources.\n - `dataset`: The Vertex dataset object instance you created.\n4. The method returns an `operation` object.\n\nAn `operation` object is how Vertex handles asynchronous calls for long running operations. While this step usually goes fast, when you first use it in your project, there is a longer delay due to provisioning.\n\nYou can use the `operation` object to get status on the operation (e.g., create `Dataset` resource) or to cancel the operation, by invoking an operation method:\n\n| Method | Description |\n| ----------- | ----------- |\n| result() | Waits for the operation to complete and returns a result object in JSON format. |\n| running() | Returns True/False on whether the operation is still running. |\n| done() | Returns True/False on whether the operation is completed. |\n| canceled() | Returns True/False on whether the operation was canceled. |\n| cancel() | Cancels the operation (this may take up to 30 seconds). |", "_____no_output_____" ] ], [ [ "TIMEOUT = 90\n\n\ndef create_dataset(name, schema, src_uri=None, labels=None, timeout=TIMEOUT):\n start_time = time.time()\n try:\n if src_uri.startswith(\"gs://\"):\n metadata = {\"input_config\": {\"gcs_source\": {\"uri\": [src_uri]}}}\n elif src_uri.startswith(\"bq://\"):\n metadata = {\"input_config\": {\"bigquery_source\": {\"uri\": [src_uri]}}}\n dataset = aip.Dataset(\n display_name=name,\n metadata_schema_uri=schema,\n labels=labels,\n metadata=json_format.ParseDict(metadata, Value()),\n )\n\n operation = clients[\"dataset\"].create_dataset(parent=PARENT, dataset=dataset)\n print(\"Long running operation:\", operation.operation.name)\n result = operation.result(timeout=TIMEOUT)\n print(\"time:\", time.time() - start_time)\n print(\"response\")\n print(\" name:\", result.name)\n print(\" display_name:\", result.display_name)\n print(\" metadata_schema_uri:\", result.metadata_schema_uri)\n print(\" metadata:\", dict(result.metadata))\n print(\" create_time:\", result.create_time)\n print(\" update_time:\", result.update_time)\n print(\" etag:\", result.etag)\n print(\" labels:\", dict(result.labels))\n return result\n except Exception as e:\n print(\"exception:\", e)\n return None\n\n\nresult = create_dataset(\"bank-\" + TIMESTAMP, DATA_SCHEMA, src_uri=IMPORT_FILE)", "_____no_output_____" ] ], [ [ "Now save the unique dataset identifier for the `Dataset` resource instance you created.", "_____no_output_____" ] ], [ [ "# The full unique ID for the dataset\ndataset_id = result.name\n# The short numeric ID for the dataset\ndataset_short_id = dataset_id.split(\"/\")[-1]\n\nprint(dataset_id)", "_____no_output_____" ] ], [ [ "## Train the model\n\nNow train an AutoML tabular binary classification model using your Vertex `Dataset` resource. To train the model, do the following steps:\n\n1. Create an Vertex training pipeline for the `Dataset` resource.\n2. Execute the pipeline to start the training.", "_____no_output_____" ], [ "### Create a training pipeline\n\nYou may ask, what do we use a pipeline for? You typically use pipelines when the job (such as training) has multiple steps, generally in sequential order: do step A, do step B, etc. By putting the steps into a pipeline, we gain the benefits of:\n\n1. Being reusable for subsequent training jobs.\n2. Can be containerized and ran as a batch job.\n3. Can be distributed.\n4. All the steps are associated with the same pipeline job for tracking progress.\n\nUse this helper function `create_pipeline`, which takes the following parameters:\n\n- `pipeline_name`: A human readable name for the pipeline job.\n- `model_name`: A human readable name for the model.\n- `dataset`: The Vertex fully qualified dataset identifier.\n- `schema`: The dataset labeling (annotation) training schema.\n- `task`: A dictionary describing the requirements for the training job.\n\nThe helper function calls the `Pipeline` client service'smethod `create_pipeline`, which takes the following parameters:\n\n- `parent`: The Vertex location root path for your `Dataset`, `Model` and `Endpoint` resources.\n- `training_pipeline`: the full specification for the pipeline training job.\n\nLet's look now deeper into the *minimal* requirements for constructing a `training_pipeline` specification:\n\n- `display_name`: A human readable name for the pipeline job.\n- `training_task_definition`: The dataset labeling (annotation) training schema.\n- `training_task_inputs`: A dictionary describing the requirements for the training job.\n- `model_to_upload`: A human readable name for the model.\n- `input_data_config`: The dataset specification.\n - `dataset_id`: The Vertex dataset identifier only (non-fully qualified) -- this is the last part of the fully-qualified identifier.\n - `fraction_split`: If specified, the percentages of the dataset to use for training, test and validation. Otherwise, the percentages are automatically selected by AutoML.", "_____no_output_____" ] ], [ [ "def create_pipeline(pipeline_name, model_name, dataset, schema, task):\n\n dataset_id = dataset.split(\"/\")[-1]\n\n input_config = {\n \"dataset_id\": dataset_id,\n \"fraction_split\": {\n \"training_fraction\": 0.8,\n \"validation_fraction\": 0.1,\n \"test_fraction\": 0.1,\n },\n }\n\n training_pipeline = {\n \"display_name\": pipeline_name,\n \"training_task_definition\": schema,\n \"training_task_inputs\": task,\n \"input_data_config\": input_config,\n \"model_to_upload\": {\"display_name\": model_name},\n }\n\n try:\n pipeline = clients[\"pipeline\"].create_training_pipeline(\n parent=PARENT, training_pipeline=training_pipeline\n )\n print(pipeline)\n except Exception as e:\n print(\"exception:\", e)\n return None\n return pipeline", "_____no_output_____" ] ], [ [ "### Construct the task requirements\n\nNext, construct the task requirements. Unlike other parameters which take a Python (JSON-like) dictionary, the `task` field takes a Google protobuf Struct, which is very similar to a Python dictionary. Use the `json_format.ParseDict` method for the conversion.\n\nThe minimal fields you need to specify are:\n\n- `prediction_type`: Whether we are doing \"classification\" or \"regression\".\n- `target_column`: The CSV heading column name for the column we want to predict (i.e., the label).\n- `train_budget_milli_node_hours`: The maximum time to budget (billed) for training the model, where 1000 = 1 hour.\n- `disable_early_stopping`: Whether True/False to let AutoML use its judgement to stop training early or train for the entire budget.\n- `transformations`: Specifies the feature engineering for each feature column.\n\nFor `transformations`, the list must have an entry for each column. The outer key field indicates the type of feature engineering for the corresponding column. In this tutorial, you set it to `\"auto\"` to tell AutoML to automatically determine it.\n\nFinally, create the pipeline by calling the helper function `create_pipeline`, which returns an instance of a training pipeline object.", "_____no_output_____" ] ], [ [ "TRANSFORMATIONS = [\n {\"auto\": {\"column_name\": \"Age\"}},\n {\"auto\": {\"column_name\": \"Job\"}},\n {\"auto\": {\"column_name\": \"MaritalStatus\"}},\n {\"auto\": {\"column_name\": \"Education\"}},\n {\"auto\": {\"column_name\": \"Default\"}},\n {\"auto\": {\"column_name\": \"Balance\"}},\n {\"auto\": {\"column_name\": \"Housing\"}},\n {\"auto\": {\"column_name\": \"Loan\"}},\n {\"auto\": {\"column_name\": \"Contact\"}},\n {\"auto\": {\"column_name\": \"Day\"}},\n {\"auto\": {\"column_name\": \"Month\"}},\n {\"auto\": {\"column_name\": \"Duration\"}},\n {\"auto\": {\"column_name\": \"Campaign\"}},\n {\"auto\": {\"column_name\": \"PDays\"}},\n {\"auto\": {\"column_name\": \"POutcome\"}},\n]", "_____no_output_____" ], [ "PIPE_NAME = \"bank_pipe-\" + TIMESTAMP\nMODEL_NAME = \"bank_model-\" + TIMESTAMP\n\ntask = Value(\n struct_value=Struct(\n fields={\n \"target_column\": Value(string_value=label_column),\n \"prediction_type\": Value(string_value=\"classification\"),\n \"train_budget_milli_node_hours\": Value(number_value=1000),\n \"disable_early_stopping\": Value(bool_value=False),\n \"transformations\": json_format.ParseDict(TRANSFORMATIONS, Value()),\n }\n )\n)\n\nresponse = create_pipeline(PIPE_NAME, MODEL_NAME, dataset_id, TRAINING_SCHEMA, task)", "_____no_output_____" ] ], [ [ "Now save the unique identifier of the training pipeline you created.", "_____no_output_____" ] ], [ [ "# The full unique ID for the pipeline\npipeline_id = response.name\n# The short numeric ID for the pipeline\npipeline_short_id = pipeline_id.split(\"/\")[-1]\n\nprint(pipeline_id)", "_____no_output_____" ] ], [ [ "### Get information on a training pipeline\n\nNow get pipeline information for just this training pipeline instance. The helper function gets the job information for just this job by calling the the job client service's `get_training_pipeline` method, with the following parameter:\n\n- `name`: The Vertex fully qualified pipeline identifier.\n\nWhen the model is done training, the pipeline state will be `PIPELINE_STATE_SUCCEEDED`.", "_____no_output_____" ] ], [ [ "def get_training_pipeline(name, silent=False):\n response = clients[\"pipeline\"].get_training_pipeline(name=name)\n if silent:\n return response\n\n print(\"pipeline\")\n print(\" name:\", response.name)\n print(\" display_name:\", response.display_name)\n print(\" state:\", response.state)\n print(\" training_task_definition:\", response.training_task_definition)\n print(\" training_task_inputs:\", dict(response.training_task_inputs))\n print(\" create_time:\", response.create_time)\n print(\" start_time:\", response.start_time)\n print(\" end_time:\", response.end_time)\n print(\" update_time:\", response.update_time)\n print(\" labels:\", dict(response.labels))\n return response\n\n\nresponse = get_training_pipeline(pipeline_id)", "_____no_output_____" ] ], [ [ "# Deployment\n\nTraining the above model may take upwards of 30 minutes time.\n\nOnce your model is done training, you can calculate the actual time it took to train the model by subtracting `end_time` from `start_time`. For your model, you will need to know the fully qualified Vertex Model resource identifier, which the pipeline service assigned to it. You can get this from the returned pipeline instance as the field `model_to_deploy.name`.", "_____no_output_____" ] ], [ [ "while True:\n response = get_training_pipeline(pipeline_id, True)\n if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:\n print(\"Training job has not completed:\", response.state)\n model_to_deploy_id = None\n if response.state == aip.PipelineState.PIPELINE_STATE_FAILED:\n raise Exception(\"Training Job Failed\")\n else:\n model_to_deploy = response.model_to_upload\n model_to_deploy_id = model_to_deploy.name\n print(\"Training Time:\", response.end_time - response.start_time)\n break\n time.sleep(60)\n\nprint(\"model to deploy:\", model_to_deploy_id)", "_____no_output_____" ] ], [ [ "## Model information\n\nNow that your model is trained, you can get some information on your model.", "_____no_output_____" ], [ "## Evaluate the Model resource\n\nNow find out how good the model service believes your model is. As part of training, some portion of the dataset was set aside as the test (holdout) data, which is used by the pipeline service to evaluate the model.", "_____no_output_____" ], [ "### List evaluations for all slices\n\nUse this helper function `list_model_evaluations`, which takes the following parameter:\n\n- `name`: The Vertex fully qualified model identifier for the `Model` resource.\n\nThis helper function uses the model client service's `list_model_evaluations` method, which takes the same parameter. The response object from the call is a list, where each element is an evaluation metric.\n\nFor each evaluation (you probably only have one) we then print all the key names for each metric in the evaluation, and for a small set (`logLoss` and `auPrc`) you will print the result.", "_____no_output_____" ] ], [ [ "def list_model_evaluations(name):\n response = clients[\"model\"].list_model_evaluations(parent=name)\n for evaluation in response:\n print(\"model_evaluation\")\n print(\" name:\", evaluation.name)\n print(\" metrics_schema_uri:\", evaluation.metrics_schema_uri)\n metrics = json_format.MessageToDict(evaluation._pb.metrics)\n for metric in metrics.keys():\n print(metric)\n print(\"logloss\", metrics[\"logLoss\"])\n print(\"auPrc\", metrics[\"auPrc\"])\n\n return evaluation.name\n\n\nlast_evaluation = list_model_evaluations(model_to_deploy_id)", "_____no_output_____" ] ], [ [ "## Model deployment for batch prediction\n\nNow deploy the trained Vertex `Model` resource you created for batch prediction. This differs from deploying a `Model` resource for on-demand prediction.\n\nFor online prediction, you:\n\n1. Create an `Endpoint` resource for deploying the `Model` resource to.\n\n2. Deploy the `Model` resource to the `Endpoint` resource.\n\n3. Make online prediction requests to the `Endpoint` resource.\n\nFor batch-prediction, you:\n\n1. Create a batch prediction job.\n\n2. The job service will provision resources for the batch prediction request.\n\n3. The results of the batch prediction request are returned to the caller.\n\n4. The job service will unprovision the resoures for the batch prediction request.", "_____no_output_____" ], [ "## Make a batch prediction request\n\nNow do a batch prediction to your deployed model.", "_____no_output_____" ], [ "### Make test items\n\nYou will use synthetic data as a test data items. Don't be concerned that we are using synthetic data -- we just want to demonstrate how to make a prediction.", "_____no_output_____" ] ], [ [ "HEADING = \"Age,Job,MaritalStatus,Education,Default,Balance,Housing,Loan,Contact,Day,Month,Duration,Campaign,PDays,Previous,POutcome,Deposit\"\nINSTANCE_1 = (\n \"58,managment,married,teritary,no,2143,yes,no,unknown,5,may,261,1,-1,0, unknown\"\n)\nINSTANCE_2 = (\n \"44,technician,single,secondary,no,39,yes,no,unknown,5,may,151,1,-1,0,unknown\"\n)", "_____no_output_____" ] ], [ [ "### Make the batch input file\n\nNow make a batch input file, which you will store in your local Cloud Storage bucket. Unlike image, video and text, the batch input file for tabular is only supported for CSV. For CSV file, you make:\n\n- The first line is the heading with the feature (fields) heading names.\n- Each remaining line is a separate prediction request with the corresponding feature values.\n\nFor example:\n\n \"feature_1\", \"feature_2\". ...\n value_1, value_2, ...", "_____no_output_____" ] ], [ [ "import tensorflow as tf\n\ngcs_input_uri = BUCKET_NAME + \"/test.csv\"\nwith tf.io.gfile.GFile(gcs_input_uri, \"w\") as f:\n f.write(HEADING + \"\\n\")\n f.write(str(INSTANCE_1) + \"\\n\")\n f.write(str(INSTANCE_2) + \"\\n\")\n\nprint(gcs_input_uri)\n! gsutil cat $gcs_input_uri", "_____no_output_____" ] ], [ [ "### Compute instance scaling\n\nYou have several choices on scaling the compute instances for handling your batch prediction requests:\n\n- Single Instance: The batch prediction requests are processed on a single compute instance.\n - Set the minimum (`MIN_NODES`) and maximum (`MAX_NODES`) number of compute instances to one.\n\n- Manual Scaling: The batch prediction requests are split across a fixed number of compute instances that you manually specified.\n - Set the minimum (`MIN_NODES`) and maximum (`MAX_NODES`) number of compute instances to the same number of nodes. When a model is first deployed to the instance, the fixed number of compute instances are provisioned and batch prediction requests are evenly distributed across them.\n\n- Auto Scaling: The batch prediction requests are split across a scaleable number of compute instances.\n - Set the minimum (`MIN_NODES`) number of compute instances to provision when a model is first deployed and to de-provision, and set the maximum (`MAX_NODES) number of compute instances to provision, depending on load conditions.\n\nThe minimum number of compute instances corresponds to the field `min_replica_count` and the maximum number of compute instances corresponds to the field `max_replica_count`, in your subsequent deployment request.", "_____no_output_____" ] ], [ [ "MIN_NODES = 1\nMAX_NODES = 1", "_____no_output_____" ] ], [ [ "### Make batch prediction request\n\nNow that your batch of two test items is ready, let's do the batch request. Use this helper function `create_batch_prediction_job`, with the following parameters:\n\n- `display_name`: The human readable name for the prediction job.\n- `model_name`: The Vertex fully qualified identifier for the `Model` resource.\n- `gcs_source_uri`: The Cloud Storage path to the input file -- which you created above.\n- `gcs_destination_output_uri_prefix`: The Cloud Storage path that the service will write the predictions to.\n- `parameters`: Additional filtering parameters for serving prediction results.\n\nThe helper function calls the job client service's `create_batch_prediction_job` metho, with the following parameters:\n\n- `parent`: The Vertex location root path for Dataset, Model and Pipeline resources.\n- `batch_prediction_job`: The specification for the batch prediction job.\n\nLet's now dive into the specification for the `batch_prediction_job`:\n\n- `display_name`: The human readable name for the prediction batch job.\n- `model`: The Vertex fully qualified identifier for the `Model` resource.\n- `dedicated_resources`: The compute resources to provision for the batch prediction job.\n - `machine_spec`: The compute instance to provision. Use the variable you set earlier `DEPLOY_GPU != None` to use a GPU; otherwise only a CPU is allocated.\n - `starting_replica_count`: The number of compute instances to initially provision, which you set earlier as the variable `MIN_NODES`.\n - `max_replica_count`: The maximum number of compute instances to scale to, which you set earlier as the variable `MAX_NODES`.\n- `model_parameters`: Additional filtering parameters for serving prediction results. *Note*, image segmentation models do not support additional parameters.\n- `input_config`: The input source and format type for the instances to predict.\n - `instances_format`: The format of the batch prediction request file: `csv` only supported.\n - `gcs_source`: A list of one or more Cloud Storage paths to your batch prediction requests.\n- `output_config`: The output destination and format for the predictions.\n - `prediction_format`: The format of the batch prediction response file: `csv` only supported.\n - `gcs_destination`: The output destination for the predictions.\n\nThis call is an asychronous operation. You will print from the response object a few select fields, including:\n\n- `name`: The Vertex fully qualified identifier assigned to the batch prediction job.\n- `display_name`: The human readable name for the prediction batch job.\n- `model`: The Vertex fully qualified identifier for the Model resource.\n- `generate_explanations`: Whether True/False explanations were provided with the predictions (explainability).\n- `state`: The state of the prediction job (pending, running, etc).\n\nSince this call will take a few moments to execute, you will likely get `JobState.JOB_STATE_PENDING` for `state`.", "_____no_output_____" ] ], [ [ "BATCH_MODEL = \"bank_batch-\" + TIMESTAMP\n\n\ndef create_batch_prediction_job(\n display_name,\n model_name,\n gcs_source_uri,\n gcs_destination_output_uri_prefix,\n parameters=None,\n):\n\n if DEPLOY_GPU:\n machine_spec = {\n \"machine_type\": DEPLOY_COMPUTE,\n \"accelerator_type\": DEPLOY_GPU,\n \"accelerator_count\": DEPLOY_NGPU,\n }\n else:\n machine_spec = {\n \"machine_type\": DEPLOY_COMPUTE,\n \"accelerator_count\": 0,\n }\n\n batch_prediction_job = {\n \"display_name\": display_name,\n # Format: 'projects/{project}/locations/{location}/models/{model_id}'\n \"model\": model_name,\n \"model_parameters\": json_format.ParseDict(parameters, Value()),\n \"input_config\": {\n \"instances_format\": IN_FORMAT,\n \"gcs_source\": {\"uris\": [gcs_source_uri]},\n },\n \"output_config\": {\n \"predictions_format\": OUT_FORMAT,\n \"gcs_destination\": {\"output_uri_prefix\": gcs_destination_output_uri_prefix},\n },\n \"dedicated_resources\": {\n \"machine_spec\": machine_spec,\n \"starting_replica_count\": MIN_NODES,\n \"max_replica_count\": MAX_NODES,\n },\n }\n response = clients[\"job\"].create_batch_prediction_job(\n parent=PARENT, batch_prediction_job=batch_prediction_job\n )\n print(\"response\")\n print(\" name:\", response.name)\n print(\" display_name:\", response.display_name)\n print(\" model:\", response.model)\n try:\n print(\" generate_explanation:\", response.generate_explanation)\n except:\n pass\n print(\" state:\", response.state)\n print(\" create_time:\", response.create_time)\n print(\" start_time:\", response.start_time)\n print(\" end_time:\", response.end_time)\n print(\" update_time:\", response.update_time)\n print(\" labels:\", response.labels)\n return response\n\n\nIN_FORMAT = \"csv\"\nOUT_FORMAT = \"csv\" # [csv]\n\nresponse = create_batch_prediction_job(\n BATCH_MODEL, model_to_deploy_id, gcs_input_uri, BUCKET_NAME, None\n)", "_____no_output_____" ] ], [ [ "Now get the unique identifier for the batch prediction job you created.", "_____no_output_____" ] ], [ [ "# The full unique ID for the batch job\nbatch_job_id = response.name\n# The short numeric ID for the batch job\nbatch_job_short_id = batch_job_id.split(\"/\")[-1]\n\nprint(batch_job_id)", "_____no_output_____" ] ], [ [ "### Get information on a batch prediction job\n\nUse this helper function `get_batch_prediction_job`, with the following paramter:\n\n- `job_name`: The Vertex fully qualified identifier for the batch prediction job.\n\nThe helper function calls the job client service's `get_batch_prediction_job` method, with the following paramter:\n\n- `name`: The Vertex fully qualified identifier for the batch prediction job. In this tutorial, you will pass it the Vertex fully qualified identifier for your batch prediction job -- `batch_job_id`\n\nThe helper function will return the Cloud Storage path to where the predictions are stored -- `gcs_destination`.", "_____no_output_____" ] ], [ [ "def get_batch_prediction_job(job_name, silent=False):\n response = clients[\"job\"].get_batch_prediction_job(name=job_name)\n if silent:\n return response.output_config.gcs_destination.output_uri_prefix, response.state\n\n print(\"response\")\n print(\" name:\", response.name)\n print(\" display_name:\", response.display_name)\n print(\" model:\", response.model)\n try: # not all data types support explanations\n print(\" generate_explanation:\", response.generate_explanation)\n except:\n pass\n print(\" state:\", response.state)\n print(\" error:\", response.error)\n gcs_destination = response.output_config.gcs_destination\n print(\" gcs_destination\")\n print(\" output_uri_prefix:\", gcs_destination.output_uri_prefix)\n return gcs_destination.output_uri_prefix, response.state\n\n\npredictions, state = get_batch_prediction_job(batch_job_id)", "_____no_output_____" ] ], [ [ "### Get Predictions\n\nWhen the batch prediction is done processing, the job state will be `JOB_STATE_SUCCEEDED`.\n\nFinally you view the predictions stored at the Cloud Storage path you set as output. The predictions will be in a CSV format, which you indicated at the time you made the batch prediction job, under a subfolder starting with the name `prediction`, and under that folder will be a file called `predictions*.csv`.\n\nNow display (cat) the contents. You will see multiple rows, one for each prediction.\n\nFor each prediction:\n\n- The first four fields are the values (features) you did the prediction on.\n- The remaining fields are the confidence values, between 0 and 1, for each prediction.", "_____no_output_____" ] ], [ [ "def get_latest_predictions(gcs_out_dir):\n \"\"\" Get the latest prediction subfolder using the timestamp in the subfolder name\"\"\"\n folders = !gsutil ls $gcs_out_dir\n latest = \"\"\n for folder in folders:\n subfolder = folder.split(\"/\")[-2]\n if subfolder.startswith(\"prediction-\"):\n if subfolder > latest:\n latest = folder[:-1]\n return latest\n\n\nwhile True:\n predictions, state = get_batch_prediction_job(batch_job_id, True)\n if state != aip.JobState.JOB_STATE_SUCCEEDED:\n print(\"The job has not completed:\", state)\n if state == aip.JobState.JOB_STATE_FAILED:\n raise Exception(\"Batch Job Failed\")\n else:\n folder = get_latest_predictions(predictions)\n ! gsutil ls $folder/prediction*.csv\n\n ! gsutil cat $folder/prediction*.csv\n break\n time.sleep(60)", "_____no_output_____" ] ], [ [ "# Cleaning up\n\nTo clean up all GCP resources used in this project, you can [delete the GCP\nproject](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n\nOtherwise, you can delete the individual resources you created in this tutorial:\n\n- Dataset\n- Pipeline\n- Model\n- Endpoint\n- Batch Job\n- Custom Job\n- Hyperparameter Tuning Job\n- Cloud Storage Bucket", "_____no_output_____" ] ], [ [ "delete_dataset = True\ndelete_pipeline = True\ndelete_model = True\ndelete_endpoint = True\ndelete_batchjob = True\ndelete_customjob = True\ndelete_hptjob = True\ndelete_bucket = True\n\n# Delete the dataset using the Vertex fully qualified identifier for the dataset\ntry:\n if delete_dataset and \"dataset_id\" in globals():\n clients[\"dataset\"].delete_dataset(name=dataset_id)\nexcept Exception as e:\n print(e)\n\n# Delete the training pipeline using the Vertex fully qualified identifier for the pipeline\ntry:\n if delete_pipeline and \"pipeline_id\" in globals():\n clients[\"pipeline\"].delete_training_pipeline(name=pipeline_id)\nexcept Exception as e:\n print(e)\n\n# Delete the model using the Vertex fully qualified identifier for the model\ntry:\n if delete_model and \"model_to_deploy_id\" in globals():\n clients[\"model\"].delete_model(name=model_to_deploy_id)\nexcept Exception as e:\n print(e)\n\n# Delete the endpoint using the Vertex fully qualified identifier for the endpoint\ntry:\n if delete_endpoint and \"endpoint_id\" in globals():\n clients[\"endpoint\"].delete_endpoint(name=endpoint_id)\nexcept Exception as e:\n print(e)\n\n# Delete the batch job using the Vertex fully qualified identifier for the batch job\ntry:\n if delete_batchjob and \"batch_job_id\" in globals():\n clients[\"job\"].delete_batch_prediction_job(name=batch_job_id)\nexcept Exception as e:\n print(e)\n\n# Delete the custom job using the Vertex fully qualified identifier for the custom job\ntry:\n if delete_customjob and \"job_id\" in globals():\n clients[\"job\"].delete_custom_job(name=job_id)\nexcept Exception as e:\n print(e)\n\n# Delete the hyperparameter tuning job using the Vertex fully qualified identifier for the hyperparameter tuning job\ntry:\n if delete_hptjob and \"hpt_job_id\" in globals():\n clients[\"job\"].delete_hyperparameter_tuning_job(name=hpt_job_id)\nexcept Exception as e:\n print(e)\n\nif delete_bucket and \"BUCKET_NAME\" in globals():\n ! gsutil rm -r $BUCKET_NAME", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "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", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d010b6850d041922f384a75d39e8698b35702776
13,494
ipynb
Jupyter Notebook
Cumulative_Projects/Wk 5 Reggie_Linear_Regression_Solution.ipynb
jfreeman812/Project_ZF
d71472e09cd19f006d758b7344b959f74b667824
[ "BSD-2-Clause" ]
null
null
null
Cumulative_Projects/Wk 5 Reggie_Linear_Regression_Solution.ipynb
jfreeman812/Project_ZF
d71472e09cd19f006d758b7344b959f74b667824
[ "BSD-2-Clause" ]
null
null
null
Cumulative_Projects/Wk 5 Reggie_Linear_Regression_Solution.ipynb
jfreeman812/Project_ZF
d71472e09cd19f006d758b7344b959f74b667824
[ "BSD-2-Clause" ]
null
null
null
31.900709
465
0.5747
[ [ [ "# Project: Linear Regression\n\nReggie is a mad scientist who has been hired by the local fast food joint to build their newest ball pit in the play area. As such, he is working on researching the bounciness of different balls so as to optimize the pit. He is running an experiment to bounce different sizes of bouncy balls, and then fitting lines to the data points he records. He has heard of linear regression, but needs your help to implement a version of linear regression in Python.\n\n_Linear Regression_ is when you have a group of points on a graph, and you find a line that approximately resembles that group of points. A good Linear Regression algorithm minimizes the _error_, or the distance from each point to the line. A line with the least error is the line that fits the data the best. We call this a line of _best fit_.\n\nWe will use loops, lists, and arithmetic to create a function that will find a line of best fit when given a set of data.\n", "_____no_output_____" ], [ "## Part 1: Calculating Error", "_____no_output_____" ], [ "\nThe line we will end up with will have a formula that looks like:\n```\ny = m*x + b\n```\n`m` is the slope of the line and `b` is the intercept, where the line crosses the y-axis.\n\nCreate a function called `get_y()` that takes in `m`, `b`, and `x` and returns what the `y` value would be for that `x` on that line!\n", "_____no_output_____" ] ], [ [ "def get_y(m, b, x):\n y = m*x + b\n return y\n\nget_y(1, 0, 7) == 7\nget_y(5, 10, 3) == 25\n", "_____no_output_____" ] ], [ [ "\nReggie wants to try a bunch of different `m` values and `b` values and see which line produces the least error. To calculate error between a point and a line, he wants a function called `calculate_error()`, which will take in `m`, `b`, and an [x, y] point called `point` and return the distance between the line and the point.\n\nTo find the distance:\n1. Get the x-value from the point and store it in a variable called `x_point`\n2. Get the x-value from the point and store it in a variable called `y_point`\n3. Use `get_y()` to get the y-value that `x_point` would be on the line\n4. Find the difference between the y from `get_y` and `y_point`\n5. Return the absolute value of the distance (you can use the built-in function `abs()` to do this)\n\nThe distance represents the error between the line `y = m*x + b` and the `point` given.\n", "_____no_output_____" ] ], [ [ "def calculate_error(m, b, point):\n x_point, y_point = point\n y = m*x_point + b\n distance = abs(y - y_point)\n return distance\n", "_____no_output_____" ] ], [ [ "Let's test this function!", "_____no_output_____" ] ], [ [ "#this is a line that looks like y = x, so (3, 3) should lie on it. thus, error should be 0:\nprint(calculate_error(1, 0, (3, 3)))\n#the point (3, 4) should be 1 unit away from the line y = x:\nprint(calculate_error(1, 0, (3, 4)))\n#the point (3, 3) should be 1 unit away from the line y = x - 1:\nprint(calculate_error(1, -1, (3, 3)))\n#the point (3, 3) should be 5 units away from the line y = -x + 1:\nprint(calculate_error(-1, 1, (3, 3)))", "0\n1\n1\n5\n" ] ], [ [ "Great! Reggie's datasets will be sets of points. For example, he ran an experiment comparing the width of bouncy balls to how high they bounce:\n", "_____no_output_____" ] ], [ [ "datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]", "_____no_output_____" ] ], [ [ "The first datapoint, `(1, 2)`, means that his 1cm bouncy ball bounced 2 meters. The 4cm bouncy ball bounced 4 meters.\n\nAs we try to fit a line to this data, we will need a function called `calculate_all_error`, which takes `m` and `b` that describe a line, and `points`, a set of data like the example above.\n\n`calculate_all_error` should iterate through each `point` in `points` and calculate the error from that point to the line (using `calculate_error`). It should keep a running total of the error, and then return that total after the loop.\n", "_____no_output_____" ] ], [ [ "def calculate_all_error(m, b, points):\n total_error = 0\n for point in datapoints:\n point_error = calculate_error(m, b, point)\n total_error += point_error\n return total_error", "_____no_output_____" ] ], [ [ "Let's test this function!", "_____no_output_____" ] ], [ [ "#every point in this dataset lies upon y=x, so the total error should be zero:\ndatapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)]\nprint(calculate_all_error(1, 0, datapoints))\n\n#every point in this dataset is 1 unit away from y = x + 1, so the total error should be 4:\ndatapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)]\nprint(calculate_all_error(1, 1, datapoints))\n\n#every point in this dataset is 1 unit away from y = x - 1, so the total error should be 4:\ndatapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)]\nprint(calculate_all_error(1, -1, datapoints))\n\n\n#the points in this dataset are 1, 5, 9, and 3 units away from y = -x + 1, respectively, so total error should be\n# 1 + 5 + 9 + 3 = 18\ndatapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)]\nprint(calculate_all_error(-1, 1, datapoints))", "0\n4\n4\n18\n" ] ], [ [ "Great! It looks like we now have a function that can take in a line and Reggie's data and return how much error that line produces when we try to fit it to the data.\n\nOur next step is to find the `m` and `b` that minimizes this error, and thus fits the data best!\n", "_____no_output_____" ], [ "## Part 2: Try a bunch of slopes and intercepts!\n\nThe way Reggie wants to find a line of best fit is by trial and error. He wants to try a bunch of different slopes (`a` values) and a bunch of different intercepts (`b` values) and see which one produces the smallest error value for his dataset.\n\nUsing a list comprehension, let's create a list of possible `a` values to try. Make the list `possible_as` that goes from -10 to 10, in increments of 0.1.", "_____no_output_____" ], [ "The way Reggie wants to find a line of best fit is by trial and error. He wants to try a bunch of different slopes (`m` values) and a bunch of different intercepts (`b` values) and see which one produces the smallest error value for his dataset.\n\nUsing a list comprehension, let's create a list of possible `m` values to try. Make the list `possible_ms` that goes from -10 to 10, in increments of 0.1.\n\nHint (to view this hint, either double-click this cell or highlight the following white space): <font color=\"white\">you can go through the values in range(-100, 100) and multiply each one by 0.1</font>\n\n", "_____no_output_____" ] ], [ [ "possible_ms = [m * 0.1 for m in range(-100, 100)]", "_____no_output_____" ] ], [ [ "Now, let's make a list of `possible_bs` to check that would be the values from -20 to 20, in steps of 0.1:", "_____no_output_____" ] ], [ [ "possible_bs = [b * 0.1 for b in range(-200, 200)]", "_____no_output_____" ] ], [ [ "We are going to find the smallest error. First, we will make every possible `y = m*x + b` line by pairing all of the possible `m`s with all of the possible `b`s. Then, we will see which `y = m*x + b` line produces the smallest total error with the set of data stored in `datapoint`.\n\nFirst, create the variables that we will be optimizing:\n* `smallest_error` &mdash; this should start at infinity (`float(\"inf\")`) so that any error we get at first will be smaller than our value of `smallest_error`\n* `best_m` &mdash; we can start this at `0`\n* `best_b` &mdash; we can start this at `0`\n\nWe want to:\n* Iterate through each element `m` in `possible_ms`\n* For every `m` value, take every `b` value in `possible_bs`\n* If the value returned from `calculate_all_error` on this `m` value, this `b` value, and `datapoints` is less than our current `smallest_error`,\n* Set `best_m` and `best_b` to be these values, and set `smallest_error` to this error.\n\nBy the end of these nested loops, the `smallest_error` should hold the smallest error we have found, and `best_m` and `best_b` should be the values that produced that smallest error value.\n\nPrint out `best_m`, `best_b` and `smallest_error` after the loops.\n\n", "_____no_output_____" ] ], [ [ "datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]\nbest_error = float(\"inf\")\nbest_m = 0\nbest_b = 0\n\nfor m in possible_ms:\n for b in possible_bs:\n \t error = calculate_all_error(m, b, datapoints)\n \t if error < best_error:\n \t\t best_m = m\n \t\t best_b = b\n \t\t best_error = error\n \t \nprint(best_m, best_b, best_error)\n", "0.30000000000000004 1.7000000000000002 4.999999999999999\n" ] ], [ [ "## Part 3: What does our model predict?\n\nNow we have seen that for this set of observations on the bouncy balls, the line that fits the data best has an `m` of 0.3 and a `b` of 1.7:\n\n```\ny = 0.3x + 1.7\n```\n\nThis line produced a total error of 5.\n\nUsing this `m` and this `b`, what does your line predict the bounce height of a ball with a width of 6 to be?\nIn other words, what is the output of `get_y()` when we call it with:\n* m = 0.3\n* b = 1.7\n* x = 6", "_____no_output_____" ] ], [ [ "get_y(0.3, 1.7, 6)", "_____no_output_____" ] ], [ [ "Our model predicts that the 6cm ball will bounce 3.5m.\n\nNow, Reggie can use this model to predict the bounce of all kinds of sizes of balls he may choose to include in the ball pit!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d010bdf4a24b60fb17b4990af62360d887f42d35
24,482
ipynb
Jupyter Notebook
examples/presentation.ipynb
jtpio/pixijs-jupyter
e690d96e177d34ddc4937b40a816f36fe427b00d
[ "BSD-3-Clause" ]
9
2018-07-10T10:11:59.000Z
2021-06-03T12:02:14.000Z
examples/presentation.ipynb
jtpio/pixijs-jupyter
e690d96e177d34ddc4937b40a816f36fe427b00d
[ "BSD-3-Clause" ]
1
2018-08-09T09:41:06.000Z
2018-08-10T06:52:34.000Z
examples/presentation.ipynb
jtpio/pixijs-jupyter
e690d96e177d34ddc4937b40a816f36fe427b00d
[ "BSD-3-Clause" ]
1
2019-10-15T15:00:22.000Z
2019-10-15T15:00:22.000Z
22.816403
262
0.498162
[ [ [ "# Practical Examples of Interactive Visualizations in JupyterLab with Pixi.js and Jupyter Widgets\n\n# PyData Berlin 2018 - 2018-07-08\n\n# Jeremy Tuloup\n\n# [@jtpio](https://twitter.com/jtpio)\n# [github.com/jtpio](https://github.com/jtpio)\n# [jtp.io](https://jtp.io)", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# The Python Visualization Landscape (2017)\n\n\n![Python Landscape](./img/python_viz_landscape.png)\n\nSource:\n\n- [Jake VanderPlas: The Python Visualization Landscape PyCon 2017](https://www.youtube.com/watch?v=FytuB8nFHPQ)\n- [Source for the Visualization](https://github.com/rougier/python-visualization-landscape), by Nicolas P. Rougier", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Motivation\n\n\n|Not This|This|\n|:--------------------------:|:-----------------------------------------:|\n|![from](img/matplotlib_barchart.png) | ![to](img/pixijs-jupyterlab.gif)|", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# JupyterLab - Pixi.js - Jupyter Widgets?", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Prerequisites\n\n# * Jupyter Notebook\n# * Python", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# JupyterLab", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "![pixi](pixi/pixijs-logo.png)\n\n## * Powerful 2D rendering engine written in JavaScript\n## * Abstraction on top of Canvas and WebGL\n\n# [Live Example!](http://localhost:4000)\n\n```javascript\nlet app = new PIXI.Application(800, 600, {backgroundColor : 0x1099bb});\ndocument.body.appendChild(app.view);\n\nlet bunny = PIXI.Sprite.fromImage('bunny.png')\n\nbunny.anchor.set(0.5);\n\nbunny.x = app.screen.width / 2;\nbunny.y = app.screen.height / 2;\n\napp.stage.addChild(bunny);\n\napp.ticker.add((delta) => {\n bunny.rotation += 0.1 * delta;\n});\n```", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Jupyter Widgets\n\n![WidgetModelView](./img/WidgetModelView.png)\n\n[Open the image](./img/WidgetModelView.png)\n\n- Source: [https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Basics.html#Why-does-displaying-the-same-widget-twice-work?](https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Basics.html#Why-does-displaying-the-same-widget-twice-work?)", "_____no_output_____" ] ], [ [ "from ipywidgets import IntSlider\nslider = IntSlider(min=0, max=10)\nslider", "_____no_output_____" ], [ "slider", "_____no_output_____" ], [ "slider.value", "_____no_output_____" ], [ "slider.value = 2", "_____no_output_____" ] ], [ [ "# Tutorial to create your own\n\n## https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Custom.html\n\n# Libraries\n\n## bqplot\n\n![bqplot](./img/bqplot.gif)\n\n## ipyleaflet\n\n![ipyleaflet](./img/ipyleaflet.gif)\n\n## ipyvolume\n\n![ipyvolume](./img/ipyvolume.gif)", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Motivation: Very Custom Visualizations", "_____no_output_____" ], [ "![motivation](./img/pixijs-jupyterlab.gif)", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Drawing Shapes on a Canvas", "_____no_output_____" ] ], [ [ "from ipyutils import SimpleShape", "_____no_output_____" ] ], [ [ "# Implementation\n\n## - [simple_shape.py](../ipyutils/simple_shape.py): defines the **SimpleShape** Python class\n## - [widget.ts](../src/simple_shapes/widget.ts): defines the **SimpleShapeModel** and **SimpleShapeView** Typescript classes", "_____no_output_____" ] ], [ [ "square = SimpleShape()\nsquare", "_____no_output_____" ], [ "square.rotate = True", "_____no_output_____" ] ], [ [ "# Level Up 🚀", "_____no_output_____" ] ], [ [ "from ipyutils import Shapes\nshapes = Shapes(n_shapes=100)\nshapes", "_____no_output_____" ], [ "shapes.shape", "_____no_output_____" ], [ "shapes.shape = 'square'", "_____no_output_____" ], [ "shapes.rotate = True", "_____no_output_____" ], [ "shapes.wobble = True", "_____no_output_____" ] ], [ [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Visualizing Recursion with the Bermuda Triangle Puzzle\n\n![Bermuda Triangle Puzzle](img/bermuda_triangle_puzzle.jpg)", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Motivation\n\n# * Solve the puzzle programmatically\n# * Verify a solution visually\n# * Animate the process", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# BermudaTriangle Widget", "_____no_output_____" ] ], [ [ "from ipyutils import TriangleAnimation, BermudaTriangle\ntriangles = TriangleAnimation()\ntriangles", "_____no_output_____" ] ], [ [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# What can we do with this widget?", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Visualize Transitions\n\nFrom | To\n:--------------------------:|:-------------------------:\n![from](img/anim_from.png) | ![to](img/anim_to.png)", "_____no_output_____" ] ], [ [ "# states\nstate_0 = [None] * 16\nprint(state_0)", "[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]\n" ], [ "state_1 = [[13, 1]] + [None] * 15\nprint(state_1)", "[[13, 1], None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]\n" ], [ "state_2 = [[13, 1], [12, 0]] + [None] * 14\nprint(state_2)", "[[13, 1], [12, 0], None, None, None, None, None, None, None, None, None, None, None, None, None, None]\n" ] ], [ [ "# Example States and Animation", "_____no_output_____" ] ], [ [ "example_states = TriangleAnimation()\nbermuda = example_states.bermuda\nbermuda.states = [\n [None] * 16,\n [[7, 0]] + [None] * 15,\n [[7, 1]] + [None] * 15,\n [[7, 2]] + [None] * 15,\n [[7, 2], [0, 0]] + [None] * 14,\n [[7, 2], [0, 1]] + [None] * 14,\n [[i, 0] for i in range(16)],\n [[i, 1] for i in range(16)],\n]\nexample_states", "_____no_output_____" ] ], [ [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Solver", "_____no_output_____" ] ], [ [ "from copy import deepcopy\n\nclass Solver(BermudaTriangle):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.reset_state()\n \n def reset_state(self):\n self.board = [None] * self.N_TRIANGLES\n self.logs = [deepcopy(self.board)]\n self.it = 0\n \n def solve(self):\n '''\n Method to implement\n '''\n raise NotImplementedError()\n\n def log(self):\n self.logs.append(deepcopy(self.board))\n \n def found(self):\n return all(self.is_valid(i) for i in range(self.N_TRIANGLES))\n \n def save_state(self):\n self.permutation = self.board\n self.states = self.logs", "_____no_output_____" ] ], [ [ "# Valid Permutation - is_valid()", "_____no_output_____" ] ], [ [ "help(Solver.is_valid)", "Help on function is_valid in module ipyutils.bermuda:\n\nis_valid(self, i)\n Parameters\n ----------\n \n i: int\n Position of the triangle to check, between 0 and 15 (inclusive)\n \n Returns\n -------\n valid: bool\n True if the triangle at position i doesn't have any conflict\n False otherwise\n\n" ] ], [ [ "```python\nsolver.is_valid(7)\n# False\n```\n![Valid](./img/valid_triangle.png)", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# First Try: Random Permutations", "_____no_output_____" ] ], [ [ "import random\n\nclass RandomSearch(Solver):\n \n def solve(self):\n random.seed(42)\n self.reset_state()\n for i in range(200):\n self.board = random.sample(self.permutation, self.N_TRIANGLES)\n self.log()\n if self.found():\n print('Found!')\n return True\n return False", "_____no_output_____" ], [ "%%time\n\nsolver = RandomSearch()\nres = solver.solve()\nsolver.save_state()", "CPU times: user 93.8 ms, sys: 3.94 ms, total: 97.7 ms\nWall time: 97.5 ms\n" ], [ "rnd = TriangleAnimation()\nrnd.bermuda.title = 'Random Search'\nrnd.bermuda.states = solver.states\nrnd", "_____no_output_____" ] ], [ [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Better: Brute Force using Recursion", "_____no_output_____" ] ], [ [ "class RecursiveSolver(Solver):\n \n def solve(self):\n self.used = [False] * self.N_TRIANGLES\n self.reset_state()\n self._place(0)\n return self.board\n \n def _place(self, i):\n self.it += 1\n if i == self.N_TRIANGLES:\n return True\n \n for j in range(self.N_TRIANGLES - 1, -1, -1):\n if self.used[j]:\n # piece number j already used\n continue\n \n self.used[j] = True\n \n for rot in range(3):\n # place the piece on the board\n self.board[i] = (j, rot)\n self.log()\n\n # stop the recursion if the current configuration\n # is not valid or a solution has been found\n if self.is_valid(i) and self._place(i + 1):\n return True\n\n # remove the piece from the board\n self.board[i] = None\n self.used[j] = False\n self.log()\n \n return False", "_____no_output_____" ], [ "%%time\n\nsolver = RecursiveSolver()\nres = solver.solve()\nif solver.found():\n print('Solution found!')\n print(f'{len(solver.logs)} steps')\n solver.save_state()\nelse:\n print('No solution found')", "Solution found!\n10753 steps\nCPU times: user 2.3 s, sys: 10.1 ms, total: 2.31 s\nWall time: 2.32 s\n" ], [ "recursion = TriangleAnimation()\nrecursion.bermuda.title = 'Recursive Search'\nrecursion.bermuda.states = solver.states\nrecursion", "_____no_output_____" ] ], [ [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# More details for this example\n\n## * In depth walkthrough on how to create a Jupyter Widget in the notebook\n## * [p5.js in the Jupyter Notebook for custom interactive visualizations](https://github.com/jtpio/p5-jupyter-notebook/blob/master/puzzle.ipynb)\n## * Using p5.js instead of Pixi.js, but similar concepts\n## * Source: [github.com/jtpio/p5-jupyter-notebook](https://github.com/jtpio/p5-jupyter-notebook)\n## * [Run on Binder](https://mybinder.org/v2/gh/jtpio/p5-jupyter-notebook/master?filepath=puzzle.ipynb)", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Recap\n\n## * Custom interactive animations with Pixi.js\n## * Leverage the JavaScript ecosystem in JupyterLab", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Applications\n\n## * Visual debugging and understanding\n## * Teaching and education, learning by doing\n## * Combine JavaScript games with data\n\n# Downside\n\n## * Requires some effort to build the visualizations in TypeScript / JavaScript", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# References\n\n## Presentations\n\n### - [Jake VanderPlas: The Python Visualization Landscape PyCon 2017](https://www.youtube.com/watch?v=FytuB8nFHPQ)\n### - [PyData London 2016: Sylvain Corlay - Interactive Visualization in Jupyter with Bqplot and Interactive Widgets](https://www.youtube.com/watch?v=eVET9IYgbao)\n### - [PLOTCON 2017: Sylvain Corlay, Interactive Data Visualization in JupyterLab with Jupyter](https://www.youtube.com/watch?v=p7Hr54VhOp0)\n### - [PyData Amsterdam 2017: Maarten Breddels | A billion stars in the Jupyter Notebook](https://www.youtube.com/watch?v=bP-JBbjwLM8)\n\n## Widgets\n\n### - [Building a Custom Widget Tutorial](https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Custom.html)\n### - [Authoring Custom Jupyter Widgets](https://blog.jupyter.org/authoring-custom-jupyter-widgets-2884a462e724)\n### - [p5.js in the Jupyter Notebook for custom interactive visualizations](https://github.com/jtpio/p5-jupyter-notebook/blob/master/puzzle.ipynb)\n### - [pythreejs](https://github.com/jovyan/pythreejs): Implemented as an Jupyter Widget\n### - [bqplot](https://github.com/bloomberg/bqplot): Great library for interactive data exploration\n### - [ipyvolume](https://github.com/maartenbreddels/ipyvolume): 3d plotting for Python in the Jupyter Notebook\n### - [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet): interactive maps in the Jupyter notebook", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ], [ "# Questions?\n\n## [@jtpio](https://twitter.com/jtpio)\n\n## [github.com/jtpio](https://github.com/jtpio)\n\n## [jtp.io](jtp.io)", "_____no_output_____" ], [ "![skip](./img/skip.png)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d010cea376f26f4a79668b1e962fa5f3d8b1f69c
20,549
ipynb
Jupyter Notebook
semana_6/intro_regressao.ipynb
rocabrera/curso_ml
e61a15ba3b031540dfce39a2d587e3738446838d
[ "MIT" ]
3
2022-01-27T22:12:01.000Z
2022-03-29T21:43:58.000Z
semana_6/intro_regressao.ipynb
rocabrera/curso_ml
e61a15ba3b031540dfce39a2d587e3738446838d
[ "MIT" ]
null
null
null
semana_6/intro_regressao.ipynb
rocabrera/curso_ml
e61a15ba3b031540dfce39a2d587e3738446838d
[ "MIT" ]
null
null
null
31.662558
357
0.601148
[ [ [ "# Regressão linear\n\n\n## **TOC:**\n\nNa aula de hoje, vamos explorar os seguintes tópicos em Python:\n\n- 1) [Introdução](#intro)\n- 2) [Regressão linear simples](#reglinear)\n- 3) [Regressão linear múltipla](#multireglinear)\n- 4) [Tradeoff viés-variância](#tradeoff)", "_____no_output_____" ] ], [ [ "# importe as principais bibliotecas de análise de dados\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "____\n____\n____", "_____no_output_____" ], [ "## 1) **Introdução** <a class=\"anchor\" id=\"intro\"></a>\n\nImagine que você que vender sua casa.\n\nVocê sabe os atributos da sua casa: quantos cômodos têm, quantos carros cabem na garagem, qual é a área construída, qual sua localidade, etc.\n\nAgora, a pergunta é: qual seria o melhor preço pra você colocá-la a venda, ou seja, quanto de fato ela vale?\n\nVocê pode solicitar a avaliação de um corretor de imóveis (contanto com a experiência dele), ou então...\n\n...fazer um modelo de **Machine Learning**, que, com base nos atributos e preços de diversas outras casas, pode fazer uma **predição** sobre o preço adequado da sua casa!\n\nPara resolver este problema, podemos utilizar um dos mais simples e importantes algoritmos de machine learning: a Regressão Linear!\n\n____", "_____no_output_____" ], [ "Para introduzirmos as ideias, vamos usar um [dataset de preço de casas](https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data).\n\nEsta base de dados contém **70 features** (+ 1 ID), que são as características de cada uma das casas listadas; e **1 target**, que é o preço pelo qual aquela casa foi vendida.\n\nPara o significado de cada uma das features, e os valores que elas podem assumir, veja a página acima.\n\n**Vamos ler a base e começar a explorá-la!**", "_____no_output_____" ] ], [ [ "df = pd.read_csv(\"data/house_prices/house_price.csv\")", "_____no_output_____" ] ], [ [ "Por enquanto, não vamos nos preocupar com os dados missing, pois vamos usar apenas uma feature no nosso modelo inicial.\n\nAproveite para depois explorar os dados da forma que quiser!\n\nPor enquanto, vamos dar uma olhada na coluna target!", "_____no_output_____" ], [ "Fica evidente que a distribuição é desviada para a direita.\n\nVamos tentar alterar isso na próximas versões do modelo para ver se teremos ganhos de performance!\n\nPor enquanto, seguimos assim.", "_____no_output_____" ], [ "Parece que a variável de área construída ```GrLivArea```) é uma forte candidata a **explicar** o preço das casas, pois vemos calaramente uma correlação entre as variáveis!\n\nMas note que há claramente dois outliers... ", "_____no_output_____" ], [ "Vamos agora iniciar a construção de um modelo bem simples, que utilize a variável GrLivArea para predizer o preço!", "_____no_output_____" ], [ "___\n___\n___", "_____no_output_____" ], [ "## 2) **Regressão linear simples** <a class=\"anchor\" id=\"reglinear\"></a>\n\nApesar de alguns outliers, parece bem adequado que os pontos plotados acima sejam descritos por uma reta, não é mesmo?\n\nOu, melhor dizendo: **a variável GrLivArea parece estar relacionada ao target SalePrice linearmente!**\n\nPara modelarmos esta relação, vamos conhecer o modelo de **Regressão Linear Simples**.\n\nComo o próprio nome diz, o modelo de Regressão Linear será **uma reta (polinômio linear)**, que melhor se ajusta aos seus dados!\n\nO modelo de **Regressão Linear Simples** será uma linha reta que relaciona Y (o preço da casa) e X (os atributos da casa). \n\nSe utilizarmos **apenas um atributo** (como, por exemplo, a área construída), temos uma **Regressão Linear Simples**, e nosso modelo é:\n\n$$ y = b_0 + b_1 X $$\n\nNeste caso, o modelo tem dois coeficientes a serem determinados: $b_0$ (intercepto ou coeficiente linear) e $b_1$ (coeficiente angular). \n\nO algoritmo do estimador é utilizado justamente para encontrarmos os coeficientes $b_0$ e $b_1$ **que melhor se ajustam aos dados!**\n\nPara fazer isso, pode-se utilizar o método dos **mínimos quadrados** ou então o **gradiente descendente**.\n\nMas não nos preocuparemos com os detalhes do treinamento: usaremos o sklearn para isso!\n\nVamos começar?", "_____no_output_____" ], [ "Agora que o modelo está treinado, podemos dar uma olhada nos coeficientes que foram encontrados!", "_____no_output_____" ], [ "Como interpretamos este resultado?\n\nO nosso modelo final é dado por:\n\n$$ y = 1562.01 + 118.61 \\times \\text{GrLiveArea}$$\n\nIsto quer dizer que:\n\n> Aumentando a variável \"GrLiveArea\" em uma unidade faz com que o preço seja aumentado em USD 118.6!\n\n> O preço mínimo a ser pago, independente da área construída, é de 1562.01!", "_____no_output_____" ], [ "Podemos visualizar o modelo treinado, neste caso:", "_____no_output_____" ], [ "Fazendo uma previsão:", "_____no_output_____" ], [ "Ou ainda:", "_____no_output_____" ], [ "É raro que consigamos visualizar nosso modelo final como fizemos acima, mas no caso da regressão linear simples, temos essa sorte! :)\n\nVamos agora fazer algumas previsões!", "_____no_output_____" ], [ "Agora que temos o modelo treinado e algumas previsões, como avaliamos a performance do modelo?\n\nPara isso, podemos dar uma olhada nos **resíduos** das predições! Os resíduos nada mais são do que **os erros do modelo**, ou seja, **a diferença entre cada valor predito e o valor real**, para **os dados de teste!**. Isto é,\n\n$$R(y_i) = y_i - \\hat{y}_i $$", "_____no_output_____" ], [ "O caso 100% ideal seria $y_i = \\hat{y}_i$, o que produziria uma reta exata!\n\nQuanto mais \"espalhados\" estiverem os pontos em torno da reta, em geral **pior é o modelo**, pois ele está errando mais!\n\nUma forma de quantificar isso através de uma métrica conhecida como **$R^2$**, o **coeficiente de determinação**.\n\nEste coeficiente indica **o quão próximos os dados estão da reta ajustada**. Por outro lado, o $R^2$ representa a porcentagem de variação na resposta que é explicada pelo modelo.\n\n$$R^2 = 1 - \\frac{\\sum_{i=1}^n(y_i-\\hat{y}_i)^2}{\\sum_{i=1}^n(y_i-\\bar{y})^2}$$\n\nÉ possível utilizar o $R^2$ nos dados de treino, mas isso não é tão significante, devido ao overfitting, que discutiremos a seguir. Mais sgnificativo é calcularmos o $R^2$ nos dados de teste como faremos a seguir. Essa métrica equivale, portanto, **ao gráfico que fizemos acima!**\n", "_____no_output_____" ], [ "Outra coisa importante é que os resíduos sejam **normalmente distribuídos**.\n\nSe esse não for o caso, é muito importante que você reveja se o modelo escolhido de fato é adequado ao seu problema!", "_____no_output_____" ], [ "Além dos resíduos, existem três principais **métricas de avaliação** do modelo de regressão linear:", "_____no_output_____" ], [ "**Mean Absolute Error** (MAE) é a média do valor absoluto de todos os resíduos (erros):\n\n$$\\frac 1n\\sum_{i=1}^n|y_i-\\hat{y}_i|$$\n\n**Mean Squared Error** (MSE) é a média dos erros quadrados:\n\n$$\\frac 1n\\sum_{i=1}^n(y_i-\\hat{y}_i)^2$$\n\n**Root Mean Squared Error** (RMSE) é a raiz quadrada da média dos erros quadrados:\n\n$$\\sqrt{\\frac 1n\\sum_{i=1}^n(y_i-\\hat{y}_i)^2}$$\n\nComparando as métricas:\n\n- **MAE** é a mais simples de entender, mas ela penaliza mais erros menores;\n- **MSE** é a métrica mais popular, pois essa métrica penaliza mais erros maiores, o que faz mais sentido em aplicações reais.\n- **RMSE** é ainda mais popular, pois esta métrica está nas mesmas unidades que o target.\n\nEstas métricas todas podem ser utilizadas como **funções de custo** a serem minimizadas pelo algoritmo do estimador.", "_____no_output_____" ], [ "___", "_____no_output_____" ], [ "## 3) **Regressão linear múltipla** <a class=\"anchor\" id=\"multireglinear\"></a>\n\n\nO modelo que fizemos acima considera uma única feature como preditora do preço da casa.\n\nMas temos outras 78 dessas features! Será que não há mais informação útil em todas essas outras variáveis?\n\nEm geral, sim! É natural que esperemos que **mais variáveis** tragam **mais informações** ao modelo, e, portanto, o torne mais preciso!\n\nPara incorporar estas outras variáveis ao modelo, é muito simples! \n\nPodemos passar a utilizar outros atributos (como o número de cômodos, qual é a renda média da vizinhança, etc.), e neste caso teremos uma **Regressão Linear Múltipla**, que nada mais é que a seguinte equação:\n\n$$ y = b_0 + b_1 X_1 + b_2 X_2 + \\cdots + b_n X_n $$\n\nNeste caso, além de $b_0$ e $b_1$, temos também outros coeficientes, um pra cada uma das $n$ features que escolhermos!\n\nModelos de regressão múltipla são potencialmente mais precisos, mas há também um lado ruim: nós perdemos a **possibilidade de visualização**. Agora, não temos mais uma reta, mas sim um **hiperplano** que relaciona todas as features com o target!\n\n<center><img src=\"https://miro.medium.com/max/1120/0*rGSfRsMjiQeG5jof.png\" width=500></center>\n\nVamos construir esse modelo?", "_____no_output_____" ], [ "Observação: a coluna \"Id\" traz apenas um número de identificação arbitrário que não deve ser correlacionado com o target. Portanto, vamos desconsiderar esta coluna de nosso modelo!", "_____no_output_____" ], [ "A performance do modelo melhorou?\n\nSerá que dá pra melhorar mais?\n\nOpções:\n\n- tentar apenas um subconjunto de features: **feature selection**\n\n\n- passar a utilizar as features categóricas: **feature engeneering**", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "## 4) **Tradeoff viés-variância** <a class=\"anchor\" id=\"tradeoff\"></a>\n\nVeremos agora um dos conceitos mais importantes em apredizado de maquina.\n\nMuitas vezes alguns modelos têm 100% de acerto nos dados de **treino**, mas **na base de teste** a performance cai para menos de 50%.\n\nIsso pode acontecer porque o modelo fica **especialista apenas no conjunto de treino**, não conseguindo **generalizar os padrões para além dos dados vistos**.\n\n<center><img src=\"https://miro.medium.com/max/1125/1*_7OPgojau8hkiPUiHoGK_w.png\" width=800></center>\n\nO overfitting está intimamente ligado com o conceito de **viés** (bias) e **variância** (variance):\n\n>**Viés**<br>\nÉ a diferença entre o que o modelo prediz, e o valor correto a ser predito.<br>\nModelos com alto viés são muito simples, de modo a **não conseguir capturar as relações que os dados de treino exibem** (underfit).<br>\nIssso faz com que ambos os erros de treino e de teste sejam altos.\n<br><br>\nEm outras palavras:<br>\n**Incapacidade de um modelo de capturar a verdadeira relação entre features e target**\n\n\n> **Variância**<br>\nVariância se refere à variabilidade das predições de um modelo.<br>\nModelos com alta variância são muito complexos, por **aprenderem demais as relações exibidas nos dados de treino** (overfit).<br>\nIsso faz com que os erros de treino sejam baixos, mas os erros de teste sejam altos.\n<br><br>\nEm outras palavras:<br>\n**Incapacidade de um modelo performar bem em outros datasets diferentes do usado no treinamento**. \n\n<center><img src=\"https://www.learnopencv.com/wp-content/uploads/2017/02/Bias-Variance-Tradeoff-In-Machine-Learning-1.png\" width=500></center>\n\n<center><img src=\"https://miro.medium.com/max/1494/1*C7ZKM93QVdpeSCGbF5TjIg.png\" width=800></center>\n\nPara demonstrar overfit ser usado o conjuto de teste [anscombe](https://en.wikipedia.org/wiki/Anscombe%27s_quartet)", "_____no_output_____" ] ], [ [ "df_anscombe = sns.load_dataset('anscombe')\n\ndf_anscombe.groupby(\"dataset\").agg({\"mean\", \"std\"})", "_____no_output_____" ] ], [ [ "Vamos supor que este dado represente valores de medições de um sensor, porém o sensor teve um pequeno problema durante a medição.\n\nPodemos perceber facilmente qual é este erro, e qual seria a função de regreesão para este sensor com os dados validos: **regressão linear**.", "_____no_output_____" ], [ "Perceba que a função linear encontrar já aprensenta um padrão muito similiar aos dados, porém um ponto error faz com que ela não tenha um resultado otimo.\n\nPodemos utilizar regressões polinomiais, que possuem ordem maiores que 1, para tentar diminuir o erro da regressão, obtendo uma equação do formato.\n\n$$\\hat{y}_{i} = \\beta_{1} + \\beta_{2} x_{i} + \\beta_{3} {x_{i}}^{2} + \\cdots + \\beta_{6} {x_{i}}^{6}$$\n\nPara criar modelos polinomiaus com o sklearn, [dê uma olhada aqui](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html)", "_____no_output_____" ], [ "Ao utilizarmos uma regressão de ordem 6 percebemos que ela se ajusta ao valor com erro, porém ela **se distancia da regressão que realmente representa os dados**. \n\nTentar **aprender o erro faz com ela com ela não aprenda a função real**. \n\nIsto acontece pois ela se **super ajustou aos dados de treino, se distanciando dos dados reais**. ", "_____no_output_____" ], [ "__Como garantir que nosso modelo não está sofrendo de overfitting?__\n\nNaturalmente, essa é uma pergunta de extrema importância, especialmente no contexto de **Redes neurais**. [Veja aqui](https://towardsdatascience.com/8-simple-techniques-to-prevent-overfitting-4d443da2ef7d) e [aqui](https://towardsdatascience.com/dont-overfit-how-to-prevent-overfitting-in-your-deep-learning-models-63274e552323) algumas discussões.\n\nNa prática: **jamais se apegue à peformance de treino!!**. O que queremos otimizar sempre será a performance **avaliada nos dados de teste**. Assim, garantimos que uma boa performance não é produto do overfitting!", "_____no_output_____" ], [ "--- ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "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" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d010d3dd19432c4679651da1d99329e198bbad57
158,849
ipynb
Jupyter Notebook
examples/3C279_spectrum.ipynb
volodymyrss/oda_api_benchmark
91580ff5ac121352f901880eeecf3bfc12fb4c24
[ "MIT" ]
null
null
null
examples/3C279_spectrum.ipynb
volodymyrss/oda_api_benchmark
91580ff5ac121352f901880eeecf3bfc12fb4c24
[ "MIT" ]
null
null
null
examples/3C279_spectrum.ipynb
volodymyrss/oda_api_benchmark
91580ff5ac121352f901880eeecf3bfc12fb4c24
[ "MIT" ]
null
null
null
85.494618
21,660
0.6898
[ [ [ "from oda_api.api import DispatcherAPI\nfrom oda_api.plot_tools import OdaImage,OdaLightCurve\nfrom oda_api.data_products import BinaryData\nimport os\nfrom astropy.io import fits\nimport numpy as np\nfrom numpy import sqrt\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "source_name='3C 279'\nra=194.046527\ndec=-5.789314\nradius=10.\nTstart='2003-03-15T00:00:00'\nTstop='2018-03-15T00:00:00'\nE1_keV=30.\nE2_keV=100.\nhost='www.astro.unige.ch/cdci/astrooda/dispatch-data'\nrebin=10 # minimal significance in energy bin, for spectral plotting", "_____no_output_____" ], [ "try: input = raw_input\nexcept NameError: pass\ntoken=input() # token for restricted access server\ncookies=dict(_oauth2_proxy=token)\ndisp=DispatcherAPI(host=host)", "\n" ], [ "disp=DispatcherAPI(host=host)", "_____no_output_____" ], [ "import requests\nurl=\"https://www.astro.unige.ch/cdci/astrooda/dispatch-data/gw/timesystem/api/v1.0/scwlist/cons/\"\ndef queryxtime(**args):\n params=Tstart+'/'+Tstop+'?&ra='+str(ra)+'&dec='+str(dec)+'&radius='+str(radius)+'&min_good_isgri=1000'\n print(url+params)\n return requests.get(url+params,cookies=cookies).json()", "_____no_output_____" ], [ "scwlist=queryxtime()\nm=len(scwlist)\npointings_osa10=[]\npointings_osa11=[]\nfor i in range(m):\n if scwlist[i][-2:]=='10':\n if(int(scwlist[i][:4])<1626):\n pointings_osa10.append(scwlist[i]+'.001')\n else:\n pointings_osa11.append(scwlist[i]+'.001')\n#else:\n# pointings=np.genfromtxt('scws_3C279_isgri_10deg.txt', dtype='str')\nm_osa10=len(pointings_osa10)\nm_osa11=len(pointings_osa11)", "https://www.astro.unige.ch/cdci/astrooda/dispatch-data/gw/timesystem/api/v1.0/scwlist/cons/2003-03-15T00:00:00/2018-03-15T00:00:00?&ra=194.046527&dec=-5.789314&radius=10.0&min_good_isgri=1000\n" ], [ "scw_lists_osa10=[]\nscw_lists_osa11=[]\ncount=0\nscw_string=''\nfor i in range(m_osa10):\n if count<50:\n scw_string=scw_string+str(pointings_osa10[i])+','\n count+=1\n else:\n scw_lists_osa10.append(scw_string[:-1])\n count=0\n scw_string=str(pointings_osa10[i])+','\nscw_lists_osa10.append(scw_string[:-1])\nprint(len(scw_lists_osa10))\ncount=0\nscw_string=''\nfor i in range(m_osa11):\n if count<50:\n scw_string=scw_string+str(pointings_osa11[i])+','\n count+=1\n else:\n scw_lists_osa11.append(scw_string[:-1])\n count=0\n scw_string=str(pointings_osa11[i])+','\nscw_lists_osa11.append(scw_string[:-1])\nprint(len(scw_lists_osa11))", "22\n2\n" ], [ "data=disp.get_product(instrument='isgri',\n product='isgri_image',\n scw_list=scw_lists_osa10[0],\n E1_keV=E1_keV,\n E2_keV=E2_keV,\n osa_version='OSA10.2',\n RA=ra,\n DEC=dec,\n detection_threshold=3.5,\n product_type='Real')", "007700160010.001,007700170010.001,007700180010.001,007700190010.001,007700200010.001,007700210010.001,007700220010.001,007700230010.001,007700240010.001,007700250010.001,007700260010.001,007700270010.001,007700280010.001,007700290010.001,007700300010.001,007700310010.001,007700320010.001,007700330010.001,007700340010.001,007700350010.001,007700360010.001,007700370010.001,007700380010.001,007700390010.001,007700400010.001,007700410010.001,007700460010.001,007700470010.001,007700480010.001,007700490010.001,007700500010.001,007700510010.001,007700520010.001,007700530010.001,007700540010.001,007700550010.001,007700560010.001,007700570010.001,007700580010.001,007700590010.001,007700600010.001,007700660010.001,007700670010.001,007800020010.001,007800030010.001,007800040010.001,007800050010.001,007800060010.001,007800070010.001,007800080010.001\n- waiting for remote response, please wait run_analysis https://www.astro.unige.ch/cdci/astrooda/dispatch-data\nscw_list 007700160010.001,007700170010.001,007700180010.001,007700190010.001,007700200010.001,007700210010.001,007700220010.001,007700230010.001,007700240010.001,007700250010.001,007700260010.001,007700270010.001,007700280010.001,007700290010.001,007700300010.001,007700310010.001,007700320010.001,007700330010.001,007700340010.001,007700350010.001,007700360010.001,007700370010.001,007700380010.001,007700390010.001,007700400010.001,007700410010.001,007700460010.001,007700470010.001,007700480010.001,007700490010.001,007700500010.001,007700510010.001,007700520010.001,007700530010.001,007700540010.001,007700550010.001,007700560010.001,007700570010.001,007700580010.001,007700590010.001,007700600010.001,007700660010.001,007700670010.001,007800020010.001,007800030010.001,007800040010.001,007800050010.001,007800060010.001,007800070010.001,007800080010.001\nE1_keV 30.0\nE2_keV 100.0\nosa_version OSA10.2\nRA 194.046527\nDEC -5.789314\ndetection_threshold 3.5\ninstrument isgri\nproduct_type isgri_image\nquery_type Real\noff_line (False,)\nquery_status ('new',)\nverbose (False,)\nsession_id 9BBCH4B0GX5I0ZJJ\ndry_run (False,)\napi True\n\n\nquery done succesfully!\n" ], [ "data.dispatcher_catalog_1.table", "_____no_output_____" ], [ "FLAG=0\ntorm=[]\nfor ID,n in enumerate(data.dispatcher_catalog_1.table['src_names']):\n if(n[0:3]=='NEW'):\n torm.append(ID)\n if(n==source_name):\n FLAG=1\ndata.dispatcher_catalog_1.table.remove_rows(torm)\nnrows=len(data.dispatcher_catalog_1.table['src_names'])", "_____no_output_____" ], [ "if FLAG==0:\n data.dispatcher_catalog_1.table.add_row((0,'3C 279',0,ra,dec,0,2,0,0))\n", "_____no_output_____" ], [ "api_cat=data.dispatcher_catalog_1.get_api_dictionary()", "_____no_output_____" ], [ "spectrum_results=[]\nfor i in range(len(scw_lists_osa10)):\n print(i)\n data=disp.get_product(instrument='isgri',\n product='isgri_spectrum',\n scw_list=scw_lists_osa10[i],\n query_type='Real',\n osa_version='OSA10.2',\n RA=ra,\n DEC=dec,\n product_type='Real',\n selected_catalog=api_cat)\n spectrum_results.append(data)", "0\n007700160010.001,007700170010.001,007700180010.001,007700190010.001,007700200010.001,007700210010.001,007700220010.001,007700230010.001,007700240010.001,007700250010.001,007700260010.001,007700270010.001,007700280010.001,007700290010.001,007700300010.001,007700310010.001,007700320010.001,007700330010.001,007700340010.001,007700350010.001,007700360010.001,007700370010.001,007700380010.001,007700390010.001,007700400010.001,007700410010.001,007700460010.001,007700470010.001,007700480010.001,007700490010.001,007700500010.001,007700510010.001,007700520010.001,007700530010.001,007700540010.001,007700550010.001,007700560010.001,007700570010.001,007700580010.001,007700590010.001,007700600010.001,007700660010.001,007700670010.001,007800020010.001,007800030010.001,007800040010.001,007800050010.001,007800060010.001,007800070010.001,007800080010.001\n- waiting for remote response, please wait run_analysis https://www.astro.unige.ch/cdci/astrooda/dispatch-data\nscw_list 007700160010.001,007700170010.001,007700180010.001,007700190010.001,007700200010.001,007700210010.001,007700220010.001,007700230010.001,007700240010.001,007700250010.001,007700260010.001,007700270010.001,007700280010.001,007700290010.001,007700300010.001,007700310010.001,007700320010.001,007700330010.001,007700340010.001,007700350010.001,007700360010.001,007700370010.001,007700380010.001,007700390010.001,007700400010.001,007700410010.001,007700460010.001,007700470010.001,007700480010.001,007700490010.001,007700500010.001,007700510010.001,007700520010.001,007700530010.001,007700540010.001,007700550010.001,007700560010.001,007700570010.001,007700580010.001,007700590010.001,007700600010.001,007700660010.001,007700670010.001,007800020010.001,007800030010.001,007800040010.001,007800050010.001,007800060010.001,007800070010.001,007800080010.001\nquery_type Real\nosa_version OSA10.2\nRA 194.046527\nDEC -5.789314\nselected_catalog {\"cat_frame\": \"fk5\", \"cat_coord_units\": \"deg\", \"cat_column_list\": [[1, 30, 50, 112, 0], [\"3C 273\", \"IGR J12391-1612\", \"NGC 4593\", \"SWIFT J1238.6+0928\", \"3C 279\"], [12.098819732666016, 4.082015037536621, 13.66150951385498, 4.295688629150391, 0.0], [187.2660675048828, 189.77621459960938, 189.91522216796875, 189.67724609375, 194.046527], [2.045917510986328, -16.179750442504883, -5.358253479003906, 9.474955558776855, -5.789314], [-32768, -32768, -32768, -32768, 0], [2, 2, 2, 1, 2], [0, 0, 0, 0, 0], [0.0002800000074785203, 0.00016999999934341758, 0.0002800000074785203, 0.07566666603088379, 0.0]], \"cat_column_names\": [\"meta_ID\", \"src_names\", \"significance\", \"ra\", \"dec\", \"NEW_SOURCE\", \"ISGRI_FLAG\", \"FLAG\", \"ERR_RAD\"], \"cat_column_descr\": [[\"meta_ID\", \"<i8\"], [\"src_names\", \"<U18\"], [\"significance\", \"<f8\"], [\"ra\", \"<f8\"], [\"dec\", \"<f8\"], [\"NEW_SOURCE\", \"<i8\"], [\"ISGRI_FLAG\", \"<i8\"], [\"FLAG\", \"<i8\"], [\"ERR_RAD\", \"<f8\"]], \"cat_lat_name\": \"dec\", \"cat_lon_name\": \"ra\"}\ninstrument isgri\nproduct_type isgri_spectrum\noff_line (False,)\nquery_status ('new',)\nverbose (False,)\nsession_id Y4FZHGU8XTMLNQ5J\ndry_run (False,)\napi True\nthe job has been submitted on the remote server\n / the job is working remotely, please wait status=done - job_id=-283616046116470052 0052 \n\nquery done succesfully!\n1\n007800090010.001,007800100010.001,007800110010.001,007800120010.001,007800130010.001,007800140010.001,007800150010.001,007800160010.001,007800170010.001,007800180010.001,007800190010.001,007800200010.001,007800210010.001,007800220010.001,007800230010.001,007800240010.001,007800250010.001,007800260010.001,007800270010.001,007800280010.001,007800290010.001,007800300010.001,007800310010.001,007800320010.001,007800330010.001,007800340010.001,007800350010.001,007800360010.001,007800370010.001,007800380010.001,007800390010.001,007800400010.001,007800410010.001,007800420010.001,007800430010.001,007800440010.001,007800450010.001,007800460010.001,008900050010.001,008900060010.001,008900070010.001,008900080010.001,008900110010.001,008900120010.001,008900130010.001,008900140010.001,008900150010.001,008900160010.001,008900170010.001,008900230010.001,008900240010.001\n- waiting for remote response, please wait run_analysis https://www.astro.unige.ch/cdci/astrooda/dispatch-data\nscw_list 007800090010.001,007800100010.001,007800110010.001,007800120010.001,007800130010.001,007800140010.001,007800150010.001,007800160010.001,007800170010.001,007800180010.001,007800190010.001,007800200010.001,007800210010.001,007800220010.001,007800230010.001,007800240010.001,007800250010.001,007800260010.001,007800270010.001,007800280010.001,007800290010.001,007800300010.001,007800310010.001,007800320010.001,007800330010.001,007800340010.001,007800350010.001,007800360010.001,007800370010.001,007800380010.001,007800390010.001,007800400010.001,007800410010.001,007800420010.001,007800430010.001,007800440010.001,007800450010.001,007800460010.001,008900050010.001,008900060010.001,008900070010.001,008900080010.001,008900110010.001,008900120010.001,008900130010.001,008900140010.001,008900150010.001,008900160010.001,008900170010.001,008900230010.001,008900240010.001\nquery_type Real\nosa_version OSA10.2\nRA 194.046527\nDEC -5.789314\nselected_catalog {\"cat_frame\": \"fk5\", \"cat_coord_units\": \"deg\", \"cat_column_list\": [[1, 30, 50, 112, 0], [\"3C 273\", \"IGR J12391-1612\", \"NGC 4593\", \"SWIFT J1238.6+0928\", \"3C 279\"], [12.098819732666016, 4.082015037536621, 13.66150951385498, 4.295688629150391, 0.0], [187.2660675048828, 189.77621459960938, 189.91522216796875, 189.67724609375, 194.046527], [2.045917510986328, -16.179750442504883, -5.358253479003906, 9.474955558776855, -5.789314], [-32768, -32768, -32768, -32768, 0], [2, 2, 2, 1, 2], [0, 0, 0, 0, 0], [0.0002800000074785203, 0.00016999999934341758, 0.0002800000074785203, 0.07566666603088379, 0.0]], \"cat_column_names\": [\"meta_ID\", \"src_names\", \"significance\", \"ra\", \"dec\", \"NEW_SOURCE\", \"ISGRI_FLAG\", \"FLAG\", \"ERR_RAD\"], \"cat_column_descr\": [[\"meta_ID\", \"<i8\"], [\"src_names\", \"<U18\"], [\"significance\", \"<f8\"], [\"ra\", \"<f8\"], [\"dec\", \"<f8\"], [\"NEW_SOURCE\", \"<i8\"], [\"ISGRI_FLAG\", \"<i8\"], [\"FLAG\", \"<i8\"], [\"ERR_RAD\", \"<f8\"]], \"cat_lat_name\": \"dec\", \"cat_lon_name\": \"ra\"}\ninstrument isgri\nproduct_type isgri_spectrum\noff_line (False,)\nquery_status ('new',)\nverbose (False,)\nsession_id CQYQM9B2TEQLIQP0\ndry_run (False,)\napi True\nthe job has been submitted on the remote server\n \\ the job is working remotely, please wait status=done - job_id=3832148009444147886 7886 \n\nquery done succesfully!\n2\n008900250010.001,008900330010.001,008900420010.001,008900430010.001,008900440010.001,008900450010.001,008900460010.001,008900470010.001,008900500010.001,008900510010.001,008900520010.001,008900530010.001,008900540010.001,008900550010.001,008900560010.001,008900570010.001,008900580010.001,008900590010.001,009000010010.001,009000020010.001,009000030010.001,009000040010.001,009000050010.001,009000110010.001,009000120010.001,009000130010.001,020700040010.001,020700050010.001,020700060010.001,020700070010.001,020700110010.001,020700120010.001,020700130010.001,020700140010.001,020700150010.001,020700410010.001,020700420010.001,020700430010.001,020700440010.001,020700450010.001,020700490010.001,020700500010.001,020700510010.001,020700520010.001,020700530010.001,020700540010.001,022600650010.001,026700000110.001,026700020010.001,026700030010.001,026700040010.001\n- waiting for remote response, please wait run_analysis https://www.astro.unige.ch/cdci/astrooda/dispatch-data\nscw_list 008900250010.001,008900330010.001,008900420010.001,008900430010.001,008900440010.001,008900450010.001,008900460010.001,008900470010.001,008900500010.001,008900510010.001,008900520010.001,008900530010.001,008900540010.001,008900550010.001,008900560010.001,008900570010.001,008900580010.001,008900590010.001,009000010010.001,009000020010.001,009000030010.001,009000040010.001,009000050010.001,009000110010.001,009000120010.001,009000130010.001,020700040010.001,020700050010.001,020700060010.001,020700070010.001,020700110010.001,020700120010.001,020700130010.001,020700140010.001,020700150010.001,020700410010.001,020700420010.001,020700430010.001,020700440010.001,020700450010.001,020700490010.001,020700500010.001,020700510010.001,020700520010.001,020700530010.001,020700540010.001,022600650010.001,026700000110.001,026700020010.001,026700030010.001,026700040010.001\nquery_type Real\nosa_version OSA10.2\nRA 194.046527\nDEC -5.789314\nselected_catalog {\"cat_frame\": \"fk5\", \"cat_coord_units\": \"deg\", \"cat_column_list\": [[1, 30, 50, 112, 0], [\"3C 273\", \"IGR J12391-1612\", \"NGC 4593\", \"SWIFT J1238.6+0928\", \"3C 279\"], [12.098819732666016, 4.082015037536621, 13.66150951385498, 4.295688629150391, 0.0], [187.2660675048828, 189.77621459960938, 189.91522216796875, 189.67724609375, 194.046527], [2.045917510986328, -16.179750442504883, -5.358253479003906, 9.474955558776855, -5.789314], [-32768, -32768, -32768, -32768, 0], [2, 2, 2, 1, 2], [0, 0, 0, 0, 0], [0.0002800000074785203, 0.00016999999934341758, 0.0002800000074785203, 0.07566666603088379, 0.0]], \"cat_column_names\": [\"meta_ID\", \"src_names\", \"significance\", \"ra\", \"dec\", \"NEW_SOURCE\", \"ISGRI_FLAG\", \"FLAG\", \"ERR_RAD\"], \"cat_column_descr\": [[\"meta_ID\", \"<i8\"], [\"src_names\", \"<U18\"], [\"significance\", \"<f8\"], [\"ra\", \"<f8\"], [\"dec\", \"<f8\"], [\"NEW_SOURCE\", \"<i8\"], [\"ISGRI_FLAG\", \"<i8\"], [\"FLAG\", \"<i8\"], [\"ERR_RAD\", \"<f8\"]], \"cat_lat_name\": \"dec\", \"cat_lon_name\": \"ra\"}\ninstrument isgri\nproduct_type isgri_spectrum\noff_line (False,)\nquery_status ('new',)\nverbose (False,)\nsession_id 2QP4GBGY4TT5S3SJ\ndry_run (False,)\napi True\n" ], [ "d=spectrum_results[0]\nfor ID,s in enumerate(d._p_list):\n if (s.meta_data['src_name']==source_name):\n if(s.meta_data['product']=='isgri_spectrum'):\n ID_spec=ID\n if(s.meta_data['product']=='isgri_arf'):\n ID_arf=ID\n if(s.meta_data['product']=='isgri_rmf'):\n ID_rmf=ID\n\nprint(ID_spec, ID_arf, ID_rmf)\n ", "3 4 5\n" ], [ "d=spectrum_results[0]\nspec=d._p_list[ID_spec].data_unit[1].data\narf=d._p_list[ID_arf].data_unit[1].data\nrmf=d._p_list[ID_rmf].data_unit[2].data\nch=spec['CHANNEL']\nrate=spec['RATE']*0.\nerr=spec['STAT_ERR']*0.\nsyst=spec['SYS_ERR']*0.\nrate.fill(0)\nerr.fill(0)\nsyst.fill(0)\nqual=spec['QUALITY']\nmatrix=rmf['MATRIX']*0.\nspecresp=arf['SPECRESP']*0.\ntot_expos=0.\ncorr_expos=np.zeros(len(rate))\nprint(len(rate))\nfor k in range(len(scw_lists_osa10)):\n d=spectrum_results[k]\n spec=d._p_list[ID_spec].data_unit[1].data\n arf=d._p_list[ID_arf].data_unit[1].data\n rmf=d._p_list[ID_rmf].data_unit[2].data\n expos=d._p_list[0].data_unit[1].header['EXPOSURE']\n tot_expos=tot_expos+expos\n print(k,expos)\n for j in range(len(rate)):\n if(spec['QUALITY'][j]==0): \n rate[j]=rate[j]+spec['RATE'][j]/(spec['STAT_ERR'][j])**2\n err[j]=err[j]+1./(spec['STAT_ERR'][j])**2\n syst[j]=syst[j]+(spec['SYS_ERR'][j])**2*expos\n corr_expos[j]=corr_expos[j]+expos\n matrix=matrix+rmf['MATRIX']*expos\n specresp=specresp+arf['SPECRESP']*expos\n\nfor i in range(len(rate)):\n if err[i]>0.:\n rate[i]=rate[i]/err[i]\n err[i]=1./sqrt(err[i])\nmatrix=matrix/tot_expos\nspecresp=specresp/tot_expos\nsyst=sqrt(syst/(corr_expos+1.))\nprint('Total exposure:',tot_expos)", "62\n0 115628.4045003584\n1 90360.35488457941\n2 66237.00101908497\n3 28053.87997326724\n4 42416.37498623534\n5 54899.01417923988\n6 72681.13209957794\n7 84306.25795508562\n8 91171.40521538183\n9 67297.86490586787\n10 50185.31346775457\n11 80500.70525250556\n12 44682.28527407059\n13 71992.67794999375\n14 69651.39811800097\n15 61578.40132774157\n16 8651.617763955479\n17 4634.80690293361\n18 2367.31019269395\n19 108753.4897604977\n20 12024.0962724554\n21 10817.12965649085\nTotal exposure: 1238890.9216577725\n" ], [ "print(rate)\nprint(err)", "[ 0.00000000e+00 -1.91108733e-02 -4.74805431e-03 -8.60083848e-03\n 2.89484225e-02 5.46972780e-03 3.97485914e-03 1.83909703e-02\n 1.79907177e-02 1.07161747e-02 1.57599468e-02 1.08829625e-02\n 7.29459012e-03 1.40787875e-02 2.61543579e-02 1.29586281e-02\n 1.04378965e-02 1.47986431e-02 3.07247937e-02 2.76438203e-02\n 1.55900978e-02 2.68101525e-02 2.20132917e-02 1.55036217e-02\n 2.15381514e-02 2.07527503e-02 1.58636644e-02 2.47534411e-03\n 1.27718551e-02 4.38565155e-03 2.54256045e-03 1.35317794e-03\n 1.20742992e-02 1.82996262e-02 1.09611489e-02 2.20161825e-02\n 1.40028633e-02 1.48153109e-02 1.11153908e-02 6.20406447e-03\n -3.77116655e-03 7.94668216e-03 4.36933571e-03 -4.14732331e-03\n -2.96756392e-03 6.25281420e-04 3.96637991e-03 3.72313219e-03\n -7.48174358e-03 -7.23820413e-03 -1.32521137e-03 -6.03199405e-05\n 8.40168097e-04 5.49091585e-03 4.69506858e-03 7.58503389e-04\n 3.12829099e-04 -2.72279885e-03 -1.93422602e-03 -9.32901818e-03\n 6.12873537e-03 -2.72820634e-03]\n[0. 0.0695955 0.03435365 0.020544 0.01424723 0.01093074\n 0.00893867 0.00767821 0.00696467 0.00649837 0.00620647 0.00591155\n 0.00568408 0.00543641 0.00699879 0.00603061 0.00526691 0.00482192\n 0.00621557 0.00566362 0.00537316 0.00522471 0.00532552 0.00598756\n 0.00701571 0.00630916 0.00543909 0.00526548 0.00505263 0.00453153\n 0.00410468 0.00426973 0.00431794 0.00425787 0.00484556 0.00446172\n 0.00417033 0.00394553 0.00378355 0.00364721 0.00356687 0.00352672\n 0.0035033 0.00346465 0.0034068 0.00333141 0.00327024 0.00321747\n 0.00441959 0.00424585 0.00403846 0.00384813 0.00368388 0.00355565\n 0.00339815 0.00321211 0.003678 0.00410753 0.00521346 0.005994\n 0.00657711 0.00488587]\n" ], [ "d._p_list[ID_spec].data_unit[1].data['RATE']=rate\nd._p_list[ID_spec].data_unit[1].data['STAT_ERR']=err\nd._p_list[ID_rmf].data_unit[2].data['MATRIX']=matrix\nd._p_list[ID_arf].data_unit[1].data['SPECRESP']=specresp", "_____no_output_____" ], [ "name=source_name.replace(\" \", \"\")\nspecname=name+'_spectrum_osa10.fits'\narfname=name+'_arf_osa10.fits.gz'\nrmfname=name+'_rmf_osa10.fits.gz'\ndata._p_list[ID_spec].write_fits_file(specname)\ndata._p_list[ID_arf].write_fits_file(arfname)\ndata._p_list[ID_rmf].write_fits_file(rmfname)", "WARNING: VerifyWarning: Keyword name 'instrument' is greater than 8 characters or contains characters not allowed by the FITS standard; a HIERARCH card will be created. [astropy.io.fits.card]\nWARNING: VerifyWarning: Keyword name 'osa_version' is greater than 8 characters or contains characters not allowed by the FITS standard; a HIERARCH card will be created. [astropy.io.fits.card]\nWARNING: VerifyWarning: Keyword name 'product_type' is greater than 8 characters or contains characters not allowed by the FITS standard; a HIERARCH card will be created. [astropy.io.fits.card]\nWARNING: VerifyWarning: Keyword name 'query_status' is greater than 8 characters or contains characters not allowed by the FITS standard; a HIERARCH card will be created. [astropy.io.fits.card]\nWARNING: VerifyWarning: Keyword name 'query_type' is greater than 8 characters or contains characters not allowed by the FITS standard; a HIERARCH card will be created. [astropy.io.fits.card]\nWARNING: VerifyWarning: Keyword name 'session_id' is greater than 8 characters or contains characters not allowed by the FITS standard; a HIERARCH card will be created. [astropy.io.fits.card]\n" ], [ "hdul = fits.open(specname, mode='update')\nhdr=hdul[1].header\nhdr.set('EXPOSURE', tot_expos)\nhdul.close()", "_____no_output_____" ], [ "!./spectrum_fit_osa10.sh $name $rebin", "\n\t\tXSPEC version: 12.9.0n\n\tBuild Date/Time: Tue Nov 8 18:03:34 2016\n\nXSPEC12>statistic chi\nDefault fit statistic is set to: Chi-Squared\n This will apply to all current and newly loaded spectra.\nXSPEC12>data 3C279_spectrum_osa10.fits\n***Warning: POISSERR keyword is missing or of wrong format, assuming FALSE.\n\n1 spectrum in use\n \nSpectral Data File: 3C279_spectrum_osa10.fits Spectrum 1\nNet count rate (cts/s) for Spectrum:1 4.900e-01 +/- 9.055e-02\n Assigned to Data Group 1 and Plot Group 1\n Noticed Channels: 1-62\n Telescope: INTEGRAL Instrument: IBIS Channel Type: PI\n Exposure Time: 1.239e+06 sec\n Using fit statistic: chi\n Using test statistic: chi\n No response loaded.\n\n***Warning! One or more spectra are missing responses,\n and are not suitable for fit.\nXSPEC12>response 3C279_rmf_osa10.fits.gz\nWarning: RMF CHANTYPE keyword (PHA) is not consistent with that from spectrum (PI)\nResponse successfully loaded.\nXSPEC12>arf 3C279_arf_osa10.fits.gz\nArf successfully loaded.\nXSPEC12>ignore bad\n\nignore: 6 channels ignored from source number 1\nXSPEC12>ignore 300.-**\n 5 channels (58-62) ignored in spectrum # 1\n\nXSPEC12>model powerlaw\n\nInput parameter value, delta, min, bot, top, and max values for ...\n 1 0.01( 0.01) -3 -2 9 10\n 10erlaw:PhoIndex> 1. 0.01 -3 -2 9 \n 1 0.01( 0.01) 0 0 1e+20 1e+24\n1e+24erlaw:norm> 0.01 0.01 0 0 1e+20 \n\n========================================================================\nModel powerlaw<1> Source No.: 1 Active/On\nModel Model Component Parameter Unit Value\n par comp\n 1 1 powerlaw PhoIndex 1.00000 +/- 0.0 \n 2 1 powerlaw norm 1.00000E-02 +/- 0.0 \n________________________________________________________________________\n\n\nFit statistic : Chi-Squared = 478951.9 using 51 PHA bins.\n\nTest statistic : Chi-Squared = 478951.9 using 51 PHA bins.\n Reduced chi-squared = 9774.529 for 49 degrees of freedom \n Null hypothesis probability = 0.000000e+00\n Current data and model not fit yet.\nXSPEC12>fit 1000\n Parameters\nChi-Squared |beta|/N Lvl 1:PhoIndex 2:norm\n78.824 14.6109 -1 1.03285 0.000248154\n78.7438 10879.1 -2 1.19254 0.000415258\n78.2251 39615.8 -3 1.33887 0.000733991\n71.434 23648.9 -4 1.30796 0.000789235\n71.3746 2376.55 -5 1.31686 0.000805472\n71.3745 11.4964 -6 1.31586 0.000802374\n==============================\n Variances and Principal Axes\n 1 2 \n 1.2961E-02| -1.0000 -0.0032 \n 2.5608E-09| 0.0032 -1.0000 \n------------------------------\n\n========================\n Covariance Matrix\n 1 2 \n 1.296e-02 4.092e-05\n 4.092e-05 1.318e-07\n------------------------\n\n========================================================================\nModel powerlaw<1> Source No.: 1 Active/On\nModel Model Component Parameter Unit Value\n par comp\n 1 1 powerlaw PhoIndex 1.31586 +/- 0.113847 \n 2 1 powerlaw norm 8.02374E-04 +/- 3.62992E-04 \n________________________________________________________________________\n\n\nFit statistic : Chi-Squared = 71.37 using 51 PHA bins.\n\nTest statistic : Chi-Squared = 71.37 using 51 PHA bins.\n Reduced chi-squared = 1.457 for 49 degrees of freedom \n Null hypothesis probability = 2.012080e-02\nXSPEC12>setplot rebin 10 10\nXSPEC12>plot eeufs\nXSPEC12>iplot\nPLT> wdata 3C279_spectrum_osa10.txt\nPLT> XSPEC12>\n XSPEC: quit\n" ], [ "spectrum_results1=[]\nfor i in range(len(scw_lists_osa11)):\n print(i)\n data=disp.get_product(instrument='isgri',\n product='isgri_spectrum',\n scw_list=scw_lists_osa11[i],\n query_type='Real',\n osa_version='OSA11.0',\n RA=ra,\n DEC=dec,\n product_type='Real',\n selected_catalog=api_cat)\n spectrum_results1.append(data)", "0\n169500140010.001,169500150010.001,169500210010.001,169500220010.001,169500230010.001,169500240010.001,169500250010.001,169500260010.001,169500270010.001,169900840010.001,169900850010.001,175400370010.001,176000060010.001,176100050010.001,176200040010.001,176200050010.001,176200450010.001,176300030010.001,176300040010.001,176400060010.001,176400460010.001,176400470010.001,176500360010.001,176500450010.001,176500460010.001,182000220010.001,182000310010.001,182100250010.001,182100340010.001,182200220010.001,182200230010.001,182200240010.001,182200320010.001,182300600010.001,182400030010.001,182400430010.001,182400440010.001,182800300010.001,182800400010.001,183200120010.001,183200130010.001,183200190010.001,183200200010.001,183200210010.001,183200220010.001,183200230010.001,183200240010.001,183200250010.001,183200290010.001,183200300010.001\n- waiting for remote response, please wait run_analysis https://www.astro.unige.ch/cdci/astrooda/dispatch-data\nscw_list 169500140010.001,169500150010.001,169500210010.001,169500220010.001,169500230010.001,169500240010.001,169500250010.001,169500260010.001,169500270010.001,169900840010.001,169900850010.001,175400370010.001,176000060010.001,176100050010.001,176200040010.001,176200050010.001,176200450010.001,176300030010.001,176300040010.001,176400060010.001,176400460010.001,176400470010.001,176500360010.001,176500450010.001,176500460010.001,182000220010.001,182000310010.001,182100250010.001,182100340010.001,182200220010.001,182200230010.001,182200240010.001,182200320010.001,182300600010.001,182400030010.001,182400430010.001,182400440010.001,182800300010.001,182800400010.001,183200120010.001,183200130010.001,183200190010.001,183200200010.001,183200210010.001,183200220010.001,183200230010.001,183200240010.001,183200250010.001,183200290010.001,183200300010.001\nquery_type Real\nosa_version OSA11.0\nRA 194.046527\nDEC -5.789314\nselected_catalog {\"cat_frame\": \"fk5\", \"cat_coord_units\": \"deg\", \"cat_column_list\": [[1, 30, 50, 112, 0], [\"3C 273\", \"IGR J12391-1612\", \"NGC 4593\", \"SWIFT J1238.6+0928\", \"3C 279\"], [12.098819732666016, 4.082015037536621, 13.66150951385498, 4.295688629150391, 0.0], [187.2660675048828, 189.77621459960938, 189.91522216796875, 189.67724609375, 194.046527], [2.045917510986328, -16.179750442504883, -5.358253479003906, 9.474955558776855, -5.789314], [-32768, -32768, -32768, -32768, 0], [2, 2, 2, 1, 2], [0, 0, 0, 0, 0], [0.0002800000074785203, 0.00016999999934341758, 0.0002800000074785203, 0.07566666603088379, 0.0]], \"cat_column_names\": [\"meta_ID\", \"src_names\", \"significance\", \"ra\", \"dec\", \"NEW_SOURCE\", \"ISGRI_FLAG\", \"FLAG\", \"ERR_RAD\"], \"cat_column_descr\": [[\"meta_ID\", \"<i8\"], [\"src_names\", \"<U18\"], [\"significance\", \"<f8\"], [\"ra\", \"<f8\"], [\"dec\", \"<f8\"], [\"NEW_SOURCE\", \"<i8\"], [\"ISGRI_FLAG\", \"<i8\"], [\"FLAG\", \"<i8\"], [\"ERR_RAD\", \"<f8\"]], \"cat_lat_name\": \"dec\", \"cat_lon_name\": \"ra\"}\ninstrument isgri\nproduct_type isgri_spectrum\noff_line (False,)\nquery_status ('new',)\nverbose (False,)\nsession_id FT1WC6B0CVLO15D4\ndry_run (False,)\napi True\nthe job has been submitted on the remote server\n / the job is working remotely, please wait status=done - job_id=-98497454171466425 6425 \n\nquery done succesfully!\n1\n183200310010.001,183200320010.001,183200330010.001,183200340010.001,183200400010.001,183200410010.001,184500030010.001,184500040010.001,184500430010.001,184600020010.001,184600100010.001,184600110010.001,184600120010.001,185000310010.001,189200400010.001,189200410010.001,189200420010.001,189200490010.001,189200500010.001,189300020010.001,189300410010.001,189300420010.001,189400030010.001,189400040010.001,189400050010.001,189400450010.001,189500070010.001,189500480010.001,189600100010.001,189700030010.001,189700040010.001,189700130010.001,189800060010.001,189800070010.001,189800080010.001,189800160010.001,189900080010.001,189900090010.001,189900170010.001,189900180010.001,189900190010.001,190000110010.001,190000120010.001,190000130010.001,190000210010.001,190100130010.001,190100140010.001\n- waiting for remote response, please wait run_analysis https://www.astro.unige.ch/cdci/astrooda/dispatch-data\nscw_list 183200310010.001,183200320010.001,183200330010.001,183200340010.001,183200400010.001,183200410010.001,184500030010.001,184500040010.001,184500430010.001,184600020010.001,184600100010.001,184600110010.001,184600120010.001,185000310010.001,189200400010.001,189200410010.001,189200420010.001,189200490010.001,189200500010.001,189300020010.001,189300410010.001,189300420010.001,189400030010.001,189400040010.001,189400050010.001,189400450010.001,189500070010.001,189500480010.001,189600100010.001,189700030010.001,189700040010.001,189700130010.001,189800060010.001,189800070010.001,189800080010.001,189800160010.001,189900080010.001,189900090010.001,189900170010.001,189900180010.001,189900190010.001,190000110010.001,190000120010.001,190000130010.001,190000210010.001,190100130010.001,190100140010.001\nquery_type Real\nosa_version OSA11.0\nRA 194.046527\nDEC -5.789314\nselected_catalog {\"cat_frame\": \"fk5\", \"cat_coord_units\": \"deg\", \"cat_column_list\": [[1, 30, 50, 112, 0], [\"3C 273\", \"IGR J12391-1612\", \"NGC 4593\", \"SWIFT J1238.6+0928\", \"3C 279\"], [12.098819732666016, 4.082015037536621, 13.66150951385498, 4.295688629150391, 0.0], [187.2660675048828, 189.77621459960938, 189.91522216796875, 189.67724609375, 194.046527], [2.045917510986328, -16.179750442504883, -5.358253479003906, 9.474955558776855, -5.789314], [-32768, -32768, -32768, -32768, 0], [2, 2, 2, 1, 2], [0, 0, 0, 0, 0], [0.0002800000074785203, 0.00016999999934341758, 0.0002800000074785203, 0.07566666603088379, 0.0]], \"cat_column_names\": [\"meta_ID\", \"src_names\", \"significance\", \"ra\", \"dec\", \"NEW_SOURCE\", \"ISGRI_FLAG\", \"FLAG\", \"ERR_RAD\"], \"cat_column_descr\": [[\"meta_ID\", \"<i8\"], [\"src_names\", \"<U18\"], [\"significance\", \"<f8\"], [\"ra\", \"<f8\"], [\"dec\", \"<f8\"], [\"NEW_SOURCE\", \"<i8\"], [\"ISGRI_FLAG\", \"<i8\"], [\"FLAG\", \"<i8\"], [\"ERR_RAD\", \"<f8\"]], \"cat_lat_name\": \"dec\", \"cat_lon_name\": \"ra\"}\ninstrument isgri\nproduct_type isgri_spectrum\noff_line (False,)\nquery_status ('new',)\nverbose (False,)\nsession_id M822KTIZCGI4I5NY\ndry_run (False,)\napi True\nthe job has been submitted on the remote server\n \\ the job is working remotely, please wait status=done - job_id=8843659157675212506 2506 \n\nquery done succesfully!\n" ], [ "d=spectrum_results1[0]\nfor ID,s in enumerate(d._p_list):\n if (s.meta_data['src_name']==source_name):\n if(s.meta_data['product']=='isgri_spectrum'):\n ID_spec=ID\n if(s.meta_data['product']=='isgri_arf'):\n ID_arf=ID\n if(s.meta_data['product']=='isgri_rmf'):\n ID_rmf=ID\n\nprint(ID_spec, ID_arf, ID_rmf)\n\n", "3 4 5\n" ], [ "d=spectrum_results1[0]\nspec=d._p_list[ID_spec].data_unit[1].data\narf=d._p_list[ID_arf].data_unit[1].data\nrmf=d._p_list[ID_rmf].data_unit[2].data\nch=spec['CHANNEL']\nrate=spec['RATE']*0.\nerr=spec['STAT_ERR']*0.\nsyst=spec['SYS_ERR']*0.\nrate.fill(0)\nerr.fill(0)\nsyst.fill(0)\nqual=spec['QUALITY']\nmatrix=rmf['MATRIX']*0.\nspecresp=arf['SPECRESP']*0.\ntot_expos=0.\ncorr_expos=np.zeros(len(rate))\nprint(len(rate))\nfor k in range(len(scw_lists_osa11)):\n d=spectrum_results1[k]\n spec=d._p_list[ID_spec].data_unit[1].data\n arf=d._p_list[ID_arf].data_unit[1].data\n rmf=d._p_list[ID_rmf].data_unit[2].data\n expos=d._p_list[0].data_unit[1].header['EXPOSURE']\n tot_expos=tot_expos+expos\n print(k,expos)\n for j in range(len(rate)):\n if(spec['QUALITY'][j]==0): \n rate[j]=rate[j]+spec['RATE'][j]/(spec['STAT_ERR'][j])**2\n err[j]=err[j]+1./(spec['STAT_ERR'][j])**2\n syst[j]=syst[j]+(spec['SYS_ERR'][j])**2*expos\n corr_expos[j]=corr_expos[j]+expos\n matrix=matrix+rmf['MATRIX']*expos\n specresp=specresp+arf['SPECRESP']*expos\n\nfor i in range(len(rate)):\n if err[i]>0.:\n rate[i]=rate[i]/err[i]\n err[i]=1./sqrt(err[i])\nmatrix=matrix/tot_expos\nspecresp=specresp/tot_expos\nsyst=sqrt(syst/(corr_expos+1.))\nprint('Total exposure:',tot_expos)", "256\n0 26026.8547870585\n1 8087.67341090079\nTotal exposure: 34114.52819795929\n" ], [ "d._p_list[ID_spec].data_unit[1].data['RATE']=rate\nd._p_list[ID_spec].data_unit[1].data['STAT_ERR']=err\nd._p_list[ID_rmf].data_unit[2].data['MATRIX']=matrix\nd._p_list[ID_arf].data_unit[1].data['SPECRESP']=specresp", "_____no_output_____" ], [ "name=source_name.replace(\" \", \"\")\nspecname=name+'_spectrum_osa11.fits'\narfname=name+'_arf_osa11.fits.gz'\nrmfname=name+'_rmf_osa11.fits.gz'\ndata._p_list[ID_spec].write_fits_file(specname)\ndata._p_list[ID_arf].write_fits_file(arfname)\ndata._p_list[ID_rmf].write_fits_file(rmfname)", "_____no_output_____" ], [ "hdul = fits.open(specname, mode='update')\nhdr=hdul[1].header\nhdr.set('EXPOSURE', tot_expos)\nhdul.close()", "_____no_output_____" ], [ "!./spectrum_fit_osa11.sh $name $rebin", "\n\t\tXSPEC version: 12.9.0n\n\tBuild Date/Time: Tue Nov 8 18:03:34 2016\n\nXSPEC12>statistic chi\nDefault fit statistic is set to: Chi-Squared\n This will apply to all current and newly loaded spectra.\nXSPEC12>data 3C279_spectrum_osa11.fits\n***Warning: POISSERR keyword is missing or of wrong format, assuming FALSE.\n\n1 spectrum in use\n \nSpectral Data File: 3C279_spectrum_osa11.fits Spectrum 1\nNet count rate (cts/s) for Spectrum:1 2.216e-01 +/- 1.530e-01\n Assigned to Data Group 1 and Plot Group 1\n Noticed Channels: 1-256\n Telescope: INTEGRAL Instrument: IBIS Channel Type: PI\n Exposure Time: 3.411e+04 sec\n Using fit statistic: chi\n Using test statistic: chi\n No response loaded.\n\n***Warning! One or more spectra are missing responses,\n and are not suitable for fit.\nXSPEC12>response 3C279_rmf_osa11.fits.gz\nResponse successfully loaded.\nXSPEC12>arf 3C279_arf_osa11.fits.gz\nArf successfully loaded.\nXSPEC12>ignore bad\n\nignore: 25 channels ignored from source number 1\nXSPEC12>ignore 300.-**\n 128 channels (129-256) ignored in spectrum # 1\n\nXSPEC12>model powerlaw\n\nInput parameter value, delta, min, bot, top, and max values for ...\n 1 0.01( 0.01) -3 -2 9 10\n 10erlaw:PhoIndex> 1. 0.01 -3 -2 9 \n 1 0.01( 0.01) 0 0 1e+20 1e+24\n1e+24erlaw:norm> 0.01 0.01 0 0 1e+20 \n\n========================================================================\nModel powerlaw<1> Source No.: 1 Active/On\nModel Model Component Parameter Unit Value\n par comp\n 1 1 powerlaw PhoIndex 1.00000 +/- 0.0 \n 2 1 powerlaw norm 1.00000E-02 +/- 0.0 \n________________________________________________________________________\n\n\nFit statistic : Chi-Squared = 26502.26 using 106 PHA bins.\n\nTest statistic : Chi-Squared = 26502.26 using 106 PHA bins.\n Reduced chi-squared = 254.8294 for 104 degrees of freedom \n Null hypothesis probability = 0.000000e+00\n Current data and model not fit yet.\nXSPEC12>fit 1000\n Parameters\nChi-Squared |beta|/N Lvl 1:PhoIndex 2:norm\n116.989 2.33136 -1 1.15343 0.000274912\n115.995 3073.36 -1 1.29865 0.000500267\n114.786 2184.51 -1 1.42512 0.000910125\n113.645 1240.59 -1 1.53466 0.00155192\n112.683 682.875 -1 1.63210 0.00246531\n111.88 389.471 -1 1.72076 0.00370055\n111.194 234.238 -1 1.80254 0.00532162\n110.597 148.006 -1 1.87866 0.00740322\n110.068 97.4112 -1 1.94998 0.0100289\n109.595 66.2761 -1 2.01715 0.0132907\n109.167 46.352 -1 2.08070 0.0172897\n108.778 33.184 -1 2.14105 0.0221363\n108.422 24.2413 -1 2.19855 0.0279507\n108.095 18.0245 -1 2.25349 0.0348639\n107.792 13.6133 -1 2.30611 0.0430177\n107.512 10.4262 -1 2.35663 0.0525655\n107.25 8.08596 -1 2.40524 0.0636732\n107.006 6.34243 -1 2.45208 0.0765190\n106.777 5.02623 -1 2.49730 0.0912946\n106.562 4.02065 -1 2.54103 0.108205\n106.36 3.24393 -1 2.58336 0.127472\n106.168 2.63793 -1 2.62441 0.149328\n105.988 2.16075 -1 2.66424 0.174026\n105.816 1.7818 -1 2.70295 0.201830\n105.654 1.47852 -1 2.74059 0.233026\n105.499 1.23405 -1 2.77725 0.267914\n105.352 1.03572 -1 2.81296 0.306812\n105.211 0.873875 -1 2.84778 0.350058\n105.077 0.741135 -1 2.88176 0.398008\n104.949 0.631792 -1 2.91495 0.451036\n104.826 0.541413 -1 2.94738 0.509540\n104.708 0.466526 -1 2.97909 0.573935\n104.595 0.4044 -1 3.01012 0.644658\n104.487 0.352869 -1 3.04049 0.722168\n104.382 0.310204 -1 3.07023 0.806947\n104.282 0.27501 -1 3.09938 0.899497\n104.185 0.246145 -1 3.12795 1.00035\n104.092 0.222663 -1 3.15597 1.11004\n104.003 0.203756 -1 3.18346 1.22916\n103.916 0.188726 -1 3.21044 1.35830\n103.833 0.176955 -1 3.23693 1.49809\n103.752 0.167894 -1 3.26295 1.64916\n103.674 0.161055 -1 3.28852 1.81219\n103.598 0.156008 -1 3.31364 1.98789\n103.525 0.152384 -1 3.33834 2.17697\n103.455 0.149872 -1 3.36263 2.38019\n103.386 0.148214 -1 3.38652 2.59833\n103.32 0.147201 -1 3.41003 2.83217\n103.255 0.146667 -1 3.43316 3.08257\n103.193 0.146481 -1 3.45593 3.35037\n103.132 0.146543 -1 3.47835 3.63645\n103.073 0.146775 -1 3.50043 3.94173\n103.016 0.147117 -1 3.52218 4.26715\n102.961 0.147525 -1 3.54360 4.61366\n102.907 0.147965 -1 3.56471 4.98227\n102.855 0.148413 -1 3.58551 5.37399\n102.804 0.14885 -1 3.60602 5.78987\n102.754 0.149263 -1 3.62623 6.23097\n102.706 0.149643 -1 3.64617 6.69841\n102.659 0.149983 -1 3.66582 7.19331\n102.613 0.150279 -1 3.68521 7.71681\n102.569 0.15053 -1 3.70434 8.27010\n102.526 0.150732 -1 3.72320 8.85439\n102.484 0.150887 -1 3.74182 9.47090\n102.442 0.150994 -1 3.76019 10.1209\n102.402 0.151054 -1 3.77833 10.8056\n102.363 0.151069 -1 3.79622 11.5265\n102.325 0.151039 -1 3.81389 12.2847\n102.288 0.150966 -1 3.83134 13.0816\n102.252 0.150853 -1 3.84856 13.9187\n102.217 0.150701 -1 3.86557 14.7974\n102.182 0.150511 -1 3.88236 15.7189\n102.149 0.150285 -1 3.89895 16.6849\n102.116 0.150026 -1 3.91534 17.6967\n102.112 0.149735 -2 4.06364 27.0748\n==============================\n Variances and Principal Axes\n 1 2 \n 3.3554E-03| -0.9999 0.0159 \n 5.3526E+03| -0.0159 -0.9999 \n------------------------------\n\n========================\n Covariance Matrix\n 1 2 \n 1.350e+00 8.490e+01\n 8.490e+01 5.351e+03\n------------------------\n\n========================================================================\nModel powerlaw<1> Source No.: 1 Active/On\nModel Model Component Parameter Unit Value\n par comp\n 1 1 powerlaw PhoIndex 4.06364 +/- 1.16199 \n 2 1 powerlaw norm 27.0748 +/- 73.1522 \n________________________________________________________________________\n\n\nFit statistic : Chi-Squared = 102.11 using 106 PHA bins.\n\nTest statistic : Chi-Squared = 102.11 using 106 PHA bins.\n Reduced chi-squared = 0.98185 for 104 degrees of freedom \n Null hypothesis probability = 5.340167e-01\nXSPEC12>setplot rebin 10 10\nXSPEC12>plot eeufs\nXSPEC12>iplot\nPLT> wdata 3C279_spectrum_osa11.txt\nPLT> XSPEC12>\n XSPEC: quit\n" ], [ "data=disp.get_product(instrument='isgri',\n product='isgri_spectrum',\n T1='2015-06-15T15:56:45',\n T2='2015-06-16T06:13:10',\n query_type='Real',\n osa_version='OSA10.2',\n RA=ra,\n DEC=dec,\n detection_threshold=5.0,\n radius=15.,\n product_type='Real',\n selected_catalog=api_cat)", "- waiting for remote response, please wait run_analysis https://www.astro.unige.ch/cdci/astrooda/dispatch-data\nT1 2015-06-15T15:56:45\nT2 2015-06-16T06:13:10\nquery_type Real\nosa_version OSA10.2\nRA 194.046527\nDEC -5.789314\ndetection_threshold 5.0\nradius 15.0\nselected_catalog {\"cat_frame\": \"fk5\", \"cat_coord_units\": \"deg\", \"cat_column_list\": [[1, 30, 50, 112, 0], [\"3C 273\", \"IGR J12391-1612\", \"NGC 4593\", \"SWIFT J1238.6+0928\", \"3C 279\"], [12.098819732666016, 4.082015037536621, 13.66150951385498, 4.295688629150391, 0.0], [187.2660675048828, 189.77621459960938, 189.91522216796875, 189.67724609375, 194.046527], [2.045917510986328, -16.179750442504883, -5.358253479003906, 9.474955558776855, -5.789314], [-32768, -32768, -32768, -32768, 0], [2, 2, 2, 1, 2], [0, 0, 0, 0, 0], [0.0002800000074785203, 0.00016999999934341758, 0.0002800000074785203, 0.07566666603088379, 0.0]], \"cat_column_names\": [\"meta_ID\", \"src_names\", \"significance\", \"ra\", \"dec\", \"NEW_SOURCE\", \"ISGRI_FLAG\", \"FLAG\", \"ERR_RAD\"], \"cat_column_descr\": [[\"meta_ID\", \"<i8\"], [\"src_names\", \"<U18\"], [\"significance\", \"<f8\"], [\"ra\", \"<f8\"], [\"dec\", \"<f8\"], [\"NEW_SOURCE\", \"<i8\"], [\"ISGRI_FLAG\", \"<i8\"], [\"FLAG\", \"<i8\"], [\"ERR_RAD\", \"<f8\"]], \"cat_lat_name\": \"dec\", \"cat_lon_name\": \"ra\"}\ninstrument isgri\nproduct_type isgri_spectrum\noff_line (False,)\nquery_status ('new',)\nverbose (False,)\nsession_id 1SWWY8TILU3Z3XFF\ndry_run (False,)\napi True\nthe job has been submitted on the remote server\n / the job is working remotely, please wait status=done - job_id=6490951792990391550 1550 \n\nquery done succesfully!\n" ], [ "data._p_list[0].write_fits_file(name+'_flare_spectrum_osa10.fits')\ndata._p_list[1].write_fits_file(name+'_flare_arf_osa10.fits.gz')\ndata._p_list[2].write_fits_file(name+'_flare_rmf_osa10.fits.gz')", "WARNING: VerifyWarning: Keyword name 'detection_threshold' is greater than 8 characters or contains characters not allowed by the FITS standard; a HIERARCH card will be created. [astropy.io.fits.card]\n" ], [ "name1=name+'_flare'\n!./spectrum_fit_osa10.sh $name1 $rebin", "\n\t\tXSPEC version: 12.9.0n\n\tBuild Date/Time: Tue Nov 8 18:03:34 2016\n\nXSPEC12>statistic chi\nDefault fit statistic is set to: Chi-Squared\n This will apply to all current and newly loaded spectra.\nXSPEC12>data 3C279_flare_spectrum_osa10.fits\n***Warning: POISSERR keyword is missing or of wrong format, assuming FALSE.\n\n1 spectrum in use\n \nSpectral Data File: 3C279_flare_spectrum_osa10.fits Spectrum 1\nNet count rate (cts/s) for Spectrum:1 nan +/- nan \n Assigned to Data Group 1 and Plot Group 1\n Noticed Channels: 1-62\n Telescope: INTEGRAL Instrument: IBIS Channel Type: PI\n Exposure Time: 2.135e+04 sec\n Using fit statistic: chi\n Using test statistic: chi\n No response loaded.\n\n***Warning! One or more spectra are missing responses,\n and are not suitable for fit.\nXSPEC12>response 3C279_flare_rmf_osa10.fits.gz\nWarning: RMF CHANTYPE keyword (PHA) is not consistent with that from spectrum (PI)\nResponse successfully loaded.\nXSPEC12>arf 3C279_flare_arf_osa10.fits.gz\nArf successfully loaded.\nXSPEC12>ignore bad\n\nignore: 6 channels ignored from source number 1\nXSPEC12>ignore 300.-**\n 5 channels (58-62) ignored in spectrum # 1\n\nXSPEC12>model powerlaw\n\nInput parameter value, delta, min, bot, top, and max values for ...\n 1 0.01( 0.01) -3 -2 9 10\n 10erlaw:PhoIndex> 1. 0.01 -3 -2 9 \n 1 0.01( 0.01) 0 0 1e+20 1e+24\n1e+24erlaw:norm> 0.01 0.01 0 0 1e+20 \n\n========================================================================\nModel powerlaw<1> Source No.: 1 Active/On\nModel Model Component Parameter Unit Value\n par comp\n 1 1 powerlaw PhoIndex 1.00000 +/- 0.0 \n 2 1 powerlaw norm 1.00000E-02 +/- 0.0 \n________________________________________________________________________\n\n\nFit statistic : Chi-Squared = 4756.72 using 51 PHA bins.\n\nTest statistic : Chi-Squared = 4756.72 using 51 PHA bins.\n Reduced chi-squared = 97.0759 for 49 degrees of freedom \n Null hypothesis probability = 0.000000e+00\n Current data and model not fit yet.\nXSPEC12>fit 1000\n Parameters\nChi-Squared |beta|/N Lvl 1:PhoIndex 2:norm\n58.6273 2.30987 -1 0.969381 0.000753270\n58.4088 34.0217 -1 0.942119 0.000673677\n58.2313 65.0327 -1 0.917774 0.000609234\n58.0868 92.3293 -1 0.895974 0.000556413\n57.9688 115.611 -1 0.876407 0.000512643\n57.8721 134.835 -1 0.858807 0.000476020\n57.7928 150.135 -1 0.842945 0.000445108\n57.7722 161.762 -2 0.759106 0.000284730\n57.5045 5503.98 -3 0.671853 0.000201620\n57.4109 4682.93 -4 0.684531 0.000222793\n57.4102 373.728 -5 0.682094 0.000221285\n==============================\n Variances and Principal Axes\n 1 2 \n 7.9836E-02| -1.0000 -0.0010 \n 1.1818E-09| 0.0010 -1.0000 \n------------------------------\n\n========================\n Covariance Matrix\n 1 2 \n 7.984e-02 7.832e-05\n 7.832e-05 7.802e-08\n------------------------\n\n========================================================================\nModel powerlaw<1> Source No.: 1 Active/On\nModel Model Component Parameter Unit Value\n par comp\n 1 1 powerlaw PhoIndex 0.682094 +/- 0.282552 \n 2 1 powerlaw norm 2.21285E-04 +/- 2.79314E-04 \n________________________________________________________________________\n\n\nFit statistic : Chi-Squared = 57.41 using 51 PHA bins.\n\nTest statistic : Chi-Squared = 57.41 using 51 PHA bins.\n Reduced chi-squared = 1.172 for 49 degrees of freedom \n Null hypothesis probability = 1.916593e-01\nXSPEC12>setplot rebin 10 10\nXSPEC12>plot eeufs\nXSPEC12>iplot\nPLT> wdata 3C279_flare_spectrum_osa10.txt\nPLT> XSPEC12>\n XSPEC: quit\n" ], [ "plt.figure(figsize=(10,7))\n\nspectrum=np.genfromtxt(name+'_spectrum_osa10.txt',skip_header=3)\nen=spectrum[:,0]\nen_err=spectrum[:,1]\nfl=spectrum[:,2]\nfl_err=spectrum[:,3]\nmo=spectrum[:,4]\nplt.errorbar(en,fl,xerr=en_err,yerr=fl_err,linestyle='none',linewidth=8,color='black',alpha=0.5)\nplt.plot(en,mo,color='black',linewidth=4)\n\n\nspectrum=np.genfromtxt(name+'_flare_spectrum_osa10.txt',skip_header=3)\nen=spectrum[:,0]\nen_err=spectrum[:,1]\nfl=spectrum[:,2]\nfl_err=spectrum[:,3]\nmo=spectrum[:,4]\nplt.errorbar(en,fl,xerr=en_err,yerr=fl_err,linestyle='none',linewidth=8,color='blue',alpha=0.5)\nplt.plot(en,mo,color='blue',linewidth=4,alpha=0.5)\n\n\nplt.tick_params(axis='both', which='major', labelsize=16)\nplt.xscale('log')\nplt.yscale('log')\nplt.ylim(1.e-3,3.e0)\nplt.xlim(15,350)\nplt.xlabel('$E$, keV',fontsize=16)\nplt.ylabel('$E^2F_E$, keV/(cm$^2$s)',fontsize=16)\nplt.savefig(name+'_spectra.pdf',format='pdf',dpi=100)\n\n\n", "_____no_output_____" ], [ "spectrum_3C279=name+'_spectra.pdf'", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d010d5cc33b41e8e5da0a910ee6a3ea53556f9ba
56,145
ipynb
Jupyter Notebook
agreg/Lambda_Calcul_en_OCaml.ipynb
doc22940/notebooks-2
6a7bdec5ed2195005d64ca1f9eaf6613d68fb8ca
[ "MIT" ]
102
2016-06-25T09:30:00.000Z
2022-03-24T21:02:49.000Z
agreg/Lambda_Calcul_en_OCaml.ipynb
Jimmy-INL/notebooks
ccf5ebc11131f56305c484cfd4556f4bcf63c19b
[ "MIT" ]
34
2016-06-26T12:21:30.000Z
2021-04-06T09:19:49.000Z
agreg/Lambda_Calcul_en_OCaml.ipynb
Jimmy-INL/notebooks
ccf5ebc11131f56305c484cfd4556f4bcf63c19b
[ "MIT" ]
44
2017-05-13T23:54:56.000Z
2021-07-17T15:34:24.000Z
25.636986
3,155
0.459596
[ [ [ "# Table of Contents\n <p><div class=\"lev1 toc-item\"><a href=\"#Lambda-calcul-implémenté-en-OCaml\" data-toc-modified-id=\"Lambda-calcul-implémenté-en-OCaml-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Lambda-calcul implémenté en OCaml</a></div><div class=\"lev2 toc-item\"><a href=\"#Expressions\" data-toc-modified-id=\"Expressions-11\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Expressions</a></div><div class=\"lev2 toc-item\"><a href=\"#But-?\" data-toc-modified-id=\"But-?-12\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>But ?</a></div><div class=\"lev2 toc-item\"><a href=\"#Grammaire\" data-toc-modified-id=\"Grammaire-13\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>Grammaire</a></div><div class=\"lev2 toc-item\"><a href=\"#L'identité\" data-toc-modified-id=\"L'identité-14\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>L'identité</a></div><div class=\"lev2 toc-item\"><a href=\"#Conditionnelles\" data-toc-modified-id=\"Conditionnelles-15\"><span class=\"toc-item-num\">1.5&nbsp;&nbsp;</span>Conditionnelles</a></div><div class=\"lev2 toc-item\"><a href=\"#Nombres\" data-toc-modified-id=\"Nombres-16\"><span class=\"toc-item-num\">1.6&nbsp;&nbsp;</span>Nombres</a></div><div class=\"lev2 toc-item\"><a href=\"#Test-d'inégalité\" data-toc-modified-id=\"Test-d'inégalité-17\"><span class=\"toc-item-num\">1.7&nbsp;&nbsp;</span>Test d'inégalité</a></div><div class=\"lev2 toc-item\"><a href=\"#Successeurs\" data-toc-modified-id=\"Successeurs-18\"><span class=\"toc-item-num\">1.8&nbsp;&nbsp;</span>Successeurs</a></div><div class=\"lev2 toc-item\"><a href=\"#Prédecesseurs\" data-toc-modified-id=\"Prédecesseurs-19\"><span class=\"toc-item-num\">1.9&nbsp;&nbsp;</span>Prédecesseurs</a></div><div class=\"lev2 toc-item\"><a href=\"#Addition\" data-toc-modified-id=\"Addition-110\"><span class=\"toc-item-num\">1.10&nbsp;&nbsp;</span>Addition</a></div><div class=\"lev2 toc-item\"><a href=\"#Multiplication\" data-toc-modified-id=\"Multiplication-111\"><span class=\"toc-item-num\">1.11&nbsp;&nbsp;</span>Multiplication</a></div><div class=\"lev2 toc-item\"><a href=\"#Paires\" data-toc-modified-id=\"Paires-112\"><span class=\"toc-item-num\">1.12&nbsp;&nbsp;</span>Paires</a></div><div class=\"lev2 toc-item\"><a href=\"#Prédécesseurs,-deuxième-essai\" data-toc-modified-id=\"Prédécesseurs,-deuxième-essai-113\"><span class=\"toc-item-num\">1.13&nbsp;&nbsp;</span>Prédécesseurs, deuxième essai</a></div><div class=\"lev2 toc-item\"><a href=\"#Listes\" data-toc-modified-id=\"Listes-114\"><span class=\"toc-item-num\">1.14&nbsp;&nbsp;</span>Listes</a></div><div class=\"lev2 toc-item\"><a href=\"#La-fonction-U\" data-toc-modified-id=\"La-fonction-U-115\"><span class=\"toc-item-num\">1.15&nbsp;&nbsp;</span>La fonction U</a></div><div class=\"lev2 toc-item\"><a href=\"#La-récursion-via-la-fonction-Y\" data-toc-modified-id=\"La-récursion-via-la-fonction-Y-116\"><span class=\"toc-item-num\">1.16&nbsp;&nbsp;</span>La récursion via la fonction Y</a></div><div class=\"lev2 toc-item\"><a href=\"#Conclusion\" data-toc-modified-id=\"Conclusion-117\"><span class=\"toc-item-num\">1.17&nbsp;&nbsp;</span>Conclusion</a></div>", "_____no_output_____" ], [ "# Lambda-calcul implémenté en OCaml\n\nCe notebook est inspiré de [ce post de blog du Professeur Matt Might](http://matt.might.net/articles/python-church-y-combinator/), qui implémente un mini langage de programmation en $\\lambda$-calcul, en Python.\nJe vais faire la même chose en OCaml.\n\n## Expressions\nOn rappelle que les expressions du [Lambda calcul](https://fr.wikipedia.org/wiki/Lambda-calcul), ou $\\lambda$-calcul, sont les suivantes :\n$$ \\begin{cases}\nx, y, z & \\text{(des variables)} \\\\\nu v & \\text{(application de deux termes}\\, u, v\\; \\text{)} \\\\\n\\lambda x. v & \\text{(lambda-function prenant la variable}\\; x \\;\\text{et le terme}\\; v \\;\\text{)}\n\\end{cases} $$\n\n## But ?\nLe but ne va pas être de les représenter comme ça avec des types formels en Caml, mais plutôt d'utiliser les constructions de Caml, respectivement `u(v)` et `fun x -> v` pour l'application et les fonctions anonymes, et encoder des fonctionnalités de plus haut niveau dans ce langage réduit.\n\n## Grammaire\nAvec une grammaire BNF, si `<var>` désigne un nom d'expression valide (on se limitera à des noms en miniscules consistitués des 26 lettres `a,b,..,z`) :\n\n <exp> ::= <var>\n | <exp>(<exp>)\n | fun <var> -> <exp>\n | (<exp>)", "_____no_output_____" ], [ "----\n## L'identité", "_____no_output_____" ] ], [ [ "let identite = fun x -> x ;;", "_____no_output_____" ], [ "let vide = fun x -> x ;;", "_____no_output_____" ] ], [ [ "## Conditionnelles\nLa conditionnelle est `si cond alors valeur_vraie sinon valeur_fausse`.", "_____no_output_____" ] ], [ [ "let si = fun cond valeur_vraie valeur_fausse -> cond valeur_vraie valeur_fausse ;;", "_____no_output_____" ] ], [ [ "C'est très simple, du moment qu'on s'assure que `cond` est soit `vrai` soit `faux` tels que définis par leur comportement :\n\n si vrai e1 e2 == e1\n si faux e1 e2 == e2", "_____no_output_____" ] ], [ [ "let vrai = fun valeur_vraie valeur_fausse -> valeur_vraie ;;\nlet faux = fun valeur_vraie valeur_fausse -> valeur_fausse ;;", "File \"[14]\", line 1, characters 28-41:\nWarning 27: unused variable valeur_fausse.\n" ] ], [ [ "La négation est facile !", "_____no_output_____" ] ], [ [ "let non = fun v x y -> v y x;;", "_____no_output_____" ] ], [ [ "En fait, on va forcer une évaluation paresseuse, comme ça si l'une des deux expressions ne terminent pas, l'évaluation fonctionne quand même.", "_____no_output_____" ] ], [ [ "let vrai_paresseux = fun valeur_vraie valeur_fausse -> valeur_vraie () ;;\nlet faux_paresseux = fun valeur_vraie valeur_fausse -> valeur_fausse () ;;", "File \"[16]\", line 1, characters 38-51:\nWarning 27: unused variable valeur_fausse.\n" ] ], [ [ "Pour rendre paresseux un terme, rien de plus simple !", "_____no_output_____" ] ], [ [ "let paresseux = fun f -> fun () -> f ;;", "_____no_output_____" ] ], [ [ "## Nombres\nLa représentation de Church consiste a écrire $n$ comme $\\lambda f. \\lambda z. f^n z$.", "_____no_output_____" ] ], [ [ "type 'a nombres = ('a -> 'a) -> 'a -> 'a;; (* inutilisé *)\ntype entiers_church = (int -> int) -> int -> int;;", "_____no_output_____" ] ], [ [ "$0$ est trivialement $\\lambda f. \\lambda z. z$ :", "_____no_output_____" ] ], [ [ "let zero = fun (f : ('a -> 'a)) (z : 'a) -> z ;;", "File \"[34]\", line 1, characters 16-17:\nWarning 27: unused variable f.\n" ] ], [ [ "$1$ est $\\lambda f. \\lambda z. f z$ :", "_____no_output_____" ] ], [ [ "let un = fun (f : ('a -> 'a)) -> f ;;", "_____no_output_____" ] ], [ [ "Avec l'opérateur de composition, l'écriture des entiers suivants est facile.", "_____no_output_____" ] ], [ [ "let compose = fun f g x -> f (g x);;", "_____no_output_____" ], [ "let deux = fun f -> compose f f;; (* == compose f (un f) *)\nlet trois = fun f -> compose f (deux f) ;;\nlet quatre = fun f -> compose f (trois f) ;;\n(* etc *)", "_____no_output_____" ] ], [ [ "On peut généraliser ça, avec une fonction qui transforme un entier (`int`) de Caml en un entier de Church :", "_____no_output_____" ] ], [ [ "let rec entierChurch (n : int) =\n fun f z -> if n = 0 then z else f ((entierChurch (n-1)) f z)\n;;", "_____no_output_____" ] ], [ [ "Par exemple :", "_____no_output_____" ] ], [ [ "(entierChurch 0) (fun x -> x + 1) 0;; (* 0 *)\n(entierChurch 7) (fun x -> x + 1) 0;; (* 7 *)\n(entierChurch 3) (fun x -> 2*x) 1;; (* 8 *)", "_____no_output_____" ] ], [ [ "Et une fonction qui fait l'inverse (note : cette fonction n'est *pas* un $\\lambda$-terme) :", "_____no_output_____" ] ], [ [ "let entierNatif c : int =\n c (fun x -> x + 1) 0\n;;", "_____no_output_____" ] ], [ [ "Un petit test :", "_____no_output_____" ] ], [ [ "entierNatif (si vrai zero un);; (* 0 *)\nentierNatif (si faux zero un);; (* 1 *)", "_____no_output_____" ], [ "entierNatif (entierChurch 100);; (* 100 *)", "_____no_output_____" ] ], [ [ "## Test d'inégalité\nOn a besoin de pouvoir tester si $n \\leq 0$ (ou $n = 0$) en fait.", "_____no_output_____" ] ], [ [ "(* prend un lambda f lambda z. ... est donne vrai ssi n = 0 ou faux sinon *)\nlet estnul = fun n -> n (fun z -> faux) (vrai);;", "File \"[43]\", line 2, characters 29-30:\nWarning 27: unused variable z.\n" ], [ "(* prend un lambda f lambda z. ... est donne vrai ssi n > 0 ou faux sinon *)\nlet estnonnul = fun n -> n (fun z -> vrai) (faux);;", "File \"[44]\", line 2, characters 32-33:\nWarning 27: unused variable z.\n" ] ], [ [ "On peut proposer cette autre implémentation, qui \"fonctionne\" pareil (au sens calcul des $\\beta$-réductions) mais est plus compliquée :", "_____no_output_____" ] ], [ [ "let estnonnul2 = fun n -> non (estnul n);;", "_____no_output_____" ], [ "entierNatif (si (estnul zero) zero un);; (* 0 *)\nentierNatif (si (estnul un) zero un);; (* 1 *)\nentierNatif (si (estnul deux) zero un);; (* 1 *)", "_____no_output_____" ], [ "entierNatif (si (estnonnul zero) zero un);; (* 0 *)\nentierNatif (si (estnonnul un) zero un);; (* 1 *)\nentierNatif (si (estnonnul deux) zero un);; (* 1 *)", "_____no_output_____" ], [ "entierNatif (si (non (estnul zero)) zero un);; (* 0 *)\nentierNatif (si (non (estnul un)) zero un);; (* 1 *)\nentierNatif (si (non (estnul deux)) zero un);; (* 1 *)", "_____no_output_____" ] ], [ [ "## Successeurs\nVue la représentation de Churc, $n+1$ consiste a appliquer l'argument $f$ une fois de plus :\n$f^{n+1}(z) = f (f^n(z))$.", "_____no_output_____" ] ], [ [ "let succ = fun n f z -> f ((n f) z) ;;", "_____no_output_____" ], [ "entierNatif (succ un);; (* 2 *)", "_____no_output_____" ], [ "deux;;\nsucc un;;", "_____no_output_____" ] ], [ [ "On remarque qu'ils ont le même typage, mais OCaml indique qu'il a moins d'informations à propos du deuxième : ce `'_a` signifie que le type est *contraint*, il sera fixé dès la première utilisation de cette fonction.\n\nC'est assez mystérieux, mais il faut retenir le point suivant : `deux` était écrit manuellement, donc le système a vu le terme en entier, il le connaît et saît que `deux = fun f -> fun x -> f (f x))`, pas de surprise. Par contre, `succ un` est le résultat d'une évaluation *partielle* et vaut `fun f z -> f ((deux f) z)`. Sauf que le système ne calcule pas tout et laisse l'évaluation partielle ! (heureusement !)", "_____no_output_____" ], [ "Si on appelle `succ un` à une fonction, le `'_a` va être contraint, et on ne pourra pas s'en reservir :", "_____no_output_____" ] ], [ [ "let succ_de_un = succ un;;", "_____no_output_____" ], [ "(succ_de_un) (fun x -> x + 1);;", "_____no_output_____" ], [ "(succ_de_un) (fun x -> x ^ \"0\");;", "_____no_output_____" ], [ "(succ un) (fun x -> x ^ \"0\");;\n(* une valeur fraîchement calculée, sans contrainte *)", "_____no_output_____" ] ], [ [ "## Prédecesseurs\nVue la représentation de Church, $\\lambda n. n-1$ n'existe pas... mais on peut tricher.", "_____no_output_____" ] ], [ [ "let pred = fun n ->\n if (entierNatif n) > 0 then entierChurch ((entierNatif n) - 1)\n else zero\n;;", "_____no_output_____" ], [ "entierNatif (pred deux);; (* 1 *)", "_____no_output_____" ], [ "entierNatif (pred trois);; (* 2 *)", "_____no_output_____" ] ], [ [ "## Addition\n\nPour ajouter $n$ et $m$, il faut appliquer une fonction $f$ $n$ fois puis $m$ fois : $f^{n+m}(z) = f^n(f^m(z))$.", "_____no_output_____" ] ], [ [ "let somme = fun n m f z -> n(f)( m(f)(z));;", "_____no_output_____" ], [ "let cinq = somme deux trois ;;", "_____no_output_____" ], [ "entierNatif cinq;;", "_____no_output_____" ], [ "let sept = somme cinq deux ;;", "_____no_output_____" ], [ "entierNatif sept;;", "_____no_output_____" ] ], [ [ "## Multiplication\n\nPour multiplier $n$ et $m$, il faut appliquer le codage de $n$ exactement $m$ fois : $f^{nm}(z) = (f^n(f^n(...(f^n(z))...))$.", "_____no_output_____" ] ], [ [ "let produit = fun n m f z -> m(n(f))(z);;", "_____no_output_____" ] ], [ [ "On peut faire encore mieux avec l'opérateur de composition :", "_____no_output_____" ] ], [ [ "let produit = fun n m -> compose m n;;", "_____no_output_____" ], [ "let six = produit deux trois ;;", "_____no_output_____" ], [ "entierNatif six;;", "_____no_output_____" ], [ "let huit = produit deux quatre ;;", "_____no_output_____" ], [ "entierNatif huit;;", "_____no_output_____" ] ], [ [ "## Paires\n\nOn va écrire un constructeur de paires, `paire a b` qui sera comme `(a, b)`, et deux destructeurs, `gauche` et `droite`, qui vérifient :\n\n gauche (paire a b) == a\n droite (paire a b) == b", "_____no_output_____" ] ], [ [ "let paire = fun a b -> fun f -> f(a)(b);;", "_____no_output_____" ], [ "let gauche = fun p -> p(fun a b -> a);;\nlet droite = fun p -> p(fun a b -> b);;", "File \"[76]\", line 1, characters 30-31:\nWarning 27: unused variable b.\n" ], [ "entierNatif (gauche (paire zero un));;\nentierNatif (droite (paire zero un));;", "_____no_output_____" ] ], [ [ "## Prédécesseurs, deuxième essai\n\nIl y a une façon, longue et compliquée ([source](http://gregfjohnson.com/pred/)) d'y arriver, avec des paires.", "_____no_output_____" ] ], [ [ "let pred n suivant premier =\n let pred_suivant = paire vrai premier in\n let pred_premier = fun p ->\n si (gauche p)\n (paire faux premier)\n (paire faux (suivant (droite p)))\n in\n let paire_finale = n pred_suivant pred_premier in\n droite paire_finale\n;;", "_____no_output_____" ] ], [ [ "Malheureusement, ce n'est pas bien typé.", "_____no_output_____" ] ], [ [ "entierNatif (pred deux);; (* 1 *)", "_____no_output_____" ] ], [ [ "## Listes\n\nPour construire des listes (simplement chaînées), on a besoin d'une valeur pour la liste vide, `listevide`, d'un constructeur pour une liste `cons`, un prédicat pour la liste vide `estvide`, un accesseur `tete` et `queue`, et avec les contraintes suivantes (avec `vrai`, `faux` définis comme plus haut) :\n\n estvide (listevide) == vrai\n estvide (cons tt qu) == faux\n \n tete (cons tt qu) == tt\n queue (cons tt qu) == qu\n\nOn va stocker tout ça avec des fonctions qui attendront deux arguments (deux fonctions - rappel tout est fonction en $\\lambda$-calcul), l'une appellée si la liste est vide, l'autre si la liste n'est pas vide.", "_____no_output_____" ] ], [ [ "let listevide = fun survide surpasvide -> survide;;", "File \"[58]\", line 1, characters 28-38:\nWarning 27: unused variable surpasvide.\n" ], [ "let cons = fun hd tl -> fun survide surpasvide -> surpasvide hd tl;;", "_____no_output_____" ] ], [ [ "Avec cette construction, `estvide` est assez simple : `survide` est `() -> vrai` et `surpasvide` est `tt qu -> faux`.", "_____no_output_____" ] ], [ [ "let estvide = fun liste -> liste (vrai) (fun tt qu -> faux);;", "File \"[60]\", line 1, characters 45-47:\nWarning 27: unused variable tt.\nFile \"[60]\", line 1, characters 48-50:\nWarning 27: unused variable qu.\n" ] ], [ [ "Deux tests :", "_____no_output_____" ] ], [ [ "entierNatif (si (estvide (listevide)) un zero);; (* estvide listevide == vrai *)\nentierNatif (si (estvide (cons un listevide)) un zero);; (* estvide (cons un listevide) == faux *)", "_____no_output_____" ] ], [ [ "Et pour les deux extracteurs, c'est très facile avec cet encodage.", "_____no_output_____" ] ], [ [ "let tete = fun liste -> liste (vide) (fun tt qu -> tt);;\nlet queue = fun liste -> liste (vide) (fun tt qu -> qu);;", "File \"[62]\", line 1, characters 45-47:\nWarning 27: unused variable qu.\n" ], [ "entierNatif (tete (cons un listevide));;\nentierNatif (tete (queue (cons deux (cons un listevide))));;\nentierNatif (tete (queue (cons trois (cons deux (cons un listevide)))));;", "_____no_output_____" ] ], [ [ "Visualisons les types que Caml trouve a des listes de tailles croissantes :", "_____no_output_____" ] ], [ [ "cons un (cons un listevide);; (* 8 variables pour une liste de taille 2 *)", "_____no_output_____" ], [ "cons un (cons un (cons un (cons un listevide)));; (* 14 variables pour une liste de taille 4 *)", "_____no_output_____" ], [ "cons un (cons un (cons un (cons un (cons un (cons un (cons un (cons un listevide)))))));; (* 26 variables pour une liste de taille 7 *)", "_____no_output_____" ] ], [ [ "Pour ces raisons là, on se rend compte que le type donné par Caml à une liste de taille $k$ croît linéairement *en taille* en fonction de $k$ !\n\nAucun espoir donc (avec cet encodage) d'avoir un type générique pour les listes représentés en Caml.\n\nEt donc nous ne sommes pas surpris de voir cet essai échouer :", "_____no_output_____" ] ], [ [ "let rec longueur liste =\n liste (zero) (fun t q -> succ (longueur q))\n;;", "_____no_output_____" ] ], [ [ "<span style=\"color:red;\">En effet, `longueur` devrait être bien typée et `liste` et `q` devraient avoir le même type, or le type de `liste` est strictement plus grand que celui de `q`...</span>", "_____no_output_____" ], [ "On peut essayer de faire une fonction `ieme`.\nOn veut que `ieme zero liste = tete` et `ieme n liste = ieme (pred n) (queue liste)`.\n\nEn écrivant en haut niveau, on aimerait pouvoir faire :", "_____no_output_____" ] ], [ [ "let pop liste =\n si (estvide liste) (listevide) (queue liste)\n;;", "_____no_output_____" ], [ "let ieme n liste =\n tete (n pop liste)\n;;", "_____no_output_____" ] ], [ [ "## La fonction U\n\nC'est le premier indice que le $\\lambda$-calcul peut être utilisé comme modèle de calcul : le terme $U : f \\to f(f)$ ne termine pas si on l'applique à lui-même.\n\nMais ce sera la faiblesse de l'utilisation de Caml : ce terme ne peut être correctement typé !", "_____no_output_____" ] ], [ [ "let u = fun f -> f (f);;", "_____no_output_____" ] ], [ [ "A noter que même dans un langage non typé (par exemple Python), on peut définir $U$ mais son exécution échouera, soit à caude d'un dépassement de pile, soit parce qu'elle ne termine pas.", "_____no_output_____" ], [ "## La récursion via la fonction Y\n\nLa fonction $Y$ trouve le point fixe d'une autre fonction.\nC'est très utile pour définir des fonctions par récurrence.\n\nPar exemple, la factorielle est le point fixe de la fonction suivante :\n\"$\\lambda f. \\lambda n. 1$ si $n \\leq 0$ sinon $n * f(n-1)$\" (écrite dans un langage plus haut niveau, pas en $\\lambda$-calcul).\n\n$Y$ satisfait ces contraintes : $Y(F) = f$ et $f = F(f)$.\nDonc $Y(F) = F(Y(F))$ et donc $Y = \\lambda F. F(Y(F))$. Mais ce premier essai ne marche pas.", "_____no_output_____" ] ], [ [ "let rec y = fun f -> f (y(f));;", "_____no_output_____" ], [ "let fact = y(fun f n -> si (estnul n) (un) (produit n (f (pred n))));;", "_____no_output_____" ] ], [ [ "On utilise la $\\eta$-expansion : si $e$ termine, $e$ est équivalent (ie tout calcul donne le même terme) à $\\lambda x. e(x)$.", "_____no_output_____" ] ], [ [ "let rec y = fun f -> f (fun x -> y(f)(x));;", "_____no_output_____" ] ], [ [ "Par contre, le typage n'arrive toujours pas à trouver que l'expression suivante devrait être bien définie :", "_____no_output_____" ] ], [ [ "let fact = y(fun f n -> si (estnul n) (un) (produit n (f (pred n))));;", "_____no_output_____" ] ], [ [ "## Conclusion\n\nJe n'ai pas réussi à traduire intégralement la prouesse initiale, écrite en Python, par Matt Might.\nDommage, le typage de Caml est trop strict pour cet exercice.", "_____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" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d010db0a48c83070c9bf80fd7700598d983c6dff
9,943
ipynb
Jupyter Notebook
notebook/seaborn_heatmap.ipynb
puyopop/python-snippets
9d70aa3b2a867dd22f5a5e6178a5c0c5081add73
[ "MIT" ]
174
2018-05-30T21:14:50.000Z
2022-03-25T07:59:37.000Z
notebook/seaborn_heatmap.ipynb
puyopop/python-snippets
9d70aa3b2a867dd22f5a5e6178a5c0c5081add73
[ "MIT" ]
5
2019-08-10T03:22:02.000Z
2021-07-12T20:31:17.000Z
notebook/seaborn_heatmap.ipynb
puyopop/python-snippets
9d70aa3b2a867dd22f5a5e6178a5c0c5081add73
[ "MIT" ]
53
2018-04-27T05:26:35.000Z
2022-03-25T07:59:37.000Z
22.963048
97
0.505079
[ [ [ "# %matplotlib inline", "_____no_output_____" ], [ "import seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "list_2d = [[0, 1, 2], [3, 4, 5]]", "_____no_output_____" ], [ "plt.figure()\nsns.heatmap(list_2d)\nplt.savefig('data/dst/seaborn_heatmap_list.png')\nplt.close('all')", "_____no_output_____" ], [ "arr_2d = np.arange(-8, 8).reshape((4, 4))\nprint(arr_2d)", "[[-8 -7 -6 -5]\n [-4 -3 -2 -1]\n [ 0 1 2 3]\n [ 4 5 6 7]]\n" ], [ "plt.figure()\nsns.heatmap(arr_2d)\nplt.savefig('data/dst/seaborn_heatmap_ndarray.png')", "_____no_output_____" ], [ "df = pd.DataFrame(data=arr_2d, index=['a', 'b', 'c', 'd'], columns=['A', 'B', 'C', 'D'])\nprint(df)", " A B C D\na -8 -7 -6 -5\nb -4 -3 -2 -1\nc 0 1 2 3\nd 4 5 6 7\n" ], [ "plt.figure()\nsns.heatmap(df)\nplt.savefig('data/dst/seaborn_heatmap_dataframe.png')", "_____no_output_____" ], [ "print(type(sns.heatmap(list_2d)))", "<class 'matplotlib.axes._subplots.AxesSubplot'>\n" ], [ "fig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nsns.heatmap(list_2d, ax=ax)\nfig.savefig('data/dst/seaborn_heatmap_list.png')", "_____no_output_____" ], [ "fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(8, 6))\nsns.heatmap(list_2d, ax=axes[0, 0])\nsns.heatmap(arr_2d, ax=axes[1, 2])\nfig.savefig('data/dst/seaborn_heatmap_list_sub.png')", "_____no_output_____" ], [ "plt.figure()\nsns.heatmap(df, annot=True)\nplt.savefig('data/dst/seaborn_heatmap_annot.png')", "_____no_output_____" ], [ "plt.figure()\nsns.heatmap(df, cbar=False)\nplt.savefig('data/dst/seaborn_heatmap_no_cbar.png')", "_____no_output_____" ], [ "plt.figure()\nsns.heatmap(df, square=True)\nplt.savefig('data/dst/seaborn_heatmap_square.png')", "_____no_output_____" ], [ "plt.figure()\nsns.heatmap(df, vmax=10, vmin=-10, center=0)\nplt.savefig('data/dst/seaborn_heatmap_vmax_vmin_center.png')", "_____no_output_____" ], [ "plt.figure()\nsns.heatmap(df, cmap='hot')\nplt.savefig('data/dst/seaborn_heatmap_hot.png')", "_____no_output_____" ], [ "plt.figure()\nsns.heatmap(df, cmap='Blues')\nplt.savefig('data/dst/seaborn_heatmap_blues.png')", "_____no_output_____" ], [ "plt.figure()\nsns.heatmap(df, cmap='Blues_r')\nplt.savefig('data/dst/seaborn_heatmap_blues_r.png')", "_____no_output_____" ], [ "current_figsize = mpl.rcParams['figure.figsize']\nprint(current_figsize)", "[6.0, 4.0]\n" ], [ "plt.figure(figsize=(9, 6)) \nsns.heatmap(df, square=True)\nplt.savefig('data/dst/seaborn_heatmap_big.png')", "_____no_output_____" ], [ "current_dpi = mpl.rcParams['figure.dpi']\nprint(current_dpi)", "72.0\n" ], [ "plt.figure()\nsns.heatmap(df, square=True)\nplt.savefig('data/dst/seaborn_heatmap_big_2.png', dpi=current_dpi * 1.5)", "_____no_output_____" ], [ "df_house = pd.read_csv('data/src/house_prices_train.csv', index_col=0)", "_____no_output_____" ], [ "df_house_corr = df_house.corr()\nprint(df_house_corr.shape)", "(37, 37)\n" ], [ "print(df_house_corr.head())", " MSSubClass LotFrontage LotArea OverallQual OverallCond \\\nMSSubClass 1.000000 -0.386347 -0.139781 0.032628 -0.059316 \nLotFrontage -0.386347 1.000000 0.426095 0.251646 -0.059213 \nLotArea -0.139781 0.426095 1.000000 0.105806 -0.005636 \nOverallQual 0.032628 0.251646 0.105806 1.000000 -0.091932 \nOverallCond -0.059316 -0.059213 -0.005636 -0.091932 1.000000 \n\n YearBuilt YearRemodAdd MasVnrArea BsmtFinSF1 BsmtFinSF2 \\\nMSSubClass 0.027850 0.040581 0.022936 -0.069836 -0.065649 \nLotFrontage 0.123349 0.088866 0.193458 0.233633 0.049900 \nLotArea 0.014228 0.013788 0.104160 0.214103 0.111170 \nOverallQual 0.572323 0.550684 0.411876 0.239666 -0.059119 \nOverallCond -0.375983 0.073741 -0.128101 -0.046231 0.040229 \n\n ... WoodDeckSF OpenPorchSF EnclosedPorch 3SsnPorch \\\nMSSubClass ... -0.012579 -0.006100 -0.012037 -0.043825 \nLotFrontage ... 0.088521 0.151972 0.010700 0.070029 \nLotArea ... 0.171698 0.084774 -0.018340 0.020423 \nOverallQual ... 0.238923 0.308819 -0.113937 0.030371 \nOverallCond ... -0.003334 -0.032589 0.070356 0.025504 \n\n ScreenPorch PoolArea MiscVal MoSold YrSold SalePrice \nMSSubClass -0.026030 0.008283 -0.007683 -0.013585 -0.021407 -0.084284 \nLotFrontage 0.041383 0.206167 0.003368 0.011200 0.007450 0.351799 \nLotArea 0.043160 0.077672 0.038068 0.001205 -0.014261 0.263843 \nOverallQual 0.064886 0.065166 -0.031406 0.070815 -0.027347 0.790982 \nOverallCond 0.054811 -0.001985 0.068777 -0.003511 0.043950 -0.077856 \n\n[5 rows x 37 columns]\n" ], [ "plt.figure(figsize=(12, 9)) \nsns.heatmap(df_house_corr, square=True, vmax=1, vmin=-1, center=0)\nplt.savefig('data/dst/seaborn_heatmap_house_price.png')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d010db4605df3cc52b2d0a4c87e9606881fc1dc1
188,543
ipynb
Jupyter Notebook
week8/Dimensionality Reduction and Clustering.ipynb
yixinouyang/dso-560-nlp-and-text-analytics
f1a322b6d4c9058880dcde5d623ebceaa164e7b4
[ "MIT" ]
16
2020-03-10T16:42:05.000Z
2021-11-19T08:07:17.000Z
week8/Dimensionality Reduction and Clustering.ipynb
yixinouyang/dso-560-nlp-and-text-analytics
f1a322b6d4c9058880dcde5d623ebceaa164e7b4
[ "MIT" ]
null
null
null
week8/Dimensionality Reduction and Clustering.ipynb
yixinouyang/dso-560-nlp-and-text-analytics
f1a322b6d4c9058880dcde5d623ebceaa164e7b4
[ "MIT" ]
54
2020-03-10T06:43:24.000Z
2022-03-22T22:20:28.000Z
162.817789
39,908
0.867144
[ [ [ "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Dimensionality-Reduction\" data-toc-modified-id=\"Dimensionality-Reduction-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Dimensionality Reduction</a></span><ul class=\"toc-item\"><li><span><a href=\"#The-Problem\" data-toc-modified-id=\"The-Problem-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>The Problem</a></span><ul class=\"toc-item\"><li><span><a href=\"#Multi-Collinearity\" data-toc-modified-id=\"Multi-Collinearity-1.1.1\"><span class=\"toc-item-num\">1.1.1&nbsp;&nbsp;</span>Multi-Collinearity</a></span></li></ul></li><li><span><a href=\"#Sparsity\" data-toc-modified-id=\"Sparsity-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Sparsity</a></span></li></ul></li><li><span><a href=\"#Principle-Component-Analysis\" data-toc-modified-id=\"Principle-Component-Analysis-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Principle Component Analysis</a></span><ul class=\"toc-item\"><li><span><a href=\"#Important-Points:\" data-toc-modified-id=\"Important-Points:-2.1\"><span class=\"toc-item-num\">2.1&nbsp;&nbsp;</span>Important Points:</a></span></li></ul></li><li><span><a href=\"#Singular-Value-Decomposition\" data-toc-modified-id=\"Singular-Value-Decomposition-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Singular Value Decomposition</a></span><ul class=\"toc-item\"><li><span><a href=\"#Measuring-the-Quality-of-the-Reconstruction\" data-toc-modified-id=\"Measuring-the-Quality-of-the-Reconstruction-3.1\"><span class=\"toc-item-num\">3.1&nbsp;&nbsp;</span>Measuring the Quality of the Reconstruction</a></span></li><li><span><a href=\"#Heuristic-Step-for-How-Many-Dimensions-to-Keep\" data-toc-modified-id=\"Heuristic-Step-for-How-Many-Dimensions-to-Keep-3.2\"><span class=\"toc-item-num\">3.2&nbsp;&nbsp;</span>Heuristic Step for How Many Dimensions to Keep</a></span></li></ul></li><li><span><a href=\"#GLOVE\" data-toc-modified-id=\"GLOVE-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>GLOVE</a></span><ul class=\"toc-item\"><li><span><a href=\"#Using-Spacy-word2vec-embeddings\" data-toc-modified-id=\"Using-Spacy-word2vec-embeddings-4.1\"><span class=\"toc-item-num\">4.1&nbsp;&nbsp;</span>Using Spacy word2vec embeddings</a></span></li><li><span><a href=\"#Using-Glove\" data-toc-modified-id=\"Using-Glove-4.2\"><span class=\"toc-item-num\">4.2&nbsp;&nbsp;</span>Using Glove</a></span></li></ul></li><li><span><a href=\"#Clustering-Text\" data-toc-modified-id=\"Clustering-Text-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Clustering Text</a></span></li></ul></div>", "_____no_output_____" ], [ "# Dimensionality Reduction\n\n## The Problem\n\nThere is an interesting tradeoff between model performance and a feature's dimensionality:\n![http://www.visiondummy.com/2014/04/curse-dimensionality-affect-classification/](images/dimensionality_vs_performance.png)\n\n>*If the amount of available training data is fixed, then overfitting occurs if we keep adding dimensions. On the other hand, if we keep adding dimensions, the amount of **training data needs to grow exponentially fast to maintain the same coverage** and to avoid overfitting* ([Computer Vision for Dummies](http://www.visiondummy.com/2014/04/curse-dimensionality-affect-classification/)).\n\n![http://www.visiondummy.com/2014/04/curse-dimensionality-affect-classification/](images/curseofdimensionality.png)\n\n### Multi-Collinearity\n\nIn many cases, there is a high degree of correlation between many of the features in a dataset. This multi-collinearity has the effect of drowning out the \"signal\" of your dataset in many cases, and amplifies \"outlier\" noise.\n\n\n## Sparsity\n\n- High dimensionality increases the sparsity of your features (**what NLP techniques have we used that illustrate this point?**)\n- The density of the training samples decreases when dimensionality increases:\n- **Distance measures (Euclidean, for instance) start losing their effectiveness**, because there isn't much difference between the max and min distances in higher dimensions.\n- Many models that rely upon **assumptions of Gaussian distributions** (like OLS linear regression), Gaussian mixture models, Gaussian processes, etc. become less and less effective since their distributions become flatter and \"fatter tailed\".\n![http://www.visiondummy.com/2014/04/curse-dimensionality-affect-classification/](images/distance-asymptote.png)\n\nWhat is the amount of data needed to maintain **20% coverage** of the feature space? For 1 dimension, it is **20% of the entire population's dataset**. For a dimensionality of $D$:\n\n$$\nX^{D} = .20\n$$\n$$\n(X^{D})^{\\frac{1}{D}} = .20^{\\frac{1}{D}}\n$$\n$$\nX = \\sqrt[D]{.20}\n$$\nYou can approximate this as \n```python\ndef coverage_requirement(requirement, D):\n return requirement ** (1 / D)\n\nx = []\ny = []\nfor d in range(1,20):\n y.append(coverage_requirement(0.10, d))\n x.append(d)\n \nimport matplotlib.pyplot as plt\n\nplt.plot(x,y)\nplt.xlabel(\"Number of Dimensions\")\nplt.ylabel(\"Appromximate % of Population Dataset\")\nplt.title(\"% of Dataset Needed to Maintain 10% Coverage of Feature Space\")\nplt.show()\n```\n<img src=\"images/coverage-needed.png\" width=\"500\">", "_____no_output_____" ] ], [ [ "import pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nreviews = pd.read_csv(\"mcdonalds-yelp-negative-reviews.csv\", encoding='latin-1')\nreviews = open(\"poor_amazon_toy_reviews.txt\", encoding='latin-1')\n\n#text = reviews[\"review\"].values\ntext = reviews.readlines()\n\nvectorizer = CountVectorizer(ngram_range=(3,3), min_df=0.01, max_df=0.75, max_features=200)\n# tokenize and build vocab\nvectorizer.fit(text)\nvector = vectorizer.transform(text)\nfeatures = vector.toarray()\nfeatures_df = pd.DataFrame(features, columns=vectorizer.get_feature_names())\n\ncorrelations = features_df.corr()\ncorrelations_stacked = correlations.stack().reset_index()\n#set column names\ncorrelations_stacked.columns = ['Tri-Gram 1','Tri-Gram 2','Correlation']\ncorrelations_stacked = correlations_stacked[correlations_stacked[\"Correlation\"] < 1]\ncorrelations_stacked = correlations_stacked.sort_values(by=['Correlation'], ascending=False)\ncorrelations_stacked.head()", "_____no_output_____" ], [ "import numpy as np\nimport matplotlib.pyplot as plt\n# visualize the correlations (install seaborn first)!\nimport seaborn as sns\n\n# Generate a mask for the upper triangle\nmask = np.triu(np.ones_like(correlations, dtype=np.bool))\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(11, 9))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(correlations, mask=mask, cmap=cmap, vmax=.3, center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\n\n", "_____no_output_____" ] ], [ [ "# Principle Component Analysis\n\nIf you have an original matrix $Z$, you can decompose this matrix into two smaller matrices $X$ and $Q$. \n\n## Important Points:\n\n- Multiplying a vector by a matrix typically changes the direction of the vector. For instance:\n<figure>\n <img src=\"images/multvector.png\" alt=\"my alt text\"/>\n <figcaption><a href=\"https://lazyprogrammer.me/tutorial-principal-components-analysis-pca\">Lazy Programmer- \n Tutorial to PCA</a></figcaption>\n</figure>", "_____no_output_____" ], [ "However, there are eigenvalues λ and eigenvectors $v$ such that\n\n$$\n\\sum_{X}v = \\lambda v\n$$\n\nMultiplying the eigenvectors $v$ with the eigenvalue $\\lambda$ does not change the direction of the eigenvector.\n\nMultiplying the eigenvector $v$ by the covariance matrix $\\sum_{X}$ also does not change the direction of the eigenvector.\n\nIf our data $X$ is of shape $N \\times D$, it turns out that we have $D$ eigenvalues and $D$ eigenvectors. This means we can arrange the eigenvalues $\\lambda$ in decreasing order so that\n\n$$\n\\lambda_3 > \\lambda_2 > \\lambda_5\n$$\n\nIn this case, $\\lambda_3$ is the largest eigenvalue, followed by $\\lambda_2$, and then $\\lambda_5$. Then, we can arrange \n\nWe can also rearrange the eigenvectors the same: $v_3$ will be the first column, $v_2$ will be the second column, and $v_5$ will be the third column.\n\nWe'll end up with two matrices $V$ and $\\Lambda$:\n<figure>\n <img src=\"images/pca1.png\" alt=\"my alt text\"/>\n <figcaption><a href=\"https://lazyprogrammer.me/tutorial-principal-components-analysis-pca\">Lazy Programmer- \n Tutorial to PCA</a></figcaption>\n</figure>", "_____no_output_____" ] ], [ [ "# what is the shape of our features?\nfeatures.shape", "_____no_output_____" ], [ "from sklearn.decomposition import PCA\npca = PCA(n_components=4)\nZ = pca.fit_transform(features)\n\n# what is the shape of Z?\nZ.shape", "_____no_output_____" ], [ "# what will happen if we take the correlation matrix and covariance matrix of our new reduced features?\nimport numpy as np\ncovariances = pd.DataFrame(np.cov(Z.transpose()))\nplt.rcParams[\"figure.figsize\"] = (5,5)\nsns.heatmap(covariances)", "_____no_output_____" ], [ "# train the model to reduce the dimensions down to 2\npca = PCA(n_components=2)\nZ_two_dimensions = pca.fit_transform(features)\nZ_two_dimensions", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\nplt.scatter(Z_two_dimensions[:,0], Z_two_dimensions[:, 1])\nreduced_features_df = pd.DataFrame(Z_two_dimensions, columns=[\"x1\", \"x2\"])\nreduced_features_df[\"text\"] = text", "_____no_output_____" ] ], [ [ "# Singular Value Decomposition\n\nGiven an input matrix $A$, we want to try to represent it instead as three smaller matrices $U$, $\\sum$, and $V$. Instead of **$n$ original terms**, we want to represent each document as **$r$ concepts** (other referred to as **latent dimensions**, or **latent factors**):\n<figure>\n <img src=\"images/svd.png\" alt=\"my alt text\"/>\n <figcaption><i>\n <a href=\"https://www.youtube.com/watch?v=P5mlg91as1c\">Mining of Massive Datasets - Dimensionality Reduction: Singular Value Decomposition</a> by Leskovec, Rajaraman, and Ullman (Stanford University)</i></figcaption>\n</figure>\n\nHere, **$A$ is your matrix of word vectors** - you could use any of the word vectorization techniques we have learned so far, include one-hot encoding, word count, TF-IDF.\n\n- $\\sum$ will be a **diagonal matrix** with values that are positive and sorted in decreasing order. Its value indicate the **variance (information encoded on that new dimension)**- therefore, the higher the value, the stronger that dimension is in capturing data from A, the original features. For our purposes, we can think of the rank of this $\\sum$ matrix as the number of desired dimensions. Instance, if we want to reduce $A$ from shape $1020 x 300$ to $1020 x 10$, we will want to reduce the rank of $\\sum$ from 300 to 10.\n\n- $U^T U = I$ and $V^T V = I$\n\n## Measuring the Quality of the Reconstruction\n\nA popular metric used for measuring the quality of the reconstruction is the [Frobenius Norm](https://en.wikipedia.org/wiki/Matrix_norm#Frobenius_norm). When you explain your methodology for reducing dimensions, usually managers / stakeholders will want to some way to compare multiple dimensionality techniques' ability to quantify its ability to retain information but trim dimensions:\n\n$$\n\\begin{equation}\n||A_{old}-A_{new}||_{F} = \\sqrt{\\sum_{ij}{(A^{old}_{ij}- A^{new}_{ij}}})^2\n\\end{equation}\n$$\n\n## Heuristic Step for How Many Dimensions to Keep\n\n1. Sum the $\\sum$ matrix's diagonal values: \n$$\n\\begin{equation}\n\\sum_{i}^{m}\\sigma_{i}\n\\end{equation}\n$$\n\n2. Define your threshold of \"information\" (variance) $\\alpha$ to keep: usually 80% to 90%. \n\n3. Define your cutoff point $C$: $$\n\\begin{equation}\nC = \\sum_{i}^{m}\\sigma_{i} \\alpha\n\\end{equation}\n$$\n\n4. Beginning with your largest singular value, sum your singular values $\\sigma_{i}$ until it is greater than C. Retain only those dimensions.", "_____no_output_____" ], [ "<figure>\n <img src=\"images/userratings.png\" alt=\"my alt text\"/>\n <figcaption><i>\n <a href=\"https://www.youtube.com/watch?v=P5mlg91as1c\">Mining of Massive Datasets - Dimensionality Reduction: Singular Value Decomposition</a> by Leskovec, Rajaraman, and Ullman (Stanford University)</i></figcaption>\n</figure>\n", "_____no_output_____" ] ], [ [ "# create sample data\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.linalg import svd\nx = np.linspace(1,20, 20) # create the first dimension\nx = np.concatenate((x,x))\ny = x + np.random.normal(0,1, 40) # create the second dimension\nz = x + np.random.normal(0,2, 40) # create the third dimension\na = x + np.random.normal(0,4, 40) # create the fourth dimension\nplt.scatter(x,y) # plot just the first two dimensions\nplt.show()", "_____no_output_____" ], [ "# create matrix\nA = np.stack([x,y,z,a]).T", "_____no_output_____" ], [ "# perform SVD\nD = 1\nU, s, V = svd(A)\nprint(f\"s is {s}\\n\")\nprint(f\"U is {U}\\n\")\nprint(f\"V is {V}\")", "_____no_output_____" ], [ "# Frobenius norm\n\ns[D:] = 0\nS = np.zeros((A.shape[0], A.shape[1]))\nS[:A.shape[1], :A.shape[1]] = np.diag(s)\nA_reconstructed = U.dot(S.dot(V))\nnp.sum((A_reconstructed - A) ** 2) ** (1/2) # Frobenius norm\n# reconstruct matrix\nU.dot(S)", "_____no_output_____" ] ], [ [ "# GLOVE\n\nGlobal vectors for word presentation:\n<figure>\n <img src=\"images/glove_1.png\" alt=\"my alt text\"/>\n <figcaption><i>\n <a href=\"https://nlp.stanford.edu/pubs/glove.pdf\">GloVe: Global Vectors for Word Representation</a></i></figcaption>\n</figure>", "_____no_output_____" ] ], [ [ "!pip3 install gensim", "Collecting gensim\n Downloading gensim-3.8.2.tar.gz (23.4 MB)\n\u001b[K |████████████████████████████████| 23.4 MB 187 kB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: numpy>=1.11.3 in /usr/local/lib/python3.8/site-packages (from gensim) (1.18.2)\nRequirement already satisfied: scipy>=1.0.0 in /usr/local/lib/python3.8/site-packages (from gensim) (1.4.1)\nRequirement already satisfied: six>=1.5.0 in /usr/local/lib/python3.8/site-packages (from gensim) (1.14.0)\nCollecting smart_open>=1.8.1\n Downloading smart_open-1.11.1.tar.gz (105 kB)\n\u001b[K |████████████████████████████████| 105 kB 264 kB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.8/site-packages (from smart_open>=1.8.1->gensim) (2.23.0)\nCollecting boto\n Downloading boto-2.49.0-py2.py3-none-any.whl (1.4 MB)\n\u001b[K |████████████████████████████████| 1.4 MB 205 kB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: boto3 in /usr/local/lib/python3.8/site-packages (from smart_open>=1.8.1->gensim) (1.12.39)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.8/site-packages (from requests->smart_open>=1.8.1->gensim) (2020.4.5.1)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.8/site-packages (from requests->smart_open>=1.8.1->gensim) (2.9)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.8/site-packages (from requests->smart_open>=1.8.1->gensim) (3.0.4)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.8/site-packages (from requests->smart_open>=1.8.1->gensim) (1.25.8)\nRequirement already satisfied: botocore<1.16.0,>=1.15.39 in /usr/local/lib/python3.8/site-packages (from boto3->smart_open>=1.8.1->gensim) (1.15.39)\nRequirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.8/site-packages (from boto3->smart_open>=1.8.1->gensim) (0.3.3)\nRequirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.8/site-packages (from boto3->smart_open>=1.8.1->gensim) (0.9.5)\nRequirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.8/site-packages (from botocore<1.16.0,>=1.15.39->boto3->smart_open>=1.8.1->gensim) (2.8.1)\nRequirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.8/site-packages (from botocore<1.16.0,>=1.15.39->boto3->smart_open>=1.8.1->gensim) (0.15.2)\nBuilding wheels for collected packages: gensim, smart-open\n Building wheel for gensim (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for gensim: filename=gensim-3.8.2-cp38-cp38-macosx_10_14_x86_64.whl size=24208273 sha256=6bd62ae0639fb3236fa9f41540baf674913434b2bcb4124b691f9bdd7a76b93e\n Stored in directory: /Users/yuchen/Library/Caches/pip/wheels/91/fa/af/b14a7e3943121f028c82af23946002f99ba18853de2381b148\n Building wheel for smart-open (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for smart-open: filename=smart_open-1.11.1-py3-none-any.whl size=95255 sha256=a104018d08730ff5b1f115c5e2cbf0c58a0becb891a33e3e3bb9f4060fac5705\n Stored in directory: /Users/yuchen/Library/Caches/pip/wheels/90/f7/ab/7b855402a7d4bf9dececf03bb7f8c831dabad2551487b675bc\nSuccessfully built gensim smart-open\nInstalling collected packages: boto, smart-open, gensim\nSuccessfully installed boto-2.49.0 gensim-3.8.2 smart-open-1.11.1\n" ], [ "# import glove embeddings into a word2vec format that is consumable by Gensim\nfrom gensim.scripts.glove2word2vec import glove2word2vec\nglove_input_file = 'glove.6B.100d.txt'\nword2vec_output_file = 'glove.6B.100d.txt.word2vec'\nglove2word2vec(glove_input_file, word2vec_output_file)", "_____no_output_____" ], [ "from gensim.models import KeyedVectors\n# load the Stanford GloVe model\nfilename = 'glove.6B.100d.txt.word2vec'\nmodel = KeyedVectors.load_word2vec_format(filename, binary=False)\n# calculate: (king - man) + woman = ?\nresult = model.most_similar(positive=['woman', 'king'], negative=['man'], topn=1)\nprint(result)", "[('queen', 0.7698541283607483)]\n" ], [ "words = [\"woman\", \"king\", \"man\", \"queen\", \"puppy\", \"kitten\", \"cat\", \n \"quarterback\", \"football\", \"stadium\", \"touchdown\",\n \"dog\", \"government\", \"tax\", \"federal\", \"judicial\", \"elections\",\n \"avocado\", \"tomato\", \"pear\", \"championship\", \"playoffs\"]\n\nvectors = [model.wv[word] for word in words]\n\nimport pandas as pd\nvector_df = pd.DataFrame(vectors)\nvector_df[\"word\"] = words\nvector_df.head()", "_____no_output_____" ] ], [ [ "## Using Spacy word2vec embeddings", "_____no_output_____" ] ], [ [ "import en_core_web_md\nimport spacy\nfrom scipy.spatial.distance import cosine\nnlp = en_core_web_md.load()", "_____no_output_____" ], [ "words = [\"woman\", \"king\", \"man\", \"queen\", \"puppy\", \"kitten\", \"cat\", \n \"quarterback\", \"football\", \"stadium\", \"touchdown\",\n \"dog\", \"government\", \"tax\", \"federal\", \"judicial\", \"elections\",\n \"avocado\", \"tomato\", \"pear\", \"championship\", \"playoffs\"]\n", "_____no_output_____" ], [ "tokens = nlp(\" \".join(words))\nword2vec_vectors = [token.vector for token in tokens]", "_____no_output_____" ], [ "np.array(word2vec_vectors).shape", "_____no_output_____" ], [ "%matplotlib inline\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import TruncatedSVD\nimport matplotlib.pyplot as plt\nimport matplotlib\ndimension_model = PCA(n_components=2)\nreduced_vectors = dimension_model.fit_transform(word2vec_vectors)", "_____no_output_____" ], [ "reduced_vectors.shape", "_____no_output_____" ], [ "matplotlib.rc('figure', figsize=(10, 10))\nfor i, vector in enumerate(reduced_vectors):\n x = vector[0]\n y = vector[1]\n plt.plot(x,y, 'bo')\n plt.text(x * (1 + 0.01), y * (1 + 0.01) , words[i], fontsize=12)", "_____no_output_____" ] ], [ [ "## Using Glove", "_____no_output_____" ] ], [ [ "%matplotlib inline\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import TruncatedSVD\nimport matplotlib.pyplot as plt\n\ndimension_model = PCA(n_components=2)\nreduced_vectors = dimension_model.fit_transform(vectors)\n\nfor i, vector in enumerate(reduced_vectors):\n x = vector[0]\n y = vector[1]\n plt.plot(x,y, 'bo')\n plt.text(x * (1 + 0.01), y * (1 + 0.01) , words[i], fontsize=12)\n\n", "_____no_output_____" ] ], [ [ "# Clustering Text", "_____no_output_____" ] ], [ [ "from sklearn.cluster import KMeans\n\nkmeans = KMeans(n_clusters=4)\ncluster_assignments = kmeans.fit_predict(reduced_vectors)\nfor cluster_assignment, word in zip(cluster_assignments, words):\n print(f\"{word} assigned to cluster {cluster_assignment}\")\n", "woman assigned to cluster 1\nking assigned to cluster 1\nman assigned to cluster 1\nqueen assigned to cluster 1\npuppy assigned to cluster 3\nkitten assigned to cluster 3\ncat assigned to cluster 3\nquarterback assigned to cluster 2\nfootball assigned to cluster 2\nstadium assigned to cluster 2\ntouchdown assigned to cluster 2\ndog assigned to cluster 3\ngovernment assigned to cluster 0\ntax assigned to cluster 0\nfederal assigned to cluster 0\njudicial assigned to cluster 0\nelections assigned to cluster 0\navocado assigned to cluster 3\ntomato assigned to cluster 3\npear assigned to cluster 3\nchampionship assigned to cluster 2\nplayoffs assigned to cluster 2\n" ], [ "color_map = {\n 0: \"r\",\n 1: \"b\",\n 2: \"g\",\n 3: \"y\"\n}\n\nplt.rcParams[\"figure.figsize\"] = (10,10)\n\nfor i, vector in enumerate(reduced_vectors):\n x = vector[0]\n y = vector[1]\n plt.plot(x,y, 'bo', c=color_map[cluster_assignments[i]])\n plt.text(x * (1 + 0.01), y * (1 + 0.01) , words[i], fontsize=12)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d0110876301904dc94bd2cfeb8d9ef5a1196953a
14,425
ipynb
Jupyter Notebook
08_OSK.ipynb
seokyeongheo/slow_statistics
f8eb8f043420f247e197e0abfe39b5cc2d418a3a
[ "MIT" ]
1
2021-01-31T12:09:45.000Z
2021-01-31T12:09:45.000Z
.ipynb_checkpoints/08_OSK-checkpoint.ipynb
seokyeongheo/slow_statistics
f8eb8f043420f247e197e0abfe39b5cc2d418a3a
[ "MIT" ]
null
null
null
.ipynb_checkpoints/08_OSK-checkpoint.ipynb
seokyeongheo/slow_statistics
f8eb8f043420f247e197e0abfe39b5cc2d418a3a
[ "MIT" ]
null
null
null
32.41573
542
0.564783
[ [ [ "## 용어 정의", "_____no_output_____" ] ], [ [ "#가설설정\n# A hypothesis test is a statistical method that uses sample data to evaluate a hypothesis about a population.\n\n1. First, we state a hypothesis about a population. Usually the hypothesis concerns the value of a population parameter. \n2. Before we select a sample, we use the hypothesis to predict the characteristics that the sample should have. \n3. Next, we obtain a random sample from the population. \n4. Finally, we compare the obtained sample data with the prediction that was made from the hypothesis.\n\n## 가설설정 프로세스\n1. State the hypothesis. null hypothesis(H0) \n\n귀무가설 : 독립변수가 종속변수에 어떤 영향을 미치지 않는다는 것 => 레스토랑의 웨이터가 레드 셔츠 입는 것이 팁에 영향이 없다.\nThe null hypothesis (H0) states that in the general population \nthere is no change, no difference, or no relationship.\nIn the context of an experiment, \nH0 predicts that the independent variable (treatment) \nhas no effect on the dependent variable (scores) for the population.\n\nm = 15.8\n\n대안가설 : 어떤 변인이 종속 변수에 효과가 있다는 것 => 레스토랑의 웨이터가 레드 셔츠 입는 것 팁에 영향이 있다. \nThe alternative hypothesis (H1) states that there is a change, a difference, \nor a relationship for the general population. \nIn the context of an experiment,\nH1 predicts that the independent variable (treatment) does have an effect on the dependent variable.\n \nm != 15.8 이다.\n\n이 실험에서는 \nm > 15.8\n\ndirectional hypothisis test\n\n2. set the criteria for a decision\n\na. Sample means that are likely to be obtained if H0 is true; \nthat is, sample means that are close to the null hypothesis\n\nb. Sample means that are very unlikely to be obtained if H0 is true;\nthat is, sample means that are very different from the null hypothesis\n\n\nThe Alpha Level\n\nalpha levels are α = .05 (5%), α = .01 (1%), and α = .001 (0.1%).\n\nThe alpha level, or the level of significance, \nis a probability value that is used to define the concept of \n“very unlikely” in a hypothesis test.\n\nThe critical region is composed of the extreme sample values that are very unlikely (as defined by the alpha level) to be obtained if the null hypothesis is true. The boundaries for the critical region are determined by the alpha level. \nIf sample data fall in the critical region, the null hypothesis is rejected.\n\n\n3. Collect data and compute sample statistics.\n\nz = sample mean - hypothesized population mean / standard error between M and m\n\n4. Make a decision\n\n1. Thesampledataarelocatedinthecriticalregion.\nBydefinition,asamplevaluein the critical region is very unlikely to occur if the null hypothesis is true. \n\n2. The sample data are not in the critical region. \nIn this case, the sample mean is reasonably close to the population mean specified in the null hypothesis (in the center of the distribution).", "_____no_output_____" ] ], [ [ "# Problems", "_____no_output_____" ] ], [ [ "1. Identify the four steps of a hypothesis test as presented in this chapter.\n\n1)State the hypothesis.\n귀무가설과 대안가설 언급\n\n2)alpha level 설정, 신뢰 구간 설정\n\n3) Collect data and compute sample statistics. \n데이터 수집과 샘플 통계적 계산\n\n4)make decision\n결론 결정\n", "_____no_output_____" ], [ "2. Define the alpha level and the critical region for a hypothesis test.\n독립변수와 종속변수에 대한 귀무가설을 reject하기 위해 그 통계치를 통상적인 수치를 벗어나 의미있는 수가 나온 것을 설정해준다. ", "_____no_output_____" ], [ "3. Define a Type I error and a Type II error and explain the consequences of each.\n가설검증에서 실제효과가 없는데 효과가 있는 것으로 나온것, 실제 효과가 있는데, 없는 것으로 나온것. 가설 설정에 문제", "_____no_output_____" ], [ "4. If the alpha level is changed from α = .05 to α = .01,\na. What happens to the boundaries for the critical\nregion?\n신뢰구간이 줄어든다.\nb. What happens to the probability of a Type I error?\n에러 확률은 낮아진다. ", "_____no_output_____" ], [ "6. Although there is a popular belief that herbal remedies such as Ginkgo biloba and Ginseng may improve learning and memory in healthy adults, these effects are usually not supported by well- controlled research (Persson, Bringlov, Nilsson, and Nyberg, 2004). In a typical study, a researcher\nobtains a sample of n = 16 participants and has each person take the herbal supplements every day for\n90 days. At the end of the 90 days, each person takes a standardized memory test. For the general popula- tion, scores from the test form a normal distribution with a mean of μ = 50 and a standard deviation of\nσ = 12. The sample of research participants had an average of M = 54.\na. Assuming a two-tailed test, state the null hypoth-\nesis in a sentence that includes the two variables\nbeing examined.\nb. Using the standard 4-step procedure, conduct a\ntwo-tailed hypothesis test with α = .05 to evaluate the effect of the supplements.\n\n\n", "_____no_output_____" ], [ "from scipy import stats\n\nsample_number = 16 # 샘플수 \npopulation_mean = 50 # 모집단의 평균\nstandard_deviation = 12 # 표준편차\nsample_mean = 54 # 샘플의 평균\n\n\nresult = stats.ttest_1samp(sample_mean, 50) # 비교집단, 관측치\n\nresult", "_____no_output_____" ], [ "sample_mean - population_mean", "_____no_output_____" ], [ "## Import \nimport numpy as np\nfrom scipy import stats\n\n\nsample_number = 16 # 샘플수 \npopulation_mean = 50 # 모집단의 평균\nstandard_deviation = 12 # 표준편차\nsample_mean = 54 # 샘플의 평균\n\n\n## 신뢰구간을 벗어나는지 아닌지 확인 함수 \n\nalpha_level05 = 1.96\nalpha_level01 = 2.58\n\ndef h_test(sample_mean, population_mean, standard_deviation, sample_number, alpha_level):\n \n \n result = (sample_mean - population_mean)/ (standard_deviation/np.sqrt(sample_number))\n \n \n if result> alpha_level or result< - alpha_level:\n print(\"a = .05 신뢰구간에서 귀무가설 reject되고, 가설이 ok\")\n\n else:\n print(\"귀무가설이 reject 되지 않아 가설이 기각됩니다.\")\n\n return result\n\n\n##Compute Cohen’s d\ndef Cohen(sample_mean, population_mean, standard_deviation):\n result = (sample_mean - population_mean) / (standard_deviation)\n \n \n if result<=0.2:\n print(\"small effect\")\n\n elif result<= 0.5:\n print(\"medium effect\")\n\n elif result<= 0.8:\n print(\"Large effect\")\n \n return result\n\n ", "_____no_output_____" ], [ "## 신뢰구간을 벗어나는지 아닌지 확인 함수 \nh_test(sample_mean, population_mean, standard_deviation, sample_number, alpha_level05)\n\n \n", "귀무가설이 reject 되지 않아 가설이 기각됩니다.\n" ], [ "Cohen(sample_mean, population_mean, standard_deviation)", "medium effect\n" ], [ "함수를 활용해서, 신뢰구간과 cohen's d를 구할 수 있다. \n", "_____no_output_____" ], [ "# ## Import the packages\n# import numpy as np\n# from scipy import stats\n\n\n# ## 함수로 만들기\n\n# #Sample Size\n# sample_number = 16 \n# population_mean = 50 # 모집단의 평균\n# standard_deviation = 12 # 표준편차\n# sample_mean = [54,54,58,53,52] # 샘플의 평균\n\n# def h_test(sample_mean, population_mean, standard_deviation, sample_number):\n \n# #For unbiased max likelihood estimate we have to divide the var by N-1, and therefore the parameter ddof = 1\n# var_sample_mean = sample_mean.var(ddof=1)\n# var_population_mean = population_mean.var(ddof=1)\n \n# #std deviation\n# std_deviation = np.sqrt((var_sample_mean + var_population_mean)/2)\n \n# ## Calculate the t-statistics\n# t = (a.mean() - b.mean())/(s*np.sqrt(2/N))\n \n# ## Define 2 random distributions\n\n# N = 10\n# #Gaussian distributed data with mean = 2 and var = 1\n# a = np.random.randn(N) + 2\n# #Gaussian distributed data with with mean = 0 and var = 1\n# b = np.random.randn(N)\n\n\n# ## Calculate the Standard Deviation\n# #Calculate the variance to get the standard deviation\n\n# #For unbiased max likelihood estimate we have to divide the var by N-1, and therefore the parameter ddof = 1\n# var_a = a.var(ddof=1)\n# var_b = b.var(ddof=1)\n\n# #std deviation\n# s = np.sqrt((var_a + var_b)/2)\n# s\n\n\n\n# ## Calculate the t-statistics\n# t = (a.mean() - b.mean())/(s*np.sqrt(2/N))\n\n\n\n# ## Compare with the critical t-value\n# #Degrees of freedom\n# df = 2*N - 2\n\n# #p-value after comparison with the t \n# p = 1 - stats.t.cdf(t,df=df)\n\n\n# print(\"t = \" + str(t))\n# print(\"p = \" + str(2*p))\n# ### You can see that after comparing the t statistic with the critical t value (computed internally) we get a good p value of 0.0005 and thus we reject the null hypothesis and thus it proves that the mean of the two distributions are different and statistically significant.\n\n\n# ## Cross Checking with the internal scipy function\n# t2, p2 = stats.ttest_ind(a,b)\n# print(\"t = \" + str(t2))\n# print(\"p = \" + str(p2))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01108dac7b72da5bd0e421abbfaf5cd547d8ce2
100,351
ipynb
Jupyter Notebook
qiskit/circuit_basics.ipynb
jonhealy1/learning-quantum
b0a1bf109450f5b0dcca5c6f81228e6dcfd62ca5
[ "MIT" ]
null
null
null
qiskit/circuit_basics.ipynb
jonhealy1/learning-quantum
b0a1bf109450f5b0dcca5c6f81228e6dcfd62ca5
[ "MIT" ]
null
null
null
qiskit/circuit_basics.ipynb
jonhealy1/learning-quantum
b0a1bf109450f5b0dcca5c6f81228e6dcfd62ca5
[ "MIT" ]
null
null
null
197.541339
44,456
0.901027
[ [ [ "Source: https://qiskit.org/documentation/tutorials/circuits/01_circuit_basics.html", "_____no_output_____" ], [ "## Circuit Basics", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom qiskit import QuantumCircuit\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "Create a Quantum Circuit acting on a quantum register of three qubits", "_____no_output_____" ] ], [ [ "circ = QuantumCircuit(3)", "_____no_output_____" ] ], [ [ "After you create the circuit with its registers, you can add gates (“operations”) to manipulate the registers. As you proceed through the tutorials you will find more gates and circuits; below is an example of a quantum circuit that makes a three-qubit GHZ state\n\n|𝜓⟩=(|000⟩+|111⟩)/2‾√\n\nTo create such a state, we start with a three-qubit quantum register. By default, each qubit in the register is initialized to |0⟩. To make the GHZ state, we apply the following gates: - A Hadamard gate 𝐻 on qubit 0, which puts it into the superposition state (|0⟩+|1⟩)/2‾√. - A controlled-Not operation (𝐶𝑋) between qubit 0 and qubit 1. - A controlled-Not operation between qubit 0 and qubit 2.\n\nOn an ideal quantum computer, the state produced by running this circuit would be the GHZ state above.", "_____no_output_____" ] ], [ [ "# Add a H gate on qubit 0, putting this qubit in superposition.\ncirc.h(0)\n# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting\n# the qubits in a Bell state.\ncirc.cx(0, 1)\n# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting\n# the qubits in a GHZ state.\ncirc.cx(0, 2)", "_____no_output_____" ] ], [ [ "Visualize circuit", "_____no_output_____" ] ], [ [ "circ.draw('mpl')", "_____no_output_____" ] ], [ [ "Simulating Circuits", "_____no_output_____" ], [ "To simulate a circuit we use the quant-info module in Qiskit. This simulator returns the quantum state, which is a complex vector of dimensions 2𝑛, where 𝑛 is the number of qubits (so be careful using this as it will quickly get too large to run on your machine).\n\nThere are two stages to the simulator. The fist is to set the input state and the second to evolve the state by the quantum circuit.", "_____no_output_____" ] ], [ [ "from qiskit.quantum_info import Statevector\n\n# Set the intial state of the simulator to the ground state using from_int\nstate = Statevector.from_int(0, 2**3)\n\n# Evolve the state by the quantum circuit\nstate = state.evolve(circ)\n\n#draw using latex\nstate.draw('latex')", "_____no_output_____" ] ], [ [ "Visualization\n\nBelow, we use the visualization function to plot the qsphere and a hinton representing the real and imaginary components of the state density matrix 𝜌.", "_____no_output_____" ] ], [ [ "state.draw('qsphere')", "/usr/local/lib/python3.9/site-packages/qiskit/visualization/state_visualization.py:705: MatplotlibDeprecationWarning: \nThe M attribute was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use self.axes.M instead.\n xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n" ], [ "state.draw('hinton')", "_____no_output_____" ] ], [ [ "Unitary representation of a circuit\n\nQiskit’s quant_info module also has an operator method which can be used to make a unitary operator for the circuit. This calculates the 2𝑛×2𝑛 matrix representing the quantum circuit.", "_____no_output_____" ] ], [ [ "from qiskit.quantum_info import Operator\n\nU = Operator(circ)\n\n# Show the results\nU.data", "_____no_output_____" ] ], [ [ "OpenQASM backend\n\nThe simulators above are useful because they provide information about the state output by the ideal circuit and the matrix representation of the circuit. However, a real experiment terminates by measuring each qubit (usually in the computational |0⟩,|1⟩ basis). Without measurement, we cannot gain information about the state. Measurements cause the quantum system to collapse into classical bits.\n\nFor example, suppose we make independent measurements on each qubit of the three-qubit GHZ state\n\n|𝜓⟩=(|000⟩+|111⟩)/2‾√,\n\nand let 𝑥𝑦𝑧 denote the bitstring that results. Recall that, under the qubit labeling used by Qiskit, 𝑥 would correspond to the outcome on qubit 2, 𝑦 to the outcome on qubit 1, and 𝑧 to the outcome on qubit 0.\n\nNote: This representation of the bitstring puts the most significant bit (MSB) on the left, and the least significant bit (LSB) on the right. This is the standard ordering of binary bitstrings. We order the qubits in the same way (qubit representing the MSB has index 0), which is why Qiskit uses a non-standard tensor product order.\n\nRecall the probability of obtaining outcome 𝑥𝑦𝑧 is given by\n\nPr(𝑥𝑦𝑧)=|⟨𝑥𝑦𝑧|𝜓⟩|2\n\nand as such for the GHZ state probability of obtaining 000 or 111 are both 1/2.\n\nTo simulate a circuit that includes measurement, we need to add measurements to the original circuit above, and use a different Aer backend.", "_____no_output_____" ] ], [ [ "# Create a Quantum Circuit\nmeas = QuantumCircuit(3, 3)\nmeas.barrier(range(3))\n# map the quantum measurement to the classical bits\nmeas.measure(range(3), range(3))\n\n# The Qiskit circuit object supports composition.\n# Here the meas has to be first and front=True (putting it before)\n# as compose must put a smaller circuit into a larger one.\nqc = meas.compose(circ, range(3), front=True)\n\n#drawing the circuit\nqc.draw('mpl')", "_____no_output_____" ] ], [ [ "This circuit adds a classical register, and three measurements that are used to map the outcome of qubits to the classical bits.\n\nTo simulate this circuit, we use the qasm_simulator in Qiskit Aer. Each run of this circuit will yield either the bitstring 000 or 111. To build up statistics about the distribution of the bitstrings (to, e.g., estimate Pr(000)), we need to repeat the circuit many times. The number of times the circuit is repeated can be specified in the execute function, via the shots keyword.", "_____no_output_____" ] ], [ [ "# Adding the transpiler to reduce the circuit to QASM instructions\n# supported by the backend\nfrom qiskit import transpile\n\n# Use Aer's qasm_simulator\nfrom qiskit.providers.aer import QasmSimulator\n\nbackend = QasmSimulator()\n\n# First we have to transpile the quantum circuit\n# to the low-level QASM instructions used by the\n# backend\nqc_compiled = transpile(qc, backend)\n\n# Execute the circuit on the qasm simulator.\n# We've set the number of repeats of the circuit\n# to be 1024, which is the default.\njob_sim = backend.run(qc_compiled, shots=1024)\n\n# Grab the results from the job.\nresult_sim = job_sim.result()", "_____no_output_____" ] ], [ [ "\nOnce you have a result object, you can access the counts via the function get_counts(circuit). This gives you the aggregated binary outcomes of the circuit you submitted.", "_____no_output_____" ] ], [ [ "counts = result_sim.get_counts(qc_compiled)\nprint(counts)", "{'000': 503, '111': 521}\n" ] ], [ [ "Approximately 50 percent of the time, the output bitstring is 000. Qiskit also provides a function plot_histogram, which allows you to view the outcomes.", "_____no_output_____" ] ], [ [ "from qiskit.visualization import plot_histogram\nplot_histogram(counts)", "_____no_output_____" ] ], [ [ "The estimated outcome probabilities Pr(000) and Pr(111) are computed by taking the aggregate counts and dividing by the number of shots (times the circuit was repeated). Try changing the shots keyword in the execute function and see how the estimated probabilities change.", "_____no_output_____" ] ], [ [ "import qiskit.tools.jupyter\n%qiskit_version_table\n%qiskit_copyright", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0110c3c7efbc1b93bb84ca519a4e9288d5aee47
11,559
ipynb
Jupyter Notebook
Linear_algebra_Solutions.ipynb
suryasuresh06/cvg1
e49a728e1dd5549e56b3ea93af581b96f861b3bc
[ "MIT" ]
null
null
null
Linear_algebra_Solutions.ipynb
suryasuresh06/cvg1
e49a728e1dd5549e56b3ea93af581b96f861b3bc
[ "MIT" ]
null
null
null
Linear_algebra_Solutions.ipynb
suryasuresh06/cvg1
e49a728e1dd5549e56b3ea93af581b96f861b3bc
[ "MIT" ]
null
null
null
19.137417
112
0.445713
[ [ [ "# Linear algebra", "_____no_output_____" ] ], [ [ "import numpy as np", "_____no_output_____" ], [ "np.__version__", "_____no_output_____" ] ], [ [ "## Matrix and vector products", "_____no_output_____" ], [ "Q1. Predict the results of the following code.", "_____no_output_____" ] ], [ [ "import numpy as np\nx = [1,2]\ny = [[4, 1], [2, 2]]\nprint np.dot(x, y)\nprint np.dot(y, x)\nprint np.matmul(x, y)\nprint np.inner(x, y)\nprint np.inner(y, x)", "[8 5]\n[6 6]\n[8 5]\n[6 6]\n[6 6]\n" ] ], [ [ "Q2. Predict the results of the following code.", "_____no_output_____" ] ], [ [ "x = [[1, 0], [0, 1]]\ny = [[4, 1], [2, 2], [1, 1]]\nprint np.dot(y, x)\nprint np.matmul(y, x)\n", "[[4 1]\n [2 2]\n [1 1]]\n[[4 1]\n [2 2]\n [1 1]]\n" ] ], [ [ "Q3. Predict the results of the following code.", "_____no_output_____" ] ], [ [ "x = np.array([[1, 4], [5, 6]])\ny = np.array([[4, 1], [2, 2]])\nprint np.vdot(x, y)\nprint np.vdot(y, x)\nprint np.dot(x.flatten(), y.flatten())\nprint np.inner(x.flatten(), y.flatten())\nprint (x*y).sum()", "30\n30\n30\n30\n30\n" ] ], [ [ "Q4. Predict the results of the following code.", "_____no_output_____" ] ], [ [ "x = np.array(['a', 'b'], dtype=object)\ny = np.array([1, 2])\nprint np.inner(x, y)\nprint np.inner(y, x)\nprint np.outer(x, y)\nprint np.outer(y, x)", "abb\nabb\n[['a' 'aa']\n ['b' 'bb']]\n[['a' 'b']\n ['aa' 'bb']]\n" ] ], [ [ "## Decompositions", "_____no_output_____" ], [ "Q5. Get the lower-trianglular `L` in the Cholesky decomposition of x and verify it.", "_____no_output_____" ] ], [ [ "x = np.array([[4, 12, -16], [12, 37, -43], [-16, -43, 98]], dtype=np.int32)\nL = np.linalg.cholesky(x)\nprint L\nassert np.array_equal(np.dot(L, L.T.conjugate()), x)", "[[ 2. 0. 0.]\n [ 6. 1. 0.]\n [-8. 5. 3.]]\n" ] ], [ [ "Q6. Compute the qr factorization of x and verify it.", "_____no_output_____" ] ], [ [ "x = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=np.float32)\nq, r = np.linalg.qr(x)\nprint \"q=\\n\", q, \"\\nr=\\n\", r\nassert np.allclose(np.dot(q, r), x)", "q=\n[[-0.85714287 0.39428571 0.33142856]\n [-0.42857143 -0.90285712 -0.03428571]\n [ 0.2857143 -0.17142858 0.94285715]] \nr=\n[[ -14. -21. 14.]\n [ 0. -175. 70.]\n [ 0. 0. -35.]]\n" ] ], [ [ "Q7. Factor x by Singular Value Decomposition and verify it.", "_____no_output_____" ] ], [ [ "x = np.array([[1, 0, 0, 0, 2], [0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0]], dtype=np.float32)\nU, s, V = np.linalg.svd(x, full_matrices=False)\nprint \"U=\\n\", U, \"\\ns=\\n\", s, \"\\nV=\\n\", v\nassert np.allclose(np.dot(U, np.dot(np.diag(s), V)), x)\n", "U=\n[[ 0. 1. 0. 0.]\n [ 1. 0. 0. 0.]\n [ 0. 0. 0. -1.]\n [ 0. 0. 1. 0.]] \ns=\n[ 3. 2.23606801 2. 0. ] \nV=\n[[ 1. 0. 0.]\n [ 0. 1. 0.]\n [ 0. 0. 1.]]\n" ] ], [ [ "## Matrix eigenvalues", "_____no_output_____" ], [ "Q8. Compute the eigenvalues and right eigenvectors of x. (Name them eigenvals and eigenvecs, respectively)", "_____no_output_____" ] ], [ [ "x = np.diag((1, 2, 3))\neigenvals = np.linalg.eig(x)[0]\neigenvals_ = np.linalg.eigvals(x)\nassert np.array_equal(eigenvals, eigenvals_)\nprint \"eigenvalues are\\n\", eigenvals\neigenvecs = np.linalg.eig(x)[1]\nprint \"eigenvectors are\\n\", eigenvecs", "eigenvalues are\n[ 1. 2. 3.]\neigenvectors are\n[[ 1. 0. 0.]\n [ 0. 1. 0.]\n [ 0. 0. 1.]]\n" ] ], [ [ "Q9. Predict the results of the following code.", "_____no_output_____" ] ], [ [ "print np.array_equal(np.dot(x, eigenvecs), eigenvals * eigenvecs)", "True\n" ] ], [ [ "## Norms and other numbers", "_____no_output_____" ], [ "Q10. Calculate the Frobenius norm and the condition number of x.", "_____no_output_____" ] ], [ [ "x = np.arange(1, 10).reshape((3, 3))\nprint np.linalg.norm(x, 'fro')\nprint np.linalg.cond(x, 'fro')", "16.8819430161\n4.56177073661e+17\n" ] ], [ [ "Q11. Calculate the determinant of x.", "_____no_output_____" ] ], [ [ "x = np.arange(1, 5).reshape((2, 2))\nout1 = np.linalg.det(x)\nout2 = x[0, 0] * x[1, 1] - x[0, 1] * x[1, 0]\nassert np.allclose(out1, out2)\nprint out1", "-2.0\n" ] ], [ [ "Q12. Calculate the rank of x.", "_____no_output_____" ] ], [ [ "x = np.eye(4)\nout1 = np.linalg.matrix_rank(x)\nout2 = np.linalg.svd(x)[1].size\nassert out1 == out2\nprint out1\n", "4\n" ] ], [ [ "Q13. Compute the sign and natural logarithm of the determinant of x.", "_____no_output_____" ] ], [ [ "x = np.arange(1, 5).reshape((2, 2))\nsign, logdet = np.linalg.slogdet(x)\ndet = np.linalg.det(x)\nassert sign == np.sign(det)\nassert logdet == np.log(np.abs(det))\nprint sign, logdet\n", "-1.0 0.69314718056\n" ] ], [ [ "Q14. Return the sum along the diagonal of x.", "_____no_output_____" ] ], [ [ "x = np.eye(4)\nout1 = np.trace(x)\nout2 = x.diagonal().sum()\nassert out1 == out2\nprint out1", "4.0\n" ] ], [ [ "## Solving equations and inverting matrices", "_____no_output_____" ], [ "Q15. Compute the inverse of x.", "_____no_output_____" ] ], [ [ "x = np.array([[1., 2.], [3., 4.]])\nout1 = np.linalg.inv(x)\nassert np.allclose(np.dot(x, out1), np.eye(2))\nprint out1\n", "[[-2. 1. ]\n [ 1.5 -0.5]]\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", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
d0110e08bcab3467c28fd8e9975ae83bb6bf56c7
40,369
ipynb
Jupyter Notebook
notebook/DL_nlp_bert_ner/nlp_ner.ipynb
YMJS-Irfan/ModelArts-Lab
ec9053cc8a1a1ada283bb9e5d01427bcbc83c309
[ "Apache-2.0" ]
1
2020-11-04T07:25:51.000Z
2020-11-04T07:25:51.000Z
notebook/DL_nlp_bert_ner/nlp_ner.ipynb
YMJS-Irfan/ModelArts-Lab
ec9053cc8a1a1ada283bb9e5d01427bcbc83c309
[ "Apache-2.0" ]
null
null
null
notebook/DL_nlp_bert_ner/nlp_ner.ipynb
YMJS-Irfan/ModelArts-Lab
ec9053cc8a1a1ada283bb9e5d01427bcbc83c309
[ "Apache-2.0" ]
null
null
null
38.446667
526
0.552602
[ [ [ "# 自然语言处理实战——命名实体识别\n\n### 进入ModelArts\n\n点击如下链接:https://www.huaweicloud.com/product/modelarts.html , 进入ModelArts主页。点击“立即使用”按钮,输入用户名和密码登录,进入ModelArts使用页面。\n\n### 创建ModelArts notebook\n\n下面,我们在ModelArts中创建一个notebook开发环境,ModelArts notebook提供网页版的Python开发环境,可以方便的编写、运行代码,并查看运行结果。\n\n第一步:在ModelArts服务主界面依次点击“开发环境”、“创建”\n\n![create_nb_create_button](./img/create_nb_create_button.png)\n\n第二步:填写notebook所需的参数:\n\n| 参数 | 说明 |\n| - - - - - | - - - - - |\n| 计费方式 | 按需计费 |\n| 名称 | Notebook实例名称 |\n| 工作环境 | Python3 |\n| 资源池 | 选择\"公共资源池\"即可 |\n| 类型 | 选择\"GPU\" |\n| 规格 | 选择\"[限时免费]体验规格GPU版\"|\n| 存储配置 | 选择EVS,磁盘规格5GB |\n\n第三步:配置好notebook参数后,点击下一步,进入notebook信息预览。确认无误后,点击“立即创建”\n\n第四步:创建完成后,返回开发环境主界面,等待Notebook创建完毕后,打开Notebook,进行下一步操作。\n![modelarts_notebook_index](./img/modelarts_notebook_index.png)\n\n### 在ModelArts中创建开发环境\n\n接下来,我们创建一个实际的开发环境,用于后续的实验步骤。\n\n第一步:点击下图所示的“打开”按钮,进入刚刚创建的Notebook\n![inter_dev_env](img/enter_dev_env.png)\n\n第二步:创建一个Python3环境的的Notebook。点击右上角的\"New\",然后创建TensorFlow 1.13.1开发环境。\n\n第三步:点击左上方的文件名\"Untitled\",并输入一个与本实验相关的名称\n\n![notebook_untitled_filename](./img/notebook_untitled_filename.png)\n![notebook_name_the_ipynb](./img/notebook_name_the_ipynb.png)\n\n\n### 在Notebook中编写并执行代码\n\n在Notebook中,我们输入一个简单的打印语句,然后点击上方的运行按钮,可以查看语句执行的结果:\n![run_helloworld](./img/run_helloworld.png)\n\n\n开发环境准备好啦,接下来可以愉快地写代码啦!\n\n\n### 准备源代码和数据\n\n准备案例所需的源代码和数据,相关资源已经保存在 OBS 中,我们通过 ModelArts SDK 将资源下载到本地。", "_____no_output_____" ] ], [ [ "from modelarts.session import Session\nsession = Session()\n\nif session.region_name == 'cn-north-1':\n bucket_path = 'modelarts-labs/notebook/DL_nlp_ner/ner.tar.gz'\n \nelif session.region_name == 'cn-north-4':\n bucket_path = 'modelarts-labs-bj4/notebook/DL_nlp_ner/ner.tar.gz'\nelse:\n print(\"请更换地区到北京一或北京四\")\n \nsession.download_data(bucket_path=bucket_path, path='./ner.tar.gz')\n\n!ls -la ", "Successfully download file modelarts-labs/notebook/DL_nlp_ner/ner.tar.gz from OBS to local ./ner.tar.gz\ntotal 375220\r\ndrwxrwsrwx 4 ma-user ma-group 4096 Sep 6 13:34 .\r\ndrwsrwsr-x 22 ma-user ma-group 4096 Sep 6 13:03 ..\r\ndrwxr-s--- 2 ma-user ma-group 4096 Sep 6 13:33 .ipynb_checkpoints\r\n-rw-r----- 1 ma-user ma-group 45114 Sep 6 13:33 ner.ipynb\r\n-rw-r----- 1 ma-user ma-group 384157325 Sep 6 13:35 ner.tar.gz\r\ndrwx--S--- 2 ma-user ma-group 4096 Sep 6 13:03 .Trash-1000\r\n" ] ], [ [ "解压从obs下载的压缩包,解压后删除压缩包。", "_____no_output_____" ] ], [ [ "# 解压\n!tar xf ./ner.tar.gz\n\n# 删除\n!rm ./ner.tar.gz\n\n!ls -la ", "total 68\r\ndrwxrwsrwx 5 ma-user ma-group 4096 Sep 6 13:35 .\r\ndrwsrwsr-x 22 ma-user ma-group 4096 Sep 6 13:03 ..\r\ndrwxr-s--- 2 ma-user ma-group 4096 Sep 6 13:33 .ipynb_checkpoints\r\ndrwxr-s--- 8 ma-user ma-group 4096 Sep 6 00:24 ner\r\n-rw-r----- 1 ma-user ma-group 45114 Sep 6 13:33 ner.ipynb\r\ndrwx--S--- 2 ma-user ma-group 4096 Sep 6 13:03 .Trash-1000\r\n" ] ], [ [ "#### 导入Python库", "_____no_output_____" ] ], [ [ "import os\nimport json\nimport numpy as np\nimport tensorflow as tf\nimport codecs\nimport pickle\nimport collections\nfrom ner.bert import modeling, optimization, tokenization", "_____no_output_____" ] ], [ [ "#### 定义路径及参数", "_____no_output_____" ] ], [ [ "data_dir = \"./ner/data\" \noutput_dir = \"./ner/output\" \nvocab_file = \"./ner/chinese_L-12_H-768_A-12/vocab.txt\" \ndata_config_path = \"./ner/chinese_L-12_H-768_A-12/bert_config.json\" \ninit_checkpoint = \"./ner/chinese_L-12_H-768_A-12/bert_model.ckpt\" \nmax_seq_length = 128 \nbatch_size = 64 \nnum_train_epochs = 5.0 ", "_____no_output_____" ] ], [ [ "#### 定义processor类获取数据,打印标签", "_____no_output_____" ] ], [ [ "tf.logging.set_verbosity(tf.logging.INFO)\nfrom ner.src.models import InputFeatures, InputExample, DataProcessor, NerProcessor\n\nprocessors = {\"ner\": NerProcessor }\nprocessor = processors[\"ner\"](output_dir)\n\nlabel_list = processor.get_labels()\nprint(\"labels:\", label_list)", "labels: ['O', 'B-PER', 'I-PER', 'B-ORG', 'I-ORG', 'B-LOC', 'I-LOC', 'X', '[CLS]', '[SEP]']\n" ] ], [ [ "以上 labels 分别表示:\n\n- O:非标注实体\n- B-PER:人名首字\n- I-PER:人名非首字\n- B-ORG:组织首字\n- I-ORG:组织名非首字\n- B-LOC:地名首字\n- I-LOC:地名非首字\n- X:未知\n- [CLS]:句首\n- [SEP]:句尾\n\n#### 加载预训练参数", "_____no_output_____" ] ], [ [ "data_config = json.load(codecs.open(data_config_path))\ntrain_examples = processor.get_train_examples(data_dir) \nnum_train_steps = int(len(train_examples) / batch_size * num_train_epochs) \nnum_warmup_steps = int(num_train_steps * 0.1) \ndata_config['num_train_steps'] = num_train_steps\ndata_config['num_warmup_steps'] = num_warmup_steps\ndata_config['num_train_size'] = len(train_examples)\n\nprint(\"显示配置信息:\")\nfor key,value in data_config.items():\n print('{key}:{value}'.format(key = key, value = value))\n\nbert_config = modeling.BertConfig.from_json_file(data_config_path)\ntokenizer = tokenization.FullTokenizer(vocab_file=vocab_file, do_lower_case=True)\n\n#tf.estimator运行参数\nrun_config = tf.estimator.RunConfig(\n model_dir=output_dir,\n save_summary_steps=1000,\n save_checkpoints_steps=1000,\n session_config=tf.ConfigProto(\n log_device_placement=False,\n inter_op_parallelism_threads=0,\n intra_op_parallelism_threads=0,\n allow_soft_placement=True\n )\n)", "显示配置信息:\nattention_probs_dropout_prob:0.1\ndirectionality:bidi\nhidden_act:gelu\nhidden_dropout_prob:0.1\nhidden_size:768\ninitializer_range:0.02\nintermediate_size:3072\nmax_position_embeddings:512\nnum_attention_heads:12\nnum_hidden_layers:12\npooler_fc_size:768\npooler_num_attention_heads:12\npooler_num_fc_layers:3\npooler_size_per_head:128\npooler_type:first_token_transform\ntype_vocab_size:2\nvocab_size:21128\nnum_train_steps:1630\nnum_warmup_steps:163\nnum_train_size:20864\n" ] ], [ [ "#### 读取数据,获取句向量", "_____no_output_____" ] ], [ [ "def convert_single_example(ex_index, example, label_list, max_seq_length, \n tokenizer, output_dir, mode):\n label_map = {}\n for (i, label) in enumerate(label_list, 1):\n label_map[label] = i\n if not os.path.exists(os.path.join(output_dir, 'label2id.pkl')):\n with codecs.open(os.path.join(output_dir, 'label2id.pkl'), 'wb') as w:\n pickle.dump(label_map, w)\n\n textlist = example.text.split(' ')\n labellist = example.label.split(' ')\n tokens = []\n labels = []\n for i, word in enumerate(textlist):\n token = tokenizer.tokenize(word)\n tokens.extend(token)\n label_1 = labellist[i]\n for m in range(len(token)):\n if m == 0:\n labels.append(label_1)\n else: \n labels.append(\"X\")\n if len(tokens) >= max_seq_length - 1:\n tokens = tokens[0:(max_seq_length - 2)]\n labels = labels[0:(max_seq_length - 2)]\n ntokens = []\n segment_ids = []\n label_ids = []\n ntokens.append(\"[CLS]\") # 句子开始设置 [CLS] 标志\n segment_ids.append(0)\n label_ids.append(label_map[\"[CLS]\"]) \n for i, token in enumerate(tokens):\n ntokens.append(token)\n segment_ids.append(0)\n label_ids.append(label_map[labels[i]])\n ntokens.append(\"[SEP]\") # 句尾添加 [SEP] 标志\n segment_ids.append(0)\n label_ids.append(label_map[\"[SEP]\"])\n input_ids = tokenizer.convert_tokens_to_ids(ntokens) \n input_mask = [1] * len(input_ids)\n\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n label_ids.append(0)\n ntokens.append(\"**NULL**\")\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n assert len(label_ids) == max_seq_length\n\n feature = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_ids=label_ids,\n )\n \n return feature\n\ndef filed_based_convert_examples_to_features(\n examples, label_list, max_seq_length, tokenizer, output_file, mode=None):\n writer = tf.python_io.TFRecordWriter(output_file)\n for (ex_index, example) in enumerate(examples):\n if ex_index % 5000 == 0:\n tf.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer, output_dir, mode)\n\n def create_int_feature(values):\n f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))\n return f\n\n features = collections.OrderedDict()\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n features[\"label_ids\"] = create_int_feature(feature.label_ids)\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n writer.write(tf_example.SerializeToString())\n\ntrain_file = os.path.join(output_dir, \"train.tf_record\")\n\n#将训练集中字符转化为features作为训练的输入\nfiled_based_convert_examples_to_features(\n train_examples, label_list, max_seq_length, tokenizer, output_file=train_file)", "INFO:tensorflow:Writing example 0 of 20864\nINFO:tensorflow:Writing example 5000 of 20864\nINFO:tensorflow:Writing example 10000 of 20864\nINFO:tensorflow:Writing example 15000 of 20864\nINFO:tensorflow:Writing example 20000 of 20864\n" ] ], [ [ "#### 引入 BiLSTM+CRF 层,作为下游模型", "_____no_output_____" ] ], [ [ "learning_rate = 5e-5 \ndropout_rate = 1.0 \nlstm_size=1 \ncell='lstm'\nnum_layers=1\n\nfrom ner.src.models import BLSTM_CRF\nfrom tensorflow.contrib.layers.python.layers import initializers\n\ndef create_model(bert_config, is_training, input_ids, input_mask,\n segment_ids, labels, num_labels, use_one_hot_embeddings,\n dropout_rate=dropout_rate, lstm_size=1, cell='lstm', num_layers=1):\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings\n )\n embedding = model.get_sequence_output()\n max_seq_length = embedding.shape[1].value\n used = tf.sign(tf.abs(input_ids))\n lengths = tf.reduce_sum(used, reduction_indices=1) \n blstm_crf = BLSTM_CRF(embedded_chars=embedding, hidden_unit=1, cell_type='lstm', num_layers=1,\n dropout_rate=dropout_rate, initializers=initializers, num_labels=num_labels,\n seq_length=max_seq_length, labels=labels, lengths=lengths, is_training=is_training)\n rst = blstm_crf.add_blstm_crf_layer(crf_only=True)\n return rst\n\ndef model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps,use_one_hot_embeddings=False):\n #构建模型\n def model_fn(features, labels, mode, params):\n tf.logging.info(\"*** Features ***\")\n for name in sorted(features.keys()):\n tf.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))\n input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n label_ids = features[\"label_ids\"]\n\n print('shape of input_ids', input_ids.shape)\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n total_loss, logits, trans, pred_ids = create_model(\n bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,\n num_labels, False, dropout_rate, lstm_size, cell, num_layers)\n\n tvars = tf.trainable_variables()\n\n if init_checkpoint:\n (assignment_map, initialized_variable_names) = \\\n modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n \n output_spec = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n train_op = optimization.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, False)\n hook_dict = {}\n hook_dict['loss'] = total_loss\n hook_dict['global_steps'] = tf.train.get_or_create_global_step()\n logging_hook = tf.train.LoggingTensorHook(\n hook_dict, every_n_iter=100)\n\n output_spec = tf.estimator.EstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n training_hooks=[logging_hook])\n\n elif mode == tf.estimator.ModeKeys.EVAL:\n def metric_fn(label_ids, pred_ids):\n\n return {\n \"eval_loss\": tf.metrics.mean_squared_error(labels=label_ids, predictions=pred_ids), }\n \n eval_metrics = metric_fn(label_ids, pred_ids)\n output_spec = tf.estimator.EstimatorSpec(\n mode=mode,\n loss=total_loss,\n eval_metric_ops=eval_metrics\n )\n else:\n output_spec = tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=pred_ids\n )\n return output_spec\n\n return model_fn\n", "_____no_output_____" ] ], [ [ "#### 创建模型,开始训练", "_____no_output_____" ] ], [ [ "model_fn = model_fn_builder(\n bert_config=bert_config,\n num_labels=len(label_list) + 1,\n init_checkpoint=init_checkpoint,\n learning_rate=learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_one_hot_embeddings=False)\n\ndef file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder):\n name_to_features = {\n \"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"label_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n }\n\n def _decode_record(record, name_to_features):\n example = tf.parse_single_example(record, name_to_features)\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n return example\n\n def input_fn(params):\n params[\"batch_size\"] = 32\n batch_size = params[\"batch_size\"]\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=300)\n d = d.apply(tf.contrib.data.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder\n ))\n return d\n\n return input_fn\n\n#训练输入\ntrain_input_fn = file_based_input_fn_builder(\n input_file=train_file,\n seq_length=max_seq_length,\n is_training=True,\n drop_remainder=True)\n\nnum_train_size = len(train_examples)\n\ntf.logging.info(\"***** Running training *****\")\ntf.logging.info(\" Num examples = %d\", num_train_size)\ntf.logging.info(\" Batch size = %d\", batch_size)\ntf.logging.info(\" Num steps = %d\", num_train_steps)\n\n#模型预测estimator\nestimator = tf.estimator.Estimator(\n model_fn=model_fn,\n config=run_config,\n params={\n 'batch_size':batch_size\n })\n\nestimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n", "INFO:tensorflow:***** Running training *****\nINFO:tensorflow: Num examples = 20864\nINFO:tensorflow: Batch size = 64\nINFO:tensorflow: Num steps = 1630\nINFO:tensorflow:Using config: {'_model_dir': './ner/output', '_tf_random_seed': None, '_save_summary_steps': 1000, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fca68ba6748>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}\nINFO:tensorflow:Calling model_fn.\nINFO:tensorflow:*** Features ***\nINFO:tensorflow: name = input_ids, shape = (32, 128)\nINFO:tensorflow: name = input_mask, shape = (32, 128)\nINFO:tensorflow: name = label_ids, shape = (32, 128)\nINFO:tensorflow: name = segment_ids, shape = (32, 128)\n" ] ], [ [ "#### 在验证集上验证模型", "_____no_output_____" ] ], [ [ "eval_examples = processor.get_dev_examples(data_dir)\neval_file = os.path.join(output_dir, \"eval.tf_record\")\nfiled_based_convert_examples_to_features(\n eval_examples, label_list, max_seq_length, tokenizer, eval_file)\ndata_config['eval.tf_record_path'] = eval_file\ndata_config['num_eval_size'] = len(eval_examples)\nnum_eval_size = data_config.get('num_eval_size', 0)\n\ntf.logging.info(\"***** Running evaluation *****\")\ntf.logging.info(\" Num examples = %d\", num_eval_size)\ntf.logging.info(\" Batch size = %d\", batch_size)\n\neval_steps = None\neval_drop_remainder = False\neval_input_fn = file_based_input_fn_builder(\n input_file=eval_file,\n seq_length=max_seq_length,\n is_training=False,\n drop_remainder=eval_drop_remainder)\n\nresult = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)\noutput_eval_file = os.path.join(output_dir, \"eval_results.txt\")\nwith codecs.open(output_eval_file, \"w\", encoding='utf-8') as writer:\n tf.logging.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n tf.logging.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\nif not os.path.exists(data_config_path):\n with codecs.open(data_config_path, 'a', encoding='utf-8') as fd:\n json.dump(data_config, fd)\n", "INFO:tensorflow:Writing example 0 of 4631\nINFO:tensorflow:***** Running evaluation *****\nINFO:tensorflow: Num examples = 4631\nINFO:tensorflow: Batch size = 64\nINFO:tensorflow:Calling model_fn.\nINFO:tensorflow:*** Features ***\nINFO:tensorflow: name = input_ids, shape = (?, 128)\nINFO:tensorflow: name = input_mask, shape = (?, 128)\nINFO:tensorflow: name = label_ids, shape = (?, 128)\nINFO:tensorflow: name = segment_ids, shape = (?, 128)\n" ] ], [ [ "#### 在测试集上进行测试", "_____no_output_____" ] ], [ [ "token_path = os.path.join(output_dir, \"token_test.txt\")\nif os.path.exists(token_path):\n os.remove(token_path)\n\nwith codecs.open(os.path.join(output_dir, 'label2id.pkl'), 'rb') as rf:\n label2id = pickle.load(rf)\n id2label = {value: key for key, value in label2id.items()}\n\npredict_examples = processor.get_test_examples(data_dir)\npredict_file = os.path.join(output_dir, \"predict.tf_record\")\nfiled_based_convert_examples_to_features(predict_examples, label_list,\n max_seq_length, tokenizer,\n predict_file, mode=\"test\")\n\ntf.logging.info(\"***** Running prediction*****\")\ntf.logging.info(\" Num examples = %d\", len(predict_examples))\ntf.logging.info(\" Batch size = %d\", batch_size)\n \npredict_drop_remainder = False\npredict_input_fn = file_based_input_fn_builder(\n input_file=predict_file,\n seq_length=max_seq_length,\n is_training=False,\n drop_remainder=predict_drop_remainder)\n\npredicted_result = estimator.evaluate(input_fn=predict_input_fn)\noutput_eval_file = os.path.join(output_dir, \"predicted_results.txt\")\nwith codecs.open(output_eval_file, \"w\", encoding='utf-8') as writer:\n tf.logging.info(\"***** Predict results *****\")\n for key in sorted(predicted_result.keys()):\n tf.logging.info(\" %s = %s\", key, str(predicted_result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(predicted_result[key])))\n\nresult = estimator.predict(input_fn=predict_input_fn)\noutput_predict_file = os.path.join(output_dir, \"label_test.txt\")\n\ndef result_to_pair(writer):\n for predict_line, prediction in zip(predict_examples, result):\n idx = 0\n line = ''\n line_token = str(predict_line.text).split(' ')\n label_token = str(predict_line.label).split(' ')\n if len(line_token) != len(label_token):\n tf.logging.info(predict_line.text)\n tf.logging.info(predict_line.label)\n for id in prediction:\n if id == 0:\n continue\n curr_labels = id2label[id]\n if curr_labels in ['[CLS]', '[SEP]']:\n continue\n try:\n line += line_token[idx] + ' ' + label_token[idx] + ' ' + curr_labels + '\\n'\n except Exception as e:\n tf.logging.info(e)\n tf.logging.info(predict_line.text)\n tf.logging.info(predict_line.label)\n line = ''\n break\n idx += 1\n writer.write(line + '\\n')\n \nfrom ner.src.conlleval import return_report\n\nwith codecs.open(output_predict_file, 'w', encoding='utf-8') as writer:\n result_to_pair(writer)\neval_result = return_report(output_predict_file)\nfor line in eval_result:\n print(line)", "INFO:tensorflow:Writing example 0 of 68\nINFO:tensorflow:***** Running prediction*****\nINFO:tensorflow: Num examples = 68\nINFO:tensorflow: Batch size = 64\nINFO:tensorflow:Calling model_fn.\nINFO:tensorflow:*** Features ***\nINFO:tensorflow: name = input_ids, shape = (?, 128)\nINFO:tensorflow: name = input_mask, shape = (?, 128)\nINFO:tensorflow: name = label_ids, shape = (?, 128)\nINFO:tensorflow: name = segment_ids, shape = (?, 128)\n" ] ], [ [ "### 在线命名实体识别\n\n由以上训练得到模型进行在线测试,可以任意输入句子,进行命名实体识别。\n\n输入“再见”,结束在线命名实体识别。\n\n<span style=\"color:red\">若下述程序未执行成功,则表示训练完成后,GPU显存还在占用,需要restart kernel,然后执行 %run 命令。</span>\n\n释放资源具体流程为:菜单 > Kernel > Restart \n\n![释放资源](./img/释放资源.png)\n", "_____no_output_____" ] ], [ [ "%run ner/src/terminal_predict.py", "checkpoint path:./ner/output/checkpoint\ngoing to restore checkpoint\nINFO:tensorflow:Restoring parameters from ./ner/output/model.ckpt-1630\n{1: 'O', 2: 'B-PER', 3: 'I-PER', 4: 'B-ORG', 5: 'I-ORG', 6: 'B-LOC', 7: 'I-LOC', 8: 'X', 9: '[CLS]', 10: '[SEP]'}\n输入句子:\n中国男篮与委内瑞拉队在北京五棵松体育馆展开小组赛最后一场比赛的争夺,赵继伟12分4助攻3抢断、易建联11分8篮板、周琦8分7篮板2盖帽。\n[['B-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'B-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'B-LOC', 'I-LOC', 'B-LOC', 'I-LOC', 'I-LOC', 'I-LOC', 'I-LOC', 'I-LOC', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-PER', 'I-PER', 'I-PER', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-PER', 'I-PER', 'I-PER', 'O', 'O', 'O', 'O', 'O', 'O', 'B-PER', 'I-PER', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']]\nLOC, 北京, 五棵松体育馆\nPER, 赵继伟, 易建联, 周琦\nORG, 中国男篮, 委内瑞拉队\ntime used: 0.908481 sec\n输入句子:\n周杰伦(Jay Chou),1979年1月18日出生于台湾省新北市,毕业于淡江中学,中国台湾流行乐男歌手。\n[['B-PER', 'I-PER', 'I-PER', 'O', 'B-PER', 'I-PER', 'I-PER', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-LOC', 'I-LOC', 'I-LOC', 'B-LOC', 'I-LOC', 'I-LOC', 'O', 'O', 'O', 'O', 'B-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'B-LOC', 'I-LOC', 'B-LOC', 'I-LOC', 'O', 'O', 'O', 'O', 'O', 'O', 'O']]\nLOC, 台湾省, 新北市, 中国, 台湾\nPER, 周杰伦, jaycho##u\nORG, 淡江中学\ntime used: 0.058148 sec\n输入句子:\n马云,1964年9月10日生于浙江省杭州市,1988年毕业于杭州师范学院外语系,同年担任杭州电子工业学院英文及国际贸易教师。\n[['B-PER', 'I-PER', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-LOC', 'I-LOC', 'I-LOC', 'B-LOC', 'I-LOC', 'I-LOC', 'O', 'O', 'O', 'O', 'O', 'O', 'B-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'B-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']]\nLOC, 浙江省, 杭州市\nPER, 马云\nORG, 杭州师范学院外语系, 杭州电子工业学院\ntime used: 0.065471 sec\n输入句子:\n再见\n\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" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0110f9da3542e8f5df264e5a0e1a8cb65320cc7
78,406
ipynb
Jupyter Notebook
100-pandas-puzzles.ipynb
LouisNodskov/100-pandas-puzzles
5ccef9e985b935566c3d8a52e4f0f2f94d0dcf70
[ "MIT" ]
null
null
null
100-pandas-puzzles.ipynb
LouisNodskov/100-pandas-puzzles
5ccef9e985b935566c3d8a52e4f0f2f94d0dcf70
[ "MIT" ]
null
null
null
100-pandas-puzzles.ipynb
LouisNodskov/100-pandas-puzzles
5ccef9e985b935566c3d8a52e4f0f2f94d0dcf70
[ "MIT" ]
null
null
null
28.183321
400
0.431064
[ [ [ "# 100 pandas puzzles\n\nInspired by [100 Numpy exerises](https://github.com/rougier/numpy-100), here are 100* short puzzles for testing your knowledge of [pandas'](http://pandas.pydata.org/) power.\n\nSince pandas is a large library with many different specialist features and functions, these excercises focus mainly on the fundamentals of manipulating data (indexing, grouping, aggregating, cleaning), making use of the core DataFrame and Series objects. \n\nMany of the excerises here are stright-forward in that the solutions require no more than a few lines of code (in pandas or NumPy... don't go using pure Python or Cython!). Choosing the right methods and following best practices is the underlying goal.\n\nThe exercises are loosely divided in sections. Each section has a difficulty rating; these ratings are subjective, of course, but should be a seen as a rough guide as to how inventive the required solution is.\n\nIf you're just starting out with pandas and you are looking for some other resources, the official documentation is very extensive. In particular, some good places get a broader overview of pandas are...\n\n- [10 minutes to pandas](http://pandas.pydata.org/pandas-docs/stable/10min.html)\n- [pandas basics](http://pandas.pydata.org/pandas-docs/stable/basics.html)\n- [tutorials](http://pandas.pydata.org/pandas-docs/stable/tutorials.html)\n- [cookbook and idioms](http://pandas.pydata.org/pandas-docs/stable/cookbook.html#cookbook)\n\nEnjoy the puzzles!\n\n\\* *the list of exercises is not yet complete! Pull requests or suggestions for additional exercises, corrections and improvements are welcomed.*", "_____no_output_____" ], [ "## Importing pandas\n\n### Getting started and checking your pandas setup\n\nDifficulty: *easy* \n\n**1.** Import pandas under the alias `pd`.", "_____no_output_____" ] ], [ [ "import pandas as pd", "_____no_output_____" ] ], [ [ "**2.** Print the version of pandas that has been imported.", "_____no_output_____" ] ], [ [ "pd.__version__", "_____no_output_____" ] ], [ [ "**3.** Print out all the *version* information of the libraries that are required by the pandas library.", "_____no_output_____" ] ], [ [ "pd.show_versions()", "\nINSTALLED VERSIONS\n------------------\ncommit : 2cb96529396d93b46abab7bbc73a208e708c642e\npython : 3.8.8.final.0\npython-bits : 64\nOS : Windows\nOS-release : 10\nVersion : 10.0.22000\nmachine : AMD64\nprocessor : Intel64 Family 6 Model 142 Stepping 10, GenuineIntel\nbyteorder : little\nLC_ALL : None\nLANG : None\nLOCALE : English_United States.1252\n\npandas : 1.2.4\nnumpy : 1.20.1\npytz : 2020.1\ndateutil : 2.8.1\npip : 20.2.2\nsetuptools : 52.0.0.post20210125\nCython : 0.29.23\npytest : 6.2.3\nhypothesis : None\nsphinx : 4.0.1\nblosc : None\nfeather : None\nxlsxwriter : 1.3.8\nlxml.etree : 4.6.3\nhtml5lib : 1.1\npymysql : None\npsycopg2 : 2.8.6 (dt dec pq3 ext lo64)\njinja2 : 2.11.3\nIPython : 7.22.0\npandas_datareader: 0.10.0\nbs4 : 4.9.3\nbottleneck : 1.3.2\nfsspec : 0.9.0\nfastparquet : None\ngcsfs : None\nmatplotlib : 3.3.4\nnumexpr : 2.7.3\nodfpy : None\nopenpyxl : 3.0.7\npandas_gbq : None\npyarrow : None\npyxlsb : None\ns3fs : None\nscipy : 1.6.2\nsqlalchemy : 1.4.7\ntables : 3.6.1\ntabulate : None\nxarray : None\nxlrd : 2.0.1\nxlwt : 1.3.0\nnumba : 0.53.1\n" ] ], [ [ "## DataFrame basics\n\n### A few of the fundamental routines for selecting, sorting, adding and aggregating data in DataFrames\n\nDifficulty: *easy*\n\nNote: remember to import numpy using:\n```python\nimport numpy as np\n```\n\nConsider the following Python dictionary `data` and Python list `labels`:\n\n``` python\ndata = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],\n 'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],\n 'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],\n 'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}\n\nlabels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']\n```\n(This is just some meaningless data I made up with the theme of animals and trips to a vet.)\n\n**4.** Create a DataFrame `df` from this dictionary `data` which has the index `labels`.", "_____no_output_____" ] ], [ [ "import numpy as np\n\nraw_data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],\n 'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],\n 'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],\n 'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}\n\nlabels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']\n\ndf = pd.DataFrame(raw_data, index=labels)# (complete this line of code)\ndf", "_____no_output_____" ] ], [ [ "**5.** Display a summary of the basic information about this DataFrame and its data (*hint: there is a single method that can be called on the DataFrame*).", "_____no_output_____" ] ], [ [ "df.describe()", "_____no_output_____" ] ], [ [ "**6.** Return the first 3 rows of the DataFrame `df`.", "_____no_output_____" ] ], [ [ "df.iloc[:3,:]", "_____no_output_____" ] ], [ [ "**7.** Select just the 'animal' and 'age' columns from the DataFrame `df`.", "_____no_output_____" ] ], [ [ "df[['animal', 'age']]", "_____no_output_____" ] ], [ [ "**8.** Select the data in rows `[3, 4, 8]` *and* in columns `['animal', 'age']`.", "_____no_output_____" ] ], [ [ "df.iloc[[3, 4, 8]][['animal','age']]", "_____no_output_____" ] ], [ [ "**9.** Select only the rows where the number of visits is greater than 3.", "_____no_output_____" ] ], [ [ "df[df['visits'] > 3]", "_____no_output_____" ] ], [ [ "**10.** Select the rows where the age is missing, i.e. it is `NaN`.", "_____no_output_____" ] ], [ [ "df[df['age'].isna()]", "_____no_output_____" ] ], [ [ "**11.** Select the rows where the animal is a cat *and* the age is less than 3.", "_____no_output_____" ] ], [ [ "df[(df['animal'] == 'cat') & (df['age'] < 3)]", "_____no_output_____" ] ], [ [ "**12.** Select the rows the age is between 2 and 4 (inclusive).", "_____no_output_____" ] ], [ [ "df.iloc[2:5]", "_____no_output_____" ] ], [ [ "**13.** Change the age in row 'f' to 1.5.", "_____no_output_____" ] ], [ [ "df.loc['f','age'] = 1.5\ndf", "_____no_output_____" ] ], [ [ "**14.** Calculate the sum of all visits in `df` (i.e. find the total number of visits).", "_____no_output_____" ] ], [ [ "df['visits'].sum()", "_____no_output_____" ] ], [ [ "**15.** Calculate the mean age for each different animal in `df`.", "_____no_output_____" ] ], [ [ "df.groupby('animal').agg({'age':'mean'})", "_____no_output_____" ] ], [ [ "**16.** Append a new row 'k' to `df` with your choice of values for each column. Then delete that row to return the original DataFrame.", "_____no_output_____" ] ], [ [ "import numpy as np\nrnum = np.random.randint(10, size=len(df))\ndf['k'] = rnum", "_____no_output_____" ] ], [ [ "**17.** Count the number of each type of animal in `df`.", "_____no_output_____" ] ], [ [ "df['animal'].value_counts()", "_____no_output_____" ] ], [ [ "**18.** Sort `df` first by the values in the 'age' in *decending* order, then by the value in the 'visits' column in *ascending* order (so row `i` should be first, and row `d` should be last).", "_____no_output_____" ] ], [ [ "df.sort_values(by = ['age', 'visits'], ascending=[False, True])", "_____no_output_____" ] ], [ [ "**19.** The 'priority' column contains the values 'yes' and 'no'. Replace this column with a column of boolean values: 'yes' should be `True` and 'no' should be `False`.", "_____no_output_____" ] ], [ [ "df['priority'] = df['priority'].map({'yes': True, 'no': False})", "_____no_output_____" ] ], [ [ "**20.** In the 'animal' column, change the 'snake' entries to 'python'.", "_____no_output_____" ] ], [ [ "df['animal'] = df['animal'].replace('snake', 'python')\ndf", "_____no_output_____" ] ], [ [ "**21.** For each animal type and each number of visits, find the mean age. In other words, each row is an animal, each column is a number of visits and the values are the mean ages (*hint: use a pivot table*).", "_____no_output_____" ] ], [ [ "df.pivot_table(index = 'animal', columns = 'visits', values = 'age', aggfunc = 'mean').fillna(0)", "_____no_output_____" ] ], [ [ "## DataFrames: beyond the basics\n\n### Slightly trickier: you may need to combine two or more methods to get the right answer\n\nDifficulty: *medium*\n\nThe previous section was tour through some basic but essential DataFrame operations. Below are some ways that you might need to cut your data, but for which there is no single \"out of the box\" method.", "_____no_output_____" ], [ "**22.** You have a DataFrame `df` with a column 'A' of integers. For example:\n```python\ndf = pd.DataFrame({'A': [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7]})\n```\n\nHow do you filter out rows which contain the same integer as the row immediately above?\n\nYou should be left with a column containing the following values:\n\n```python\n1, 2, 3, 4, 5, 6, 7\n```", "_____no_output_____" ], [ "**23.** Given a DataFrame of numeric values, say\n```python\ndf = pd.DataFrame(np.random.random(size=(5, 3))) # a 5x3 frame of float values\n```\n\nhow do you subtract the row mean from each element in the row?", "_____no_output_____" ], [ "**24.** Suppose you have DataFrame with 10 columns of real numbers, for example:\n\n```python\ndf = pd.DataFrame(np.random.random(size=(5, 10)), columns=list('abcdefghij'))\n```\nWhich column of numbers has the smallest sum? Return that column's label.", "_____no_output_____" ], [ "**25.** How do you count how many unique rows a DataFrame has (i.e. ignore all rows that are duplicates)? As input, use a DataFrame of zeros and ones with 10 rows and 3 columns.\n\n```python\ndf = pd.DataFrame(np.random.randint(0, 2, size=(10, 3)))\n```", "_____no_output_____" ], [ "The next three puzzles are slightly harder.\n\n\n**26.** In the cell below, you have a DataFrame `df` that consists of 10 columns of floating-point numbers. Exactly 5 entries in each row are NaN values. \n\nFor each row of the DataFrame, find the *column* which contains the *third* NaN value.\n\nYou should return a Series of column labels: `e, c, d, h, d`", "_____no_output_____" ] ], [ [ "nan = np.nan\n\ndata = [[0.04, nan, nan, 0.25, nan, 0.43, 0.71, 0.51, nan, nan],\n [ nan, nan, nan, 0.04, 0.76, nan, nan, 0.67, 0.76, 0.16],\n [ nan, nan, 0.5 , nan, 0.31, 0.4 , nan, nan, 0.24, 0.01],\n [0.49, nan, nan, 0.62, 0.73, 0.26, 0.85, nan, nan, nan],\n [ nan, nan, 0.41, nan, 0.05, nan, 0.61, nan, 0.48, 0.68]]\n\ncolumns = list('abcdefghij')\n\ndf = pd.DataFrame(data, columns=columns)\n\n# write a solution to the question here", "_____no_output_____" ] ], [ [ "**27.** A DataFrame has a column of groups 'grps' and and column of integer values 'vals': \n\n```python\ndf = pd.DataFrame({'grps': list('aaabbcaabcccbbc'), \n 'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})\n```\nFor each *group*, find the sum of the three greatest values. You should end up with the answer as follows:\n```\ngrps\na 409\nb 156\nc 345\n```", "_____no_output_____" ] ], [ [ "df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'), \n 'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})\n\n# write a solution to the question here", "_____no_output_____" ] ], [ [ "**28.** The DataFrame `df` constructed below has two integer columns 'A' and 'B'. The values in 'A' are between 1 and 100 (inclusive). \n\nFor each group of 10 consecutive integers in 'A' (i.e. `(0, 10]`, `(10, 20]`, ...), calculate the sum of the corresponding values in column 'B'.\n\nThe answer should be a Series as follows:\n\n```\nA\n(0, 10] 635\n(10, 20] 360\n(20, 30] 315\n(30, 40] 306\n(40, 50] 750\n(50, 60] 284\n(60, 70] 424\n(70, 80] 526\n(80, 90] 835\n(90, 100] 852\n```", "_____no_output_____" ] ], [ [ "df = pd.DataFrame(np.random.RandomState(8765).randint(1, 101, size=(100, 2)), columns = [\"A\", \"B\"])\n\n# write a solution to the question here", "_____no_output_____" ] ], [ [ "## DataFrames: harder problems \n\n### These might require a bit of thinking outside the box...\n\n...but all are solvable using just the usual pandas/NumPy methods (and so avoid using explicit `for` loops).\n\nDifficulty: *hard*", "_____no_output_____" ], [ "**29.** Consider a DataFrame `df` where there is an integer column 'X':\n```python\ndf = pd.DataFrame({'X': [7, 2, 0, 3, 4, 2, 5, 0, 3, 4]})\n```\nFor each value, count the difference back to the previous zero (or the start of the Series, whichever is closer). These values should therefore be \n\n```\n[1, 2, 0, 1, 2, 3, 4, 0, 1, 2]\n```\n\nMake this a new column 'Y'.", "_____no_output_____" ], [ "**30.** Consider the DataFrame constructed below which contains rows and columns of numerical data. \n\nCreate a list of the column-row index locations of the 3 largest values in this DataFrame. In this case, the answer should be:\n```\n[(5, 7), (6, 4), (2, 5)]\n```", "_____no_output_____" ] ], [ [ "df = pd.DataFrame(np.random.RandomState(30).randint(1, 101, size=(8, 8)))", "_____no_output_____" ] ], [ [ "**31.** You are given the DataFrame below with a column of group IDs, 'grps', and a column of corresponding integer values, 'vals'.\n\n```python\ndf = pd.DataFrame({\"vals\": np.random.RandomState(31).randint(-30, 30, size=15), \n \"grps\": np.random.RandomState(31).choice([\"A\", \"B\"], 15)})\n```\n\nCreate a new column 'patched_values' which contains the same values as the 'vals' any negative values in 'vals' with the group mean:\n\n```\n vals grps patched_vals\n0 -12 A 13.6\n1 -7 B 28.0\n2 -14 A 13.6\n3 4 A 4.0\n4 -7 A 13.6\n5 28 B 28.0\n6 -2 A 13.6\n7 -1 A 13.6\n8 8 A 8.0\n9 -2 B 28.0\n10 28 A 28.0\n11 12 A 12.0\n12 16 A 16.0\n13 -24 A 13.6\n14 -12 A 13.6\n```", "_____no_output_____" ], [ "**32.** Implement a rolling mean over groups with window size 3, which ignores NaN value. For example consider the following DataFrame:\n\n```python\n>>> df = pd.DataFrame({'group': list('aabbabbbabab'),\n 'value': [1, 2, 3, np.nan, 2, 3, np.nan, 1, 7, 3, np.nan, 8]})\n>>> df\n group value\n0 a 1.0\n1 a 2.0\n2 b 3.0\n3 b NaN\n4 a 2.0\n5 b 3.0\n6 b NaN\n7 b 1.0\n8 a 7.0\n9 b 3.0\n10 a NaN\n11 b 8.0\n```\nThe goal is to compute the Series:\n\n```\n0 1.000000\n1 1.500000\n2 3.000000\n3 3.000000\n4 1.666667\n5 3.000000\n6 3.000000\n7 2.000000\n8 3.666667\n9 2.000000\n10 4.500000\n11 4.000000\n```\nE.g. the first window of size three for group 'b' has values 3.0, NaN and 3.0 and occurs at row index 5. Instead of being NaN the value in the new column at this row index should be 3.0 (just the two non-NaN values are used to compute the mean (3+3)/2)", "_____no_output_____" ], [ "## Series and DatetimeIndex\n\n### Exercises for creating and manipulating Series with datetime data\n\nDifficulty: *easy/medium*\n\npandas is fantastic for working with dates and times. These puzzles explore some of this functionality.\n", "_____no_output_____" ], [ "**33.** Create a DatetimeIndex that contains each business day of 2015 and use it to index a Series of random numbers. Let's call this Series `s`.", "_____no_output_____" ], [ "**34.** Find the sum of the values in `s` for every Wednesday.", "_____no_output_____" ], [ "**35.** For each calendar month in `s`, find the mean of values.", "_____no_output_____" ], [ "**36.** For each group of four consecutive calendar months in `s`, find the date on which the highest value occurred.", "_____no_output_____" ], [ "**37.** Create a DateTimeIndex consisting of the third Thursday in each month for the years 2015 and 2016.", "_____no_output_____" ], [ "## Cleaning Data\n\n### Making a DataFrame easier to work with\n\nDifficulty: *easy/medium*\n\nIt happens all the time: someone gives you data containing malformed strings, Python, lists and missing data. How do you tidy it up so you can get on with the analysis?\n\nTake this monstrosity as the DataFrame to use in the following puzzles:\n\n```python\ndf = pd.DataFrame({'From_To': ['LoNDon_paris', 'MAdrid_miLAN', 'londON_StockhOlm', \n 'Budapest_PaRis', 'Brussels_londOn'],\n 'FlightNumber': [10045, np.nan, 10065, np.nan, 10085],\n 'RecentDelays': [[23, 47], [], [24, 43, 87], [13], [67, 32]],\n 'Airline': ['KLM(!)', '<Air France> (12)', '(British Airways. )', \n '12. Air France', '\"Swiss Air\"']})\n```\nFormatted, it looks like this:\n\n```\n From_To FlightNumber RecentDelays Airline\n0 LoNDon_paris 10045.0 [23, 47] KLM(!)\n1 MAdrid_miLAN NaN [] <Air France> (12)\n2 londON_StockhOlm 10065.0 [24, 43, 87] (British Airways. )\n3 Budapest_PaRis NaN [13] 12. Air France\n4 Brussels_londOn 10085.0 [67, 32] \"Swiss Air\"\n```\n\n\n(It's some flight data I made up; it's not meant to be accurate in any way.)\n", "_____no_output_____" ], [ "**38.** Some values in the the **FlightNumber** column are missing (they are `NaN`). These numbers are meant to increase by 10 with each row so 10055 and 10075 need to be put in place. Modify `df` to fill in these missing numbers and make the column an integer column (instead of a float column).", "_____no_output_____" ], [ "**39.** The **From\\_To** column would be better as two separate columns! Split each string on the underscore delimiter `_` to give a new temporary DataFrame called 'temp' with the correct values. Assign the correct column names 'From' and 'To' to this temporary DataFrame. ", "_____no_output_____" ], [ "**40.** Notice how the capitalisation of the city names is all mixed up in this temporary DataFrame 'temp'. Standardise the strings so that only the first letter is uppercase (e.g. \"londON\" should become \"London\".)", "_____no_output_____" ], [ "**41.** Delete the **From_To** column from `df` and attach the temporary DataFrame 'temp' from the previous questions.", "_____no_output_____" ], [ "**42**. In the **Airline** column, you can see some extra puctuation and symbols have appeared around the airline names. Pull out just the airline name. E.g. `'(British Airways. )'` should become `'British Airways'`.", "_____no_output_____" ], [ "**43**. In the RecentDelays column, the values have been entered into the DataFrame as a list. We would like each first value in its own column, each second value in its own column, and so on. If there isn't an Nth value, the value should be NaN.\n\nExpand the Series of lists into a DataFrame named `delays`, rename the columns `delay_1`, `delay_2`, etc. and replace the unwanted RecentDelays column in `df` with `delays`.", "_____no_output_____" ], [ "The DataFrame should look much better now.\n```\n FlightNumber Airline From To delay_1 delay_2 delay_3\n0 10045 KLM London Paris 23.0 47.0 NaN\n1 10055 Air France Madrid Milan NaN NaN NaN\n2 10065 British Airways London Stockholm 24.0 43.0 87.0\n3 10075 Air France Budapest Paris 13.0 NaN NaN\n4 10085 Swiss Air Brussels London 67.0 32.0 NaN\n```", "_____no_output_____" ], [ "## Using MultiIndexes\n\n### Go beyond flat DataFrames with additional index levels\n\nDifficulty: *medium*\n\nPrevious exercises have seen us analysing data from DataFrames equipped with a single index level. However, pandas also gives you the possibilty of indexing your data using *multiple* levels. This is very much like adding new dimensions to a Series or a DataFrame. For example, a Series is 1D, but by using a MultiIndex with 2 levels we gain of much the same functionality as a 2D DataFrame.\n\nThe set of puzzles below explores how you might use multiple index levels to enhance data analysis.\n\nTo warm up, we'll look make a Series with two index levels. ", "_____no_output_____" ], [ "**44**. Given the lists `letters = ['A', 'B', 'C']` and `numbers = list(range(10))`, construct a MultiIndex object from the product of the two lists. Use it to index a Series of random numbers. Call this Series `s`.", "_____no_output_____" ], [ "**45.** Check the index of `s` is lexicographically sorted (this is a necessary proprty for indexing to work correctly with a MultiIndex).", "_____no_output_____" ], [ "**46**. Select the labels `1`, `3` and `6` from the second level of the MultiIndexed Series.", "_____no_output_____" ], [ "**47**. Slice the Series `s`; slice up to label 'B' for the first level and from label 5 onwards for the second level.", "_____no_output_____" ], [ "**48**. Sum the values in `s` for each label in the first level (you should have Series giving you a total for labels A, B and C).", "_____no_output_____" ], [ "**49**. Suppose that `sum()` (and other methods) did not accept a `level` keyword argument. How else could you perform the equivalent of `s.sum(level=1)`?", "_____no_output_____" ], [ "**50**. Exchange the levels of the MultiIndex so we have an index of the form (letters, numbers). Is this new Series properly lexsorted? If not, sort it.", "_____no_output_____" ], [ "## Minesweeper\n\n### Generate the numbers for safe squares in a Minesweeper grid\n\nDifficulty: *medium* to *hard*\n\nIf you've ever used an older version of Windows, there's a good chance you've played with Minesweeper:\n- https://en.wikipedia.org/wiki/Minesweeper_(video_game)\n\n\nIf you're not familiar with the game, imagine a grid of squares: some of these squares conceal a mine. If you click on a mine, you lose instantly. If you click on a safe square, you reveal a number telling you how many mines are found in the squares that are immediately adjacent. The aim of the game is to uncover all squares in the grid that do not contain a mine.\n\nIn this section, we'll make a DataFrame that contains the necessary data for a game of Minesweeper: coordinates of the squares, whether the square contains a mine and the number of mines found on adjacent squares.", "_____no_output_____" ], [ "**51**. Let's suppose we're playing Minesweeper on a 5 by 4 grid, i.e.\n```\nX = 5\nY = 4\n```\nTo begin, generate a DataFrame `df` with two columns, `'x'` and `'y'` containing every coordinate for this grid. That is, the DataFrame should start:\n```\n x y\n0 0 0\n1 0 1\n2 0 2\n```", "_____no_output_____" ], [ "**52**. For this DataFrame `df`, create a new column of zeros (safe) and ones (mine). The probability of a mine occuring at each location should be 0.4.", "_____no_output_____" ], [ "**53**. Now create a new column for this DataFrame called `'adjacent'`. This column should contain the number of mines found on adjacent squares in the grid. \n\n(E.g. for the first row, which is the entry for the coordinate `(0, 0)`, count how many mines are found on the coordinates `(0, 1)`, `(1, 0)` and `(1, 1)`.)", "_____no_output_____" ], [ "**54**. For rows of the DataFrame that contain a mine, set the value in the `'adjacent'` column to NaN.", "_____no_output_____" ], [ "**55**. Finally, convert the DataFrame to grid of the adjacent mine counts: columns are the `x` coordinate, rows are the `y` coordinate.", "_____no_output_____" ], [ "## Plotting\n\n### Visualize trends and patterns in data\n\nDifficulty: *medium*\n\nTo really get a good understanding of the data contained in your DataFrame, it is often essential to create plots: if you're lucky, trends and anomalies will jump right out at you. This functionality is baked into pandas and the puzzles below explore some of what's possible with the library.\n\n**56.** Pandas is highly integrated with the plotting library matplotlib, and makes plotting DataFrames very user-friendly! Plotting in a notebook environment usually makes use of the following boilerplate:\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.style.use('ggplot')\n```\n\nmatplotlib is the plotting library which pandas' plotting functionality is built upon, and it is usually aliased to ```plt```.\n\n```%matplotlib inline``` tells the notebook to show plots inline, instead of creating them in a separate window. \n\n```plt.style.use('ggplot')``` is a style theme that most people find agreeable, based upon the styling of R's ggplot package.\n\nFor starters, make a scatter plot of this random data, but use black X's instead of the default markers. \n\n```df = pd.DataFrame({\"xs\":[1,5,2,8,1], \"ys\":[4,2,1,9,6]})```\n\nConsult the [documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html) if you get stuck!", "_____no_output_____" ], [ "**57.** Columns in your DataFrame can also be used to modify colors and sizes. Bill has been keeping track of his performance at work over time, as well as how good he was feeling that day, and whether he had a cup of coffee in the morning. Make a plot which incorporates all four features of this DataFrame.\n\n(Hint: If you're having trouble seeing the plot, try multiplying the Series which you choose to represent size by 10 or more)\n\n*The chart doesn't have to be pretty: this isn't a course in data viz!*\n\n```\ndf = pd.DataFrame({\"productivity\":[5,2,3,1,4,5,6,7,8,3,4,8,9],\n \"hours_in\" :[1,9,6,5,3,9,2,9,1,7,4,2,2],\n \"happiness\" :[2,1,3,2,3,1,2,3,1,2,2,1,3],\n \"caffienated\" :[0,0,1,1,0,0,0,0,1,1,0,1,0]})\n```", "_____no_output_____" ], [ "**58.** What if we want to plot multiple things? Pandas allows you to pass in a matplotlib *Axis* object for plots, and plots will also return an Axis object.\n\nMake a bar plot of monthly revenue with a line plot of monthly advertising spending (numbers in millions)\n\n```\ndf = pd.DataFrame({\"revenue\":[57,68,63,71,72,90,80,62,59,51,47,52],\n \"advertising\":[2.1,1.9,2.7,3.0,3.6,3.2,2.7,2.4,1.8,1.6,1.3,1.9],\n \"month\":range(12)\n })\n```", "_____no_output_____" ], [ "Now we're finally ready to create a candlestick chart, which is a very common tool used to analyze stock price data. A candlestick chart shows the opening, closing, highest, and lowest price for a stock during a time window. The color of the \"candle\" (the thick part of the bar) is green if the stock closed above its opening price, or red if below.\n\n![Candlestick Example](img/candle.jpg)\n\nThis was initially designed to be a pandas plotting challenge, but it just so happens that this type of plot is just not feasible using pandas' methods. If you are unfamiliar with matplotlib, we have provided a function that will plot the chart for you so long as you can use pandas to get the data into the correct format.\n\nYour first step should be to get the data in the correct format using pandas' time-series grouping function. We would like each candle to represent an hour's worth of data. You can write your own aggregation function which returns the open/high/low/close, but pandas has a built-in which also does this.", "_____no_output_____" ], [ "The below cell contains helper functions. Call ```day_stock_data()``` to generate a DataFrame containing the prices a hypothetical stock sold for, and the time the sale occurred. Call ```plot_candlestick(df)``` on your properly aggregated and formatted stock data to print the candlestick chart.", "_____no_output_____" ] ], [ [ "import numpy as np\ndef float_to_time(x):\n return str(int(x)) + \":\" + str(int(x%1 * 60)).zfill(2) + \":\" + str(int(x*60 % 1 * 60)).zfill(2)\n\ndef day_stock_data():\n #NYSE is open from 9:30 to 4:00\n time = 9.5\n price = 100\n results = [(float_to_time(time), price)]\n while time < 16:\n elapsed = np.random.exponential(.001)\n time += elapsed\n if time > 16:\n break\n price_diff = np.random.uniform(.999, 1.001)\n price *= price_diff\n results.append((float_to_time(time), price))\n \n \n df = pd.DataFrame(results, columns = ['time','price'])\n df.time = pd.to_datetime(df.time)\n return df\n\n#Don't read me unless you get stuck!\ndef plot_candlestick(agg):\n \"\"\"\n agg is a DataFrame which has a DatetimeIndex and five columns: [\"open\",\"high\",\"low\",\"close\",\"color\"]\n \"\"\"\n fig, ax = plt.subplots()\n for time in agg.index:\n ax.plot([time.hour] * 2, agg.loc[time, [\"high\",\"low\"]].values, color = \"black\")\n ax.plot([time.hour] * 2, agg.loc[time, [\"open\",\"close\"]].values, color = agg.loc[time, \"color\"], linewidth = 10)\n\n ax.set_xlim((8,16))\n ax.set_ylabel(\"Price\")\n ax.set_xlabel(\"Hour\")\n ax.set_title(\"OHLC of Stock Value During Trading Day\")\n plt.show()", "_____no_output_____" ] ], [ [ "**59.** Generate a day's worth of random stock data, and aggregate / reformat it so that it has hourly summaries of the opening, highest, lowest, and closing prices", "_____no_output_____" ], [ "**60.** Now that you have your properly-formatted data, try to plot it yourself as a candlestick chart. Use the ```plot_candlestick(df)``` function above, or matplotlib's [```plot``` documentation](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html) if you get stuck.", "_____no_output_____" ], [ "*More exercises to follow soon...*", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "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" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "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", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
d011269aab28f34074c6425a4287846bee358741
11,569
ipynb
Jupyter Notebook
Evaluating Performance - Weather.ipynb
mouax209/mouax209
85ec8564ead807a225f3ff36d7cf485462d895f4
[ "CC-BY-3.0" ]
null
null
null
Evaluating Performance - Weather.ipynb
mouax209/mouax209
85ec8564ead807a225f3ff36d7cf485462d895f4
[ "CC-BY-3.0" ]
null
null
null
Evaluating Performance - Weather.ipynb
mouax209/mouax209
85ec8564ead807a225f3ff36d7cf485462d895f4
[ "CC-BY-3.0" ]
null
null
null
42.848148
112
0.387847
[ [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn import linear_model\nimport statsmodels.api as sm\nfrom sqlalchemy import create_engine\n\n# Display preferences.\n%matplotlib inline\npd.options.display.float_format = '{:.3f}'.format\n\nimport warnings\nwarnings.filterwarnings(action=\"ignore\")\n\npostgres_user = 'dsbc_student'\npostgres_pw = '7*.8G9QH21'\npostgres_host = '142.93.121.174'\npostgres_port = '5432'\npostgres_db = 'weatherinszeged'\n\nengine = create_engine('postgresql://{}:{}@{}:{}/{}'.format(\n postgres_user, postgres_pw, postgres_host, postgres_port, postgres_db))\n\nweather_df = pd.read_sql_query('select * from weatherinszeged',con=engine)\n\n# no need for an open connection, as we're only doing a single query\nengine.dispose()", "_____no_output_____" ], [ "# Y is the target variable\nY = weather_df['apparenttemperature'] - weather_df['temperature']\n\n# X is the feature set\nX = weather_df[['humidity','windspeed']]\n\n# We add constant to the model as it's a best practice\n# to do so every time!\nX = sm.add_constant(X)\n\n# We fit an OLS model using statsmodels\nresults = sm.OLS(Y, X).fit()\n\n# We print the summary results.\nprint(results.summary())", " OLS Regression Results \n==============================================================================\nDep. Variable: y R-squared: 0.288\nModel: OLS Adj. R-squared: 0.288\nMethod: Least Squares F-statistic: 1.949e+04\nDate: Mon, 20 Jan 2020 Prob (F-statistic): 0.00\nTime: 21:09:48 Log-Likelihood: -1.7046e+05\nNo. Observations: 96453 AIC: 3.409e+05\nDf Residuals: 96450 BIC: 3.409e+05\nDf Model: 2 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nconst 2.4381 0.021 115.948 0.000 2.397 2.479\nhumidity -3.0292 0.024 -126.479 0.000 -3.076 -2.982\nwindspeed -0.1193 0.001 -176.164 0.000 -0.121 -0.118\n==============================================================================\nOmnibus: 3935.747 Durbin-Watson: 0.267\nProb(Omnibus): 0.000 Jarque-Bera (JB): 4613.311\nSkew: -0.478 Prob(JB): 0.00\nKurtosis: 3.484 Cond. No. 88.1\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n" ], [ "#r-sqaured = .288 and Adjusted r-squared = .288\n# This is unsatisfactory because it's very low and gives a lot of room to improve the model", "_____no_output_____" ], [ "#interaction \n# Y is the target variable\nY = weather_df['apparenttemperature'] - weather_df['temperature']\n\nweather_df[\"humidity\"] = weather_df.humidity * weather_df.windspeed\n\n# X is the feature set\nX = weather_df[['humidity','windspeed']]\n\n# We add a constant to the model as it's a best practice\n# to do so every time!\nX = sm.add_constant(X)\n\n# We fit an OLS model using statsmodels\nresults = sm.OLS(Y, X).fit()\n\n# We print the summary results\nprint(results.summary())", " OLS Regression Results \n==============================================================================\nDep. Variable: y R-squared: 0.341\nModel: OLS Adj. R-squared: 0.341\nMethod: Least Squares F-statistic: 2.497e+04\nDate: Mon, 20 Jan 2020 Prob (F-statistic): 0.00\nTime: 21:11:15 Log-Likelihood: -1.6670e+05\nNo. Observations: 96453 AIC: 3.334e+05\nDf Residuals: 96450 BIC: 3.334e+05\nDf Model: 2 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nconst 0.2178 0.008 26.385 0.000 0.202 0.234\nhumidity -0.2854 0.002 -158.432 0.000 -0.289 -0.282\nwindspeed 0.0819 0.001 62.418 0.000 0.079 0.084\n==============================================================================\nOmnibus: 4795.516 Durbin-Watson: 0.265\nProb(Omnibus): 0.000 Jarque-Bera (JB): 9042.719\nSkew: -0.379 Prob(JB): 0.00\nKurtosis: 4.295 Cond. No. 29.5\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n" ], [ "#The new r-squared and adjusted r-squared have barely risen, still low given they're below the .50 mark\n#This doesn't improve the model by much", "_____no_output_____" ], [ "# Y is the target variable\nY = weather_df['apparenttemperature'] - weather_df['temperature']\n\n# X is the feature set with visibility\nX = weather_df[['humidity','windspeed','visibility']]\n\n# We add constant to the model as it's a best practice\n# to do so every time!\nX = sm.add_constant(X)\n\n# We fit an OLS model using statsmodels\nresults = sm.OLS(Y, X).fit()\n\n# We print the summary results.\nprint(results.summary())", " OLS Regression Results \n==============================================================================\nDep. Variable: y R-squared: 0.361\nModel: OLS Adj. R-squared: 0.361\nMethod: Least Squares F-statistic: 1.815e+04\nDate: Mon, 20 Jan 2020 Prob (F-statistic): 0.00\nTime: 21:12:45 Log-Likelihood: -1.6524e+05\nNo. Observations: 96453 AIC: 3.305e+05\nDf Residuals: 96449 BIC: 3.305e+05\nDf Model: 3 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nconst -0.3657 0.013 -27.184 0.000 -0.392 -0.339\nhumidity -0.2603 0.002 -141.975 0.000 -0.264 -0.257\nwindspeed 0.0623 0.001 46.462 0.000 0.060 0.065\nvisibility 0.0583 0.001 54.446 0.000 0.056 0.060\n==============================================================================\nOmnibus: 4991.814 Durbin-Watson: 0.285\nProb(Omnibus): 0.000 Jarque-Bera (JB): 9859.261\nSkew: -0.378 Prob(JB): 0.00\nKurtosis: 4.371 Cond. No. 57.3\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n" ], [ "#This is the best model by far because the r-squared and adjusted r-sqaured \n#values, because it's the highest among the three at 0.361; and the AIC and BIC numbers are the lowest", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d0113475e4e8b4df8d5ed0466e22040e734a5dd9
96,367
ipynb
Jupyter Notebook
doc/example_notebooks/Single view, gaussian mixture model.ipynb
idc9/mvmm
64fce755a7cd53be9b08278484c7a4c77daf38d1
[ "MIT" ]
1
2021-08-17T13:22:54.000Z
2021-08-17T13:22:54.000Z
doc/example_notebooks/Single view, gaussian mixture model.ipynb
idc9/mvmm
64fce755a7cd53be9b08278484c7a4c77daf38d1
[ "MIT" ]
null
null
null
doc/example_notebooks/Single view, gaussian mixture model.ipynb
idc9/mvmm
64fce755a7cd53be9b08278484c7a4c77daf38d1
[ "MIT" ]
null
null
null
370.642308
52,668
0.938682
[ [ [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom mvmm.single_view.gaussian_mixture import GaussianMixture\nfrom mvmm.single_view.MMGridSearch import MMGridSearch\n\nfrom mvmm.single_view.toy_data import sample_1d_gmm\nfrom mvmm.single_view.sim_1d_utils import plot_est_params\nfrom mvmm.viz_utils import plot_scatter_1d, set_xaxis_int_ticks\nfrom mvmm.single_view.opt_diagnostics import plot_opt_hist\n", "_____no_output_____" ] ], [ [ "# sample data from a 1d gussian mixture model", "_____no_output_____" ] ], [ [ "n_samples = 200\nn_components = 3\nX, y, true_params = sample_1d_gmm(n_samples=n_samples,\n n_components=n_components,\n random_state=1)\nplot_scatter_1d(X)", "_____no_output_____" ] ], [ [ "# Fit a Gaussian mixture model", "_____no_output_____" ] ], [ [ "# fit a guassian mixture model with 3 (the true number) of components\n# from mvmm.single_view.gaussian_mixture.GaussianMixture() is similar to sklearn.mixture.GaussianMixture()\ngmm = GaussianMixture(n_components=3,\n n_init=10) # 10 random initalizations\ngmm.fit(X)\n\n\n# plot parameter estimates\nplot_scatter_1d(X)\nplot_est_params(gmm)", "_____no_output_____" ], [ "# the GMM class has all the familiar sklearn functionality\ngmm.sample(n_samples=20)\ngmm.predict(X)\ngmm.score_samples(X)\ngmm.predict_proba(X)\ngmm.bic(X)\n\n# with a few added API features for convenience\n\n# sample from a single mixture component\ngmm.sample_from_comp(y=0)\n\n# observed data log-likelihood\ngmm.log_likelihood(X)\n\n# total number of cluster parameters\ngmm._n_parameters()\n\n# some additional metadata is stored such as the fit time (in seconds)\ngmm.metadata_['fit_time']\n\n# gmm.opt_data_ stores the optimization history\nplot_opt_hist(loss_vals=gmm.opt_data_['history']['loss_val'],\n init_loss_vals=gmm.opt_data_['init_loss_vals'],\n loss_name='observed data negative log likelihood')", "_____no_output_____" ] ], [ [ "# Model selection with BIC", "_____no_output_____" ] ], [ [ "# setup the base estimator for the grid search\n# here we add some custom arguments\nbase_estimator = GaussianMixture(reg_covar=1e-6,\n init_params_method='rand_pts', # initalize cluster means from random data points\n n_init=10, abs_tol=1e-8, rel_tol=1e-8, max_n_steps=200)\n\n# do a grid search from 1 to 10 components\nparam_grid = {'n_components': np.arange(1, 10 + 1)}\n\n\n# setup grid search object and fit using the data\ngrid_search = MMGridSearch(base_estimator=base_estimator, param_grid=param_grid)\ngrid_search.fit(X)\n\n# the best model is stored in .best_estimator_\nprint('BIC selected the model with', grid_search.best_estimator_.n_components, ' components')", "BIC selected the model with 3 components\n" ], [ "# all fit estimators are containted in .estimators_\nprint(len(grid_search.estimators_))\n\n# the model selection for each grid point are stored in /model_sel_scores_\nprint(grid_search.model_sel_scores_)\n\n# plot BIC\nn_comp_seq = grid_search.param_grid['n_components']\nest_n_comp = grid_search.best_params_['n_components']\nbic_values = grid_search.model_sel_scores_['bic']\n\nplt.plot(n_comp_seq, bic_values, marker='.')\nplt.axvline(est_n_comp,\n label='estimated {} components'.format(est_n_comp),\n color='red')\nplt.legend()\n\nplt.xlabel('n_components')\nplt.ylabel('BIC')\nset_xaxis_int_ticks()", "10\n bic aic\n0 516.654319 510.057684\n1 353.053751 336.562164\n2 167.420223 141.033684\n3 172.957731 136.676240\n4 181.186136 135.009693\n5 198.034419 141.963024\n6 201.967577 136.001230\n7 226.684487 150.823187\n8 230.178894 144.422643\n9 244.147315 148.496112\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d01136164d25497fab9039d342be2caf83562709
24,855
ipynb
Jupyter Notebook
doc/introduction.ipynb
Magica-Chen/seaborn
340756eef61cc06129df9d779ea12260e17e61e4
[ "BSD-3-Clause" ]
1
2020-08-05T10:55:54.000Z
2020-08-05T10:55:54.000Z
doc/introduction.ipynb
vinayakreddy/seaborn
0fba83b47c7a2650f5549bd9b551d4057fb3c97a
[ "BSD-3-Clause" ]
null
null
null
doc/introduction.ipynb
vinayakreddy/seaborn
0fba83b47c7a2650f5549bd9b551d4057fb3c97a
[ "BSD-3-Clause" ]
null
null
null
45.689338
701
0.647958
[ [ [ ".. _introduction:\n\n.. currentmodule:: seaborn\n\nAn introduction to seaborn\n==========================\n\n.. raw:: html\n\n <div class=col-md-9>\n\nSeaborn is a library for making statistical graphics in Python. It is built on top of `matplotlib <https://matplotlib.org/>`_ and closely integrated with `pandas <https://pandas.pydata.org/>`_ data structures.\n\nHere is some of the functionality that seaborn offers:\n\n- A dataset-oriented API for examining :ref:`relationships <scatter_bubbles>` between :ref:`multiple variables <faceted_lineplot>`\n- Specialized support for using categorical variables to show :ref:`observations <jitter_stripplot>` or :ref:`aggregate statistics <pointplot_anova>` \n- Options for visualizing :ref:`univariate <distplot_options>` or :ref:`bivariate <joint_kde>` distributions and for :ref:`comparing <horizontal_boxplot>` them between subsets of data\n- Automatic estimation and plotting of :ref:`linear regression <anscombes_quartet>` models for different kinds :ref:`dependent <logistic_regression>` variables\n- Convenient views onto the overall :ref:`structure <scatterplot_matrix>` of complex datasets\n- High-level abstractions for structuring :ref:`multi-plot grids <faceted_histogram>` that let you easily build :ref:`complex <pair_grid_with_kde>` visualizations\n- Concise control over matplotlib figure styling with several :ref:`built-in themes <aesthetics_tutorial>`\n- Tools for choosing :ref:`color palettes <palette_tutorial>` that faithfully reveal patterns in your data\n\nSeaborn aims to make visualization a central part of exploring and understanding data. Its dataset-oriented plotting functions operate on dataframes and arrays containing whole datasets and internally perform the necessary semantic mapping and statistical aggregation to produce informative plots.\n\nHere's an example of what this means:", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ], [ "import seaborn as sns\nsns.set()\ntips = sns.load_dataset(\"tips\")\nsns.relplot(x=\"total_bill\", y=\"tip\", col=\"time\",\n hue=\"smoker\", style=\"smoker\", size=\"size\",\n data=tips);", "_____no_output_____" ] ], [ [ "A few things have happened here. Let's go through them one by one:\n\n1. We import seaborn, which is the only library necessary for this simple example.", "_____no_output_____" ] ], [ [ "import seaborn as sns", "_____no_output_____" ] ], [ [ "Behind the scenes, seaborn uses matplotlib to draw plots. Many tasks can be accomplished with only seaborn functions, but further customization might require using matplotlib directly. This is explained in more detail :ref:`below <intro_plot_customization>`. For interactive work, it's recommended to use a Jupyter/IPython interface in `matplotlib mode <https://ipython.readthedocs.io/en/stable/interactive/plotting.html>`_, or else you'll have to call :func:`matplotlib.pyplot.show` when you want to see the plot.\n\n2. We apply the default default seaborn theme, scaling, and color palette.", "_____no_output_____" ] ], [ [ "sns.set()", "_____no_output_____" ] ], [ [ "This uses the `matplotlib rcParam system <https://matplotlib.org/users/customizing.html>`_ and will affect how all matplotlib plots look, even if you don't make them with seaborn. Beyond the default theme, there are :ref:`several other options <aesthetics_tutorial>`, and you can independently control the style and scaling of the plot to quickly translate your work between presentation contexts (e.g., making a plot that will have readable fonts when projected during a talk). If you like the matplotlib defaults or prefer a different theme, you can skip this step and still use the seaborn plotting functions.\n\n3. We load one of the example datasets.", "_____no_output_____" ] ], [ [ "tips = sns.load_dataset(\"tips\")", "_____no_output_____" ] ], [ [ "Most code in the docs will use the :func:`load_dataset` function to get quick access to an example dataset. There's nothing particularly special about these datasets; they are just pandas dataframes, and we could have loaded them with :func:`pandas.read_csv` or build them by hand. Many examples use the \"tips\" dataset, which is very boring but quite useful for demonstration. The tips dataset illustrates the \"tidy\" approach to organizing a dataset. You'll get the most out of seaborn if your datasets are organized this way, and it is explained in more detail :ref:`below <intro_tidy_data>`.\n\n4. We draw a faceted scatter plot with multiple semantic variables.", "_____no_output_____" ] ], [ [ "sns.relplot(x=\"total_bill\", y=\"tip\", col=\"time\",\n hue=\"smoker\", style=\"smoker\", size=\"size\",\n data=tips)", "_____no_output_____" ] ], [ [ "This particular plot shows the relationship between five variables in the tips dataset. Three are numeric, and two are categorical. Two numeric variables (``total_bill`` and ``tip``) determined the position of each point on the axes, and the third (``size``) determined the size of each point. One categorical variable split the dataset onto two different axes (facets), and the other determined the color and shape of each point.\n\nAll of this was accomplished using a single call to the seaborn function :func:`relplot`. Notice how we only provided the names of the variables in the dataset and the roles that we wanted them to play in the plot. Unlike when using matplotlib directly, it wasn't necessary to translate the variables into parameters of the visualization (e.g., the specific color or marker to use for each category). That translation was done automatically by seaborn. This lets the user stay focused on the question they want the plot to answer.\n\n.. _intro_api_abstraction:\n\nAPI abstraction across visualizations\n-------------------------------------\n\nThere is no universal best way to visualize data. Different questions are best answered by different kinds of visualizations. Seaborn tries to make it easy to switch between different visual representations that can be parameterized with the same dataset-oriented API.\n\nThe function :func:`relplot` is named that way because it is designed to visualize many different statistical *relationships*. While scatter plots are a highly effective way of doing this, relationships where one variable represents a measure of time are better represented by a line. The :func:`relplot` function has a convenient ``kind`` parameter to let you easily switch to this alternate representation:", "_____no_output_____" ] ], [ [ "dots = sns.load_dataset(\"dots\")\nsns.relplot(x=\"time\", y=\"firing_rate\", col=\"align\",\n hue=\"choice\", size=\"coherence\", style=\"choice\",\n facet_kws=dict(sharex=False),\n kind=\"line\", legend=\"full\", data=dots);", "_____no_output_____" ] ], [ [ "Notice how the ``size`` and ``style`` parameters are shared across the scatter and line plots, but they affect the two visualizations differently (changing marker area and symbol vs line width and dashing). We did not need to keep those details in mind, letting us focus on the overall structure of the plot and the information we want it to convey.\n\n.. _intro_stat_estimation:\n\nStatistical estimation and error bars\n-------------------------------------\n\nOften we are interested in the average value of one variable as a function of other variables. Many seaborn functions can automatically perform the statistical estimation that is necessary to answer these questions:", "_____no_output_____" ] ], [ [ "fmri = sns.load_dataset(\"fmri\")\nsns.relplot(x=\"timepoint\", y=\"signal\", col=\"region\",\n hue=\"event\", style=\"event\",\n kind=\"line\", data=fmri);", "_____no_output_____" ] ], [ [ "When statistical values are estimated, seaborn will use bootstrapping to compute confidence intervals and draw error bars representing the uncertainty of the estimate.\n\nStatistical estimation in seaborn goes beyond descriptive statistics. For example, it is also possible to enhance a scatterplot to include a linear regression model (and its uncertainty) using :func:`lmplot`:", "_____no_output_____" ] ], [ [ "sns.lmplot(x=\"total_bill\", y=\"tip\", col=\"time\", hue=\"smoker\",\n data=tips);", "_____no_output_____" ] ], [ [ ".. _intro_categorical:\n\nSpecialized categorical plots\n-----------------------------\n\nStandard scatter and line plots visualize relationships between numerical variables, but many data analyses involve categorical variables. There are several specialized plot types in seaborn that are optimized for visualizing this kind of data. They can be accessed through :func:`catplot`. Similar to :func:`relplot`, the idea of :func:`catplot` is that it exposes a common dataset-oriented API that generalizes over different representations of the relationship between one numeric variable and one (or more) categorical variables.\n\nThese representations offer different levels of granularity in their presentation of the underlying data. At the finest level, you may wish to see every observation by drawing a scatter plot that adjusts the positions of the points along the categorical axis so that they don't overlap:", "_____no_output_____" ] ], [ [ "sns.catplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n kind=\"swarm\", data=tips);", "_____no_output_____" ] ], [ [ "Alternately, you could use kernel density estimation to represent the underlying distribution that the points are sampled from:", "_____no_output_____" ] ], [ [ "sns.catplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n kind=\"violin\", split=True, data=tips);", "_____no_output_____" ] ], [ [ "Or you could show the only mean value and its confidence interval within each nested category:", "_____no_output_____" ] ], [ [ "sns.catplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n kind=\"bar\", data=tips);", "_____no_output_____" ] ], [ [ ".. _intro_func_types:\n\nFigure-level and axes-level functions\n-------------------------------------\n\nHow do these tools work? It's important to know about a major distinction between seaborn plotting functions. All of the plots shown so far have been made with \"figure-level\" functions. These are optimized for exploratory analysis because they set up the matplotlib figure containing the plot(s) and make it easy to spread out the visualization across multiple axes. They also handle some tricky business like putting the legend outside the axes. To do these things, they use a seaborn :class:`FacetGrid`.\n\nEach different figure-level plot ``kind`` combines a particular \"axes-level\" function with the :class:`FacetGrid` object. For example, the scatter plots are drawn using the :func:`scatterplot` function, and the bar plots are drawn using the :func:`barplot` function. These functions are called \"axes-level\" because they draw onto a single matplotlib axes and don't otherwise affect the rest of the figure.\n\nThe upshot is that the figure-level function needs to control the figure it lives in, while axes-level functions can be combined into a more complex matplotlib figure with other axes that may or may not have seaborn plots on them:", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nf, axes = plt.subplots(1, 2, sharey=True, figsize=(6, 4))\nsns.boxplot(x=\"day\", y=\"tip\", data=tips, ax=axes[0])\nsns.scatterplot(x=\"total_bill\", y=\"tip\", hue=\"day\", data=tips, ax=axes[1]);", "_____no_output_____" ] ], [ [ "Controlling the size of the figure-level functions works a little bit differently than it does for other matplotlib figures. Instead of setting the overall figure size, the figure-level functions are parameterized by the size of each facet. And instead of setting the height and width of each facet, you control the height and *aspect* ratio (ratio of width to height). This parameterization makes it easy to control the size of the graphic without thinking about exactly how many rows and columns it will have, although it can be a source of confusion:", "_____no_output_____" ] ], [ [ "sns.relplot(x=\"time\", y=\"firing_rate\", col=\"align\",\n hue=\"choice\", size=\"coherence\", style=\"choice\",\n height=4.5, aspect=2 / 3,\n facet_kws=dict(sharex=False),\n kind=\"line\", legend=\"full\", data=dots);", "_____no_output_____" ] ], [ [ "The way you can tell whether a function is \"figure-level\" or \"axes-level\" is whether it takes an ``ax=`` parameter. You can also distinguish the two classes by their output type: axes-level functions return the matplotlib ``axes``, while figure-level functions return the :class:`FacetGrid`.\n\n\n.. _intro_dataset_funcs:\n\nVisualizing dataset structure\n-----------------------------\n\nThere are two other kinds of figure-level functions in seaborn that can be used to make visualizations with multiple plots. They are each oriented towards illuminating the structure of a dataset. One, :func:`jointplot`, focuses on a single relationship:", "_____no_output_____" ] ], [ [ "iris = sns.load_dataset(\"iris\")\nsns.jointplot(x=\"sepal_length\", y=\"petal_length\", data=iris);", "_____no_output_____" ] ], [ [ "The other, :func:`pairplot`, takes a broader view, showing all pairwise relationships and the marginal distributions, optionally conditioned on a categorical variable :", "_____no_output_____" ] ], [ [ "sns.pairplot(data=iris, hue=\"species\");", "_____no_output_____" ] ], [ [ "Both :func:`jointplot` and :func:`pairplot` have a few different options for visual representation, and they are built on top of classes that allow more thoroughly customized multi-plot figures (:class:`JointGrid` and :class:`PairGrid`, respectively).\n\n.. _intro_plot_customization:\n\nCustomizing plot appearance\n---------------------------\n\nThe plotting functions try to use good default aesthetics and add informative labels so that their output is immediately useful. But defaults can only go so far, and creating a fully-polished custom plot will require additional steps. Several levels of additional customization are possible. \n\nThe first way is to use one of the alternate seaborn themes to give your plots a different look. Setting a different theme or color palette will make it take effect for all plots:", "_____no_output_____" ] ], [ [ "sns.set(style=\"ticks\", palette=\"muted\")\nsns.relplot(x=\"total_bill\", y=\"tip\", col=\"time\",\n hue=\"smoker\", style=\"smoker\", size=\"size\",\n data=tips);", "_____no_output_____" ] ], [ [ "For figure-specific customization, all seaborn functions accept a number of optional parameters for switching to non-default semantic mappings, such as different colors. (Appropriate use of color is critical for effective data visualization, and seaborn has :ref:`extensive support <palette_tutorial>` for customizing color palettes).\n\nFinally, where there is a direct correspondence with an underlying matplotlib function (like :func:`scatterplot` and :meth:`matplotlib.axes.Axes.scatter`), additional keyword arguments will be passed through to the matplotlib layer:", "_____no_output_____" ] ], [ [ "sns.relplot(x=\"total_bill\", y=\"tip\", col=\"time\",\n hue=\"size\", style=\"smoker\", size=\"size\",\n palette=\"YlGnBu\", markers=[\"D\", \"o\"], sizes=(10, 125),\n edgecolor=\".2\", linewidth=.5, alpha=.75,\n data=tips);", "_____no_output_____" ] ], [ [ "In the case of :func:`relplot` and other figure-level functions, that means there are a few levels of indirection because :func:`relplot` passes its exta keyword arguments to the underlying seaborn axes-level function, which passes *its* extra keyword arguments to the underlying matplotlib function. So it might take some effort to find the right documentation for the parameters you'll need to use, but in principle an extremely detailed level of customization is possible.\n\nSome customization of figure-level functions can be accomplished through additional parameters that get passed to :class:`FacetGrid`, and you can use the methods on that object to control many other properties of the figure. For even more tweaking, you can access the matplotlib objects that the plot is drawn onto, which are stored as attributes:", "_____no_output_____" ] ], [ [ "g = sns.catplot(x=\"total_bill\", y=\"day\", hue=\"time\",\n height=3.5, aspect=1.5,\n kind=\"box\", legend=False, data=tips);\ng.add_legend(title=\"Meal\")\ng.set_axis_labels(\"Total bill ($)\", \"\")\ng.set(xlim=(0, 60), yticklabels=[\"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"])\ng.despine(trim=True)\ng.fig.set_size_inches(6.5, 3.5)\ng.ax.set_xticks([5, 15, 25, 35, 45, 55], minor=True);\nplt.setp(g.ax.get_yticklabels(), rotation=30);", "_____no_output_____" ] ], [ [ "Because the figure-level functions are oriented towards efficient exploration, using them to manage a figure that you need to be precisely sized and organized may take more effort than setting up the figure directly in matplotlib and using the corresponding axes-level seaborn function. Matplotlib has a comprehensive and powerful API; just about any attribute of the figure can be changed to your liking. The hope is that a combination of seaborn's high-level interface and matplotlib's deep customizability will allow you to quickly explore your data and create graphics that can be tailored into a `publication quality <https://github.com/wagnerlabpapers/Waskom_PNAS_2017>`_ final product.\n\n.. _intro_tidy_data:\n\nOrganizing datasets\n-------------------\n\nAs mentioned above, seaborn will be most powerful when your datasets have a particular organization. This format is alternately called \"long-form\" or \"tidy\" data and is described in detail by Hadley Wickham in this `academic paper <http://vita.had.co.nz/papers/tidy-data.html>`_. The rules can be simply stated:\n\n1. Each variable is a column\n2. Each observation is a row\n\nA helpful mindset for determining whether your data are tidy is to think backwards from the plot you want to draw. From this perspective, a \"variable\" is something that will be assigned a role in the plot. It may be useful to look at the example datasets and see how they are structured. For example, the first five rows of the \"tips\" dataset look like this:", "_____no_output_____" ] ], [ [ "tips.head()", "_____no_output_____" ] ], [ [ "In some domains, the tidy format might feel awkward at first. Timeseries data, for example, are sometimes stored with every timepoint as part of the same observational unit and appearing in the columns. The \"fmri\" dataset that we used :ref:`above <intro_stat_estimation>` illustrates how a tidy timeseries dataset has each timepoint in a different row:", "_____no_output_____" ] ], [ [ "fmri.head()", "_____no_output_____" ] ], [ [ "Many seaborn functions can plot wide-form data, but only with limited functionality. To take advantage of the features that depend on tidy-formatted data, you'll likely find the :func:`pandas.melt` function useful for \"un-pivoting\" a wide-form dataframe. More information and useful examples can be found `in this blog post <https://tomaugspurger.github.io/modern-5-tidy.html>`_ by one of the pandas developers.\n\n.. _intro_next_steps:\n\nNext steps\n----------\n\nYou have a few options for where to go next. You might first want to learn how to :ref:`install seaborn <installing>`. Once that's done, you can browse the :ref:`example gallery <example_gallery>` to get a broader sense for what kind of graphics seaborn can produce. Or you can read through the :ref:`official tutorial <tutorial>` for a deeper discussion of the different tools and what they are designed to accomplish. If you have a specific plot in mind and want to know how to make it, you could check out the :ref:`API reference <api_ref>`, which documents each function's parameters and shows many examples to illustrate usage.", "_____no_output_____" ], [ ".. raw:: html\n \n </div>", "_____no_output_____" ] ] ]
[ "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw", "code", "raw" ]
[ [ "raw" ], [ "code", "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "raw", "raw" ] ]
d0114e20d832a0df3dc382fb63a46bf27c9ef76b
2,029
ipynb
Jupyter Notebook
lectures/L6/Exercise_1.ipynb
HeyItsRiddhi/cs207_riddhi_shah
18d7d6f1fcad213ce35a93ee33c03620f8b06b65
[ "MIT" ]
null
null
null
lectures/L6/Exercise_1.ipynb
HeyItsRiddhi/cs207_riddhi_shah
18d7d6f1fcad213ce35a93ee33c03620f8b06b65
[ "MIT" ]
null
null
null
lectures/L6/Exercise_1.ipynb
HeyItsRiddhi/cs207_riddhi_shah
18d7d6f1fcad213ce35a93ee33c03620f8b06b65
[ "MIT" ]
null
null
null
29.838235
214
0.595367
[ [ [ "# Exercise 1\n\nIn this problem, you will write a closure to make writing messages easier. Suppose you write the following message all the time: \n```python \nprint(\"The correct answer is: {0:17.16f}\".format(answer))\n```\nWouldn't it be nicer to just write \n```python \ncorrect_answer_is(answer)\n```\nand have the message? Your task is to write a closure to accomplish that. Here's how everything should work:\n```python\ncorrect_answer_is = my_message(message)\ncorrect_answer_is(answer)\n```\nThe output should be: `The correct answer is: 42.0000000000000000.`\n\nNow change the message to something else. Notice that you don't need to re-write everything. You simply need to get a new message function from `my_message` and invoke your new function when you want to.\n\nYou should feel free to modify this in any way you like. Creativity is encouraged!", "_____no_output_____" ], [ "def my_message(message):\n def correct_answer_is(answer):\n c=(message,'{0:17.16f}'.format(answer))\n return c\n return correct_answer_is\n\ncorrect_answer_is = my_message(\"The correct answer is:\")\nprint(correct_answer_is(42))\ncorrect_answer_is = my_message(\"The answer is:\")\nprint(correct_answer_is(42))", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown" ] ]
d01154e95f95b8a658485b6b5832eeab895e74f6
265,468
ipynb
Jupyter Notebook
R Files/German(Overall).R.ipynb
tzuliu/Do-Scandals-Matter-An-Interrupted-Time-Series-Design-on-Three-Cases
fe1b9d7dae773aea1f1786109304e7eb0fcd023b
[ "MIT" ]
5
2018-07-23T02:51:13.000Z
2021-03-23T03:19:43.000Z
R Files/German(Overall).R.ipynb
tzuliu/Do-Scandals-Matter-An-Interrupted-Time-Series-Design-on-Three-Cases
fe1b9d7dae773aea1f1786109304e7eb0fcd023b
[ "MIT" ]
null
null
null
R Files/German(Overall).R.ipynb
tzuliu/Do-Scandals-Matter-An-Interrupted-Time-Series-Design-on-Three-Cases
fe1b9d7dae773aea1f1786109304e7eb0fcd023b
[ "MIT" ]
2
2021-04-09T14:02:22.000Z
2021-08-12T21:30:55.000Z
745.696629
129,402
0.938283
[ [ [ "rm(list=ls())\nlibrary(foreign)\nlibrary(TSA)\nlibrary(zoo)\nlibrary(eventstudies)\nlibrary(tseries)\n# library(strucchange) not available under certain versions\nlibrary(urca)\nlibrary(changepoint)\nlibrary(forecast)\nlibrary(MASS)", "Loading required package: leaps\nLoading required package: locfit\nlocfit 1.5-9.1 \t 2013-03-22\nLoading required package: mgcv\nLoading required package: nlme\nThis is mgcv 1.8-17. For overview type 'help(\"mgcv-package\")'.\nLoading required package: tseries\n\nAttaching package: ‘TSA’\n\nThe following objects are masked from ‘package:stats’:\n\n acf, arima\n\nThe following object is masked from ‘package:utils’:\n\n tar\n\n\nAttaching package: ‘zoo’\n\nThe following objects are masked from ‘package:base’:\n\n as.Date, as.Date.numeric\n\nLoading required package: xts\nLoading required package: boot\nSuccessfully loaded changepoint package version 2.2.2\n NOTE: Predefined penalty values changed in version 2.2. Previous penalty values with a postfix 1 i.e. SIC1 are now without i.e. SIC and previous penalties without a postfix i.e. SIC are now with a postfix 0 i.e. SIC0. See NEWS and help files for further details.\n\nAttaching package: ‘forecast’\n\nThe following objects are masked from ‘package:TSA’:\n\n fitted.Arima, plot.Arima\n\nThe following object is masked from ‘package:nlme’:\n\n getResponse\n\n" ] ], [ [ "read the data (only **Germany**)", "_____no_output_____" ] ], [ [ "ger <- read.dta(\"/...your folder/DAYPOLLS_GER.dta\")", "_____no_output_____" ] ], [ [ "create the date (based on stata)", "_____no_output_____" ] ], [ [ "ger$date <- seq(as.Date(\"1957-09-16\"),as.Date(\"2013-09-22\"), by=\"day\")", "_____no_output_____" ] ], [ [ "subset the data", "_____no_output_____" ] ], [ [ "geroa <- ger[ger$date >= \"2000-01-01\",]", "_____no_output_____" ] ], [ [ "reducing the data", "_____no_output_____" ] ], [ [ "geroar <- cbind(geroa$poll_p1_ipo, geroa$poll_p4_ipo)", "_____no_output_____" ] ], [ [ "create the daily times series data", "_____no_output_____" ] ], [ [ "geroar <- zoo(geroar, geroa$date)", "_____no_output_____" ] ], [ [ "name the column (don't need for date)", "_____no_output_____" ] ], [ [ "colnames(geroar) <- c(\"CDU/CSU\", \"FDP\")", "_____no_output_____" ] ], [ [ "searching for the index of the date when scandal happend", "_____no_output_____" ] ], [ [ "which(time(geroar)==\"2010-12-02\")", "_____no_output_____" ], [ "which(time(geroar)==\"2011-02-16\")", "_____no_output_____" ] ], [ [ "create values for vline, one for each panel", "_____no_output_____" ] ], [ [ "v.panel <- function(x, ...){\n\tlines(x, ...)\n\tpanel.number <- parent.frame()$panel.number\n\tabline(v = vlines[panel.number], col = \"red\", lty=2)\n}", "_____no_output_____" ] ], [ [ "plot **CDU/CSU** after 2000", "_____no_output_____" ] ], [ [ "plot(geroar$CDU, main=\"CDU/CSU after 2000\", xlab=\"Time\", ylab=\"Approval Rate\")\nabline(v=time(geroar$CDU)[3989], lty=2, col=\"red\")\nabline(v=time(geroar$CDU)[4065], lty=2, col=\"red\")", "_____no_output_____" ] ], [ [ "plot **FDP** after 2000", "_____no_output_____" ] ], [ [ "plot(geroar$FDP, main=\"FDP after 2000\", xlab=\"Time\", ylab=\"Approval Rate\")\nabline(v=time(geroar$CDU)[3989], lty=2, col=\"red\")\nabline(v=time(geroar$CDU)[4065], lty=2, col=\"red\")", "_____no_output_____" ] ], [ [ "Go to **German(CDU)2M1**, **German(FDP)2M1**, **German(CDU)2M2**, and **German(FDP)2M2**", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d01155b4730b1289f3fea7908e28a37fc2b256dd
799,179
ipynb
Jupyter Notebook
docs/lectures/lecture8/lab5/cs109b-lab5-cnn-solutions.ipynb
rahuliem/2019-CS109B-1
bacb726bc6ce2887da05d76d5f0f481e0b062db1
[ "MIT" ]
1
2019-03-15T00:13:38.000Z
2019-03-15T00:13:38.000Z
docs/lectures/lecture8/lab5/cs109b-lab5-cnn-solutions.ipynb
rahuliem/2019-CS109B-1
bacb726bc6ce2887da05d76d5f0f481e0b062db1
[ "MIT" ]
null
null
null
docs/lectures/lecture8/lab5/cs109b-lab5-cnn-solutions.ipynb
rahuliem/2019-CS109B-1
bacb726bc6ce2887da05d76d5f0f481e0b062db1
[ "MIT" ]
null
null
null
482.887613
123,796
0.937251
[ [ [ "# <img style=\"float: left; padding-right: 10px; width: 45px\" src=\"https://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/iacs.png\"> CS-109B Introduction to Data Science\n## Lab 5: Convolutional Neural Networks\n\n**Harvard University**<br>\n**Spring 2019**<br>\n**Lab instructor:** Eleni Kaxiras<br>\n**Instructors:** Pavlos Protopapas and Mark Glickman<br>\n**Authors:** Eleni Kaxiras, Pavlos Protopapas, Patrick Ohiomoba, and Davis Sontag", "_____no_output_____" ] ], [ [ "# RUN THIS CELL TO PROPERLY HIGHLIGHT THE EXERCISES\nimport requests\nfrom IPython.core.display import HTML\nstyles = requests.get(\"https://raw.githubusercontent.com/Harvard-IACS/2019-CS109B/master/content/styles/cs109.css\").text\nHTML(styles)", "_____no_output_____" ] ], [ [ "## Learning Goals\n\nIn this lab we will look at Convolutional Neural Networks (CNNs), and their building blocks.\n\nBy the end of this lab, you should:\n\n- know how to put together the building blocks used in CNNs - such as convolutional layers and pooling layers - in `keras` with an example.\n- have a good undertanding on how images, a common type of data for a CNN, are represented in the computer and how to think of them as arrays of numbers. \n- be familiar with preprocessing images with `keras` and `sckit-learn`.\n- use `keras-viz` to produce Saliency maps. \n- learn best practices for configuring the hyperparameters of a CNN.\n- run your first CNN and see the error rate.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = (5,5)\n\nimport numpy as np\nfrom scipy.optimize import minimize\n\nimport tensorflow as tf\nimport keras\nfrom keras import layers\nfrom keras import models\nfrom keras import utils\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom keras.layers import Flatten\nfrom keras.layers import Dropout\nfrom keras.layers import Activation\nfrom keras.regularizers import l2\nfrom keras.optimizers import SGD\nfrom keras.optimizers import RMSprop\nfrom keras import datasets\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.callbacks import History\n\nfrom keras import losses\nfrom keras.datasets import mnist\nfrom keras.utils import to_categorical\n\nfrom sklearn.utils import shuffle\n\nprint(tf.VERSION)\nprint(tf.keras.__version__)\n\n%matplotlib inline", "1.12.0\n2.1.6-tf\n" ] ], [ [ "## Prologue: `keras-viz` Visualization Toolkit\n\n`keras-vis` is a high-level toolkit for visualizing and debugging your trained keras neural net models. Currently supported visualizations include:\n\n- Activation maximization\n- **Saliency maps** \n- Class activation maps\n\nAll visualizations by default support N-dimensional image inputs. i.e., it generalizes to N-dim image inputs to your model. Compatible with both theano and tensorflow backends with 'channels_first', 'channels_last' data format.\n\nRead the documentation at https://raghakot.github.io/keras-vis.https://github.com/raghakot/keras-vis\n\nTo install use `pip install git+https://github.com/raghakot/keras-vis.git --upgrade`", "_____no_output_____" ], [ "## SEAS JupyterHub\n\n[Instructions for Using SEAS JupyterHub](https://canvas.harvard.edu/courses/48088/pages/instructions-for-using-seas-jupyterhub)\n\nSEAS and FAS are providing you with a platform in AWS to use for the class (accessible from the 'Jupyter' menu link in Canvas). These are AWS p2 instances with a GPU, 10GB of disk space, and 61 GB of RAM, for faster training for your networks. Most of the libraries such as keras, tensorflow, pandas, etc. are pre-installed. If a library is missing you may install it via the Terminal.\n\n**NOTE : The AWS platform is funded by SEAS and FAS for the purposes of the class. It is not running against your individual credit. You are not allowed to use it for purposes not related to this course.**\n\n**Help us keep this service: Make sure you stop your instance as soon as you do not need it.**\n\n![aws-dog](fig/aws-dog.jpeg)", "_____no_output_____" ], [ "## Part 1: Parts of a Convolutional Neural Net\n\nThere are three types of layers in a Convolutional Neural Network:\n\n- Convolutional Layers\n- Pooling Layers.\n- Dropout Layers.\n- Fully Connected Layers.\n\n### a. Convolutional Layers.\n\nConvolutional layers are comprised of **filters** and **feature maps**. The filters are essentially the **neurons** of the layer. They have the weights and produce the input for the next layer. The feature map is the output of one filter applied to the previous layer. \n\nThe fundamental difference between a densely connected layer and a convolution layer is that dense layers learn global patterns in their input feature space (for example, for an MNIST digit, patterns involving all pixels), whereas convolution layers learn local patterns: in the case of images, patterns found in small 2D windows of the inputs called *receptive fields*. \n\nThis key characteristic gives convnets two interesting properties:\n\n- The patterns they learn are **translation invariant**. After learning a certain pattern in the lower-right corner of a picture, a convnet can recognize it anywhere: for example, in the upper-left corner. A densely connected network would have to learn the pattern anew if it appeared at a new location. This makes convnets data efficient when processing images (because the visual world is fundamentally translation invariant): they need fewer training samples to learn representations that have generalization power.\n\n- They can learn **spatial hierarchies of patterns**. A first convolution layer will learn small local patterns such as edges, a second convolution layer will learn larger patterns made of the features of the first layers, and so on. This allows convnets to efficiently learn increasingly complex and abstract visual concepts (because the visual world is fundamentally spatially hierarchical).\n\nConvolutions operate over 3D tensors, called feature maps, with two spatial axes (height and width) as well as a depth axis (also called the channels axis). For an RGB image, the dimension of the depth axis is 3, because the image has three color channels: red, green, and blue. For a black-and-white picture, like the MNIST digits, the depth is 1 (levels of gray). The convolution operation extracts patches from its input feature map and applies the same transformation to all of these patches, producing an output feature map. This output feature map is still a 3D tensor: it has a width and a height. Its depth can be arbitrary, because the output depth is a parameter of the layer, and the different channels in that depth axis no longer stand for specific colors as in RGB input; rather, they stand for filters. Filters encode specific aspects of the input data: at a high level, a single filter could encode the concept “presence of a face in the input,” for instance.\n\nIn the MNIST example that we will see, the first convolution layer takes a feature map of size (28, 28, 1) and outputs a feature map of size (26, 26, 32): it computes 32 filters over its input. Each of these 32 output channels contains a 26×26 grid of values, which is a response map of the filter over the input, indicating the response of that filter pattern at different locations in the input. \n\nConvolutions are defined by two key parameters:\n- Size of the patches extracted from the inputs. These are typically 3×3 or 5×5 \n- The number of filters computed by the convolution. \n\n**Padding**: One of \"valid\", \"causal\" or \"same\" (case-insensitive). \"valid\" means \"no padding\". \"same\" results in padding the input such that the output has the same length as the original input. \"causal\" results in causal (dilated) convolutions,\n\nIn `keras` see [convolutional layers](https://keras.io/layers/convolutional/)\n\n**keras.layers.Conv2D**(filters, kernel_size, strides=(1, 1), padding='valid', activation=None, use_bias=True, \n kernel_initializer='glorot_uniform', data_format='channels_last', \n bias_initializer='zeros')", "_____no_output_____" ], [ "#### How are the values in feature maps calculated?\n\n![title](fig/convolution-many-filters.png)", "_____no_output_____" ], [ "### Exercise 1:\n\n - Compute the operations by hand (assuming zero padding and same arrays for all channels) to produce the first element of the 4x4 feature map. How did we get the 4x4 output size?\n - Write this Conv layer in keras ", "_____no_output_____" ], [ "-- your answer here\n", "_____no_output_____" ], [ "### b. Pooling Layers.\n\nPooling layers are also comprised of filters and feature maps. Let's say the pooling layer has a 2x2 receptive field and a stride of 2. This stride results in feature maps that are one half the size of the input feature maps. We can use a max() operation for each receptive field. \n\nIn `keras` see [pooling layers](https://keras.io/layers/pooling/)\n\n**keras.layers.MaxPooling2D**(pool_size=(2, 2), strides=None, padding='valid', data_format=None)\n\n![Max Pool](fig/MaxPool.png)", "_____no_output_____" ], [ "### c. Dropout Layers.\n\nDropout consists in randomly setting a fraction rate of input units to 0 at each update during training time, which helps prevent overfitting.\n\nIn `keras` see [Dropout layers](https://keras.io/layers/core/)\n\nkeras.layers.Dropout(rate, seed=None)\n\nrate: float between 0 and 1. Fraction of the input units to drop.<br>\nseed: A Python integer to use as random seed.\n\nReferences\n\n[Dropout: A Simple Way to Prevent Neural Networks from Overfitting](http://www.jmlr.org/papers/volume15/srivastava14a/srivastava14a.pdf)", "_____no_output_____" ], [ "### d. Fully Connected Layers.\n\nA fully connected layer flattens the square feature map into a vector. Then we can use a sigmoid or softmax activation function to output probabilities of classes. \n\nIn `keras` see [FC layers](https://keras.io/layers/core/)\n\n**keras.layers.Dense**(units, activation=None, use_bias=True, \n kernel_initializer='glorot_uniform', bias_initializer='zeros')", "_____no_output_____" ], [ "#### IT'S ALL ABOUT THE HYPERPARAMETERS!\n\n- stride\n- size of filter\n- number of filters\n- poolsize", "_____no_output_____" ], [ "## Part 2: Preprocessing the data\n### Taking a look at how images are represented in a computer using a photo of a Picasso sculpture", "_____no_output_____" ] ], [ [ "img = plt.imread('data/picasso.png')\nimg.shape", "_____no_output_____" ], [ "img[1,:,1]", "_____no_output_____" ], [ "print(type(img[50][0][0]))", "<class 'numpy.float32'>\n" ], [ "# let's see the image\nimgplot = plt.imshow(img)", "_____no_output_____" ] ], [ [ "#### Visualizing the channels", "_____no_output_____" ] ], [ [ "R_img = img[:,:,0]\nG_img = img[:,:,1]\nB_img = img[:,:,2]\nplt.subplot(221)\nplt.imshow(R_img, cmap=plt.cm.Reds)\nplt.subplot(222)\nplt.imshow(G_img, cmap=plt.cm.Greens)\nplt.subplot(223)\nplt.imshow(B_img, cmap=plt.cm.Blues) \nplt.subplot(224)\nplt.imshow(img) \nplt.show()", "_____no_output_____" ] ], [ [ "More on preprocessing data below!", "_____no_output_____" ], [ "If you want to learn more: [Image Processing with Python and Scipy](http://prancer.physics.louisville.edu/astrowiki/index.php/Image_processing_with_Python_and_SciPy)", "_____no_output_____" ], [ "## Part 3: Putting the Parts together to make a small ConvNet Model\n\nLet's put all the parts together to make a convnet for classifying our good old MNIST digits.", "_____no_output_____" ] ], [ [ "# Load data and preprocess\n(train_images, train_labels), (test_images, test_labels) = mnist.load_data() # load MNIST data\ntrain_images.shape", "_____no_output_____" ], [ "train_images.max(), train_images.min()", "_____no_output_____" ], [ "train_images = train_images.reshape((60000, 28, 28, 1)) # Reshape to get third dimension\ntrain_images = train_images.astype('float32') / 255 # Normalize between 0 and 1\n\ntest_images = test_images.reshape((10000, 28, 28, 1)) # Reshape to get third dimension\ntest_images = test_images.astype('float32') / 255 # Normalize between 0 and 1\n\n# Convert labels to categorical data\ntrain_labels = to_categorical(train_labels)\ntest_labels = to_categorical(test_labels)", "_____no_output_____" ], [ "mnist_cnn_model = models.Sequential() # Create sequential model\n\n# Add network layers\nmnist_cnn_model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))\nmnist_cnn_model.add(layers.MaxPooling2D((2, 2)))\nmnist_cnn_model.add(layers.Conv2D(64, (3, 3), activation='relu')) \nmnist_cnn_model.add(layers.MaxPooling2D((2, 2)))\nmnist_cnn_model.add(layers.Conv2D(64, (3, 3), activation='relu'))", "_____no_output_____" ] ], [ [ "The next step is to feed the last output tensor (of shape (3, 3, 64)) into a densely connected classifier network like those you’re already familiar with: a stack of Dense layers. These classifiers process vectors, which are 1D, whereas the current output is a 3D tensor. First we have to flatten the 3D outputs to 1D, and then add a few Dense layers on top.", "_____no_output_____" ] ], [ [ "mnist_cnn_model.add(layers.Flatten())\nmnist_cnn_model.add(layers.Dense(64, activation='relu'))\nmnist_cnn_model.add(layers.Dense(10, activation='softmax'))\n\nmnist_cnn_model.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_1 (Conv2D) (None, 26, 26, 32) 320 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 13, 13, 32) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 11, 11, 64) 18496 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 5, 5, 64) 0 \n_________________________________________________________________\nconv2d_3 (Conv2D) (None, 3, 3, 64) 36928 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 576) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 64) 36928 \n_________________________________________________________________\ndense_2 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 93,322\nTrainable params: 93,322\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "# Compile model\nmnist_cnn_model.compile(optimizer='rmsprop',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n# Fit the model\nmnist_cnn_model.fit(train_images, train_labels, epochs=5, batch_size=64)\n\n# Evaluate the model on the test data:\ntest_loss, test_acc = mnist_cnn_model.evaluate(test_images, test_labels)\ntest_acc", "Epoch 1/5\n60000/60000 [==============================] - 21s 343us/step - loss: 0.1780 - acc: 0.9456\nEpoch 2/5\n60000/60000 [==============================] - 21s 352us/step - loss: 0.0479 - acc: 0.9854\nEpoch 3/5\n60000/60000 [==============================] - 25s 419us/step - loss: 0.0341 - acc: 0.9896\nEpoch 4/5\n60000/60000 [==============================] - 21s 349us/step - loss: 0.0254 - acc: 0.9922\nEpoch 5/5\n60000/60000 [==============================] - 21s 347us/step - loss: 0.0200 - acc: 0.9941\n10000/10000 [==============================] - 1s 124us/step\n" ] ], [ [ "A densely connected network (MLP) running MNIST usually has a test accuracy of 97.8%, whereas our basic convnet has a test accuracy of 99.03%: we decreased the error rate by 68% (relative) with only 5 epochs. Not bad! But why does this simple convnet work so well, compared to a densely connected model? The answer is above on how convolutional layers work!", "_____no_output_____" ], [ "### Data Preprocessing : Meet the `ImageDataGenerator` class in `keras` [(docs)](https://keras.io/preprocessing/image/)", "_____no_output_____" ], [ "The MNIST and other pre-loaded dataset are formatted in a way that is almost ready for feeding into the model. What about plain images? They should be formatted into appropriately preprocessed floating-point tensors before being fed into the network.\n\nThe Dogs vs. Cats dataset that you’ll use isn’t packaged with Keras. It was made available by Kaggle as part of a computer-vision competition in late 2013, back when convnets weren’t mainstream. The data has been downloaded for you from https://www.kaggle.com/c/dogs-vs-cats/data The pictures are medium-resolution color JPEGs. ", "_____no_output_____" ] ], [ [ "# TODO: set your base dir to your correct local location\nbase_dir = 'data/cats_and_dogs_small'\n\nimport os, shutil\n\n# Set up directory information\n\ntrain_dir = os.path.join(base_dir, 'train')\nvalidation_dir = os.path.join(base_dir, 'validation')\ntest_dir = os.path.join(base_dir, 'test')\n\ntrain_cats_dir = os.path.join(train_dir, 'cats')\ntrain_dogs_dir = os.path.join(train_dir, 'dogs')\n\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\n\ntest_cats_dir = os.path.join(test_dir, 'cats')\ntest_dogs_dir = os.path.join(test_dir, 'dogs')\n\nprint('total training cat images:', len(os.listdir(train_cats_dir))) \nprint('total training dog images:', len(os.listdir(train_dogs_dir))) \nprint('total validation cat images:', len(os.listdir(validation_cats_dir)))\nprint('total validation dog images:', len(os.listdir(validation_dogs_dir)))\nprint('total test cat images:', len(os.listdir(test_cats_dir))) \nprint('total test dog images:', len(os.listdir(test_dogs_dir))) ", "total training cat images: 1000\ntotal training dog images: 1000\ntotal validation cat images: 500\ntotal validation dog images: 500\ntotal test cat images: 500\ntotal test dog images: 500\n" ] ], [ [ "So you do indeed have 2,000 training images, 1,000 validation images, and 1,000 test images. Each split contains the same number of samples from each class: this is a balanced binary-classification problem, which means classification accuracy will be an appropriate measure of success.", "_____no_output_____" ], [ "#### Building the network", "_____no_output_____" ] ], [ [ "from keras import layers\nfrom keras import models\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu',\n input_shape=(150, 150, 3)))\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(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_4 (Conv2D) (None, 148, 148, 32) 896 \n_________________________________________________________________\nmax_pooling2d_3 (MaxPooling2 (None, 74, 74, 32) 0 \n_________________________________________________________________\nconv2d_5 (Conv2D) (None, 72, 72, 64) 18496 \n_________________________________________________________________\nmax_pooling2d_4 (MaxPooling2 (None, 36, 36, 64) 0 \n_________________________________________________________________\nconv2d_6 (Conv2D) (None, 34, 34, 128) 73856 \n_________________________________________________________________\nmax_pooling2d_5 (MaxPooling2 (None, 17, 17, 128) 0 \n_________________________________________________________________\nconv2d_7 (Conv2D) (None, 15, 15, 128) 147584 \n_________________________________________________________________\nmax_pooling2d_6 (MaxPooling2 (None, 7, 7, 128) 0 \n_________________________________________________________________\nflatten_2 (Flatten) (None, 6272) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 512) 3211776 \n_________________________________________________________________\ndense_4 (Dense) (None, 1) 513 \n=================================================================\nTotal params: 3,453,121\nTrainable params: 3,453,121\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "For the compilation step, you’ll go with the RMSprop optimizer. Because you ended the network with a single sigmoid unit, you’ll use binary crossentropy as the loss.", "_____no_output_____" ] ], [ [ "from keras import optimizers\nmodel.compile(loss='binary_crossentropy',\n optimizer=optimizers.RMSprop(lr=1e-4),\n metrics=['acc'])", "_____no_output_____" ] ], [ [ "The steps for getting it into the network are roughly as follows:\n\n1. Read the picture files.\n2. Decode the JPEG content to RGB grids of pixels.\n3. Convert these into floating-point tensors.\n4. Rescale the pixel values (between 0 and 255) to the [0, 1] interval (as you know, neural networks prefer to deal with small input values).\n\nIt may seem a bit daunting, but fortunately Keras has utilities to take care of these steps automatically with the class `ImageDataGenerator`, which lets you quickly set up Python generators that can automatically turn image files on disk into batches of preprocessed tensors. This is what you’ll use here.", "_____no_output_____" ] ], [ [ "from keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size=(150, 150),\n batch_size=20,\n class_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_dir,\n target_size=(150, 150),\n batch_size=20,\n class_mode='binary')", "Found 2000 images belonging to 2 classes.\nFound 1000 images belonging to 2 classes.\n" ] ], [ [ "Let’s look at the output of one of these generators: it yields batches of 150×150 RGB images (shape (20, 150, 150, 3)) and binary labels (shape (20,)). There are 20 samples in each batch (the batch size). Note that the generator yields these batches indefinitely: it loops endlessly over the images in the target folder. For this reason, you need to break the iteration loop at some point:", "_____no_output_____" ] ], [ [ "for data_batch, labels_batch in train_generator:\n print('data batch shape:', data_batch.shape)\n print('labels batch shape:', labels_batch.shape)\n break", "data batch shape: (20, 150, 150, 3)\nlabels batch shape: (20,)\n" ] ], [ [ "Let’s fit the model to the data using the generator. You do so using the `.fit_generator` method, the equivalent of `.fit` for data generators like this one. It expects as its first argument a Python generator that will yield batches of inputs and targets indefinitely, like this one does. \n\nBecause the data is being generated endlessly, the Keras model needs to know how many samples to draw from the generator before declaring an epoch over. This is the role of the `steps_per_epoch` argument: after having drawn steps_per_epoch batches from the generator—that is, after having run for steps_per_epoch gradient descent steps - the fitting process will go to the next epoch. In this case, batches are 20 samples, so it will take 100 batches until you see your target of 2,000 samples.\n\nWhen using fit_generator, you can pass a validation_data argument, much as with the fit method. It’s important to note that this argument is allowed to be a data generator, but it could also be a tuple of Numpy arrays. If you pass a generator as validation_data, then this generator is expected to yield batches of validation data endlessly; thus you should also specify the validation_steps argument, which tells the process how many batches to draw from the validation generator for evaluation", "_____no_output_____" ] ], [ [ "history = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n epochs=5, # TODO: should be 30\n validation_data=validation_generator,\n validation_steps=50)\n\n\n# It’s good practice to always save your models after training.\nmodel.save('cats_and_dogs_small_1.h5')", "Epoch 1/5\n100/100 [==============================] - 55s 549ms/step - loss: 0.6885 - acc: 0.5320 - val_loss: 0.6711 - val_acc: 0.6220\nEpoch 2/5\n100/100 [==============================] - 56s 558ms/step - loss: 0.6620 - acc: 0.5950 - val_loss: 0.6500 - val_acc: 0.6170\nEpoch 3/5\n100/100 [==============================] - 56s 562ms/step - loss: 0.6198 - acc: 0.6510 - val_loss: 0.6771 - val_acc: 0.5790\nEpoch 4/5\n100/100 [==============================] - 57s 567ms/step - loss: 0.5733 - acc: 0.6955 - val_loss: 0.5993 - val_acc: 0.6740\nEpoch 5/5\n100/100 [==============================] - 57s 566ms/step - loss: 0.5350 - acc: 0.7305 - val_loss: 0.6140 - val_acc: 0.6520\n" ] ], [ [ "Let’s plot the loss and accuracy of the model over the training and validation data during training:", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(1, 1, figsize=(10,6))\nax.plot((history.history['acc']), 'r', label='train')\nax.plot((history.history['val_acc']), 'b' ,label='val')\nax.set_xlabel(r'Epoch', fontsize=20)\nax.set_ylabel(r'Accuracy', fontsize=20)\nax.legend()\nax.tick_params(labelsize=20)", "_____no_output_____" ] ], [ [ "Let's try data augmentation", "_____no_output_____" ] ], [ [ "datagen = ImageDataGenerator(\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')", "_____no_output_____" ] ], [ [ "These are just a few of the options available (for more, see the Keras documentation). \nLet’s quickly go over this code:\n\n- rotation_range is a value in degrees (0–180), a range within which to randomly rotate pictures.\n- width_shift and height_shift are ranges (as a fraction of total width or height) within which to randomly translate pictures vertically or horizontally.\n- shear_range is for randomly applying shearing transformations.\n- zoom_range is for randomly zooming inside pictures.\n- horizontal_flip is for randomly flipping half the images horizontally—relevant when there are no assumptions of - horizontal asymmetry (for example, real-world pictures).\n- fill_mode is the strategy used for filling in newly created pixels, which can appear after a rotation or a width/height shift. \n\nLet’s look at the augmented images", "_____no_output_____" ] ], [ [ "from keras.preprocessing import image\nfnames = [os.path.join(train_dogs_dir, fname) for\n fname in os.listdir(train_dogs_dir)]\nimg_path = fnames[3] # Chooses one image to augment\nimg = image.load_img(img_path, target_size=(150, 150))\n# Reads the image and resizes it\nx = image.img_to_array(img) # Converts it to a Numpy array with shape (150, 150, 3) \nx = x.reshape((1,) + x.shape) # Reshapes it to (1, 150, 150, 3)\ni=0\nfor batch in datagen.flow(x, batch_size=1):\n plt.figure(i)\n imgplot = plt.imshow(image.array_to_img(batch[0]))\n i += 1\n if i % 4 == 0:\n break\n\nplt.show()", "_____no_output_____" ] ], [ [ "If you train a new network using this data-augmentation configuration, the network will never see the same input twice. But the inputs it sees are still heavily intercorrelated, because they come from a small number of original images—you can’t produce new information, you can only remix existing information. As such, this may not be enough to completely get rid of overfitting. To further fight overfitting, you’ll also add a **Dropout** layer to your model right before the densely connected classifier.", "_____no_output_____" ] ], [ [ "model = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu',\n input_shape=(150, 150, 3)))\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(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy',\n optimizer=optimizers.RMSprop(lr=1e-4),\n metrics=['acc'])", "_____no_output_____" ], [ "# Let’s train the network using data augmentation and dropout.\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n# Note that the validation data shouldn’t be augmented!\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size=(150, 150),\n batch_size=32,\n class_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_dir,\n target_size=(150, 150),\n batch_size=32,\n class_mode='binary')\n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n epochs=5, # TODO: should be 100\n validation_data=validation_generator,\n validation_steps=50)\n\nmodel.save('cats_and_dogs_small_2.h5')", "Found 2000 images belonging to 2 classes.\nFound 1000 images belonging to 2 classes.\nEpoch 1/5\n100/100 [==============================] - 94s 935ms/step - loss: 0.6902 - acc: 0.5294 - val_loss: 0.7003 - val_acc: 0.4924\nEpoch 2/5\n100/100 [==============================] - 88s 882ms/step - loss: 0.6763 - acc: 0.5703 - val_loss: 0.7350 - val_acc: 0.5090\nEpoch 3/5\n100/100 [==============================] - 90s 899ms/step - loss: 0.6681 - acc: 0.5816 - val_loss: 0.6458 - val_acc: 0.6098\nEpoch 4/5\n100/100 [==============================] - 88s 877ms/step - loss: 0.6496 - acc: 0.6241 - val_loss: 0.6431 - val_acc: 0.6192\nEpoch 5/5\n100/100 [==============================] - 89s 886ms/step - loss: 0.6298 - acc: 0.6369 - val_loss: 0.5897 - val_acc: 0.6580\n" ] ], [ [ "And let’s plot the results again. Thanks to data augmentation and dropout, you’re no longer overfitting: the training curves are closely tracking the validation curves. You now reach an accuracy of 82%, a 15% relative improvement over the non-regularized model. (Note: these numbers are for 100 epochs..)", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(1, 1, figsize=(10,6))\nax.plot((history.history['acc']), 'r', label='train')\nax.plot((history.history['val_acc']), 'b' ,label='val')\nax.set_xlabel(r'Epoch', fontsize=20)\nax.set_ylabel(r'Accuracy', fontsize=20)\nax.legend()\nax.tick_params(labelsize=20)", "_____no_output_____" ] ], [ [ "By using regularization techniques even further, and by tuning the network’s parameters (such as the number of filters per convolution layer, or the number of layers in the network), you may be able to get an even better accuracy, likely up to 86% or 87%. But it would prove difficult to go any higher just by training your own convnet from scratch, because you have so little data to work with. As a next step to improve your accuracy on this problem, you’ll have to use a pretrained model.", "_____no_output_____" ], [ "## Part 4: keras viz toolkit", "_____no_output_____" ], [ "https://github.com/raghakot/keras-vis/blob/master/examples/mnist/attention.ipynb", "_____no_output_____" ] ], [ [ "class_idx = 0\nindices = np.where(test_labels[:, class_idx] == 1.)[0]\n\n# pick some random input from here.\nidx = indices[0]\n\n# Lets sanity check the picked image.\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (18, 6)\n\nplt.imshow(test_images[idx][..., 0])", "_____no_output_____" ], [ "input_shape=(28, 28, 1)\nnum_classes = 10\nbatch_size = 128\nepochs = 5\n\nmodel = Sequential()\nmodel.add(layers.Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\nmodel.add(layers.Dropout(0.25))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(128, activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(num_classes, activation='softmax', name='preds'))\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adam(),\n metrics=['accuracy'])\n\nmodel.fit(train_images, train_labels,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(test_images, test_labels))\n\nscore = model.evaluate(test_images, test_labels, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])", "Train on 60000 samples, validate on 10000 samples\nEpoch 1/5\n60000/60000 [==============================] - 81s 1ms/step - loss: 0.2462 - acc: 0.9248 - val_loss: 0.0524 - val_acc: 0.9828\nEpoch 2/5\n60000/60000 [==============================] - 86s 1ms/step - loss: 0.0905 - acc: 0.9726 - val_loss: 0.0391 - val_acc: 0.9857\nEpoch 3/5\n60000/60000 [==============================] - 83s 1ms/step - loss: 0.0691 - acc: 0.9788 - val_loss: 0.0376 - val_acc: 0.9876\nEpoch 4/5\n60000/60000 [==============================] - 81s 1ms/step - loss: 0.0544 - acc: 0.9832 - val_loss: 0.0307 - val_acc: 0.9896\nEpoch 5/5\n60000/60000 [==============================] - 84s 1ms/step - loss: 0.0467 - acc: 0.9854 - val_loss: 0.0305 - val_acc: 0.9904\nTest loss: 0.030515316201592212\nTest accuracy: 0.9904\n" ], [ "from vis.visualization import visualize_saliency\nfrom vis.utils import utils\nfrom keras import activations\n\n# Utility to search for layer index by name. \n# Alternatively we can specify this as -1 since it corresponds to the last layer.\nlayer_idx = utils.find_layer_idx(model, 'preds')", "_____no_output_____" ], [ "plt.rcParams[\"figure.figsize\"] = (5,5)\nfrom vis.visualization import visualize_cam\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# This corresponds to the Dense linear layer.\nfor class_idx in np.arange(10): \n indices = np.where(test_labels[:, class_idx] == 1.)[0]\n idx = indices[0]\n\n f, ax = plt.subplots(1, 4)\n ax[0].imshow(test_images[idx][..., 0])\n \n for i, modifier in enumerate([None, 'guided', 'relu']):\n grads = visualize_cam(model, layer_idx, filter_indices=class_idx, \n seed_input=test_images[idx], backprop_modifier=modifier) \n if modifier is None:\n modifier = 'vanilla'\n ax[i+1].set_title(modifier) \n ax[i+1].imshow(grads, cmap='jet')", "_____no_output_____" ] ], [ [ "#### References and Acknowledgements\nThe cats and dogs part of this lab is based on the book Deep Learning with Python, Chapter 5 written by the Francois Chollet, the author of Keras. It is a very practical introduction to Deep Learning. It is appropriate for those with some Python knowledge who want to start with machine learning.\n\nThe saliency maps are from https://github.com/raghakot/keras-vis/blob/master/examples/mnist/attention.ipynb", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
d01167309dcf91d67bcf58ddeea245b52923e32e
3,021
ipynb
Jupyter Notebook
practice 1-checkpoint.ipynb
adaobi15/adaobiCSC102
889419ead330a8b469e95cee7febba2d66635284
[ "MIT" ]
null
null
null
practice 1-checkpoint.ipynb
adaobi15/adaobiCSC102
889419ead330a8b469e95cee7febba2d66635284
[ "MIT" ]
null
null
null
practice 1-checkpoint.ipynb
adaobi15/adaobiCSC102
889419ead330a8b469e95cee7febba2d66635284
[ "MIT" ]
null
null
null
19.616883
294
0.461768
[ [ [ "names = [\"ada\", \"sope\", \"james\"]\nprint (names[0] + \"\\n\" + names[1] + \"\\n\"+ names[2])", "ada\nsope\njames\n" ], [ "#iterating through a list using for loop \nnames = [\"ada\", \"sope\", \"james\"]\ni = 0\n\nfor i in names:\n print (i)\n", "_____no_output_____" ], [ "#tuples are not mutable\nnames = [\"ada\", \"sope\", \"james\"]\n\nnames[0] = \"adaobi\"\n\nprint (names)\n\n\"james\" in names", "['adaobi', 'sope', 'james']\n" ], [ "a = \"adaobi\"\nprint (a[0] + a[1] + a[2] )\n", "ada\n" ], [ "a = \"adaobi\"\nb =\"arinzechi\"\n\nprint (a +\" \"+ b)", "adaobi arinzechi\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
d01185baf3cebecc54735e16f3a9d821703c60a4
48,720
ipynb
Jupyter Notebook
colors_overview.ipynb
MallikaKhullar/Stanford_CS224u
36dc3394408c698a524c0d508923eb7934a862ce
[ "Apache-2.0" ]
1
2022-02-07T21:41:10.000Z
2022-02-07T21:41:10.000Z
colors_overview.ipynb
MallikaKhullar/Stanford_CS224u
36dc3394408c698a524c0d508923eb7934a862ce
[ "Apache-2.0" ]
null
null
null
colors_overview.ipynb
MallikaKhullar/Stanford_CS224u
36dc3394408c698a524c0d508923eb7934a862ce
[ "Apache-2.0" ]
1
2021-12-10T00:52:35.000Z
2021-12-10T00:52:35.000Z
27.619048
644
0.589409
[ [ [ "# Pragmatic color describers", "_____no_output_____" ] ], [ [ "__author__ = \"Christopher Potts\"\n__version__ = \"CS224u, Stanford, Spring 2020\"", "_____no_output_____" ] ], [ [ "## Contents\n\n1. [Overview](#Overview)\n1. [Set-up](#Set-up)\n1. [The corpus](#The-corpus)\n 1. [Corpus reader](#Corpus-reader)\n 1. [ColorsCorpusExample instances](#ColorsCorpusExample-instances)\n 1. [Displaying examples](#Displaying-examples)\n 1. [Color representations](#Color-representations)\n 1. [Utterance texts](#Utterance-texts)\n 1. [Far, Split, and Close conditions](#Far,-Split,-and-Close-conditions)\n1. [Toy problems for development work](#Toy-problems-for-development-work)\n1. [Core model](#Core-model)\n 1. [Toy dataset illustration](#Toy-dataset-illustration)\n 1. [Predicting sequences](#Predicting-sequences)\n 1. [Listener-based evaluation](#Listener-based-evaluation)\n 1. [Other prediction and evaluation methods](#Other-prediction-and-evaluation-methods)\n 1. [Cross-validation](#Cross-validation)\n1. [Baseline SCC model](#Baseline-SCC-model)\n1. [Modifying the core model](#Modifying-the-core-model)\n 1. [Illustration: LSTM Cells](#Illustration:-LSTM-Cells)\n 1. [Illustration: Deeper models](#Illustration:-Deeper-models)", "_____no_output_____" ], [ "## Overview\n\nThis notebook is part of our unit on grounding. It illustrates core concepts from the unit, and it provides useful background material for the associated homework and bake-off.", "_____no_output_____" ], [ "## Set-up", "_____no_output_____" ] ], [ [ "from colors import ColorsCorpusReader\nimport os\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport torch\nfrom torch_color_describer import (\n ContextualColorDescriber, create_example_dataset)\nimport utils\nfrom utils import START_SYMBOL, END_SYMBOL, UNK_SYMBOL", "_____no_output_____" ], [ "utils.fix_random_seeds()", "_____no_output_____" ] ], [ [ "The [Stanford English Colors in Context corpus](https://cocolab.stanford.edu/datasets/colors.html) (SCC) is included in the data distribution for this course. If you store the data in a non-standard place, you'll need to update the following:", "_____no_output_____" ] ], [ [ "COLORS_SRC_FILENAME = os.path.join(\n \"data\", \"colors\", \"filteredCorpus.csv\")", "_____no_output_____" ] ], [ [ "## The corpus", "_____no_output_____" ], [ "The SCC corpus is based in a two-player interactive game. The two players share a context consisting of three color patches, with the display order randomized between them so that they can't use positional information when communicating.\n\nThe __speaker__ is privately assigned a target color and asked to produce a description of it that will enable the __listener__ to identify the speaker's target. The listener makes a choice based on the speaker's message, and the two succeed if and only if the listener identifies the target correctly.\n\nIn the game, the two players played repeated reference games and could communicate with each other in a free-form way. This opens up the possibility of modeling these repeated interactions as task-oriented dialogues. However, for this unit, we'll ignore most of this structure. We'll treat the corpus as a bunch of independent reference games played by anonymous players, and we will ignore the listener and their choices entirely.\n\nFor the bake-off, we will be distributing a separate test set. Thus, all of the data in the SCC can be used for exploration and development.", "_____no_output_____" ], [ "### Corpus reader", "_____no_output_____" ], [ "The corpus reader class is `ColorsCorpusReader` in `colors.py`. The reader's primary function is to let you iterate over corpus examples:", "_____no_output_____" ] ], [ [ "corpus = ColorsCorpusReader(\n COLORS_SRC_FILENAME,\n word_count=None, \n normalize_colors=True)", "_____no_output_____" ] ], [ [ "The two keyword arguments have their default values here. \n\n* If you supply `word_count` with an interger value, it will restrict to just examples where the utterance has that number of words (using a whitespace heuristic). This creates smaller corpora that are useful for development.\n\n* The colors in the corpus are in [HLS format](https://en.wikipedia.org/wiki/HSL_and_HSV). With `normalize_colors=False`, the first (hue) value is an integer between 1 and 360 inclusive, and the L (lightness) and S (saturation) values are between 1 and 100 inclusive. With `normalize_colors=True`, these values are all scaled to between 0 and 1 inclusive. The default is `normalize_colors=True` because this is a better choice for all the machine learning models we'll consider.", "_____no_output_____" ] ], [ [ "examples = list(corpus.read())", "_____no_output_____" ] ], [ [ "We can verify that we read in the same number of examples as reported in [Monroe et al. 2017](https://transacl.org/ojs/index.php/tacl/article/view/1142):", "_____no_output_____" ] ], [ [ "# Should be 46994:\n\nlen(examples)", "_____no_output_____" ] ], [ [ "### ColorsCorpusExample instances", "_____no_output_____" ], [ "The examples are `ColorsCorpusExample` instances:", "_____no_output_____" ] ], [ [ "ex1 = next(corpus.read())", "_____no_output_____" ] ], [ [ "These objects have a lot of attributes and methods designed to help you study the corpus and use it for our machine learning tasks. Let's review some highlights.", "_____no_output_____" ], [ "#### Displaying examples", "_____no_output_____" ], [ "You can see what the speaker saw, with the utterance they chose wote above the patches:", "_____no_output_____" ] ], [ [ "ex1.display(typ='speaker')", "The darker blue one\n" ] ], [ [ "This is the original order of patches for the speaker. The target happens to the be the leftmost patch, as indicated by the black box around it.\n\nHere's what the listener saw, with the speaker's message printed above the patches:", "_____no_output_____" ] ], [ [ "ex1.display(typ='listener')", "The darker blue one\n" ] ], [ [ "The listener isn't shown the target, of course, so no patches are highlighted.", "_____no_output_____" ], [ "If `display` is called with no arguments, then the target is placed in the final position and the other two are given in an order determined by the corpus metadata:", "_____no_output_____" ] ], [ [ "ex1.display()", "The darker blue one\n" ] ], [ [ "This is the representation order we use for our machine learning models.", "_____no_output_____" ], [ "#### Color representations", "_____no_output_____" ], [ "For machine learning, we'll often need to access the color representations directly. The primary attribute for this is `colors`:", "_____no_output_____" ] ], [ [ "ex1.colors", "_____no_output_____" ] ], [ [ "In this display order, the third element is the target color and the first two are the distractors. The attributes `speaker_context` and `listener_context` return the same colors but in the order that those players saw them. For example:", "_____no_output_____" ] ], [ [ "ex1.speaker_context", "_____no_output_____" ] ], [ [ "#### Utterance texts", "_____no_output_____" ], [ "Utterances are just strings: ", "_____no_output_____" ] ], [ [ "ex1.contents", "_____no_output_____" ] ], [ [ "There are cases where the speaker made a sequences of utterances for the same trial. We follow [Monroe et al. 2017](https://transacl.org/ojs/index.php/tacl/article/view/1142) in concatenating these into a single utterances. To preserve the original information, the individual turns are separated by `\" ### \"`. Example 3 is the first with this property – let's check it out:", "_____no_output_____" ] ], [ [ "ex3 = examples[2]", "_____no_output_____" ], [ "ex3.contents", "_____no_output_____" ] ], [ [ "The method `parse_turns` will parse this into individual turns:", "_____no_output_____" ] ], [ [ "ex3.parse_turns()", "_____no_output_____" ] ], [ [ "For examples consisting of a single turn, `parse_turns` returns a list of length 1:", "_____no_output_____" ] ], [ [ "ex1.parse_turns()", "_____no_output_____" ] ], [ [ "### Far, Split, and Close conditions", "_____no_output_____" ], [ "The SCC contains three conditions:\n \n__Far condition__: All three colors are far apart in color space. Example:", "_____no_output_____" ] ], [ [ "print(\"Condition type:\", examples[1].condition)\n\nexamples[1].display()", "Condition type: far\npurple\n" ] ], [ [ "__Split condition__: The target is close to one of the distractors, and the other is far away from both of them. Example:", "_____no_output_____" ] ], [ [ "print(\"Condition type:\", examples[3].condition)\n\nexamples[3].display()", "Condition type: split\nlime\n" ] ], [ [ "__Close condition__: The target is similar to both distractors. Example:", "_____no_output_____" ] ], [ [ "print(\"Condition type:\", examples[2].condition)\n\nexamples[2].display()", "Condition type: close\nMedium pink ### the medium dark one\n" ] ], [ [ "These conditions go from easiest to hardest when it comes to reliable communication. In the __Far__ condition, the context is hardly relevant, whereas the nature of the distractors reliably shapes the speaker's choices in the other two conditions. \n\nYou can begin to see how this affects speaker choices in the above examples: \"purple\" suffices for the __Far__ condition, a more marked single word (\"lime\") suffices in the __Split__ condition, and the __Close__ condition triggers a pretty long, complex description.", "_____no_output_____" ], [ "The `condition` attribute provides access to this value: ", "_____no_output_____" ] ], [ [ "ex1.condition", "_____no_output_____" ] ], [ [ "The following verifies that we have the same number of examples per condition as reported in [Monroe et al. 2017](https://transacl.org/ojs/index.php/tacl/article/view/1142):", "_____no_output_____" ] ], [ [ "pd.Series([ex.condition for ex in examples]).value_counts()", "_____no_output_____" ] ], [ [ "## Toy problems for development work", "_____no_output_____" ], [ "The SCC corpus is fairly large and quite challenging as an NLU task. This means it isn't ideal when it comes to testing hypotheses and debugging code. Poor performance could trace to a mistake, but it could just as easily trace to the fact that the problem is very challenging from the point of view of optimization.\n\nTo address this, the module `torch_color_describer.py` includes a function `create_example_dataset` for creating small, easy datasets with the same basic properties as the SCC corpus.\n\nHere's a toy problem containing just six examples:", "_____no_output_____" ] ], [ [ "tiny_contexts, tiny_words, tiny_vocab = create_example_dataset(\n group_size=2, vec_dim=2)", "_____no_output_____" ], [ "tiny_vocab", "_____no_output_____" ], [ "tiny_words", "_____no_output_____" ], [ "tiny_contexts", "_____no_output_____" ] ], [ [ "Each member of `tiny_contexts` contains three vectors. The final (target) vector always has values in a range that determines the corresponding word sequence, which is drawn from a set of three fixed sequences. Thus, the model basically just needs to learn to ignore the distractors and find the association between the target vector and the corresponding sequence. \n\nAll the models we study have a capacity to solve this task with very little data, so you should see perfect or near perfect performance on reasonably-sized versions of this task.", "_____no_output_____" ], [ "## Core model", "_____no_output_____" ], [ "Our core model for this problem is implemented in `torch_color_describer.py` as `ContextualColorDescriber`. At its heart, this is a pretty standard encoder–decoder model:\n\n* `Encoder`: Processes the color contexts as a sequence. We always place the target in final position so that it is closest to the supervision signals that we get when decoding.\n\n* `Decoder`: A neural language model whose initial hidden representation is the final hidden representation of the `Encoder`.\n\n* `EncoderDecoder`: Coordinates the operations of the `Encoder` and `Decoder`.\n\nFinally, `ContextualColorDescriber` is a wrapper around these model components. It handle the details of training and implements the prediction and evaluation functions that we will use.\n\nMany additional details about this model are included in the slides for this unit.", "_____no_output_____" ], [ "### Toy dataset illustration", "_____no_output_____" ], [ "To highlight the core functionality of `ContextualColorDescriber`, let's create a small toy dataset and use it to train and evaluate a model:", "_____no_output_____" ] ], [ [ "toy_color_seqs, toy_word_seqs, toy_vocab = create_example_dataset(\n group_size=50, vec_dim=2)", "_____no_output_____" ], [ "toy_color_seqs_train, toy_color_seqs_test, toy_word_seqs_train, toy_word_seqs_test = \\\n train_test_split(toy_color_seqs, toy_word_seqs)", "_____no_output_____" ] ], [ [ "Here we expose all of the available parameters with their default values:", "_____no_output_____" ] ], [ [ "toy_mod = ContextualColorDescriber(\n toy_vocab, \n embedding=None, # Option to supply a pretrained matrix as an `np.array`.\n embed_dim=10, \n hidden_dim=10, \n max_iter=100, \n eta=0.01,\n optimizer=torch.optim.Adam,\n batch_size=128,\n l2_strength=0.0,\n warm_start=False,\n device=None)", "_____no_output_____" ], [ "_ = toy_mod.fit(toy_color_seqs_train, toy_word_seqs_train)", "Epoch 100; err = 0.13451486825942993" ] ], [ [ "### Predicting sequences", "_____no_output_____" ], [ "The `predict` method takes a list of color contexts as input and returns model descriptions:", "_____no_output_____" ] ], [ [ "toy_preds = toy_mod.predict(toy_color_seqs_test)", "_____no_output_____" ], [ "toy_preds[0]", "_____no_output_____" ] ], [ [ "We can then check that we predicted all correct sequences:", "_____no_output_____" ] ], [ [ "toy_correct = sum(1 for x, p in zip(toy_word_seqs_test, toy_preds))\n\ntoy_correct / len(toy_word_seqs_test)", "_____no_output_____" ] ], [ [ "For real problems, this is too stringent a requirement, since there are generally many equally good descriptions. This insight gives rise to metrics like [BLEU](https://en.wikipedia.org/wiki/BLEU), [METEOR](https://en.wikipedia.org/wiki/METEOR), [ROUGE](https://en.wikipedia.org/wiki/ROUGE_(metric)), [CIDEr](https://arxiv.org/pdf/1411.5726.pdf), and others, which seek to relax the requirement of an exact match with the test sequence. These are reasonable options to explore, but we will instead adopt a communcation-based evaluation, as discussed in the next section.", "_____no_output_____" ], [ "### Listener-based evaluation", "_____no_output_____" ], [ "`ContextualColorDescriber` implements a method `listener_accuracy` that we will use for our primary evaluations in the assignment and bake-off. The essence of the method is that we can calculate\n\n$$\nc^{*} = \\text{argmax}_{c \\in C} P_S(\\text{utterance} \\mid c)\n$$\n\n\nwhere $P_S$ is our describer model and $C$ is the set of all permutations of all three colors in the color context. We take $c^{*}$ to be a correct prediction if it is one where the target is in the privileged final position. (There are two such contexts; we try both in case the order of the distractors influences the predictions, and the model is correct if one of them has the highest probability.)\n\nHere's the listener accuracy of our toy model:", "_____no_output_____" ] ], [ [ "toy_mod.listener_accuracy(toy_color_seqs_test, toy_word_seqs_test)", "_____no_output_____" ] ], [ [ "### Other prediction and evaluation methods", "_____no_output_____" ], [ "You can get the perplexities for test examles with `perpelexities`:", "_____no_output_____" ] ], [ [ "toy_perp = toy_mod.perplexities(toy_color_seqs_test, toy_word_seqs_test)", "_____no_output_____" ], [ "toy_perp[0]", "_____no_output_____" ] ], [ [ "You can use `predict_proba` to see the full probability distributions assigned to test examples:", "_____no_output_____" ] ], [ [ "toy_proba = toy_mod.predict_proba(toy_color_seqs_test, toy_word_seqs_test)", "_____no_output_____" ], [ "toy_proba[0].shape", "_____no_output_____" ], [ "for timestep in toy_proba[0]:\n print(dict(zip(toy_vocab, timestep)))", "{'<s>': 1.0, '</s>': 0.0, 'A': 0.0, 'B': 0.0, '$UNK': 0.0}\n{'<s>': 0.0036859103, '</s>': 0.0002668097, 'A': 0.9854643, 'B': 0.00914348, '$UNK': 0.0014396048}\n{'<s>': 0.004782134, '</s>': 0.024507374, 'A': 0.0019362223, 'B': 0.96381474, '$UNK': 0.0049594548}\n{'<s>': 0.0050890064, '</s>': 0.9780351, 'A': 0.014443797, 'B': 0.0008280464, '$UNK': 0.0016041624}\n" ] ], [ [ "### Cross-validation", "_____no_output_____" ], [ "You can use `utils.fit_classifier_with_crossvalidation` to cross-validate these models. Just be sure to set `scoring=None` so that the sklearn model selection methods use the `score` method of `ContextualColorDescriber`, which is an alias for `listener_accuracy`:", "_____no_output_____" ] ], [ [ "best_mod = utils.fit_classifier_with_crossvalidation(\n toy_color_seqs_train, \n toy_word_seqs_train, \n toy_mod, \n cv=2,\n scoring=None,\n param_grid={'hidden_dim': [10, 20]})", "Epoch 100; err = 0.12754583358764648" ] ], [ [ "## Baseline SCC model", "_____no_output_____" ], [ "Just to show how all the pieces come together, here's a very basic SCC experiment using the core code and very simplistic assumptions (which you will revisit in the assignment) about how to represent the examples:", "_____no_output_____" ], [ "To facilitate quick development, we'll restrict attention to the two-word examples:", "_____no_output_____" ] ], [ [ "dev_corpus = ColorsCorpusReader(COLORS_SRC_FILENAME, word_count=2)", "_____no_output_____" ], [ "dev_examples = list(dev_corpus.read())", "_____no_output_____" ], [ "len(dev_examples)", "_____no_output_____" ] ], [ [ "Here we extract the raw colors and texts (as strings):", "_____no_output_____" ] ], [ [ "dev_cols, dev_texts = zip(*[[ex.colors, ex.contents] for ex in dev_examples])", "_____no_output_____" ] ], [ [ "To tokenize the examples, we'll just split on whitespace, taking care to add the required boundary symbols:", "_____no_output_____" ] ], [ [ "dev_word_seqs = [[START_SYMBOL] + text.split() + [END_SYMBOL] for text in dev_texts]", "_____no_output_____" ] ], [ [ "We'll use a random train–test split:", "_____no_output_____" ] ], [ [ "dev_cols_train, dev_cols_test, dev_word_seqs_train, dev_word_seqs_test = \\\n train_test_split(dev_cols, dev_word_seqs)", "_____no_output_____" ] ], [ [ "Our vocab is determined by the train set, and we take care to include the `$UNK` token:", "_____no_output_____" ] ], [ [ "dev_vocab = sorted({w for toks in dev_word_seqs_train for w in toks}) + [UNK_SYMBOL]", "_____no_output_____" ] ], [ [ "And now we're ready to train a model:", "_____no_output_____" ] ], [ [ "dev_mod = ContextualColorDescriber(\n dev_vocab, \n embed_dim=10, \n hidden_dim=10, \n max_iter=10, \n batch_size=128)", "_____no_output_____" ], [ "_ = dev_mod.fit(dev_cols_train, dev_word_seqs_train)", "Epoch 10; err = 101.7589635848999" ] ], [ [ "And finally an evaluation in terms of listener accuracy:", "_____no_output_____" ] ], [ [ "dev_mod.listener_accuracy(dev_cols_test, dev_word_seqs_test)", "_____no_output_____" ] ], [ [ "## Modifying the core model", "_____no_output_____" ], [ "The first few assignment problems concern how you preprocess the data for your model. After that, the goal is to subclass model components in `torch_color_describer.py`. For the bake-off submission, you can do whatever you like in terms of modeling, but my hope is that you'll be able to continue subclassing based on `torch_color_describer.py`.\n\nThis section provides some illustrative examples designed to give you a feel for how the code is structured and what your options are in terms of creating subclasses.", "_____no_output_____" ], [ "### Illustration: LSTM Cells", "_____no_output_____" ], [ "Both the `Encoder` and the `Decoder` of `torch_color_describer` are currently GRU cells. Switching to another cell type is easy:", "_____no_output_____" ], [ "__Step 1__: Subclass the `Encoder`; all we have to do here is change `GRU` from the original to `LSTM`:", "_____no_output_____" ] ], [ [ "import torch.nn as nn\nfrom torch_color_describer import Encoder\n\nclass LSTMEncoder(Encoder):\n def __init__(self, color_dim, hidden_dim):\n super().__init__(color_dim, hidden_dim) \n self.rnn = nn.LSTM(\n input_size=self.color_dim,\n hidden_size=self.hidden_dim,\n batch_first=True)", "_____no_output_____" ] ], [ [ "__Step 2__: Subclass the `Decoder`, making the same simple change as above:", "_____no_output_____" ] ], [ [ "import torch.nn as nn\nfrom torch_color_describer import Encoder, Decoder\n\nclass LSTMDecoder(Decoder):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs) \n self.rnn = nn.LSTM(\n input_size=self.embed_dim,\n hidden_size=self.hidden_dim,\n batch_first=True)", "_____no_output_____" ] ], [ [ "__Step 3__:`ContextualColorDescriber` has a method called `build_graph` that sets up the `Encoder` and `Decoder`. The needed revision just uses `LSTMEncoder`:", "_____no_output_____" ] ], [ [ "from torch_color_describer import EncoderDecoder\n\nclass LSTMContextualColorDescriber(ContextualColorDescriber): \n \n def build_graph(self):\n \n # Use the new Encoder:\n encoder = LSTMEncoder(\n color_dim=self.color_dim,\n hidden_dim=self.hidden_dim)\n\n # Use the new Decoder:\n decoder = LSTMDecoder(\n vocab_size=self.vocab_size,\n embed_dim=self.embed_dim,\n embedding=self.embedding,\n hidden_dim=self.hidden_dim)\n\n return EncoderDecoder(encoder, decoder)", "_____no_output_____" ] ], [ [ "Here's an example run:", "_____no_output_____" ] ], [ [ "lstm_mod = LSTMContextualColorDescriber(\n toy_vocab, \n embed_dim=10, \n hidden_dim=10, \n max_iter=100, \n batch_size=128)", "_____no_output_____" ], [ "_ = lstm_mod.fit(toy_color_seqs_train, toy_word_seqs_train) ", "Epoch 100; err = 0.14593948423862457" ], [ "lstm_mod.listener_accuracy(toy_color_seqs_test, toy_word_seqs_test)", "_____no_output_____" ] ], [ [ "### Illustration: Deeper models", "_____no_output_____" ], [ "The `Encoder` and `Decoder` are both currently hard-coded to have just one hidden layer. It is straightforward to make them deeper as long as we ensure that both the `Encoder` and `Decoder` have the same depth; since the `Encoder` final states are the initial hidden states for the `Decoder`, we need this alignment. \n\n(Strictly speaking, we could have different numbers of `Encoder` and `Decoder` layers, as long as we did some kind of averaging or copying to achieve the hand-off from `Encoder` to `Decocer`. I'll set this possibility aside.)", "_____no_output_____" ], [ "__Step 1__: We need to subclass the `Encoder` and `Decoder` so that they have `num_layers` argument that is fed into the RNN cell:", "_____no_output_____" ] ], [ [ "import torch.nn as nn\nfrom torch_color_describer import Encoder, Decoder\n\nclass DeepEncoder(Encoder):\n def __init__(self, *args, num_layers=2, **kwargs):\n super().__init__(*args, **kwargs)\n self.num_layers = num_layers\n self.rnn = nn.GRU(\n input_size=self.color_dim,\n hidden_size=self.hidden_dim,\n num_layers=self.num_layers,\n batch_first=True) \n\n\nclass DeepDecoder(Decoder):\n def __init__(self, *args, num_layers=2, **kwargs):\n super().__init__(*args, **kwargs) \n self.num_layers = num_layers\n self.rnn = nn.GRU(\n input_size=self.embed_dim,\n hidden_size=self.hidden_dim,\n num_layers=self.num_layers,\n batch_first=True) ", "_____no_output_____" ] ], [ [ "__Step 2__: As before, we need to update the `build_graph` method of `ContextualColorDescriber`. The needed revision just uses `DeepEncoder` and `DeepDecoder`. To expose this new argument to the user, we also add a new keyword argument to `ContextualColorDescriber`:", "_____no_output_____" ] ], [ [ "from torch_color_describer import EncoderDecoder\n\nclass DeepContextualColorDescriber(ContextualColorDescriber): \n def __init__(self, *args, num_layers=2, **kwargs):\n self.num_layers = num_layers\n super().__init__(*args, **kwargs)\n \n def build_graph(self):\n encoder = DeepEncoder(\n color_dim=self.color_dim,\n hidden_dim=self.hidden_dim,\n num_layers=self.num_layers) # The new piece is this argument.\n\n decoder = DeepDecoder(\n vocab_size=self.vocab_size,\n embed_dim=self.embed_dim,\n embedding=self.embedding,\n hidden_dim=self.hidden_dim,\n num_layers=self.num_layers) # The new piece is this argument.\n\n return EncoderDecoder(encoder, decoder)", "_____no_output_____" ] ], [ [ "An example/test run:", "_____no_output_____" ] ], [ [ "mod_deep = DeepContextualColorDescriber(\n toy_vocab, \n embed_dim=10, \n hidden_dim=10, \n max_iter=100,\n batch_size=128)", "_____no_output_____" ], [ "_ = mod_deep.fit(toy_color_seqs_train, toy_word_seqs_train) ", "Epoch 100; err = 0.10894003510475159" ], [ "mod_deep.listener_accuracy(toy_color_seqs_test, toy_word_seqs_test)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d0119003f614b6e03e9abb40aaffcef84589abc4
59,322
ipynb
Jupyter Notebook
discrete dynamic programming.ipynb
keiikegami/DP
be00f528e8e0aeb62c9547a9b99f84e28bcf3940
[ "MIT" ]
null
null
null
discrete dynamic programming.ipynb
keiikegami/DP
be00f528e8e0aeb62c9547a9b99f84e28bcf3940
[ "MIT" ]
null
null
null
discrete dynamic programming.ipynb
keiikegami/DP
be00f528e8e0aeb62c9547a9b99f84e28bcf3940
[ "MIT" ]
null
null
null
60.532653
150
0.724554
[ [ [ "# Simple Optimal Growth Model for Disrete DP\n# making a class which prepares the instances for DiscreteDP \n\nimport numpy as np\n\nclass SimpleOG(object):\n \n def __init__(self, B = 10, M = 5 , alpha = 0.5, beta = 0.9):\n \n self.B ,self.M ,self.alpha, self.beta = B,M,alpha,beta\n self.n = B+M+1\n self.m = M+1\n \n self.R = np.empty((self.n, self.m))\n self.Q = np.zeros((self.n, self.m, self.n))\n \n self.populate_Q()\n self.populate_R()\n \n def u(self, c):\n return c**self.alpha\n \n def populate_R(self):\n for i in range(self.n):\n for j in range(self.m):\n if i >= j:\n self.R[i][j] = self.u(i - j)\n else:\n self.R[i][j] = -np.inf\n \n def populate_Q(self):\n for a in range(self.m):\n self.Q[:, a, a:(a + self.B + 1)] = 1.0 / (self.B +1)", "_____no_output_____" ], [ "g = SimpleOG()", "_____no_output_____" ], [ "# Using DiscreteDP\n#DiscreteDP needs three arguments, R, Q, beta\n\nimport quantecon as qe\n\nddp = qe.markov.DiscreteDP(g.R, g.Q, g.beta)", "_____no_output_____" ], [ "# solving DP by using DiscreetDP\n\nresults = ddp.solve(method = \"policy_iteration\")", "_____no_output_____" ], [ "results", "_____no_output_____" ], [ "ddp.compute_greedy(results.v)", "_____no_output_____" ], [ "# check the elements in results\n\ndir(results)", "_____no_output_____" ], [ "print \"The maximum number of iterations is\" , results.max_iter\nprint \"The transition matrix taken when following the optimal policy is\" ,results.mc\nprint \"The method used here to solve this problem is \", results.method\nprint \"The number of iterations taken here is \", results.num_iter\nprint \"The optimal value function is \", results.v\nprint \"The optimal policy function is \", results.sigma", "The maximum number of iterations is 250\nThe transition matrix taken when following the optimal policy is <bound method MarkovChain.__repr__ of Markov chain with transition matrix \nP = \n[[ 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0. 0.\n 0. 0. 0. ]\n [ 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0. 0.\n 0. 0. 0. ]\n [ 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0. 0.\n 0. 0. 0. ]\n [ 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0. 0.\n 0. 0. 0. ]\n [ 0. 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0. 0. 0. 0. ]\n [ 0. 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0. 0. 0. 0. ]\n [ 0. 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0. 0. 0. 0. ]\n [ 0. 0. 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0. 0. 0. ]\n [ 0. 0. 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0. 0. 0. ]\n [ 0. 0. 0. 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0. 0. ]\n [ 0. 0. 0. 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0. 0. ]\n [ 0. 0. 0. 0. 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0. ]\n [ 0. 0. 0. 0. 0. 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909]\n [ 0. 0. 0. 0. 0. 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909]\n [ 0. 0. 0. 0. 0. 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909]\n [ 0. 0. 0. 0. 0. 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909 0.09090909\n 0.09090909 0.09090909 0.09090909 0.09090909]]>\nThe method used here to solve this problem is policy iteration\nThe number of iterations taken here is 3\nThe optimal value function is [ 19.01740222 20.01740222 20.43161578 20.74945302 21.04078099\n 21.30873018 21.54479816 21.76928181 21.98270358 22.18824323\n 22.3845048 22.57807736 22.76109127 22.94376708 23.11533996\n 23.27761762]\nThe optimal policy function is [0 0 0 0 1 1 1 2 2 3 3 4 5 5 5 5]\n" ], [ "# optimal value function は、各stateが初期状態の時に達成しうる無限期間での最大化された期待効用\n#optimal policy functionは、各stateに対して取るべき次の行動を表示。例えば、state7に対しては、indexの7番目を見て、action2を取る。", "_____no_output_____" ], [ "# and mc is MarkovChain instance\n#so, you can calculate the stationary distribution for P\n# optimal policyをとっている時に、stationary_distributionに従って初期状態を決定すれば、以降取る状態の分布はstationary_distributionに従う\nresults.mc.stationary_distributions\n", "_____no_output_____" ], [ "# the graph for this distribution\nimport matplotlib.pyplot as plt\n% matplotlib inline\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nh = results.mc.stationary_distributions\nax.bar(np.arange(16), h[0])\nplt.show()", "_____no_output_____" ], [ "g.R", "_____no_output_____" ], [ "# betaを変えてstationaryを表示してみる(小さいほど近視眼的)\n#patientなほど、高いstateを取るようになる\n#これは、目先の紅葉が高い消費を抑えて、収入を将来の貯蓄にまわすようになること意味する\n\nimport numpy as np\nimport quantecon as qe\nimport matplotlib.pyplot as plt\ni = 1\n\nfor beta_2 in [0.05, 0.5, 0.9, 0.95, 0.99]:\n k = SimpleOG(beta = beta_2)\n ddp = qe.markov.DiscreteDP(k.R, k.Q, k.beta)\n results = ddp.solve(method = \"policy_iteration\")\n f = results.mc.stationary_distributions\n fig = plt.figure(figsize=(10, 15))\n plt.subplot(5,1,i)\n plt.bar(np.arange(16), f[0])\n i +=1\n plt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0119d255d7f39d0b4ea97a315a2ac23b3203b82
75,985
ipynb
Jupyter Notebook
pydata/03_numerics.ipynb
andreamelloncelli/cineca-lectures
cb4ef19ac1b82eb1fa1cd9ef17f1c28f81eaced5
[ "MIT" ]
null
null
null
pydata/03_numerics.ipynb
andreamelloncelli/cineca-lectures
cb4ef19ac1b82eb1fa1cd9ef17f1c28f81eaced5
[ "MIT" ]
null
null
null
pydata/03_numerics.ipynb
andreamelloncelli/cineca-lectures
cb4ef19ac1b82eb1fa1cd9ef17f1c28f81eaced5
[ "MIT" ]
1
2020-02-28T00:15:33.000Z
2020-02-28T00:15:33.000Z
19.533419
1,790
0.474251
[ [ [ "# Ipython magic\n%pylab inline", "Populating the interactive namespace from numpy and matplotlib\n" ] ], [ [ "## Introduction", "_____no_output_____" ], [ "In the `numpy` package the terminology used for vectors, matrices and higher-dimensional data sets is *array*. \n\n", "_____no_output_____" ], [ "## Creating `numpy` arrays", "_____no_output_____" ], [ "There are a number of ways to initialize new numpy arrays, for example from\n\n* a Python list or tuples\n* using functions that are dedicated to generating numpy arrays, such as `arange`, `linspace`, etc.\n* reading data from files", "_____no_output_____" ], [ "### From lists", "_____no_output_____" ], [ "We can use the `numpy.array` function.", "_____no_output_____" ] ], [ [ "# a vector: the argument to the array function is a Python list\nv = array([1,2,3,4])\nv", "_____no_output_____" ], [ "# a matrix: the argument to the array function is a nested Python list\nM = array([[1, 2], [3, 4]])\nM", "_____no_output_____" ] ], [ [ "The `v` and `M` objects are both of the type `numpy.ndarray`", "_____no_output_____" ] ], [ [ "type(v), type(M)", "_____no_output_____" ] ], [ [ "The difference between the `v` and `M` arrays is only their shapes. \n\nWe can check it with the `ndarray.shape` property.", "_____no_output_____" ] ], [ [ "v.shape", "_____no_output_____" ], [ "M.shape", "_____no_output_____" ] ], [ [ "The number of elements in the array is available through the `ndarray.size` property:", "_____no_output_____" ] ], [ [ "M.size", "_____no_output_____" ] ], [ [ "Equivalently, we could use the function `numpy.shape` and `numpy.size`", "_____no_output_____" ] ], [ [ "shape(M)", "_____no_output_____" ], [ "size(M)", "_____no_output_____" ] ], [ [ "So far the `numpy.ndarray` looks awefully much like a Python list (or nested list). \n\nWhy not simply use Python lists for computations instead of creating a new array type? \n\n**There are several reasons**", "_____no_output_____" ], [ "* Python lists are very general. \n - They can contain any kind of object. \n - They are dynamically typed. \n* They do not support mathematical functions \n - such as matrix and dot multiplications, etc. \n - Implementating such functions for Python lists would not be very efficient \n * because of the dynamic typing", "_____no_output_____" ], [ "* Numpy arrays are **statically typed** and **homogeneous**. \n - The type of the elements is determined when array is created\n - By already knowing the static type, numpy can implement low-level optimization\n* Numpy arrays are memory efficient.\n - fast implementation of mathematical functions can be implemented in a compiled language\n * C and Fortran is used", "_____no_output_____" ], [ "Using the `dtype` (data type) property of an `ndarray`, we can see what type the data of an array has:", "_____no_output_____" ] ], [ [ "M.dtype", "_____no_output_____" ] ], [ [ "We get an error if we try to assign a value of the wrong type to an element in a numpy array:", "_____no_output_____" ] ], [ [ "M[0,0] = \"hello\"", "_____no_output_____" ] ], [ [ "If we want, we can explicitly define the type of the array data when we create it, using the `dtype` keyword argument: ", "_____no_output_____" ] ], [ [ "M = array([[1, 2], [3, 4]], dtype=complex)\n\nM", "_____no_output_____" ] ], [ [ "Common types that can be used with `dtype` \n\n `int`, `float`, `complex`, `bool`, `object`, etc.\n\nWe can also explicitly define the bit size of the data types\n\n `int64`, `int16`, `float128`, `complex128`.", "_____no_output_____" ], [ "## If i don't see it, i don't believe it", "_____no_output_____" ], [ "`ndarray` = n-dimension array", "_____no_output_____" ], [ "<img src=\"images/ndarray.png\">", "_____no_output_____" ], [ "A quick benchmark", "_____no_output_____" ] ], [ [ "# Normal python vector\ndim = 10000\na = range(dim)\nt1 = %timeit -o [i**2 for i in a]", "_____no_output_____" ], [ "# Numpy vector with normal python loop\nb = arange(dim)\nt2 = %timeit -o [i**2 for i in b]", "_____no_output_____" ], [ "# Numpy vector with numpy loop\nc = arange(dim)\nt3 = %timeit -n 1000 -o [c**2]", "_____no_output_____" ], [ "print \"Python loops (no) speedup: \", t1.best / t2.best", "_____no_output_____" ], [ "print \"Numpy loops speedup:\", int(t1.best / t3.best), \"x\"", "_____no_output_____" ] ], [ [ "We want to make sure...", "_____no_output_____" ] ], [ [ "print \"Type\", type(a), [i**2 for i in a][0:10]", "_____no_output_____" ], [ "print type(b), (b**2)[0:10]", "_____no_output_____" ] ], [ [ "## Using more array-generating functions", "_____no_output_____" ], [ "#### arange", "_____no_output_____" ] ], [ [ "# create a range\nx = arange(0, 10, 1) # arguments: start, stop, step\nx", "_____no_output_____" ], [ "x = arange(-1, 1, 0.1)\nx", "_____no_output_____" ], [ "type(x)", "_____no_output_____" ] ], [ [ "#### mgrid", "_____no_output_____" ] ], [ [ "print numpy.mgrid.__doc__.split('\\n')[0]", "_____no_output_____" ], [ "x, y = mgrid[0:5, 0:5] # similar to meshgrid in MATLAB", "_____no_output_____" ], [ "x", "_____no_output_____" ], [ "y", "_____no_output_____" ] ], [ [ "#### random data", "_____no_output_____" ] ], [ [ "from numpy import random\n# uniform random numbers in [0,1]\nrandom.rand(5,5)", "_____no_output_____" ], [ "# standard normal distributed random numbers\nrandom.randn(5,5)", "_____no_output_____" ] ], [ [ "#### diag", "_____no_output_____" ] ], [ [ "# a diagonal matrix\ndiag([1,2,3])", "_____no_output_____" ], [ "# diagonal with offset from the main diagonal\ndiag([1,2,3], k=1) ", "_____no_output_____" ] ], [ [ "#### zeros and ones", "_____no_output_____" ] ], [ [ "zeros((3,3))", "_____no_output_____" ], [ "ones((3,3))", "_____no_output_____" ] ], [ [ "## More properties of arrays", "_____no_output_____" ] ], [ [ "M.itemsize # bytes per element", "_____no_output_____" ], [ "M.nbytes # number of bytes", "_____no_output_____" ], [ "M.ndim # number of dimensions", "_____no_output_____" ], [ "# With `newaxis`, we can insert new dimensions in an array\nv = array([1,2,3])\nprint \"Original:\", shape(v)\n\n# column matrix\nprint \"Col:\", v[:,newaxis].shape\n\n# row matrix\nprint \"Row:\", v[newaxis,:].shape\n", "_____no_output_____" ] ], [ [ "##Exercise", "_____no_output_____" ], [ "Create your own matrix and try some of the operations shown so far", "_____no_output_____" ], [ "## Manipulating arrays", "_____no_output_____" ], [ "### Indexing", "_____no_output_____" ], [ "We can index elements in an array using the square bracket and indices:", "_____no_output_____" ] ], [ [ "# v is a vector, and has only one dimension, taking one index\nv[0]", "_____no_output_____" ], [ "# M is a matrix, or a 2 dimensional array, taking two indices \nM[1,1]", "_____no_output_____" ] ], [ [ "If we omit an index of a multidimensional array it returns the whole row (or, in general, a N-1 dimensional array) ", "_____no_output_____" ] ], [ [ "M", "_____no_output_____" ], [ "M[1]", "_____no_output_____" ] ], [ [ "The same thing can be achieved with using `:` instead of an index", "_____no_output_____" ] ], [ [ "M[1,:] # row 1", "_____no_output_____" ], [ "M[:,1] # column 1", "_____no_output_____" ] ], [ [ "We can assign new values to elements in an array using indexing", "_____no_output_____" ] ], [ [ "M[0,0] = 1", "_____no_output_____" ], [ "M", "_____no_output_____" ], [ "# also works for rows and columns\nM[1,:] = 0\nM[:,2] = -1", "_____no_output_____" ], [ "M", "_____no_output_____" ] ], [ [ "### Index slicing", "_____no_output_____" ], [ "Index slicing is the technical name for the syntax `M[lower:upper:step]` to extract part of an array", "_____no_output_____" ] ], [ [ "A = array([1,2,3,4,5])\nA", "_____no_output_____" ], [ "A[1:3]", "_____no_output_____" ] ], [ [ "Array slices are *mutable*: \n\nif they are assigned a new value the original array from which the slice was extracted is modified", "_____no_output_____" ] ], [ [ "A[1:3] = [-2,-3]\n\nA", "_____no_output_____" ] ], [ [ "We can omit any of the three parameters in `M[lower:upper:step]`:", "_____no_output_____" ] ], [ [ "A[::] # lower, upper, step all take the default values", "_____no_output_____" ], [ "A[::2] # step is 2, lower and upper defaults to the beginning and end of the array", "_____no_output_____" ], [ "A[:3] # first three elements", "_____no_output_____" ], [ "A[3:] # elements from index 3", "_____no_output_____" ] ], [ [ "Negative indices counts from the end of the array (positive index from the begining):", "_____no_output_____" ] ], [ [ "A = array([1,2,3,4,5])", "_____no_output_____" ], [ "A[-1] # the last element in the array", "_____no_output_____" ], [ "A[-3:] # the last three elements", "_____no_output_____" ] ], [ [ "Index slicing works exactly the same way for multidimensional arrays:", "_____no_output_____" ] ], [ [ "A = array([[n+m*10 for n in range(5)] for m in range(5)])\n\nA", "_____no_output_____" ], [ "# a block from the original array\nA[1:4, 1:4]", "_____no_output_____" ], [ "# strides\nA[::2, ::2]", "_____no_output_____" ] ], [ [ "### Fancy indexing", "_____no_output_____" ], [ "Fancy indexing is the name for when **an array or list** is used in-place of an *index*", "_____no_output_____" ] ], [ [ "row_indices = [1, 2, 3]\nA[row_indices]", "_____no_output_____" ], [ "col_indices = [1, 2, -1] # remember, index -1 means the last element\nA[row_indices, col_indices]", "_____no_output_____" ] ], [ [ "##Exercise", "_____no_output_____" ], [ "- Define two odd number: n, m\n- Create a random matrix with shape n x m\n- Compute the middle cell position and get the center element", "_____no_output_____" ] ], [ [ "odd_list = range(1,10,2)\nimport random as stdrand\nn = stdrand.choice(odd_list)\nm = stdrand.choice(odd_list)\nprint \"Dimenions:\", n, m\nMAT = random.randn(n,m)\nmatrix_center = (n/2, m/2)\n\nprint MAT\nMAT[matrix_center]\n\n", "Dimenions: 3 1\n[[-2.19577913]\n [ 1.64321869]\n [-1.65874573]]\n" ] ], [ [ "###We can also index masks\n* e.g. a Numpy array of data type `bool`\n - an element is selected (True) or not (False) \n - depending on the value of the index mask at the position each element", "_____no_output_____" ] ], [ [ "B = array([n for n in range(5)])\nB", "_____no_output_____" ], [ "row_mask = array([True, False, True, False, False])\nB[row_mask]", "_____no_output_____" ], [ "# same thing\nrow_mask = array([1,0,1,0,0], dtype=bool)\nB[row_mask]", "_____no_output_____" ] ], [ [ "This feature is very useful to conditionally select elements from an array, using for example comparison operators:", "_____no_output_____" ] ], [ [ "x = arange(0, 10, 0.5)\nx", "_____no_output_____" ], [ "mask = (5 < x) * (x < 7.5)\nx[mask]\nprint mask\nprint x[mask]", "[False False False False False False False False False False False True\n True True True False False False False False]\n[ 5.5 6. 6.5 7. ]\n" ] ], [ [ "## Other functions \nfor extracting data from arrays and creating arrays", "_____no_output_____" ], [ "### where", "_____no_output_____" ], [ "The index mask can be converted to position index using the `where` function", "_____no_output_____" ] ], [ [ "indices = where(mask)\n\nindices", "_____no_output_____" ], [ "x[indices] # this indexing is equivalent to the fancy indexing x[mask]", "_____no_output_____" ] ], [ [ "### diag", "_____no_output_____" ], [ "With the diag function we can also extract the diagonal and subdiagonals of an array", "_____no_output_____" ] ], [ [ "diag(A)", "_____no_output_____" ], [ "diag(A, -1)", "_____no_output_____" ] ], [ [ "### choose", "_____no_output_____" ], [ "Constructs an array by picking elements form several arrays", "_____no_output_____" ] ], [ [ "which = [1, 0, 1, 0]\nchoices = [[-2,-2,-2,-2], [5,5,5,5]]\n\nchoose(which, choices)", "_____no_output_____" ] ], [ [ "## Linear algebra", "_____no_output_____" ], [ "Efficient numerical calculation with Numpy\n\n- Object should always be formulated in terms of matrix and vector operations\n- like matrix-matrix multiplication.", "_____no_output_____" ], [ "### Scalar-array operations", "_____no_output_____" ], [ "We can use the usual arithmetic operators to multiply, add, subtract, and divide arrays with scalar numbers.", "_____no_output_____" ] ], [ [ "v1 = arange(0, 5)", "_____no_output_____" ], [ "v1 * 2", "_____no_output_____" ], [ "v1 + 2", "_____no_output_____" ], [ "# Also works on a matrix\nA * 2, A + 2", "_____no_output_____" ] ], [ [ "## Exercise", "_____no_output_____" ], [ "Can you list the first 20 elements of the *\"power of two\"* using scalar array operations?", "_____no_output_____" ] ], [ [ "from numpy import array\nelements = 20\ntwo = array([2]*elements)\nfor i in range(len(two)):\n two[i:] = two[i:]*2\nprint two", "[ 4 8 16 32 64 128 256 512 1024\n 2048 4096 8192 16384 32768 65536 131072 262144 524288\n 1048576 2097152]\n" ] ], [ [ "### Element-wise array-array operations", "_____no_output_____" ], [ "When we add, subtract, multiply and divide arrays with each other, the default behaviour is **element-wise** operations:", "_____no_output_____" ] ], [ [ "print A\nprint A * A # element-wise multiplication", "[[ 0 1 2 3 4]\n [10 11 12 13 14]\n [20 21 22 23 24]\n [30 31 32 33 34]\n [40 41 42 43 44]]\n[[ 0 1 4 9 16]\n [ 100 121 144 169 196]\n [ 400 441 484 529 576]\n [ 900 961 1024 1089 1156]\n [1600 1681 1764 1849 1936]]\n" ], [ "v1 * v1", "_____no_output_____" ] ], [ [ "If we multiply arrays with compatible shapes, we get an element-wise multiplication of each row:", "_____no_output_____" ] ], [ [ "A.shape, v1.shape", "_____no_output_____" ], [ "A * v1", "_____no_output_____" ] ], [ [ "### Matrix algebra", "_____no_output_____" ], [ "What about matrix mutiplication? \n\n* We can either use the `dot` function, which applies a matrix-matrix, matrix-vector, or inner vector multiplication to its two arguments: ", "_____no_output_____" ] ], [ [ "dot(A, A)", "_____no_output_____" ], [ "dot(A, v1)", "_____no_output_____" ], [ "dot(v1, v1)", "_____no_output_____" ] ], [ [ "Alternatively\n\n* we can cast the array objects to the type `matrix`. \n\n<small>Note: This changes the behavior of the standard arithmetic operators `+, -, *` to use matrix algebra.</small>", "_____no_output_____" ] ], [ [ "M = matrix(A)\nM", "_____no_output_____" ], [ "v = matrix(v1).T # make it a column vector\nv", "_____no_output_____" ], [ "M * M", "_____no_output_____" ], [ "M * v", "_____no_output_____" ], [ "# inner product\nv.T * v", "_____no_output_____" ], [ "# with matrix objects, standard matrix algebra applies\nv + M*v", "_____no_output_____" ] ], [ [ "###warning\nIf we try to add, subtract or multiply objects with incomplatible shapes we get an error:", "_____no_output_____" ] ], [ [ "v = matrix([1,2,3,4,5,6]).T", "_____no_output_____" ], [ "shape(M), shape(v)", "_____no_output_____" ], [ "M * v", "_____no_output_____" ] ], [ [ "See also the related functions: `inner`, `outer`, `cross`, `kron`, `tensordot`", "_____no_output_____" ], [ "### Matrix computations", "_____no_output_____" ], [ "#### Inverse", "_____no_output_____" ] ], [ [ "C = matrix([[1j, 2j], [3j, 4j]])", "_____no_output_____" ], [ "inv(C) # equivalent to C.I ", "_____no_output_____" ], [ "C.I * C", "_____no_output_____" ] ], [ [ "#### Determinant", "_____no_output_____" ] ], [ [ "det(C)", "_____no_output_____" ], [ "det(C.I)", "_____no_output_____" ] ], [ [ "## Data processing\nFile Input/Output", "_____no_output_____" ], [ "### Comma-separated values (CSV)", "_____no_output_____" ], [ "A very common file format for data files are the comma-separated values (CSV).", "_____no_output_____" ] ], [ [ "# To read data from such file into Numpy arrays we can use the `numpy.genfromtxt` function\n?genfromtxt", "_____no_output_____" ] ], [ [ "data source: https://archive.ics.uci.edu/ml/datasets/Covertype", "_____no_output_____" ] ], [ [ "A = genfromtxt('data/num.csv.gz', delimiter = ',')", "_____no_output_____" ], [ "A.shape", "_____no_output_____" ], [ "A.size", "_____no_output_____" ], [ "A[:4,:3]", "_____no_output_____" ] ], [ [ "Using `numpy.savetxt` we can store a Numpy array to a file in **TSV** format:", "_____no_output_____" ] ], [ [ "M = rand(3,3)\n\nM", "_____no_output_____" ], [ "savetxt(\"random-matrix.csv\", M)", "_____no_output_____" ], [ "!cat random-matrix.csv", "3.703227066684050550e-01 7.210743066150180347e-01 8.177851226846111210e-03\r\n5.481568888557009078e-01 4.370262664386908025e-01 4.854412252923472337e-01\r\n9.957061580132914314e-01 8.303192596515113211e-01 3.483319463859742005e-01\r\n" ] ], [ [ "## Exercise", "_____no_output_____" ], [ "Read from the gzipped csv:\n- Only from row 11 to 20\n- Only third and sixth column\n- Truncate values to integer", "_____no_output_____" ] ], [ [ "read = 10\nskip = 10\na_len = len(A)\nB = genfromtxt('data/num.csv.gz', delimiter = ',', usecols = (2, 5),\n skip_header=skip, skip_footer=a_len-(read+skip), dtype=np.int16)", "_____no_output_____" ] ], [ [ "### Numpy's native file format", "_____no_output_____" ], [ "Useful when storing and reading back numpy array data. Use the functions `numpy.save` and `numpy.load`:", "_____no_output_____" ] ], [ [ "# numpy binary file saving\nsave(\"random-matrix.npy\", M)\n# check type of file\n!file random-matrix.npy", "random-matrix.npy: data\r\n" ], [ "# very fast, but not portable\nload(\"random-matrix.npy\")", "_____no_output_____" ] ], [ [ "### Statistics", "_____no_output_____" ], [ "Numpy provides a number of functions to calculate statistics of datasets in arrays.", "_____no_output_____" ] ], [ [ "data = A[:1000,:5]\ndata.shape", "_____no_output_____" ] ], [ [ "#### mean", "_____no_output_____" ] ], [ [ "# The mean of the 4th element\nmean(data[:,3])", "_____no_output_____" ] ], [ [ "#### standard deviations and variance", "_____no_output_____" ] ], [ [ "std(data[:,3]), var(data[:,3])", "_____no_output_____" ] ], [ [ "#### min and max", "_____no_output_____" ] ], [ [ "# search the lowest value of a column\ncol = 4\nprint \"Min value for\", col, \"is\", data[:,col].min()\nprint \"Max value for\", col, \"is\", data[:,col].max()", "Min value for 4 is -45.0\nMax value for 4 is 245.0\n" ] ], [ [ "There are many other operations. \n\n...but you will find more power in *pandas* for this.", "_____no_output_____" ], [ "### Copy and \"deep copy\"", "_____no_output_____" ], [ "- when objects are passed between functions \n - you want to avoid an excessive amount of memory copying when it is not necessary \n - (techincal term: pass by reference)", "_____no_output_____" ] ], [ [ "A = array([[1, 2], [3, 4]])\nA", "_____no_output_____" ], [ "B = A # now B is referring to the same array data as A \nB", "_____no_output_____" ], [ "A == B # check this", "_____no_output_____" ], [ "# changing B affects A\nB[0,0] = 10\nB", "_____no_output_____" ], [ "A", "_____no_output_____" ] ], [ [ "If we want to avoid this behavior \n- get a new completely independent object `B` copied from `A`\n- we need to do a so-called \"deep copy\" using the function `copy`", "_____no_output_____" ] ], [ [ "B = copy(A)", "_____no_output_____" ], [ "# now, if we modify B, A is not affected\nB[0,0] = -5\n\nB", "_____no_output_____" ], [ "A", "_____no_output_____" ] ], [ [ "### Iterating over array elements", "_____no_output_____" ], [ "> Vectorization describes the absence of any explicit looping, indexing, etc., in the code - these things are taking place, of course, just “behind the scenes” (in optimized, pre-compiled C code).\n\nsource: numpy website", "_____no_output_____" ], [ "- Generally, we want to avoid iterating over the elements of arrays \n * at all costs\n- In a *interpreted language* like Python (or MATLAB, or R)\n * iterations are really slow compared to vectorized operations\n- Use always numpy functions which are optimized\n * if you try a `for` loop you know what you get", "_____no_output_____" ], [ "### Type casting", "_____no_output_____" ], [ "- Numpy arrays are *statically typed*\n- the type of an array does not change once created\n- but we can explicitly cast an array of some type to another \n - using the `astype` functions \n - (see also the similar `asarray` function) \n - This always create a new array of new type", "_____no_output_____" ] ], [ [ "M.dtype", "_____no_output_____" ], [ "M", "_____no_output_____" ], [ "M2 = M.astype(bool)\nM2", "_____no_output_____" ], [ "M3 = M.astype(str)\nM3", "_____no_output_____" ] ], [ [ "## Versions", "_____no_output_____" ] ], [ [ "%reload_ext version_information\n\n%version_information numpy", "_____no_output_____" ] ], [ [ "**Let's move to the next part :)**", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d011a6992c3ab9f49b2d89ca114ec6567b137f90
6,010
ipynb
Jupyter Notebook
BisQue_Graphical_Annotations.ipynb
benlazarine/bisque-notebooks
b8d2d710262b6fc63d88f445081fe7536bf851e1
[ "BSD-3-Clause" ]
1
2018-11-10T05:05:10.000Z
2018-11-10T05:05:10.000Z
BisQue_Graphical_Annotations.ipynb
benlazarine/bisque-notebooks
b8d2d710262b6fc63d88f445081fe7536bf851e1
[ "BSD-3-Clause" ]
null
null
null
BisQue_Graphical_Annotations.ipynb
benlazarine/bisque-notebooks
b8d2d710262b6fc63d88f445081fe7536bf851e1
[ "BSD-3-Clause" ]
1
2019-12-02T05:32:16.000Z
2019-12-02T05:32:16.000Z
23.02682
119
0.51797
[ [ [ "Uploading an image with graphical annotations stored in a CSV file\n======================\n\nWe'll be using standard python tools to parse CSV and create an XML document describing cell nuclei for BisQue\n\nMake sure you have bisque api installed:\n> pip install bisque-api", "_____no_output_____" ] ], [ [ "import os\nimport csv\nfrom datetime import datetime\ntry:\n from lxml import etree\nexcept ImportError:\n import xml.etree.ElementTree as etree", "_____no_output_____" ] ], [ [ "Include BisQue API", "_____no_output_____" ] ], [ [ "from bqapi import BQSession\nfrom bqapi.util import save_blob", "_____no_output_____" ] ], [ [ "define some paths", "_____no_output_____" ] ], [ [ "path = '.'\npath_img = os.path.join(path, 'BisQue_CombinedSubtractions.lsm')\npath_csv = os.path.join(path, 'BisQue_CombinedSubtractions.csv')", "_____no_output_____" ] ], [ [ "Parse CSV file and load nuclei positions\n------------------------------------------\n\nWe'll create a list of XYZT coordinates with confidence", "_____no_output_____" ] ], [ [ "#x, y, z, t, confidence\ncoords = []\nwith open(path_csv, 'rb') as csvfile:\n reader = csv.reader(csvfile)\n h = reader.next()\n for r in reader:\n c = (r[0], r[1], r[2], r[4])\n print c\n coords.append(c)", "_____no_output_____" ] ], [ [ "Initiaize authenticated session\n--------------\n\nInitialize a BisQue session using simple user credentials", "_____no_output_____" ] ], [ [ "root = 'https://bisque.cyverse.org'\nuser = 'demo'\npswd = 'iplant'\n\nsession = BQSession().init_local(user, pswd, bisque_root=root, create_mex=False)", "_____no_output_____" ] ], [ [ "Create XML image descriptor\n---------------------------\n\nWe'll provide a suggested path in the remote user's directory ", "_____no_output_____" ] ], [ [ "path_on_bisque = 'demo/nuclei_%s/%s'%(datetime.now().strftime('%Y%m%dT%H%M%S'), os.path.basename(path_img))\nresource = etree.Element('image', name=path_on_bisque)\nprint etree.tostring(resource, pretty_print=True)", "_____no_output_____" ] ], [ [ "Upload the image\n-----------------", "_____no_output_____" ] ], [ [ "# use import service to /import/transfer activating import service\nr = etree.XML(session.postblob(path_img, xml=resource)).find('./') \n\nif r is None or r.get('uri') is None:\n print 'Upload failed'\nelse:\n print 'Uploaded ID: %s, URL: %s\\n'%(r.get('resource_uniq'), r.get('uri'))\n print etree.tostring(r, pretty_print=True)", "_____no_output_____" ] ], [ [ "Add graphical annotations\n------------------------------\n\nWe'll create point annotaions as an XML attached to the image we just uploaded into BisQue", "_____no_output_____" ] ], [ [ "g = etree.SubElement (r, 'gobject', type='My nuclei')\nfor c in coords:\n p = etree.SubElement(g, 'point')\n etree.SubElement(p, 'vertex', x=c[0], y=c[1], z=c[2])\n etree.SubElement(p, 'tag', name='confidence', value=c[3])\n\nprint etree.tostring(r, pretty_print=True)", "_____no_output_____" ] ], [ [ "Save graphical annotations to the system\n------------------------------------------\n\nAfter storing all annotations become searchable ", "_____no_output_____" ] ], [ [ "url = session.service_url('data_service')\nr = session.postxml(url, r)\n\nif r is None or r.get('uri') is None:\n print 'Adding annotations failed'\nelse:\n print 'Image ID: %s, URL: %s'%(r.get('resource_uniq'), r.get('uri'))", "_____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" ] ]
d011b3319b0fbf23f5b4fa20edb6c0baa71bee29
5,696
ipynb
Jupyter Notebook
anaysis.ipynb
yao0510/Fake-EmoReact-2021
d6d6facd46c1a31cbc70bfef8688715897b9470b
[ "MIT" ]
null
null
null
anaysis.ipynb
yao0510/Fake-EmoReact-2021
d6d6facd46c1a31cbc70bfef8688715897b9470b
[ "MIT" ]
null
null
null
anaysis.ipynb
yao0510/Fake-EmoReact-2021
d6d6facd46c1a31cbc70bfef8688715897b9470b
[ "MIT" ]
null
null
null
25.542601
128
0.535288
[ [ [ "import pandas as pd\nimport json\nimport numpy as np\nfrom cleaner import *", "_____no_output_____" ], [ "# df_train = read_json('./processed_data/preprocess_train.json')\n# df_dev = read_json('./processed_data/preprocess_my_dev.json')\n# df_test = read_json('./processed_data/preprocess_eval.json')\ndf_train = read_json('./original_data/train.json')\ndf_dev = read_json('./processed_data/my_dev.json')\ndf_test = read_json('./original_data/eval.json')\nprint(\"Number of training data: {}\".format(df_train.shape[0]))\nprint(\"Number of developing data: {}\".format(df_dev.shape[0]))\nprint(\"Number of testing data: {}\".format(df_test.shape[0]))", "_____no_output_____" ], [ "category = {\n 'fake': 0,\n 'real': 1\n}\ndf_train['label'] = df_train['label'].map(category)\ndf_dev['label'] = df_dev['label'].map(category)", "_____no_output_____" ], [ "# df_train[df_train['label'] == 0]['idx'].value_counts()\n# for each in df_train[df_train['idx'] == 21934].values:\n# print(each[4])\ndf_train[df_train['idx'] == 21934]", "_____no_output_____" ], [ "df_train[df_train['label'] == 1]['context_idx'].value_counts(), df_dev[df_dev['label'] == 1]['context_idx'].value_counts()", "_____no_output_____" ], [ "df_train['label'].value_counts(), df_dev['label'].value_counts()", "_____no_output_____" ], [ "# df_my_gold = pd.read_csv('./my_gold_dev.csv')\n# df_dev['label'] = df_my_gold['label']\n# df_dev.to_json('my_dev.json', orient='records')", "_____no_output_____" ], [ "label = []\nfor i in range(len(df_test)):\n if df_test['context_idx'][i] == 0:\n label.append('real')\n else:\n label.append('fake')\ndf_test['label'] = label\nprint(df_test['label'].value_counts())\ndf_test[['idx', 'context_idx', 'label']].to_csv('eval.csv', index=False)", "_____no_output_____" ], [ "# same idx will contain the same label\ndf_predicted = pd.read_csv('my_gold_dev.csv')\ndf_predicted['label'].value_counts()", "_____no_output_____" ], [ "diff, diff_with_root = 0, 0\nfor idx in df_predicted['idx'].unique():\n real_fake_counts = df_predicted[df_predicted['idx'] == idx]['label'].value_counts()\n real_fake_list = real_fake_counts.keys().to_list()\n if len(real_fake_list) != 1:\n # method 1: same as root\n root = df_predicted.loc[(df_predicted['idx'] == idx) & (df_predicted['context_idx'] == 0), 'label'].tolist()[0]\n\n # method 2: same as majority\n majority = real_fake_list[np.argmax(real_fake_counts)]\n\n df_predicted.loc[(df_predicted['idx'] == idx), 'label'] = majority\n \n if root != majority:\n diff_with_root += 1\n\n diff += 1\ndiff, diff_with_root", "_____no_output_____" ], [ "df_predicted['label'].value_counts()\ndf_predicted.to_csv('dev.csv', index=False)", "_____no_output_____" ], [ "df_train['combine'] = ['[CLS] '] + df_train['text'] + [' [SEP] '] + df_train['reply'] + [' [SEP]']", "_____no_output_____" ], [ "df_train['combine'].to_csv(r'LM/training.txt', header=None, index=None, sep=' ')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d011c308a1530cf1273c44ca0837489c3ec6c822
4,951
ipynb
Jupyter Notebook
ga1/GroupAssignment1_Template.ipynb
lfgberg/IST210
41f74e55e435f78cc34befdad67d46674c369dfb
[ "MIT" ]
null
null
null
ga1/GroupAssignment1_Template.ipynb
lfgberg/IST210
41f74e55e435f78cc34befdad67d46674c369dfb
[ "MIT" ]
null
null
null
ga1/GroupAssignment1_Template.ipynb
lfgberg/IST210
41f74e55e435f78cc34befdad67d46674c369dfb
[ "MIT" ]
null
null
null
21.526087
246
0.524137
[ [ [ "# Illegal Airplane Dealership ", "_____no_output_____" ], [ "### what is your idea?", "_____no_output_____" ], [ "An Illegal Airplane Dealership, with ECommerce!", "_____no_output_____" ], [ "### what makes it unique?", "_____no_output_____" ], [ "Where else are you going to buy an airplane? There are other companies that do this, but it is a very niche market. ", "_____no_output_____" ], [ "### is this a brand-new product or business, or are you borrowing from another business?", "_____no_output_____" ], [ "It is brand new in the aspect that we will be selling commercially, not militarily. Anyone with the proper credentials can pull up and buy an A-10 Warthog 2. ", "_____no_output_____" ], [ "### describe a typical business interaction or a day at your business.", "_____no_output_____" ], [ "A typical day in the business would include receiving potential buyer input to tailor the right aircraft for their needs. Another common interaction would be maintenance requests, fuel requests, and training on how to operate the aircraft. ", "_____no_output_____" ], [ "### list your 5 entities/tables and for each, provide details about what data will be stored in the entities/tables.", "_____no_output_____" ], [ "1. Transactions (real time data) \n\n* ID - int\n\n* Customer ID - int (REFERENCES CUSTOMER) \n\n* $ - float\n\n* IDs of Items - int (UPDATES INVENTORY) \n\n2. Inventory \n\n* ID - int\n\n* Aircraft ID - int (REFERENCES AIRCRAFT) \n\n* Quantity - int\n\n3. Staff \n\n* ID - int\n\n* Position - String \n\n* Name - String\n\n4. Customer \n\n* ID - int\n\n* Name - String\n\n* Billing info - String\n\n5. Aircraft \n\n* ID - int\n\n* Type - String\n\n* Color - String\n\n* Hours on frame - float \n\n* Condition - String\n\n* Cost - float\n\n6. Maintenance Tickets (real time data) \n\n* ID - int\n\n* Service IDs - int (REFERENCES SERVICES) \n\n* Customer ID - int (REFERENCES CUSTOMER) \n\n* Employee ID - int (REFERENCES STAFF) \n\n7. Services \n\n* ID - int\n\n* Name - String\n\n* Cost - float\n\n* Hours - float\n\n* Description - String", "_____no_output_____" ], [ "### provide a goal for your project ", "_____no_output_____" ], [ "We want to create an easy-to-use database that brings the dark secrets of illegal acquisition of fighter planes to the fingertips of our devoted buyers. Our motto is “Never seen that individual before in my life”. ", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d011d1074a6a6103cd3b52cd751f9d72c6f0a35c
64,056
ipynb
Jupyter Notebook
NeoML/docs/en/Python/tutorials/KMeans.ipynb
NValerij/neoml
ec534fee0cebf2a8f06975d52e8715e4fe6ea380
[ "ECL-2.0", "Apache-2.0" ]
1
2021-05-30T09:19:35.000Z
2021-05-30T09:19:35.000Z
NeoML/docs/en/Python/tutorials/KMeans.ipynb
NValerij/neoml
ec534fee0cebf2a8f06975d52e8715e4fe6ea380
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NeoML/docs/en/Python/tutorials/KMeans.ipynb
NValerij/neoml
ec534fee0cebf2a8f06975d52e8715e4fe6ea380
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
217.877551
56,356
0.91637
[ [ [ "Copyright © 2017-2021 ABBYY Production LLC", "_____no_output_____" ] ], [ [ "#@title\n# \n# 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# http://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_____" ] ], [ [ "# *k*-means clustering", "_____no_output_____" ], [ "[Download the tutorial as a Jupyter notebook](https://github.com/neoml-lib/neoml/blob/master/NeoML/docs/en/Python/tutorials/KMeans.ipynb)\n\nIn this tutorial, we will use the NeoML implementation of *k*-means clustering algorithm to clusterize a randomly generated dataset.\n\nThe tutorial includes the following steps:\n\n* [Generate the dataset](#Generate-the-dataset)\n* [Cluster the data](#Cluster-the-data)\n* [Visualize the results](#Visualize-the-results)", "_____no_output_____" ], [ "## Generate the dataset", "_____no_output_____" ], [ "*Note:* This section doesn't have any NeoML-specific code. It just generates a dataset. If you are not running this notebook, you may [skip](#Cluster-the-data) this section.", "_____no_output_____" ], [ "Let's generate a dataset of 4 clusters on the plane. Each cluster will be generated from center + noise taken from normal distribution for each coordinate.", "_____no_output_____" ] ], [ [ "import numpy as np\n\nnp.random.seed(451)\n\nn_dots = 128\nn_clusters = 4\ncenters = np.array([(-2., -2.),\n (-2., 2.),\n (2., -2.),\n (2., 2.)])\nX = np.zeros(shape=(n_dots, 2), dtype=np.float32)\ny = np.zeros(shape=(n_dots,), dtype=np.int32)\n\nfor i in range(n_dots):\n # Choose random center\n cluster_id = np.random.randint(0, n_clusters)\n y[i] = cluster_id\n # object = center + some noise\n X[i, 0] = centers[cluster_id][0] + np.random.normal(0, 1)\n X[i, 1] = centers[cluster_id][1] + np.random.normal(0, 1)", "_____no_output_____" ] ], [ [ "## Cluster the data", "_____no_output_____" ], [ "Now we'll create a `neoml.Clustering.KMeans` class that represents the clustering algorithm, and feed the data into it.", "_____no_output_____" ] ], [ [ "import neoml\n\nkmeans = neoml.Clustering.KMeans(max_iteration_count=1000,\n cluster_count=n_clusters,\n thread_count=4)\ny_pred, centers_pred, vars_pred = kmeans.clusterize(X)", "_____no_output_____" ] ], [ [ "Before going further let's take a look at the returned data.", "_____no_output_____" ] ], [ [ "print('y_pred')\nprint(' ', type(y_pred))\nprint(' ', y_pred.shape)\nprint(' ', y_pred.dtype)\n\nprint('centers_pred')\nprint(' ', type(centers_pred))\nprint(' ', centers_pred.shape)\nprint(' ', centers_pred.dtype)\n\nprint('vars_pred')\nprint(' ', type(vars_pred))\nprint(' ', vars_pred.shape)\nprint(' ', vars_pred.dtype)", "y_pred\n <class 'numpy.ndarray'>\n (128,)\n int32\ncenters_pred\n <class 'numpy.ndarray'>\n (4, 2)\n float64\nvars_pred\n <class 'numpy.ndarray'>\n (4, 2)\n float64\n" ] ], [ [ "As you can see, the `y_pred` array contains the cluster indices of each object. `centers_pred` and `disps_pred` contain centers and variances of each cluster.", "_____no_output_____" ], [ "## Visualize the results", "_____no_output_____" ], [ "In this section we'll draw both clusterizations: ground truth and predicted.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport matplotlib.pyplot as plt\n\ncolors = {\n 0: 'r',\n 1: 'g',\n 2: 'b',\n 3: 'y'\n}\n\n# Create figure with 2 subplots\nfig, axs = plt.subplots(ncols=2)\nfig.set_size_inches(10, 5)\n\n# Show ground truth\naxs[0].set_title('Ground truth')\naxs[0].scatter(X[:, 0], X[:, 1], marker='o', c=list(map(colors.get, y)))\naxs[0].scatter(centers[:, 0], centers[:, 1], marker='x', c='black')\n\n# Show NeoML markup\naxs[1].set_title('NeoML K-Means')\naxs[1].scatter(X[:, 0], X[:, 1], marker='o', c=list(map(colors.get, y_pred)))\naxs[1].scatter(centers_pred[:, 0], centers_pred[:, 1], marker='x', c='black')\n\nplt.show()", "_____no_output_____" ] ], [ [ "As you can see, *k*-means didn't clusterize the outliers correctly.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
d011d139f40c68ba31f764a16e9aab06a7d80740
4,817
ipynb
Jupyter Notebook
python_impresionador/for/For Enumerate.ipynb
joselucas77/Python
60a1eafa1d5b06b55cea806daeb9a90616845b04
[ "MIT" ]
null
null
null
python_impresionador/for/For Enumerate.ipynb
joselucas77/Python
60a1eafa1d5b06b55cea806daeb9a90616845b04
[ "MIT" ]
null
null
null
python_impresionador/for/For Enumerate.ipynb
joselucas77/Python
60a1eafa1d5b06b55cea806daeb9a90616845b04
[ "MIT" ]
null
null
null
27.525714
274
0.542661
[ [ [ "# Enumerate\n\n### Estrutura:\n\nO enumerate permite que você percorra uma lista e ao mesmo tempo tenha em uma variável o índice daquele item.\n\n- for normalmente", "_____no_output_____" ] ], [ [ "for item in lista:\n resto do código", "_____no_output_____" ] ], [ [ "funcionarios = ['Maria', 'José', 'Antônio', 'João', 'Francisco', 'Ana', 'Luiz', 'Paulo', 'Carlos', 'Manoel', 'Pedro', 'Francisca', 'Marcos', 'Raimundo', 'Sebastião', 'Antônia', 'Marcelo', 'Jorge', 'Márcia', 'Geraldo', 'Adriana', 'Sandra', 'Luis']\nfor funcionario in funcionarios:\n print(funcionario)", "Maria\nJosé\nAntônio\nJoão\nFrancisco\nAna\nLuiz\nPaulo\nCarlos\nManoel\nPedro\nFrancisca\nMarcos\nRaimundo\nSebastião\nAntônia\nMarcelo\nJorge\nMárcia\nGeraldo\nAdriana\nSandra\nLuis\n" ] ], [ [ "for i, item in enumerate(lista):\n resto do código", "_____no_output_____" ] ], [ [ "funcionarios = ['Maria', 'José', 'Antônio', 'João', 'Francisco', 'Ana', 'Luiz', 'Paulo', 'Carlos', 'Manoel', 'Pedro', 'Francisca', 'Marcos', 'Raimundo', 'Sebastião', 'Antônia', 'Marcelo', 'Jorge', 'Márcia', 'Geraldo', 'Adriana', 'Sandra', 'Luis']\n\nfor i, funcionario in enumerate(funcionarios):\n print('{} é o funcionário {}'.format(i, funcionario))", "0 é o funcionário Maria\n1 é o funcionário José\n2 é o funcionário Antônio\n3 é o funcionário João\n4 é o funcionário Francisco\n5 é o funcionário Ana\n6 é o funcionário Luiz\n7 é o funcionário Paulo\n8 é o funcionário Carlos\n9 é o funcionário Manoel\n10 é o funcionário Pedro\n11 é o funcionário Francisca\n12 é o funcionário Marcos\n13 é o funcionário Raimundo\n14 é o funcionário Sebastião\n15 é o funcionário Antônia\n16 é o funcionário Marcelo\n17 é o funcionário Jorge\n18 é o funcionário Márcia\n19 é o funcionário Geraldo\n20 é o funcionário Adriana\n21 é o funcionário Sandra\n22 é o funcionário Luis\n" ] ], [ [ "### Exemplo Prático\n\nVamos pegar um exemplo de nível mínimo de estoque. Em uma fábrica você tem vários produtos e não pode deixar que os produtos fiquem em falta. Para isso, foi definido uma quantidade mínima de estoque que os produtos precisam ter:\n\nIdentifique quais produtos estão abaixo do nível mínimo de estoque.", "_____no_output_____" ] ], [ [ "estoque = [1200, 300, 800, 1500, 1900, 2750, 400, 20, 23, 70, 90, 80, 1100, 999, 900, 880, 870, 50, 1111, 120, 300, 450, 800]\nprodutos = ['coca', 'pepsi', 'guarana', 'skol', 'brahma', 'agua', 'del valle', 'dolly', 'red bull', 'cachaça', 'vinho tinto', 'vodka', 'vinho branco', 'tequila', 'champagne', 'gin', 'guaracamp', 'matte', 'leite de castanha', 'leite', 'jurupinga', 'sprite', 'fanta']\nnivel_minimo = 50\n\nfor i, qtde in enumerate(estoque):\n if qtde < nivel_minimo:\n print(f'{produtos[i]} está abaixo do nível mínimo. Temos apenas {qtde} unidades')", "dolly está abaixo do nível mínimo. Temos apenas 20 unidades\nred bull está abaixo do nível mínimo. Temos apenas 23 unidades\n" ] ] ]
[ "markdown", "raw", "code", "raw", "code", "markdown", "code" ]
[ [ "markdown" ], [ "raw" ], [ "code" ], [ "raw" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d011edb3223a89438a7b62fc8bf9d8bb4c7f6d4d
49,459
ipynb
Jupyter Notebook
LBGM/nb/11. RandomGradientSamplingMNIST.ipynb
sidsrini12/FURL_Sim
55b420a771858c06f1aef58f48bb68302be36621
[ "MIT" ]
null
null
null
LBGM/nb/11. RandomGradientSamplingMNIST.ipynb
sidsrini12/FURL_Sim
55b420a771858c06f1aef58f48bb68302be36621
[ "MIT" ]
null
null
null
LBGM/nb/11. RandomGradientSamplingMNIST.ipynb
sidsrini12/FURL_Sim
55b420a771858c06f1aef58f48bb68302be36621
[ "MIT" ]
null
null
null
66.387919
26,136
0.749388
[ [ [ "import sys\nsys.path.append('../src')", "_____no_output_____" ], [ "import common.config as cfg\nfrom common.nb_utils import estimate_optimal_ncomponents, pca_transform\nfrom common.utils import get_device, Struct\nfrom data.loader import get_testloader, get_trainloader\nimport matplotlib.pyplot as plt\nfrom models.fcn import FCN\nfrom models.resnet import resnet18\nfrom models.model_op import get_model_grads, gradient_approximation\nfrom models.svm import SVM\nimport models.resnet as resnet\nimport numpy as np\nimport pickle as pkl\nimport torch as t\nimport time\nfrom tqdm.notebook import tqdm", "_____no_output_____" ], [ "dataset = 'mnist'\ninput_size = cfg.input_sizes[dataset]\noutput_size = cfg.output_sizes[dataset]\nlr = 1e-1\nsdirs_algo = 'pca' # 'qr'\nbs = 16\nepochs = 20", "_____no_output_____" ], [ "device = t.device('cuda:1')\nloss = t.nn.CrossEntropyLoss().to(device)", "_____no_output_____" ], [ "trainloader = get_trainloader(dataset, bs, True)\ntestloader = get_testloader(dataset, bs, True)", "_____no_output_____" ], [ "sdirs = []\nm = 6\nn_accum = m*50\nfor idx, (data, labels) in tqdm(enumerate(trainloader), total=len(trainloader), leave=False):\n x, y = data.to(device), labels.to(device)\n model = resnet.resnet18(num_channels=1, num_classes=output_size).to(device)\n optimizer = t.optim.SGD(model.parameters(), lr=lr)\n optimizer.zero_grad()\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n loss_val.backward()\n sdirs.append(get_model_grads(model))\n if idx == n_accum:\n break", "_____no_output_____" ], [ "sdirs_ = []\nfor i in range(len(sdirs[0])):\n sdirs_.append(np.hstack([_[i].reshape(-1, 1).cpu().numpy() for _ in sdirs]))\n[_.shape for _ in sdirs_]\nn0 = [_.shape[1] for _ in sdirs_]", "_____no_output_____" ], [ "n = [estimate_optimal_ncomponents(_, 0.99)[0] for _ in sdirs_]", "_____no_output_____" ], [ "plt.figure(figsize=(10, 2))\nplt.bar(range(len(n0)), [_/m for _ in n0], color='r')\nplt.bar(range(len(n)), [_/m for _ in n], color='k', alpha=0.6)\nplt.title('grads: {}, bs: {}, dataset: {}'.format(n_accum, bs, dataset))\nname = '../ckpts/nb/grads_{}_bs_{}_dataset_{}.png'.format(\n n_accum, bs, dataset\n)\nprint(name)\nplt.savefig(name, bbox_inches='tight', dpi=330)", "_____no_output_____" ] ], [ [ "# BS: 32 MNIST\n![](../ckpts/nb/grads_300_bs_16_dataset_mnist.png)\n![](../ckpts/nb/grads_200_bs_16_dataset_mnist.png)\n![](../ckpts/nb/grads_100_bs_16_dataset_mnist.png)\n![](../ckpts/nb/grads_50_bs_16_dataset_mnist.png)", "_____no_output_____" ], [ "# BS: 128 MNIST\n![](../ckpts/nb/grads_300_bs_128_dataset_mnist.png)\n![](../ckpts/nb/grads_200_bs_128_dataset_mnist.png)\n![](../ckpts/nb/grads_100_bs_128_dataset_mnist.png)\n![](../ckpts/nb/grads_50_bs_128_dataset_mnist.png)", "_____no_output_____" ] ], [ [ "if sdirs_algo=='pca':\n sdirs0, _ = pca_transform(sdirs0, n0)\n# sdirs1, _ = pca_transform(sdirs1, n1)\nelse:\n sdirs0, _ = np.linalg.qr(sdirs0)\n# sdirs1, _ = np.linalg.qr(sdirs1)\nsdirs0.shape, sdirs1.shape", "_____no_output_____" ], [ "sdirs = [[t.Tensor(sdirs0[:, _].reshape(output_size, input_size)), t.Tensor(sdirs1[:,_].reshape(output_size,))] for _ in range(sdirs0.shape[1])]", "_____no_output_____" ] ], [ [ "# pretraining", "_____no_output_____" ] ], [ [ "trainloader = get_trainloader(dataset, 256, False)\ntestloader = get_testloader(dataset, 256, False)", "_____no_output_____" ], [ "model = resnet.resnet18(num_channels=1, num_classes=output_size).to(device)\nmodel.load_state_dict(t.load('../ckpts/init/{}_resnet18.init'.format(dataset)))\n\ncorrecti = 0\nx_test = 0\nfor idx, (data, labels) in enumerate(testloader):\n x, y = data.to(device), labels.to(device)\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\ny_test = correcti/len(testloader.dataset)\nx_test, y_test", "_____no_output_____" ] ], [ [ "# w/o gradient approximation", "_____no_output_____" ] ], [ [ "model = resnet.resnet18(num_channels=1, num_classes=output_size).to(device)\nmodel.load_state_dict(t.load('../ckpts/init/{}_resnet18.init'.format(dataset)))\n\nxb_train, yb_train = [], []\nxb_test, yb_test =[], []\nfor _ in tqdm(range(1, epochs+1), leave=False):\n xb_train.append(_)\n correcti = 0\n for idx, (data, labels) in enumerate(trainloader):\n x, y = data.to(device), labels.to(device)\n optimizer = t.optim.SGD(model.parameters(), lr=lr)\n optimizer.zero_grad()\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n loss_val.backward()\n optimizer.step()\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n yb_train.append(correcti/len(trainloader.dataset))\n \n correcti = 0\n for idx, (data, labels) in enumerate(testloader):\n x, y = data.to(device), labels.to(device)\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n yb_test.append(correcti/len(testloader.dataset))\n print('{} \\t {:.4f} \\t {:.2f} \\t {:.2f}'.format(\n xb_train[-1], loss_val.item(), yb_train[-1], yb_test[-1]\n ))", "_____no_output_____" ] ], [ [ "# gradient approximation using all directions", "_____no_output_____" ] ], [ [ "model = resnet.resnet18(num_channels=1, num_classes=output_size).to(device)\nmodel.load_state_dict(t.load('../ckpts/init/{}_resnet18.init'.format(dataset)))\n\nxa_train, ya_train = [], []\nxa_test, ya_test = [], []\nfor _ in tqdm(range(1, epochs+1), leave=False):\n start = time.time()\n xa_train.append(_)\n xa_test.append(_)\n correcti = 0\n for idx, (data, labels) in enumerate(trainloader):\n x, y = data.to(device), labels.to(device)\n optimizer = t.optim.SGD(model.parameters(), lr=lr)\n optimizer.zero_grad()\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n loss_val.backward()\n _, error = gradient_approximation(model, sdirs, device, [])\n optimizer.step()\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n ya_train.append(correcti/len(trainloader.dataset))\n \n correcti = 0\n for idx, (data, labels) in enumerate(testloader):\n x, y = data.to(device), labels.to(device)\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n ya_test.append(correcti/len(testloader.dataset))\n print('{} \\t {:.4f} \\t {:.2f} \\t {:.2f}'.format(\n xa_train[-1], loss_val.item(), ya_train[-1], ya_test[-1]\n ))", "_____no_output_____" ] ], [ [ "# gradient approximation using n directions", "_____no_output_____" ] ], [ [ "n = 1\nmodel = resnet.resnet18(num_channels=1, num_classes=output_size).to(device)\nmodel.load_state_dict(t.load('../ckpts/init/{}_resnet18.init'.format(dataset)))\n\nxe_train, ye_train = [], []\nxe_test, ye_test = [], []\nfor _ in tqdm(range(1, epochs+1), leave=False):\n start = time.time()\n xe_train.append(_)\n xe_test.append(_)\n correcti = 0\n for idx, (data, labels) in enumerate(trainloader):\n x, y = data.to(device), labels.to(device)\n optimizer = t.optim.SGD(model.parameters(), lr=lr)\n optimizer.zero_grad()\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n loss_val.backward()\n _, error = gradient_approximation(\n model, \n [sdirs[idx]], device, [])\n optimizer.step()\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n ye_train.append(correcti/len(trainloader.dataset))\n \n correcti = 0\n for idx, (data, labels) in enumerate(testloader):\n x, y = data.to(device), labels.to(device)\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n ye_test.append(correcti/len(testloader.dataset))\n print('{} \\t {:.4f} \\t {:.2f} \\t {:.2f}'.format(\n xe_train[-1], loss_val.item(), ye_train[-1], ye_test[-1]\n ))", "_____no_output_____" ], [ "n = 10\nmodel = resnet.resnet18(num_channels=1, num_classes=output_size).to(device)\nmodel.load_state_dict(t.load('../ckpts/init/{}_resnet18.init'.format(dataset)))\n\nxc_train, yc_train = [], []\nxc_test, yc_test = [], []\nfor _ in tqdm(range(1, epochs+1), leave=False):\n start = time.time()\n xc_train.append(_)\n xc_test.append(_)\n correcti = 0\n for idx, (data, labels) in enumerate(trainloader):\n x, y = data.to(device), labels.to(device)\n optimizer = t.optim.SGD(model.parameters(), lr=lr)\n optimizer.zero_grad()\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n loss_val.backward()\n _, error = gradient_approximation(\n model, \n sdirs[idx: idx+n] , device, [])\n optimizer.step()\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n yc_train.append(correcti/len(trainloader.dataset))\n \n correcti = 0\n for idx, (data, labels) in enumerate(testloader):\n x, y = data.to(device), labels.to(device)\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n yc_test.append(correcti/len(testloader.dataset))\n print('{} \\t {:.4f} \\t {:.2f} \\t {:.2f}'.format(\n xc_train[-1], loss_val.item(), yc_train[-1], yc_test[-1]\n ))", "_____no_output_____" ], [ "n = 100\nmodel = resnet.resnet18(num_channels=1, num_classes=output_size).to(device)\nmodel.load_state_dict(t.load('../ckpts/init/{}_resnet18.init'.format(dataset)))\n\nxd_train, yd_train = [], []\nxd_test, yd_test = [], []\nfor _ in tqdm(range(1, epochs+1), leave=False):\n start = time.time()\n xd_train.append(_)\n xd_test.append(_)\n correcti = 0\n for idx, (data, labels) in enumerate(trainloader):\n x, y = data.to(device), labels.to(device)\n optimizer = t.optim.SGD(model.parameters(), lr=lr)\n optimizer.zero_grad()\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n loss_val.backward()\n _, error = gradient_approximation(\n model, \n sdirs[idx: idx+n], device, [])\n optimizer.step()\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n yd_train.append(correcti/len(trainloader.dataset))\n \n correcti = 0\n for idx, (data, labels) in enumerate(testloader):\n x, y = data.to(device), labels.to(device)\n y_hat = model(x)\n loss_val = loss(y_hat, y)\n predi = y_hat.argmax(1, keepdim=True)\n correcti += predi.eq(y.view_as(predi)).sum().item()\n yd_test.append(correcti/len(testloader.dataset))\n print('{} \\t {:.4f} \\t {:.2f} \\t {:.2f}'.format(\n xd_train[-1], loss_val.item(), yd_train[-1], yd_test[-1]\n ))", "_____no_output_____" ], [ "plt.figure()\nplt.plot([x_test]+xb_train, [y_test]+yb_test, label='SGD', c='r')\n# plt.plot([x_test]+xa_train, [y_test]+ya_test, label='SGD {}-approx.'.format(len(sdirs)), c='b')\nplt.plot([x_test]+xc_train, [y_test]+yc_test, label='SGD 10-approx.', c='g')\nplt.plot([x_test]+xd_train, [y_test]+yd_test, label='SGD 100-approx.', c='k')\nplt.plot([x_test]+xe_train, [y_test]+ye_test, label='SGD 1-approx.', c='c')\n\nhistory = {\n 'test': [x_test, y_test],\n# 'a': [xa_train, ya_train, xa_test, ya_test],\n 'b': [xb_train, yb_train, xb_test, yb_test],\n 'c': [xc_train, yc_train, xc_test, yc_test],\n 'd': [xd_train, yd_train, xd_test, yd_test],\n 'e': [xe_train, ye_train, xe_test, ye_test],\n}\n\nname = 'clf_{}_{}_algo_{}_bs_{}_sgd_vs_sgd_approx_random_grad_sampling'.format(\n 'resnet18', dataset, sdirs_algo, bs)\nprint(name)\n\npkl.dump(history, open('../ckpts/history/{}.pkl'.format(name), 'wb'))\n\nplt.xlabel('epochs')\nplt.ylabel('accuracy')\nplt.legend()\nplt.savefig(\n '../ckpts/plots/{}.png'.format(name), \n dpi=300, bbox_inches='tight'\n)", "clf_resnet18_mnist_algo_pca_bs_16_sgd_vs_sgd_approx_random_grad_sampling\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d011fc278750325b1f6d177d8210b667435765f5
12,968
ipynb
Jupyter Notebook
data/notebooks/score.ipynb
jimmyrocks/valhalla-jupyter
cbccd6a2feb8a59454d73f7ef42d57305a3ee8d6
[ "MIT" ]
1
2019-07-19T17:33:57.000Z
2019-07-19T17:33:57.000Z
data/notebooks/score.ipynb
jimmyrocks/valhalla-jupyter
cbccd6a2feb8a59454d73f7ef42d57305a3ee8d6
[ "MIT" ]
null
null
null
data/notebooks/score.ipynb
jimmyrocks/valhalla-jupyter
cbccd6a2feb8a59454d73f7ef42d57305a3ee8d6
[ "MIT" ]
null
null
null
30.80285
111
0.427051
[ [ [ "lat = 40.229730557967\nlon = -74.002934930983\n\nprofile = [\n {\n \"key\": \"natural\",\n \"value\": \"beach\",\n \"distance_within\": 15,\n \"type\": \"bicycle\",\n \"weight\": 20\n },\n {\n \"key\": \"name\",\n \"value\": \"Newark Penn Station\",\n \"distance_within\": 60,\n \"type\": \"auto\",\n \"weight\": 10\n },\n {\n \"key\": \"name\",\n \"value\": \"Hurley School (historical)\",\n \"distance_within\": 20,\n \"type\": \"auto\",\n \"weight\": 10\n },\n {\n \"key\": \"name\",\n \"value\": \"Sandy Hook Lighthouse\",\n \"distance_within\": 30,\n \"type\": \"auto\",\n \"weight\": 10\n },\n {\n \"key\": \"amenity\",\n \"value\": \"pub\",\n \"distance_within\": 5,\n \"type\": \"pedestrian\",\n \"weight\": 20\n },\n {\n \"key\": \"amenity\",\n \"value\": \"cafe\",\n \"distance_within\": 5,\n \"type\": \"pedestrian\",\n \"weight\": 20\n },\n {\n \"key\": \"amenity\",\n \"value\": \"restaurant\",\n \"distance_within\": 5,\n \"type\": \"pedestrian\",\n \"weight\": 20\n },\n {\n \"key\": \"highway\",\n \"value\": \"cycleway\",\n \"distance_within\": 10,\n \"type\": \"bicycle\",\n \"weight\": 20\n },\n]", "_____no_output_____" ], [ "query_fields = \"\"\"\n[\n'access',\n'addr:housename',\n'addr:housenumber',\n'addr:interpolation',\n'admin_level',\n'aerialway',\n'aeroway',\n'amenity',\n'area',\n'barrier',\n'bicycle',\n'brand',\n'bridge',\n'boundary',\n'building',\n'construction',\n'covered',\n'culvert',\n'cutting',\n'denomination',\n'disused',\n'embankment',\n'foot',\n'generator:source',\n'harbour',\n'highway',\n'historic',\n'horse',\n'intermittent',\n'junction',\n'landuse',\n'layer',\n'leisure',\n'lock',\n'man_made',\n'military',\n'motorcar',\n'name',\n'natural',\n'office',\n'oneway',\n'operator',\n'place',\n'population',\n'power',\n'power_source',\n'public_transport',\n'railway',\n'ref',\n'religion',\n'route',\n'service',\n'shop',\n'sport',\n'surface',\n'toll',\n'tourism',\n'tower:type',\n'tunnel',\n'water',\n'waterway',\n'wetland',\n'width',\n'wood'\n]\n\"\"\"\n", "_____no_output_____" ], [ "import psycopg2\ndef get_buffer(lat, lon, key_query, distance_in_meters):\n\n conn = psycopg2.connect(host=\"postgres\",database=\"osm\", user=\"osm\", password=\"osm\")\n cursor = conn.cursor()\n query_fields_2 = query_fields.replace('\\'', '\"')\n \n cursor.execute(\"\"\"\n SELECT name, keys,\n ST_X(closest_point) as lon,\n ST_Y(closest_point) as lat,\n distance\n FROM (\n SELECT *, ST_Transform(ST_ClosestPoint(way, \n ST_TRANSFORM(\n ST_SETSRID(\n ST_GeomFromText(\n 'POINT(%f %f)'\n ),\n 4326),\n 3857)), 4326) as closest_point,\n ST_DISTANCE(\n way,\n ST_TRANSFORM(\n ST_SETSRID(\n ST_GeomFromText(\n 'POINT(%f %f)'\n ),\n 4326),\n 3857)\n ) AS distance\n FROM (\n SELECT osm_id, name, way,\n hstore(ARRAY%s, ARRAY%s) as keys\n from planet_osm_polygon\n UNION ALL\n SELECT osm_id, name, way,\n hstore(ARRAY%s, ARRAY%s) as keys\n from planet_osm_point\n UNION ALL\n SELECT osm_id, name, way,\n hstore(ARRAY%s, ARRAY%s) as keys\n from planet_osm_line) osm WHERE\n ST_DWithin(way,\n ST_TRANSFORM(\n ST_SETSRID(\n ST_GeomFromText(\n 'POINT(%f %f)'\n ),\n 4326),\n 3857), %f)\n AND %s\n ) nearby ORDER BY DISTANCE LIMIT 2\n \"\"\" % (lon, lat, lon, lat,\n query_fields, query_fields_2, \n query_fields, query_fields_2, \n query_fields, query_fields_2, \n lon, lat, distance_in_meters,\n key_query))\n #select * FROM (\n # select\n # *,\n # ST_X(ST_Transform(st_centroid(way), 4326)) as lon,\n # ST_Y(ST_Transform(st_centroid(way), 4326)) as lat,\n # ST_DISTANCE(\n # way,\n # ST_TRANSFORM(\n # ST_SETSRID(\n # ST_GeomFromText(\n # 'POINT(%f %f)'\n # ),\n # 4326),\n # 3857)\n # ) AS distance\n # FROM\n # planet_osm_polygon\n #) AS subquery WHERE distance < %f \n #ORDER BY distance;\n #\"\"\" % (lon, lat, distance_in_meters))\n returned_data = []\n for record in cursor:\n returned_data.append(record)\n\n cursor.close()\n return returned_data\n\ncosting_multiplier = {\n 'auto': 100,\n 'bicycle': 30,\n 'pedestrian': 10\n}\n\nscores = list()\nfor setting in profile:\n key_query = \"keys->'%s' = '%s'\" % (setting['key'], setting['value'])\n distance_in_meters = setting['distance_within'] * costing_multiplier[setting['type']] * 100\n nearby = get_buffer(lat, lon, key_query, distance_in_meters)\n if len(nearby) == 0:\n nearby = [[None, None, None, None, None]]\n print (key_query, distance_in_meters, nearby[0][4])\n scores.append({'profile': setting, 'name': nearby[0][0],'lon': nearby[0][2], 'lat': nearby[0][3]})\n \n#print (scores)", "keys->'natural' = 'beach' 45000 663.919528442108\nkeys->'name' = 'Newark Penn Station' 600000 75817.8832295781\nkeys->'name' = 'Hurley School (historical)' 200000 14263.8246985781\nkeys->'name' = 'Sandy Hook Lighthouse' 300000 33883.9816776153\nkeys->'amenity' = 'pub' 5000 651.249237072539\nkeys->'amenity' = 'cafe' 5000 827.184895398681\nkeys->'amenity' = 'restaurant' 5000 710.12369094896\nkeys->'highway' = 'cycleway' 30000 6240.16576978148\n" ], [ "# Load the path from Valhalla\n\nimport requests\nimport json\n\ndef get_routed_distance(o_lon, o_lat, d_lon, d_lat, costing):\n url = \"http://valhalla:8002/route\"\n data = {\n \"locations\":[\n {\n \"lat\":o_lat,\n \"lon\":o_lon,\n \"type\":\"break\"\n },{\n \"lat\":d_lat,\n \"lon\":d_lon,\n \"type\":\"break\"\n }\n ],\n \"costing\":costing,\n \"directions_options\":{\n \"units\":\"miles\"\n }\n }\n\n data_json = json.dumps(data)\n response = requests.post(url, data=data_json)\n response_obj = json.loads(response.text)\n #distance = response_obj['trip']['summary']['length']\n time_in_seconds = response_obj['trip']['summary']['time']\n #west = response_obj['trip']['summary']['min_lon']\n #south = response_obj['trip']['summary']['min_lat']\n #east = response_obj['trip']['summary']['max_lon']\n #north = response_obj['trip']['summary']['max_lat']\n #geometry = decode_geometry(response_obj['trip']['legs'][0]['shape'])\n #print (distance)\n #print (time_in_seconds)\n return time_in_seconds", "_____no_output_____" ], [ "total_weights = 0\ntotal_weighted_values = 0\nfor score in scores:\n ideal_distance = (score['profile']['distance_within'] * 60)\n value = 0\n if (score['lon'] and score['lat']):\n time = get_routed_distance(lon, lat, score['lon'], score['lat'], score['profile']['type'])\n\n if time > ideal_distance:\n value = 100 - (((time - ideal_distance) / 60) * 2)\n elif time < ideal_distance:\n value = 100 + (((ideal_distance - time) / 60) * 0.5)\n else:\n value = 100\n\n if value > 200:\n value = 200\n elif value < 0:\n value = 0\n\n score['time'] = time\n score['ideal_time'] = ideal_distance\n score['value'] = value\n score['weighted_time'] = value * score['profile']['weight']\n total_weights = total_weights + score['profile']['weight']\n total_weighted_values = total_weighted_values + score['weighted_time']\n print(score['profile']['key'],score['profile']['value'],score['profile']['weight'],score['value'])\n \n \nfinal_score = (total_weighted_values / total_weights)\nprint('-------------------------') \nprint (final_score)", "natural beach 20 106.48333333333333\nname Newark Penn Station 10 102.25833333333334\nname Hurley School (historical) 10 103.35\nname Sandy Hook Lighthouse 10 89.16666666666667\namenity pub 20 91.06666666666666\namenity cafe 20 92.06666666666666\namenity restaurant 20 88.6\nhighway cycleway 20 68.7\n-------------------------\n91.43141025641026\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
d011fe9f38c6d241bbe63157206656e031bbf7e4
510,519
ipynb
Jupyter Notebook
Model backlog/EfficientNet/EfficientNetB5/169 - EfficientNetB5 - Reg - Big Classifier Max.ipynb
ThinkBricks/APTOS2019BlindnessDetection
e524fd69f83a1252710076c78b6a5236849cd885
[ "MIT" ]
23
2019-09-08T17:19:16.000Z
2022-02-02T16:20:09.000Z
Model backlog/EfficientNet/EfficientNetB5/169 - EfficientNetB5 - Reg - Big Classifier Max.ipynb
ThinkBricks/APTOS2019BlindnessDetection
e524fd69f83a1252710076c78b6a5236849cd885
[ "MIT" ]
1
2020-03-10T18:42:12.000Z
2020-09-18T22:02:38.000Z
Model backlog/EfficientNet/EfficientNetB5/169 - EfficientNetB5 - Reg - Big Classifier Max.ipynb
ThinkBricks/APTOS2019BlindnessDetection
e524fd69f83a1252710076c78b6a5236849cd885
[ "MIT" ]
16
2019-09-21T12:29:59.000Z
2022-03-21T00:42:26.000Z
135.957124
84,356
0.744313
[ [ [ "## 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 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.callbacks import EarlyStopping, ReduceLROnPlateau, Callback, LearningRateScheduler\nfrom keras.layers import Dense, Dropout, GlobalAveragePooling2D, GlobalMaxPooling2D, Input, Flatten, BatchNormalization, Activation\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-data-split/hold-out.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')\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])\n\n# Preprocecss data\nX_train[\"id_code\"] = X_train[\"id_code\"].apply(lambda x: x + \".png\")\nX_val[\"id_code\"] = X_val[\"id_code\"].apply(lambda x: x + \".png\")\ntest[\"id_code\"] = test[\"id_code\"].apply(lambda x: x + \".png\")\ndisplay(X_train.head())", "Number of train samples: 2929\nNumber of validation samples: 733\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_____" ] ], [ [ "train_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(base_path, save_path, image_id, HEIGHT, 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 \n# Pre-procecss train set\nfor i, image_id in enumerate(X_train['id_code']):\n preprocess_image(train_base_path, train_dest_path, image_id, HEIGHT, WIDTH)\n \n# Pre-procecss validation set\nfor i, image_id in enumerate(X_val['id_code']):\n preprocess_image(train_base_path, validation_dest_path, image_id, HEIGHT, WIDTH)\n \n# Pre-procecss test set\nfor i, image_id in enumerate(test['id_code']):\n preprocess_image(test_base_path, test_dest_path, image_id, HEIGHT, WIDTH)", "_____no_output_____" ] ], [ [ "# Data generator", "_____no_output_____" ] ], [ [ "datagen=ImageDataGenerator(rescale=1./255, \n rotation_range=360,\n horizontal_flip=True,\n vertical_flip=True)\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=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 2929 validated image filenames.\nFound 733 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 = GlobalMaxPooling2D()(base_model.output)\n x = Dropout(0.5)(x)\n x = Dense(1024)(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = Dropout(0.5)(x)\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(-7, 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_max_pooling2d_1 (GlobalM (None, 2048) 0 swish_116[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 2048) 0 global_max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 1024) 2098176 dropout_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_117 (BatchN (None, 1024) 4096 dense_1[0][0] \n__________________________________________________________________________________________________\nactivation_40 (Activation) (None, 1024) 0 batch_normalization_117[0][0] \n__________________________________________________________________________________________________\ndropout_2 (Dropout) (None, 1024) 0 activation_40[0][0] \n__________________________________________________________________________________________________\nfinal_output (Dense) (None, 1) 1025 dropout_2[0][0] \n==================================================================================================\nTotal params: 30,616,817\nTrainable params: 2,101,249\nNon-trainable params: 28,515,568\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 - 56s - loss: 3.6864 - acc: 0.2126 - val_loss: 2.2876 - val_acc: 0.2898\nEpoch 2/5\n - 42s - loss: 2.0355 - acc: 0.2989 - val_loss: 1.7932 - val_acc: 0.2739\nEpoch 3/5\n - 42s - loss: 1.3178 - acc: 0.3542 - val_loss: 1.9237 - val_acc: 0.2653\nEpoch 4/5\n - 42s - loss: 1.3226 - acc: 0.3797 - val_loss: 1.8302 - val_acc: 0.2397\nEpoch 5/5\n - 42s - loss: 1.2150 - acc: 0.3888 - val_loss: 1.5631 - val_acc: 0.2126\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_max_pooling2d_1 (GlobalM (None, 2048) 0 swish_116[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 2048) 0 global_max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 1024) 2098176 dropout_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_117 (BatchN (None, 1024) 4096 dense_1[0][0] \n__________________________________________________________________________________________________\nactivation_40 (Activation) (None, 1024) 0 batch_normalization_117[0][0] \n__________________________________________________________________________________________________\ndropout_2 (Dropout) (None, 1024) 0 activation_40[0][0] \n__________________________________________________________________________________________________\nfinal_output (Dense) (None, 1) 1025 dropout_2[0][0] \n==================================================================================================\nTotal params: 30,616,817\nTrainable params: 30,442,033\nNon-trainable params: 174,784\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 - 132s - loss: 1.0718 - acc: 0.4170 - val_loss: 0.9465 - val_acc: 0.3780\nEpoch 2/20\n - 79s - loss: 0.8428 - acc: 0.4893 - val_loss: 0.8162 - val_acc: 0.3680\nEpoch 3/20\n - 79s - loss: 0.6449 - acc: 0.5577 - val_loss: 0.6129 - val_acc: 0.4265\nEpoch 4/20\n - 79s - loss: 0.5159 - acc: 0.6356 - val_loss: 0.4949 - val_acc: 0.7090\nEpoch 5/20\n - 79s - loss: 0.4497 - acc: 0.6687 - val_loss: 0.4369 - val_acc: 0.7504\nEpoch 6/20\n - 79s - loss: 0.4147 - acc: 0.6979 - val_loss: 0.3351 - val_acc: 0.7660\nEpoch 7/20\n - 80s - loss: 0.3866 - acc: 0.7112 - val_loss: 0.3645 - val_acc: 0.7589\nEpoch 8/20\n - 79s - loss: 0.3669 - acc: 0.7208 - val_loss: 0.4052 - val_acc: 0.7760\nEpoch 9/20\n - 79s - loss: 0.3639 - acc: 0.7172 - val_loss: 0.3453 - val_acc: 0.7632\nEpoch 10/20\n - 79s - loss: 0.3359 - acc: 0.7199 - val_loss: 0.3330 - val_acc: 0.7618\nEpoch 11/20\n - 79s - loss: 0.3127 - acc: 0.7355 - val_loss: 0.3715 - val_acc: 0.7589\nEpoch 12/20\n - 79s - loss: 0.2917 - acc: 0.7403 - val_loss: 0.3323 - val_acc: 0.8174\nEpoch 13/20\n - 79s - loss: 0.2658 - acc: 0.7668 - val_loss: 0.2836 - val_acc: 0.7789\nEpoch 14/20\n - 79s - loss: 0.2590 - acc: 0.7727 - val_loss: 0.3227 - val_acc: 0.8088\nEpoch 15/20\n - 79s - loss: 0.2444 - acc: 0.7786 - val_loss: 0.2977 - val_acc: 0.7917\nEpoch 16/20\n - 79s - loss: 0.2533 - acc: 0.7759 - val_loss: 0.3011 - val_acc: 0.7903\nEpoch 17/20\n - 79s - loss: 0.2264 - acc: 0.7951 - val_loss: 0.2744 - val_acc: 0.8160\nEpoch 18/20\n - 79s - loss: 0.2214 - acc: 0.7967 - val_loss: 0.3145 - val_acc: 0.7960\nEpoch 19/20\n - 79s - loss: 0.1857 - acc: 0.8170 - val_loss: 0.2873 - val_acc: 0.8188\nEpoch 20/20\n - 79s - loss: 0.2119 - acc: 0.7910 - val_loss: 0.3039 - val_acc: 0.8068\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.960\nValidation Cohen Kappa score: 0.902\nComplete set Cohen Kappa score: 0.949\n" ] ], [ [ "## Apply model to test set and output predictions", "_____no_output_____" ] ], [ [ "def apply_tta(model, generator, steps=10):\n step_size = generator.n//generator.batch_size\n preds_tta = []\n for i in range(steps):\n generator.reset()\n preds = model.predict_generator(generator, steps=step_size)\n preds_tta.append(preds)\n\n return np.mean(preds_tta, axis=0)\n\npreds = apply_tta(model, test_generator)\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_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "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" ] ]
d0120655733d8d486552e71dd835c97c3753ab06
11,211
ipynb
Jupyter Notebook
ch4_DL_computation/4.5 load and save.ipynb
gunpowder78/Dive-into-DL-TensorFlow2.0
a5af9941b2968741adb44eee9f8cd2e49f71cf49
[ "Apache-2.0" ]
null
null
null
ch4_DL_computation/4.5 load and save.ipynb
gunpowder78/Dive-into-DL-TensorFlow2.0
a5af9941b2968741adb44eee9f8cd2e49f71cf49
[ "Apache-2.0" ]
null
null
null
ch4_DL_computation/4.5 load and save.ipynb
gunpowder78/Dive-into-DL-TensorFlow2.0
a5af9941b2968741adb44eee9f8cd2e49f71cf49
[ "Apache-2.0" ]
null
null
null
43.119231
1,341
0.584337
[ [ [ "import tensorflow as tf\nimport numpy as np\nprint(tf.__version__)", "2.0.0\n" ] ], [ [ "## 4.5.1 load and save NDarray", "_____no_output_____" ] ], [ [ "import numpy as np\n\nx = tf.ones(3)\nx", "_____no_output_____" ], [ "np.save('x.npy', x)\nx2 = np.load('x.npy')\nx2", "_____no_output_____" ], [ "y = tf.zeros(4)\nnp.save('xy.npy',[x,y])\nx2, y2 = np.load('xy.npy', allow_pickle=True)\n(x2, y2)", "_____no_output_____" ], [ "mydict = {'x': x, 'y': y}\nnp.save('mydict.npy', mydict)\nmydict2 = np.load('mydict.npy', allow_pickle=True)\nmydict2", "_____no_output_____" ] ], [ [ "## 4.5.2 load and save model parameters", "_____no_output_____" ] ], [ [ "X = tf.random.normal((2,20))\nX", "_____no_output_____" ], [ "class MLP(tf.keras.Model):\n def __init__(self):\n super().__init__()\n self.flatten = tf.keras.layers.Flatten() # Flatten层将除第一维(batch_size)以外的维度展平\n self.dense1 = tf.keras.layers.Dense(units=256, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(units=10)\n\n def call(self, inputs): \n x = self.flatten(inputs) \n x = self.dense1(x) \n output = self.dense2(x) \n return output\n\nnet = MLP()\nY = net(X)\nY", "_____no_output_____" ], [ "net.save_weights(\"4.5saved_model.h5\")", "_____no_output_____" ], [ "net2 = MLP()\nnet2.load_weights(\"4.5saved_model.h5\")\nY2 = net2(X)\nY2 == Y", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d0120ab5994927c1a56410ac397826ecf6c2036c
41,761
ipynb
Jupyter Notebook
Analysis/3D-Analysis.ipynb
SkinLesionsResearch/NCPL
562e9664f77e14ed9b2655b82e8498b8a8ce5d2d
[ "MIT" ]
null
null
null
Analysis/3D-Analysis.ipynb
SkinLesionsResearch/NCPL
562e9664f77e14ed9b2655b82e8498b8a8ce5d2d
[ "MIT" ]
null
null
null
Analysis/3D-Analysis.ipynb
SkinLesionsResearch/NCPL
562e9664f77e14ed9b2655b82e8498b8a8ce5d2d
[ "MIT" ]
null
null
null
116.002778
30,160
0.825435
[ [ [ "#方法一,利用关键字\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport os, sys\nimport pandas as pd\n\nos.chdir(\"/home/jackie/ResearchArea/SkinCancerResearch/semi_skin_cancer\")\nsys.path.append(\"/home/jackie/ResearchArea/SkinCancerResearch/semi_skin_cancer\")", "_____no_output_____" ], [ "df = pd.read_csv(\"latex_generator/acfi_res.csv\")\ndf_max_acc_idx = df.groupby(by=[\"num_labeled\", \"lambda_param\", \"w\"])[\"Accuracy\"].idxmax()\ndf = df.iloc[df_max_acc_idx].reset_index(drop=True)\ndf = df[df[\"num_labeled\"]==500].reset_index(drop=True)\ndf", "_____no_output_____" ], [ "fig = plt.figure() #定义新的三维坐标轴\nax3 = plt.axes(projection='3d')\n\n#定义三维数据\nxx = np.arange(-5,5,0.5)\nyy = np.arange(-5,5,0.5)\nX, Y = np.meshgrid(xx, yy)\nZ = np.sin(X)+np.cos(Y)\n\nxx = df[\"lambda_param\"]\nyy = df[\"w\"]\nX, Y = np.meshgrid(xx, yy)\nZ = np.sin(X)+np.cos(Y)\n# Z = np.array(np.meshgrid(df[\"Accuracy\"]))\n\nprint(np.sin(X).shape, \", \", np.cos(Y).shape)\nprint(Z.shape)\n#作图\nax3.plot_surface(X,Y,Z,cmap='rainbow')\n#ax3.contour(X,Y,Z, zdim='z',offset=-2,cmap='rainbow) #等高线图,要设置offset,为Z的最小值\nplt.show()\n", "(7, 7) , (7, 7)\n(7, 7)\n" ], [ "X.shape", "_____no_output_____" ], [ "xx", "_____no_output_____" ], [ "X", "_____no_output_____" ], [ "from matplotlib.pyplot import imshow\nimport numpy as np\nfrom PIL import Image\n\n%matplotlib inline\npil_im = Image.open('Analysis/3d-Analysis-Example.png', 'r')\nimshow(np.asarray(pil_im))", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d0120b8aa5c28a86595c2462ce555de90a27027e
432
ipynb
Jupyter Notebook
docs/Notes.ipynb
UoB-HPC/minicombust
26fc17956d42971b07ef6052d46c5ee4d70e4fb2
[ "Apache-2.0" ]
3
2021-11-24T10:56:10.000Z
2022-02-01T12:05:41.000Z
docs/Notes.ipynb
UoB-HPC/minicombust
26fc17956d42971b07ef6052d46c5ee4d70e4fb2
[ "Apache-2.0" ]
null
null
null
docs/Notes.ipynb
UoB-HPC/minicombust
26fc17956d42971b07ef6052d46c5ee4d70e4fb2
[ "Apache-2.0" ]
1
2022-01-02T13:15:11.000Z
2022-01-02T13:15:11.000Z
20.571429
175
0.592593
[ [ [ "# Notes in progress\n\n* Ali Thari in his load-balancing paper describes a LES-based model using FGM in PRECISE. This is massively different from our proposed RANS-based, ??? combustion model.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
d01218eda0e85dd28e7909bea11a534719f9a172
268,808
ipynb
Jupyter Notebook
notebooks/exp43_analysis.ipynb
CoAxLab/infomercial
fa5d1c1e5c1351735dda2961a2a94f71cd17e270
[ "MIT" ]
4
2019-11-14T03:13:25.000Z
2021-01-04T17:30:23.000Z
notebooks/exp43_analysis.ipynb
CoAxLab/infomercial
fa5d1c1e5c1351735dda2961a2a94f71cd17e270
[ "MIT" ]
null
null
null
notebooks/exp43_analysis.ipynb
CoAxLab/infomercial
fa5d1c1e5c1351735dda2961a2a94f71cd17e270
[ "MIT" ]
null
null
null
673.704261
132,320
0.951873
[ [ [ "# Exp 43 analysis\n\nSee `./informercial/Makefile` for experimental\ndetails.", "_____no_output_____" ] ], [ [ "import os\nimport numpy as np\n\nfrom IPython.display import Image\nimport matplotlib\nimport matplotlib.pyplot as plt`\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport seaborn as sns\nsns.set_style('ticks')\n\nmatplotlib.rcParams.update({'font.size': 16})\nmatplotlib.rc('axes', titlesize=16)\n\nfrom infomercial.exp import meta_bandit\nfrom infomercial.local_gym import bandit\nfrom infomercial.exp.meta_bandit import load_checkpoint\n\nimport gym", "_____no_output_____" ], [ "# ls ../data/exp2*", "_____no_output_____" ] ], [ [ "# Load and process data", "_____no_output_____" ] ], [ [ "data_path =\"/Users/qualia/Code/infomercial/data/\"\nexp_name = \"exp43\"\nbest_params = load_checkpoint(os.path.join(data_path, f\"{exp_name}_best.pkl\"))\nsorted_params = load_checkpoint(os.path.join(data_path, f\"{exp_name}_sorted.pkl\"))", "_____no_output_____" ], [ "best_params", "_____no_output_____" ] ], [ [ "# Performance\n\nof best parameters", "_____no_output_____" ] ], [ [ "env_name = 'BanditOneHigh2-v0'\nnum_episodes = 20*100\n\n# Run w/ best params\nresult = meta_bandit(\n env_name=env_name,\n num_episodes=num_episodes, \n lr=best_params[\"lr\"], \n tie_threshold=best_params[\"tie_threshold\"],\n seed_value=19,\n save=\"exp43_best_model.pkl\"\n)", "_____no_output_____" ], [ "# Plot run\nepisodes = result[\"episodes\"]\nactions =result[\"actions\"]\nscores_R = result[\"scores_R\"]\nvalues_R = result[\"values_R\"]\nscores_E = result[\"scores_E\"]\nvalues_E = result[\"values_E\"]\n\n# Get some data from the gym...\nenv = gym.make(env_name)\nbest = env.best\nprint(f\"Best arm: {best}, last arm: {actions[-1]}\")\n\n# Init plot\nfig = plt.figure(figsize=(6, 14))\ngrid = plt.GridSpec(5, 1, wspace=0.3, hspace=0.8)\n\n# Do plots:\n# Arm\nplt.subplot(grid[0, 0])\nplt.scatter(episodes, actions, color=\"black\", alpha=.5, s=2, label=\"Bandit\")\nplt.plot(episodes, np.repeat(best, np.max(episodes)+1), \n color=\"red\", alpha=0.8, ls='--', linewidth=2)\nplt.ylim(-.1, np.max(actions)+1.1)\nplt.ylabel(\"Arm choice\")\nplt.xlabel(\"Episode\")\n\n# score\nplt.subplot(grid[1, 0])\nplt.scatter(episodes, scores_R, color=\"grey\", alpha=0.4, s=10, label=\"R\")\nplt.scatter(episodes, scores_E, color=\"purple\", alpha=0.9, s=10, label=\"E\")\nplt.ylabel(\"log score\")\nplt.xlabel(\"Episode\")\nplt.semilogy()\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n_ = sns.despine()\n\n# Q\nplt.subplot(grid[2, 0])\nplt.scatter(episodes, values_R, color=\"grey\", alpha=0.4, s=10, label=\"R\")\nplt.scatter(episodes, values_E, color=\"purple\", alpha=0.4, s=10, label=\"E\")\nplt.ylabel(\"log Q(s,a)\")\nplt.xlabel(\"Episode\")\nplt.semilogy()\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n_ = sns.despine()\n\n# -\nplt.savefig(\"figures/epsilon_bandit.pdf\", bbox_inches='tight')\nplt.savefig(\"figures/epsilon_bandit.eps\", bbox_inches='tight')", "Best arm: 0, last arm: 0\n" ] ], [ [ "# Sensitivity\n\nto parameter choices", "_____no_output_____" ] ], [ [ "total_Rs = [] \nties = []\nlrs = []\ntrials = list(sorted_params.keys())\nfor t in trials:\n total_Rs.append(sorted_params[t]['total_E'])\n ties.append(sorted_params[t]['tie_threshold'])\n lrs.append(sorted_params[t]['lr'])\n \n# Init plot\nfig = plt.figure(figsize=(10, 18))\ngrid = plt.GridSpec(4, 1, wspace=0.3, hspace=0.8)\n\n# Do plots:\n# Arm\nplt.subplot(grid[0, 0])\nplt.scatter(trials, total_Rs, color=\"black\", alpha=.5, s=6, label=\"total R\")\nplt.xlabel(\"Sorted params\")\nplt.ylabel(\"total R\")\n_ = sns.despine()\n\nplt.subplot(grid[1, 0])\nplt.scatter(trials, ties, color=\"black\", alpha=.3, s=6, label=\"total R\")\nplt.xlabel(\"Sorted params\")\nplt.ylabel(\"Tie threshold\")\n_ = sns.despine()\n\nplt.subplot(grid[2, 0])\nplt.scatter(trials, lrs, color=\"black\", alpha=.5, s=6, label=\"total R\")\nplt.xlabel(\"Sorted params\")\nplt.ylabel(\"lr\")\n_ = sns.despine()", "_____no_output_____" ] ], [ [ "# Distributions\n\nof parameters", "_____no_output_____" ] ], [ [ "# Init plot\nfig = plt.figure(figsize=(5, 6))\ngrid = plt.GridSpec(2, 1, wspace=0.3, hspace=0.8)\n\nplt.subplot(grid[0, 0])\nplt.hist(ties, color=\"black\")\nplt.xlabel(\"tie threshold\")\nplt.ylabel(\"Count\")\n_ = sns.despine()\n\nplt.subplot(grid[1, 0])\nplt.hist(lrs, color=\"black\")\nplt.xlabel(\"lr\")\nplt.ylabel(\"Count\")\n_ = sns.despine()", "_____no_output_____" ] ], [ [ "of total reward", "_____no_output_____" ] ], [ [ "# Init plot\nfig = plt.figure(figsize=(5, 2))\ngrid = plt.GridSpec(1, 1, wspace=0.3, hspace=0.8)\n\nplt.subplot(grid[0, 0])\nplt.hist(total_Rs, color=\"black\", bins=50)\nplt.xlabel(\"Total reward\")\nplt.ylabel(\"Count\")\nplt.xlim(0, 10)\n_ = sns.despine()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d012194d00c5b594185e2bea9f55e73fa66ef225
8,468
ipynb
Jupyter Notebook
notebooks/book1/04/imdb_mlp_bow_tf.ipynb
patel-zeel/pyprobml
027ef3c13a2a63d958e05fdedb68fd7b8f0e0261
[ "MIT" ]
null
null
null
notebooks/book1/04/imdb_mlp_bow_tf.ipynb
patel-zeel/pyprobml
027ef3c13a2a63d958e05fdedb68fd7b8f0e0261
[ "MIT" ]
1
2022-03-27T04:59:50.000Z
2022-03-27T04:59:50.000Z
notebooks/book1/04/imdb_mlp_bow_tf.ipynb
patel-zeel/pyprobml
027ef3c13a2a63d958e05fdedb68fd7b8f0e0261
[ "MIT" ]
2
2022-03-26T11:52:36.000Z
2022-03-27T05:17:48.000Z
44.104167
1,152
0.6077
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d0121b30e31e5247effdb888de55c983dfb397cf
16,536
ipynb
Jupyter Notebook
src/DDPG_algo/DDPG_Discrete.ipynb
JoyPang123/MineRL-Explore
4f527236571ea8a8d700d2d56c1718f2126d2d8d
[ "MIT" ]
1
2021-12-07T07:37:40.000Z
2021-12-07T07:37:40.000Z
src/DDPG_algo/DDPG_Discrete.ipynb
JoyPang123/snake_env
4f527236571ea8a8d700d2d56c1718f2126d2d8d
[ "MIT" ]
null
null
null
src/DDPG_algo/DDPG_Discrete.ipynb
JoyPang123/snake_env
4f527236571ea8a8d700d2d56c1718f2126d2d8d
[ "MIT" ]
null
null
null
38.189376
122
0.429729
[ [ [ "!pip install wandb\n!wandb login", "_____no_output_____" ], [ "from collections import deque\nimport random\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torchvision.transforms as transforms\nimport gym\n\nimport wandb", "_____no_output_____" ], [ "class Actor(nn.Module):\n def __init__(self, num_actions):\n super().__init__()\n\n # Create the layers for the model\n self.actor = nn.Sequential(\n nn.Conv2d(\n in_channels=3, out_channels=32,\n kernel_size=5, padding=2, stride=2\n ), # (32, 32, 32)\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=32, out_channels=64,\n kernel_size=3, padding=1, stride=2\n ), # (64, 16, 16)\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=64, out_channels=64,\n kernel_size=3, padding=1, stride=2\n ), # (64, 8, 8)\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=64, out_channels=128,\n kernel_size=3, padding=1, stride=2\n ), # (128, 4, 4)\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Flatten(start_dim=1), # (2048)\n nn.Linear(128 * 4 * 4, 512),\n nn.ReLU(),\n nn.Linear(512, num_actions),\n nn.Softmax(dim=-1)\n )\n\n def forward(self, x):\n return self.actor(x)\n\n\nclass Critic(nn.Module):\n def __init__(self, act_dim):\n super().__init__()\n\n # Create the layers for the model\n self.critic = nn.Sequential(\n nn.Conv2d(\n in_channels=3, out_channels=32,\n kernel_size=5, padding=2, stride=2\n ), # (32, 32, 32)\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=32, out_channels=64,\n kernel_size=3, padding=1, stride=2\n ), # (64, 16, 16)\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=64, out_channels=64,\n kernel_size=3, padding=1, stride=2\n ), # (64, 8, 8)\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=64, out_channels=128,\n kernel_size=3, padding=1, stride=2\n ), # (128, 4, 4)\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Flatten(start_dim=1), # (2048)\n )\n\n self.fc = nn.Sequential(\n nn.Linear(128 * 4 * 4 + act_dim, 512),\n nn.ReLU(),\n nn.Linear(512, 1),\n nn.Tanh()\n )\n\n def forward(self, state, action):\n x = self.critic(state)\n x = torch.cat([x, action], dim=1)\n x = self.fc(x)\n\n return x", "_____no_output_____" ], [ "class ReplayMemory:\n def __init__(self, max_len):\n self.replay = deque(maxlen=max_len)\n\n def store_experience(self, state, reward,\n action, next_state,\n done):\n self.replay.append([state, reward, action, next_state, done])\n\n def size(self):\n return len(self.replay)\n\n def sample(self, batch_size):\n if len(self.replay) < batch_size:\n return None\n\n return random.sample(self.replay, k=batch_size)", "_____no_output_____" ], [ "class DDPG:\n def __init__(self, memory_size, num_actions,\n actor_lr, critic_lr, gamma,\n tau, device, img_transforms):\n # Set up model\n self.actor = Actor(num_actions).to(device)\n self.target_actor = Actor(num_actions).to(device)\n self.target_actor.eval()\n self.critic = Critic(num_actions).to(device)\n self.target_critic = Critic(num_actions).to(device)\n self.target_critic.eval()\n\n # Set up optimizer and criterion\n self.critic_criterion = nn.MSELoss()\n self.actor_optim = torch.optim.Adam(self.actor.parameters(), lr=actor_lr)\n self.critic_optim = torch.optim.Adam(self.critic.parameters(), lr=critic_lr)\n\n # Set up transforms and other hyper-parameters\n self.device = device\n self.img_transforms = img_transforms\n self.num_actions = num_actions\n self.memory = ReplayMemory(memory_size)\n self.gamma = gamma\n self.tau = tau\n\n def choose_action(self, cur_state, eps):\n # Open evaluation mode\n self.actor.eval()\n\n # Exploration\n if np.random.uniform() < eps:\n action = np.random.randint(0, self.num_actions)\n else: # Exploitation\n cur_state = self.img_transforms(cur_state).to(self.device).unsqueeze(0)\n action_list = self.actor(cur_state)\n action = torch.argmax(action_list, dim=-1).item()\n\n # Open training mode\n self.actor.train()\n return action\n\n def actor_update(self, batch_data):\n # Separate the data into groups\n cur_state_batch = []\n\n for cur_state, *_ in batch_data:\n cur_state_batch.append(self.img_transforms(cur_state).unsqueeze(0))\n\n cur_state_batch = torch.cat(cur_state_batch, dim=0).to(self.device)\n actor_actions = F.gumbel_softmax(torch.log(F.softmax(self.actor(cur_state_batch), dim=1)), hard=True)\n\n loss = -self.critic(cur_state_batch, actor_actions).mean()\n self.actor_optim.zero_grad()\n loss.backward()\n self.actor_optim.step()\n\n def critic_update(self, batch_data):\n # Separate the data into groups\n cur_state_batch = []\n reward_batch = []\n action_batch = []\n next_state_batch = []\n done_batch = []\n\n for cur_state, reward, action, next_state, done in batch_data:\n cur_state_batch.append(self.img_transforms(cur_state).unsqueeze(0))\n reward_batch.append(reward)\n action_batch.append(action)\n next_state_batch.append(self.img_transforms(next_state).unsqueeze(0))\n done_batch.append(done)\n\n cur_state_batch = torch.cat(cur_state_batch, dim=0).to(self.device)\n reward_batch = torch.FloatTensor(reward_batch).to(self.device)\n action_batch = torch.LongTensor(action_batch)\n action_batch = torch.zeros(len(batch_data), self.num_actions).scatter_(\n 1, action_batch.unsqueeze(1), 1).to(self.device)\n next_state_batch = torch.cat(next_state_batch, dim=0).to(self.device)\n done_batch = torch.Tensor(done_batch).to(self.device)\n\n # Compute the TD error between eval and target\n Q_eval = self.critic(cur_state_batch, action_batch)\n next_action = F.softmax(self.target_actor(next_state_batch), dim=1)\n\n index = torch.argmax(next_action, dim=1).unsqueeze(1)\n next_action = torch.zeros_like(next_action).scatter_(1, index, 1).to(self.device)\n Q_target = reward_batch + self.gamma * (1 - done_batch) * self.target_critic(next_state_batch,\n next_action).squeeze(1)\n\n loss = self.critic_criterion(Q_eval.squeeze(1), Q_target)\n\n self.critic_optim.zero_grad()\n loss.backward()\n self.critic_optim.step()\n\n def soft_update(self):\n # EMA for both actor and critic network\n for param, target_param in zip(self.actor.parameters(), self.target_actor.parameters()):\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\n\n for param, target_param in zip(self.critic.parameters(), self.target_critic.parameters()):\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)", "_____no_output_____" ], [ "env = gym.make(\"snake:snake-v0\", mode=\"hardworking\")\ndevice = \"cpu\"\n\n# Set up environment hyperparameters\nnum_actions = env.action_space.n\n\n# Set up training hyperparameters\ntau = 0.05\nmax_time_steps = 100000\nmax_iter = 2000\ngamma = 0.9\nmemory_size = 2000\nbatch_size = 32\nactor_lr = 3e-4\ncritic_lr = 3e-4", "_____no_output_____" ], [ "def train(max_time_steps, max_iter, memory_size, \n num_actions, actor_lr, critic_lr,\n gamma, tau, device, batch_size):\n \n # Set up model training\n img_transforms = transforms.Compose([\n transforms.ToTensor(),\n transforms.Resize((64, 64))\n ])\n\n ddpg = DDPG(\n memory_size, num_actions, \n actor_lr, critic_lr, gamma,\n tau, device, img_transforms\n )\n max_reward = -1e-9\n\n running_reward = 0\n running_episodes = 0\n\n time_step = 0\n print_freq = max_iter * 2\n\n while time_step < max_time_steps:\n state = env.reset()\n current_ep_reward = 0\n\n for _ in range(max_iter):\n # Get reward and state\n actions = ddpg.choose_action(state[\"frame\"], 0.1)\n new_state, reward, done, _ = env.step(actions)\n\n current_ep_reward += reward\n ddpg.memory.store_experience(state[\"frame\"], reward, actions, new_state[\"frame\"], done)\n state = new_state\n\n if done:\n break\n \n # Wait for updating\n if ddpg.memory.size() < batch_size:\n continue\n\n batch_data = ddpg.memory.sample(batch_size)\n ddpg.critic_update(batch_data)\n ddpg.actor_update(batch_data)\n ddpg.soft_update()\n\n time_step += 1\n\n if time_step % print_freq == 0:\n avg_reward = running_reward / running_episodes\n\n print(f\"Iteration:{running_episodes}, get average reward: {avg_reward:.2f}\")\n\n running_reward = 0\n running_episodes = 0\n log = {\n \"avg_reward\": avg_reward,\n }\n wandb.log(log)\n\n if avg_reward > max_reward:\n max_reward = avg_reward\n torch.save(ddpg.actor.state_dict(), \"actor_best.pt\")\n torch.save(ddpg.critic.state_dict(), \"critic_best.pt\")\n \n running_reward += current_ep_reward\n running_episodes += 1", "_____no_output_____" ], [ "model_config = {\n \"gamma\": gamma,\n \"max_time_steps\": max_time_steps,\n \"memory size\": memory_size\n}\nrun = wandb.init(\n project=\"snake_RL\",\n resume=False,\n config=model_config,\n name=\"DDPG\"\n)\n\ntrain(\n max_time_steps, max_iter, memory_size, \n 4, actor_lr, critic_lr,\n gamma, tau, \"cpu\", batch_size\n)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0122bd1e38c53065c4254d698f71408a717664c
8,557
ipynb
Jupyter Notebook
module1-decision-trees/LS_DS_221_assignment.ipynb
SwetaSengupta/DS-Unit-2-Kaggle-Challenge
0ac09400f2de7029ce730698ded47a3476618009
[ "MIT" ]
null
null
null
module1-decision-trees/LS_DS_221_assignment.ipynb
SwetaSengupta/DS-Unit-2-Kaggle-Challenge
0ac09400f2de7029ce730698ded47a3476618009
[ "MIT" ]
null
null
null
module1-decision-trees/LS_DS_221_assignment.ipynb
SwetaSengupta/DS-Unit-2-Kaggle-Challenge
0ac09400f2de7029ce730698ded47a3476618009
[ "MIT" ]
null
null
null
40.173709
464
0.625219
[ [ [ "Lambda School Data Science\n\n*Unit 2, Sprint 2, Module 1*\n\n---", "_____no_output_____" ], [ "# Decision Trees\n\n## Assignment\n- [ ] [Sign up for a Kaggle account](https://www.kaggle.com/), if you don’t already have one. Go to our Kaggle InClass competition website. You will be given the URL in Slack. Go to the Rules page. Accept the rules of the competition. Notice that the Rules page also has instructions for the Submission process. The Data page has feature definitions.\n- [ ] Do train/validate/test split with the Tanzania Waterpumps data.\n- [ ] Begin with baselines for classification.\n- [ ] Select features. Use a scikit-learn pipeline to encode categoricals, impute missing values, and fit a decision tree classifier.\n- [ ] Get your validation accuracy score.\n- [ ] Get and plot your feature importances.\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\n## Stretch Goals\n\n### Reading\n\n- A Visual Introduction to Machine Learning\n - [Part 1: A Decision Tree](http://www.r2d3.us/visual-intro-to-machine-learning-part-1/)\n - [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) — _Don’t worry about understanding the code, just get introduced to the concepts. This 10 minute video has excellent diagrams and explanations._\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\n### Doing\n- [ ] Add your own stretch goal(s) !\n- [ ] Define a function to wrangle train, validate, and test sets in the same way. Clean outliers and engineer features. (For example, [what columns have zeros and shouldn't?](https://github.com/Quartz/bad-data-guide#zeros-replace-missing-values) What columns are duplicates, or nearly duplicates? Can you extract the year from date_recorded? Can you engineer new features, such as the number of years from waterpump construction to waterpump inspection?)\n- [ ] Try other [scikit-learn imputers](https://scikit-learn.org/stable/modules/impute.html).\n- [ ] Make exploratory visualizations and share on Slack.\n\n\n#### Exploratory visualizations\n\nVisualize the relationships between feature(s) and target. I recommend you do this with your training set, after splitting your data. \n\nFor this problem, you may want to create a new column to represent the target as a number, 0 or 1. For example:\n\n```python\ntrain['functional'] = (train['status_group']=='functional').astype(int)\n```\n\n\n\nYou can try [Seaborn \"Categorical estimate\" plots](https://seaborn.pydata.org/tutorial/categorical.html) for features with reasonably few unique values. (With too many unique values, the plot is unreadable.)\n\n- Categorical features. (If there are too many unique values, you can replace less frequent values with \"OTHER.\")\n- Numeric features. (If there are too many unique values, you can [bin with pandas cut / qcut functions](https://pandas.pydata.org/pandas-docs/stable/getting_started/basics.html?highlight=qcut#discretization-and-quantiling).)\n\nYou can try [Seaborn linear model plots](https://seaborn.pydata.org/tutorial/regression.html) with numeric features. For this classification problem, you may want to use the parameter `logistic=True`, but it can be slow.\n\nYou do _not_ need to use Seaborn, but it's nice because it includes confidence intervals to visualize uncertainty.\n\n#### High-cardinality categoricals\n\nThis code from a previous assignment demonstrates how to replace less frequent values with 'OTHER'\n\n```python\n# Reduce cardinality for NEIGHBORHOOD feature ...\n\n# Get a list of the top 10 neighborhoods\ntop10 = train['NEIGHBORHOOD'].value_counts()[:10].index\n\n# At locations where the neighborhood is NOT in the top 10,\n# replace the neighborhood with 'OTHER'\ntrain.loc[~train['NEIGHBORHOOD'].isin(top10), 'NEIGHBORHOOD'] = 'OTHER'\ntest.loc[~test['NEIGHBORHOOD'].isin(top10), 'NEIGHBORHOOD'] = 'OTHER'\n```\n", "_____no_output_____" ] ], [ [ "import 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 !pip install pandas-profiling==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_____" ], [ "# Check Pandas Profiling version\nimport pandas_profiling\npandas_profiling.__version__", "_____no_output_____" ], [ "# Old code for Pandas Profiling version 2.3\n# It can be very slow with medium & large datasets.\n# These parameters will make it faster.\n\n# profile = train.profile_report(\n# check_correlation_pearson=False,\n# correlations={\n# 'pearson': False,\n# 'spearman': False,\n# 'kendall': False,\n# 'phi_k': False,\n# 'cramers': False,\n# 'recoded': False,\n# },\n# plot={'histogram': {'bayesian_blocks_bins': False}},\n# )\n#\n\n# New code for Pandas Profiling version 2.4\nfrom pandas_profiling import ProfileReport\nprofile = ProfileReport(train, minimal=True).to_notebook_iframe()\n\nprofile", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code" ] ]
d0124ce2d20ce01c6b8730bfd2ab75f6421a1f47
271,686
ipynb
Jupyter Notebook
indoorLocalizationModel/sequential_lstm_prediction_advanced.ipynb
wuh0007/masterThesis_LSTM_indoorLocalization
3972ebda7f59ad75a2ea7dd1cbb8af30925bf2c4
[ "MIT" ]
null
null
null
indoorLocalizationModel/sequential_lstm_prediction_advanced.ipynb
wuh0007/masterThesis_LSTM_indoorLocalization
3972ebda7f59ad75a2ea7dd1cbb8af30925bf2c4
[ "MIT" ]
null
null
null
indoorLocalizationModel/sequential_lstm_prediction_advanced.ipynb
wuh0007/masterThesis_LSTM_indoorLocalization
3972ebda7f59ad75a2ea7dd1cbb8af30925bf2c4
[ "MIT" ]
null
null
null
32.851995
174
0.347265
[ [ [ "import pandas as pd\nimport numpy as np\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom os import listdir", "_____no_output_____" ], [ "from keras.preprocessing import sequence\nimport tensorflow as tf\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Conv1D, Input, Concatenate, GlobalMaxPooling1D, ConvLSTM2D\nfrom keras.layers import LSTM\nfrom keras.layers import Flatten\nfrom keras.layers import Dropout\nfrom keras.callbacks import EarlyStopping\nfrom keras import optimizers\nfrom keras.regularizers import l1,l2,l1_l2\n\nfrom keras.optimizers import Adam\nfrom keras.models import load_model\nfrom keras.callbacks import ModelCheckpoint", "_____no_output_____" ], [ "# split a univariate sequence into samples\ndef split_sequence(sequence, n_steps):\n\tX, y = list(), list()\n\tfor i in range(len(sequence)):\n\t\t# find the end of this pattern\n\t\tend_ix = i + n_steps\n# \t\tprint(end_ix, len(sequence))\n\t\tif end_ix == len(sequence):\n# \t\t\tprint(end_ix)\n\t\t\tseq_x, seq_y = sequence[i:end_ix], end_ix-1\n\t\t\tX.append(seq_x)\n\t\t\ty.append(seq_y) \n\t\t# check if we are beyond the sequence\n\t\tif end_ix > len(sequence)-1:\n\t\t\tbreak\n\t\t# gather input and output parts of the pattern\n\t\tseq_x, seq_y = sequence[i:end_ix], sequence[end_ix]\n\t\tX.append(seq_x)\n\t\ty.append(seq_y)\n# \treturn np.array(X), np.array(y)\n\treturn X, y", "_____no_output_____" ], [ "with open('output.txt') as f:\n content = f.readlines()\n# you may also want to remove whitespace characters like `\\n` at the end of each line\ncontent = [x.strip() for x in content] \n\nprocessed = []\nfor i in range(0, len(content)): \n a_list = content[i].split() \n map_object = map(int, a_list)\n list_of_integers = list(map_object)\n processed.append(list_of_integers)", "_____no_output_____" ], [ "# Reversing a list using reversed() \ndef Reverse(lst): \n return [ele for ele in reversed(lst)] \n\nprocessed_18 = []\nfor i in range(len(processed)):\n if len(processed[i]) == 18:\n processed_18.append(processed[i])\n processed_18.append(Reverse(processed[i]))\nprocessed_18", "_____no_output_____" ], [ "# choose a number of time steps\nn_steps = 3\n\nsamples = []\nsamples_output = []\n# split into samples\nfor i in range(len(processed_18)): \n X, y = split_sequence(processed_18[i], n_steps)\n samples.append(X)\n samples_output.append(y)", "_____no_output_____" ], [ "samples", "_____no_output_____" ], [ "samples_output", "_____no_output_____" ], [ "import itertools\nconcat = list(itertools.chain.from_iterable(samples))\nconcat_output = list(itertools.chain.from_iterable(samples_output))", "_____no_output_____" ], [ "concat,len(concat)", "_____no_output_____" ], [ "concat_output,len(concat_output)", "_____no_output_____" ], [ "concat_output = [str(x) for x in concat_output]\nconcat_output", "_____no_output_____" ], [ "b_set = set(tuple(x) for x in concat)\nconcat_set = [ list(x) for x in b_set ]\nconcat_set,len(concat_set)", "_____no_output_____" ], [ "from collections import defaultdict\n\ndef list_duplicates(seq):\n tally = defaultdict(list)\n for i,item in enumerate(seq):\n tally[item].append(i)\n return ((key,locs) for key,locs in tally.items() \n if len(locs)>1)\ndict_dup = dict()\nfor dup in sorted(list_duplicates(tuple(x) for x in concat)):\n dict_dup.update({dup[0] : dup[1]})\n print(dup)", "((0, 1, 2), [0, 32, 64, 96, 128, 160, 192, 224])\n((0, 3, 4), [256, 288, 320, 352])\n((0, 3, 6), [384, 416, 448, 480])\n((1, 2, 5), [1, 33, 65, 97, 129, 161, 193, 225, 259, 291, 323, 355, 389, 421, 455, 491])\n((1, 4, 3), [286, 318, 350, 382])\n((1, 4, 7), [412, 444, 474, 502])\n((2, 1, 0), [31, 63, 95, 127, 159, 191, 223, 255])\n((2, 1, 4), [285, 317, 349, 381, 411, 443, 473, 501])\n((2, 5, 4), [130, 162, 194, 226])\n((2, 5, 8), [2, 34, 66, 98, 260, 292, 324, 356, 390, 422, 456, 492])\n((3, 4, 1), [257, 289, 321, 353])\n((3, 4, 5), [156, 188, 220, 252])\n((3, 4, 7), [22, 56, 90, 122])\n((3, 6, 7), [133, 165, 385, 417])\n((3, 6, 9), [11, 41, 71, 103, 197, 229, 449, 481])\n((4, 1, 2), [258, 290, 322, 354, 388, 420, 454, 490])\n((4, 3, 0), [287, 319, 351, 383])\n((4, 3, 6), [10, 40, 70, 102, 132, 164, 196, 228])\n((4, 5, 2), [157, 189, 221, 253])\n((4, 7, 6), [413, 445])\n((4, 7, 8), [91, 123])\n((4, 7, 10), [23, 57, 475, 503])\n((5, 2, 1), [30, 62, 94, 126, 158, 190, 222, 254, 284, 316, 348, 380, 410, 442, 472, 500])\n((5, 4, 3), [131, 163, 195, 227])\n((5, 8, 7), [67, 99, 325, 357])\n((5, 8, 11), [3, 35, 261, 293, 391, 423, 457, 493])\n((6, 3, 0), [415, 447, 479, 511])\n((6, 3, 4), [21, 55, 89, 121, 155, 187, 219, 251])\n((6, 7, 4), [386, 418])\n((6, 7, 8), [134, 166, 345, 377])\n((6, 7, 10), [277, 311])\n((6, 9, 10), [72, 198, 328, 450])\n((6, 9, 12), [12, 42, 104, 230, 268, 298, 360, 482])\n((7, 4, 1), [387, 419, 453, 489])\n((7, 4, 3), [9, 39, 69, 101])\n((7, 6, 3), [154, 186, 414, 446])\n((7, 6, 9), [267, 297, 327, 359])\n((7, 8, 5), [92, 124, 346, 378])\n((7, 8, 11), [135, 167, 201, 237])\n((7, 10, 9), [216, 476])\n((7, 10, 11), [58, 312])\n((7, 10, 13), [24, 244, 278, 504])\n((8, 5, 2), [29, 61, 93, 125, 283, 315, 347, 379, 409, 441, 471, 499])\n((8, 7, 4), [68, 100])\n((8, 7, 6), [153, 185, 326, 358])\n((8, 7, 10), [215, 243])\n((8, 11, 10), [36, 168, 294, 424])\n((8, 11, 14), [4, 136, 202, 238, 262, 392, 458, 494])\n((9, 6, 3), [20, 54, 88, 120, 218, 250, 478, 510])\n((9, 6, 7), [276, 310, 344, 376])\n((9, 10, 7), [199, 451])\n((9, 10, 11), [73, 182, 329, 438])\n((9, 10, 13), [148, 404])\n((9, 12, 15), [13, 43, 105, 141, 171, 231, 269, 299, 361, 397, 427, 483])\n((10, 7, 4), [8, 38, 452, 488])\n((10, 7, 6), [266, 296])\n((10, 7, 8), [200, 236])\n((10, 9, 6), [87, 217, 343, 477])\n((10, 9, 12), [140, 170, 396, 426])\n((10, 11, 8), [59, 183, 313, 439])\n((10, 11, 14), [74, 110, 330, 366])\n((10, 13, 14), [25, 149, 279, 405])\n((10, 13, 16), [115, 245, 371, 505])\n((11, 8, 5), [28, 60, 282, 314, 408, 440, 470, 498])\n((11, 8, 7), [152, 184, 214, 242])\n((11, 10, 7), [37, 295])\n((11, 10, 9), [86, 169, 342, 425])\n((11, 10, 13), [114, 370])\n((11, 14, 13), [5, 75, 137, 203, 263, 331, 393, 459])\n((11, 14, 17), [111, 239, 367, 495])\n((12, 9, 6), [19, 53, 119, 249, 275, 309, 375, 509])\n((12, 9, 10), [147, 181, 403, 437])\n((12, 13, 14), [83, 211, 339, 467])\n((12, 15, 16), [14, 44, 78, 106, 142, 172, 206, 232, 270, 300, 334, 362, 398, 428, 462, 484])\n((13, 10, 7), [7, 235, 265, 487])\n((13, 10, 9), [139, 395])\n((13, 10, 11), [109, 365])\n((13, 12, 15), [77, 205, 333, 461])\n((13, 14, 11), [26, 84, 150, 212, 280, 340, 406, 468])\n((13, 14, 17), [47, 175, 303, 431])\n((13, 16, 15), [50, 116, 178, 246, 306, 372, 434, 506])\n((14, 11, 8), [27, 151, 213, 241, 281, 407, 469, 497])\n((14, 11, 10), [85, 113, 341, 369])\n((14, 13, 10), [6, 138, 264, 394])\n((14, 13, 12), [76, 204, 332, 460])\n((14, 13, 16), [49, 177, 305, 433])\n((15, 12, 9), [18, 52, 118, 146, 180, 248, 274, 308, 374, 402, 436, 508])\n((15, 12, 13), [82, 210, 338, 466])\n((15, 16, 13), [45, 107, 173, 233, 301, 363, 429, 485])\n((15, 16, 17), [15, 79, 143, 207, 271, 335, 399, 463])\n((16, 13, 10), [108, 234, 364, 486])\n((16, 13, 14), [46, 174, 302, 430])\n((16, 15, 12), [17, 51, 81, 117, 145, 179, 209, 247, 273, 307, 337, 373, 401, 435, 465, 507])\n((17, 14, 11), [112, 240, 368, 496])\n((17, 14, 13), [48, 176, 304, 432])\n((17, 16, 15), [16, 80, 144, 208, 272, 336, 400, 464])\n" ], [ "concat_output_processed = []\nfor i in range(len(concat_set)):\n b = dict_dup[tuple(concat_set[i])]\n c = [concat_output[i] for i in b]\n concat_output_processed.append(set(c))", "_____no_output_____" ], [ "concat_set, len(concat_set)", "_____no_output_____" ], [ "concat_output_processed, len(concat_output_processed)", "_____no_output_____" ], [ "for i in range(len(concat_output_processed)):\n concat_output_processed[i] = list(concat_output_processed[i])\n while (len(concat_output_processed[i]) < 2):\n concat_output_processed[i].append(concat_output_processed[i][0])\n concat_output_processed[i] = [int(x) for x in concat_output_processed[i]]", "_____no_output_____" ], [ "concat_output_processed", "_____no_output_____" ], [ "concat_output_processed_one = []\nfor i in range(len(concat_output_processed)):\n concat_output_processed_one.append(concat_output_processed[i][0])\n ", "_____no_output_____" ], [ "X, y = np.array(concat_set), np.array(concat_output_processed)\n# X, y = np.array(concat_set), np.array(concat_output_processed_one)\nX,y ", "_____no_output_____" ], [ "# X, y = np.array(concat_set), np.array(concat_output_processed)\nX, y = np.array(concat_set), np.array(concat_output_processed_one)\nX,y ", "_____no_output_____" ], [ "# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.externals.joblib import dump, load\nsc1 = StandardScaler()\nX = sc1.fit_transform(X)\n# sc2 = StandardScaler()\n# y = sc2.fit_transform(y.reshape(-1,1))", "_____no_output_____" ], [ "X, y", "_____no_output_____" ], [ "# reshape from [samples, timesteps] into [samples, timesteps, features]\nn_features = 1\nX = X.reshape((X.shape[0], X.shape[1], n_features))", "_____no_output_____" ], [ "X.shape", "_____no_output_____" ], [ "y.shape", "_____no_output_____" ], [ "model = Sequential()\nmodel.add(LSTM(128, return_sequences=False, kernel_regularizer=l2(0.01), input_shape=(3, 1)))\n# model.add(Flatten())\n# model.add(Dense(64, activation='relu'))\nmodel.add(Dense(1, activation='linear'))\n# model.compile(optimizer='adam', loss='mse')\n# model.fit(X, y, epochs=130, validation_split=0.1, batch_size=2)", "_____no_output_____" ], [ "model.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nlstm_6 (LSTM) (None, 128) 66560 \n_________________________________________________________________\ndense_8 (Dense) (None, 1) 129 \n=================================================================\nTotal params: 66,689\nTrainable params: 66,689\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "import os\nmodel_filename = 'model-{epoch:03d}-{loss:03f}.h5'\ncheckpoint_path = os.path.join('temp_seqpred/', model_filename)\nmonitor = EarlyStopping(monitor = 'loss', min_delta = 1e-3, patience = 100, verbose = 1, mode = 'auto')\ncheckpoint = ModelCheckpoint(filepath=checkpoint_path, verbose=1, monitor='loss',save_best_only=True, mode='auto') \nadam = optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, amsgrad=False)\nmodel.compile(optimizer = 'adam', loss = 'mse')", "_____no_output_____" ], [ "# Fitting our model [input_smallseq, input_medseq, input_origseq, input_smoothseq]\nprint('Train...')\nhistory = model.fit(X, y, callbacks = [monitor, checkpoint], verbose = 1, batch_size = 1, nb_epoch = 1000)", "Train...\n" ], [ "# serialize model to JSON\nmodel_json = model.to_json()\nwith open(\"/home/hongyu/Documents/Spring2020/ECE_research/signal_analysis/data_18points/3_section_sliding5/MSLSTM_models/lstm_nextMove.json\", \"w\") as json_file:\n json_file.write(model_json)\n# serialize weights to HDF5\n# model.save_weights(\"/home/hongyu/Documents/Spring2020/ECE_research/signal_analysis/data_18points/3_section_sliding5/MSLSTM_weights/MSLSTM_18pts_weight.h5\")\nprint(\"Saved model to disk\")", "Saved model to disk\n" ], [ "dump(sc1, 'std_scaler_nextMove.bin', compress=True)", "_____no_output_____" ], [ "from keras.models import model_from_json\n# load json and create model\n# json_file = open(\"/home/hongyu/Documents/Spring2020/ECE_research/signal_analysis/data_18points/3_section_sliding5/MSLSTM_models/MSLSTM_18pts_model.json\", 'r')\n# loaded_model_json = json_file.read()\n# json_file.close()\n# model = model_from_json(loaded_model_json)\n# load weights into new model\nmodel.load_weights(\"/home/hongyu/Documents/Spring2020/ECE_research/signal_analysis/data_18points/3_section_sliding5/MSLSTM_weights/model-959-0.057756-nextMove.h5\")\nprint(\"Loaded model from disk\")", "Loaded model from disk\n" ], [ "# test_input = np.array([[1, 4, 7],\n# [0, 1, 2],\n# [ 3, 6, 9]]) #[10, 8], [5, 18]\n# test_input = np.array([[ 8, 11, 10, 7],\n# [14, 13, 12, 15],\n# [14, 13, 10, 9]]) # [4,6] , [16,20], [12,20]\n# test_input = np.array([[14, 13, 12, 15],\n# [14, 13, 10, 9],\n# [11, 8, 7, 10],\n# [ 4, 1, 2, 5],\n# [ 0, 1, 2, 5],\n# [ 0, 3, 6, 9]])# 16, 12, 13, 8, 4, 5\ntest_input = np.array([[1, 4, 7],\n [0, 1, 2],\n [ 0, 3, 6],\n [3, 6, 9],\n [6, 3, 4],\n [0, 6, 8]]) #10, 5, 9, 12, 5, ?\n \ntest_input = sc1.transform(test_input)\ntest_input = test_input.reshape((6, 3, 1))\ntest_output = model.predict(test_input, verbose=0)\n# test_output = sc2.inverse_transform(test_output)\nprint(np.round(test_output))\n", "[[10.]\n [ 5.]\n [ 9.]\n [12.]\n [ 5.]\n [11.]]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01253079153b5e6ac710853715e07929d21c54d
126,721
ipynb
Jupyter Notebook
ipython_notebooks/reactions.ipynb
kgourgou/stochastic-simulations-class
5ee62f38758de91182431108d62796c709c869d3
[ "MIT" ]
null
null
null
ipython_notebooks/reactions.ipynb
kgourgou/stochastic-simulations-class
5ee62f38758de91182431108d62796c709c869d3
[ "MIT" ]
null
null
null
ipython_notebooks/reactions.ipynb
kgourgou/stochastic-simulations-class
5ee62f38758de91182431108d62796c709c869d3
[ "MIT" ]
null
null
null
253.442
41,376
0.90472
[ [ [ "<script>\n function code_toggle() {\n if (code_shown){\n $('div.input').hide('500');\n $('#toggleButton').val('Show Code')\n } else {\n $('div.input').show('500');\n $('#toggleButton').val('Hide Code')\n }\n code_shown = !code_shown\n }\n\n $( document ).ready(function(){\n code_shown=false;\n $('div.input').hide()\n });\n</script>\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" id=\"toggleButton\" value=\"Show Code\"></form>", "_____no_output_____" ] ], [ [ "# Importing some python libraries.\nimport numpy as np\nfrom numpy.random import randn,rand\nimport matplotlib.pyplot as pl\n\nfrom matplotlib.pyplot import plot\n\nimport seaborn as sns\n%matplotlib inline\n\n# Fixing figure sizes\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 10,5\n\n\n\nsns.set_palette('Reds_r')", "_____no_output_____" ] ], [ [ "# Reaction Network Homework\n\nIn this homework, we will study a very simple set of reactions by modelling it through three different ways. First, we shall employ an ODE model called the **Reaction Rate Equation**. Then, we will solve the **Chemical Langevin Equation** and, finally, we will simulate the exact model by \"solving\" the **Chemical Master Equation**. \n\nThe reaction network of choice shall be a simple birth-death process, described by the relations : \n\n$$\n\\begin{align}\n\\emptyset \\stackrel{a}{\\to} X,\\\\\nX \\stackrel{\\mu X}{\\to} \\emptyset.\n\\end{align}\n$$\n\n$X$ here is the population number.\n\nThroughout, we shall use $a=10$ and $\\mu=1.0$. \n\n## Reaction Rate Equation\n\nThe reaction rate equation corresponding to the system is \n\n$$\n\\begin{align}\n\\dot{x}=a-\\mu\\cdot x,\\\\\nx(0)=x_0.\n\\end{align}\n$$\n\nAs this is a linear equation, we can solve it exactly, with solution\n\n$$\nx(t)=x(t) = a/\\mu+(x_0-a/\\mu) e^{\\mu (-t)}\n$$\n\n", "_____no_output_____" ] ], [ [ "# Solution of the RRE\ndef x(t,x0=3,a=10.0,mu=1.0):\n return (x0-a/mu)*np.exp(-t*mu)+a/mu\n", "_____no_output_____" ] ], [ [ "We note that there is a stationary solution, $x(t)=a/\\mu$. From the exponential in the solution, we can see that this is an attracting fixed point.", "_____no_output_____" ] ], [ [ "t = np.linspace(0,3)\nx0list = np.array([0.5,1,15])\n\nsns.set_palette(\"Reds\",n_colors=3)\n\nfor x0 in x0list: \n pl.plot(t,x(t,x0),linewidth=4)\n\npl.title('Population numbers for different initial conditions.', fontsize=20)\npl.xlabel('Time',fontsize=20)", "_____no_output_____" ] ], [ [ "# Chemical Langevin Equation\n\nNext, we will model the system by using the CLE. For our particular birth/death process, this will be \n\n$$\ndX_t=(a-\\mu\\cdot X_t)dt+(\\sqrt{a}-\\sqrt{\\mu\\cdot X_t})dW.\n$$\n\nTo solve this, we shall use the Euler-Maruyama scheme from the previous homework. We fix a $\\Delta t$ positive. Then, the scheme shall be : \n\n$$\nX_{n+1}=X_n+(a-\\mu\\cdot X_n)\\Delta t+(\\sqrt{a}-\\sqrt{\\mu\\cdot X_t})\\cdot \\sqrt{\\Delta t}\\cdot z,\\ z\\sim N(0,1).\n$$", "_____no_output_____" ] ], [ [ "def EM(xinit,T,Dt=0.1,a=1,mu=2):\n '''\n Returns the solution of the CLE with parameters a, mu\n \n Arguments\n =========\n xinit : real, initial condition.\n Dt : real, stepsize of the Euler-Maruyama.\n T : real, final time to reach.\n a : real, parameter of the RHS. \n mu : real, parameter of the RHS.\n \n '''\n \n n = int(T/Dt) # number of steps to reach T\n X = np.zeros(n)\n z = randn(n)\n \n X[0] = xinit # Initial condition\n \n # EM method \n for i in xrange(1,n):\n X[i] = X[i-1] + Dt* (a-mu*X[i-1])+(np.sqrt(a)-np.sqrt(mu*X[i-1]))*np.sqrt(Dt)*z[i]\n \n return X\n ", "_____no_output_____" ] ], [ [ "Similarly to the previous case, here is a run with multiple initial conditions. ", "_____no_output_____" ] ], [ [ "T = 10 # final time to reach\nDt = 0.01 # time-step for EM\n\n# Set the palette to reds with ten colors\nsns.set_palette('Reds',10)\n\ndef plotPaths(T,Dt):\n n = int(T/Dt)\n t = np.linspace(0,T,n)\n\n xinitlist = np.linspace(10,15,10)\n\n for x0 in xinitlist : \n path = EM(xinit=x0,T=T,Dt=Dt,a=10.0,mu=1.0)\n pl.plot(t, path,linewidth=5)\n\n pl.xlabel('time', fontsize=20)\n pl.title('Paths for initial conditions between 1 and 10.', fontsize=20)\n \n return path\n \npath = plotPaths(T,Dt)\n\nprint 'Paths decay towards', path[np.size(path)-1]\nprint 'The stationary point is', 1.0", "Paths decay towards 10.0004633499\nThe stationary point is 1.0\n" ] ], [ [ "We notice that the asymptotic behavior of the CLE is the same as that of the RRE. The only notable difference is the initial random kicks in the paths, all because of the stochasticicity. ", "_____no_output_____" ], [ "\n## Chemical Master Equation\n\nFinally, we shall simulate the system exactly by using the Stochastic Simulation Algorithm (SSA). ", "_____no_output_____" ] ], [ [ "def SSA(xinit, nsteps, a=10.0, mu=1.0):\n '''\n Using SSA to exactly simulate the death/birth process starting\n from xinit and for nsteps. \n \n a and mu are parameters of the propensities.\n \n Returns\n =======\n path : array-like, the path generated. \n tpath: stochastic time steps\n '''\n \n \n path = np.zeros(nsteps)\n tpath= np.zeros(nsteps)\n \n path[0] = xinit # initial population\n \n u = rand(2,nsteps) # pre-pick all the uniform variates we need\n \n for i in xrange(1,nsteps):\n \n # The propensities will be normalized\n tot_prop = path[i-1]*mu+a\n prob = path[i-1]*mu/tot_prop # probability of death \n \n if(u[0,i]<prob):\n # Death \n path[i] = path[i-1]-1 \n else:\n # Birth\n path[i] = path[i-1]+1\n \n # Time stayed at current state \n tpath[i] = -np.log(u[1,i])*1/tot_prop\n \n \n tpath = np.cumsum(tpath)\n return path, tpath ", "_____no_output_____" ] ], [ [ "Now that we have SSA setup, we can run multiple paths and compare the results to the previous cases.", "_____no_output_____" ] ], [ [ "# Since the paths below are not really related\n# let's use a more interesting palette \n# for the plot. \n\nsns.set_palette('hls',1)\n\nfor _ in xrange(1):\n path, tpath = SSA(xinit=1,nsteps=100)\n\n # Since this is the path of a jump process\n # I'm switching from \"plot\" to \"step\" \n # to get the figure right. :) \n pl.step(tpath,path,linewidth=5,alpha=0.9)\n\npl.title('One path simulated with SSA, $a<\\mu$. ', fontsize=20);\npl.xlabel('Time', fontsize=20)\n\n", "_____no_output_____" ], [ "# Since the paths below are not really related\n# let's use a more interesting palette \n# for the plot. \n\nsns.set_palette('hls',3)\n\nfor _ in xrange(3):\n path, tpath = SSA(xinit=1,nsteps=100)\n\n # Since this is the path of a jump process\n # I'm switching from \"plot\" to \"step\" \n # to get the figure right. :) \n pl.step(tpath,path,linewidth=5,alpha=0.9)\n\npl.title('Three paths simulated with SSA, $a<\\mu$. ', fontsize=20);\npl.xlabel('Time', fontsize=20)\n", "_____no_output_____" ] ], [ [ "We can see three chains above, all starting from $X_0=1$, and simulated with the SSA.", "_____no_output_____" ] ], [ [ "npaths = 1\nnsteps = 30000\n\npath = np.zeros([npaths,nsteps])\nfor i in xrange(npaths):\n path[i,:], tpath = SSA(xinit=1,nsteps=nsteps)\n\nskip = 20000\nsum(path[0,skip:nsteps-1]*tpath[skip:nsteps-1])/sum(tpath[skip:nsteps-1])", "_____no_output_____" ] ] ]
[ "raw", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "raw" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
d0127f94f947d0fd92683887204da52b4611211d
24,043
ipynb
Jupyter Notebook
site/ko/r1/tutorials/keras/overfit_and_underfit.ipynb
justaverygoodboy/docs-l10n
8d4857750f2b5e8e6889acbb4b1e2f98ad7ce34e
[ "Apache-2.0" ]
null
null
null
site/ko/r1/tutorials/keras/overfit_and_underfit.ipynb
justaverygoodboy/docs-l10n
8d4857750f2b5e8e6889acbb4b1e2f98ad7ce34e
[ "Apache-2.0" ]
null
null
null
site/ko/r1/tutorials/keras/overfit_and_underfit.ipynb
justaverygoodboy/docs-l10n
8d4857750f2b5e8e6889acbb4b1e2f98ad7ce34e
[ "Apache-2.0" ]
null
null
null
34.844928
458
0.49686
[ [ [ "##### Copyright 2018 The TensorFlow Authors.", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ], [ "#@title MIT License\n#\n# Copyright (c) 2017 François Chollet\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.", "_____no_output_____" ] ], [ [ "# 과대적합과 과소적합", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/r1/tutorials/keras/overfit_and_underfit.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />구글 코랩(Colab)에서 실행하기</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/ko/r1/tutorials/keras/overfit_and_underfit.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />깃허브(GitHub) 소스 보기</a>\n </td>\n</table>", "_____no_output_____" ], [ "Note: 이 문서는 텐서플로 커뮤니티에서 번역했습니다. 커뮤니티 번역 활동의 특성상 정확한 번역과 최신 내용을 반영하기 위해 노력함에도\n불구하고 [공식 영문 문서](https://www.tensorflow.org/?hl=en)의 내용과 일치하지 않을 수 있습니다.\n이 번역에 개선할 부분이 있다면\n[tensorflow/docs](https://github.com/tensorflow/docs) 깃헙 저장소로 풀 리퀘스트를 보내주시기 바랍니다.\n문서 번역이나 리뷰에 참여하려면\n[docs-ko@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ko)로\n메일을 보내주시기 바랍니다.", "_____no_output_____" ], [ "지금까지 그랬듯이 이 예제의 코드도 `tf.keras` API를 사용합니다. 텐서플로 [케라스 가이드](https://www.tensorflow.org/r1/guide/keras)에서 `tf.keras` API에 대해 더 많은 정보를 얻을 수 있습니다.\n\n앞서 영화 리뷰 분류와 주택 가격 예측의 두 예제에서 일정 에포크 동안 훈련하면 검증 세트에서 모델 성능이 최고점에 도달한 다음 감소하기 시작한 것을 보았습니다.\n\n다른 말로 하면, 모델이 훈련 세트에 *과대적합*(overfitting)된 것입니다. 과대적합을 다루는 방법은 꼭 배워야 합니다. *훈련 세트*에서 높은 성능을 얻을 수 있지만 진짜 원하는 것은 *테스트 세트*(또는 이전에 본 적 없는 데이터)에 잘 일반화되는 모델입니다.\n\n과대적합의 반대는 *과소적합*(underfitting)입니다. 과소적합은 테스트 세트의 성능이 향상될 여지가 아직 있을 때 일어납니다. 발생하는 원인은 여러가지입니다. 모델이 너무 단순하거나, 규제가 너무 많거나, 그냥 단순히 충분히 오래 훈련하지 않는 경우입니다. 즉 네트워크가 훈련 세트에서 적절한 패턴을 학습하지 못했다는 뜻입니다.\n\n모델을 너무 오래 훈련하면 과대적합되기 시작하고 테스트 세트에서 일반화되지 못하는 패턴을 훈련 세트에서 학습합니다. 과대적합과 과소적합 사이에서 균형을 잡아야 합니다. 이를 위해 적절한 에포크 횟수동안 모델을 훈련하는 방법을 배워보겠습니다.\n\n과대적합을 막는 가장 좋은 방법은 더 많은 훈련 데이터를 사용하는 것입니다. 많은 데이터에서 훈련한 모델은 자연적으로 일반화 성능이 더 좋습니다. 데이터를 더 준비할 수 없을 때 그다음으로 가장 좋은 방법은 규제(regularization)와 같은 기법을 사용하는 것입니다. 모델이 저장할 수 있는 정보의 양과 종류에 제약을 부과하는 방법입니다. 네트워크가 소수의 패턴만 기억할 수 있다면 최적화 과정 동안 일반화 가능성이 높은 가장 중요한 패턴에 촛점을 맞출 것입니다.\n\n이 노트북에서 널리 사용되는 두 가지 규제 기법인 가중치 규제와 드롭아웃(dropout)을 알아 보겠습니다. 이런 기법을 사용하여 IMDB 영화 리뷰 분류 모델의 성능을 향상시켜 보죠.", "_____no_output_____" ] ], [ [ "import tensorflow.compat.v1 as tf\n\nfrom tensorflow import keras\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nprint(tf.__version__)", "_____no_output_____" ] ], [ [ "## IMDB 데이터셋 다운로드\n\n이전 노트북에서처럼 임베딩을 사용하지 않고 여기에서는 문장을 멀티-핫 인코딩(multi-hot encoding)으로 변환하겠습니다. 이 모델은 훈련 세트에 빠르게 과대적합될 것입니다. 과대적합을 발생시키기고 어떻게 해결하는지 보이기 위해 선택했습니다.\n\n멀티-핫 인코딩은 정수 시퀀스를 0과 1로 이루어진 벡터로 변환합니다. 정확하게 말하면 시퀀스 `[3, 5]`를 인덱스 3과 5만 1이고 나머지는 모두 0인 10,000 차원 벡터로 변환한다는 의미입니다.", "_____no_output_____" ] ], [ [ "NUM_WORDS = 10000\n\n(train_data, train_labels), (test_data, test_labels) = keras.datasets.imdb.load_data(num_words=NUM_WORDS)\n\ndef multi_hot_sequences(sequences, dimension):\n # 0으로 채워진 (len(sequences), dimension) 크기의 행렬을 만듭니다\n results = np.zeros((len(sequences), dimension))\n for i, word_indices in enumerate(sequences):\n results[i, word_indices] = 1.0 # results[i]의 특정 인덱스만 1로 설정합니다\n return results\n\n\ntrain_data = multi_hot_sequences(train_data, dimension=NUM_WORDS)\ntest_data = multi_hot_sequences(test_data, dimension=NUM_WORDS)", "_____no_output_____" ] ], [ [ "만들어진 멀티-핫 벡터 중 하나를 살펴 보죠. 단어 인덱스는 빈도 순으로 정렬되어 있습니다. 그래프에서 볼 수 있듯이 인덱스 0에 가까울수록 1이 많이 등장합니다:", "_____no_output_____" ] ], [ [ "plt.plot(train_data[0])", "_____no_output_____" ] ], [ [ "## 과대적합 예제\n\n과대적합을 막는 가장 간단한 방법은 모델의 규모를 축소하는 것입니다. 즉, 모델에 있는 학습 가능한 파라미터의 수를 줄입니다(모델 파라미터는 층(layer)의 개수와 층의 유닛(unit) 개수에 의해 결정됩니다). 딥러닝에서는 모델의 학습 가능한 파라미터의 수를 종종 모델의 \"용량\"이라고 말합니다. 직관적으로 생각해 보면 많은 파라미터를 가진 모델이 더 많은 \"기억 용량\"을 가집니다. 이런 모델은 훈련 샘플과 타깃 사이를 일반화 능력이 없는 딕셔너리와 같은 매핑으로 완벽하게 학습할 수 있습니다. 하지만 이전에 본 적 없는 데이터에서 예측을 할 땐 쓸모가 없을 것입니다.\n\n항상 기억해야 할 점은 딥러닝 모델이 훈련 세트에는 학습이 잘 되는 경향이 있지만 진짜 해결할 문제는 학습이 아니라 일반화라는 것입니다.\n\n반면에 네트워크의 기억 용량이 부족하다면 이런 매핑을 쉽게 학습할 수 없을 것입니다. 손실을 최소화하기 위해서는 예측 성능이 더 많은 압축된 표현을 학습해야 합니다. 또한 너무 작은 모델을 만들면 훈련 데이터를 학습하기 어렵울 것입니다. \"너무 많은 용량\"과 \"충분하지 않은 용량\" 사이의 균형을 잡아야 합니다.\n\n안타깝지만 어떤 모델의 (층의 개수나 뉴런 개수에 해당하는) 적절한 크기나 구조를 결정하는 마법같은 공식은 없습니다. 여러 가지 다른 구조를 사용해 실험을 해봐야만 합니다.\n\n알맞은 모델의 크기를 찾으려면 비교적 적은 수의 층과 파라미터로 시작해서 검증 손실이 감소할 때까지 새로운 층을 추가하거나 층의 크기를 늘리는 것이 좋습니다. 영화 리뷰 분류 네트워크를 사용해 이를 실험해 보죠.\n\n```Dense``` 층만 사용하는 간단한 기준 모델을 만들고 작은 규모의 버전와 큰 버전의 모델을 만들어 비교하겠습니다.", "_____no_output_____" ], [ "### 기준 모델 만들기", "_____no_output_____" ] ], [ [ "baseline_model = keras.Sequential([\n # `.summary` 메서드 때문에 `input_shape`가 필요합니다\n keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(16, activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n])\n\nbaseline_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n\nbaseline_model.summary()", "_____no_output_____" ], [ "baseline_history = baseline_model.fit(train_data,\n train_labels,\n epochs=20,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2)", "_____no_output_____" ] ], [ [ "### 작은 모델 만들기", "_____no_output_____" ], [ "앞서 만든 기준 모델과 비교하기 위해 적은 수의 은닉 유닛을 가진 모델을 만들어 보죠:", "_____no_output_____" ] ], [ [ "smaller_model = keras.Sequential([\n keras.layers.Dense(4, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(4, activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n])\n\nsmaller_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n\nsmaller_model.summary()", "_____no_output_____" ] ], [ [ "같은 데이터를 사용해 이 모델을 훈련합니다:", "_____no_output_____" ] ], [ [ "smaller_history = smaller_model.fit(train_data,\n train_labels,\n epochs=20,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2)", "_____no_output_____" ] ], [ [ "### 큰 모델 만들기\n\n아주 큰 모델을 만들어 얼마나 빠르게 과대적합이 시작되는지 알아 볼 수 있습니다. 이 문제에 필요한 것보다 훨씬 더 큰 용량을 가진 네트워크를 추가해서 비교해 보죠:", "_____no_output_____" ] ], [ [ "bigger_model = keras.models.Sequential([\n keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(512, activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n])\n\nbigger_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy','binary_crossentropy'])\n\nbigger_model.summary()", "_____no_output_____" ] ], [ [ "역시 같은 데이터를 사용해 모델을 훈련합니다:", "_____no_output_____" ] ], [ [ "bigger_history = bigger_model.fit(train_data, train_labels,\n epochs=20,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2)", "_____no_output_____" ] ], [ [ "### 훈련 손실과 검증 손실 그래프 그리기\n\n<!--TODO(markdaoust): This should be a one-liner with tensorboard -->", "_____no_output_____" ], [ "실선은 훈련 손실이고 점선은 검증 손실입니다(낮은 검증 손실이 더 좋은 모델입니다). 여기서는 작은 네트워크가 기준 모델보다 더 늦게 과대적합이 시작되었습니다(즉 에포크 4가 아니라 6에서 시작됩니다). 또한 과대적합이 시작되고 훨씬 천천히 성능이 감소합니다.", "_____no_output_____" ] ], [ [ "def plot_history(histories, key='binary_crossentropy'):\n plt.figure(figsize=(16,10))\n\n for name, history in histories:\n val = plt.plot(history.epoch, history.history['val_'+key],\n '--', label=name.title()+' Val')\n plt.plot(history.epoch, history.history[key], color=val[0].get_color(),\n label=name.title()+' Train')\n\n plt.xlabel('Epochs')\n plt.ylabel(key.replace('_',' ').title())\n plt.legend()\n\n plt.xlim([0,max(history.epoch)])\n\n\nplot_history([('baseline', baseline_history),\n ('smaller', smaller_history),\n ('bigger', bigger_history)])", "_____no_output_____" ] ], [ [ "큰 네트워크는 거의 바로 첫 번째 에포크 이후에 과대적합이 시작되고 훨씬 더 심각하게 과대적합됩니다. 네트워크의 용량이 많을수록 훈련 세트를 더 빠르게 모델링할 수 있습니다(훈련 손실이 낮아집니다). 하지만 더 쉽게 과대적합됩니다(훈련 손실과 검증 손실 사이에 큰 차이가 발생합니다).", "_____no_output_____" ], [ "## 전략", "_____no_output_____" ], [ "### 가중치를 규제하기", "_____no_output_____" ], [ "아마도 오캄의 면도날(Occam's Razor) 이론을 들어 보았을 것입니다. 어떤 것을 설명하는 두 가지 방법이 있다면 더 정확한 설명은 최소한의 가정이 필요한 가장 \"간단한\" 설명일 것입니다. 이는 신경망으로 학습되는 모델에도 적용됩니다. 훈련 데이터와 네트워크 구조가 주어졌을 때 이 데이터를 설명할 수 있는 가중치의 조합(즉, 가능한 모델)은 많습니다. 간단한 모델은 복잡한 것보다 과대적합되는 경향이 작을 것입니다.\n\n여기서 \"간단한 모델\"은 모델 파라미터의 분포를 봤을 때 엔트로피(entropy)가 작은 모델입니다(또는 앞 절에서 보았듯이 적은 파라미터를 가진 모델입니다). 따라서 과대적합을 완화시키는 일반적인 방법은 가중치가 작은 값을 가지도록 네트워크의 복잡도에 제약을 가하는 것입니다. 이는 가중치 값의 분포를 좀 더 균일하게 만들어 줍니다. 이를 \"가중치 규제\"(weight regularization)라고 부릅니다. 네트워크의 손실 함수에 큰 가중치에 해당하는 비용을 추가합니다. 이 비용은 두 가지 형태가 있습니다:\n\n* [L1 규제](https://developers.google.com/machine-learning/glossary/#L1_regularization)는 가중치의 절댓값에 비례하는 비용이 추가됩니다(즉, 가중치의 \"L1 노름(norm)\"을 추가합니다).\n\n* [L2 규제](https://developers.google.com/machine-learning/glossary/#L2_regularization)는 가중치의 제곱에 비례하는 비용이 추가됩니다(즉, 가중치의 \"L2 노름\"의 제곱을 추가합니다). 신경망에서는 L2 규제를 가중치 감쇠(weight decay)라고도 부릅니다. 이름이 다르지만 혼돈하지 마세요. 가중치 감쇠는 수학적으로 L2 규제와 동일합니다.\n\n`tf.keras`에서는 가중치 규제 객체를 층의 키워드 매개변수에 전달하여 가중치에 규제를 추가합니다. L2 가중치 규제를 추가해 보죠.", "_____no_output_____" ] ], [ [ "l2_model = keras.models.Sequential([\n keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001),\n activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001),\n activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n])\n\nl2_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n\nl2_model_history = l2_model.fit(train_data, train_labels,\n epochs=20,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2)", "_____no_output_____" ] ], [ [ "```l2(0.001)```는 네트워크의 전체 손실에 층에 있는 가중치 행렬의 모든 값이 ```0.001 * weight_coefficient_value**2```만큼 더해진다는 의미입니다. 이런 페널티(penalty)는 훈련할 때만 추가됩니다. 따라서 테스트 단계보다 훈련 단계에서 네트워크 손실이 훨씬 더 클 것입니다.\n\nL2 규제의 효과를 확인해 보죠:", "_____no_output_____" ] ], [ [ "plot_history([('baseline', baseline_history),\n ('l2', l2_model_history)])", "_____no_output_____" ] ], [ [ "결과에서 보듯이 모델 파라미터의 개수는 같지만 L2 규제를 적용한 모델이 기본 모델보다 과대적합에 훨씬 잘 견디고 있습니다.", "_____no_output_____" ], [ "### 드롭아웃 추가하기\n\n드롭아웃(dropout)은 신경망에서 가장 효과적이고 널리 사용하는 규제 기법 중 하나입니다. 토론토(Toronto) 대학의 힌튼(Hinton)과 그의 제자들이 개발했습니다. 드롭아웃을 층에 적용하면 훈련하는 동안 층의 출력 특성을 랜덤하게 끕니다(즉, 0으로 만듭니다). 훈련하는 동안 어떤 입력 샘플에 대해 [0.2, 0.5, 1.3, 0.8, 1.1] 벡터를 출력하는 층이 있다고 가정해 보죠. 드롭아웃을 적용하면 이 벡터에서 몇 개의 원소가 랜덤하게 0이 됩니다. 예를 들면, [0, 0.5, 1.3, 0, 1.1]가 됩니다. \"드롭아웃 비율\"은 0이 되는 특성의 비율입니다. 보통 0.2에서 0.5 사이를 사용합니다. 테스트 단계에서는 어떤 유닛도 드롭아웃하지 않습니다. 훈련 단계보다 더 많은 유닛이 활성화되기 때문에 균형을 맞추기 위해 층의 출력 값을 드롭아웃 비율만큼 줄입니다.\n\n`tf.keras`에서는 `Dropout` 층을 이용해 네트워크에 드롭아웃을 추가할 수 있습니다. 이 층은 바로 이전 층의 출력에 드롭아웃을 적용합니다.\n\nIMDB 네트워크에 두 개의 `Dropout` 층을 추가하여 과대적합이 얼마나 감소하는지 알아 보겠습니다:", "_____no_output_____" ] ], [ [ "dpt_model = keras.models.Sequential([\n keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dropout(0.5),\n keras.layers.Dense(16, activation=tf.nn.relu),\n keras.layers.Dropout(0.5),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n])\n\ndpt_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy','binary_crossentropy'])\n\ndpt_model_history = dpt_model.fit(train_data, train_labels,\n epochs=20,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2)", "_____no_output_____" ], [ "plot_history([('baseline', baseline_history),\n ('dropout', dpt_model_history)])", "_____no_output_____" ] ], [ [ "드롭아웃을 추가하니 기준 모델보다 확실히 향상되었습니다.\n\n정리하면 신경망에서 과대적합을 방지하기 위해 가장 널리 사용하는 방법은 다음과 같습니다:\n\n* 더 많은 훈련 데이터를 모읍니다.\n* 네트워크의 용량을 줄입니다.\n* 가중치 규제를 추가합니다.\n* 드롭아웃을 추가합니다.\n\n이 문서에서 다루지 않은 중요한 방법 두 가지는 데이터 증식(data-augmentation)과 배치 정규화(batch normalization)입니다.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d0127ff1cf98ce8bcb6574dcedb2991e74809738
11,747
ipynb
Jupyter Notebook
Inferential Coding Practice.ipynb
anushka-DS/Inferential-Statistics
c3ba3bd33a541cb74bc1946818085b8e7e458b93
[ "MIT" ]
null
null
null
Inferential Coding Practice.ipynb
anushka-DS/Inferential-Statistics
c3ba3bd33a541cb74bc1946818085b8e7e458b93
[ "MIT" ]
null
null
null
Inferential Coding Practice.ipynb
anushka-DS/Inferential-Statistics
c3ba3bd33a541cb74bc1946818085b8e7e458b93
[ "MIT" ]
null
null
null
29.890585
304
0.567294
[ [ [ "## Gambling 101\n\nYou are participating in a lottery game. A deck of cards numbered from 1-50 is shuffled and 5 cards are drawn out and laid out. You are given a coin. For each card, you toss the coin and pick it up if it says heads, otherwise you don't pick it up. The sum of the cards is what you win.\nThe lottery ticket costs c rupees. If the expected value of the sum of cards you pick up is less than the lottery ticket, then you buy another ticket otherwise you don't.\n\nInput Format:\nThe first 5 lines of the input will contain 5 numbers between 1 to 50.\nThe next line will contain c, the cost of lottery ticket.\n\nOutput Format:\nPrint \"Don't buy another\" if the expected value is less than the ticket price and print \"Buy another one\" if the expected value is more than the ticket price.\n\n**Sample Input:**\n1\n4\n6\n17\n3\n23\n\n**Sample Output:**\nDon't buy another\n\n**Note:** You have to take input using the input() function. For your practice with taking inputs, the stub will be empty.", "_____no_output_____" ] ], [ [ "#my_input1 = input(\"Enter the 1st input here :\" )\n#my_input2 = input(\"Enter the 2nd input here :\" )\n#my_input3 = input(\"Enter the 3rd input here :\" )\n#my_input4 = input(\"Enter the 4th input here :\" )\n#my_input5 = input(\"Enter the 5th input here :\" )\nc = input(\"cost of lottery ticket here :\" )\n\nimport ast,sys\ninput_str = sys.stdin.read()\ninput_list = ast.literal_eval(input_str)\nmy_input=input_list[0]\n\nsum=0\nfor i in range(0,5):\n sum=sum+int(my_input[i])\nif sum<=int(c):\n print(\"Don't buy another\")\nelse:\n print(\"Buy another one\")", "_____no_output_____" ] ], [ [ "## Generating normal distribution\n\nGenerate an array of real numbers representing a normal distribution. You will be given the mean and standard deviation as input. You have to generate 10 such numbers.\n**Hint:** You can use numpy's numpy's np.random here... np.random https://pynative.com/python-random-seed/.\n \nTo keep the output consistent, you have to set the seed as a specific number which will be given to you as input. Setting a seed means that every time you generate random numbers, they will be the same for the same seed. You can read more about it here.. https://pynative.com/python-random-seed/\n\n\n**Input Format:**\nThe input will contain 3 lines which have the seed, mean and standard deviation of the distribution in the same order.\nThe output will be a numpy array of the generated normal distribution.\n\n**Sample Input:**\n1\n0\n0.1", "_____no_output_____" ] ], [ [ "import numpy as np \nseed=int(input())\nmean=float(input())\nstd_dev=float(input())\nnp.random.seed(seed)\ns = np.random.normal(mean, std_dev, 10)\nprint(s)", "1\n0\n0.1\n[ 0.16243454 -0.06117564 -0.05281718 -0.10729686 0.08654076 -0.23015387\n 0.17448118 -0.07612069 0.03190391 -0.02493704]\n" ] ], [ [ "## Confidence Intervals\n\nFor a given column in a dataframe, you have to calculate the 90 percent confidence interval for its mean value. (You can find Z* value for 90 percent confidence from previous segments)\nThe input will have the column name. \n\nThe output should have the confidence interval printed as a tuple.\n\n**Note:** Do not use the inbuilt function via statmodels.api or any other libraries. You should write the code on your own to get accurate answers.\nThe confidence interval values have to be approximated up to two decimal places.\n\n**Sample Input:**\nGRE Score", "_____no_output_____" ] ], [ [ "import pandas as pd \nimport numpy as np\ndf=pd.read_csv(\"https://media-doselect.s3.amazonaws.com/generic/N9LKLvBAx1y14PLoBdL0yRn3/Admission_Predict.csv\")\ncol=input()\nmean = df[col].mean()\nsd = df[col].std()\nn = len(df)\nZstar=1.65\nse = sd/np.sqrt(n)\nlcb = mean - Zstar * se\nucb = mean + Zstar * se\nprint((round(lcb,2),round(ucb,2)))\n\n#via statmodels.api you can do this as follows:\n#import statsmodels.api as sm\n#sm.stats.DescrStatsW(df[col]).zconfint_mean()", "GRE Score\n(315.86, 317.75)\n" ] ], [ [ "## College admissions\n\nThe probability that a college will accept a student's application is x.\nConsider that m students have applied to college. You have to find the probability that at most n students are accepted by the college.\n\nThe input will contain three lines with x, m and n respectively.\nThe output should be rounded off to four decimal places.\n\n**Sample Input:**\n0.3\n5\n2\n\n**Sample Output:**\n0.8369", "_____no_output_____" ] ], [ [ "#probability of accepting an application\nx=float(input())\n\n#number of applicants\nm=int(input())\n\n#find the probability that at most n applications are accepted\nn=int(input())\n\n#write your code here\nimport scipy.stats as ss\n\ndist=ss.binom(m,x)\nsum=0.0\nfor i in range(0,n+1):\n sum=sum+dist.pmf(i)\nprint(round(sum,4))", "_____no_output_____" ] ], [ [ "## Tossing a coin\n\nGiven that you are tossing a coin n times, you have to find the probability of getting heads at most m times.\nThe input will have two lines containing n and m respectively.\n\n**Sample Input:**\n10\n2\n\n**Sample Output:**\n0.0547", "_____no_output_____" ] ], [ [ "import scipy.stats as ss\n#number of trials\nn=int(input())\n\n# find the probability of getting at most m heads\nm=int(input())\ndist=ss.binom(n,0.5)\nsum=0.0\nfor i in range(0,m+1):\n sum=sum+dist.pmf(i)\nprint(round(sum,4))\n#you can also use the following\n#round(dist.cdf(m),2)", "_____no_output_____" ] ], [ [ "## Combination Theory\n\nYou are given a list of n natural numbers. You select m numbers from the list at random. \nFind the probability that at least one of the selected alphabets is \"x\" where x is a number given to you as input.\nThe first line of input will contain a list of numbers. The second line will contain m and the third line will contain x.\n\nThe output should be printed out as float.\n\n**Sample Input:**\n[1,2,3,4,5,6,6,6,6,7,7,7]\n3\n6\n\n**Sample Output:**\n0.7454545454545455", "_____no_output_____" ] ], [ [ "import ast,sys\ninput_str = sys.stdin.read()\ninput_list = ast.literal_eval(input_str)\nnums=input_list[0]\n\n#m numbers are chosen\nm=int(input_list[1])\n\n#find probability of getting at least one x \nx=int(input_list[2])\nfrom itertools import combinations \nnum = 0\nden = 0\nfor c in combinations(nums,m):\n den=den+1\n if x in c:\n num=num+1", "_____no_output_____" ] ], [ [ "## Rolling the dice\n\nA die is rolled n times. You have to find the probability that a number i is rolled at least j times(up to four decimal places)\nThe input will contain the integers n, i and j in three lines respectively. You can assume that j<n and 0<i<7.\nThe output should be rounded off to four decimal places.\n\n**Sample Input:**\n4\n1\n2\n\n**Sample Output:**\n0.1319", "_____no_output_____" ] ], [ [ "import scipy.stats as ss\nn=int(input())\ni=int(input())\nj=int(input())\ndist=ss.binom(n,1/6)\nprint(round(1-dist.cdf(j-1),4))", "_____no_output_____" ] ], [ [ "## Lego Stack\n\nYou are given a row of Lego Blocks consisting of n blocks. All the blocks given have a square base whose side length is known. You need to stack the blocks over each other and create a vertical tower. Block-1 can go over Block-2 only if sideLength(Block-2)>sideLength(Block-1).\nFrom the row of Lego blocks, you on only pick up either the leftmost or rightmost block.\nPrint \"Possible\" if it is possible to stack all n cubes this way or else print \"Impossible\".\n\n**Input Format:**\nThe input will contain a list of n integers representing the side length of each block's base in the row starting from the leftmost.\n\n**Sample Input:**\n[5 ,4, 2, 1, 4 ,5]\n\n**Sample Output:**\nPossible", "_____no_output_____" ] ], [ [ "import ast,sys\ninput_str = sys.stdin.read()\nsides = ast.literal_eval(input_str)#list of side lengths\nl=len(sides)\ndiff = [(sides[i]-sides[i+1]) for i in range(l-1)]\ni = 0 \nwhile (i<l-1 and diff[i]>=0) : i += 1 \nwhile (i<l-1 and diff[i]<=0) : i += 1\nif (i==l-1) : print(\"Possible\") \nelse : print(\"Impossible\")\n\n#to understand the code, try printing out all intermediate variables.", "_____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" ] ]
d0129886a14437458caf326efac5b852acd6172b
231,823
ipynb
Jupyter Notebook
Starter_Code/credit_risk_ensemble.ipynb
eriklarson33/HW_11-Risky_Business
03f110e50a937c8474f9c0b20c1d05581f99b634
[ "ADSL" ]
null
null
null
Starter_Code/credit_risk_ensemble.ipynb
eriklarson33/HW_11-Risky_Business
03f110e50a937c8474f9c0b20c1d05581f99b634
[ "ADSL" ]
null
null
null
Starter_Code/credit_risk_ensemble.ipynb
eriklarson33/HW_11-Risky_Business
03f110e50a937c8474f9c0b20c1d05581f99b634
[ "ADSL" ]
null
null
null
45.760561
31,020
0.446082
[ [ [ "# Ensemble Learning\n\n## Initial Imports", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom collections import Counter", "_____no_output_____" ], [ "from sklearn.metrics import balanced_accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom imblearn.metrics import classification_report_imbalanced", "_____no_output_____" ] ], [ [ "## Read the CSV and Perform Basic Data Cleaning", "_____no_output_____" ] ], [ [ "# Load the data\nfile_path = Path('Resources/LoanStats_2019Q1.csv')\ndf = pd.read_csv(file_path)\n\n# Preview the data\ndf.head()", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 68817 entries, 0 to 68816\nData columns (total 86 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 loan_amnt 68817 non-null float64\n 1 int_rate 68817 non-null float64\n 2 installment 68817 non-null float64\n 3 home_ownership 68817 non-null object \n 4 annual_inc 68817 non-null float64\n 5 verification_status 68817 non-null object \n 6 issue_d 68817 non-null object \n 7 loan_status 68817 non-null object \n 8 pymnt_plan 68817 non-null object \n 9 dti 68817 non-null float64\n 10 delinq_2yrs 68817 non-null float64\n 11 inq_last_6mths 68817 non-null float64\n 12 open_acc 68817 non-null float64\n 13 pub_rec 68817 non-null float64\n 14 revol_bal 68817 non-null float64\n 15 total_acc 68817 non-null float64\n 16 initial_list_status 68817 non-null object \n 17 out_prncp 68817 non-null float64\n 18 out_prncp_inv 68817 non-null float64\n 19 total_pymnt 68817 non-null float64\n 20 total_pymnt_inv 68817 non-null float64\n 21 total_rec_prncp 68817 non-null float64\n 22 total_rec_int 68817 non-null float64\n 23 total_rec_late_fee 68817 non-null float64\n 24 recoveries 68817 non-null float64\n 25 collection_recovery_fee 68817 non-null float64\n 26 last_pymnt_amnt 68817 non-null float64\n 27 next_pymnt_d 68817 non-null object \n 28 collections_12_mths_ex_med 68817 non-null float64\n 29 policy_code 68817 non-null float64\n 30 application_type 68817 non-null object \n 31 acc_now_delinq 68817 non-null float64\n 32 tot_coll_amt 68817 non-null float64\n 33 tot_cur_bal 68817 non-null float64\n 34 open_acc_6m 68817 non-null float64\n 35 open_act_il 68817 non-null float64\n 36 open_il_12m 68817 non-null float64\n 37 open_il_24m 68817 non-null float64\n 38 mths_since_rcnt_il 68817 non-null float64\n 39 total_bal_il 68817 non-null float64\n 40 il_util 68817 non-null float64\n 41 open_rv_12m 68817 non-null float64\n 42 open_rv_24m 68817 non-null float64\n 43 max_bal_bc 68817 non-null float64\n 44 all_util 68817 non-null float64\n 45 total_rev_hi_lim 68817 non-null float64\n 46 inq_fi 68817 non-null float64\n 47 total_cu_tl 68817 non-null float64\n 48 inq_last_12m 68817 non-null float64\n 49 acc_open_past_24mths 68817 non-null float64\n 50 avg_cur_bal 68817 non-null float64\n 51 bc_open_to_buy 68817 non-null float64\n 52 bc_util 68817 non-null float64\n 53 chargeoff_within_12_mths 68817 non-null float64\n 54 delinq_amnt 68817 non-null float64\n 55 mo_sin_old_il_acct 68817 non-null float64\n 56 mo_sin_old_rev_tl_op 68817 non-null float64\n 57 mo_sin_rcnt_rev_tl_op 68817 non-null float64\n 58 mo_sin_rcnt_tl 68817 non-null float64\n 59 mort_acc 68817 non-null float64\n 60 mths_since_recent_bc 68817 non-null float64\n 61 mths_since_recent_inq 68817 non-null float64\n 62 num_accts_ever_120_pd 68817 non-null float64\n 63 num_actv_bc_tl 68817 non-null float64\n 64 num_actv_rev_tl 68817 non-null float64\n 65 num_bc_sats 68817 non-null float64\n 66 num_bc_tl 68817 non-null float64\n 67 num_il_tl 68817 non-null float64\n 68 num_op_rev_tl 68817 non-null float64\n 69 num_rev_accts 68817 non-null float64\n 70 num_rev_tl_bal_gt_0 68817 non-null float64\n 71 num_sats 68817 non-null float64\n 72 num_tl_120dpd_2m 68817 non-null float64\n 73 num_tl_30dpd 68817 non-null float64\n 74 num_tl_90g_dpd_24m 68817 non-null float64\n 75 num_tl_op_past_12m 68817 non-null float64\n 76 pct_tl_nvr_dlq 68817 non-null float64\n 77 percent_bc_gt_75 68817 non-null float64\n 78 pub_rec_bankruptcies 68817 non-null float64\n 79 tax_liens 68817 non-null float64\n 80 tot_hi_cred_lim 68817 non-null float64\n 81 total_bal_ex_mort 68817 non-null float64\n 82 total_bc_limit 68817 non-null float64\n 83 total_il_high_credit_limit 68817 non-null float64\n 84 hardship_flag 68817 non-null object \n 85 debt_settlement_flag 68817 non-null object \ndtypes: float64(76), object(10)\nmemory usage: 45.2+ MB\n" ], [ "pd.set_option('display.max_rows', None) # or 1000\ndf.nunique(axis=0)", "_____no_output_____" ], [ "df['recoveries'].value_counts()", "_____no_output_____" ], [ "df['pymnt_plan'].value_counts()", "_____no_output_____" ], [ "# Drop all unnecessary columns with only a single value.\npd.set_option('display.max_columns', None) # or 1000\ndf.drop(columns=['pymnt_plan','recoveries','collection_recovery_fee','policy_code','acc_now_delinq','num_tl_120dpd_2m','num_tl_30dpd','tax_liens','hardship_flag','debt_settlement_flag'], inplace=True)\ndf.head()", "_____no_output_____" ], [ "# Update the DataFrame to numerical values:\ndf_encoded = pd.get_dummies(df, columns=['home_ownership','verification_status','issue_d','initial_list_status','next_pymnt_d','application_type',], drop_first=True)\ndf_encoded.head()", "_____no_output_____" ] ], [ [ "## Split the Data into Training and Testing", "_____no_output_____" ] ], [ [ "# Create our features\nX = df_encoded.drop(columns=['loan_status'])", "_____no_output_____" ], [ "# Create our target\ny = df_encoded['loan_status'].to_frame('loan_status')\ny.head()", "_____no_output_____" ], [ "X.describe()", "_____no_output_____" ], [ "# Check the balance of our target values\ny['loan_status'].value_counts()", "_____no_output_____" ], [ "# Split the X and y into X_train, X_test, y_train, y_test\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)", "_____no_output_____" ] ], [ [ "## Data Pre-Processing\n\nScale the training and testing data using the `StandardScaler` from `sklearn`. Remember that when scaling the data, you only scale the features data (`X_train` and `X_testing`).", "_____no_output_____" ] ], [ [ "X_train.columns", "_____no_output_____" ], [ "X_train.head()", "_____no_output_____" ], [ "X_train.shape", "_____no_output_____" ] ], [ [ "## NEW SOLUTION: USE SCIKIT-LEARN'S ColumnTransformer():\nOneHotEncoder versus GetDummies:\nhttps://www.quora.com/When-would-you-choose-to-use-pandas-get_dummies-vs-sklearn-OneHotEncoder\nBoth options are equally handy but the major difference is that OneHotEncoder is a transformer class, so it can be fitted to data. Once fitted, it is able to transform validation data based on the categories it learned. That is, if previously unseed data contains new categories and is being transformed, the encoder will ignore them or raise an error (depending on handle_unknown parameter). Also, OneHotEncoder matches scikit-learn’s transformer API so that one can use it in pipelines for convenience.\n\nBasically, get_dummies is used in exploratory analysis, whereas OneHotEncoder in computation and estimation. See documentations for more details.", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.compose import make_column_transformer", "_____no_output_____" ], [ "ohe = OneHotEncoder()\nsc = StandardScaler()", "_____no_output_____" ], [ "ct = make_column_transformer(\n (sc, ['loan_amnt', 'int_rate', 'installment', 'annual_inc', 'dti',\n 'delinq_2yrs', 'inq_last_6mths', 'open_acc', 'pub_rec', 'revol_bal',\n 'total_acc', 'out_prncp', 'out_prncp_inv', 'total_pymnt',\n 'total_pymnt_inv', 'total_rec_prncp', 'total_rec_int',\n 'total_rec_late_fee', 'last_pymnt_amnt', 'collections_12_mths_ex_med',\n 'tot_coll_amt', 'tot_cur_bal', 'open_acc_6m', 'open_act_il',\n 'open_il_12m', 'open_il_24m', 'mths_since_rcnt_il', 'total_bal_il',\n 'il_util', 'open_rv_12m', 'open_rv_24m', 'max_bal_bc', 'all_util',\n 'total_rev_hi_lim', 'inq_fi', 'total_cu_tl', 'inq_last_12m',\n 'acc_open_past_24mths', 'avg_cur_bal', 'bc_open_to_buy', 'bc_util',\n 'chargeoff_within_12_mths', 'delinq_amnt', 'mo_sin_old_il_acct',\n 'mo_sin_old_rev_tl_op', 'mo_sin_rcnt_rev_tl_op', 'mo_sin_rcnt_tl',\n 'mort_acc', 'mths_since_recent_bc', 'mths_since_recent_inq',\n 'num_accts_ever_120_pd', 'num_actv_bc_tl', 'num_actv_rev_tl',\n 'num_bc_sats', 'num_bc_tl', 'num_il_tl', 'num_op_rev_tl',\n 'num_rev_accts', 'num_rev_tl_bal_gt_0', 'num_sats',\n 'num_tl_90g_dpd_24m', 'num_tl_op_past_12m', 'pct_tl_nvr_dlq',\n 'percent_bc_gt_75', 'pub_rec_bankruptcies', 'tot_hi_cred_lim',\n 'total_bal_ex_mort', 'total_bc_limit', 'total_il_high_credit_limit']),\n (ohe, ['home_ownership_MORTGAGE', 'home_ownership_OWN', 'home_ownership_RENT',\n 'verification_status_Source Verified', 'verification_status_Verified',\n 'issue_d_Jan-2019', 'issue_d_Mar-2019', 'initial_list_status_w',\n 'next_pymnt_d_May-2019', 'application_type_Joint App'])\n)", "_____no_output_____" ], [ "X_train_scaled = ct.fit_transform(X_train)\nprint(type(X_train_scaled))", "<class 'numpy.ndarray'>\n" ], [ "pd.DataFrame(X_train_scaled).head()", "_____no_output_____" ], [ "print(type(X_train_scaled))", "<class 'numpy.ndarray'>\n" ], [ "# Fit & Transform to standardize X_test:\nX_test_scaled = ct.fit_transform(X_test)\nprint(type(X_test_scaled))", "<class 'numpy.ndarray'>\n" ] ], [ [ "## Ensemble Learners\n\nIn this section, you will compare two ensemble algorithms to determine which algorithm results in the best performance. You will train a Balanced Random Forest Classifier and an Easy Ensemble classifier . For each algorithm, be sure to complete the folliowing steps:\n\n1. Train the model using the training data. \n2. Calculate the balanced accuracy score from sklearn.metrics.\n3. Display the confusion matrix from sklearn.metrics.\n4. Generate a classication report using the `imbalanced_classification_report` from imbalanced-learn.\n5. For the Balanced Random Forest Classifier only, print the feature importance sorted in descending order (most important feature to least important) along with the feature score\n\nNote: Use a random state of 1 for each algorithm to ensure consistency between tests", "_____no_output_____" ], [ "### Balanced Random Forest Classifier", "_____no_output_____" ] ], [ [ "# Resample the training data with the BalancedRandomForestClassifier\nfrom imblearn.ensemble import BalancedRandomForestClassifier\nbrf = BalancedRandomForestClassifier(n_estimators=1000, random_state=1)\nbrf.fit(X_train_scaled, y_train)", "_____no_output_____" ], [ "# Predict\ny_pred_rf = brf.predict(X_test_scaled)", "_____no_output_____" ], [ "# Calculated the balanced accuracy score\nfrom sklearn.metrics import balanced_accuracy_score\n\nbalanced_accuracy_score(y_test, y_pred_rf)", "_____no_output_____" ], [ "# Display the confusion matrix\nconfusion_matrix(y_test, y_pred_rf)", "_____no_output_____" ], [ "# Print the imbalanced classification report\nprint(classification_report_imbalanced(y_test, y_pred_rf))", " pre rec spe f1 geo iba sup\n\n high_risk 0.07 0.66 0.94 0.12 0.79 0.61 104\n low_risk 1.00 0.94 0.66 0.97 0.79 0.64 17101\n\navg / total 0.99 0.94 0.67 0.96 0.79 0.64 17205\n\n" ], [ "# Calculate the feature importance\nimportance = brf.feature_importances_\n# List the features sorted in descending order by feature importance\nsorted(zip(brf.feature_importances_, X.columns), reverse=True)", "_____no_output_____" ] ], [ [ "### Visualizing the Features by Importance to the model: (Top 20)", "_____no_output_____" ] ], [ [ "importance_df = pd.DataFrame(sorted(zip(brf.feature_importances_, X.columns), reverse=True))\nimportance_df.set_index(importance_df[1], inplace=True)\nimportance_df.drop(columns=1, inplace=True)\nimportance_df.rename(columns={0:'Feature Importances'}, inplace=True)\nimportance_sorted = importance_df.sort_values(by='Feature Importances').head(20)\nimportance_sorted.plot(kind='barh', color='blue', title='Top 20 Features Importances', legend=False)", "_____no_output_____" ] ], [ [ "### Easy Ensemble Classifier\nhttps://imbalanced-learn.org/stable/references/generated/imblearn.ensemble.EasyEnsembleClassifier.html", "_____no_output_____" ] ], [ [ "# Create an instance of an Easy Ensemble Classifier:\nfrom imblearn.ensemble import EasyEnsembleClassifier \neec = EasyEnsembleClassifier(n_estimators=1000, random_state=1)", "_____no_output_____" ], [ "# Train the Classifier\neec.fit(X_train_scaled, y_train)", "_____no_output_____" ], [ "# Predict\ny_pred_eec = eec.predict(X_test_scaled)", "_____no_output_____" ], [ "# Calculated the balanced accuracy score\nbalanced_accuracy_score(y_test, y_pred_eec)", "_____no_output_____" ], [ "# Display the confusion matrix\ncm_eec = confusion_matrix(y_test, y_pred_eec)\ncm_eec_df = pd.DataFrame(\n cm_eec, index=['Actual=No: 0', 'Actual=Yes: 1'], columns=['Predicted=No: 0', 'Predicted=Yes: 1']\n)\nprint('Confusion Matrix:')\ndisplay(cm_eec_df)", "Confusion Matrix:\n" ], [ "# Print the imbalanced classification report\nprint(classification_report_imbalanced(y_test, y_pred_eec))", " pre rec spe f1 geo iba sup\n\n high_risk 0.09 0.88 0.95 0.17 0.91 0.82 104\n low_risk 1.00 0.95 0.88 0.97 0.91 0.83 17101\n\navg / total 0.99 0.95 0.88 0.97 0.91 0.83 17205\n\n" ] ], [ [ "### Final Questions\n\n1. Which model had the best balanced accuracy score?\n\n Easy Ensemble Classifier.\n\n2. Which model had the best recall score?\n\n Easy Ensemble Classifier.\n\n3. Which model had the best geometric mean score?\n\n Easy Ensemble Classifier.\n\n4. What are the top three features?\n\n 1. open_rv_12m\n 2. delinq_2yrs\n 3. tot_coll_amt", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
d012a593594f291b2918ec7854f9a6f45b8861c1
48,159
ipynb
Jupyter Notebook
Desafio 7 (enem-2)/main.ipynb
leosimoes/Codenation-AceleraDev-DataScience
328a8248d09544e57e2b45ac9b2df29f858bcef8
[ "MIT" ]
null
null
null
Desafio 7 (enem-2)/main.ipynb
leosimoes/Codenation-AceleraDev-DataScience
328a8248d09544e57e2b45ac9b2df29f858bcef8
[ "MIT" ]
null
null
null
Desafio 7 (enem-2)/main.ipynb
leosimoes/Codenation-AceleraDev-DataScience
328a8248d09544e57e2b45ac9b2df29f858bcef8
[ "MIT" ]
null
null
null
35.2297
373
0.393405
[ [ [ "# Codenation - Data Science\n<pre>Autor: Leonardo Simões</pre>\n\n## Desafio 7 - Descubra as melhores notas de matemática do ENEM 2016\n\nVocê deverá criar um modelo para prever a nota da prova de matemática de quem participou do ENEM 2016. Para isso, usará Python, Pandas, Sklearn e Regression.\n\n### Detalhes\n\nO contexto do desafio gira em torno dos resultados do ENEM 2016 (disponíveis no arquivo train.csv). Este arquivo, e apenas ele, deve ser utilizado para todos os desafios. Qualquer dúvida a respeito das colunas, consulte o [Dicionário dos Microdados do Enem 2016](https://s3-us-west-1.amazonaws.com/acceleration-assets-highway/data-science/dicionario-de-dados.zip).\n\nNo arquivo test.csv crie um modelo para prever nota da prova de matemática (coluna `NU_NOTA_MT`) de quem participou do ENEM 2016. \n\nSalve sua resposta em um arquivo chamado answer.csv com duas colunas: `NU_INSCRICAO` e `NU_NOTA_MT`.\n\n### Tópicos\n\nNeste desafio você aprenderá:\n- Python\n- Pandas\n- Sklearn\n- Regression\n\n\n", "_____no_output_____" ], [ "## Setup geral", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error", "_____no_output_____" ] ], [ [ "## Análise dos dados", "_____no_output_____" ], [ "Lendo os arquivos de treino (train) e de teste (test).", "_____no_output_____" ] ], [ [ "df_train = pd.read_csv('train.csv')\ndf_train.head()", "_____no_output_____" ], [ "df_test = pd.read_csv('test.csv')\ndf_test.head()", "_____no_output_____" ] ], [ [ "Antes de manipular os dataframes, deve-separar as colunas de notas da prova de matemática do treino e a do número de inscrição do teste.", "_____no_output_____" ] ], [ [ "train_y = df_train['NU_NOTA_MT'].fillna(0)", "_____no_output_____" ], [ "n_insc = df_test['NU_INSCRICAO'].values", "_____no_output_____" ] ], [ [ "Idealmente os arquivos de teste e treino teriam as mesmas colunas, exceto a que deve ser predita. \nEntão, primeiro verifica-se a quantidade de colunas de cada, e depois exclui-se as colunas que não pertence a ambas.", "_____no_output_____" ] ], [ [ "len(df_test.columns)", "_____no_output_____" ], [ "len(df_train.columns)", "_____no_output_____" ], [ "colunas_intersecao = np.intersect1d(df_train.columns.values, df_test.columns.values)\ncolunas_intersecao", "_____no_output_____" ], [ "df_train = df_train[colunas_intersecao]\ndf_train.head()", "_____no_output_____" ], [ "df_test = df_test[colunas_intersecao]\ndf_test.head()", "_____no_output_____" ], [ "df_train.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 13730 entries, 0 to 13729\nData columns (total 47 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 CO_PROVA_CH 13730 non-null object \n 1 CO_PROVA_CN 13730 non-null object \n 2 CO_PROVA_LC 13730 non-null object \n 3 CO_PROVA_MT 13730 non-null object \n 4 CO_UF_RESIDENCIA 13730 non-null int64 \n 5 IN_BAIXA_VISAO 13730 non-null int64 \n 6 IN_CEGUEIRA 13730 non-null int64 \n 7 IN_DISCALCULIA 13730 non-null int64 \n 8 IN_DISLEXIA 13730 non-null int64 \n 9 IN_GESTANTE 13730 non-null int64 \n 10 IN_IDOSO 13730 non-null int64 \n 11 IN_SABATISTA 13730 non-null int64 \n 12 IN_SURDEZ 13730 non-null int64 \n 13 IN_TREINEIRO 13730 non-null int64 \n 14 NU_IDADE 13730 non-null int64 \n 15 NU_INSCRICAO 13730 non-null object \n 16 NU_NOTA_CH 10341 non-null float64\n 17 NU_NOTA_CN 10341 non-null float64\n 18 NU_NOTA_COMP1 10133 non-null float64\n 19 NU_NOTA_COMP2 10133 non-null float64\n 20 NU_NOTA_COMP3 10133 non-null float64\n 21 NU_NOTA_COMP4 10133 non-null float64\n 22 NU_NOTA_COMP5 10133 non-null float64\n 23 NU_NOTA_LC 10133 non-null float64\n 24 NU_NOTA_REDACAO 10133 non-null float64\n 25 Q001 13730 non-null object \n 26 Q002 13730 non-null object \n 27 Q006 13730 non-null object \n 28 Q024 13730 non-null object \n 29 Q025 13730 non-null object \n 30 Q026 13730 non-null object \n 31 Q027 6357 non-null object \n 32 Q047 13730 non-null object \n 33 SG_UF_RESIDENCIA 13730 non-null object \n 34 TP_ANO_CONCLUIU 13730 non-null int64 \n 35 TP_COR_RACA 13730 non-null int64 \n 36 TP_DEPENDENCIA_ADM_ESC 4282 non-null float64\n 37 TP_ENSINO 4282 non-null float64\n 38 TP_ESCOLA 13730 non-null int64 \n 39 TP_LINGUA 13730 non-null int64 \n 40 TP_NACIONALIDADE 13730 non-null int64 \n 41 TP_PRESENCA_CH 13730 non-null int64 \n 42 TP_PRESENCA_CN 13730 non-null int64 \n 43 TP_PRESENCA_LC 13730 non-null int64 \n 44 TP_SEXO 13730 non-null object \n 45 TP_STATUS_REDACAO 10133 non-null float64\n 46 TP_ST_CONCLUSAO 13730 non-null int64 \ndtypes: float64(12), int64(20), object(15)\nmemory usage: 4.9+ MB\n" ] ], [ [ "Em um momento anterior eu usei todas as colunas numéricas na predição, mas isso se mostrou menos eficaz do que usar apenas as colunas de notas.", "_____no_output_____" ] ], [ [ "colunas_numericas = df_train.select_dtypes(include=['float64', 'int64']).columns\ncolunas_numericas ", "_____no_output_____" ], [ "colunas_notas = ['NU_NOTA_CH', 'NU_NOTA_CN', 'NU_NOTA_COMP1', 'NU_NOTA_COMP2','NU_NOTA_COMP3',\n 'NU_NOTA_COMP4','NU_NOTA_COMP5','NU_NOTA_LC', 'NU_NOTA_REDACAO']", "_____no_output_____" ], [ "df_train = df_train[colunas_notas].fillna(0)", "_____no_output_____" ], [ "df_test = df_test[colunas_notas].fillna(0)", "_____no_output_____" ], [ "sc = StandardScaler()\nx_train = sc.fit_transform(df_train)\nx_test = sc.transform(df_test)", "_____no_output_____" ], [ "lm = LinearRegression()\nlm.fit(x_train, train_y)\ny_teste = lm.predict(x_test)\ny_teste = [round(y,1) for y in y_teste]", "_____no_output_____" ] ], [ [ "Depois de predizer as notas do arquivo de teste, estas foram salvar em um arquivo csv.", "_____no_output_____" ] ], [ [ "answer = pd.DataFrame()\nanswer['NU_INSCRICAO'] = n_insc\nanswer['NU_NOTA_MT'] = y_teste\nanswer.head()", "_____no_output_____" ], [ "answer.to_csv('answer.csv', index=False)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d012cd06e20f081da60c8d8a64b19347858b6549
634,707
ipynb
Jupyter Notebook
08 - The matplotlib Ecosystem/0802 - Pandas.ipynb
croach/mastering-matplotlib
fdc2aca87140a1927d9230ab61305cd742e200d5
[ "MIT" ]
137
2016-04-16T17:25:19.000Z
2022-01-22T21:45:41.000Z
08 - The matplotlib Ecosystem/0802 - Pandas.ipynb
croach/mastering-matplotlib
fdc2aca87140a1927d9230ab61305cd742e200d5
[ "MIT" ]
2
2016-04-09T19:27:49.000Z
2018-04-15T15:35:17.000Z
08 - The matplotlib Ecosystem/0802 - Pandas.ipynb
croach/mastering-matplotlib
fdc2aca87140a1927d9230ab61305cd742e200d5
[ "MIT" ]
76
2016-03-23T09:58:36.000Z
2021-08-05T14:28:02.000Z
1,590.744361
442,484
0.947242
[ [ [ "## Introduction\n\nIf you've had any experience with the python scientific stack, you've probably come into contact with, or at least heard of, the [pandas][1] data analysis library. Before the introduction of pandas, if you were to ask anyone what language to learn as a budding data scientist, most would've likely said the [R statistical programming language][2]. With its [data frame][3] data structure, it was the obvious winner when it came to filtering, slicing, aggregating, or analyzing your data. However, with the introduction of pandas to python's growing set of data analysis libraries, the gap between the two langauges has effectively closed, and as a result, pandas has become a vital tool for data scientists using python.\n\nWhile we won't be covering the pandas library itself, since that's a topic fit for a course of its own, in this lesson we will be discussing the simple interface pandas provides for interacting with the matplotlib library. In addition, we'll also take a look at the recent changes the matplotlib team has made to make it possible for the two libraries to work together more harmoniously.\n\nThat said, let's get set up and see what pandas has to offer.\n\n[1]: http://pandas.pydata.org/\n[2]: https://www.r-project.org/\n[3]: https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Data-frames", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom IPython.display import set_matplotlib_formats\nset_matplotlib_formats('retina')", "_____no_output_____" ] ], [ [ "### What is pandas?\n\nPandas is a library created by [Wes McKinney][1] that provides several data structures that make working with data fast, efficient, and easy. Chief among them is the `DataFrame`, which takes on R's `data.frame` data type, and in many scenarios, bests it. It also provides a simple wrapper around the `pyplot` interface, allowing you to plot the data in your `DataFrame` objects without any context switching in many cases. \n\nBut, enough talk, let's see it in action.\n\n[1]: https://twitter.com/wesmckinn\n\n### Import the Library\n\nThe following bit of code imports the pandas library using the widely accepted `pd` naming convention. You'll likely see pandas imported like this just about everywhere it's used, and it is recommended that you always use the same naming convention in your code as well.", "_____no_output_____" ] ], [ [ "import pandas as pd", "_____no_output_____" ] ], [ [ "### Load in Some Data\n\nIn the next cell, we'll use the `read_csv` function to load in the [Census Income][1] dataset from the [UCI Machine Learning Repository][2]. Incidentally, this is the exact same dataset that we used in our Exploratory Data Analysis (EDA) example in chapter 2, so we'll get to see some examples of how we could perform some of the same steps using the plotting commands on our `DataFrame` object. \n\n[1]: http://archive.ics.uci.edu/ml/datasets/Adult\n[2]: http://archive.ics.uci.edu/ml/index.html", "_____no_output_____" ] ], [ [ "import pandas as pd\n\n# Download and read in the data from the UCI Machine Learning Repository\ndf = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data', \n header=None,\n names=('age', \n 'workclass', \n 'fnlwgt', \n 'education', \n 'education_num', \n 'marital_status', \n 'occupation', \n 'relationship', \n 'race', \n 'sex', \n 'capital_gain', \n 'capital_loss', \n 'hours_per_week', \n 'native_country', \n 'target'))", "_____no_output_____" ] ], [ [ "### Plotting With pandas\n\nJust like we did in our EDA example from chapter 2, we can once again create a simple histogram from our data. This time though, notice that we simply call the `hist` command on the column that contains the education level to plot our data.", "_____no_output_____" ] ], [ [ "df.education_num.hist(bins=16);", "_____no_output_____" ] ], [ [ "And, remember, pandas isn't doing anything magical here, it's just providing a very simple wrapper around the `pyplot` module. At the end of the day, the code above is simply calling the `pyplot.hist` function to create the histogram. So, we can interact with the plot that it produces the same way we would any other plot. As an example, let's create our histogram again, but this time let's get rid of that empty bar to the left by setting the plot's x-axis limits using the `pyplot.xlim` function.", "_____no_output_____" ] ], [ [ "df.education_num.hist(bins=16)\n# Remove the empty bar from the histogram that's below the \n# education_num's minimum value.\nplt.xlim(df.education_num.min(), df.education_num.max());", "_____no_output_____" ] ], [ [ "Well, that looks better, but we're still stuck with many of the same problems that we had in the original EDA lesson. You'll notice that most of the x-ticks don't actually line up with their bars, and there's a good reason for that. Remember, in that lesson, we discussed how a histogram was meant to be used with continuous data, and in our case we're dealing with discrete values. So, a bar chart is actually what we want to use here.\n\nLuckily, pandas makes the task of creating the bar chart even easier. In our EDA lesson, we had to do the frequency count ourselves, and take care of lining the x-axis labels up properly, and several other small issues. With pandas, it's just a single line of code. First, we call the `value_counts` function on the `education` column to get a set of frequency counts, ordered largest to smallest, for each education level. Then, we call the `plot` function on the `Series` object returned from `value_counts`, and pass in the type of plot with the `kind` parameter, and while we're at it, we'll set our width to 1, like we did in the chapter 2 example, to make it look more histogram-ish.", "_____no_output_____" ] ], [ [ "df.education.value_counts().plot(kind='bar', width=1);", "_____no_output_____" ] ], [ [ "Now, rather than passing in the plot type with the `kind` parameter, we could've also just called the `bar` function from the `plot` object, like we do in the next cell.", "_____no_output_____" ] ], [ [ "df.education.value_counts().plot.bar(width=1);", "_____no_output_____" ] ], [ [ "Ok, so that's a pretty good introduction to the simple interface that pandas provides to the matplotlib library, but it doesn't stop there. Pandas also provides a handful of more complex plotting functions in the `pandas.tools.plotting` module. So, let's import another dataset and take a look at an example of what's available. \n\nIn the cell below, we pull in the Iris dataset that we used in our scatterplot matrix example from chapter 3. Incidentally, if you don't want to mess with network connections, or if you happen to be in a situation where network access just isn't an option, I've copied the data file to the local data folder. The file can be found at `./data/iris_data.csv`", "_____no_output_____" ] ], [ [ "df = pd.read_csv('https://raw.githubusercontent.com/pydata/pandas/master/pandas/tests/data/iris.csv')", "_____no_output_____" ] ], [ [ "We'll need a color map, essentially just a dictionary mapping each species to a unique color, so we'll put one together in the next cell. Fortunately, pandas makes it easy to get the species names by simply calling the `unique` function on the `Name` column.", "_____no_output_____" ] ], [ [ "names = df.Name.unique()\ncolors = ['red', 'green', 'blue']\ncmap = dict(zip(names, colors))", "_____no_output_____" ] ], [ [ "Now, before we take a look at one of the functions from the `plotting` module, let's quickly take a look at one of the [changes that was made to matplotlib in version 1.5][1] to accommodate labeled data, like a pandas `DataFrame` for example. The code in the next cell, creates a scatter plot using the `pyplot.scatter` function, like we've done in the past, but notice how we specify the columns that contain our `x` and `y` values. In our example below, we are simply passing in the names of the columns alongside the `DataFrame` object itself. Now, it's arguable just how much more readable this light layer of abstraction is over just passing in the data directly, but it's nice to have the option, nonetheless.\n\n[1]: http://matplotlib.org/users/whats_new.html#working-with-labeled-data-like-pandas-dataframes", "_____no_output_____" ] ], [ [ "plt.scatter(x='PetalLength', y='PetalWidth', data=df, c=df.Name.apply(lambda name: cmap[name]));", "_____no_output_____" ] ], [ [ "Now, we're ready to take a look at one of the functions that pandas provides us, and for comparison sake, let's take a look at our old friend, the scatterplot matrix. In the next cell, we'll import the `scatter_matrix` function from the `pandas.tools.plotting` module and run it on the Iris dataset.", "_____no_output_____" ] ], [ [ "from pandas.tools.plotting import scatter_matrix\nscatter_matrix(df, figsize=(10,8), c=df.Name.apply(lambda name: cmap[name]), s=40);", "_____no_output_____" ] ], [ [ "Well, that looks pretty good, and it's a heck of a lot easier than writing our own. Though, I prefer the seaborn version, this one will do in a pinch. If you get a chance, I recommend taking a look at what the pandas `plotting` module has to offer. Aside from the scatterplot matrix function, it also provides functions for creating things like density plots and parallel coordinates plots. It's not as powerful as the seaborn library, but many times it may be all you need to perform your analysis.\n\n## Conclusion\n\nAnd, that will bring us to the end once again.\n\nTo recap, in this lesson, we saw some quick examples of how to use the Pandas data analysis library with the matplotlib library. Specifically, we saw a few examples of the simple interface that pandas provides to the `pyplot` module, and we also saw one example of the new labeled data change that was made to matplotlib in version 1.5. Finally, we took a quick look at one of the more complex functions that the pandas `plotting` module provides.\n\nThe main goal of this lesson wasn't to turn you into a pandas power user, but rather to give you some idea of what pandas provides, and more importantly, to take away any of the mystery of how it works. Now that you understand that pandas is basically just providing a very simple layer of abstraction on top of the `pyplot` interface, you should be prepared to deal with any issues that come up when plotting the data in your `DataFrame` objects.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]