hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
list | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
list | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
list | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
list | cell_types
list | cell_type_groups
list |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ecccbd70c8e60f8892206c65d4fb55867369a211 | 6,215 | ipynb | Jupyter Notebook | python/python_examples/fftDev/nFactorNP.ipynb | rrjudd/jvsip | 56a965fff595b027139ff151d27d434f2480b9e8 | [
"MIT"
] | 10 | 2016-01-16T04:10:13.000Z | 2022-03-22T02:17:44.000Z | python/python_examples/fftDev/nFactorNP.ipynb | rrjudd/jvsip | 56a965fff595b027139ff151d27d434f2480b9e8 | [
"MIT"
] | 1 | 2015-09-11T04:48:03.000Z | 2015-09-11T13:44:29.000Z | python/python_examples/fftDev/nFactorNP.ipynb | rrjudd/jvsip | 56a965fff595b027139ff151d27d434f2480b9e8 | [
"MIT"
] | 4 | 2017-06-13T21:48:23.000Z | 2020-08-26T15:07:44.000Z | 16.529255 | 63 | 0.388254 | [
[
[
"### Factor Integer N into two largest common denominators",
"_____no_output_____"
]
],
[
[
"def factors(N):\n n=int(N)\n lm=n/2 + 1\n out=[]\n t = 1\n for i in range(2,lm):\n if N % i == 0 and t == 1:\n a=i;b=N/i\n out.append((a,b))\n if a >= b:\n print(a,b)\n t = 0\n if t == 1:\n print('prime')",
"_____no_output_____"
],
[
"factors(93*7)",
"(31, 21)\n"
],
[
"factors(31)",
"prime\n"
],
[
"factors(21)",
"(7, 3)\n"
],
[
"factors(7), factors(3)",
"prime\nprime\n"
],
[
"def factors0(N):\n n=int(N)\n lm=n/2 + 1\n a=1; b=N\n for i in range(2,lm):\n if N % i == 0:\n a=i;b=N/i\n if a >= b:\n break\n if a != 1:\n factors0(a)\n if b != N:\n factors0(b)\n print((a,b))",
"_____no_output_____"
],
[
"def factors1(N):\n n=int(N)\n lm=n/2 + 1\n a=1; b=N\n for i in range(2,lm):\n if N % i == 0:\n a=i;b=N/i\n if a >= b:\n break\n if a != 1:\n factors1(a)\n if b != N:\n factors1(b)\n if a == 1:\n print(b)",
"_____no_output_____"
],
[
"factors1(16812)",
"467\n3\n2\n3\n2\n"
],
[
"n1 = N/16811\nn1",
"_____no_output_____"
],
[
"n2 = n1/17\nn2",
"_____no_output_____"
],
[
"n3 = n2/7\nn3",
"_____no_output_____"
],
[
"3 * 3 * 7 * 17 * 16811",
"_____no_output_____"
],
[
"factors0(98)",
"(1, 7)\n(1, 2)\n(7, 2)\n(1, 7)\n(14, 7)\n"
],
[
"factors0(14)",
"(1, 7)\n(1, 2)\n(7, 2)\n"
],
[
"98 % 7",
"_____no_output_____"
],
[
"98/7",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecccc37ce06484875f63a148e0bd2ab33dca79ae | 88,487 | ipynb | Jupyter Notebook | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial3.ipynb | KylePoe/course-content-dl | 9849a7f3c3dd139a5e99b38ac526fd78077d8ee3 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | null | null | null | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial3.ipynb | KylePoe/course-content-dl | 9849a7f3c3dd139a5e99b38ac526fd78077d8ee3 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | null | null | null | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial3.ipynb | KylePoe/course-content-dl | 9849a7f3c3dd139a5e99b38ac526fd78077d8ee3 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | null | null | null | 36.854227 | 807 | 0.563563 | [
[
[
"<a href=\"https://colab.research.google.com/github/NeuromatchAcademy/course-content-dl/blob/main/tutorials/W1D2_LinearDeepLearning/W1D2_Tutorial3.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a> <a href=\"https://kaggle.com/kernels/welcome?src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial3.ipynb\" target=\"_parent\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open in Kaggle\"/></a>",
"_____no_output_____"
],
[
"# Tutorial 3: Deep linear neural networks\n**Week 1, Day 2: Linear Deep Learning**\n\n**By Neuromatch Academy**\n\n__Content creators:__ Saeed Salehi, Spiros Chavlis, Andrew Saxe\n\n__Content reviewers:__ Polina Turishcheva, Antoine De Comite\n\n__Content editors:__ Anoop Kulkarni\n\n__Production editors:__ Khalid Almubarak, Spiros Chavlis\n",
"_____no_output_____"
],
[
"**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**\n\n<p align='center'><img src='https://github.com/NeuromatchAcademy/widgets/blob/master/sponsors.png?raw=True'/></p>",
"_____no_output_____"
],
[
"---\n# Tutorial Objectives\n\n* Deep linear neural networks\n* Learning dynamics and singular value decomposition\n* Representational Similarity Analysis\n* Illusory correlations & ethics",
"_____no_output_____"
]
],
[
[
"# @title Tutorial slides\n\n# @markdown These are the slides for the videos in this tutorial\n\n# @markdown If you want to locally download the slides, click [here](https://osf.io/bncr8/download)\nfrom IPython.display import IFrame\nIFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/bncr8/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)",
"_____no_output_____"
]
],
[
[
"---\n# Setup\n\nThis a GPU-Free tutorial!",
"_____no_output_____"
]
],
[
[
"# @title Install dependencies\n!pip install git+https://github.com/NeuromatchAcademy/evaltools --quiet\n\nfrom evaltools.airtable import AirtableForm",
"_____no_output_____"
],
[
"# Imports\nimport math\nimport torch\nimport matplotlib\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch.nn as nn\nimport torch.optim as optim",
"_____no_output_____"
],
[
"# @title Figure settings\n\nfrom matplotlib import gridspec\nfrom ipywidgets import interact, IntSlider, FloatSlider, fixed\nfrom ipywidgets import FloatLogSlider, Layout, VBox\nfrom ipywidgets import interactive_output\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n%config InlineBackend.figure_format = 'retina'\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle\")",
"_____no_output_____"
],
[
"# @title Plotting functions\n\ndef plot_x_y_hier_data(im1, im2, subplot_ratio=[1, 2]):\n fig = plt.figure(figsize=(12, 5))\n gs = gridspec.GridSpec(1, 2, width_ratios=subplot_ratio)\n ax0 = plt.subplot(gs[0])\n ax1 = plt.subplot(gs[1])\n ax0.imshow(im1, cmap=\"cool\")\n ax1.imshow(im2, cmap=\"cool\")\n # plt.suptitle(\"The whole dataset as imshow plot\", y=1.02)\n ax0.set_title(\"Labels of all samples\")\n ax1.set_title(\"Features of all samples\")\n ax0.set_axis_off()\n ax1.set_axis_off()\n plt.tight_layout()\n plt.show()\n\n\ndef plot_x_y_hier_one(im1, im2, subplot_ratio=[1, 2]):\n fig = plt.figure(figsize=(12, 1))\n gs = gridspec.GridSpec(1, 2, width_ratios=subplot_ratio)\n ax0 = plt.subplot(gs[0])\n ax1 = plt.subplot(gs[1])\n ax0.imshow(im1, cmap=\"cool\")\n ax1.imshow(im2, cmap=\"cool\")\n ax0.set_title(\"Labels of a single sample\")\n ax1.set_title(\"Features of a single sample\")\n ax0.set_axis_off()\n ax1.set_axis_off()\n plt.tight_layout()\n plt.show()\n\n\ndef plot_tree_data(label_list = None, feature_array = None, new_feature = None):\n cmap = matplotlib.colors.ListedColormap(['cyan', 'magenta'])\n n_features = 10\n n_labels = 8\n im1 = np.eye(n_labels)\n if feature_array is None:\n im2 = np.array([[1, 1, 1, 1, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 1, 1, 1],\n [1, 1, 1, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 1],\n [0, 0, 1, 1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 1, 0, 0],\n [0, 1, 1, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 1, 0, 1]]).T\n im2[im2 == 0] = -1\n feature_list = ['can_grow',\n 'is_mammal',\n 'has_leaves',\n 'can_move',\n 'has_trunk',\n 'can_fly',\n 'can_swim',\n 'has_stem',\n 'is_warmblooded',\n 'can_flower']\n else:\n im2 = feature_array\n if label_list is None:\n label_list = ['Goldfish', 'Tuna', 'Robin', 'Canary',\n 'Rose', 'Daisy', 'Pine', 'Oak']\n fig = plt.figure(figsize=(12, 7))\n gs = gridspec.GridSpec(1, 2, width_ratios=[1, 1.35])\n ax1 = plt.subplot(gs[0])\n ax2 = plt.subplot(gs[1])\n ax1.imshow(im1, cmap=cmap)\n if feature_array is None:\n implt = ax2.imshow(im2, cmap=cmap, vmin=-1.0, vmax=1.0)\n else:\n implt = ax2.imshow(im2[:, -n_features:], cmap=cmap, vmin=-1.0, vmax=1.0)\n divider = make_axes_locatable(ax2)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.1)\n cbar = plt.colorbar(implt, cax=cax, ticks=[-0.5, 0.5])\n cbar.ax.set_yticklabels(['no', 'yes'])\n ax1.set_title(\"Labels\")\n ax1.set_yticks(ticks=np.arange(n_labels))\n ax1.set_yticklabels(labels=label_list)\n ax1.set_xticks(ticks=np.arange(n_labels))\n ax1.set_xticklabels(labels=label_list, rotation='vertical')\n ax2.set_title(\"{} random Features\".format(n_features))\n ax2.set_yticks(ticks=np.arange(n_labels))\n ax2.set_yticklabels(labels=label_list)\n if feature_array is None:\n ax2.set_xticks(ticks=np.arange(n_features))\n ax2.set_xticklabels(labels=feature_list, rotation='vertical')\n else:\n ax2.set_xticks(ticks=[n_features-1])\n ax2.set_xticklabels(labels=[new_feature], rotation='vertical')\n plt.tight_layout()\n plt.show()\n\n\ndef plot_loss(loss_array, title=\"Training loss (Mean Squared Error)\", c=\"r\"):\n plt.figure(figsize=(10, 5))\n plt.plot(loss_array, color=c)\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"MSE\")\n plt.title(title)\n plt.show()\n\n\ndef plot_loss_sv(loss_array, sv_array):\n n_sing_values = sv_array.shape[1]\n sv_array = sv_array / np.max(sv_array)\n cmap = plt.cm.get_cmap(\"Set1\", n_sing_values)\n\n _, (plot1, plot2) = plt.subplots(2, 1, sharex=True, figsize=(10, 10))\n plot1.set_title(\"Training loss (Mean Squared Error)\")\n plot1.plot(loss_array, color='r')\n\n plot2.set_title(\"Evolution of singular values (modes)\")\n for i in range(n_sing_values):\n plot2.plot(sv_array[:, i], c=cmap(i))\n plot2.set_xlabel(\"Epoch\")\n plt.show()\n\n\ndef plot_loss_sv_twin(loss_array, sv_array):\n n_sing_values = sv_array.shape[1]\n sv_array = sv_array / np.max(sv_array)\n cmap = plt.cm.get_cmap(\"winter\", n_sing_values)\n\n fig = plt.figure(figsize=(10, 5))\n ax1 = plt.gca()\n ax1.set_title(\"Learning Dynamics\")\n ax1.set_xlabel(\"Epoch\")\n ax1.set_ylabel(\"Mean Squared Error\", c='r')\n ax1.tick_params(axis='y', labelcolor='r')\n ax1.plot(loss_array, color='r')\n\n ax2 = ax1.twinx()\n ax2.set_ylabel(\"Singular values (modes)\", c='b')\n ax2.tick_params(axis='y', labelcolor='b')\n for i in range(n_sing_values):\n ax2.plot(sv_array[:, i], c=cmap(i))\n\n fig.tight_layout()\n plt.show()\n\n\ndef plot_ills_sv_twin(ill_array, sv_array, ill_label):\n n_sing_values = sv_array.shape[1]\n sv_array = sv_array / np.max(sv_array)\n cmap = plt.cm.get_cmap(\"winter\", n_sing_values)\n\n fig = plt.figure(figsize=(10, 5))\n ax1 = plt.gca()\n ax1.set_title(\"Network training and the Illusory Correlations\")\n ax1.set_xlabel(\"Epoch\")\n ax1.set_ylabel(ill_label, c='r')\n ax1.tick_params(axis='y', labelcolor='r')\n ax1.plot(ill_array, color='r', linewidth=3)\n ax1.set_ylim(-1.05, 1.05)\n # ax1.set_yticks([-1, 0, 1])\n # ax1.set_yticklabels(['False', 'Not sure', 'True'])\n\n ax2 = ax1.twinx()\n ax2.set_ylabel(\"Singular values (modes)\", c='b')\n ax2.tick_params(axis='y', labelcolor='b')\n for i in range(n_sing_values):\n ax2.plot(sv_array[:, i], c=cmap(i))\n\n fig.tight_layout()\n plt.show()\n\n\ndef plot_loss_sv_rsm(loss_array, sv_array, rsm_array, i_ep):\n n_ep = loss_array.shape[0]\n rsm_array = rsm_array / np.max(rsm_array)\n sv_array = sv_array / np.max(sv_array)\n\n n_sing_values = sv_array.shape[1]\n cmap = plt.cm.get_cmap(\"winter\", n_sing_values)\n\n fig = plt.figure(figsize=(14, 5))\n gs = gridspec.GridSpec(1, 2, width_ratios=[5, 3])\n\n ax0 = plt.subplot(gs[1])\n ax0.yaxis.tick_right()\n implot = ax0.imshow(rsm_array[i_ep], cmap=\"Purples\", vmin=0.0, vmax=1.0)\n divider = make_axes_locatable(ax0)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.9)\n cbar = plt.colorbar(implot, cax=cax, ticks=[])\n cbar.ax.set_ylabel('Similarity', fontsize=12)\n ax0.set_title(\"RSM at epoch {}\".format(i_ep), fontsize=16)\n # ax0.set_axis_off()\n ax0.set_yticks(ticks=np.arange(n_sing_values))\n ax0.set_yticklabels(labels=item_names)\n # ax0.set_xticks([])\n ax0.set_xticks(ticks=np.arange(n_sing_values))\n ax0.set_xticklabels(labels=item_names, rotation='vertical')\n\n ax1 = plt.subplot(gs[0])\n ax1.set_title(\"Learning Dynamics\", fontsize=16)\n ax1.set_xlabel(\"Epoch\")\n ax1.set_ylabel(\"Mean Squared Error\", c='r')\n ax1.tick_params(axis='y', labelcolor='r', direction=\"in\")\n ax1.plot(np.arange(n_ep), loss_array, color='r')\n ax1.axvspan(i_ep-2, i_ep+2, alpha=0.2, color='m')\n\n ax2 = ax1.twinx()\n ax2.set_ylabel(\"Singular values\", c='b')\n ax2.tick_params(axis='y', labelcolor='b', direction=\"in\")\n for i in range(n_sing_values):\n ax2.plot(np.arange(n_ep), sv_array[:, i], c=cmap(i))\n ax1.set_xlim(-1, n_ep+1)\n ax2.set_xlim(-1, n_ep+1)\n\n plt.show()",
"_____no_output_____"
],
[
"#@title Helper functions\n\natform = AirtableForm('appn7VdPRseSoMXEG',\\\n 'W1D2_T3','https://portal.neuromatchacademy.org/api/redirect/to/f60119ed-1c22-4dae-9e18-b6a767f477e1')\n\ndef build_tree(n_levels, n_branches, probability, to_np_array=True):\n \"\"\"Builds a tree\n \"\"\"\n assert 0.0 <= probability <= 1.0\n\n tree = {}\n\n tree[\"level\"] = [0]\n for i in range(1, n_levels+1):\n tree[\"level\"].extend([i]*(n_branches**i))\n\n tree[\"pflip\"] = [probability]*len(tree[\"level\"])\n\n tree[\"parent\"] = [None]\n k = len(tree[\"level\"])-1\n for j in range(k//n_branches):\n tree[\"parent\"].extend([j]*n_branches)\n\n if to_np_array:\n tree[\"level\"] = np.array(tree[\"level\"])\n tree[\"pflip\"] = np.array(tree[\"pflip\"])\n tree[\"parent\"] = np.array(tree[\"parent\"])\n\n return tree\n\n\ndef sample_from_tree(tree, n):\n \"\"\" Generates n samples from a tree\n \"\"\"\n items = [i for i, v in enumerate(tree[\"level\"]) if v == max(tree[\"level\"])]\n n_items = len(items)\n x = np.zeros(shape=(n, n_items))\n rand_temp = np.random.rand(n, len(tree[\"pflip\"]))\n flip_temp = np.repeat(tree[\"pflip\"].reshape(1, -1), n, 0)\n samp = (rand_temp > flip_temp) * 2 - 1\n\n for i in range(n_items):\n j = items[i]\n prop = samp[:, j]\n while tree[\"parent\"][j] is not None:\n j = tree[\"parent\"][j]\n prop = prop * samp[:, j]\n x[:, i] = prop.T\n return x\n\n\ndef generate_hsd():\n # building the tree\n n_branches = 2 # 2 branches at each node\n probability = .15 # flipping probability\n n_levels = 3 # number of levels (depth of tree)\n tree = build_tree(n_levels, n_branches, probability, to_np_array=True)\n tree[\"pflip\"][0] = 0.5\n n_samples = 10000 # Sample this many features\n\n tree_labels = np.eye(n_branches**n_levels)\n tree_features = sample_from_tree(tree, n_samples).T\n return tree_labels, tree_features\n\n\ndef linear_regression(X, Y):\n \"\"\"Analytical Linear regression\n\n \"\"\"\n assert isinstance(X, np.ndarray)\n assert isinstance(Y, np.ndarray)\n M, Dx = X.shape\n N, Dy = Y.shape\n assert Dx == Dy\n W = Y @ X.T @ np.linalg.inv(X @ X.T)\n return W\n\n\ndef add_feature(existing_features, new_feature):\n assert isinstance(existing_features, np.ndarray)\n assert isinstance(new_feature, list)\n new_feature = np.array([new_feature]).T\n # return np.hstack((tree_features, new_feature*2-1))\n return np.hstack((tree_features, new_feature))\n\n\ndef net_svd(model, in_dim):\n \"\"\"Performs a Singular Value Decomposition on a given model weights\n\n Args:\n model (torch.nn.Module): neural network model\n in_dim (int): the input dimension of the model\n\n Returns:\n U, Σ, V (Tensors): Orthogonal, diagonal, and orthogonal matrices\n \"\"\"\n W_tot = torch.eye(in_dim)\n for weight in model.parameters():\n W_tot = weight.detach() @ W_tot\n U, SIGMA, V = torch.svd(W_tot)\n return U, SIGMA, V\n\n\ndef net_rsm(h):\n \"\"\"Calculates the Representational Similarity Matrix\n\n Arg:\n h (torch.Tensor): activity of a hidden layer\n\n Returns:\n (torch.Tensor): Representational Similarity Matrix\n \"\"\"\n rsm = h @ h.T\n return rsm\n\n\ndef initializer_(model, gamma=1e-12):\n \"\"\"(in-place) Re-initialization of weights\n\n Args:\n model (torch.nn.Module): PyTorch neural net model\n gamma (float): initialization scale\n \"\"\"\n for weight in model.parameters():\n n_out, n_in = weight.shape\n sigma = gamma / math.sqrt(n_in + n_out)\n nn.init.normal_(weight, mean=0.0, std=sigma)\n\n\ndef test_initializer_ex(seed):\n torch.manual_seed(seed)\n model = LNNet(5000, 5000, 1)\n try:\n ex_initializer_(model, gamma=1)\n std = torch.std(next(iter(model.parameters())).detach()).item()\n if -1e-5 <= (std - 0.01) <= 1e-5:\n print(\"Well done! Seems to be correct!\")\n else:\n print(\"Please double check your implementation!\")\n except:\n print(\"Faulty Implementation!\")\n\n\ndef test_net_svd_ex(seed):\n torch.manual_seed(seed)\n model = LNNet(8, 30, 100)\n try:\n U_ex, Σ_ex, V_ex = ex_net_svd(model, 8)\n U, Σ, V = net_svd(model, 8)\n if (torch.all(torch.isclose(U_ex.detach(), U.detach(), atol=1e-6)) and\n torch.all(torch.isclose(Σ_ex.detach(), Σ.detach(), atol=1e-6)) and\n torch.all(torch.isclose(V_ex.detach(), V.detach(), atol=1e-6))):\n print(\"Well done! Seems to be correct!\")\n else:\n print(\"Please double check your implementation!\")\n except:\n print(\"Faulty Implementation!\")\n\n\ndef test_net_rsm_ex(seed):\n torch.manual_seed(seed)\n x = torch.rand(7, 17)\n try:\n y_ex = ex_net_rsm(x)\n y = x @ x.T\n if (torch.all(torch.isclose(y_ex, y, atol=1e-6))):\n print(\"Well done! Seems to be correct!\")\n else:\n print(\"Please double check your implementation!\")\n except:\n print(\"Faulty Implementation!\")",
"_____no_output_____"
],
[
"#@title Set random seed\n\n#@markdown Executing `set_seed(seed=seed)` you are setting the seed\n\n# for DL its critical to set the random seed so that students can have a\n# baseline to compare their results to expected results.\n# Read more here: https://pytorch.org/docs/stable/notes/randomness.html\n\n# Call `set_seed` function in the exercises to ensure reproducibility.\nimport random\nimport torch\n\ndef set_seed(seed=None, seed_torch=True):\n if seed is None:\n seed = np.random.choice(2 ** 32)\n random.seed(seed)\n np.random.seed(seed)\n if seed_torch:\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print(f'Random seed {seed} has been set.')\n\n\n# In case that `DataLoader` is used\ndef seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)",
"_____no_output_____"
],
[
"#@title Set device (GPU or CPU). Execute `set_device()`\n# especially if torch modules used.\n\n# inform the user if the notebook uses GPU or CPU.\n\ndef set_device():\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n if device != \"cuda\":\n print(\"GPU is not enabled in this notebook. \\n\"\n \"If you want to enable it, in the menu under `Runtime` -> \\n\"\n \"`Hardware accelerator.` and select `GPU` from the dropdown menu\")\n else:\n print(\"GPU is enabled in this notebook. \\n\"\n \"If you want to disable it, in the menu under `Runtime` -> \\n\"\n \"`Hardware accelerator.` and select `None` from the dropdown menu\")\n\n return device",
"_____no_output_____"
],
[
"SEED = 2021\nset_seed(seed=SEED)\nDEVICE = set_device()",
"_____no_output_____"
]
],
[
[
"This colab notebook is GPU free!",
"_____no_output_____"
],
[
"---\n# Section 0: Prelude\n*Time estimate: ~10 mins*\n\n",
"_____no_output_____"
],
[
"**A note on the exercises**: Most of the exercises are marked Optional (Bonus) and should only read through them if you are in a tight timeline. Therefore we would not rely on the implementation of the exercises. If necessary, you can look at the *Helper Functions* cell above to find the functions and classes used in this tutorial.\n\nThroughout this tutorial, we will use a linear neural net with a single hidden layer. We have also excluded `bias` from the layers. Please note that the forward loop returns the hidden activation, besides the network output (prediction). we will need it in section 3.",
"_____no_output_____"
]
],
[
[
"class LNNet(nn.Module):\n \"\"\"A Linear Neural Net with one hidden layer\n \"\"\"\n\n def __init__(self, in_dim, hid_dim, out_dim):\n \"\"\"\n Args:\n in_dim (int): input dimension\n out_dim (int): ouput dimension\n hid_dim (int): hidden dimension\n \"\"\"\n super().__init__()\n self.in_hid = nn.Linear(in_dim, hid_dim, bias=False)\n self.hid_out = nn.Linear(hid_dim, out_dim, bias=False)\n\n def forward(self, x):\n \"\"\"\n Args:\n x (torch.Tensor): input tensor\n \"\"\"\n hid = self.in_hid(x) # hidden activity\n out = self.hid_out(hid) # output (prediction)\n return out, hid",
"_____no_output_____"
]
],
[
[
"Other than `net_svd` and `net_rsm` functions, the training loop should be mostly familiar to you. We will define these functions in the coming sections.\n\n**important**: Please note that the two functions are part of inner training loop and are therefore executed and recorded at every iteration.",
"_____no_output_____"
]
],
[
[
"def train(model, inputs, targets, n_epochs, lr, illusory_i=0):\n \"\"\"Training function\n\n Args:\n model (torch nn.Module): the neural network\n inputs (torch.Tensor): features (input) with shape `[batch_size, input_dim]`\n targets (torch.Tensor): targets (labels) with shape `[batch_size, output_dim]`\n n_epochs (int): number of training epochs (iterations)\n lr (float): learning rate\n illusory_i (int): index of illusory feature\n\n Returns:\n np.ndarray: record (evolution) of training loss\n np.ndarray: record (evolution) of singular values (dynamic modes)\n np.ndarray: record (evolution) of representational similarity matrices\n np.ndarray: record of network prediction for the last feature\n \"\"\"\n in_dim = inputs.size(1)\n\n losses = np.zeros(n_epochs) # loss records\n modes = np.zeros((n_epochs, in_dim)) # singular values (modes) records\n rs_mats = [] # representational similarity matrices\n illusions = np.zeros(n_epochs) # prediction for the given feature\n\n optimizer = optim.SGD(model.parameters(), lr=lr)\n criterion = nn.MSELoss()\n\n for i in range(n_epochs):\n optimizer.zero_grad()\n predictions, hiddens = model(inputs)\n loss = criterion(predictions, targets)\n loss.backward()\n optimizer.step()\n\n # Section 2 Singular value decomposition\n U, Σ, V = net_svd(model, in_dim)\n\n # Section 3 calculating representational similarity matrix\n RSM = net_rsm(hiddens.detach())\n\n # Section 4 network prediction of illusory_i inputs for the last feature\n pred_ij = predictions.detach()[illusory_i, -1]\n\n # logging (recordings)\n losses[i] = loss.item()\n modes[i] = Σ.detach().numpy()\n rs_mats.append(RSM.numpy())\n illusions[i] = pred_ij.numpy()\n\n return losses, modes, np.array(rs_mats), illusions",
"_____no_output_____"
]
],
[
[
"We also need take over the initialization of the weights. In PyTorch, [`nn.init`](https://pytorch.org/docs/stable/nn.init.html) provides us with the functions to initialize tensors from a given distribution.",
"_____no_output_____"
],
[
"## Coding Exercise 0: Re-initialization (Optional)\n\nComplete the function `ex_initializer_`, such that the weights are sampled from the following distribution:\n\n\\begin{equation}\n\\mathcal{N}\\left(\\mu=0, ~~\\sigma=\\gamma \\sqrt{\\dfrac{1}{n_{in} + n_{out}}} \\right)\n\\end{equation}\n\nwhere $\\gamma$ is the initialization scale, $n_{in}$ and $n_{out}$ are respectively input and output dimensions of the layer. the Underscore (\"_\") in `ex_initializer_` and other functions, denotes \"[in-place](https://discuss.pytorch.org/t/what-is-in-place-operation/16244/2)\" operation.\n\n**important note**: since we did not include bias in the layers, the `model.parameters()` would only return the weights in each layer.",
"_____no_output_____"
]
],
[
[
"#add event to airtable\natform.add_event('Coding Exercise 0: Re-initialization')\n\ndef ex_initializer_(model, gamma=1e-12):\n \"\"\"(in-place) Re-initialization of weights\n\n Args:\n model (torch.nn.Module): PyTorch neural net model\n gamma (float): initialization scale\n \"\"\"\n for weight in model.parameters():\n n_out, n_in = weight.shape\n #################################################\n ## Define the standard deviation (sigma) for the normal distribution\n # as given in the equation above\n # Complete the function and remove or comment the line below\n raise NotImplementedError(\"Function `ex_initializer_`\")\n #################################################\n sigma = ...\n nn.init.normal_(weight, mean=0.0, std=sigma)\n\n\n\n## uncomment and run\n# test_initializer_ex(SEED)",
"_____no_output_____"
]
],
[
[
"[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D2_LinearDeepLearning/solutions/W1D2_Tutorial3_Solution_e471aef3.py)\n\n",
"_____no_output_____"
],
[
"---\n# Section 1: Deep Linear Neural Nets\n\n*Time estimate: ~20 mins*",
"_____no_output_____"
]
],
[
[
"# @title Video 1: Intro to Representation Learning\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1iM4y1T7eJ\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"DqMSU4Bikt0\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n#add event to airtable\natform.add_event('Video 1: Intro to Representation Learning')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"So far, depth just seems to slow down the learning. And we know that a single nonlinear hidden layer (given enough number of neurons and infinite training samples) has the potential to approximate any function. So it seems fair to ask: **What is depth good for**?\n\nOne reason can be that shallow nonlinear neural networks hardly meet their true potential in practice. In the contrast, deep neural nets are often surprisingly powerful in learning complex functions without sacrificing generalization. A core intuition behind deep learning is that deep nets derive their power through learning internal representations. How does this work? To address representation learning, we have to go beyond the 1D chain.\n\nFor this and the next couple of exercises, we use syntactically generated hierarchically structured data through a *branching diffusion process* (see [this reference](https://www.pnas.org/content/pnas/suppl/2019/05/16/1820226116.DCSupplemental/pnas.1820226116.sapp.pdf) for more details).\n\n<center><img src=\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W1D2_LinearDeepLearning/static/tree.png\" alt=\"Simple nn graph\" width=\"600\"/></center>\n\n<center> hierarchically structured data (a tree) </center>\n\nThe inputs to the network are labels (i.e. names), while the outputs are the features (i.e. attributes). For example, for the label \"Goldfish\", the network has to learn all the (artificially created) features, such as \"*can swim*\", \"*is cold-blooded*\", \"*has fins*\", and more. Given that we are training on hierarchically structured data, network could also learn the tree structure, that Goldfish and Tuna have rather similar features, and Robin has more in common with Tuna, compared to Rose.",
"_____no_output_____"
]
],
[
[
"# @markdown #### Run to generate and visualize training samples from tree\n\ntree_labels, tree_features = generate_hsd()\n\n# convert (cast) data from np.ndarray to torch.Tensor\nlabel_tensor = torch.tensor(tree_labels).float()\nfeature_tensor = torch.tensor(tree_features).float()\n\nitem_names = ['Goldfish', 'Tuna', 'Robin', 'Canary',\n 'Rose', 'Daisy', 'Pine', 'Oak']\nplot_tree_data()\n\n# dimensions\nprint(\"---------------------------------------------------------------\")\nprint(\"Input Dimension: {}\".format(tree_labels.shape[1]))\nprint(\"Output Dimension: {}\".format(tree_features.shape[1]))\nprint(\"Number of samples: {}\".format(tree_features.shape[0]))",
"_____no_output_____"
]
],
[
[
"To continue this tutorial, it is vital to understand the premise of our training data and what the task is. Therefore, please take your time to discuss them with your pod.\n\n<center><img src=\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W1D2_LinearDeepLearning/static/neural_net.png\" alt=\"neural net\" width=\"600\"/></center>\n\n<center> The neural network used for this tutorial </center>",
"_____no_output_____"
],
[
"## Interactive Demo 1: Training the deep LNN\n\nTraining a neural net on our data is straight forward. But before executing the next cell, remember the training loss curve from previous tutorial.",
"_____no_output_____"
]
],
[
[
"# @markdown #### Make sure you execute this cell to train the network and plot\n\nlr = 100.0 # learning rate\ngamma = 1e-12 # initialization scale\nn_epochs = 250 # number of epochs\ndim_input = 8 # input dimension = `label_tensor.size(1)`\ndim_hidden = 30 # hidden neurons\ndim_output = 10000 # output dimension = `feature_tensor.size(1)`\n\n# model instantiation\ndlnn_model = LNNet(dim_input, dim_hidden, dim_output)\n\n# weights re-initialization\ninitializer_(dlnn_model, gamma)\n\n# training\nlosses, *_ = train(dlnn_model,\n label_tensor,\n feature_tensor,\n n_epochs=n_epochs,\n lr=lr)\n\n# plotting\nplot_loss(losses)",
"_____no_output_____"
]
],
[
[
"**Think!**\n\nWhy haven't we seen these \"bumps\" in training before? And should we look for them in the future? What do these bumps mean?\n\nRecall from previous tutorial, that we are always interested in learning rate ($\\eta$) and initialization ($\\gamma$) that would give us the fastest but yet stable (reliable) convergence. Try finding the optimal $\\eta$ and $\\gamma$ using the following widgets. More specifically, try large $\\gamma$ and see if we can recover the bumps by tuning the $\\eta$.",
"_____no_output_____"
]
],
[
[
"# @markdown #### Make sure you execute this cell to enable the widget!\n\ndef loss_lr_init(lr, gamma):\n \"\"\"Trains and plots the loss evolution given lr and initialization\n Args:\n lr (float): learning rate\n gamma (float): initialization scale\n \"\"\"\n n_epochs = 250 # number of epochs\n dim_input = 8 # input dimension = `label_tensor.size(1)`\n dim_hidden = 30 # hidden neurons\n dim_output = 10000 # output dimension = `feature_tensor.size(1)`\n\n # model instantiation\n dlnn_model = LNNet(dim_input, dim_hidden, dim_output)\n\n # weights re-initialization\n initializer_(dlnn_model, gamma)\n\n losses, *_ = train(dlnn_model,\n label_tensor,\n feature_tensor,\n n_epochs=n_epochs,\n lr=lr)\n\n plot_loss(losses)\n\n_ = interact(loss_lr_init,\n lr = FloatSlider(min=1.0, max=200.0,\n step=1.0, value=100.0,\n continuous_update=False,\n readout_format='.1f',\n description='eta'),\n epochs = fixed(250),\n gamma = FloatLogSlider(min=-15, max=1,\n step=1, value=1e-12, base=10,\n continuous_update=False,\n description='gamma')\n )",
"_____no_output_____"
]
],
[
[
"---\n# Section 2: Singular Value Decomposition (SVD)\n\n*Time estimate: ~20 mins*",
"_____no_output_____"
]
],
[
[
"# @title Video 2: SVD\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1bw411R7DJ\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"18oNWRziskM\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n#add event to airtable\natform.add_event('Video 2: SVD')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"In this section, we intend to study the learning (training) dynamics we just saw. First, we should know that a linear neural network is performing sequential matrix multiplications, which can be simplified to:\n\n\\begin{align}\n\\mathbf{y} &= \\mathbf{W}_{L}~\\mathbf{W}_{L-1}~\\dots~\\mathbf{W}_{1} ~ \\mathbf{x} \\\\\n &= (\\prod_{i=1}^{L}{\\mathbf{W}_{i}}) ~ \\mathbf{x} \\\\\n &= \\mathbf{W}_{tot} ~ \\mathbf{x}\n\\end{align}\n\nwhere $L$ denotes the number of layers in our network.\n\n[Saxe et al. (2013)](https://arxiv.org/abs/1312.6120) showed that to analyze and to understanding the nonlinear learning dynamics of a deep LNN, we can use [Singular Value Decomposition (SVD)](https://en.wikipedia.org/wiki/Singular_value_decomposition) to decompose the $\\mathbf{W}_{tot}$ into orthogonal vectors, where orthogonality of the vectors would ensure their \"individuality (independence)\". This means we can break a deep wide LNN into multiple deep narrow LNN, so their activity is untangled from each other.\n\n<br/>\n\n__A Quick intro to SVD__\n\nAny real-valued matix $A$ (yes, ANY) can be decomposed (factorized) to 3 matrices:\n\n\\begin{equation}\n\\mathbf{A} = \\mathbf{U} \\mathbf{Σ} \\mathbf{V}^{\\top}\n\\end{equation}\n\nwhere $U$ is an orthogonal matrix, $\\Sigma$ is a diagonal matrix, and $V$ is again an orthogonal matrix. The diagonal elements of $\\Sigma$ are called **singular values**.\n\nThe main difference between SVD and EigenValue Decomposition (EVD), is that EVD requires $A$ to be squared and does not guarantee the eigenvectors to be orthogonal. \n\nWe strongly recommend the [Singular Value Decomposition (the SVD)](https://www.youtube.com/watch?v=mBcLRGuAFUk) by the amazing [Gilbert Strang](http://www-math.mit.edu/~gs/) if you would like to learn more.\n",
"_____no_output_____"
],
[
"## Coding Exercise 2: SVD (Optional)\n\nThe goal is to perform the SVD on $\\mathbf{W}_{tot}$ in every epoch, and record the singular values (modes) during the training.\n\nComplete the function `ex_net_svd`, by first calculating the $\\mathbf{W}_{tot} = \\prod_{i=1}^{L}{\\mathbf{W}_{i}}$ and finally performing SVD on the $\\mathbf{W}_{tot}$. Please use the PyTorch [`torch.svd`](https://pytorch.org/docs/stable/generated/torch.svd.html) instead of NumPy [`np.linalg.svd`](https://numpy.org/doc/stable/reference/generated/numpy.linalg.svd.html).",
"_____no_output_____"
]
],
[
[
"def ex_net_svd(model, in_dim):\n \"\"\"Performs a Singular Value Decomposition on a given model weights\n\n Args:\n model (torch.nn.Module): neural network model\n in_dim (int): the input dimension of the model\n\n Returns:\n U, Σ, V (Tensors): Orthogonal, diagonal, and orthogonal matrices\n \"\"\"\n W_tot = torch.eye(in_dim)\n for weight in model.parameters():\n #################################################\n ## Calculate the W_tot by multiplication of all weights\n # and then perform SVD on the W_tot using pytorch's `torch.svd`\n # Remember that weights need to be `.detach()` from the graph\n # Complete the function and remove or comment the line below\n raise NotImplementedError(\"Function `ex_net_svd`\")\n #################################################\n W_tot = ...\n U, Σ, V = ...\n return U, Σ, V\n\n#add event to airtable\natform.add_event('Coding Exercise 2: SVD')\n\n## Uncomment and run\n# test_net_svd_ex(SEED)",
"_____no_output_____"
]
],
[
[
"[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D2_LinearDeepLearning/solutions/W1D2_Tutorial3_Solution_51b2e553.py)\n\n",
"_____no_output_____"
]
],
[
[
"# @markdown #### Make sure you execute this cell to train the network and plot\n\nlr = 100.0 # learning rate\ngamma = 1e-12 # initialization scale\nn_epochs = 250 # number of epochs\ndim_input = 8 # input dimension = `label_tensor.size(1)`\ndim_hidden = 30 # hidden neurons\ndim_output = 10000 # output dimension = `feature_tensor.size(1)`\n\n# model instantiation\ndlnn_model = LNNet(dim_input, dim_hidden, dim_output)\n\n# weights re-initialization\ninitializer_(dlnn_model, gamma)\n\n# training\nlosses, modes, *_ = train(dlnn_model,\n label_tensor,\n feature_tensor,\n n_epochs=n_epochs,\n lr=lr)\n\nplot_loss_sv_twin(losses, modes)",
"_____no_output_____"
]
],
[
[
"**Think!**\n\nIn EigenValue decomposition, the amount of variance explained by eigenvectors is proportional to the corresponding eigenvalues. What about the SVD? We see that the gradient descent guides the network to first learn the features that carry more information (have higher singular value)!",
"_____no_output_____"
]
],
[
[
"# @title Video 3: SVD - Discussion\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1t54y1J7Tb\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"JEbRPPG2kUI\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n#add event to airtable\natform.add_event('Video 3: SVD - Discussion')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"---\n# Section 3: Representational Similarity Analysis (RSA)\n\n*Time estimate: ~20 mins*",
"_____no_output_____"
]
],
[
[
"# @title Video 4: RSA\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV19f4y157zD\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"YOs1yffysX8\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n#add event to airtable\natform.add_event('Video 4: RSA')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"The previous section ended with an interesting remark. SVD helped to break our deep \"wide\" linear neural net into 8 deep \"narrow\" linear neural nets.\n\nThe first narrow net (highest singular value) converges fastest, while the last four narrow nets, converge almost simultaneously and have the smallest singular values. Can it be that the narrow net with larger mode is learning the difference between \"living things\" and \"objects\", while another narrow net with smaller mode is learning the difference between Fish and Birds? how could we check this hypothesis?\n\nRepresentational Similarity Analysis (RSA) is an approach that could help us understand the internal representation of our network. The main idea is that the activity of hidden units (neurons) in the network must be similar when the network is presented with similar input. For our dataset (hierarchically structured data), we expect the activity of neurons in the hidden layer to be more similar for Tuna and Canary, and less similar for Tuna and Oak.\n\nFor similarity measure, we can use the good old dot (scalar) product, which is also called cosine similarity. For calculating the dot product between multiple vectors (which would be our case), we can simply use matrix multiplication. Therefore the Representational Similarity Matrix for multiple-input (batch) activity could be calculated as follow:\n\n\\begin{equation}\nRSM = \\mathbf{H} \\mathbf{H}^{\\top}\n\\end{equation}\n\nwhere $\\mathbf{H} = \\mathbf{X} \\mathbf{W_1}$ is the activity of hidden neurons for a given batch $\\mathbf{X}$.\n",
"_____no_output_____"
],
[
"## Coding Exercise 3: RSA (Optional)\n\nThe task is simple. We would need to measure the similarity between hidden layer activities $~\\mathbf{h} = \\mathbf{x} ~\\mathbf{W_1}$) for every input $\\mathbf{x}$.\n\nIf we perform RSA in every iteration, we could also see the evolution of representation learning.",
"_____no_output_____"
]
],
[
[
"def ex_net_rsm(h):\n \"\"\"Calculates the Representational Similarity Matrix\n\n Arg:\n h (torch.Tensor): activity of a hidden layer\n\n Returns:\n (torch.Tensor): Representational Similarity Matrix\n \"\"\"\n #################################################\n ## Calculate the Representational Similarity Matrix\n # Complete the function and remove or comment the line below\n raise NotImplementedError(\"Function `ex_net_rsm`\")\n #################################################\n rsm = ...\n return rsm\n\n#add event to airtable\natform.add_event(' Coding Exercise 3: RSA')\n\n## Uncomment and run\n# test_net_rsm_ex(SEED)",
"_____no_output_____"
]
],
[
[
"[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D2_LinearDeepLearning/solutions/W1D2_Tutorial3_Solution_394c7d85.py)\n\n",
"_____no_output_____"
],
[
"Now we can train the model while recording the losses, modes, and RSMs at every iteration. First, use the epoch slider to explore the evolution of RSM without changing default lr ($\\eta$) and initialization ($\\gamma$). Then, as we did before, set $\\eta$ and $\\gamma$ to larger values to see whether you can retrieve the sequential structured learning of representations.",
"_____no_output_____"
]
],
[
[
"#@markdown #### Make sure you execute this cell to enable widgets\n\ndef loss_svd_rsm_lr_gamma(lr, gamma, i_ep):\n \"\"\"\n Args:\n lr (float): learning rate\n gamma (float): initialization scale\n i_ep (int): which epoch to show\n\n \"\"\"\n n_epochs = 250 # number of epochs\n dim_input = 8 # input dimension = `label_tensor.size(1)`\n dim_hidden = 30 # hidden neurons\n dim_output = 10000 # output dimension = `feature_tensor.size(1)`\n\n # model instantiation\n dlnn_model = LNNet(dim_input, dim_hidden, dim_output)\n\n # weights re-initialization\n initializer_(dlnn_model, gamma)\n\n # training\n losses, modes, rsms, _ = train(dlnn_model,\n label_tensor,\n feature_tensor,\n n_epochs=n_epochs,\n lr=lr)\n plot_loss_sv_rsm(losses, modes, rsms, i_ep)\n\ni_ep_slider = IntSlider(min=10, max=241, step=1, value=61,\n continuous_update=False,\n description='Epoch',\n layout=Layout(width='630px'))\n\nlr_slider = FloatSlider(min=20.0, max=200.0, step=1.0, value=100.0,\n continuous_update=False,\n readout_format='.1f',\n description='eta')\n\ngamma_slider = FloatLogSlider(min=-15, max=1, step=1,\n value=1e-12, base=10,\n continuous_update=False,\n description='gamma')\n\nwidgets_ui = VBox([lr_slider, gamma_slider, i_ep_slider])\n\nwidgets_out = interactive_output(loss_svd_rsm_lr_gamma,\n {'lr': lr_slider,\n 'gamma': gamma_slider,\n 'i_ep': i_ep_slider})\n\ndisplay(widgets_ui, widgets_out)",
"_____no_output_____"
]
],
[
[
"Let's take a moment to analyze this more. A deep neural net is learning the representations, rather than a naive mapping (look-up table). This is thought to be the reason for deep neural nets supreme generalization and transfer learning ability. Unsurprisingly, neural nets with no hidden layer are incapable of representation learning, even with extremely small initialization.",
"_____no_output_____"
]
],
[
[
"# @title Video 5: RSA - Discussion\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV18y4y1j7Xr\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"vprldATyq1o\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n#add event to airtable\natform.add_event('Video 5: RSA - Discussion')\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"---\n# Section 4: Illusory Correlations\n\n*Time estimate: ~20-30 mins*",
"_____no_output_____"
]
],
[
[
"# @title Video 6: Illusory Correlations\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1vv411E7Sq\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"RxsAvyIoqEo\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n#add event to airtable\natform.add_event('Video 6: Illusory Correlations')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"Let's recall the training loss curves. There was often a long plateau (where the weights are stuck at a saddle point), followed by a sudden drop. For very deep complex neural nets, such plateaus can take hours of training, and we are often tempted to stop the training, because we believe it is \"as good as it gets\"! Another side effect of \"immature interruption\" of training is the network finding (learning) illusory correlations.\n\nTo better understand this, let's do the next demonstration and exercise.",
"_____no_output_____"
],
[
"## Demonstration: Illusory Correlations\n\nOur original dataset has 4 animals: Canary, Robin, Goldfish, and Tuna. These animals all have bones. Therefore if we include a \"has bone\" feature, the network would learn it at the second level (i.e. second bump, second mode convergence), when it learns the animal-plants distinction.\n\nWhat if the dataset has Shark instead of Goldfish. Sharks don't have bones (their skeletons are made of cartilaginous, which is much lighter than true bone and more flexible). Then we will have a feature which is *True* (i.e. +1) for Tuna, Robin, and Canary, but *False* (i.e. -1) for all the plants and the shark! Let's see what the network does.\n\nFirst, we add the new feature to the targets. We then start training our LNN and in every epoch, record the network prediction for \"sharks having bones\".\n\n<center><img src=\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W1D2_LinearDeepLearning/static/shark_tree.png\" alt=\"Simple nn graph\" width=\"600\"/></center>",
"_____no_output_____"
]
],
[
[
"# sampling new data from the tree\ntree_labels, tree_features = generate_hsd()\n\n# replacing Goldfish with Shark\nitem_names = ['Shark', 'Tuna', 'Robin', 'Canary',\n 'Rose', 'Daisy', 'Pine', 'Oak']\n\n# index of label to record\nillusion_idx = 0 # Shark is the first element\n\n# the new feature (has bones) vector\nnew_feature = [-1, 1, 1, 1, -1, -1, -1, -1]\nits_label = 'has_bones'\n\n# adding feature has_bones to the feature array\ntree_features = add_feature(tree_features, new_feature)\n\n# plotting\nplot_tree_data(item_names, tree_features, its_label)",
"_____no_output_____"
]
],
[
[
"You can see the new feature shown in the last column of the plot above.\n\nNow we can train the network on the new data, and record the network prediction (output) for Shark (indexed 0) label and \"has bone\" feature (last feature, indexed -1), during the training.\n\nHere is the snippet from the training loop that keeps track of network prediction for `illusory_i`th label and last (`-1`) feature:\n\n```python\npred_ij = predictions.detach()[illusory_i, -1]\n```",
"_____no_output_____"
]
],
[
[
"#@markdown #### Make sure you execute this cell to train the network and plot\n\n# convert (cast) data from np.ndarray to torch.Tensor\nlabel_tensor = torch.tensor(tree_labels).float()\nfeature_tensor = torch.tensor(tree_features).float()\n\nlr = 100.0 # learning rate\ngamma = 1e-12 # initialization scale\nn_epochs = 250 # number of epochs\ndim_input = 8 # input dimension = `label_tensor.size(1)`\ndim_hidden = 30 # hidden neurons\ndim_output = feature_tensor.size(1)\n\n# model instantiation\ndlnn_model = LNNet(dim_input, dim_hidden, dim_output)\n\n# weights re-initialization\ninitializer_(dlnn_model, gamma)\n\n# training\n_, modes, _, ill_predictions = train(dlnn_model,\n label_tensor,\n feature_tensor,\n n_epochs=n_epochs,\n lr=lr,\n illusory_i=illusion_idx)\n\n# a label for the plot\nill_label = f\"Prediction for {item_names[illusion_idx]} {its_label}\"\n\n# plotting\nplot_ills_sv_twin(ill_predictions, modes, ill_label)",
"_____no_output_____"
]
],
[
[
"It seems that the network starts by learning an \"illusory correlation\" that sharks have bones, and in later epochs, as it learns deeper representations, it can see (learn) beyond the illusory correlation. This is important to remember that we never presented the network with any data saying that sharks have bones.",
"_____no_output_____"
],
[
"## Exercise 4: Illusory Correlations\n\nThis exercise is just for you to explore the idea of illusory correlations. Think of medical, natural, or possibly social illusory correlations which can test the learning power of deep linear neural nets.\n\n**important notes**: the generated data is independent of tree labels, therefore the names are just for convenience.\n\nHere is our example for **Non-human Living things do not speak**. The lines marked by `{edit}` are for you to change in your example.\n",
"_____no_output_____"
]
],
[
[
"# sampling new data from the tree\ntree_labels, tree_features = generate_hsd()\n\n# {edit} replacing Canary with Parrot\nitem_names = ['Goldfish', 'Tuna', 'Robin', 'Parrot',\n 'Rose', 'Daisy', 'Pine', 'Oak']\n\n# {edit} index of label to record\nillusion_idx = 3 # Parrot is the fourth element\n\n# {edit} the new feature (cannot speak) vector\nnew_feature = [1, 1, 1, -1, 1, 1, 1, 1]\nits_label = 'cannot_speak'\n\n# adding feature has_bones to the feature array\ntree_features = add_feature(tree_features, new_feature)\n\n# plotting\nplot_tree_data(item_names, tree_features, its_label)",
"_____no_output_____"
],
[
"# @markdown #### Make sure you execute this cell to train the network and plot\n\n# convert (cast) data from np.ndarray to torch.Tensor\nlabel_tensor = torch.tensor(tree_labels).float()\nfeature_tensor = torch.tensor(tree_features).float()\n\nlr = 100.0 # learning rate\ngamma = 1e-12 # initialization scale\nn_epochs = 250 # number of epochs\ndim_input = 8 # input dimension = `label_tensor.size(1)`\ndim_hidden = 30 # hidden neurons\ndim_output = feature_tensor.size(1)\n\n# model instantiation\ndlnn_model = LNNet(dim_input, dim_hidden, dim_output)\n\n# weights re-initialization\ninitializer_(dlnn_model, gamma)\n\n# training\n_, modes, _, ill_predictions = train(dlnn_model,\n label_tensor,\n feature_tensor,\n n_epochs=n_epochs,\n lr=lr,\n illusory_i=illusion_idx)\n\n# a label for the plot\nill_label = f\"Prediction for {item_names[illusion_idx]} {its_label}\"\n\n# plotting\nplot_ills_sv_twin(ill_predictions, modes, ill_label)",
"_____no_output_____"
],
[
"# @title Video 7: Illusory Correlations - Discussion\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1vv411E7rg\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"6VLHKQjQJmI\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n#add event to airtable\natform.add_event('Video 7: Illusory Correlations')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"---\n# Summary\n\nThe second day of the course has ended. So, in the third tutorial of the linear deep learning day we have learned more advanced topics. In the beginning we implemented a deep linear neural network and then we studied its learning dynamics using the linear algebra tool called singular value decomposition. Then, we learned about the representational similarity analysis and the illusory correlation.",
"_____no_output_____"
]
],
[
[
"# @title Video 8: Outro\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1AL411n7ns\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"N2szOIsKyXE\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n#add event to airtable\natform.add_event('Video 8: Outro')\n\ndisplay(out)",
"_____no_output_____"
],
[
"# @title Airtable Submission Link\nfrom IPython import display as IPydisplay\nIPydisplay.HTML(\n f\"\"\"\n <div>\n <a href= \"{atform.url()}\" target=\"_blank\">\n <img src=\"https://github.com/NeuromatchAcademy/course-content-dl/blob/main/tutorials/static/SurveyButton.png?raw=1\"\n alt=\"button link end of day Survey\" style=\"width:410px\"></a>\n </div>\"\"\" )",
"_____no_output_____"
]
],
[
[
"---\n# Bonus\n\n*Time estimate: ~20-30 mins*",
"_____no_output_____"
]
],
[
[
"# @title Video 9: Linear Regression\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Pf4y1L71L\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"uULOAbhYaaE\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"## Section 5.1: Linear Regression\n\nGenerally, *regression* refers to a set of methods for modeling the mapping (relationship) between one (or more) independent variable(s) (i.e., features) and one (or more) dependent variable(s) (i.e., labels). For example, if we want to examine the relative impacts of calendar date, GPS coordinates, and time of the say (the independent variables) on air temperature (the dependent variable). On the other hand, regression can be used for predictive analysis. Thus the independent variables are also called predictors. When the model contains more than one predictor, then the method is called *multiple regression*, and if it contains more than one dependent variable called *multivariate regression*. Regression problems pop up whenever we want to predict a numerical (usually continuous) value.\n\nThe independent variables are collected in vector $\\mathbf{x} \\in \\mathbb{R}^M$, where $M$ denotes the number of independent variables, while the dependent variables are collected in vector $\\mathbf{y} \\in \\mathbb{R}^N$, where $N$ denotes the number of dependent variables. And the mapping between them is represented by the weight matrix $\\mathbf{W} \\in \\mathbb{R}^{N \\times M}$ and a bias vector $\\mathbf{b} \\in \\mathbb{R}^{N}$ (generalizing to affine mappings).\n\nThe multivariate regression model can be written as:\n\n\\begin{equation}\n\\mathbf{y} = \\mathbf{W} ~ \\mathbf{x} + \\mathbf{b}\n\\end{equation}\n\nor it can be written in matrix format as:\n\n\\begin{equation}\n\\begin{bmatrix} y_{1} \\\\ y_{2} \\\\ \\vdots \\\\ y_{N} \\\\ \\end{bmatrix} = \\begin{bmatrix} w_{1,1} & w_{1,2} & \\dots & w_{1,M} \\\\ w_{2,1} & w_{2,2} & \\dots & w_{2,M} \\\\ \\vdots & \\ddots & \\ddots & \\vdots \\\\ w_{N,1} & w_{N,2} & \\dots & w_{N,M} \\end{bmatrix} \\begin{bmatrix} x_{1} \\\\ x_{2} \\\\ \\vdots \\\\ x_{M} \\\\ \\end{bmatrix} + \\begin{bmatrix} b_{1} \\\\ b_{2} \\\\ \\vdots \\\\b_{N} \\\\ \\end{bmatrix}\n\\end{equation}\n",
"_____no_output_____"
],
[
"## Section 5.2: Vectorized regression\n\nLinear regression can be simply extended to multi-samples ($D$) input-output mapping, which we can collect in a matrix $\\mathbf{X} \\in \\mathbb{R}^{M \\times D}$, sometimes called the design matrix. The sample dimension also shows up in the output matrix $\\mathbf{Y} \\in \\mathbb{R}^{N \\times D}$. Thus, linear regression takes the following form:\n\n\\begin{equation}\n\\mathbf{Y} = \\mathbf{W} ~ \\mathbf{X} + \\mathbf{b}\n\\end{equation}\n\nwhere matrix $\\mathbf{W} \\in \\mathbb{R}^{N \\times M}$ and the vector $\\mathbf{b} \\in \\mathbb{R}^{N}$ (broadcasted over sample dimension) are the desired parameters to find.",
"_____no_output_____"
],
[
"## Section 5.3: Analytical Linear Regression",
"_____no_output_____"
],
[
"Linear regression is a relatively simple optimization problem. Unlike most other models that we will see in this course, linear regression for mean squared loss can be solved analytically.\n\nFor $D$ samples (batch size), $\\mathbf{X} \\in \\mathbb{R}^{M \\times D}$, and $\\mathbf{Y} \\in \\mathbb{R}^{N \\times D}$, the goal of linear regression is to find $\\mathbf{W} \\in \\mathbb{R}^{N \\times M}$ such that:\n\n\\begin{equation}\n\\mathbf{Y} = \\mathbf{W} ~ \\mathbf{X}\n\\end{equation}\n\nGiven the Squared Error loss function, we have:\n\n\\begin{equation}\nLoss(\\mathbf{W}) = ||\\mathbf{Y} - \\mathbf{W} ~ \\mathbf{X}||^2\n\\end{equation}\n\nSo, using matrix notation, the optimization problem is given by:\n\n\\begin{align}\n\\mathbf{W^{*}} &= \\underset{\\mathbf{W}}{\\mathrm{argmin}} \\left( Loss (\\mathbf{W}) \\right) \\\\\n &= \\underset{\\mathbf{W}}{\\mathrm{argmin}} \\left( ||\\mathbf{Y} - \\mathbf{W} ~ \\mathbf{X}||^2 \\right) \\\\\n&= \\underset{\\mathbf{W}}{\\mathrm{argmin}} \\left( \\left( \\mathbf{Y} - \\mathbf{W} ~ \\mathbf{X}\\right)^{\\top} \\left( \\mathbf{Y} - \\mathbf{W} ~ \\mathbf{X}\\right) \\right)\n\\end{align}\n\nTo solve the minimization problem, we can simply set the derivative of the loss with respect to $\\mathbf{W}$ to zero.\n\n\\begin{equation}\n\\dfrac{\\partial Loss}{\\partial \\mathbf{W}} = 0\n\\end{equation}\n\nAssuming that $\\mathbf{X}\\mathbf{X}^{\\top}$ is full-rank, and thus it is invertible we can write:\n\n\\begin{equation}\n\\mathbf{W}^{\\mathbf{*}} = \\mathbf{Y} \\mathbf{X}^{\\top} \\left( \\mathbf{X} \\mathbf{X}^{\\top} \\right) ^{-1}\n\\end{equation}\n\n",
"_____no_output_____"
],
[
"### Coding Exercise 5.3.1: Analytical solution to LR\n\nComplete the function `linear_regression` for finding the analytical solution to linear regression.\n",
"_____no_output_____"
]
],
[
[
"def linear_regression(X, Y):\n \"\"\"Analytical Linear regression\n\n Args:\n X (np.ndarray): design matrix\n Y (np.ndarray): target ouputs\n\n return:\n np.ndarray: estimated weights (mapping)\n \"\"\"\n assert isinstance(X, np.ndarray)\n assert isinstance(Y, np.ndarray)\n M, Dx = X.shape\n N, Dy = Y.shape\n assert Dx == Dy\n #################################################\n ## Complete the linear_regression_exercise function\n # Complete the function and remove or comment the line below\n raise NotImplementedError(\"Linear Regression `linear_regression`\")\n #################################################\n W = ...\n\n return W\n\n\nW_true = np.random.randint(low=0, high=10, size=(3, 3)).astype(float)\n\nX_train = np.random.rand(3, 37) # 37 samples\nnoise = np.random.normal(scale=0.01, size=(3, 37))\nY_train = W_true @ X_train + noise\n\n## Uncomment and run\n# W_estimate = linear_regression(X_train, Y_train)\n# print(f\"True weights:\\n {W_true}\")\n# print(f\"\\nEstimated weights:\\n {np.round(W_estimate, 1)}\")",
"_____no_output_____"
]
],
[
[
"[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D2_LinearDeepLearning/solutions/W1D2_Tutorial3_Solution_55ea556e.py)\n\n",
"_____no_output_____"
],
[
"## Demonstration: Linear Regression vs. DLNN\n\nA linear neural network with NO hidden layer is very similar to linear regression in its core. We also know that no matter how many hidden layers a linear network has, it can be compressed to linear regression (no hidden layers).\n\nIn this demonstration, we use the hierarchically structured data to:\n\n* analytically find the mapping between features and labels\n* train a zero-depth LNN to find the mapping \n* compare them to the $W_{tot}$ from the already trained deep LNN",
"_____no_output_____"
]
],
[
[
"# sampling new data from the tree\ntree_labels, tree_features = generate_hsd()\n\n# convert (cast) data from np.ndarray to torch.Tensor\nlabel_tensor = torch.tensor(tree_labels).float()\nfeature_tensor = torch.tensor(tree_features).float()",
"_____no_output_____"
],
[
"# calculating the W_tot for deep network (already trained model)\n\nlr = 100.0 # learning rate\ngamma = 1e-12 # initialization scale\nn_epochs = 250 # number of epochs\ndim_input = 8 # input dimension = `label_tensor.size(1)`\ndim_hidden = 30 # hidden neurons\ndim_output = 10000 # output dimension = `feature_tensor.size(1)`\n\n# model instantiation\ndlnn_model = LNNet(dim_input, dim_hidden, dim_output)\n\n# weights re-initialization\ninitializer_(dlnn_model, gamma)\n\n# training\nlosses, modes, rsms, ills = train(dlnn_model,\n label_tensor,\n feature_tensor,\n n_epochs=n_epochs,\n lr=lr)\n\ndeep_W_tot = torch.eye(dim_input)\nfor weight in dlnn_model.parameters():\n deep_W_tot = weight @ deep_W_tot\ndeep_W_tot = deep_W_tot.detach().numpy()",
"_____no_output_____"
],
[
"# analytically estimation of weights\n# our data is batch first dimension, so we need to transpose our data\nanalytical_weights = linear_regression(tree_labels.T, tree_features.T)",
"_____no_output_____"
],
[
"class LRNet(nn.Module):\n \"\"\"A Linear Neural Net with ZERO hidden layer (LR net)\n \"\"\"\n\n def __init__(self, in_dim, out_dim):\n \"\"\"\n Args:\n in_dim (int): input dimension\n hid_dim (int): hidden dimension\n \"\"\"\n super().__init__()\n self.in_out = nn.Linear(in_dim, out_dim, bias=False)\n\n def forward(self, x):\n \"\"\"\n Args:\n x (torch.Tensor): input tensor\n \"\"\"\n out = self.in_out(x) # output (prediction)\n return out",
"_____no_output_____"
],
[
"lr = 1000.0 # learning rate\ngamma = 1e-12 # initialization scale\nn_epochs = 250 # number of epochs\ndim_input = 8 # input dimension = `label_tensor.size(1)`\ndim_output = 10000 # output dimension = `feature_tensor.size(1)`\n\n# model instantiation\nLR_model = LRNet(dim_input, dim_output)\noptimizer = optim.SGD(LR_model.parameters(), lr=lr)\ncriterion = nn.MSELoss()\n\nlosses = np.zeros(n_epochs) # loss records\nfor i in range(n_epochs): # training loop\n optimizer.zero_grad()\n predictions = LR_model(label_tensor)\n loss = criterion(predictions, feature_tensor)\n loss.backward()\n optimizer.step()\n losses[i] = loss.item()\n\n# trained weights from zero_depth_model\nLR_model_weights = next(iter(LR_model.parameters())).detach().numpy()\n\nplot_loss(losses, \"Training loss for zero depth LNN\", c=\"r\")",
"_____no_output_____"
],
[
"print(\"The final weights from all methods are approximately equal?! \"\n\"{}!\".format(\n (np.allclose(analytical_weights, LR_model_weights, atol=1e-02) and \\\n np.allclose(analytical_weights, deep_W_tot, atol=1e-02))\n )\n)",
"_____no_output_____"
]
],
[
[
"As you may have guessed, they all arrive at the same results but through very different paths.",
"_____no_output_____"
]
],
[
[
"# @title Video 10: Linear Regression - Discussion\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV18v411E7Wg\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"gG15_J0i05Y\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
ecccd1401e0c9500629dc19cdf41af8b75d44e07 | 13,167 | ipynb | Jupyter Notebook | notebooks/large_coarse_quantizer.ipynb | DmitryKey/big-ann-benchmarks | 03bd0b2df932b579f4838baaee527f090c96f849 | [
"MIT"
] | 75 | 2021-07-25T07:50:11.000Z | 2022-03-25T04:18:54.000Z | notebooks/large_coarse_quantizer.ipynb | DmitryKey/big-ann-benchmarks | 03bd0b2df932b579f4838baaee527f090c96f849 | [
"MIT"
] | 54 | 2021-07-26T02:23:32.000Z | 2022-02-15T05:44:23.000Z | notebooks/large_coarse_quantizer.ipynb | DmitryKey/big-ann-benchmarks | 03bd0b2df932b579f4838baaee527f090c96f849 | [
"MIT"
] | 21 | 2021-07-27T08:44:22.000Z | 2022-03-18T07:56:23.000Z | 22.431005 | 206 | 0.516746 | [
[
[
"It is useful to cluster the 1B datasets to around 262k - 1M clusters for IVF indexing with Faiss.\nHowever, it is not feasible to do the clustering within the allocated time for indexing. \n\nTherefore, here we evaluate other options to break down the clustering cost, while getting the same number of clusters.\nThe model that we use is: Deep1M (1M database vectors), 4096 clusters (which conveniently breaks down to 2^6 * 2^6)\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport faiss\nfrom faiss.contrib import datasets",
"_____no_output_____"
],
[
"ds = datasets.DatasetDeep1B(10**6)",
"_____no_output_____"
],
[
"xt = ds.get_train(10**5)\nd = ds.d\nxb = ds.get_database()\nxq = ds.get_queries()\ngt = ds.get_groundtruth()\n",
"_____no_output_____"
],
[
"sqrt_nlist = 64\nnlist = sqrt_nlist**2",
"_____no_output_____"
]
],
[
[
"# Flat quantizer",
"_____no_output_____"
],
[
"Flat quantizer is what we would like to apprach, but it probably too costly. \nWe include it here as a topline.\nThe measure we use is recall of nearest neighbor vs. number of computed distances.",
"_____no_output_____"
]
],
[
[
"quantizer = faiss.IndexFlatL2(d)\nindex = faiss.IndexIVFFlat(quantizer, d, nlist)",
"_____no_output_____"
],
[
"index.train(xt)\nindex.add(xb)\nindex.invlists.imbalance_factor()",
"_____no_output_____"
],
[
"stats = faiss.cvar.indexIVF_stats\nfor nprobe in 1, 4, 16, 64: \n index.nprobe = nprobe \n stats.reset()\n D, I = index.search(xq, 100)\n rank = 1\n recall = (I[:, :rank] == gt[:, :1]).sum() / len(xq)\n print(f\"nprobe={nprobe} 1-recall @ {rank}: {recall} dis/q={stats.ndis/len(xq):.2f}\")",
"nprobe=1 1-recall @ 1: 0.3745 dis/q=349.15\nnprobe=4 1-recall @ 1: 0.6849 dis/q=1344.67\nnprobe=16 1-recall @ 1: 0.9004 dis/q=5040.35\nnprobe=64 1-recall @ 1: 0.9793 dis/q=18331.49\n"
]
],
[
[
"# IMI quantizer",
"_____no_output_____"
],
[
"The IMI quantizer is a cheap way of breaking down the dataset into buckets. It is a PQ2x6 and each PQ code ends in a separate bucket. ",
"_____no_output_____"
]
],
[
[
"quantizer = faiss.MultiIndexQuantizer(d, 2, int(np.log2(sqrt_nlist)))",
"_____no_output_____"
],
[
"index = faiss.IndexIVFFlat(quantizer, d, nlist)\nindex.quantizer_trains_alone = 1",
"_____no_output_____"
],
[
"index.train(xt)\nindex.add(xb)\nindex.invlists.imbalance_factor()\n",
"_____no_output_____"
],
[
"stats = faiss.cvar.indexIVF_stats\n\nfor nprobe in 1, 4, 16, 64: \n index.nprobe = nprobe \n stats.reset()\n\n D, I = index.search(xq, 100)\n rank = 1\n recall = (I[:, :rank] == gt[:, :1]).sum() / len(xq)\n print(f\"nprobe={nprobe} 1-recall @ {rank}: {recall} dis/q={stats.ndis/len(xq):.2f}\")",
"nprobe=1 1-recall @ 1: 0.437 dis/q=3972.32\nnprobe=4 1-recall @ 1: 0.6948 dis/q=9210.20\nnprobe=16 1-recall @ 1: 0.8656 dis/q=19246.74\nnprobe=64 1-recall @ 1: 0.9613 dis/q=41114.89\n"
]
],
[
[
"So way less efficient than the flat quantizer, due to imbalanced inverted lists. TBH, the IMI quantizer usually sets a cap on the number of distances rather than fixing the number of visited buckets. ",
"_____no_output_____"
],
[
"# Residual quantizer",
"_____no_output_____"
],
[
"This is a 2-level additive quantizer where the first level is trained first, then the second. Since it is an additive quantizer, the top-k centroids can be retrieved efficiently with lookup tables. ",
"_____no_output_____"
]
],
[
[
"quantizer = faiss.ResidualCoarseQuantizer(d, 2, int(np.log2(sqrt_nlist)))",
"_____no_output_____"
],
[
"index = faiss.IndexIVFFlat(quantizer, d, nlist)\nindex.quantizer_trains_alone = 1",
"_____no_output_____"
],
[
"index.train(xt)",
"_____no_output_____"
],
[
"quantizer.set_beam_factor(-1)",
"_____no_output_____"
],
[
"index.add(xb)\nindex.invlists.imbalance_factor()",
"_____no_output_____"
],
[
"stats = faiss.cvar.indexIVF_stats\n\nfor nprobe in 1, 4, 16, 64: \n index.nprobe = nprobe \n stats.reset()\n\n D, I = index.search(xq, 100)\n rank = 1\n recall = (I[:, :rank] == gt[:, :1]).sum() / len(xq)\n print(f\"nprobe={nprobe} 1-recall @ {rank}: {recall} dis/q={stats.ndis/len(xq):.2f}\")",
"nprobe=1 1-recall @ 1: 0.3079 dis/q=878.77\nnprobe=4 1-recall @ 1: 0.6091 dis/q=3017.90\nnprobe=16 1-recall @ 1: 0.8608 dis/q=9996.18\nnprobe=64 1-recall @ 1: 0.9685 dis/q=31318.18\n"
]
],
[
[
"Unfortunately still not very good. ",
"_____no_output_____"
],
[
"# 2-level tree quantizer",
"_____no_output_____"
],
[
"This is a suggestion by Harsha: just cluster to 64 centroids at the first level and train separate clusterings within each bucket.",
"_____no_output_____"
]
],
[
[
"# 1st level quantizer ",
"_____no_output_____"
],
[
"km = faiss.Kmeans(d, sqrt_nlist)",
"_____no_output_____"
],
[
"km.train(xt)",
"_____no_output_____"
],
[
"centroids1 = km.centroids",
"_____no_output_____"
],
[
"xt2 = ds.get_train(500_000)\n\n_, assign1 = km.assign(xt2)\nbc = np.bincount(assign1)\no = assign1.argsort()",
"_____no_output_____"
],
[
"i0 = 0\nc2 = []\nfor c1 in range(sqrt_nlist): \n print(c1, end=\"\\r\", flush=True)\n i1 = i0 + bc[c1]\n subset = o[i0:i1]\n assert np.all(assign1[subset] == c1)\n km = faiss.Kmeans(d, sqrt_nlist)\n xtsub = xt2[subset]\n km.train(xtsub)\n c2.append(km.centroids)\n i0 = i1",
"63\r"
]
],
[
[
"Then we just stack the centroids together and forget about the first level clustering. \nIn reality with 262k-1M clusters, we'll train a HNSW or NSG index on top. ",
"_____no_output_____"
]
],
[
[
"centroids12 = np.vstack(c2)",
"_____no_output_____"
],
[
"quantizer = faiss.IndexFlatL2(d)\nquantizer.add(centroids12)\nindex = faiss.IndexIVFFlat(quantizer, d, nlist)",
"_____no_output_____"
],
[
"index.add(xb)\nindex.invlists.imbalance_factor()",
"_____no_output_____"
],
[
"stats = faiss.cvar.indexIVF_stats\nfor nprobe in 1, 4, 16, 64: \n index.nprobe = nprobe \n stats.reset()\n D, I = index.search(xq, 100)\n rank = 1\n recall = (I[:, :rank] == gt[:, :1]).sum() / len(xq)\n print(f\"nprobe={nprobe} 1-recall @ {rank}: {recall} dis/q={stats.ndis/len(xq):.2f}\")",
"nprobe=1 1-recall @ 1: 0.3774 dis/q=291.20\nnprobe=4 1-recall @ 1: 0.6847 dis/q=1153.03\nnprobe=16 1-recall @ 1: 0.8995 dis/q=4459.66\nnprobe=64 1-recall @ 1: 0.9825 dis/q=16942.70\n"
]
],
[
[
"Turns out this is very good: same level of accuracy as the flat topline!",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
ecccd86879b4012ff6b2700c29f0ca3d47442c16 | 213,271 | ipynb | Jupyter Notebook | FigS2F_cas-1234.ipynb | andim/crispr_repertoires | 6a998587550841451f8be8b58a40515c4c60d684 | [
"MIT"
] | null | null | null | FigS2F_cas-1234.ipynb | andim/crispr_repertoires | 6a998587550841451f8be8b58a40515c4c60d684 | [
"MIT"
] | null | null | null | FigS2F_cas-1234.ipynb | andim/crispr_repertoires | 6a998587550841451f8be8b58a40515c4c60d684 | [
"MIT"
] | null | null | null | 1,191.458101 | 209,650 | 0.957688 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
ecccde41ebff4d80a4d0912a1bf375386ff13328 | 7,938 | ipynb | Jupyter Notebook | assignments/midterm/AlgorithmsEx03.ipynb | nproctor/phys202-2015-work | acb4c686f3394aa339e8916447cf508a804edb2a | [
"MIT"
] | null | null | null | assignments/midterm/AlgorithmsEx03.ipynb | nproctor/phys202-2015-work | acb4c686f3394aa339e8916447cf508a804edb2a | [
"MIT"
] | null | null | null | assignments/midterm/AlgorithmsEx03.ipynb | nproctor/phys202-2015-work | acb4c686f3394aa339e8916447cf508a804edb2a | [
"MIT"
] | null | null | null | 23.909639 | 327 | 0.536659 | [
[
[
"# Algorithms Exercise 3",
"_____no_output_____"
],
[
"## Imports",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nfrom matplotlib import pyplot as plt\nimport numpy as np",
"_____no_output_____"
],
[
"from IPython.html.widgets import interact",
"_____no_output_____"
]
],
[
[
"## Character counting and entropy",
"_____no_output_____"
],
[
"Write a function `char_probs` that takes a string and computes the probabilities of each character in the string:\n\n* First do a character count and store the result in a dictionary.\n* Then divide each character counts by the total number of character to compute the normalized probabilties.\n* Return the dictionary of characters (keys) and probabilities (values).",
"_____no_output_____"
]
],
[
[
"def char_probs(s):\n \"\"\"Find the probabilities of the unique characters in the string s.\n \n Parameters\n ----------\n s : str\n A string of characters.\n \n Returns\n -------\n probs : dict\n A dictionary whose keys are the unique characters in s and whose values\n are the probabilities of those characters.\n \"\"\"\n x = []\n for char in s:\n x.append(char)\n r = {x[i]: x.count(x[i])/len(x) for i in range(len(x))}\n return(r)\n ",
"_____no_output_____"
],
[
"char_probs(\"abbc\")",
"_____no_output_____"
],
[
"test1 = char_probs('aaaa')\nassert np.allclose(test1['a'], 1.0)\ntest2 = char_probs('aabb')\nassert np.allclose(test2['a'], 0.5)\nassert np.allclose(test2['b'], 0.5)\ntest3 = char_probs('abcd')\nassert np.allclose(test3['a'], 0.25)\nassert np.allclose(test3['b'], 0.25)\nassert np.allclose(test3['c'], 0.25)\nassert np.allclose(test3['d'], 0.25)",
"_____no_output_____"
]
],
[
[
"The [entropy](http://en.wikipedia.org/wiki/Entropy_%28information_theory%29) is a quantiative measure of the disorder of a probability distribution. It is used extensively in Physics, Statistics, Machine Learning, Computer Science and Information Science. Given a set of probabilities $P_i$, the entropy is defined as:\n\n$$H = - \\Sigma_i P_i \\log_2(P_i)$$ \n\nIn this expression $\\log_2$ is the base 2 log (`np.log2`), which is commonly used in information science. In Physics the natural log is often used in the definition of entropy.\n\nWrite a funtion `entropy` that computes the entropy of a probability distribution. The probability distribution will be passed as a Python `dict`: the values in the `dict` will be the probabilities.\n\nTo compute the entropy, you should:\n\n* First convert the values (probabilities) of the `dict` to a Numpy array of probabilities.\n* Then use other Numpy functions (`np.log2`, etc.) to compute the entropy.\n* Don't use any `for` or `while` loops in your code.",
"_____no_output_____"
]
],
[
[
"def entropy(d):\n \"\"\"Compute the entropy of a dict d whose values are probabilities.\"\"\"\n a = np.array(list(d.values()))\n entropy = -(sum(a))*np.log2(a)\n return(entropy)",
"_____no_output_____"
],
[
"entropy({'a': 0.25, 'b': 0.5, 'c': 0.25})",
"_____no_output_____"
],
[
"assert np.allclose(entropy({'a': 0.5, 'b': 0.5}), 1.0)\nassert np.allclose(entropy({'a': 1.0}), 0.0)",
"_____no_output_____"
]
],
[
[
"Use IPython's `interact` function to create a user interface that allows you to type a string into a text box and see the entropy of the character probabilities of the string.",
"_____no_output_____"
]
],
[
[
"from IPython.display import display",
"_____no_output_____"
],
[
"def new_func(n):\n \"\"\"Made so interact can take a string and output entropy of char_prob(\"string\")\"\"\"\n a = char_probs(n)\n print(entropy(a))",
"_____no_output_____"
],
[
"interact(new_func, n = \"aaa\");\n",
"[ 1.5849625 1.5849625 1.5849625]\n"
],
[
"assert True # use this for grading the pi digits histogram",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
ecccdf86d68e61521a4fa3d3fda59f978119b5ca | 3,073 | ipynb | Jupyter Notebook | quantum-coin-flip.ipynb | johannesridho/quantum-coin-flip | 52c366ab7b634a5ca34a243aba95ddcd6d70c7d7 | [
"MIT"
] | null | null | null | quantum-coin-flip.ipynb | johannesridho/quantum-coin-flip | 52c366ab7b634a5ca34a243aba95ddcd6d70c7d7 | [
"MIT"
] | null | null | null | quantum-coin-flip.ipynb | johannesridho/quantum-coin-flip | 52c366ab7b634a5ca34a243aba95ddcd6d70c7d7 | [
"MIT"
] | null | null | null | 25.188525 | 124 | 0.571754 | [
[
[
"%matplotlib inline\n# Importing standard Qiskit libraries and configuring account\nfrom qiskit import QuantumCircuit, execute, Aer, IBMQ\nfrom qiskit.compiler import transpile, assemble\nfrom qiskit.tools.jupyter import *\nfrom qiskit.visualization import *\n# Loading your IBM Q account(s)\nprovider = IBMQ.load_account()",
"_____no_output_____"
],
[
"# create a circuit with 1 qubit to process information, and 1 classical bit to store the result\ncircuit = QuantumCircuit(1, 1)\ncircuit.draw()",
"_____no_output_____"
],
[
"# apply a Hadamard gate to transform the qubit into a superposition state\ncircuit.h(0)\n\n# apply a measurement to retrieve the definite state of a qubit in superposition, and store it in the classical bit\ncircuit.measure([0], [0])\n\ncircuit.draw()",
"_____no_output_____"
],
[
"# run in a simulator\nbackend = Aer.get_backend('qasm_simulator')\n\n# use this to run in a real quantum computer provided by IBM\n# you can see the options in IBM Quantum Experience dashboard, here I use ibmq_london\n# backend = provider.get_backend('ibmq_london')",
"_____no_output_____"
],
[
"# execute the job in 1 shot, run it multiple times to get a different results\njob = execute(circuit, backend, shots=1)\ncounts = job.result().get_counts(circuit)\n\nprint(\"Result:\")\n\nif '0' in counts.keys():\n print(\"tail\")\nelse:\n print(\"head\")",
"_____no_output_____"
],
[
"# we can also run it in 100 shots, this will show us the counts of '0' and '1' appeared in 100 shots/experiments\njob = execute(circuit, backend, shots=100)\ncounts = job.result().get_counts(circuit)\n\nprint(\"Result:\", counts)",
"_____no_output_____"
],
[
"plot_histogram(counts)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccce07fadcfe364602ab749e624b687090f97ef | 31,842 | ipynb | Jupyter Notebook | amazon_reviews_LSTM.ipynb | tanmay-kulkarni/amazon_food_reviews | 4742a68eddff297c98abc4ffa4b21fe1168f6d4b | [
"MIT"
] | null | null | null | amazon_reviews_LSTM.ipynb | tanmay-kulkarni/amazon_food_reviews | 4742a68eddff297c98abc4ffa4b21fe1168f6d4b | [
"MIT"
] | null | null | null | amazon_reviews_LSTM.ipynb | tanmay-kulkarni/amazon_food_reviews | 4742a68eddff297c98abc4ffa4b21fe1168f6d4b | [
"MIT"
] | null | null | null | 29.239669 | 437 | 0.495917 | [
[
[
"<h1 align=\"center\">Classifying Amazon Food Reviews using LSTMs </h1>\n\n## Introduction\n\nThe Amazon Food Reviews is a dataset published [here](https://www.kaggle.com/snap/amazon-fine-food-reviews) on Kaggle of nearly 500K user reviews collected on the site for more than ten years upto 2012. The original dataset has a rating of 1 to 5 for each of the products given by the users along with their text reviews. Based on this rating, the objective of this study is to predict whether a review is positive or negative.\n\nI've cleaned the data already and saved it on disk. The two important columns in it which we'll use are `cleaned_text` and `Score`. The column Score is our Target variable with values 0 or 1 and it indicates whether the review is positive or negative. The value 0 bein negative and 1 being positive.\n\nLet's start by importing the libraries we need.",
"_____no_output_____"
]
],
[
[
"import numpy\nfrom keras.datasets import imdb\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.layers import LSTM\nfrom keras.layers.convolutional import Conv1D\nfrom keras.layers.convolutional import MaxPooling1D\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing import sequence\nimport sqlite3\nimport pandas as pd\nfrom collections import Counter\nfrom sklearn.model_selection import train_test_split\nimport keras_metrics\nfrom sklearn.metrics import roc_curve\nimport matplotlib.pyplot as plt\nimport scikitplot as skplt",
"_____no_output_____"
]
],
[
[
"### Mount the Google Drive\n\nThe cleaned dataframe is stored on my Google Drive and I'm using Colaboratory because it has access to a GPU environment. The following block of code attaches the drive to Google Colaboratory.",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/gdrive')",
"_____no_output_____"
]
],
[
[
"## Load the reviews from disk\n\nThe reviews are stored in a `.sqlite` file. Load them in a dataframe.",
"_____no_output_____"
]
],
[
[
"# load sqlite database\ncon = sqlite3.connect('/gdrive/My Drive/amazon/reviews_cleaned_final.sqlite')",
"_____no_output_____"
],
[
"#conn = sqlite3.connect('/gdrive/My Drive/amazon/reviews_cleaned_final.sqlite')\ndf = pd.read_sql('select * from Reviews;', con, index_col='index')\ncon.close()\ndf.head()",
"_____no_output_____"
]
],
[
[
"Only keep the `cleaned_text` and `Score` columns because these will be used for training the neural network.",
"_____no_output_____"
]
],
[
[
"df = df[['cleaned_text', 'Score']]",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 364171 entries, 0 to 525813\nData columns (total 2 columns):\ncleaned_text 364171 non-null object\nScore 364171 non-null object\ndtypes: object(2)\nmemory usage: 8.3+ MB\n"
]
],
[
[
"## Generate frequency counts of words",
"_____no_output_____"
]
],
[
[
"counter = Counter()\n\nc = 0\n\nfor review in df.cleaned_text:\n for word in review.decode('utf-8').split():\n counter[word] += 1\n print(c, end='\\r')\n c += 1",
""
]
],
[
[
"Create a dictionary mapping from word to its frequency in the entire review corpus",
"_____no_output_____"
]
],
[
[
"word_to_freq_DICT_5k = dict(counter.most_common(5000))",
"_____no_output_____"
]
],
[
[
"Reverse the above mapping and store it in another variable",
"_____no_output_____"
]
],
[
[
"freq_to_word_DICT_5k = {v:k for k, v in word_to_freq_DICT_5k.items()}",
"_____no_output_____"
]
],
[
[
"Now, generate mappings between a word and its index and vice versa. e.g. 'abc' : 4 will mean 'abc' is the 4th most frequent word encountered in the text.",
"_____no_output_____"
]
],
[
[
"word_to_index_lookup = dict(zip(freq_to_word_DICT_5k.values(), range(1,5001)))\nindex_to_word_lookup = {v:k for k,v in word_to_index_lookup.items()}",
"_____no_output_____"
]
],
[
[
"Create a dummy column in the dataframe. This column will contain the index-vector representation of each review. i.e. each word in a review is replaced by its index from the mapping we defined above. This index is what will be given as input to the LSTM.",
"_____no_output_____"
]
],
[
[
"df['freq_vectors'] = df.cleaned_text\n\ndef text_to_word_frequency(review):\n return [word_to_index_lookup[word] if word in word_to_index_lookup.keys() else 0 for word in review.decode('utf-8').split()]\n\ndf['freq_vectors'] = df.freq_vectors.map(text_to_word_frequency)",
"_____no_output_____"
]
],
[
[
"Here's what the new index-vectorized reviews look like.",
"_____no_output_____"
]
],
[
[
"print(df['freq_vectors'][2])",
"[0, 193, 0, 246, 0, 1378, 0, 262, 209, 0, 382, 692, 0, 0, 529, 238, 43, 692, 361, 1224, 522, 3, 171, 44, 396, 57, 0, 1477, 0, 0, 0, 0, 57, 0, 0, 354, 0, 1124, 0]\n"
]
],
[
[
"Map the Score variable from string to an integer",
"_____no_output_____"
]
],
[
[
"df.Score = df.Score.map({'positive' : 1, 'negative' : 0 })",
"_____no_output_____"
]
],
[
[
"## Train and Test data\n\nLet's divide all the reviews in the ratio 80:20 for Train and Test respectively.",
"_____no_output_____"
]
],
[
[
"X_train, X_test, y_train, y_test = train_test_split(df.freq_vectors.values,df.Score.values, test_size=0.2, random_state=13)",
"_____no_output_____"
],
[
"X_train.shape, y_train.shape, X_test.shape, y_test.shape",
"_____no_output_____"
]
],
[
[
"## Truncate or Pad input sequences\n\nIn real world data, it is impossible that each review will have the same length. But our neural network requires that the length of input is consistent. To that end, we'll fix the length of each review to 75 words and pad the reviews which are smaller than 75 words by zeros.",
"_____no_output_____"
]
],
[
[
"# truncate and/or pad input sequences\nmax_review_length = 75\nX_train = sequence.pad_sequences(X_train, maxlen=max_review_length)\nX_test = sequence.pad_sequences(X_test, maxlen=max_review_length)\n\nprint(X_train.shape)\nprint(X_train[1])",
"(291336, 75)\n[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 987 105\n 378 1269 2 396 317 0 98 121 140 95 6 113 105 0\n 364 369 105 43 1452 145 378 142 98 780 234 3 9 815\n 0 85 151 370 495]\n"
]
],
[
[
"Shape of input train and test data after padding",
"_____no_output_____"
]
],
[
[
"X_train.shape, X_test.shape, y_train.shape, y_test.shape",
"_____no_output_____"
]
],
[
[
"## Model 1\n\n\nArchitecture: \n\n**[ 75(E) - 100(L) - 1(Sigmoid Output) ]**\n\n\nwhere \n\nE = Embedding Layer\n\nL = LSTM Layer",
"_____no_output_____"
]
],
[
[
"# create the model\ntop_words = 5000\nembedding_vecor_length = 32\nmodel = Sequential()\nmodel.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))\nmodel.add(LSTM(100))\nmodel.add(Dense(1, activation='sigmoid'))\nprint(model.summary())\n#Refer: https://datascience.stackexchange.com/questions/10615/number-of-parameters-in-an-lstm-model",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_4 (Embedding) (None, 75, 32) 160000 \n_________________________________________________________________\nlstm_3 (LSTM) (None, 100) 53200 \n_________________________________________________________________\ndense_3 (Dense) (None, 1) 101 \n=================================================================\nTotal params: 213,301\nTrainable params: 213,301\nNon-trainable params: 0\n_________________________________________________________________\nNone\n"
]
],
[
[
"## Compile the model",
"_____no_output_____"
]
],
[
[
"model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy', keras_metrics.precision(), keras_metrics.recall() ])",
"_____no_output_____"
]
],
[
[
"## Fit the model",
"_____no_output_____"
]
],
[
[
"model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=64)\n#model.fit(X_train, y_train, nb_epoch=10, batch_size=32)\n# Final evaluation of the model\nscores = model.evaluate(X_test, y_test, verbose=1)\n#print(\"Accuracy: %.2f%%\" % (scores[1]*100))",
"Train on 291336 samples, validate on 72835 samples\nEpoch 1/3\n291336/291336 [==============================] - 973s 3ms/step - loss: 0.2255 - acc: 0.9097 - precision: 0.9297 - recall: 0.9659 - val_loss: 0.2082 - val_acc: 0.9167 - val_precision: 0.9398 - val_recall: 0.9630\nEpoch 2/3\n291336/291336 [==============================] - 985s 3ms/step - loss: 0.1954 - acc: 0.9212 - precision: 0.9394 - recall: 0.9690 - val_loss: 0.1900 - val_acc: 0.9237 - val_precision: 0.9403 - val_recall: 0.9712\nEpoch 3/3\n291336/291336 [==============================] - 993s 3ms/step - loss: 0.1819 - acc: 0.9271 - precision: 0.9447 - recall: 0.9703 - val_loss: 0.1859 - val_acc: 0.9258 - val_precision: 0.9440 - val_recall: 0.9696\n72835/72835 [==============================] - 179s 2ms/step\n"
],
[
"print(\"Accuracy: %.2f%%\" % (scores[1]*100))\nprint(\"Precision: %.2f%%\" % (scores[2]*100))\nprint(\"Recall: %.2f%%\" % (scores[3]*100))",
"Accuracy: 92.58%\nPrecision: 94.40%\nRecall: 96.96%\n"
]
],
[
[
"## Model 2: With Dropout\n\n**[ 75(E) - D - 100(L) - D - 1 (sigmoid output)]**",
"_____no_output_____"
]
],
[
[
"model = Sequential()\nmodel.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))\nmodel.add(Dropout(0.2))\nmodel.add(LSTM(100))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_5 (Embedding) (None, 75, 32) 160000 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 75, 32) 0 \n_________________________________________________________________\nlstm_4 (LSTM) (None, 100) 53200 \n_________________________________________________________________\ndropout_4 (Dropout) (None, 100) 0 \n_________________________________________________________________\ndense_4 (Dense) (None, 1) 101 \n=================================================================\nTotal params: 213,301\nTrainable params: 213,301\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"Compile model",
"_____no_output_____"
]
],
[
[
"model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy',keras_metrics.precision(), keras_metrics.recall()])",
"_____no_output_____"
]
],
[
[
"## Fit model ",
"_____no_output_____"
]
],
[
[
"model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=64)\n#model.fit(X_train, y_train, nb_epoch=10, batch_size=32)\n# Final evaluation of the model\nscores = model.evaluate(X_test, y_test, verbose=1)\n#print(\"Accuracy: %.2f%%\" % (scores[1]*100))",
"Train on 291336 samples, validate on 72835 samples\nEpoch 1/3\n291336/291336 [==============================] - 1001s 3ms/step - loss: 0.2276 - acc: 0.9088 - precision: 0.9293 - recall: 0.9653 - val_loss: 0.2062 - val_acc: 0.9172 - val_precision: 0.9328 - val_recall: 0.9718\nEpoch 2/3\n291336/291336 [==============================] - 991s 3ms/step - loss: 0.2003 - acc: 0.9198 - precision: 0.9386 - recall: 0.9682 - val_loss: 0.1930 - val_acc: 0.9215 - val_precision: 0.9412 - val_recall: 0.9674\nEpoch 3/3\n291336/291336 [==============================] - 986s 3ms/step - loss: 0.1874 - acc: 0.9248 - precision: 0.9426 - recall: 0.9698 - val_loss: 0.1871 - val_acc: 0.9247 - val_precision: 0.9371 - val_recall: 0.9763\n72835/72835 [==============================] - 176s 2ms/step\n"
],
[
"print(\"Accuracy: %.2f%%\" % (scores[1]*100))\nprint(\"Precision: %.2f%%\" % (scores[2]*100))\nprint(\"Recall: %.2f%%\" % (scores[3]*100))",
"Accuracy: 92.47%\nPrecision: 93.71%\nRecall: 97.63%\n"
],
[
"#!pip install keras-metrics",
"_____no_output_____"
]
],
[
[
"# Conclusion:\n\n* We classifed Amazon Food Reviwes using LSTMs. The two architectures we tried were:\n \n [ 75(E) - 100(L) - 1(Sigmoid Output) ]\n [ 75(E) - D - 100(L) - D - 1 (sigmoid output)]\n where\n \n E = Embedding Layer\n D = Dropout Layer\n L = LSTM\n \n Both the models gave similar performance. The accuracy, precision and Recall obtained were:\n \n - Accuracy: 92.58%\n - Precision: 94.40%\n - Recall: 96.96%",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
ecccecb2cc6ac8dd39c3f3bec0dd5c7844e41ddc | 858,215 | ipynb | Jupyter Notebook | notebooks/7 Nonlinear ensemble filtering Lorenz 63 with fixed order Hermite map.ipynb | mleprovost/TransportBasedInference.jl | bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7 | [
"MIT"
] | 1 | 2022-03-23T03:16:56.000Z | 2022-03-23T03:16:56.000Z | notebooks/7 Nonlinear ensemble filtering Lorenz 63 with fixed order Hermite map.ipynb | mleprovost/TransportBasedInference.jl | bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7 | [
"MIT"
] | null | null | null | notebooks/7 Nonlinear ensemble filtering Lorenz 63 with fixed order Hermite map.ipynb | mleprovost/TransportBasedInference.jl | bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7 | [
"MIT"
] | null | null | null | 150.590454 | 619 | 0.595103 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
ecccf5fbc2302c672bba9c5f417e1a3c356c5f57 | 43,604 | ipynb | Jupyter Notebook | examples/multi-gpu-movielens/01-03-MultiGPU-Download-Convert-ETL-with-NVTabular-Training-with-TensorFlow.ipynb | boliu61/NVTabular | ff4d97c64beab5a2ec827d2166fb9a8f46376075 | [
"Apache-2.0"
] | 1 | 2021-09-06T10:38:03.000Z | 2021-09-06T10:38:03.000Z | examples/multi-gpu-movielens/01-03-MultiGPU-Download-Convert-ETL-with-NVTabular-Training-with-TensorFlow.ipynb | boliu61/NVTabular | ff4d97c64beab5a2ec827d2166fb9a8f46376075 | [
"Apache-2.0"
] | 1 | 2021-08-30T21:24:22.000Z | 2021-08-30T21:24:22.000Z | examples/multi-gpu-movielens/01-03-MultiGPU-Download-Convert-ETL-with-NVTabular-Training-with-TensorFlow.ipynb | liftoffio/NVTabular | 4ebb6bc11da12f2a0034dccc8f59701dd2240061 | [
"Apache-2.0"
] | null | null | null | 51.909524 | 508 | 0.652027 | [
[
[
"# Copyright 2021 NVIDIA Corporation. All Rights Reserved.\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.\n# ==============================================================================",
"_____no_output_____"
]
],
[
[
"<img src=\"http://developer.download.nvidia.com/compute/machine-learning/frameworks/nvidia_logo.png\" style=\"width: 90px; float: right;\">\n\n# Multi-GPU with MovieLens: ETL and Training \n\n## Overview\n\nNVIDIA Merlin is a open source framework to accelerate and scale end-to-end recommender system pipelines on GPU. In this notebook, we use NVTabular, Merlin’s ETL component, to scale feature engineering and pre-processing to multiple GPUs and then perform data-parallel distributed training of a neural network on multiple GPUs with TensorFlow, [Horovod](https://horovod.readthedocs.io/en/stable/), and [NCCL](https://developer.nvidia.com/nccl).\n\nThe pre-requisites for this notebook are to be familiar with NVTabular and its API:\n- You can read more about NVTabular, its API and specialized dataloaders in [Getting Started with Movielens notebooks](../getting-started-movielens).\n- You can read more about scaling NVTabular ETL in [Scaling Criteo notebooks](../scaling-criteo).\n\n**In this notebook, we will focus only on the new information related to multi-GPU training, so please check out the other notebooks first (if you haven’t already.)**\n\n### Learning objectives\n\nIn this notebook, we learn how to scale ETL and deep learning taining to multiple GPUs\n- Learn to use larger than GPU/host memory datasets for ETL and training\n- Use multi-GPU or multi node for ETL with NVTabular\n- Use NVTabular dataloader to accelerate TensorFlow pipelines\n- Scale TensorFlow training with Horovod\n\n### Dataset\n\nIn this notebook, we use the [MovieLens25M](https://grouplens.org/datasets/movielens/25m/) dataset. It is popular for recommender systems and is used in academic publications. The dataset contains 25M movie ratings for 62,000 movies given by 162,000 users. Many projects use only the user/item/rating information of MovieLens, but the original dataset provides metadata for the movies, as well.\n\nNote: We are using the MovieLens 25M dataset in this example for simplicity, although the dataset is not large enough to require multi-GPU training. However, the functionality demonstrated in this notebook can be easily extended to scale recommender pipelines for larger datasets in the same way.\n\n### Tools\n\n- [Horovod](https://horovod.readthedocs.io/en/stable/) is a distributed deep learning framework that provides tools for multi-GPU optimization.\n- The [NVIDIA Collective Communication Library (NCCL)](https://developer.nvidia.com/nccl) provides the underlying GPU-based implementations of the [allgather](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/operations.html#allgather) and [allreduce](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/operations.html#allreduce) cross-GPU communication operations.",
"_____no_output_____"
],
[
"## Download and Convert\n\nFirst, we will download and convert the dataset to Parquet. This section is based on [01-Download-Convert.ipynb](../getting-started-movielens/01-Download-Convert.ipynb).",
"_____no_output_____"
],
[
"#### Download",
"_____no_output_____"
]
],
[
[
"# External dependencies\nimport os\nimport pathlib\n\nimport cudf # cuDF is an implementation of Pandas-like Dataframe on GPU\n\nfrom nvtabular.utils import download_file\nfrom sklearn.model_selection import train_test_split\n\nINPUT_DATA_DIR = os.environ.get(\n \"INPUT_DATA_DIR\", \"~/nvt-examples/multigpu-movielens/data/\"\n)\nBASE_DIR = pathlib.Path(INPUT_DATA_DIR).expanduser()\nzip_path = pathlib.Path(BASE_DIR, \"ml-25m.zip\")\ndownload_file(\n \"http://files.grouplens.org/datasets/movielens/ml-25m.zip\", zip_path, redownload=False\n)",
"downloading ml-25m.zip: 262MB [00:13, 19.4MB/s] \nunzipping files: 100%|██████████| 8/8 [00:04<00:00, 1.92files/s]\n"
]
],
[
[
"#### Convert",
"_____no_output_____"
]
],
[
[
"movies = cudf.read_csv(pathlib.Path(BASE_DIR, \"ml-25m\", \"movies.csv\"))\nmovies[\"genres\"] = movies[\"genres\"].str.split(\"|\")\nmovies = movies.drop(\"title\", axis=1)\nmovies.to_parquet(pathlib.Path(BASE_DIR, \"ml-25m\", \"movies_converted.parquet\"))",
"_____no_output_____"
]
],
[
[
"#### Split into train and validation datasets",
"_____no_output_____"
]
],
[
[
"ratings = cudf.read_csv(pathlib.Path(BASE_DIR, \"ml-25m\", \"ratings.csv\"))\nratings = ratings.drop(\"timestamp\", axis=1)\ntrain, valid = train_test_split(ratings, test_size=0.2, random_state=42)\ntrain.to_parquet(pathlib.Path(BASE_DIR, \"train.parquet\"))\nvalid.to_parquet(pathlib.Path(BASE_DIR, \"valid.parquet\"))",
"_____no_output_____"
]
],
[
[
"## ETL with NVTabular\n\nWe finished downloading and converting the dataset. We will preprocess and engineer features with NVTabular on multiple GPUs. You can read more\n- about NVTabular's features and API in [getting-started-movielens/02-ETL-with-NVTabular.ipynb](../getting-started-movielens/02-ETL-with-NVTabular.ipynb).\n- scaling NVTabular ETL to multiple GPUs [scaling-criteo/02-ETL-with-NVTabular.ipynb](../scaling-criteo/02-ETL-with-NVTabular.ipynb).",
"_____no_output_____"
],
[
"#### Deploy a Distributed-Dask Cluster\n\nThis section is based on [scaling-criteo/02-ETL-with-NVTabular.ipynb](../scaling-criteo/02-ETL-with-NVTabular.ipynb) and [multi-gpu-toy-example/multi-gpu_dask.ipynb](../multi-gpu-toy-example/multi-gpu_dask.ipynb)",
"_____no_output_____"
]
],
[
[
"# Standard Libraries\nimport shutil\n\n# External Dependencies\nimport cupy as cp\nimport cudf\nimport dask_cudf\nfrom dask_cuda import LocalCUDACluster\nfrom dask.distributed import Client\nfrom dask.utils import parse_bytes\nfrom dask.delayed import delayed\nimport rmm\n\n# NVTabular\nimport nvtabular as nvt\nimport nvtabular.ops as ops\nfrom nvtabular.io import Shuffle\nfrom nvtabular.utils import device_mem_size",
"_____no_output_____"
],
[
"# define some information about where to get our data\ninput_path = pathlib.Path(BASE_DIR, \"converted\", \"movielens\")\ndask_workdir = pathlib.Path(BASE_DIR, \"test_dask\", \"workdir\")\noutput_path = pathlib.Path(BASE_DIR, \"test_dask\", \"output\")\nstats_path = pathlib.Path(BASE_DIR, \"test_dask\", \"stats\")\n\n# Make sure we have a clean worker space for Dask\nif pathlib.Path.is_dir(dask_workdir):\n shutil.rmtree(dask_workdir)\ndask_workdir.mkdir(parents=True)\n\n# Make sure we have a clean stats space for Dask\nif pathlib.Path.is_dir(stats_path):\n shutil.rmtree(stats_path)\nstats_path.mkdir(parents=True)\n\n# Make sure we have a clean output path\nif pathlib.Path.is_dir(output_path):\n shutil.rmtree(output_path)\noutput_path.mkdir(parents=True)\n\n# Get device memory capacity\ncapacity = device_mem_size(kind=\"total\")",
"_____no_output_____"
],
[
"# Deploy a Single-Machine Multi-GPU Cluster\nprotocol = \"tcp\" # \"tcp\" or \"ucx\"\nvisible_devices = \"0,1\" # Delect devices to place workers\ndevice_spill_frac = 0.5 # Spill GPU-Worker memory to host at this limit.\n# Reduce if spilling fails to prevent\n# device memory errors.\ncluster = None # (Optional) Specify existing scheduler port\nif cluster is None:\n cluster = LocalCUDACluster(\n protocol=protocol,\n CUDA_VISIBLE_DEVICES=visible_devices,\n local_directory=dask_workdir,\n device_memory_limit=capacity * device_spill_frac,\n )\n\n# Create the distributed client\nclient = Client(cluster)\nclient",
"_____no_output_____"
],
[
"# Initialize RMM pool on ALL workers\ndef _rmm_pool():\n rmm.reinitialize(\n pool_allocator=True,\n initial_pool_size=None, # Use default size\n )\n\n\nclient.run(_rmm_pool)",
"_____no_output_____"
]
],
[
[
"#### Defining our Preprocessing Pipeline\n\nThis subsection is based on [getting-started-movielens/02-ETL-with-NVTabular.ipynb](../getting-started-movielens/02-ETL-with-NVTabular.ipynb). The only difference is that we initialize the NVTabular workflow using the LocalCUDACluster client with `nvt.Workflow(output, client=client)`.",
"_____no_output_____"
]
],
[
[
"movies = cudf.read_parquet(pathlib.Path(BASE_DIR, \"ml-25m\", \"movies_converted.parquet\"))\njoined = [\"userId\", \"movieId\"] >> nvt.ops.JoinExternal(movies, on=[\"movieId\"])\ncat_features = joined >> nvt.ops.Categorify()\nratings = nvt.ColumnGroup([\"rating\"]) >> (lambda col: (col > 3).astype(\"int8\"))\noutput = cat_features + ratings\n# USE client in NVTabular workfow\nworkflow = nvt.Workflow(output, client=client)\n!rm -rf $BASE_DIR/train\n!rm -rf $BASE_DIR/valid\ntrain_iter = nvt.Dataset([str(pathlib.Path(BASE_DIR, \"train.parquet\"))], part_size=\"100MB\")\nvalid_iter = nvt.Dataset([str(pathlib.Path(BASE_DIR, \"valid.parquet\"))], part_size=\"100MB\")\nworkflow.fit(train_iter)\nworkflow.save(pathlib.Path(BASE_DIR, \"workflow\"))\nshuffle = Shuffle.PER_WORKER # Shuffle algorithm\nout_files_per_proc = 4 # Number of output files per worker\nworkflow.transform(train_iter).to_parquet(\n output_path=pathlib.Path(BASE_DIR, \"train\"),\n shuffle=shuffle,\n out_files_per_proc=out_files_per_proc,\n)\nworkflow.transform(valid_iter).to_parquet(\n output_path=pathlib.Path(BASE_DIR, \"valid\"),\n shuffle=shuffle,\n out_files_per_proc=out_files_per_proc,\n)\n\nclient.shutdown()\ncluster.close()",
"/usr/local/lib/python3.8/dist-packages/distributed/worker.py:3560: UserWarning: Large object of size 1.90 MiB detected in task graph: \n (\"('read-parquet-d36dd514a8adc53a9a91115c9be1d852' ... 1115c9be1d852')\nConsider scattering large objects ahead of time\nwith client.scatter to reduce scheduler burden and \nkeep data on workers\n\n future = client.submit(func, big_data) # bad\n\n big_future = client.scatter(big_data) # good\n future = client.submit(func, big_future) # good\n warnings.warn(\n"
]
],
[
[
"## Training with TensorFlow on multiGPUs\n\nIn this section, we will train a TensorFlow model with multi-GPU support. In the NVTabular v0.5 release, we added multi-GPU support for NVTabular dataloaders. We will modify the [getting-started-movielens/03-Training-with-TF.ipynb](../getting-started-movielens/03-Training-with-TF.ipynb) to use multiple GPUs. Please review that notebook, if you have questions about the general functionality of the NVTabular dataloaders or the neural network architecture.\n\n#### NVTabular dataloader for TensorFlow\n\nWe’ve identified that the dataloader is one bottleneck in deep learning recommender systems when training pipelines with TensorFlow. The normal TensorFlow dataloaders cannot prepare the next training batches fast enough and therefore, the GPU is not fully utilized. \n\nWe developed a highly customized tabular dataloader for accelerating existing pipelines in TensorFlow. In our experiments, we see a speed-up by 9x of the same training workflow with NVTabular dataloader. NVTabular dataloader’s features are:\n- removing bottleneck of item-by-item dataloading\n- enabling larger than memory dataset by streaming from disk\n- reading data directly into GPU memory and remove CPU-GPU communication\n- preparing batch asynchronously in GPU to avoid CPU-GPU communication\n- supporting commonly used .parquet format\n- easy integration into existing TensorFlow pipelines by using similar API - works with tf.keras models\n- **supporting multi-GPU training with Horovod**\n\nYou can find more information on the dataloaders in our [blogpost](https://medium.com/nvidia-merlin/training-deep-learning-based-recommender-systems-9x-faster-with-tensorflow-cc5a2572ea49).",
"_____no_output_____"
],
[
"#### Using Horovod with Tensorflow and NVTabular\n\nThe training script below is based on [getting-started-movielens/03-Training-with-TF.ipynb](../getting-started-movielens/03-Training-with-TF.ipynb), with a few important changes:\n\n- We provide several additional parameters to the `KerasSequenceLoader` class, including the total number of workers `hvd.size()`, the current worker's id number `hvd.rank()`, and a function for generating random seeds `seed_fn()`. \n\n```python\n train_dataset_tf = KerasSequenceLoader(\n ...\n global_size=hvd.size(),\n global_rank=hvd.rank(),\n seed_fn=seed_fn,\n )\n\n```\n- The seed function uses Horovod to collectively generate a random seed that's shared by all workers so that they can each shuffle the dataset in a consistent way and select partitions to work on without overlap. The seed function is called by the dataloader during the shuffling process at the beginning of each epoch:\n\n```python\n def seed_fn():\n min_int, max_int = tf.int32.limits\n max_rand = max_int // hvd.size()\n\n # Generate a seed fragment on each worker\n seed_fragment = cupy.random.randint(0, max_rand).get()\n\n # Aggregate seed fragments from all Horovod workers\n seed_tensor = tf.constant(seed_fragment)\n reduced_seed = hvd.allreduce(seed_tensor, name=\"shuffle_seed\", op=hvd.mpi_ops.Sum) \n\n return reduced_seed % max_rand\n```\n\n- We wrap the TensorFlow optimizer with Horovod's `DistributedOptimizer` class and scale the learning rate by the number of workers:\n\n```python\n opt = tf.keras.optimizers.SGD(0.01 * hvd.size())\n opt = hvd.DistributedOptimizer(opt)\n```\n\n- We wrap the TensorFlow gradient tape with Horovod's `DistributedGradientTape` class:\n\n```python\n with tf.GradientTape() as tape:\n ...\n tape = hvd.DistributedGradientTape(tape, sparse_as_dense=True)\n```\n\n- After the first batch, we broadcast the model and optimizer parameters to all workers with Horovod:\n\n```python\n # Note: broadcast should be done after the first gradient step to\n # ensure optimizer initialization.\n if first_batch:\n hvd.broadcast_variables(model.variables, root_rank=0)\n hvd.broadcast_variables(opt.variables(), root_rank=0)\n```\n\n- We only save checkpoints from the first worker to avoid multiple workers trying to write to the same files:\n\n```python\n if hvd.rank() == 0:\n checkpoint.save(checkpoint_dir)\n```\n\nThe rest of the script is the same as the MovieLens example in [getting-started-movielens/03-Training-with-TF.ipynb](../getting-started-movielens/03-Training-with-TF.ipynb). In order to run it with Horovod, we first need to write it to a file.",
"_____no_output_____"
]
],
[
[
"%%writefile './tf_trainer.py'\n\n# External dependencies\nimport argparse\nimport glob\nimport os\n\nimport cupy\n\n# we can control how much memory to give tensorflow with this environment variable\n# IMPORTANT: make sure you do this before you initialize TF's runtime, otherwise\n# TF will have claimed all free GPU memory\nos.environ[\"TF_MEMORY_ALLOCATION\"] = \"0.3\" # fraction of free memory\n\nimport nvtabular as nvt # noqa: E402 isort:skip\nfrom nvtabular.framework_utils.tensorflow import layers # noqa: E402 isort:skip\nfrom nvtabular.loader.tensorflow import KerasSequenceLoader # noqa: E402 isort:skip\n\nimport tensorflow as tf # noqa: E402 isort:skip\nimport horovod.tensorflow as hvd # noqa: E402 isort:skip\n\nparser = argparse.ArgumentParser(description=\"Process some integers.\")\nparser.add_argument(\"--dir_in\", default=None, help=\"Input directory\")\nparser.add_argument(\"--batch_size\", default=None, help=\"batch size\")\nparser.add_argument(\"--cats\", default=None, help=\"categorical columns\")\nparser.add_argument(\"--cats_mh\", default=None, help=\"categorical multihot columns\")\nparser.add_argument(\"--conts\", default=None, help=\"continuous columns\")\nparser.add_argument(\"--labels\", default=None, help=\"continuous columns\")\nargs = parser.parse_args()\n\n\nBASE_DIR = args.dir_in or \"./data/\"\nBATCH_SIZE = int(args.batch_size or 16384) # Batch Size\nCATEGORICAL_COLUMNS = args.cats or [\"movieId\", \"userId\"] # Single-hot\nCATEGORICAL_MH_COLUMNS = args.cats_mh or [\"genres\"] # Multi-hot\nNUMERIC_COLUMNS = args.conts or []\nTRAIN_PATHS = sorted(\n glob.glob(os.path.join(BASE_DIR, \"train/*.parquet\"))\n) # Output from ETL-with-NVTabular\nhvd.init()\n\n# Seed with system randomness (or a static seed)\ncupy.random.seed(None)\n\n\ndef seed_fn():\n \"\"\"\n Generate consistent dataloader shuffle seeds across workers\n\n Reseeds each worker's dataloader each epoch to get fresh a shuffle\n that's consistent across workers.\n \"\"\"\n min_int, max_int = tf.int32.limits\n max_rand = max_int // hvd.size()\n\n # Generate a seed fragment on each worker\n seed_fragment = cupy.random.randint(0, max_rand).get()\n\n # Aggregate seed fragments from all Horovod workers\n seed_tensor = tf.constant(seed_fragment)\n reduced_seed = hvd.allreduce(seed_tensor, name=\"shuffle_seed\", op=hvd.mpi_ops.Sum)\n\n return reduced_seed % max_rand\n\n\nproc = nvt.Workflow.load(os.path.join(BASE_DIR, \"workflow/\"))\nEMBEDDING_TABLE_SHAPES, MH_EMBEDDING_TABLE_SHAPES = nvt.ops.get_embedding_sizes(proc)\nEMBEDDING_TABLE_SHAPES.update(MH_EMBEDDING_TABLE_SHAPES)\n\ntrain_dataset_tf = KerasSequenceLoader(\n TRAIN_PATHS, # you could also use a glob pattern\n batch_size=BATCH_SIZE,\n label_names=[\"rating\"],\n cat_names=CATEGORICAL_COLUMNS + CATEGORICAL_MH_COLUMNS,\n cont_names=NUMERIC_COLUMNS,\n engine=\"parquet\",\n shuffle=True,\n buffer_size=0.06, # how many batches to load at once\n parts_per_chunk=1,\n global_size=hvd.size(),\n global_rank=hvd.rank(),\n seed_fn=seed_fn,\n)\ninputs = {} # tf.keras.Input placeholders for each feature to be used\nemb_layers = [] # output of all embedding layers, which will be concatenated\nfor col in CATEGORICAL_COLUMNS:\n inputs[col] = tf.keras.Input(name=col, dtype=tf.int32, shape=(1,))\n# Note that we need two input tensors for multi-hot categorical features\nfor col in CATEGORICAL_MH_COLUMNS:\n inputs[col] = \\\n (tf.keras.Input(name=f\"{col}__values\", dtype=tf.int64, shape=(1,)),\n tf.keras.Input(name=f\"{col}__nnzs\", dtype=tf.int64, shape=(1,)))\nfor col in CATEGORICAL_COLUMNS + CATEGORICAL_MH_COLUMNS:\n emb_layers.append(\n tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_identity(\n col, EMBEDDING_TABLE_SHAPES[col][0]\n ), # Input dimension (vocab size)\n EMBEDDING_TABLE_SHAPES[col][1], # Embedding output dimension\n )\n )\nemb_layer = layers.DenseFeatures(emb_layers)\nx_emb_output = emb_layer(inputs)\nx = tf.keras.layers.Dense(128, activation=\"relu\")(x_emb_output)\nx = tf.keras.layers.Dense(128, activation=\"relu\")(x)\nx = tf.keras.layers.Dense(128, activation=\"relu\")(x)\nx = tf.keras.layers.Dense(1, activation=\"sigmoid\")(x)\nmodel = tf.keras.Model(inputs=inputs, outputs=x)\nloss = tf.losses.BinaryCrossentropy()\nopt = tf.keras.optimizers.SGD(0.01 * hvd.size())\nopt = hvd.DistributedOptimizer(opt)\ncheckpoint_dir = \"./checkpoints\"\ncheckpoint = tf.train.Checkpoint(model=model, optimizer=opt)\n\n\[email protected](experimental_relax_shapes=True)\ndef training_step(examples, labels, first_batch):\n with tf.GradientTape() as tape:\n probs = model(examples, training=True)\n loss_value = loss(labels, probs)\n # Horovod: add Horovod Distributed GradientTape.\n tape = hvd.DistributedGradientTape(tape, sparse_as_dense=True)\n grads = tape.gradient(loss_value, model.trainable_variables)\n opt.apply_gradients(zip(grads, model.trainable_variables))\n # Horovod: broadcast initial variable states from rank 0 to all other processes.\n # This is necessary to ensure consistent initialization of all workers when\n # training is started with random weights or restored from a checkpoint.\n #\n # Note: broadcast should be done after the first gradient step to ensure optimizer\n # initialization.\n if first_batch:\n hvd.broadcast_variables(model.variables, root_rank=0)\n hvd.broadcast_variables(opt.variables(), root_rank=0)\n return loss_value\n\n\n# Horovod: adjust number of steps based on number of GPUs.\nfor batch, (examples, labels) in enumerate(train_dataset_tf):\n loss_value = training_step(examples, labels, batch == 0)\n if batch % 100 == 0 and hvd.local_rank() == 0:\n print(\"Step #%d\\tLoss: %.6f\" % (batch, loss_value))\nhvd.join()\n\n# Horovod: save checkpoints only on worker 0 to prevent other workers from\n# corrupting it.\nif hvd.rank() == 0:\n checkpoint.save(checkpoint_dir)",
"Overwriting ./tf_trainer.py\n"
]
],
[
[
"We'll also need a small wrapper script to check environment variables set by the Horovod runner to see which rank we'll be assigned, in order to set CUDA_VISIBLE_DEVICES properly for each worker:",
"_____no_output_____"
]
],
[
[
"%%writefile './hvd_wrapper.sh'\n\n#!/bin/bash\n\n# Get local process ID from OpenMPI or alternatively from SLURM\nif [ -z \"${CUDA_VISIBLE_DEVICES:-}\" ]; then\n if [ -n \"${OMPI_COMM_WORLD_LOCAL_RANK:-}\" ]; then\n LOCAL_RANK=\"${OMPI_COMM_WORLD_LOCAL_RANK}\"\n elif [ -n \"${SLURM_LOCALID:-}\" ]; then\n LOCAL_RANK=\"${SLURM_LOCALID}\"\n fi\n export CUDA_VISIBLE_DEVICES=${LOCAL_RANK}\nfi\n\nexec \"$@\"",
"Overwriting ./hvd_wrapper.sh\n"
]
],
[
[
"OpenMPI and Slurm are tools for running distributed computed jobs. In this example, we’re using OpenMPI, but depending on the environment you run distributed training jobs in, you may need to check slightly different environment variables to find the total number of workers (global size) and each process’s worker number (global rank.)\n\nWhy do we have to check environment variables instead of using `hvd.rank()` and `hvd.local_rank()`? NVTabular does some GPU configuration when imported and needs to be imported before Horovod to avoid conflicts. We need to set GPU visibility before NVTabular is imported (when Horovod isn’t yet available) so that multiple processes don’t each try to configure all the GPUs, so as a workaround, we “cheat” and peek at environment variables set by horovodrun to decide which GPU each process should use.",
"_____no_output_____"
]
],
[
[
"!horovodrun -np 2 sh hvd_wrapper.sh python tf_trainer.py --dir_in $BASE_DIR --batch_size 16384",
"2021-06-04 16:39:06.000313: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0\n[1,0]<stderr>:2021-06-04 16:39:08.979997: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0\n[1,1]<stderr>:2021-06-04 16:39:09.064191: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0\n[1,0]<stderr>:2021-06-04 16:39:10.138200: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set\n[1,0]<stderr>:2021-06-04 16:39:10.138376: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcuda.so.1\n[1,0]<stderr>:2021-06-04 16:39:10.139777: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Found device 0 with properties: \n[1,0]<stderr>:pciBusID: 0000:0b:00.0 name: GeForce GTX 1080 Ti computeCapability: 6.1\n[1,0]<stderr>:coreClock: 1.582GHz coreCount: 28 deviceMemorySize: 10.91GiB deviceMemoryBandwidth: 451.17GiB/s\n[1,0]<stderr>:2021-06-04 16:39:10.139823: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0\n[1,0]<stderr>:2021-06-04 16:39:10.139907: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.11\n[1,0]<stderr>:2021-06-04 16:39:10.139949: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublasLt.so.11\n[1,0]<stderr>:2021-06-04 16:39:10.139990: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcufft.so.10\n[1,0]<stderr>:2021-06-04 16:39:10.140029: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcurand.so.10\n[1,0]<stderr>:2021-06-04 16:39:10.140084: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusolver.so.11\n[1,0]<stderr>:2021-06-04 16:39:10.140123: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusparse.so.11\n[1,0]<stderr>:2021-06-04 16:39:10.140169: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudnn.so.8\n[1,0]<stderr>:2021-06-04 16:39:10.144021: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1888] Adding visible gpu devices: 0\n[1,1]<stderr>:2021-06-04 16:39:10.367414: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set\n[1,1]<stderr>:2021-06-04 16:39:10.367496: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcuda.so.1\n[1,1]<stderr>:2021-06-04 16:39:10.368324: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Found device 0 with properties: \n[1,1]<stderr>:pciBusID: 0000:42:00.0 name: GeForce GTX 1080 Ti computeCapability: 6.1\n[1,1]<stderr>:coreClock: 1.582GHz coreCount: 28 deviceMemorySize: 10.92GiB deviceMemoryBandwidth: 451.17GiB/s\n[1,1]<stderr>:2021-06-04 16:39:10.368347: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0\n[1,1]<stderr>:2021-06-04 16:39:10.368396: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.11\n[1,1]<stderr>:2021-06-04 16:39:10.368424: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublasLt.so.11\n[1,1]<stderr>:2021-06-04 16:39:10.368451: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcufft.so.10\n[1,1]<stderr>:2021-06-04 16:39:10.368475: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcurand.so.10\n[1,1]<stderr>:2021-06-04 16:39:10.368512: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusolver.so.11\n[1,1]<stderr>:2021-06-04 16:39:10.368537: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusparse.so.11\n[1,1]<stderr>:2021-06-04 16:39:10.368573: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudnn.so.8\n[1,1]<stderr>:2021-06-04 16:39:10.369841: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1888] Adding visible gpu devices: 0\n[1,1]<stderr>:2021-06-04 16:39:11.730033: I tensorflow/compiler/jit/xla_gpu_device.cc:99] Not creating XLA devices, tf_xla_enable_xla_devices not set\n[1,1]<stderr>:2021-06-04 16:39:11.730907: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Found device 0 with properties: \n[1,1]<stderr>:pciBusID: 0000:42:00.0 name: GeForce GTX 1080 Ti computeCapability: 6.1\n[1,1]<stderr>:coreClock: 1.582GHz coreCount: 28 deviceMemorySize: 10.92GiB deviceMemoryBandwidth: 451.17GiB/s\n[1,1]<stderr>:2021-06-04 16:39:11.730990: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0\n[1,1]<stderr>:2021-06-04 16:39:11.731005: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.11\n[1,1]<stderr>:2021-06-04 16:39:11.731018: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublasLt.so.11\n[1,1]<stderr>:2021-06-04 16:39:11.731029: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcufft.so.10\n[1,1]<stderr>:2021-06-04 16:39:11.731038: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcurand.so.10\n[1,1]<stderr>:2021-06-04 16:39:11.731049: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusolver.so.11\n[1,1]<stderr>:2021-06-04 16:39:11.731059: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusparse.so.11\n[1,1]<stderr>:2021-06-04 16:39:11.731078: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudnn.so.8\n[1,1]<stderr>:2021-06-04 16:39:11.732312: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1888] Adding visible gpu devices: 0\n[1,1]<stderr>:2021-06-04 16:39:11.732350: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0\n[1,1]<stderr>:2021-06-04 16:39:11.732473: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1287] Device interconnect StreamExecutor with strength 1 edge matrix:\n[1,1]<stderr>:2021-06-04 16:39:11.732487: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1293] 0 \n[1,1]<stderr>:2021-06-04 16:39:11.732493: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1306] 0: N \n[1,1]<stderr>:2021-06-04 16:39:11.734431: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1432] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 3352 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:42:00.0, compute capability: 6.1)\n[1,0]<stderr>:2021-06-04 16:39:11.821346: I tensorflow/compiler/jit/xla_gpu_device.cc:99] Not creating XLA devices, tf_xla_enable_xla_devices not set\n[1,0]<stderr>:2021-06-04 16:39:11.822270: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Found device 0 with properties: \n[1,0]<stderr>:pciBusID: 0000:0b:00.0 name: GeForce GTX 1080 Ti computeCapability: 6.1\n[1,0]<stderr>:coreClock: 1.582GHz coreCount: 28 deviceMemorySize: 10.91GiB deviceMemoryBandwidth: 451.17GiB/s\n[1,0]<stderr>:2021-06-04 16:39:11.822360: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0\n[1,0]<stderr>:2021-06-04 16:39:11.822376: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.11\n[1,0]<stderr>:2021-06-04 16:39:11.822389: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublasLt.so.11\n[1,0]<stderr>:2021-06-04 16:39:11.822400: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcufft.so.10\n[1,0]<stderr>:2021-06-04 16:39:11.822411: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcurand.so.10\n[1,0]<stderr>:2021-06-04 16:39:11.822425: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusolver.so.11\n[1,0]<stderr>:2021-06-04 16:39:11.822434: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusparse.so.11\n[1,0]<stderr>:2021-06-04 16:39:11.822454: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudnn.so.8\n[1,0]<stderr>:2021-06-04 16:39:11.823684: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1888] Adding visible gpu devices: 0\n[1,0]<stderr>:2021-06-04 16:39:11.823731: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0\n[1,0]<stderr>:2021-06-04 16:39:11.823868: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1287] Device interconnect StreamExecutor with strength 1 edge matrix:\n[1,0]<stderr>:2021-06-04 16:39:11.823881: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1293] 0 \n[1,0]<stderr>:2021-06-04 16:39:11.823888: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1306] 0: N \n[1,0]<stderr>:2021-06-04 16:39:11.825784: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1432] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 3352 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:0b:00.0, compute capability: 6.1)\n[1,0]<stderr>:2021-06-04 16:39:17.634485: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2)\n[1,0]<stderr>:2021-06-04 16:39:17.668915: I tensorflow/core/platform/profile_utils/cpu_utils.cc:112] CPU Frequency: 2993950000 Hz\n[1,1]<stderr>:2021-06-04 16:39:17.694128: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2)\n[1,1]<stderr>:2021-06-04 16:39:17.703326: I tensorflow/core/platform/profile_utils/cpu_utils.cc:112] CPU Frequency: 2993950000 Hz\n[1,0]<stderr>:2021-06-04 16:39:17.780825: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.11\n[1,1]<stderr>:2021-06-04 16:39:17.810644: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.11\n[1,0]<stderr>:2021-06-04 16:39:17.984966: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublasLt.so.11\n[1,1]<stderr>:2021-06-04 16:39:18.012113: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublasLt.so.11\n[1,0]<stdout>:Step #0\tLoss: 0.695094\n[1,0]<stdout>:Step #100\tLoss: 0.669580\n[1,0]<stdout>:Step #200\tLoss: 0.661098\n[1,0]<stdout>:Step #300\tLoss: 0.660680\n[1,0]<stdout>:Step #400\tLoss: 0.658633\n[1,0]<stdout>:Step #500\tLoss: 0.660251\n[1,0]<stdout>:Step #600\tLoss: 0.657047\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
eccd001ed93ab2c51b8f42c5d3a477454ae8f31a | 47,398 | ipynb | Jupyter Notebook | 4-Interpretibility/EmployeeAttritionClassifier_Interpretability_Remote.ipynb | lehmus/bert-stack-overflow | 0fb848e0ac80622cb1650a66b1e486b66da1ff31 | [
"MIT"
] | 3 | 2020-09-27T12:26:07.000Z | 2021-08-30T09:32:08.000Z | 4-Interpretibility/EmployeeAttritionClassifier_Interpretability_Remote.ipynb | lehmus/bert-stack-overflow | 0fb848e0ac80622cb1650a66b1e486b66da1ff31 | [
"MIT"
] | null | null | null | 4-Interpretibility/EmployeeAttritionClassifier_Interpretability_Remote.ipynb | lehmus/bert-stack-overflow | 0fb848e0ac80622cb1650a66b1e486b66da1ff31 | [
"MIT"
] | null | null | null | 69.498534 | 1,204 | 0.6937 | [
[
[
"Copyright (c) Microsoft Corporation. All rights reserved.\n\nLicensed under the MIT License.",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"# Interpretability With Tensorflow On Azure Machine Learning Service (Remote)\n\n\n## Overview of Tutorial\nThis notebook is Part 4 (Explaining Your Model Using Interpretability) of a four part workshop that demonstrates an end-to-end workflow for using Tensorflow on Azure Machine Learning Service. The different components of the workshop are as follows:\n\n- Part 1: [Preparing Data and Model Training](https://github.com/microsoft/bert-stack-overflow/blob/master/1-Training/AzureServiceClassifier_Training.ipynb)\n- Part 2: [Inferencing and Deploying a Model](https://github.com/microsoft/bert-stack-overflow/blob/master/2-Inferencing/AzureServiceClassifier_Inferencing.ipynb)\n- Part 3: [Setting Up a Pipeline Using MLOps](https://github.com/microsoft/bert-stack-overflow/tree/master/3-ML-Ops)\n- Part 4: [Explaining Your Model Interpretability](https://github.com/microsoft/bert-stack-overflow/blob/master/4-Interpretibility/IBMEmployeeAttritionClassifier_Interpretability.ipynb)\n\n_**This notebook showcases how to use the Azure Machine Learning Interpretability SDK to train and explain a binary classification model remotely on an Azure Machine Leanrning Compute Target (AMLCompute).**_\n\n## Table of Contents\n\n1. [Introduction](#Introduction)\n1. [Setup](#Setup)\n 1. Initialize a Workspace\n 1. Create an Experiment\n 1. Introduction to AmlCompute\n 1. Submit an AmlCompute run \n1. Additional operations to perform on AmlCompute\n1. [Download model explanations from Azure Machine Learning Run History](#Download)",
"_____no_output_____"
],
[
"## Introduction\n\nThis notebook showcases how to train and explain a binary classification model remotely via Azure Machine Learning Compute (AMLCompute), and download the calculated explanations locally on your personal machine.\nIt demonstrates the API calls that you need to make to submit a run for training and explaining a model to AMLCompute, and download the compute explanations remotely.\n\nWe will showcase one of the tabular data explainers: TabularExplainer (SHAP).\n\nProblem: Employee Attrition Classification Problem\n\n\n\n\n\n",
"_____no_output_____"
],
[
"## Change Tensorflow and Interpret Library Versions\n\nWe will be using an older version (1.14) for this particular tutorial in the series as Tensorflow 2.0 is not yet supported for Interpretibility on Azure Machine Learning service. We will also be using version 0.1.0.4 of the interpret library. \n\nIf haven't already done so, please update your library versions.",
"_____no_output_____"
]
],
[
[
"%pip uninstall tensorflow-gpu keras --yes\n%pip install tensorflow-gpu==1.14 interpret-community==0.1.0.4",
"Collecting azureml.contrib.interpret\n Using cached https://files.pythonhosted.org/packages/05/cf/05ff8cc39de0c97bc1fd564dc618a8256ff5b2f08446556fc73435e69652/azureml_contrib_interpret-1.0.69-py3-none-any.whl\nRequirement already satisfied, skipping upgrade: azureml-interpret==1.0.69.* in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from azureml.contrib.interpret) (1.0.69)\nCollecting interpret-community==0.1.0.2 (from azureml-interpret==1.0.69.*->azureml.contrib.interpret)\n Using cached https://files.pythonhosted.org/packages/8b/3b/a7eb6beac2d8b21ea442ffe73d90b236e89c97bc6e2c805bcb96ed2c0bdf/interpret_community-0.1.0.2-py3-none-any.whl\nRequirement already satisfied, skipping upgrade: shap<=0.29.3,>=0.20.0 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.29.3)\nRequirement already satisfied, skipping upgrade: interpret>=0.1.17 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.1.18)\nRequirement already satisfied, skipping upgrade: pandas in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.23.4)\nRequirement already satisfied, skipping upgrade: packaging in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (19.2)\nRequirement already satisfied, skipping upgrade: scipy in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (1.1.0)\nRequirement already satisfied, skipping upgrade: scikit-learn in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.20.3)\nRequirement already satisfied, skipping upgrade: numpy in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (1.16.2)\nRequirement already satisfied, skipping upgrade: matplotlib in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (3.1.1)\nRequirement already satisfied, skipping upgrade: tqdm>4.25.0 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (4.36.1)\nRequirement already satisfied, skipping upgrade: scikit-image in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.16.1)\nRequirement already satisfied, skipping upgrade: ipython in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (7.8.0)\nRequirement already satisfied, skipping upgrade: interpret-core[dash,debug,decisiontree,ebm,lime,linear,notebook,plotly,required,sensitivity,shap,treeinterpreter]>=0.1.18 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret>=0.1.17->interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.1.18)\nRequirement already satisfied, skipping upgrade: python-dateutil>=2.5.0 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from pandas->interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (2.8.0)\nRequirement already satisfied, skipping upgrade: pytz>=2011k in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from pandas->interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (2019.3)\nRequirement already satisfied, skipping upgrade: six in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from packaging->interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (1.12.0)\nRequirement already satisfied, skipping upgrade: pyparsing>=2.0.2 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from packaging->interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (2.4.2)\nRequirement already satisfied, skipping upgrade: kiwisolver>=1.0.1 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from matplotlib->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (1.1.0)\nRequirement already satisfied, skipping upgrade: cycler>=0.10 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from matplotlib->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.10.0)\nRequirement already satisfied, skipping upgrade: imageio>=2.3.0 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from scikit-image->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (2.6.0)\nRequirement already satisfied, skipping upgrade: pillow>=4.3.0 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from scikit-image->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (6.2.0)\nRequirement already satisfied, skipping upgrade: PyWavelets>=0.4.0 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from scikit-image->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (1.0.3)\nRequirement already satisfied, skipping upgrade: networkx>=2.0 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from scikit-image->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (2.3)\nRequirement already satisfied, skipping upgrade: pygments in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from ipython->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (2.4.2)\nRequirement already satisfied, skipping upgrade: pexpect; sys_platform != \"win32\" in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from ipython->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (4.7.0)\nRequirement already satisfied, skipping upgrade: prompt-toolkit<2.1.0,>=2.0.0 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from ipython->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (2.0.10)\nRequirement already satisfied, skipping upgrade: backcall in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from ipython->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.1.0)\nRequirement already satisfied, skipping upgrade: decorator in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from ipython->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (4.4.0)\nRequirement already satisfied, skipping upgrade: setuptools>=18.5 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from ipython->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (41.4.0)\nRequirement already satisfied, skipping upgrade: jedi>=0.10 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from ipython->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.15.1)\nRequirement already satisfied, skipping upgrade: traitlets>=4.2 in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from ipython->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (4.3.3)\nRequirement already satisfied, skipping upgrade: pickleshare in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from ipython->shap<=0.29.3,>=0.20.0->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (0.7.5)\nRequirement already satisfied, skipping upgrade: dash>=1.0.0; extra == \"dash\" in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret-core[dash,debug,decisiontree,ebm,lime,linear,notebook,plotly,required,sensitivity,shap,treeinterpreter]>=0.1.18->interpret>=0.1.17->interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (1.4.0)\nRequirement already satisfied, skipping upgrade: dash-table>=4.1.0; extra == \"dash\" in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret-core[dash,debug,decisiontree,ebm,lime,linear,notebook,plotly,required,sensitivity,shap,treeinterpreter]>=0.1.18->interpret>=0.1.17->interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (4.4.0)\nRequirement already satisfied, skipping upgrade: gevent>=1.3.6; extra == \"dash\" in /anaconda/envs/azureml_py36/lib/python3.6/site-packages (from interpret-core[dash,debug,decisiontree,ebm,lime,linear,notebook,plotly,required,sensitivity,shap,treeinterpreter]>=0.1.18->interpret>=0.1.17->interpret-community==0.1.0.2->azureml-interpret==1.0.69.*->azureml.contrib.interpret) (1.4.0)\n"
]
],
[
[
"After installing packages, you must close and reopen the notebook as well as restarting the kernel.\n\nLet's make sure we have the right verisons",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nimport interpret_community\n\nprint(tf.version.VERSION)",
"1.14.0\n"
],
[
"# Check core SDK version number\nimport azureml.core\n\nprint(\"SDK version:\", azureml.core.VERSION)",
"SDK version: 1.0.69\n"
]
],
[
[
"## Connect To Workspace\n\nJust like in the previous tutorials, we will need to connect to a [workspace](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.workspace(class)?view=azure-ml-py).\n\nThe following code will allow you to create a workspace if you don't already have one created. You must have an Azure subscription to create a workspace:\n\n```python\nfrom azureml.core import Workspace\nws = Workspace.create(name='myworkspace',\n subscription_id='<azure-subscription-id>',\n resource_group='myresourcegroup',\n create_resource_group=True,\n location='eastus2')\n```\n\n**If you are running this on a Notebook VM, you can import the existing workspace.**",
"_____no_output_____"
]
],
[
[
"from azureml.core import Workspace\n\nws = Workspace.from_config()\nprint(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')",
"107835-aml-ws\naml-rg-107835\nsouthcentralus\n07a3b836-0813-4c05-afd4-3a7ab00358d9\n"
]
],
[
[
"> **Note:** that the above commands reads a config.json file that exists by default within the Notebook VM. If you are running this locally or want to use a different workspace, you must add a config file to your project directory. The config file should have the following schema:\n\n```\n {\n \"subscription_id\": \"<SUBSCRIPTION-ID>\",\n \"resource_group\": \"<RESOURCE-GROUP>\",\n \"workspace_name\": \"<WORKSPACE-NAME>\"\n }\n```",
"_____no_output_____"
],
[
"## Create An Experiment\n\n**Experiment** is a logical container in an Azure ML Workspace. It hosts run records which can include run metrics and output artifacts from your experiments.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Experiment\nexperiment_name = 'explainer-remote-run-tfworld19'\nexperiment = Experiment(workspace=ws, name=experiment_name)",
"_____no_output_____"
]
],
[
[
"## Create Compute Target\n\nA [compute target](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.computetarget?view=azure-ml-py) is a designated compute resource/environment where you run your training script or host your service deployment. This location may be your local machine or a cloud-based compute resource. Compute targets can be reused across the workspace for different runs and experiments. \n\n**If you completed tutorial 1 of this series, then you should have already created a compute target and can skip this step**\n\nOtherwise, run the cell below to create an auto-scaling [Azure Machine Learning Compute](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.compute.amlcompute?view=azure-ml-py) cluster, which is a managed-compute infrastructure that allows the user to easily create a single or multi-node compute. To create the cluster, we need to specify the following parameters:\n\n- `vm_size`: The is the type of GPUs that we want to use in our cluster. For this tutorial, we will use **Standard_NC12s_v3 (NVIDIA V100) GPU Machines** .\n- `idle_seconds_before_scaledown`: This is the number of seconds before a node will scale down in our auto-scaling cluster. We will set this to **6000** seconds. \n- `min_nodes`: This is the minimum numbers of nodes that the cluster will have. To avoid paying for compute while they are not being used, we will set this to **0** nodes.\n- `max_modes`: This is the maximum number of nodes that the cluster will scale up to. Will will set this to **2** nodes.\n\n**When jobs are submitted to the cluster it takes approximately 5 minutes to allocate new nodes** ",
"_____no_output_____"
]
],
[
[
"from azureml.core.compute import AmlCompute, ComputeTarget\n\ncluster_name = 'v100cluster'\ncompute_config = AmlCompute.provisioning_configuration(vm_size='Standard_NC12s_v3', \n idle_seconds_before_scaledown=6000,\n min_nodes=0, \n max_nodes=2)\n\ncompute_target = ComputeTarget.create(ws, cluster_name, compute_config)\ncompute_target.wait_for_completion(show_output=True)",
"Succeeded\nAmlCompute wait for completion finished\nMinimum number of nodes requested have been provisioned\n"
]
],
[
[
"**If you already have the compute target created, then you can directly run this cell.**",
"_____no_output_____"
]
],
[
[
"compute_target = ws.compute_targets['v100cluster']",
"_____no_output_____"
]
],
[
[
"## Submit Experiment Run\n\nNow that our compute is ready, we can begin to submit our run.",
"_____no_output_____"
],
[
"### Create project directory\n\nCreate a directory that will contain all the necessary code from your local machine that you will need access to on the remote resource. This includes the training script, and any additional files your training script depends on",
"_____no_output_____"
]
],
[
[
"import os\nimport shutil\n\nproject_folder = './TFworld-explainer-remote-run-on-amlcompute'\nos.makedirs(project_folder, exist_ok=True)\nshutil.copy('train_explain-model.py', project_folder)",
"_____no_output_____"
]
],
[
[
"### Submit job to cluster",
"_____no_output_____"
]
],
[
[
"from azureml.core.runconfig import RunConfiguration\nfrom azureml.core.conda_dependencies import CondaDependencies\nfrom azureml.core.runconfig import DEFAULT_CPU_IMAGE\n\n# create a new runconfig object\nrun_config = RunConfiguration()\n\n# signal that you want to use our cluster to execute script.\nrun_config.target = compute_target\n\n# enable Docker \nrun_config.environment.docker.enabled = True\n\n# set Docker base image to the default CPU-based image\nrun_config.environment.docker.base_image = DEFAULT_CPU_IMAGE\n\n# use conda_dependencies.yml to create a conda environment in the Docker image for execution\nrun_config.environment.python.user_managed_dependencies = False\n\n\npip_packages = [\n 'azureml-defaults', 'azureml-core', 'azureml-telemetry',\n 'azureml-dataprep', 'sklearn', 'sklearn-pandas', 'tensorflow==1.14.0',\n 'azureml-contrib-interpret', 'azureml-interpret'\n]\n\n\nindex_url = 'https://azuremlsdktestpypi.azureedge.net/sdk-release/Candidate/604C89A437BA41BD942B4F46D9A3591D/'\nrun_config.environment.python.conda_dependencies = CondaDependencies.create(pip_packages=pip_packages,\n pin_sdk_version=False, \n pip_indexurl=index_url)\n\n\n\n# Now submit a run on AmlCompute\nfrom azureml.core.script_run_config import ScriptRunConfig\n\nscript_run_config = ScriptRunConfig(source_directory=project_folder,\n script='train_explain-model.py',\n run_config=run_config)\n\nrun = experiment.submit(script_run_config)\n\n# Show run details\nrun",
"_____no_output_____"
]
],
[
[
"Note: if you need to cancel a run, you can follow [these instructions](https://aka.ms/aml-docs-cancel-run).",
"_____no_output_____"
]
],
[
[
"from azureml.widgets import RunDetails\nRunDetails(run).show()",
"_____no_output_____"
]
],
[
[
"## Download \nDownload model explanation data.",
"_____no_output_____"
]
],
[
[
"from azureml.contrib.interpret.explanation.explanation_client import ExplanationClient\n\n# Get model explanation data\nclient = ExplanationClient.from_run(run)\nglobal_explanation = client.download_model_explanation()\nlocal_importance_values = global_explanation.local_importance_values\nexpected_values = global_explanation.expected_values\n",
"_____no_output_____"
],
[
"# Or you can use the saved run.id to retrive the feature importance values\nclient = ExplanationClient.from_run_id(ws, experiment_name, run.id)\nglobal_explanation = client.download_model_explanation()\nlocal_importance_values = global_explanation.local_importance_values\nexpected_values = global_explanation.expected_values",
"_____no_output_____"
],
[
"# Get the top k (e.g., 4) most important features with their importance values\nglobal_explanation_topk = client.download_model_explanation(top_k=4)\nglobal_importance_values = global_explanation_topk.get_ranked_global_values()\nglobal_importance_names = global_explanation_topk.get_ranked_global_names()",
"_____no_output_____"
],
[
"print('global importance values: {}'.format(global_importance_values))\nprint('global importance names: {}'.format(global_importance_names))",
"_____no_output_____"
],
[
"# Get the top k (e.g., 4) most important features with their importance values\nglobal_explanation = client.download_model_explanation()\nglobal_importance_values = global_explanation.get_ranked_global_values()\nglobal_importance_names = global_explanation.get_ranked_global_names()",
"_____no_output_____"
],
[
"print('global importance values: {}'.format(global_importance_values))\nprint('global importance names: {}'.format(global_importance_names))",
"global importance values: [0.03999193825435882, 0.031464853252919395, 0.02760060189002182, 0.02456048385916402, 0.02258847868616334, 0.022035631877649273, 0.020207199700294994, 0.020114264275080666, 0.019977203398518766, 0.019378221757655807, 0.0170920545860935, 0.015884334486342123, 0.01586617894132825, 0.013408480313220787, 0.012007829060718718, 0.011751867982559418, 0.011463914137255388, 0.011372582275944364, 0.01032799605886111, 0.010208142977892548, 0.010004060575232718, 0.009948627988387974, 0.008879074315566815, 0.008483158706590357, 0.007304193859418363, 0.0056123067810683784, 0.005469643877212432, 0.005419917839260414, 0.004600788428833444, 0.0044333516100935]\nglobal importance names: ['OverTime', 'MaritalStatus', 'EducationField', 'JobRole', 'YearsInCurrentRole', 'Age', 'JobSatisfaction', 'EnvironmentSatisfaction', 'RelationshipSatisfaction', 'TrainingTimesLastYear', 'JobInvolvement', 'WorkLifeBalance', 'DistanceFromHome', 'Department', 'NumCompaniesWorked', 'JobLevel', 'StockOptionLevel', 'YearsSinceLastPromotion', 'YearsWithCurrManager', 'MonthlyIncome', 'TotalWorkingYears', 'DailyRate', 'YearsAtCompany', 'BusinessTravel', 'Gender', 'MonthlyRate', 'PerformanceRating', 'PercentSalaryHike', 'HourlyRate', 'Education']\n"
],
[
"print(global_explanation.get_feature_importance_dict())",
"{'OverTime': 0.03999193825435882, 'MaritalStatus': 0.031464853252919395, 'EducationField': 0.02760060189002182, 'JobRole': 0.02456048385916402, 'YearsInCurrentRole': 0.02258847868616334, 'Age': 0.022035631877649273, 'JobSatisfaction': 0.020207199700294994, 'EnvironmentSatisfaction': 0.020114264275080666, 'RelationshipSatisfaction': 0.019977203398518766, 'TrainingTimesLastYear': 0.019378221757655807, 'JobInvolvement': 0.0170920545860935, 'WorkLifeBalance': 0.015884334486342123, 'DistanceFromHome': 0.01586617894132825, 'Department': 0.013408480313220787, 'NumCompaniesWorked': 0.012007829060718718, 'JobLevel': 0.011751867982559418, 'StockOptionLevel': 0.011463914137255388, 'YearsSinceLastPromotion': 0.011372582275944364, 'YearsWithCurrManager': 0.01032799605886111, 'MonthlyIncome': 0.010208142977892548, 'TotalWorkingYears': 0.010004060575232718, 'DailyRate': 0.009948627988387974, 'YearsAtCompany': 0.008879074315566815, 'BusinessTravel': 0.008483158706590357, 'Gender': 0.007304193859418363, 'MonthlyRate': 0.0056123067810683784, 'PerformanceRating': 0.005469643877212432, 'PercentSalaryHike': 0.005419917839260414, 'HourlyRate': 0.004600788428833444, 'Education': 0.0044333516100935}\n"
]
]
] | [
"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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccd05a147a9344911c41d8f07917529af37749e | 2,120 | ipynb | Jupyter Notebook | Keylock.ipynb | emresolaaksu/random_pass_generator | b1c5a4e5babf0842a10aeb4dbcc86e53348925c2 | [
"MIT"
] | null | null | null | Keylock.ipynb | emresolaaksu/random_pass_generator | b1c5a4e5babf0842a10aeb4dbcc86e53348925c2 | [
"MIT"
] | null | null | null | Keylock.ipynb | emresolaaksu/random_pass_generator | b1c5a4e5babf0842a10aeb4dbcc86e53348925c2 | [
"MIT"
] | null | null | null | 28.266667 | 238 | 0.465566 | [
[
[
"<a href=\"https://colab.research.google.com/github/emresolaaksu/random_pass_generator/blob/main/Keylock.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import random\n\nlength_of_pass = int(input(\"Enter lenght of the password! \"))\n\nif length_of_pass > (126 - 33) + 1:\n print(\"Are You An İdiot\")\n exit()\n\npass_list = []\n\nwhile len(pass_list) < length_of_pass:\n\n numbers = random.randint(0,1000000000)\n numbers_modded = numbers % (127-33)\n numbers_shifted = numbers_modded + 33\n pass_list.append(chr(numbers_shifted))\n pass_list = list(dict.fromkeys(pass_list))\n\npass_str = ''.join(map(str, pass_list))\nprint(\"Your Password İs = \", pass_str)",
"Enter lenght of the password! 8\n['?', '-', '&', 'w', 'g', '^', '>', ']'] 8\nYour Password İs = ?-&wg^>]\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
]
] |
eccd1f46f3b96860895024a5e785be2c0befcc9e | 26,929 | ipynb | Jupyter Notebook | Notes/.ipynb_checkpoints/EECS325Notes-checkpoint.ipynb | gentsk77/EECS325 | f6c81c25af12f67dac897112e07ee7e690540269 | [
"MIT"
] | null | null | null | Notes/.ipynb_checkpoints/EECS325Notes-checkpoint.ipynb | gentsk77/EECS325 | f6c81c25af12f67dac897112e07ee7e690540269 | [
"MIT"
] | null | null | null | Notes/.ipynb_checkpoints/EECS325Notes-checkpoint.ipynb | gentsk77/EECS325 | f6c81c25af12f67dac897112e07ee7e690540269 | [
"MIT"
] | null | null | null | 38.360399 | 247 | 0.622155 | [
[
[
"# EECS325 Computer Network\n",
"_____no_output_____"
],
[
"# Jan 15, Tuesday",
"_____no_output_____"
],
[
"Refer to the syllbus available on canvas.\n# Chapter One: Introduction\n",
"_____no_output_____"
],
[
"## Internet as an example of network systems\n\n\n- `Routers` and `switches` are pretty much the same now days.\n\n- Devices not automatically connected. Need the `ISPs`.\n\n- Need `protocol` (the standards) to have a formatted signals. \n\n- Also need internet standards to define the entity\n\n",
"_____no_output_____"
],
[
"## Protocol \n- `Protocal`: define the interactions between two end systems or entities (message to be sent and received etc.)\n- `Internet protocol`: defines the standard of internetworks communication\n- Set up connection with internet protocol request (eg: TCP) between your pc and the server. Once the connection is setup, you are allowed to get to the file corresponded to the link\n- `TCP request` checks if you are authorized to receive the file.",
"_____no_output_____"
],
[
"## Network Structure\n\n- Different network system on the edge, connected by different ISPs.\n\n- `Routers`: routers within different ISPs relay/forward traffic from your pc/desktop. Routers transmit data, provide scalability, security, etc.\n\n- `Network edge`: the end of the communication\n\n- `Bandwidth`: determines the performance(speed) of your access network\n\n",
"_____no_output_____"
],
[
"## Access Network Type\n\n### Digital subscriber line (DSL)\n\nDSL modem -- DSLAM(receive all different signals with different frequencies)\n\ntelephone network -- DSLAM(receive all different signals with different frequencies)\n\n### Cable network\n\nyour cable modem -- cable headend\n\n### Difference:\n\n- `DSL`: dedicated link, transmission rate slow\n\n- `Cable`: link shared by multiple users; transmission rate faster\n\n- Both DSL and Cable network carry data generated by different signals, thus need `frequency division multiplexing` to differentiate channels \n\n#### Frequency Division Multiplexing (FDM)\n\nSince all signals(video, data, control messages) are mixed together, need to differentiate them with FDM. \n\n#### Hyrid Fiber Coax (HFC)\n\nProvide asymmetric up/downstream services\n\n### Your home network\n\n[Wired devices with ethernet interface (eg: laptop, desktop)] -- [router(transmit data, provide scalability, security, etc.)] -- [cable/DSL modem] -- ....\n\n[Wireless devices] -- [wireless access] -- [router] -- [cable/DSL modem] -ethernet switch- [institutional modem (-- institutional mail, web servers, etc.)] -institutional link to ISP- ...\n\n### Enterprise network\n\nHas institutional mail, web servers; high transmission rate\n\n---",
"_____no_output_____"
],
[
"# Jan 17, Thursday",
"_____no_output_____"
],
[
"### Wireless LANs\n\n- Cover smaller area. Has three different protocols that support different transmission rate\n\n- `Bandwidth`: limited by actual channel (wireless/wired, wired > wireless), different frequencies for wireless channels, cable network determined by the material of the cable\n\n### Wide-area Wireless Access\n\neg: your cellular data. smaller capacity, cover larger area. provided by different carriers",
"_____no_output_____"
],
[
"### Process of Sending Data Packets\n\n[App message] -break into smaller packets of L bits, with transmission rate R- [router]",
"_____no_output_____"
],
[
"## Physical Media\n\n### Coaxial Cable \n\n- Bidirectional: support bidirectional data transmission\n\n- Broadband: support multiple channels on cable; HFC\n\n### Fiber optic cable\n\n- Higher speed, lower error rate\n\n### Radio\n\n- Bidirectional\n- Propogation environment effects: easily affected by the environment. Reflection, interference, obstruction by objects\n- `Terrestrial microwave`\n- `LAN`\n- `Wide area`\n- `Satellite`",
"_____no_output_____"
],
[
"## The Network Core\n\n### Packet switching: store and forward\n\n- `Packets`: consist of bits (basic units)\n- Packets transmitted in the link as 0/1 signals bit by bit. \n- Some bits arrive at the routers faster than the rest, it will wait until all the bits arrive in the router before the next transmission\n- Transmission time: length of packet L/ transmission rate R\n- Routers are connected to multiple end users. Packets of the end users have to be queued, which can be dropped(lost) if the memory(buffer) fills up. \n\n#### Routing\n\n- `Routing`: determines where the packets should be heading to (making decision) by the `routing algorithm` according to a `local forwarding table`\n- `local forwarding table` a mapped table contains the following\n - `header value`: the address of the destination, does not change, is shared by the whole system \n - `output link`: the link the packet should be transmitted to, local to each router\n- `Routing algorithm`: distributed algorithm that only knows the condition of neighbouring routers. \n- Routers need to exchange information to determine the destination. \n- Routers do not know the buffer condition of each other. \n- The routing process is completed by software of routers.\n\n#### Forwarding\n\n- The action the router performs according to local forwarding table \n- The forwarding process is completed by the hardware of routers.\n\n### Circuit switching\n\n- Dedicated resource shared by users. \n- Resources remain idle if not in use. \n- Circuit switching is no longer in use right now. Mostly replaced by packet switching. ",
"_____no_output_____"
],
[
"#### FDM (Frequency Devision Multiplexing)\n\n- Equally devide the bandwidth for the users so that all the users can use the channels all the time\n\n#### TDM (Time Devision Multiplexing)\n\n- Each user use the entire bandwidth exclusively for a very small amount of time periodically, so the users cannot realize that they are sharing the bandwidth with other users \n- Widely applied in the Operating System, eg: Linux (reserve different time intervals for multiple users)",
"_____no_output_____"
],
[
"### Packet Switching VS Circuit Switching\n\nrefer to the slides for an example \n\n#### Circuit Switching\n\nOnly allow limited amount of users. Reserve resources for limited users.\n\n#### Packet Switching\n\n- Allow resource to be shared. Thus could accomodate more users.\n\n- Could have `congestions`: `packet lost/delay`, need good protocol for reliable data transfer, `congestion control`.\n",
"_____no_output_____"
],
[
"## Internet Structure: network of networks \n\nWe need to connect different access networks with each other. But how?\n\nWith a global ISP? NO, need the same agreement \n\nWith __different core ISPs interconnected to each other__? YES!\n\n- Different `core ISPs` connected by `peering links` and `IXP hubs` (internet exchanging point) \n\n- Core ISPs connected to `regional ISPs`\n\n- `Content providers` (eg: Google) with multiple `data centers` connected to IXP and connected directly to the regional ISPs \n\n- `POP`: point of presence. Frequently used by content providers to get closer to their end users\n\n",
"_____no_output_____"
],
[
"## Four Sources of Delay \n\nThe sequence is: arrive at router - `process` - `queueing` - `transmission` - leave router - `propogation` - arrive at next router\n\n### Process Delay\n\nThe time the router takes to process the entire packet upon arrival \n\n### Transmission Delay\n\nThe time the router takes to process and direct the packet bits by bits in the router (The time the toll station takes to serve the entire caravan car by car)\n\n\n### Queueing Delay\n\n- Time interval between arrival and being sent again while waiting in the router. (The time one caravan waits while the former caravan is being serviced)\n- Calculate length of queueing delay by determining the value of average queueing delay\n- Can lead to data loss.\n\n### Propogation Delay\n\n- The time it takes the packets to travel in the link from one router to the next. (The time the caravan takes to travel to the next toll station)\n- Usually very fast\n\n### Packet Loss \n\n- `Packet loss`: packets can be dropped due to insufficient `buffer size`\n- `Buffer size`: the storage size of packets that could be stored in the router\n\n## Throughput\n\nRate (bits/time unit) at which bits transferred between sender/receiver\n\n### Bottleneck link\n\nLink on end to end path that has smaller transmission rate\n\n---",
"_____no_output_____"
],
[
"# January 22, Tuesday \n\nRevisiting slides on last Thursday",
"_____no_output_____"
],
[
"## Protocol Layers\n\n- Used to organize all the pieces of `network structure`: host, routers, etc. \n- `Moduralization` ensures that `individual layers` would not affect the functions of other layers \n- The layers can work completely independently by themselves, but also able to communicate information\n- But we may not always divide all the functions into independant layers.\n \n### Internet Protocol Stack: End to End Protocol\n\n#### Application\n- Supporting the network applications. \n- eg: FTP, HTTP, SMTP \n- HTTP is developed based on TCP \n\n#### Transport\n\n- Interprocess data transfer\n- Only happens between two end systems to let two processes communicate with each other\n- eg: TCP (guarantee reliability of data transfer, contains congestion control), UDP\n- TCP is slower than UDP. Most game/game streaming applications use UDP rather than TCP. But TCP contains reliability, whereas UDP does not guarantee\n- Not necessary for the routers/switches to support the transport layer protocols, although most devices now days can also support such layer. \n\n#### Network\n\n- Both routing and forwarding are in this layer. \n- Routing of datagrams from source to destination.\n- Only IP protocol\n- IP protocol: consists of different routing protocols \n\n#### Link\n\n- Only used to transfer data within two neighbouring network elements (router to router, switches to switches, etc.)\n- Do not connect two end users\n- eg: Ethernet (wired connection), 802.11 (WiFi, wireless connection), PPP \n\n#### Physical \n\n- Basically are just bits on the wire",
"_____no_output_____"
],
[
"### ISO/OSI reference model\n\n- Includes two extra layers\n- Just below the application layer\n- Not necessary for all applications, thus can be combined with application layer\n\n#### Presentation \n\n- Allows application to describe/interpret the meaning of data: encryption, compression etc. \n\n#### Session\n\n- Synchronization, checkpointing, recovery of data exchange",
"_____no_output_____"
],
[
"### Process of data transfer between end users\n- Data are transferred with encapsulation\n- Each layer generates a specific type of header and attach it to the message being tranferred. The header contains layer specific information (eg: ip address by the network layer), and only corresponding layers can decrypt it.\n- While the headers are being transferred between different layers, some of the headers might be changed, such as the data link layer, and the network layer for specific applications\n- Tranport layer information (header) will never be changed\n- The process: [application layer] - message -> [transport layer] - segment -> [network layer] - datagram -> [link layer] - frame -> [physical layer]\n- Each layer can only see the correct corresponded header\n- The layers try to interpret/decapsulate the packets even though they might not understand??\n- [source] - encapsulated packets -> [router]\n- Router drop the network header and check how to head the packet to the next link\n- [router] - encapsulated packets -> [destination]\n- The destination end user decrpt the packet encapsulated with layers of headers",
"_____no_output_____"
],
[
"## Network Security\n### Malware\nHide behind your system/application.\n- Virus: need to be exectued to infect your devices \n- Worm: if your pc is infected, your mobile device can also get infected\n- Spywre: record yoru keystrokes \n- Once infected, the host can be enrolled in botnet, used by the hacker to attack servers illegally. \n- By hacking other machines, the hackers utilize others' devices and hide their identities. \n\n---",
"_____no_output_____"
],
[
"# Jan 24, Thursday",
"_____no_output_____"
],
[
"### Denial of Service (DoS)\n\n### Packet \"Sniffing\"",
"_____no_output_____"
],
[
"# Chapter Two: Application Layer",
"_____no_output_____"
],
[
"## Application Architecture",
"_____no_output_____"
],
[
"### Client-Server Architecture\n#### Server\n- Always-on host\n- Have a permanent public IP address in most cases\n- Have more servers to cater more requests: have data centers\n- Data center: a building stores only servers, routers, switches etc. An approach for server providers to scale up?\n\n\n#### Client\n- Dynamic IP adress depanding on server\n- Does not communicate directly with each other. \n- [Client] - message -> [Server] - message -> [Client]\n\n#### Communication process\n- Clients initiate connections\n- Server waits to be contracted by clients\n\n### P2P architecture\n- No need to always deploy the servers for the client to share contents\n- End systems can directly communicate with each other\n- Peers request and provide serivce to each other, which pertains self scalability: both new capacity and demands are brought to the architecture when new peers show up\n\n#### Process of communication\n- Start inter-process communication defiend by OS\n- Process: program running within a host\n- Processes in different host communicate by exchanging messages\n\n### Sockets\n\n### Addressing processes\n- Processes need identifier to receive messages\n- Identifier: containing IP address and prot number associated with the process on host \n- Port number eg: HTTP (80) \n\n### App-layer protocol defines\n\n- REFER TO THE SLIDES DUDE\n\n### What transport services the app required\n\n- Interlayer requirements that should be done by layer collaboration\n- Also see the slides\n\n### Internet transport protocols services\n- Reliable transport: between sending and receiving sides \n- Flow control: by receiving side(?) to make sure receivers do not get overwhelmed by sender messages\n- Congestion control: by sending side to make sure internet resources are also shared by other end systems ",
"_____no_output_____"
],
[
"## Web and HTTP\n\n- Internet objects are addressable by URL which consists of a host name + a path name\n\n### HTTP connections\n- HTTP is using TCP protocal\n- Client initiates TCP connection to server using port 80\n- Server accpets the TCP connection from client\n- HTTP messages (application layer protocol messages) exchanged between browser (HTTP client) and Web server\n- The server closes the TCP connection (sometimes the client can also close the connetion by accident, in which case the server might not konw, and the server will close the connection after a certain amount of time -- connection timeout)\n- HTTP is stateless, servers do not need to maintain a certain state of past client requests\n- SSL: provides secured library for TCP. TCP does not use SSL by default\n- HTTPs is TCP using SSL?\n\n#### Non persistant HTTP connections\n- At most one object can be sent over TCP connection, which will be closed by the server after one request message and resoponse\n- To download multiple objects, the HTTP client should build up multiple connections\n- After downloading the first object receiving from the server, in order to download a second object, the HTTP client should establish the TCP connection with the server again, and repeat sending out requests etc. \n- RTT (Run Trip Time): the time it takes the small packet to tranvel from the client to the server and then back from the server to the packet. Cannot avoid this time no matter what.\n- Initiate TCP connection: 1 RTT (must happen before sending HTTP request)\n- Send HTTP request and receive file back from server: 1 RTT + some time to transmit the file\n- Cost 2 RTT to request and receive in total \n\n#### Persistant HTTP connections\n- Only need to set up the TCP connection once, all later on request and response can be communicated within the connection established\n- Cost only 1 RTT roughly\n\n### HTTP request message\n- Two types: request and response \n- Applying the ASCII format, which is a human readable format\n\n#### General format\n- Reuest line\n- Header lines\n- Body: contains the user input if the user is using post method \n - eg: user input typed in the search box \n - POST method\n - URL method\n\n### HTTP response message\n- Status line: versions of HTTP protocol the server is running\n- Header lines: \n- Data objects requested by the client\n\n#### Response status codes\n- 200: ok\n- 301: requested object moved permanently, new location will be specified in this message\n- 400: bad request, probably due to mistyping in the URL. Can also be due to something wrong on the server side\n - The API exists, but you called the wrong API request\n- 404: requested file not provided by the server side :(((((((\n - Also means API error. The API does not even exist\n- 505: some internal errors in the server :(\n\n---",
"_____no_output_____"
],
[
"# Jan 29, Tuesday",
"_____no_output_____"
],
[
"## User-server state: cookies\n- Servers do not maintain information for clients\n- Not so convenient, we want to keep track of the user data and let the server identify specific user\n- eg: unique user ID on a website\n - your browser will use that ID upon the HTTP request and the server would know who you are \n- Refer to slides on the process of HTTP request with cookies and cookies specific information sent by server (kept in backend database)\n\n### Cookies can be used for\n- authorization\n- shopping carts\n- can also violate privacy, can be shut down\n\n## Web Caches (proxy server)\n- Satisfying user request without involving origin server\n\n### Forward Proxy (we are talking about this one)\n- Closer to the client side\n- Client first go through cache for information\n - Client send HTTP request to proxy server\n - Proxy server process data\n - If information available, send HTTP response back to the client directly\n - Else request information from origin server with HTTP request, receive HTTP response from origin server\n- Reduces traffic through the public internet, saves client time\n- Through HTTP protocol and origin server, the proxy server would know what to keep and how long to keep\n\n### Reverse Proxy\n- Closer to the server side \n\n### Caching Example\n\n#### Without web cache mechanism\n- Without using caching, access link becomes most utilized by the browsers to go directly to the origin server\n- Total delay = internet delay + access delay + LAN delay\n\n#### Increase access link capacity without web cache\n- Time it takes to go through access link decreased to 10%!\n\n#### Install local web cache server\n- Attach a cache server to the local institutional server\n- How to calculate total delay\n - Total delay that could be processed by the local web cache\n - Total delay that could only be processed by the origin server\n \n### Conditional GET\n- Goal: he server won't send object if cache has up-to-date cached version in the web cache server\n - No object transmission delay\n - Lower link utilization\n- Proxy request the date of data last modified from server\n- Server send back the date of data last modified \n - If the object has not been modified since the date specified\n - HTTP 304 Not modified\n - No object attached\n - If the object has been modified\n - HTTP 200 OK\n - Object included ",
"_____no_output_____"
],
[
"## Electronic Mail\n- Three major components\n - user agents\n - the mail readers\n - composing, editing, reading mail messages \n - eg: Outlook, iPhone mail client\n - mail server\n - mailbox contains incoming messages for user\n - message queue of outgoing messages to be sent\n - SMTP (simple mail transfer protocol)\n - protocol between mail servers for exchanging mail messages\n - client side of the mail server send message to server side of the mail server with SMTP protocol\n- Steps of sending emails\n 1. User sender compose email on UA\n 2. UA use SMTP protocol to transfer message to mail server of user sender\n 3. Client side of sender's mail server connect with server side of recepient's mail server with SMTP protocol (the handshaking process)\n 4. Sender's mail server transfers the mail message to recepeint's mail server with TCP connection\n 5. Closure of the connection\n 6. Recepient's mail server send the message to recepient's UA \n \n### SMTP protocol \n- SMTP uses persistent connections\n- SMTP client side [push] information to other mail server\n - unlike HTTP which pull information\n- multiple objects sent in multipart message\n\n### Mail message format\n- RFC 822: standard for text message format\n - header lines: To, From, Subject\n - Note: different from SMTP commands MAIL FROM, RCPT TO, etc.\n - body: the message body content, ASCII character only \n \n \n---",
"_____no_output_____"
]
]
] | [
"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"
]
] |
eccd333d3ddc953a96f2d8e544eccfb4b02589d7 | 15,647 | ipynb | Jupyter Notebook | Advection_dffusion_reaction.ipynb | snuesslein/Positive_RK_Reproducibility | fa508766bb166a62e87e0c43f0f5887b9890e899 | [
"MIT"
] | 1 | 2020-05-10T13:54:10.000Z | 2020-05-10T13:54:10.000Z | Advection_dffusion_reaction.ipynb | snuesslein/Positive_RK_Reproducibility | fa508766bb166a62e87e0c43f0f5887b9890e899 | [
"MIT"
] | 2 | 2020-05-11T12:55:22.000Z | 2021-03-01T10:43:02.000Z | Advection_dffusion_reaction.ipynb | snuesslein/Positive_RK_Reproducibility | fa508766bb166a62e87e0c43f0f5887b9890e899 | [
"MIT"
] | 2 | 2020-05-10T09:22:15.000Z | 2020-05-11T07:02:46.000Z | 29.137803 | 127 | 0.468205 | [
[
[
"# Advection-diffusion-reaction system used by Kopecz and Meister (2019)",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom nodepy import rk\nimport cvxpy as cp\n\nimport plot_fkt\nplot_fkt.setup_plt()\n\nimport numpy.linalg as linalg\n\nfrom numba import jit, float64, stencil\n\n#Extrapolation method\nex2 = rk.extrap(2,'implicit euler').__num__()\nex3 = rk.extrap(3,'implicit euler').__num__()\nex4 = rk.extrap(4,'implicit euler').__num__()\nex5 = rk.extrap(5,'implicit euler').__num__()\nex6 = rk.extrap(6,'implicit euler').__num__()\nex8 = rk.extrap(8,'implicit euler').__num__()\n\nfrom OrderCondition import *\nfrom RKimple import *\nimport utils ",
"_____no_output_____"
],
[
"def plot_stepsizes(status,slot = None):\n\n #At first plot the stepsizes according to the evalautions\n dt = np.array(status['dt_calc'])\n tol_met = np.array(status['sc'])\n neg = np.array(status['b'])\n n= np.arange(len(dt))\n plt.figure()\n plt.plot(n,dt,'-k')\n plt.plot(n[tol_met=='m'],dt[tol_met=='m'],'bx',label ='steps')\n plt.plot(n[tol_met!='m'],dt[tol_met!='m'],'rx',label ='tol not met')\n plt.plot(n[neg=='r'],dt[neg=='r'],'ro',label = 'infeasible')\n plt.xlim(slot)\n plt.grid()\n plt.legend()\n\n #plot error and change in commparison\n plt.figure()\n change = np.array(status['change'])\n error = np.array(status['error'])\n old_min = np.array(status['old_min'])\n plt.plot(change,'x',label = 'Change')\n plt.plot(error,'x',label = 'Error')\n plt.plot(old_min,'x' ,label = 'Min')\n plt.xlim(slot)\n #plt.ylim([-0,1])\n plt.grid()\n plt.legend()",
"_____no_output_____"
],
[
"beta1 = (0.7/5)\nbeta2 = (0.3/5)\n#compute a totla error out of error and change and use this as inmut for a single PI controller\ndef dt_logic_PI(stepsize_control,dt_old,dt_adp,error,change,success,tol_met):\n print('error:',error)\n\n facmax = 1.2\n facmin = 0.1\n fac = 10\n w_change = 1\n #compute total error\n if change == None:\n change = 10 #maybe set her some other value\n error_tot = error + w_change*change\n \n dt_old = dt_logic_PI.dt_old \n\n #Control\n Tol = stepsize_control.a_tol\n dt = dt_old *(Tol/error_tot)**beta1*(dt_logic_PI.error_tot_old[-1]/error_tot)**beta2\n \n #Update storage vaiables\n dt_logic_PI.error_tot_old[:-1] = dt_logic_PI.error_tot_old[1:] \n dt_logic_PI.error_tot_old[-1] = error_tot\n\n \n dt = min(facmax*dt_old,max(facmin*dt_old,dt))\n dt_logic_PI.dt_old=dt\n return max(dt,stepsize_control.dt_min)\n\n\ndt_logic_PI.error_tot_old = np.zeros(3)\ndt_logic_PI.dt_old=0.01",
"_____no_output_____"
],
[
"# Now we implement the advection Diffusion equation\n# To achieve compatibility with the existing time integrators the u's are stored in a single vector\n\n#u= [u_1^T,u_2^T,u_3^T,u_4^T]^T\n\n@stencil\ndef kernel_adv(a,dxi):\n return dxi*(a[0]-a[-1])\n\n@stencil\ndef kernel_dif(a,dxqi):\n return dxqi*(a[-1]-2*a[0]+a[1])\n\n@jit(float64[:](float64[:],float64),nopython=True)\ndef adv(u,dxi):\n du = kernel_adv(u,dxi)\n \n #Periodic\n du[0]=dxi*(u[0]-u[-1])\n return du\n\n@jit(float64[:](float64[:],float64),nopython=True)\ndef dif(u,dxqi):\n du = kernel_dif(u,dxqi)\n\n #Periodic\n du[0] =dxqi*(u[-1]-2*u[0]+u[1])\n du[-1]=dxqi*(u[-2]-2*u[-1]+u[0])\n \n return du\n\n\n@jit(float64[:](float64,float64[:]),nopython=True)\ndef f_ADP(t,u):\n a=1e-2\n d=1e-6\n \n du = np.zeros_like(u)\n \n #split u in different parts\n N = len(u)//4\n u1 = u[0:N]\n u2 = u[N:2*N]\n u3 = u[2*N:3*N]\n u4 = u[3*N:4*N]\n \n #calculate Production\n pu1 = 0.01*u2+0.01*u3+0.003*u4-(u1*u2)/(0.01+u1)\n pu2 = -0.01*u2-0.5*(1-np.exp(-1.21*u2**2))*u3-0.05*u2+(u1*u2)/(0.01+u1)\n pu3 = 0.5*(1-np.exp(-1.21*u2**2))*u3-0.01*u3-0.02*u3\n pu4 = 0.05*u2 + 0.02*u3-0.003*u4\n \n #Advection and Diffusion\n dx=1/N #periodic boundary\n dxq = dx**2\n \n \n du[0:N] = -a*adv(u1,1/dx)+d*dif(u1,1/dxq) + pu1 \n du[N:2*N] = -a*adv(u2,1/dx)+d*dif(u2,1/dxq) + pu2\n du[2*N:3*N] = -a*adv(u3,1/dx)+d*dif(u3,1/dxq) + pu3\n du[3*N:4*N] = -a*adv(u4,1/dx)+d*dif(u4,1/dxq) + pu4 \n \n return du\n\n\n#Added a modification to the function that alters the behavior for values <0.005 to make shure that\n#there is no second root of the stageeqation with negative us\n@jit(float64[:](float64,float64[:]),nopython=True)\ndef f_ADP_pos(t,u):\n a=1e-2\n d=1e-6\n \n du = np.zeros_like(u)\n \n #split u in different parts\n N = len(u)//4\n u1 = np.where(u[0:N]>-0.005,u[0:N],-0.005) #\n u2 = np.where(u[N:2*N]>-0.005,u[N:2*N],-0.005)\n u3 = np.where(u[2*N:3*N]>-0.005,u[2*N:3*N],-0.005)\n u4 = np.where(u[3*N:4*N]>-0.005,u[3*N:4*N],-0.005)\n \n \n \n #calculate Production\n pu1 = 0.01*u2+0.01*u3+0.003*u4-(u1*u2)/(0.01+u1)\n pu2 = -0.01*u2-0.5*(1-np.exp(-1.21*u2**2))*u3-0.05*u2+(u1*u2)/(0.01+u1)\n pu3 = 0.5*(1-np.exp(-1.21*u2**2))*u3-0.01*u3-0.02*u3\n pu4 = 0.05*u2 + 0.02*u3-0.003*u4\n \n #Advection and Diffusion\n dx=1/N #periodic boundary\n dxq = dx**2\n \n \n du[0:N] = -a*adv(u1,1/dx)+d*dif(u1,1/dxq) + pu1 \n du[N:2*N] = -a*adv(u2,1/dx)+d*dif(u2,1/dxq) + pu2\n du[2*N:3*N] = -a*adv(u3,1/dx)+d*dif(u3,1/dxq) + pu3\n du[3*N:4*N] = -a*adv(u4,1/dx)+d*dif(u4,1/dxq) + pu4 \n \n return du",
"_____no_output_____"
],
[
"#Additional functions for better handling of System\n\ndef initial_ADP(N):\n start = np.array([8.,2.,1.,4.])\n u1s = np.zeros(N)\n u1s[0:N//2]=7\n u1s[N//2:]=8\n\n u2s = np.zeros(N)\n u2s[N//2:-1]=2\n\n u3s = np.zeros(N)\n u3s[N//2:]=1\n\n u4s = np.zeros(N)\n u4s[0:N//2]=1\n u4s[N//2:]=4\n\n\n u0=np.ones(N*4)\n u0[0:N] = u1s\n u0[N:2*N] = u2s\n u0[2*N:3*N] = u3s\n u0[3*N:4*N] = u4s\n \n return u0\n \n\ndef plot_image(u,t):\n N = u.shape[0]//4\n cmap=plt.get_cmap('plasma')\n display(u.shape)\n extent=[0,t[-1],1,0]\n plt.subplot(4, 1, 1)\n plt.imshow(u[0:N,:],cmap=cmap,extent=extent)\n plt.colorbar()\n plt.axis('tight')\n plt.subplot(4, 1, 2)\n plt.imshow(u[N:2*N,:],cmap=cmap,extent=extent)\n plt.colorbar()\n plt.axis('tight')\n plt.subplot(4, 1, 3)\n plt.imshow(u[2*N:3*N,:],cmap=cmap,extent=extent)\n plt.colorbar()\n plt.axis('tight')\n plt.subplot(4, 1, 4)\n plt.imshow(u[3*N:4*N,:],cmap=cmap,extent=extent)\n plt.colorbar()\n plt.axis('tight')\n\ndef plot_at_time(u,T,legend=True):\n n=np.argmin(np.abs(t-T))\n \n\n print(n,t[n])\n\n\n u_ = u[:,n]\n N= len(u_)//4\n\n u1 = u_[0:N]\n u2 = u_[N:2*N]\n u3 = u_[2*N:3*N]\n u4 = u_[3*N:4*N]\n\n x = np.linspace(0,1,101)\n plt.plot(x,np.append(u1,u1[:1]),label='$u_1$')\n plt.plot(x,np.append(u2,u2[:1]),label='$u_2$')\n plt.plot(x,np.append(u3,u3[:1]),label='$u_3$')\n plt.plot(x,np.append(u4,u4[:1]),label='$u_4$')\n plt.xlabel('$x$')\n plt.ylabel('$u_i$')\n plt.xlim([0,1])\n \n #plt.title('T='+str(T))\n if legend:\n plt.legend()",
"_____no_output_____"
],
[
"N =100\nx = np.linspace(0,1,num = N)\ndx=1/(N) # no -1 because of periodic boundary\n\n\nu0 = initial_ADP(N)\n\nex3.bhat=np.array([-1,1,1,0,0,0])\n\ndt_logic_PI.error_tot_old = np.zeros(3)\ndt_logic_PI.dt_old=0.01\n\nsolver_ex3 = Solver(rkm = ex3,\n dt = 0.01,\n t_final = 60,\n b_fixed=False,\n tol_neg=1e-8,\n tol_change = 5,\n p = [3,2,1],\n theta = [1],\n solver = cp.MOSEK,\n convex=False,\n solver_eqs=solver_nonlinear_arg,\n LP_opts = {'reduce':True,'verbose':False})\n\nproblem_ADR = Problem(f=f_ADP_pos,\n u0=u0,\n minval=0,\n maxval=np.inf)\n\ncontrol = StepsizeControl(dt_min = 0,dt_max = np.infty,a_tol = 0.01,r_tol=0.001,f = dt_logic_PI\n ,tol_reqect = 10*0.01)\n\nbeta1 = (0.7/5)\nbeta2 = (0.5/5)\n\nstatus,t,u,b,KK = RK_integrate(solver=solver_ex3,problem=problem_ADR,stepsize_control=control,verbose=True,dumpK=True)\n\nt = np.array(t)\nu = np.array(u).T\nb = np.array(b).T\nutils.show_status(status)",
"_____no_output_____"
],
[
"for T in (0,9,18,27,50):\n plt.figure(figsize=[6.4, 4])\n plot_at_time(u,T,legend=(T==0))\n plt.savefig('ADP_sol_'+\"{:02d}\".format(T)+'.pdf',bbox_inches = \"tight\")",
"_____no_output_____"
],
[
"plot_stepsizes(status)",
"_____no_output_____"
],
[
"rkm = ex3\nplt.figure(figsize=[6.4*2, 4.7*2])\ndt = np.array(status['dt_calc'])\nold_min = np.array(status['old_min'])\nnew_min = np.array(status['new_min'])\n\nchange = np.array(status['change'])\nerror = np.array(status['error']) \n\nplt.subplot(5,1,1)\nplt.plot(t,dt,'xC1')\nplt.ylabel('$\\Delta t$')\nplt.grid()\nplt.xlim([-1,61])\nplt.ylim([-0.2,1.8])\nplt.gca().tick_params(labelbottom=False) \n\n\nplt.subplot(5,1,2)\nplt.plot(t,old_min,'x',label='before adaptation')\nplt.plot(t,new_min,'+',label='after adaptation')\nplt.grid()\nplt.xlim([-1,61])\nax = plt.gca()\nax.set_yticks((0,-0.0025,-0.0050))\nax.set_yticklabels(('$0$', r'$-2.5 \\times 10^{-3}$', r'$-5 \\times 10^{-3}$'))\nplt.legend()\nplt.ylabel(r'$\\min(u)$')\nplt.gca().tick_params(labelbottom=False) \n\n\nplt.subplot(5,1,3)\nplt.plot(t,error,'x',label = '$err_{T}$')\nplt.plot(t,change,'+',label = r'$\\delta$')\nplt.xlim([-1,61])\nplt.grid()\nplt.legend()\nplt.ylabel('Error')\nplt.gca().tick_params(labelbottom=False) \n\n\n\nplt.subplot(5,1,4)\nb_orig = rkm.b.copy()\nb_orig.shape=(len(b_orig),1)\nplt.plot(t[1:],np.linalg.norm((b-b_orig),axis=0,ord=1)[1:],'xC1')\nplt.xlim([-1,61])\n#plt.ylim([-2.5,2])\nplt.ylabel(r'$\\| \\tilde{b} - b \\|_1 $')\nplt.grid()\nplt.gca().tick_params(labelbottom=False) \n\n\nplt.subplot(5,1,5)\nmass = np.sum(u,axis=0)\nplt.plot(t,mass-mass[0],'xC1')\nplt.ylabel(r'$\\sum u - \\sum u(0)$')#\nax = plt.gca()\nax.set_yticks((0,-2.5e-13,-5e-13))\nax.set_yticklabels(('$0$', r'$-2.5 \\times 10^{-13}$',r'$-5 \\times 10^{-13}$'))\nplt.ylim([-7e-13,2e-13])\nplt.xlim([-1,61])\nplt.grid()\n\nplt.xlabel('$t$')\n\nplt.savefig('ADP_stepsize_b.pdf',bbox_inches = \"tight\")",
"_____no_output_____"
],
[
"#Stats:\nbs=np.array(status['b'])\nprint('Number of steps:',np.sum(bs!=None))\nprint('Number of adaptions:',np.sum(bs=='c'))\nnp.min(u)",
"_____no_output_____"
],
[
"#check linear invariants:\nmass = np.sum(u,axis=0)",
"_____no_output_____"
],
[
"plt.plot(t,mass-mass[0])",
"_____no_output_____"
],
[
"mass[1]",
"_____no_output_____"
],
[
"print(utils.get_max_iter_h(status))",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccd4b482022df2d00fdb8338735840dc112c7d3 | 34,475 | ipynb | Jupyter Notebook | bls_quarterly_county.ipynb | rebekahanne/consumption_and_tradewar | 6be32968ca2b9c2e49ae142cc5c363010e14fd43 | [
"MIT"
] | null | null | null | bls_quarterly_county.ipynb | rebekahanne/consumption_and_tradewar | 6be32968ca2b9c2e49ae142cc5c363010e14fd43 | [
"MIT"
] | null | null | null | bls_quarterly_county.ipynb | rebekahanne/consumption_and_tradewar | 6be32968ca2b9c2e49ae142cc5c363010e14fd43 | [
"MIT"
] | 1 | 2019-12-12T10:53:22.000Z | 2019-12-12T10:53:22.000Z | 34.544088 | 273 | 0.405047 | [
[
[
"import pandas as pd # data package\nimport matplotlib.pyplot as plt # graphics \nimport datetime as dt\nimport numpy as np\n\nimport requests, io # internet and input tools \nimport zipfile as zf # zip file tools \nimport os \n\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\nimport statsmodels.formula.api as smf\nfrom linearmodels.iv import IV2SLS\nfrom linearmodels.panel import PanelOLS",
"_____no_output_____"
]
],
[
[
"### Overview. \n\nThis file essentially grabs the month by county files from the [Quarterly Census of Employment and Wages](https://www.bls.gov/cew/) files from the BLS and then creates employment measures at the county-level, monthly frequency. A couple of comments about the code:\n\n - In the funciton ``clean_bls_quarter`` there is a line to be uncommented or not depending upon if I want a dataset with goods employment or total employment. Future enhancements of this notebook should just return one dataframe with both.\n \n \n - It can accomadate the 2016 data (and further back if modified). Currently it just uses the 2017, 2018, and 2019 (which only have Q1 values. See the relese calander when updates will be made.\n \n### Step 1\n\nBring in the trade/tariff data for which we will merge stuff....",
"_____no_output_____"
]
],
[
[
"cwd = os.getcwd()\n\ntrade_data = pq.read_table(cwd + \"\\\\data\\\\total_trade_data.parquet\").to_pandas()\n\ntrade_data[\"time\"] = pd.to_datetime(trade_data.time)\n\ntrade_data.set_index([\"area_fips\", \"time\"],inplace = True)",
"_____no_output_____"
],
[
"trade_data.head()\n\nexposure = pd.qcut(trade_data.xs('2018-12-1', level=1).tariff, 4 ,labels = False)\n\nmost_exposed = exposure[exposure == 3].index.tolist()\n\ntrade_data.loc[most_exposed].xs('2018-12-1', level=1).tariff.mean()",
"_____no_output_____"
]
],
[
[
"This is ultra-clunky. Should fix in the future. But it takes names (which is how the BLS files are written) and then will map them into a datatime value.",
"_____no_output_____"
]
],
[
[
"empl_time_dict_16 = {\"January Employment\":dt.datetime(2016,1,1),\n \"February Employment\":dt.datetime(2016,2,1),\n \"March Employment\":dt.datetime(2016,3,1),\n \"April Employment\":dt.datetime(2016,4,1),\n \"May Employment\":dt.datetime(2016,5,1),\n \"June Employment\":dt.datetime(2016,6,1),\n \"July Employment\":dt.datetime(2016,7,1),\n \"August Employment\":dt.datetime(2016,8,1),\n \"September Employment\":dt.datetime(2016,9,1),\n \"October Employment\":dt.datetime(2016,10,1),\n \"November Employment\":dt.datetime(2016,11,1),\n \"December Employment\":dt.datetime(2016,12,1),}",
"_____no_output_____"
],
[
"empl_time_dict_17 = {\"January Employment\":dt.datetime(2017,1,1),\n \"February Employment\":dt.datetime(2017,2,1),\n \"March Employment\":dt.datetime(2017,3,1),\n \"April Employment\":dt.datetime(2017,4,1),\n \"May Employment\":dt.datetime(2017,5,1),\n \"June Employment\":dt.datetime(2017,6,1),\n \"July Employment\":dt.datetime(2017,7,1),\n \"August Employment\":dt.datetime(2017,8,1),\n \"September Employment\":dt.datetime(2017,9,1),\n \"October Employment\":dt.datetime(2017,10,1),\n \"November Employment\":dt.datetime(2017,11,1),\n \"December Employment\":dt.datetime(2017,12,1),}\n\nempl_time_dict_18 = {\"January Employment\":dt.datetime(2018,1,1),\n \"February Employment\":dt.datetime(2018,2,1),\n \"March Employment\":dt.datetime(2018,3,1),\n \"April Employment\":dt.datetime(2018,4,1),\n \"May Employment\":dt.datetime(2018,5,1),\n \"June Employment\":dt.datetime(2018,6,1),\n \"July Employment\":dt.datetime(2018,7,1),\n \"August Employment\":dt.datetime(2018,8,1),\n \"September Employment\":dt.datetime(2018,9,1),\n \"October Employment\":dt.datetime(2018,10,1),\n \"November Employment\":dt.datetime(2018,11,1),\n \"December Employment\":dt.datetime(2018,12,1),}\n\nempl_time_dict_19 = {\"January Employment\":dt.datetime(2019,1,1),\n \"February Employment\":dt.datetime(2019,2,1),\n \"March Employment\":dt.datetime(2019,3,1),}\n\nclistQ1 = ['Area\\nCode','NAICS','Qtr','January Employment', 'February Employment',\n 'March Employment', 'Total Quarterly Wages', 'Average Weekly Wage','Own',\"Area Type\"]",
"_____no_output_____"
]
],
[
[
"### Step 2: Download\n\nThis downloads the ``.zip`` files for which we can grab the data. They are all in excell format. ",
"_____no_output_____"
]
],
[
[
"#url = \"https://data.bls.gov/cew/data/files/2016/xls/2016_all_county_high_level.zip\"\n# This will read in the annual, single file. It's big, but has all we want...\n\n#r = requests.get(url) \n\n# convert bytes to zip file \n#bls_q2016 = zf.ZipFile(io.BytesIO(r.content)) \n#bls_q2016.extractall(cwd + \"\\\\bls_files\")\n\nurl = \"https://data.bls.gov/cew/data/files/2017/xls/2017_all_county_high_level.zip\"\n# This will read in the annual, single file. It's big, but has all we want...\n\nr = requests.get(url) \n\n# convert bytes to zip file \nbls_q2017 = zf.ZipFile(io.BytesIO(r.content)) \nbls_q2017.extractall(cwd + \"\\\\bls_files\")\n\nurl = \"https://data.bls.gov/cew/data/files/2018/xls/2018_all_county_high_level.zip\"\n\nr = requests.get(url) \n\nbls_q2018 = zf.ZipFile(io.BytesIO(r.content)) \nbls_q2018.extractall(cwd + \"\\\\bls_files\")",
"_____no_output_____"
],
[
"url = \"https://data.bls.gov/cew/data/files/2019/xls/2019_all_county_high_level.zip\"\n\nr = requests.get(url) \n\nbls_q2019 = zf.ZipFile(io.BytesIO(r.content)) \nbls_q2019.extractall(cwd + \"\\\\bls_files\")",
"_____no_output_____"
],
[
"bls_q2019.filelist",
"_____no_output_____"
]
],
[
[
" ### Step 3: Clean and Shape it\n \n Below is a function that takes in an excell sheet and does what we want to it. Then below we will work through a for loop over all the sheets.",
"_____no_output_____"
]
],
[
[
"def clean_bls_quarter(excell_sheet, time_dict):\n\n df = pd.read_excel(excell_sheet, sheet_name = \"US_St_Cn_MSA\")\n\n# Take only private\n\n df = df[df[\"Own\"] == 5] \n\n# Take aggregate\n\n df = df[df[\"NAICS\"] == 101] # Take goods producing \n \n #df = df[df[\"NAICS\"] == 10] # Take all employment in all sectors\n\n# Take only counties \n df = df[df[\"Area Type\"] == \"County\"] \n\n df.rename({\"Area\\nCode\": \"GEOFIPS\"},axis = 1, inplace = True)\n\n df[\"GEOFIPS\"] = df[\"GEOFIPS\"].astype(int)\n\n df.set_index(\"GEOFIPS\", inplace = True)\n\n df = df.reindex(trade_data.index.get_level_values(0).unique().astype(int).tolist())\n\n df = df.iloc[:,[13,14,15]].reset_index()\n # This grabs only values we want, i.e. the employment for that quarter. So for example,\n # in Q1, 13 = January, 14 = Febuary, 15 = March. And so forth for Q2...\n\n df = df.melt(\"GEOFIPS\")\n\n df.replace(time_dict,inplace = True)\n\n df.rename({\"variable\":\"time\", \"value\":\"emply_month\", \"GEOFIPS\": \"area_fips\"}, axis = 1, inplace = True)\n \n df[\"area_fips\"] = df[\"area_fips\"].astype(str)\n \n df.set_index([\"area_fips\", \"time\"], inplace = True)\n \n\n return df",
"_____no_output_____"
]
],
[
[
"Then given the function above, work through the file list. ",
"_____no_output_____"
]
],
[
[
"#root_name = cwd + \"\\\\bls_files\\\\\"\n\n#root_name = root_name + \"allhlcn16\"\n\n#quarter = [\"1\",\"2\",\"3\",\"4\"]\n\ndf = pd.DataFrame([])\n\n#for item in quarter:\n \n# file_name = root_name + item + \".xlsx\"\n \n# df = df.append(clean_bls_quarter(file_name,empl_time_dict_16))\n \n############################################################################\n\nroot_name = cwd + \"\\\\bls_files\\\\\"\n\nroot_name = root_name + \"allhlcn17\"\n\nquarter = [\"1\",\"2\",\"3\",\"4\"]\n\nfor item in quarter:\n \n file_name = root_name + item + \".xlsx\"\n \n df = df.append(clean_bls_quarter(file_name,empl_time_dict_17))\n \n############################################################################ \nroot_name = cwd + \"\\\\bls_files\\\\\"\n\nroot_name = root_name + \"allhlcn18\"\n\nquarter = [\"1\",\"2\",\"3\",\"4\"]\n\nfor item in quarter:\n \n file_name = root_name + item + \".xlsx\"\n \n df = df.append(clean_bls_quarter(file_name,empl_time_dict_18))\n \n############################################################################ \nroot_name = cwd + \"\\\\bls_files\\\\\"\n\nroot_name = root_name + \"allhlcn19\"\n\nquarter = [\"1\"]\n\nfor item in quarter:\n \n file_name = root_name + item + \".xlsx\"\n \n df = df.append(clean_bls_quarter(file_name,empl_time_dict_19))",
"_____no_output_____"
]
],
[
[
"Then just checksome stuff, reshape, then save for the analysis part. Note how this is working (again clunky), if you want the goods employment, uncomment out that. If you want total employment do the other one.",
"_____no_output_____"
]
],
[
[
"df.tail()",
"_____no_output_____"
],
[
"df.sort_values([\"area_fips\", \"time\"], inplace = True)",
"_____no_output_____"
],
[
"trade_employ = trade_data.merge(df, left_index = True, right_index = True, how = \"left\")\n# This is a place to be mindfull about time period, if we want ",
"_____no_output_____"
],
[
"file_path = os.getcwd() + \"\\\\data\\\\trade_employment_goods.parquet\"\n\npq.write_table(pa.Table.from_pandas(trade_employ.reset_index()), file_path)\n\n#file_path = os.getcwd() + \"\\\\data\\\\trade_employment_all.parquet\"\n\n#pq.write_table(pa.Table.from_pandas(trade_employ.reset_index()), file_path)",
"_____no_output_____"
],
[
"trade_employ.corr()",
"_____no_output_____"
],
[
"trade_employ.tail(25)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccd68d9900be285f1471611db223af1524b1fdd | 24,941 | ipynb | Jupyter Notebook | _sources/curriculum-notebooks/Mathematics/DataRepresentation/data-representation.ipynb | mlamoureux/CallystoJBook | 058080e1bb6370c0a072ed1c0ded96fe1e2947de | [
"CC0-1.0"
] | 21 | 2018-08-23T20:41:26.000Z | 2021-04-21T02:27:13.000Z | _sources/curriculum-notebooks/Mathematics/DataRepresentation/data-representation.ipynb | mlamoureux/CallystoJBook | 058080e1bb6370c0a072ed1c0ded96fe1e2947de | [
"CC0-1.0"
] | 113 | 2018-07-23T21:05:00.000Z | 2022-03-16T23:40:08.000Z | _sources/curriculum-notebooks/Mathematics/DataRepresentation/data-representation.ipynb | mlamoureux/CallystoJBook | 058080e1bb6370c0a072ed1c0ded96fe1e2947de | [
"CC0-1.0"
] | 11 | 2018-11-20T16:36:59.000Z | 2021-08-03T12:58:55.000Z | 24,941 | 24,941 | 0.66096 | [
[
[
"\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/DataRepresentation/data-representation.ipynb&depth=1\" target=\"_parent\"><img src=\"https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true\" width=\"123\" height=\"24\" alt=\"Open in Callysto\"/></a>",
"_____no_output_____"
]
],
[
[
"from IPython.display import HTML\nhide_me = ''\nHTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n if (code_show) {\n $('div.input').each(function(id) {\n el = $(this).find('.cm-variable:first');\n if (id == 0 || el.text() == 'hide_me') {\n $(this).hide();\n }\n });\n $('div.output_prompt').css('opacity', 0);\n } else {\n $('div.input').each(function(id) {\n $(this).show();\n });\n $('div.output_prompt').css('opacity', 1);\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\n<form action=\"javascript:code_toggle()\"><input style=\"opacity:1\" type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>''')",
"_____no_output_____"
],
[
"hide_me\n\nfrom ipywidgets import interact\nimport ipywidgets as widgets\nimport IPython\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\nimport plotly as py\nimport plotly.graph_objs as go\n\nimport pylab\n\nfrom IPython.display import Image, HTML, YouTubeVideo",
"_____no_output_____"
]
],
[
[
"# Data Representation in Graphs\n\n##### Grade 8 curriculum",
"_____no_output_____"
],
[
"Data plays an ever-increasing role in our lives. Like it or not, we are faced with numerical information every day, and we use it to make decisions. Should I be glad that 9 out of 10 dentists recommend my toothpaste? What about the 10th? A new study says that going for a run at 5 a.m. every morning reduces my risk of catching some terrible disease by 15%. Is it worth getting out of bed?\n\nIt's often hard to find meaning in data if it's just a bunch of numbers on a page, so we make that easier by using graphs. Graphs take data and turn them into pictures—bars, lines, circles, and more. But not all graphs are created equal; some do their jobs better than others. A good graph is a perfect tool for understanding a problem. A bad graph can be confusing, or in some cases, intentionally misleading.\n\nGraphs are used every day by news media, politicians, and scientists to convey information. Some use them well; some do not. In this notebook, we'll explore good and bad examples of graphs. By working through the examples and exercises in this notebook, you'll learn:\n\n- how to decide which type of graph is best for a given set of data;\n- how to identify flawed or misleading graphs;\n- how some of those flaws can be corrected; and\n- most importantly, how to read a graph and apply its meaning to your everyday life.\n",
"_____no_output_____"
],
[
"*Many of the examples of bad graphs you'll find below are from the media (and one source in particular). This notebook isn't trying to criticize these sources. They just happen to have given us a lot of examples to choose from.*",
"_____no_output_____"
],
[
"## What makes a good graph?\n\nFirst and most importantly, a graph should allow a reader, at a glance, to understand the information it's meant to convey. A good graph is like a good movie scene; if it's set up well, you can tell exactly what you're supposed to know. Some basic parts of a successful graph are:\n\n1. A title\n2. Proper labels\n3. Axes that start at zero (if numerical)\n4. Percentages that add to 100%\n5. Easy to read\n6. Use of colours, *as long as they are meaningful* and not just for show\n\n*By the way: **axes** (ACK-sees) are the reference lines on a graph. They're where you find the names of the categories (usually at the bottom) and the number scale (usually on the left). One of these lines is called an **axis** (ACK-sis).*",
"_____no_output_____"
],
[
"For a quick overview of different types of graphs and simple examples, you might find this \n[Math Is Fun](https://www.mathsisfun.com/data/pictographs.html) article useful. We'll look at some of these kinds of graphs below. You'll notice many of them are eye-catching, and they also convey information really well.\n\nOne of the places you'll find a lot of graphs is in political coverage. The media (and many of their readers/viewers) love a good \"horse race\". For example, this [CBC federal poll tracking article](http://www.cbc.ca/news/politics/poll-tracker-federal-poll-averages-and-seat-projections-1.4171977) uses almost every type of graph you'll find in this notebook.\n\nWe'll also explore how a graph can be used to [mislead someone](http://teachersinstitute.yale.edu/curriculum/units/2008/6/08.06.06.x.html). We hope this notebook will help you learn how to avoid using misleading graphs, as well as how to avoid being misled yourself.\n\nThere's even a [wall of shame](http://bcuchta.com/wall_of_shame/) with some of the worst graphs and charts!",
"_____no_output_____"
],
[
"## Let's look at bar graphs\n\n### What is a bar graph?\n\nA bar graph is a graph where data is separated into categories, and those categories are shown as bars with different heights. It's a very useful graph, but it can also easily be misleading.\n\n\n\nfrom [Math is Fun](https://mathsisfun.com/data/images/bar-graph-fruit.svg)\n\n### When are bar graphs good to use?\n\nBar graphs can be used in many ways, but they usually show one piece of information collected from many groups or categories. For example, they might show the number of hours worked by people in different age groups, or how many grey shirts each girl in a class owns.\n\n### What are some ways to misuse bar graphs?\n\n1. **Make the scale on the graph start above zero.** This makes small differences between bars look much bigger than they really are.\n2. **Change the width of the bars to make one category look more important.** This gives one bar more area, which looks like more data.\n3. **Remove the space between the bars** (that's a **histogram**). Histograms are used for a different kind of data set, and so they are read in a different way.\n\nHere's an example of a poorly made bar graph. It shows the total welfare (support money) received by people in the US from 2009 to 2011. Each year is divided into 4 three-month pieces called **quarters**.\n\n\n\nfrom [MediaMatters](https://www.mediamatters.org/fox-news/today-dishonest-fox-charts-government-aid-edition)\n\nWhat makes this a bad bar graph?\n1. Their scale starts at 94 million insead of 0.\n2. The bars are in 3D, making their values harder to read.\n3. Their y-axis has 8 labels, but there are 10 levels on the graph (including the top and bottom).\n\nWhoever made this graph probably wanted the viewer to think welfare in the US is rising faster than it really is. Now, let's ask ourselves:\n\n- What can we change to make this a good graph?\n- How does it look after we make these changes?\n- Why might the original creators not want to use our new graph?\n\nOne way we can improve this graph is by changing where its scale starts. Play with the slider below to see how the graph looks with different scales.",
"_____no_output_____"
],
[
"*Slide the slider below to change the starting point of the $y$-axis. The initial position corresponds to the graph in the image above. As you move the slider to the left, the starting point for the $y$-axis is reduced to zero.*\n\n*Warning: This graph is slow to respond, please be patient with it.*",
"_____no_output_____"
]
],
[
[
"hide_me\n\ncolumns = ['09-Q1', '09-Q2', '09-Q3', '09-Q4', '10-Q1', '10-Q2','10-Q3', '10-Q4', '11-Q1', '11-Q2']\n#fig, ax = plt.subplots()\ndef plot(yaxis=94):\n y = [97, 98, 99, 101, 104, 105, 106, 107, 107.5, 108]\n x = np.arange(len(y))\n fig, ax = plt.subplots(figsize=(10,4))\n ax.bar(x, y, width=0.5)\n ax.set_xticks(x)\n ax.set_xticklabels(columns)\n ax.set_ylim((yaxis,110))\n ax.set_title(\"Federal Welfare Received in the US\")\n \ninteract(plot, yaxis=(0,90), continuous_update = True, wait = False)\n#plt.show()",
"_____no_output_____"
]
],
[
[
"## Let's look at pictographs\n\n### What is a pictograph?\n\nA pictograph is a way to show data using images, where each image represents a certain number of things that are being measured. They look a lot like bar graphs and they can be horizontal or vertical too.\n\n\n\nfrom [Math is Fun](https://www.mathsisfun.com/data/images/pictograph-tennis.svg)\n\n### Why do people like to use pictographs?\n\nThe main reason is because the pictures offer something for readers to connect with other than just a row of coloured bars.\n\nAlso, pictographs often work best to show data with small numbers. If everything can be easily expressed with a simple scale like the one above, then a pictograph might be the right choice to represent the data.\n\n### When are pictographs not a good choice?\n\nIn the example above, what if Sam played 46 games instead of 45? This pictogram counts games in steps of 5, so numbers in between these steps might be hard or impossible to show.\n\nA reader might also make a connection with a pictograph that wasn't intended. Let's show this with an example.\n\nOn Halloween, Shayna and Michael went trick-or-treating. Shayna got 18 pieces of candy, and Michael got 36. Their totals are shown in this pictograph:\n\n\n\nfrom [teachersinstitute.yale.edu](http://teachersinstitute.yale.edu/curriculum/units/2008/6/08.06.06.x.html)\n\nAt first, is looks like a fine way to show how much candy each child got. The heights of the candy corn pieces are being used to mark the two amounts. But as a viewer, we don't see just the height—we also see the width. Not only is the second candy corn twice as high, it's also twice as wide, giving it four times the area as the first candy corn. This makes it *look like* Michael got 4 times as much candy as Shayna, even though he only got twice as much.\n\nClick the \"Display\" button below to show a better, more accurate way to represent the same data:",
"_____no_output_____"
]
],
[
[
"hide_me\n\npic = Image('images/CandyCornGraph.png')\nclicker = widgets.Checkbox(value=False, description='Display', disabled=False)\n\ndef checking(a):\n if clicker.value == True:\n IPython.display.display(pic)\n else:\n IPython.display.clear_output()\n IPython.display.display(clicker)\n\nIPython.display.display(clicker)\nclicker.observe(checking, 'value')",
"_____no_output_____"
]
],
[
[
"## Let's look at line graphs\n\n### What is a line graph?\n\nA line graph is a way to show how the measurement of one value responds to changes in another, like how something may change over time. In fact, time is one of the most common variables with a line graph.\n\n\n\nfrom [Math is Fun](https://www.mathsisfun.com/data/images/line-graph-example.svg)\n\n### Why are line graphs useful?\n\nThey show a moving trend with a line that's easy to follow, instead of just dots on a graph. They work best when the trend involves the change of one variable (jobs, temperature, debt) with respect to another (usually time).\n\nIn some cases it can also be useful to plot multiple lines on one graph, usually with different colours to help tell them apart. For example, one might plot polling results for different political parties over time, as with this graph from the CBC:\n\n\n\nfrom [cbc.ca](http://www.cbc.ca/polopoly_fs/1.3265490!/fileImage/httpImage/image.jpg)\n\n\n### How can line graphs go wrong?\n\nA common error with line graphs is unlabelled axes. A graph might show a line that slopes upwards, but without labels, we wouldn't know what is growing or how fast. Also, line graphs can trick us into thinking a trend is linear by spacing out the ticks unevenly on one axis, so that the data points neatly line up. Like this example:\n\n\n\nfrom [Online Stat Book](http://onlinestatbook.com/2/graphing_distributions/graphics/graph2.png)",
"_____no_output_____"
]
],
[
[
"hide_me\n\nfix = widgets.SelectionSlider(options=['original', 'fixed'], value ='original', description='Slide to fix',\n continuous_update=True, orientation='horizontal',)\n\ndef fixing(a):\n if fix.value == 'fixed':\n IPython.display.clear_output()\n IPython.display.display(fix)\n f, ax1 = plt.subplots(1,1,figsize=(10,5))\n ax1.set_title(\"Job Loss by Quarter\")\n ax1.set_xlabel('Months from November 07',fontsize=15)\n ax1.set_ylabel(\"Jobs Lost in Millions\",color='b',fontsize=15)\n x1 = [1, 10, 16, 29]\n y1 = [7,9,13.5,15]\n ax1.plot(x1, y1,\"bo-\")\n plt.legend()\n plt.show()\n else:\n IPython.display.clear_output()\n IPython.display.display(fix)\n f, ax1 = plt.subplots(1,1,figsize=(10,5))\n ax1.set_title(\"Job Loss by Quarter\")\n ax1.set_xlabel('Months from November 07',fontsize=15)\n ax1.set_ylabel(\"Jobs Lost in Millions\",color='b',fontsize=15)\n x1 = [0,7,23,29]\n y1 = [7,9,13.5,15]\n ax1.plot(x1, y1,\"bo-\")\n plt.legend()\n plt.show()\n \nIPython.display.display(fix) \nfix.observe(fixing, 'value')\n\nIPython.display.clear_output()\nIPython.display.display(fix)\nf, ax1 = plt.subplots(1,1,figsize=(10,5))\nax1.set_title(\"Job Loss by Quarter\")\nax1.set_xlabel('Months from November 07',fontsize=15)\nax1.set_ylabel(\"Jobs Lost in Millions\",color='b',fontsize=15)\nx1 = [0,7,23,29]\ny1 = [7,9,13.5,15]\nax1.plot(x1, y1,\"bo-\")\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Let's look at circle graphs\n\n### What is a circle graph?\n\nAlso known as a pie chart, a circle graph is used to show how a total is split into different groups. The whole pie represents the total, and each slice of the pie represents a different group. Each slice gets as much of the pie as its group has of the total—the bigger the slice, the more of the total that group represents.\n\n\n\nfrom [Math is Fun](https://www.mathsisfun.com/data/images/pie-chart-movies.svg)\n\n### Why are circle graphs useful?\n\nThey make it easy to compare group sizes; if there's a biggest or smallest group, that's easy to see, since group sizes are shown as pieces of a whole.\n\n### Why might people not use circle graphs?\n\nTo be displayed as a circle graph, data must be converted into percentages of the total, then into slices of a circle, which is more work than other graphs need. Plus, it's easy to mess up if the data are not converted properly (or at all). Circle graphs are also hard to draw accurately on paper, since you need a protractor to ensure your angles are correct. Some people might even say that any time a circle graph would do, a bar graph would do better, and that the pie chart below is the only acceptable one.\n\n\n\nfrom [Flowing Data](https://i1.wp.com/flowingdata.com/wp-content/uploads/2008/09/Pie-I-have-Eaten.jpg)",
"_____no_output_____"
],
[
"********************\n\n### What's wrong with these graphs?\n\n\n\n[Business Insider](https://amp.businessinsider.com/images/51cb26c469beddf14c000015-750-453.jpg)\n\n\n\n[Flowing Data](http://flowingdata.com/wp-content/uploads/yapb_cache/app15725951258947184.acq6gmp0hf4sowckg80ssc8wg.2xne1totli0w8s8k0o44cs0wc.th.png)\n\n\n\n[Flowing Data](https://i0.wp.com/flowingdata.com/wp-content/uploads/2013/03/130207SuperBowlPoll.jpg?fit=500%2C430&ssl=1)\n",
"_____no_output_____"
],
[
"## What was wrong with these graphs?\n\n1. Mislabeled/Missing axes\n2. Plotted wrong\n3. Hard to read\n4. Numbers don't add to 100%\n5. Wrong data shown",
"_____no_output_____"
],
[
"The video below goes through several examples of bad/misleading graphs (some of them shown in this notebook) and why they are not good representations of the original data.",
"_____no_output_____"
]
],
[
[
"hide_me\n\nYouTubeVideo('1F7gm_BG0iQ')",
"_____no_output_____"
]
],
[
[
"*************\n\n## Practice Questions\n\n### Question 1\n\nA group of kids was asked **what they do first** when they get home from school. The data are shown in the table below. [Data source here](http://www.ur.umich.edu/9900/Apr03_00/7.htm)\n\n| Activity | Percent|\n|-----------------|-----|\n| Eat | 27% |\n| Personal Care | 19% |\n| Watch TV | 15% |\n| Study | 13% |\n| Play | 9% |\n| Other | 17% |",
"_____no_output_____"
]
],
[
[
"hide_me\n\nanswer = widgets.RadioButtons(options=['','circle graph', 'line graph', 'bar graph', 'pictograph'],\n value='', description='Answer:')\nlabels = ['Eat', 'Personal Care', 'Watch TV', 'Study', 'Play', 'Other']\ndata = [0.27, 0.19, 0.15, 0.13, 0.09, 0.17]\n\ndef display():\n print('What would be the best graph to display this set of data?')\n IPython.display.display(answer)\n\ndef check(a):\n IPython.display.clear_output(wait=False)\n display()\n if answer.value == 'circle graph':\n print(\"Correct! Circle graphs are used for percentages.\")\n print(\"Let's see this data in a circle graph.\")\n patches, texts = plt.pie(data, labels=labels)\n plt.axis('equal')\n plt.tight_layout()\n plt.show()\n else:\n if answer.value == 'bar graph':\n print(\"A Bar graph would work, but there's a better option. Try again.\")\n else:\n if answer.value == 'line graph':\n print(\"Line graphs are good for change over time, not percentages. Try again.\")\n else:\n print(\"A pictograph would work if the data was in amounts instead of percentages. Try again.\")\n\ndisplay()\nanswer.observe(check, 'value')",
"_____no_output_____"
]
],
[
[
"### Question 2\n\nA group of kids was asked **how much time** they spend doing different activities after school. The data are shown in the table below. [Data source here](http://www.ur.umich.edu/9900/Apr03_00/7.htm)\n\n| Activity | Time spent (minutes)|\n|-----------------|-----|\n| Reading | 30 |\n| Chores | 30 |\n| Watch TV | 100 |\n| Study | 60 |\n| Play | 74 |\n| Sports | 60 |",
"_____no_output_____"
]
],
[
[
"hide_me\n\nanswer2 = widgets.RadioButtons(options=['','circle graph', 'line graph', 'bar graph', 'pictograph'],\n value='', description='Answer:')\nlabels2 = ['Reading', 'Chores', 'Watch TV', 'Study', 'Play', 'Sports']\ndata2 = [30, 30, 100, 60, 74, 60]\nx = np.arange(len(data2))\n\ndef display2():\n print('What would be the best graph to display this set of data?')\n IPython.display.display(answer2)\n\ndef check(a):\n IPython.display.clear_output(wait=False)\n display2()\n if answer2.value == 'circle graph':\n print(\"A circle graph is used for percentages. Try again.\")\n else:\n if answer2.value == 'bar graph':\n print(\"Correct! A bar graph shows the relation between both parameters in an easy to read format.\")\n print(\"Let's see what that looks like.\")\n plt.bar(x, data2, width = .3)\n plt.xticks(x, labels2)\n plt.ylabel('Time in Minutes')\n plt.title('Time Spent on Afterschool Activities')\n plt.show()\n else:\n if answer2.value == 'line graph':\n print(\"Line graphs are good for change over time. Try again.\")\n else:\n print(\"A pictograph would work, but there's a better option to be more accurate. Try again.\")\n\ndisplay2()\nanswer2.observe(check, 'value')",
"_____no_output_____"
]
],
[
[
"Now that we have seen many examples of both good and bad graphs, let's look at [the worst graphs in science literature](https://www.biostat.wisc.edu/~kbroman/topten_worstgraphs/) and try to figure out why each graph is on the list.\n\n(You can click on a graph to make it bigger. See if you can point out the flaws in these graphs on your own, then click the \"Discussion\" links to learn what's wrong with each graph and why it made it to the list!)",
"_____no_output_____"
],
[
"*Even top academic institutions sometimes produce images that, while they might look impressive, do very little to help us understand the numbers involved in an issue. Try to figure out what's wrong with these\n[infographics from Princeton](http://www.princeton.edu/~ina/infographics/index.html) on your own.*",
"_____no_output_____"
],
[
"## What have we learned?\n\nIn this notebook, we have learned:\n\n* Graphs are great at conveying numerical information\n* Not all types of graphs are created equal\n* Graphs can be manipulated to be misleading\n* How to identify misleading parts of graphs \n* There are steps to create truthful graphs\n\nWith this knowledge, you are able to be more informed when you see any kind of data displayed in a graph. You are also able to create truthful graphs of your own. Keep trying to identify good and bad graphs in your every day life.",
"_____no_output_____"
],
[
"[](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
eccda9405d84eb2d6ef47907ded781c137a9c659 | 10,280 | ipynb | Jupyter Notebook | notebooks/David-App-Playground.ipynb | eppinglen/Triangulator | a71118994c2afff52fe31aab999152b4086e7160 | [
"MIT"
] | null | null | null | notebooks/David-App-Playground.ipynb | eppinglen/Triangulator | a71118994c2afff52fe31aab999152b4086e7160 | [
"MIT"
] | null | null | null | notebooks/David-App-Playground.ipynb | eppinglen/Triangulator | a71118994c2afff52fe31aab999152b4086e7160 | [
"MIT"
] | null | null | null | 33.376623 | 502 | 0.542315 | [
[
[
"## SDS Demo App\nThis app demos the result of the SDS team at the JPIAMR hackathon.",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n#%load_ext line_profiler\n%autoreload 2\nimport jupyterlab_dash\nimport multiprocessing",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n"
],
[
"import pandas as pd\nimport numpy as np\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport random\nimport string\nimport pickle",
"_____no_output_____"
],
[
"def randomString(stringLength=5):\n \"\"\"Generate a random string of fixed length\"\"\"\n letters = string.ascii_lowercase\n return \"\".join(random.choice(letters) for i in range(stringLength))\n\n\ndef calculate_clinician_behavior(\n clin_prescriptions=None, recommendations=None, diagnosis=\"UTI\"\n):\n \"\"\"Calculate the clinician scores for the app\"\"\"\n second_perc = np.random.uniform(0, 0.5, size=100)\n third_perc = 0.5 - second_perc\n doctor_labels = np.array([randomString(5) for i in range(100)])\n df = pd.DataFrame(\n data={\n \"2nd level antibiotics\": second_perc,\n \"3rd level antibiotics\": third_perc,\n \"doctor\": doctor_labels,\n }\n )\n df[\"class\"] = \"Average\"\n df.iloc[30, 3] = \"You\"\n return df",
"_____no_output_____"
],
[
"bars_a = calculate_clinician_behavior().groupby(\"class\").mean().reset_index().melt(\"class\")\nbars_b = calculate_clinician_behavior().groupby(\"class\").mean().reset_index().melt(\"class\")\ndata={'Acute Cystitis Females >12 years old,Uncomplicated': bars_a, 'Pneumonia- Adult: Community acquired, mild to moderate, Outpatient without comorbidity/modifying factors': bars_b}",
"_____no_output_____"
],
[
"with open('../app/static_data.pckl', 'wb') as outf:\n pickle.dump(data, outf)",
"_____no_output_____"
],
[
"with open('../app/static_data.pckl', 'rb') as inf:\n data2 = pickle.load(inf)",
"_____no_output_____"
],
[
"if viewer:\n viewer.terminate()\n del viewer\n del app",
"_____no_output_____"
],
[
"viewer = jupyterlab_dash.AppViewer(port=8099)",
"_____no_output_____"
],
[
"import dash\nimport pickle\nimport plotly.express as px\nimport pandas as pd\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n#diagnosis = ['Acute Cystitis Females >12 years old,Uncomplicated', 'Pneumonia- Adult: Community acquired, mild to moderate, Outpatient without comorbidity/modifying factors']\ndiagnosis_treatments = {'Acute Cystitis Females >12 years old,Uncomplicated': ['1st level - TMP/SMX 1 DS tab po bid for 3 days', '1st level - Trimethoprim 200mg once po daily for 3 days', '1st level - Macrobid 100 mg po bid for 5 days', '2nd level - Amoxicillin 500mg po TID for 7 days', '2nd level - Norfloxacin 400mg po bid for 3 days', '2nd level - Ciprofloxacin 250mg po bid for 3 days', '3rd level - Cephalexin 500mg po bid for 7 days', '3rd level - Levoquin 250mg po daily for 3 days'],\n 'Pneumonia- Adult: Community acquired, mild to moderate, Outpatient without comorbidity/modifying factors': ['1st level - Amoxicillin 1g po tid for 7 days', '2nd level - Doxycycline 100mg po bid day 1 and then qd days 2-7', '2nd level - Azithromycin 250mg 2 tabs day 1 and then one tab days 2-5', '2nd level - Clarithromycin 500mg po once daily for 7 days', '3rd level - Levofloxacin 750mg po qd for 5 days', '3rd level - Moxifloxacin 400mg po once daily for 5 days']\n\n }\ndef pres_behavior_chart(bars):\n fig = px.bar(\n bars,\n x=\"variable\",\n y=\"value\",\n color=\"class\",\n barmode=\"group\",\n )\n fig.layout.xaxis.title = \"Prescriptions for female patients between 20-30 years for the same diagnosis\"\n fig.layout.yaxis.title = \"Percentage of prescriptions for the given class\"\n return fig\n\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\napp.title = 'SDS Decision Helper'\n\napp.layout = html.Div(children=[\n html.Div([\n html.Div([\n html.H4(\"Your diagnosis\"),\n dcc.RadioItems(\n id='diagnosis-options',\n options=[{'label': i, 'value': i} for i in list(diagnosis_treatments.keys())],\n value=list(diagnosis_treatments.keys())[0],\n labelStyle={'display': 'inline-block'}\n ),\n html.Hr()],\n className='six columns')],\n className='row')\n ,\n html.Div([\n html.Div([\n html.H4(\"Your prescription behavior for 2nd and 3rd line antibiotics\"),\n dcc.Graph(id='prescribing-graph')\n ],\n className='six columns'),\n html.Div([\n html.H4(\"Your treatment options\"),\n html.Label(['Recommended antibiotics for your area',\n dcc.Dropdown(id='dropdown-treatments'\n )]),\n html.Hr(),\n html.Button(id='submit-button', n_clicks=0, children='Generate prescription'),\n html.Div(id='output-prescription', children=\"\"),\n html.Hr(),\n html.Button(id='submit-button-final', n_clicks=0, children='SEND prescription'),\n html.Div(id='output-prescription-final', children=\"\")\n ],\n className='six columns')\n ],\n className='row')\n])\n\n\[email protected](Output('output-prescription', 'children'),\n [Input('submit-button', 'n_clicks')],\n [State('dropdown-treatments', 'value')])\ndef send_prescription(n_clicks, prescription):\n if n_clicks > 0:\n return \"Prescription of {} for patient {}\".format(prescription.split('- ')[1], \"Christina Miller, female, 25 years\")\n\n \[email protected](Output('output-prescription-final', 'children'),\n [Input('submit-button-final', 'n_clicks')],\n [State('output-prescription', 'children')])\ndef send_prescription_final(n_clicks, prescription):\n if n_clicks > 0:\n return \"Sent prescription to pharmacy\"\n\n \[email protected](\n Output('dropdown-treatments', 'options'),\n [Input('diagnosis-options', 'value')])\ndef set_dropdown_treatments_1st(selected_diagnosis):\n \n return [{'label': i, 'value': i} for i in diagnosis_treatments[selected_diagnosis]]\n\n\[email protected](\n Output('dropdown-treatments', 'value'),\n [Input('diagnosis-options', 'value')])\ndef set_dropdown_treatments(selected_diagnosis):\n return diagnosis_treatments[selected_diagnosis][0]\n\n\[email protected](\n Output('prescribing-graph', 'figure'),\n [Input('diagnosis-options', 'value')])\ndef plot_prescribing_behavior(diagnosis):\n return pres_behavior_chart(data[diagnosis])\n\n\n\n\nif __name__ == '__main__':\n app.run_server(debug=True, port=8060)",
"_____no_output_____"
],
[
"viewer.show(app)",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccdc25a5707cab38be8a7a962dbcd396e46bf17 | 568,119 | ipynb | Jupyter Notebook | JpytrNb/pdfPlot/GasFrac_BH-Copy1.ipynb | Max-astro/A2Project | 5d40263742133f214936b06b622d08092e694aed | [
"MIT"
] | null | null | null | JpytrNb/pdfPlot/GasFrac_BH-Copy1.ipynb | Max-astro/A2Project | 5d40263742133f214936b06b622d08092e694aed | [
"MIT"
] | null | null | null | JpytrNb/pdfPlot/GasFrac_BH-Copy1.ipynb | Max-astro/A2Project | 5d40263742133f214936b06b622d08092e694aed | [
"MIT"
] | null | null | null | 427.157143 | 54,060 | 0.92788 | [
[
[
"import numpy as np\nimport h5py\nimport json\nimport sys\nsys.path.append('F:\\Linux')\nimport illustris_python as il\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.colors import BoundaryNorm, ListedColormap\n\n\ndef xyline(x, y):\n points = np.array([x, y]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n return segments\n\n\ndef LoadMergHist(simu, subhaloID):\n '''\n return subhalo's main progenitor and merger history with snapshot\n '''\n if (simu == 'TNG') or (simu == 'tng'):\n ldir = 'f:/Linux/localRUN/tng_DiskMerTree/%d.json' % subhaloID\n else:\n ldir = 'f:/Linux/localRUN/il1_DiskMerTree/%d.json' % subhaloID\n \n with open(ldir) as f:\n data = json.load(f)\n \n Main = np.array(data['Main'])\n return dict(zip(Main[:, 0], Main[:, 1])), np.array(data['Mergers'])\n\ndef HistValAndBin(nums, bins, more=0, mask=0):\n if mask == 1:\n reMask = []\n\n val = []\n tmp = nums[nums < bins[1]]\n if mask == 1:\n reMask.append(nums < bins[1])\n val.append(len(tmp))\n\n for i in range(1,len(bins)-1):\n tmp = nums[(nums > bins[i]) & (nums <= bins[i+1])]\n val.append(len(tmp))\n if mask == 1:\n reMask.append((nums > bins[i]) & (nums <= bins[i+1]))\n\n if more == 1:\n tmp = nums[nums > bins[-1]]\n val.append(len(tmp))\n if mask == 1:\n reMask.append(nums > bins[-1])\n\n if mask == 0:\n return np.array(val)\n else:\n return np.array(val), np.array(reMask)\n\ndef ErrorBarMedian(data):\n #return 25%, 50%, 75%\n if len(data) == 0:\n return 0, 0, 0\n elif len(data) < 3:\n return 0, np.median(data), 0\n else:\n data.sort()\n return data[int(len(data) / 4)], np.median(data), data[int(len(data) * 0.75)]\n\ndef Ydata(simu, ids, rawdata, SnapList, Redshift):\n dataWithZ = {}\n for x in Redshift:\n dataWithZ[x] = []\n #all each halo's information into 'dataWithZ'\n for subID in ids:\n data = []\n prog = LoadMergHist(simu, subID)[0]\n plot = 1\n for snap in SnapList:\n try:\n haloID = prog[snap]\n data.append(rawdata[snap][haloID])\n except:\n plot = 0 \n \n if plot:\n for i in range(len(data)):\n dataWithZ[Redshift[i]].append(data[i])\n\n #calculate Error bar\n plotdata = [[], [], []]\n for i in range(len(data)):\n d0, d1, d2 = ErrorBarMedian(dataWithZ[Redshift[i]])\n plotdata[0].append(d0)\n plotdata[1].append(d1)\n plotdata[2].append(d2)\n plotdata = np.array(plotdata)\n Err = np.vstack((plotdata[1,:] - plotdata[0,:], plotdata[2,:] - plotdata[1,:]))\n return plotdata[1,:], Err\n\ndef findGid(simu, snap, ids):\n res = []\n GID = il.func.loadSubhalos(simu, snap, 'SubhaloGrNr')\n for haloID in ids:\n try:\n prog = LoadMergHist(simu, haloID)[0]\n subID = prog[snap]\n except:\n continue\n\n res.append(GID[subID])\n return np.unique(res)\n\ndef logmas(data):\n if type(data) != type(np.array(0)):\n data = np.array(data)\n data = np.log10(data * 10 ** 10)\n data[np.isinf(data)] = 0\n data[np.isnan(data)] = 0\n return data",
"_____no_output_____"
],
[
"rs = np.array([0, 0.2, 0.5, 0.7, 1.0, 1.5, 2.0, 2.5, 3.0])\nil1_snap = [135, 120, 108, 95, 85, 75, 68, 64, 60]\ntng_snap = [99, 84, 67, 59, 50, 40, 33, 29, 25]\n\n# rs = np.array([0, 0.2, 0.5, 0.7, 1.0, 1.5, 2.0])\n# il1_snap = [135, 120, 108, 95, 85, 75, 68]\n# tng_snap = [99, 84, 67, 59, 50, 40, 33]",
"_____no_output_____"
],
[
"tng_BHMass = {}\ntng_BHdot = {}\n\ntng_MgasDivSFR = {}\ntng_sSFR = {}\ntng_SFR = {}\ntng_GF = {}\n\nfor snap in tng_snap:\n BHmas = il.func.loadSubhalos('TNG', snap, 'SubhaloBHMass')\n dot = il.func.loadSubhalos('TNG', snap, 'SubhaloBHMdot')\n tng_BHMass[snap] = logmas(BHmas / 0.6774)\n tng_BHdot[snap] = dot\n\n sfr = il.func.loadSubhalos('TNG', snap, 'SubhaloSFR') \n mass = il.func.loadSubhalos('TNG', snap, 'SubhaloMassType') * 10**10 / 0.6774\n MgasDivSFR = mass[:, 0] / sfr\n MgasDivSFR[np.isinf(MgasDivSFR)] = 0\n MgasDivSFR[np.isnan(MgasDivSFR)] = 0\n \n sSFR = sfr / mass[:, 4]\n sSFR[np.isinf(sSFR)] = 0\n sSFR[np.isnan(sSFR)] = 0\n mas = il.func.loadSubhalos('TNG', snap, 'SubhaloMassInHalfRadType')\n Gf = mas[:, 0] / (mas[:, 4] + mas[:, 0])\n Gf[np.isnan(Gf)] = 0\n tng_GF[snap] = Gf\n tng_SFR[snap] = sfr\n tng_sSFR[snap] = sSFR\n tng_MgasDivSFR[snap] = MgasDivSFR",
"d:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:119: RuntimeWarning: divide by zero encountered in log10\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:17: RuntimeWarning: divide by zero encountered in true_divide\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:17: RuntimeWarning: invalid value encountered in true_divide\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:21: RuntimeWarning: divide by zero encountered in true_divide\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:21: RuntimeWarning: invalid value encountered in true_divide\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:25: RuntimeWarning: invalid value encountered in true_divide\n"
],
[
"il1_BHMass = {}\nil1_BHdot = {}\n\nil1_MgasDivSFR = {}\nil1_sSFR = {}\nil1_SFR = {}\nil1_GF = {}\n\nfor snap in il1_snap:\n mas = il.func.loadSubhalos('il1', snap, 'SubhaloBHMass')\n dot = il.func.loadSubhalos('il1', snap, 'SubhaloBHMdot')\n il1_BHMass[snap] = logmas(mas / 0.704)\n il1_BHdot[snap] = dot\n \n sfr = il.func.loadSubhalos('il1', snap, 'SubhaloSFR')\n mass = il.func.loadSubhalos('il1', snap, 'SubhaloMassType') * 10**10 / 0.704\n MgasDivSFR = mass[:, 0] / sfr\n MgasDivSFR[np.isinf(MgasDivSFR)] = 0\n MgasDivSFR[np.isnan(MgasDivSFR)] = 0\n \n sSFR = sfr / mass[:, 4]\n sSFR[np.isinf(sSFR)] = 0\n sSFR[np.isnan(sSFR)] = 0\n mas = il.func.loadSubhalos('il1', snap, 'SubhaloMassInHalfRadType')\n Gf = mas[:, 0] / (mas[:, 4] + mas[:, 0])\n Gf[np.isnan(Gf)] = 0\n il1_GF[snap] = Gf\n il1_SFR[snap] = sfr\n il1_sSFR[snap] = sSFR\n il1_MgasDivSFR[snap] = MgasDivSFR",
"d:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:119: RuntimeWarning: divide by zero encountered in log10\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:17: RuntimeWarning: divide by zero encountered in true_divide\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:17: RuntimeWarning: invalid value encountered in true_divide\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:21: RuntimeWarning: divide by zero encountered in true_divide\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:21: RuntimeWarning: invalid value encountered in true_divide\nd:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:25: RuntimeWarning: invalid value encountered in true_divide\n"
],
[
"il1_barID = np.load('f:/Linux/localRUN/barredID_il1.npy')\nil1_diskID = np.load('f:/Linux/localRUN/diskID_il1.npy')\n\ntng_barID = np.load('f:/Linux/localRUN/barredID_4WP_TNG.npy')\ntng_diskID = np.load('f:/Linux/localRUN/diskID_4WP.npy')",
"_____no_output_____"
],
[
"tng_unbar = []\nfor i in tng_diskID:\n if i not in tng_barID:\n tng_unbar.append(i)\n \nil1_unbar = []\nfor i in il1_diskID:\n if i not in il1_barID:\n il1_unbar.append(i)",
"_____no_output_____"
],
[
"def getMultiData(simu, snapList, fields, haloType):\n res = []\n for i in range(len(fields)):\n res.append({})\n for snap in snapList:\n if haloType == 'fof':\n tmp = il.func.loadhalos(simu, snap, fields)\n else:\n tmp = il.func.loadSubhalos(simu, snap, fields)\n for i in range(len(fields)):\n res[i][snap] = tmp[fields[i]]\n return res\n\ndef getData(simu, snapList, fields, haloType):\n raw = {}\n for snap in snapList:\n if haloType == 'fof':\n tmp = il.func.loadhalos(simu, snap, fields)\n else:\n tmp = il.func.loadSubhalos(simu, snap, fields)\n raw[snap] = tmp[i]\n return raw",
"_____no_output_____"
],
[
"tng_subDM = {}\ntng_sub2r = {}\ntng_Groups = {}\ntng_r200 = {}\ntng_r500 = {}\n\n\nfor snap in tng_snap:\n sub = logmas(il.func.loadSubhalos('TNG', snap, 'SubhaloMassType')[:, 1] / 0.6774)\n sub2r = logmas(il.func.loadSubhalos('TNG', snap, 'SubhaloMassInRadType')[:, 1] / 0.6774)\n r200 = logmas(il.func.loadhalos('TNG', snap, 'Group_M_Crit200') / 0.6774)\n r500 = logmas(il.func.loadhalos('TNG', snap, 'Group_M_Crit500') / 0.6774)\n\n Groups = il.func.loadSubhalos('TNG', snap, \"SubhaloGrNr\")\n tng_Groups[snap] = Groups\n\n tng_subDM[snap] = sub\n tng_sub2r[snap] = sub2r\n tng_r200[snap] = r200\n tng_r500[snap] = r500",
"d:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:119: RuntimeWarning: divide by zero encountered in log10\n"
],
[
"il1_subDM = {}\nil1_sub2r = {}\nil1_Groups = {}\nil1_r200 = {}\nil1_r500 = {}\n\nfor snap in il1_snap:\n sub = logmas(il.func.loadSubhalos('il1', snap, 'SubhaloMassType')[:, 1] / 0.704)\n sub2r = logmas(il.func.loadSubhalos('il1', snap, 'SubhaloMassInRadType')[:, 1] / 0.704)\n r200 = logmas(il.func.loadhalos('il1', snap, 'Group_M_Crit200') / 0.704)\n r500 = logmas(il.func.loadhalos('il1', snap, 'Group_M_Crit500') / 0.704)\n\n Groups = il.func.loadSubhalos('il1', snap, \"SubhaloGrNr\")\n il1_Groups[snap] = Groups\n\n il1_subDM[snap] = sub\n il1_sub2r[snap] = sub2r\n il1_r200[snap] = r200\n il1_r500[snap] = r500",
"d:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:119: RuntimeWarning: divide by zero encountered in log10\n"
],
[
"def DMhaloMassInRad():\n il1_Y, il1_Err = Ydata('il1', il1_barID, il1_sub2r, il1_snap, rs)\n il1_Y_2, il1_Err_2 = Ydata('il1', il1_unbar, il1_sub2r, il1_snap, rs)\n tng_Y, tng_Err = Ydata('TNG', tng_barID, tng_sub2r, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, tng_sub2r, tng_snap, rs)\n\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('Z', fontsize=20)\n ax.set_ylabel(r'$log_{10}[M_\\odot]}$', fontsize=20)\n # ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 3.1)\n ax.set_ylim(9.5, 11.6)\n ax.set_xticks(rs)\n # ax.set_title(\"Galaxies(subhalo) dark matter mass\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n plt.savefig('f:/Linux/local_result/subDM_mass_InRad.pdf')",
"_____no_output_____"
],
[
"DMhaloMassInRad()",
"_____no_output_____"
],
[
"def DMhaloMass():\n rs = np.array([0, 0.2, 0.5, 0.7, 1.0, 1.5, 2.0])\n il1_snap = [135, 120, 108, 95, 85, 75, 68]\n tng_snap = [99, 84, 67, 59, 50, 40, 33]\n \n il1_Y, il1_Err = Ydata('il1', il1_barID, il1_subDM, il1_snap, rs)\n il1_Y_2, il1_Err_2 = Ydata('il1', il1_unbar, il1_subDM, il1_snap, rs)\n tng_Y, tng_Err = Ydata('TNG', tng_barID, tng_subDM, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, tng_subDM, tng_snap, rs)\n\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$z$', fontsize=20)\n ax.set_ylabel(r'$log_{10}(M_{DM}[M_\\odot])$', fontsize=20)\n # ax.set_yscale(\"log\")\n# ax.set_xlim(-0.1, 3.1)\n# ax.set_ylim(9.5, 11.6)\n ax.set_xticks(rs)\n # ax.set_title(\"Galaxies(subhalo) dark matter mass\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n ax.set_xlim(-0.1, 2.1)\n plt.savefig('f:/Linux/local_result/subDM_mass_20.pdf')",
"_____no_output_____"
],
[
"DMhaloMass()",
"_____no_output_____"
],
[
"il1_subDM",
"_____no_output_____"
],
[
"def fof_Ydata(simu, ids, rawdata, SnapList, Redshift, GID):\n dataWithZ = {}\n for x in Redshift:\n dataWithZ[x] = []\n #all each halo's information into 'dataWithZ'\n for subID in ids:\n data = []\n prog = LoadMergHist(simu, subID)[0]\n plot = 1\n for snap in SnapList:\n try:\n haloID = prog[snap]\n gid = GID[snap][haloID]\n data.append(rawdata[snap][gid])\n except:\n plot = 0 \n\n if plot:\n for i in range(len(data)):\n dataWithZ[Redshift[i]].append(data[i])\n\n #calculate Error bar\n plotdata = [[], [], []]\n for i in range(len(data)):\n d0, d1, d2 = ErrorBarMedian(dataWithZ[Redshift[i]])\n plotdata[0].append(d0)\n plotdata[1].append(d1)\n plotdata[2].append(d2)\n plotdata = np.array(plotdata)\n Err = np.vstack((plotdata[1,:] - plotdata[0,:], plotdata[2,:] - plotdata[1,:]))\n return plotdata[1, :], Err",
"_____no_output_____"
],
[
"def FOF_R500():\n il1_Y, il1_Err = fof_Ydata('il1', il1_barID, il1_r500, il1_snap, rs, il1_Groups)\n il1_Y_2, il1_Err_2 = fof_Ydata('il1', il1_unbar, il1_r500, il1_snap, rs, il1_Groups)\n tng_Y, tng_Err = fof_Ydata('TNG', tng_barID, tng_r500, tng_snap, rs, tng_Groups)\n tng_Y_2, tng_Err_2 = fof_Ydata('TNG', tng_unbar, tng_r500, tng_snap, rs, tng_Groups)\n\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('Z', fontsize=20)\n ax.set_ylabel(r'$log_{10}[M_\\odot]}$', fontsize=20)\n # ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 3.1)\n ax.set_ylim(10.8, 13.6)\n ax.set_xticks(rs)\n # ax.set_title(\"Galaxy host FOF halos(Group) dark matter mass\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n plt.savefig('f:/Linux/local_result/R500_mass.pdf')",
"_____no_output_____"
],
[
"def FOF_R200():\n rs = np.array([0, 0.2, 0.5, 0.7, 1.0, 1.5, 2.0])\n il1_snap = [135, 120, 108, 95, 85, 75, 68]\n tng_snap = [99, 84, 67, 59, 50, 40, 33]\n \n il1_Y, il1_Err = fof_Ydata('il1', il1_barID, il1_r200, il1_snap, rs, il1_Groups)\n il1_Y_2, il1_Err_2 = fof_Ydata('il1', il1_unbar, il1_r200, il1_snap, rs, il1_Groups)\n tng_Y, tng_Err = fof_Ydata('TNG', tng_barID, tng_r200, tng_snap, rs, tng_Groups)\n tng_Y_2, tng_Err_2 = fof_Ydata('TNG', tng_unbar, tng_r200, tng_snap, rs, tng_Groups)\n\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$z$', fontsize=20)\n ax.set_ylabel(r'$log_{10}(M[M_\\odot])}$', fontsize=20)\n # ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 2.1)\n ax.set_ylim(11, 13.6)\n ax.set_xticks(rs)\n # ax.set_title(\"Galaxy host FOF halos(Group) dark matter mass\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n ax.set_xlim(-0.1, 2.1)\n plt.savefig('f:/Linux/local_result/R200_mass_20.pdf')",
"_____no_output_____"
],
[
"FOF_R200()",
"_____no_output_____"
],
[
"FOF_R500()",
"_____no_output_____"
],
[
"def Edot(BHMdot):\n Edot_kine = (2.83 / 4.89) * 1e45 * BHMdot\n return Edot_kine\n\nenergy = {}\nfor i in tng_BHdot.keys():\n energy[i] = np.log10(Edot(tng_BHdot[i]))",
"d:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:7: RuntimeWarning: divide by zero encountered in log10\n import sys\n"
],
[
"energy",
"_____no_output_____"
],
[
"def AGN_Energy():\n tng_Y, tng_Err = Ydata('TNG', tng_barID, energy, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, energy, tng_snap, rs)\n\n\n #plot info\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('Z', fontsize=20)\n ax.set_ylabel(r'$log_{10}(E_{kinetic AGN}$ erg/s)', fontsize=20)\n ax.set_xlim(-0.1, 3.1)\n ax.set_xticks(rs)\n # ax.set_yscale(\"log\")\n # ax.set_ylim(0.1, 0.00000001)\n # ax.set_title(r\"TNG galaxies BlackHole accretion rates\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n ax.legend()\n # plt.savefig('f:/Linux/local_result/BH/en.eps')",
"_____no_output_____"
],
[
"AGN_Energy()",
"_____no_output_____"
],
[
"rs = np.array([0, 0.2, 0.5, 0.7, 1.0, 1.5, 2.0, 2.5, 3.0])\nil1_snap = [135, 120, 108, 95, 85, 75, 68, 64, 60]\ntng_snap = [99, 84, 67, 59, 50, 40, 33, 29, 25]",
"_____no_output_____"
],
[
"def Global_GasFraction_V2():\n #Global_il1-TNG_Gasfration\n il1_Y, il1_Err = Ydata('il1', il1_barID, il1_GF, il1_snap, rs)\n il1_Y_2, il1_Err_2 = Ydata('il1', il1_unbar, il1_GF, il1_snap, rs)\n \n tng_Y, tng_Err = Ydata('TNG', tng_barID, tng_GF, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, tng_GF, tng_snap, rs)\n\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel(r'$z$', fontsize=20)\n ax.set_ylabel(r'Gas Fraction', fontsize=20)\n # ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 3.1)\n ax.set_ylim(-0.02, 0.85)\n ax.set_xticks(rs)\n # ax.set_title(r\"il1&TNG galaxies gas fraction\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n# ax.legend(loc = 2)\n plt.savefig('f:/Linux/local_result/SFR-GF/Global_GasFraction_V2.pdf')",
"_____no_output_____"
],
[
"def Global_GasFraction_renew():\n #Global_il1-TNG_Gasfration\n il1_Y, il1_Err = Ydata('il1', il1_barID, il1_GF, il1_snap, rs)\n il1_Y_2, il1_Err_2 = Ydata('il1', il1_unbar, il1_GF, il1_snap, rs)\n \n tng_Y, tng_Err = Ydata('TNG', tng_barID, tng_GF, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, tng_GF, tng_snap, rs)\n\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel(r'$z$', fontsize=20)\n ax.set_ylabel(r'Gas Fraction', fontsize=20)\n # ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 3.1)\n ax.set_ylim(-0.02, 0.85)\n ax.set_xticks(rs)\n # ax.set_title(r\"il1&TNG galaxies gas fraction\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n# ax.legend(loc = 2)\n plt.savefig('f:/Linux/local_result/SFR-GF/Global_GasFraction_renew.pdf')",
"_____no_output_____"
],
[
"Global_GasFraction_renew()",
"_____no_output_____"
],
[
"def Global_SFR_renew():\n #Global_il1-TNG_GAS\n il1_Y, il1_Err = Ydata('il1', il1_barID, il1_SFR, il1_snap, rs)\n il1_Y_2, il1_Err_2 = Ydata('il1', il1_unbar, il1_SFR, il1_snap, rs)\n \n tng_Y, tng_Err = Ydata('TNG', tng_barID, tng_SFR, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, tng_SFR, tng_snap, rs)\n\n #plot info\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$z$', fontsize=20)\n ax.set_ylabel(r'SFR [$M_\\odot/yr$]', fontsize=20)\n # ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 3.1)\n ax.set_xticks(rs)\n # ax.set_ylim(-0.02, 0.85)\n # ax.set_title(r\"il1&TNG galaxies star formation rate\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n plt.savefig('f:/Linux/local_result/SFR-GF/Global_SFR_renew.pdf')",
"_____no_output_____"
],
[
"Global_SFR_renew()",
"_____no_output_____"
],
[
"def Global_sSFR():\n #Global_il1-TNG_GAS\n il1_Y, il1_Err = Ydata('il1', il1_barID, il1_sSFR, il1_snap, rs)\n il1_Y_2, il1_Err_2 = Ydata('il1', il1_unbar, il1_sSFR, il1_snap, rs)\n \n tng_Y, tng_Err = Ydata('TNG', tng_barID, tng_sSFR, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, tng_sSFR, tng_snap, rs)\n\n #plot info\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$z$', fontsize=20)\n ax.set_ylabel(r'sSFR $[yr^{-1}]$', fontsize=20)\n ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 3.1)\n ax.set_xticks(rs)\n # ax.set_ylim(-0.02, 0.85)\n # ax.set_title(r\"il1&TNG galaxies star formation rate\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n# plt.savefig('f:/Linux/local_result/SFR-GF/Global_sSFR.pdf')",
"_____no_output_____"
],
[
"Global_sSFR()",
"_____no_output_____"
],
[
"def Global_MgasDivSFR():\n #Global_il1-TNG_GAS\n il1_Y, il1_Err = Ydata('il1', il1_barID, il1_MgasDivSFR, il1_snap, rs)\n il1_Y_2, il1_Err_2 = Ydata('il1', il1_unbar, il1_MgasDivSFR, il1_snap, rs)\n \n tng_Y, tng_Err = Ydata('TNG', tng_barID, tng_MgasDivSFR, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, tng_MgasDivSFR, tng_snap, rs)\n\n #plot info\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$z$', fontsize=20)\n ax.set_ylabel(r'$\\frac{M_{gas}}{SFR}[yr]$', fontsize=20)\n ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 3.1)\n ax.set_xticks(rs)\n # ax.set_ylim(-0.02, 0.85)\n # ax.set_title(r\"il1&TNG galaxies star formation rate\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n plt.savefig('f:/Linux/result_v2/MgasDivSFR.pdf')",
"_____no_output_____"
],
[
"Global_MgasDivSFR()",
"_____no_output_____"
],
[
"#Part-B : Black Hole ",
"_____no_output_____"
],
[
"def Global_BHdot():\n il1_Y, il1_Err = Ydata('il1', il1_barID, il1_BHdot, il1_snap, rs)\n il1_Y_2, il1_Err_2 = Ydata('il1', il1_unbar, il1_BHdot, il1_snap, rs)\n \n tng_Y, tng_Err = Ydata('TNG', tng_barID, tng_BHdot, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, tng_BHdot, tng_snap, rs)\n\n #plot info\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$z$', fontsize=20)\n ax.set_ylabel(r'$\\dot{M}_{BH}[10^{10} M_\\odot / Gyr]$', fontsize=20)\n ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 3.1)\n ax.set_xticks(rs)\n # ax.set_ylim(0.1, 0.00000001)\n # ax.set_title(r\"TNG galaxies BlackHole accretion rates\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n\n plt.savefig('f:/Linux/local_result/BH/Global_BHdot.pdf')",
"_____no_output_____"
],
[
"Global_BHdot()",
"_____no_output_____"
],
[
"def Global_BHmass():\n #Global_il1-TNG_BHmass\n il1_Y, il1_Err = Ydata('il1', il1_barID, il1_BHMass, il1_snap, rs)\n il1_Y_2, il1_Err_2 = Ydata('il1', il1_unbar, il1_BHMass, il1_snap, rs)\n \n tng_Y, tng_Err = Ydata('TNG', tng_barID, tng_BHMass, tng_snap, rs)\n tng_Y_2, tng_Err_2 = Ydata('TNG', tng_unbar, tng_BHMass, tng_snap, rs)\n\n\n #plot info\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$z$', fontsize=20)\n ax.set_ylabel(r'$log_{10}(M_*/M_\\odot)$', fontsize=20)\n# ax.set_yscale(\"log\")\n ax.set_xlim(-0.1, 3.1)\n ax.set_xticks(rs)\n # ax.set_ylim(0.1, 0.00000001)\n # ax.set_title(r\"TNG & Illustris-1 galaxies BlackHole Mass\")\n\n #lines\n ax.errorbar(rs-0.02, tng_Y, yerr=tng_Err, elinewidth=2, capthick=2, capsize=3, color='r', fmt='o',ms=5, ls='-', label='TNG-100 barred')\n ax.errorbar(rs-0.02, tng_Y_2, yerr=tng_Err_2, elinewidth=2, capthick=2, capsize=3, color='orange', fmt='^',ms=5, ls='-.', label='TNG-100 unbarred')\n ax.errorbar(rs+0.02, il1_Y, yerr=il1_Err, elinewidth=2, capthick=2, capsize=3, color='blue', fmt='o', ms=5, ls='-', label='Illustris-1 barred')\n ax.errorbar(rs+0.02, il1_Y_2, yerr=il1_Err_2, elinewidth=2, capthick=2, capsize=3, color='c', fmt='^', ms=5, ls='-.', label='Illustris-1 unbarred')\n \n ax.tick_params(labelsize=14)\n ax.legend(loc = 0, fontsize=12)\n plt.savefig('f:/Linux/local_result/BH/Global_BHmass.pdf')",
"_____no_output_____"
],
[
"Global_BHmass()",
"_____no_output_____"
],
[
"il1_BHdot, il1_SFR",
"_____no_output_____"
],
[
"plt.plot([1,2], [1,2])",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccdf3a4697856fe974dbf72d71b3520e6b789b5 | 23,046 | ipynb | Jupyter Notebook | Models/additional Models/CORTADO.ipynb | mattiasu96/recsys-challenge-2021-twitter | 80b78050739a93165cbaaf256bd13932582a8930 | [
"Apache-2.0"
] | 6 | 2021-09-05T09:20:33.000Z | 2022-03-09T13:41:42.000Z | Models/additional Models/CORTADO.ipynb | mattiasu96/recsys-challenge-2021-twitter | 80b78050739a93165cbaaf256bd13932582a8930 | [
"Apache-2.0"
] | null | null | null | Models/additional Models/CORTADO.ipynb | mattiasu96/recsys-challenge-2021-twitter | 80b78050739a93165cbaaf256bd13932582a8930 | [
"Apache-2.0"
] | 3 | 2021-09-06T09:19:49.000Z | 2021-11-19T14:11:52.000Z | 23,046 | 23,046 | 0.60965 | [
[
[
"targetColName=\"like\"\ntargetIndex=3\nlr=[0.05,0.03,0.07,0.01]\norigin=\"drive/MyDrive/twitter/onechunk/\"\neta = 0.1\nnrounds = 100\nmax_depth = 6",
"_____no_output_____"
]
],
[
[
"#Setup\n",
"_____no_output_____"
]
],
[
[
"!pip install cortado",
"Collecting cortado\n Downloading https://files.pythonhosted.org/packages/08/d9/bfd0af6d1e551622eac25585ab48114206db9ecd788459bee2cad2b1ae9b/cortado-1.0rc3-py3-none-any.whl\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from cortado) (1.1.5)\nRequirement already satisfied: numba in /usr/local/lib/python3.7/dist-packages (from cortado) (0.51.2)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from cortado) (1.19.5)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->cortado) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->cortado) (2.8.1)\nRequirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba->cortado) (0.34.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba->cortado) (56.0.0)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->cortado) (1.15.0)\nInstalling collected packages: cortado\nSuccessfully installed cortado-1.0rc3\n"
],
[
"import os \nos.system(f\"cp {origin}* ../content/\")",
"_____no_output_____"
],
[
"import cortado as cr\nimport pandas as pd\ntrain=pd.read_csv(\"trainFinal.csv\", index_col=0)\ntest=pd.read_csv(\"testFinal.csv\", index_col=0)\n\ncolumns=[\"retweet\",\"retweetCom\",\"reply\",\"like\"]\n\n\n\nfor col in columns:\n if col!= targetColName:\n train.drop(col,axis=1,inplace=True)\n test.drop(col,axis=1,inplace=True)",
"/usr/local/lib/python3.7/dist-packages/numpy/lib/arraysetops.py:580: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison\n mask |= (ar1 == a)\n"
],
[
"train[:5]",
"_____no_output_____"
],
[
"train = cr.DataFrame.from_pandas(train)\ntest=cr.DataFrame.from_pandas(test)",
"_____no_output_____"
],
[
"train.covariates",
"_____no_output_____"
],
[
"factoredCvTrain=[]\nfactoredCvTest=[]\nfor c in train.covariates:\n if c.name!=targetColName:\n factoredCvTrain.append(cr.Factor.from_covariate(train[c.name]))\n factoredCvTest.append(cr.Factor.from_covariate(test[c.name]))",
"_____no_output_____"
],
[
"trainTarget=train[\"like\"]",
"_____no_output_____"
],
[
"trainTarget",
"_____no_output_____"
],
[
"factors=train.factors+factoredCvTrain",
"_____no_output_____"
]
],
[
[
"#Model\n",
"_____no_output_____"
]
],
[
[
"trees, pred_cr = cr.xgblogit(trainTarget, factors, eta = eta, lambda_ = 1.0, gamma = 0.0, minh = 1.0, nrounds =20, maxdepth =6 , slicelen=1000000)",
"_____no_output_____"
],
[
"from sklearn.metrics import roc_auc_score\ny = trainTarget.to_array() # convert to numpy array\nauc_cr = roc_auc_score(y, pred_cr) # cortado auc\nprint(\"cortado auc: {auc_cr}\".format(auc_cr=auc_cr))",
"cortado auc: 0.914938316479314\n"
],
[
"pred_cr",
"_____no_output_____"
],
[
"y",
"_____no_output_____"
],
[
"factors[:1]",
"_____no_output_____"
],
[
"factor=factors[:1]",
"_____no_output_____"
],
[
"t=trees[0][0][0]",
"_____no_output_____"
],
[
"t.leftnode.partitions[key]",
"_____no_output_____"
],
[
"key=[k for k in t.leftnode.partitions.keys()][0]",
"_____no_output_____"
],
[
"for k in t.leftnode.partitions.keys():\n temp=t.leftnode.partitions[k]\n for i in temp:\n if i==False:\n print(temp)\n print(k)\n break",
"[False True False ... False False False]\nFactor pagerank_ed_to_ing_ing with 2426667 obs and 186999 levels: [2.9677273e-07,2.9677577e-07) [3.3296106e-07,3.3296317e-07) [-inf,7.998292e-08) [3.568045e-07,3.5680512e-07) [-inf,7.998292e-08) [3.568045e-07,3.5680512e-07) [3.421685e-07,3.421685e-07) [-inf,7.998292e-08) [3.568045e-07,3.5680512e-07) [3.038948e-07,3.0389572e-07) ...\n"
],
[
"cr.logistic.get_pred(pred_cr)",
"_____no_output_____"
],
[
"pred_cr",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecce01292dc8fb9f89a313f45edc7e94cae0e6aa | 1,797 | ipynb | Jupyter Notebook | docs/source/user_guide/utilities.ipynb | gcode-ai/rayml | 92c4f3c6041f465fee27a6c03bd7959c4ef21124 | [
"BSD-3-Clause"
] | null | null | null | docs/source/user_guide/utilities.ipynb | gcode-ai/rayml | 92c4f3c6041f465fee27a6c03bd7959c4ef21124 | [
"BSD-3-Clause"
] | null | null | null | docs/source/user_guide/utilities.ipynb | gcode-ai/rayml | 92c4f3c6041f465fee27a6c03bd7959c4ef21124 | [
"BSD-3-Clause"
] | null | null | null | 29.459016 | 315 | 0.633278 | [
[
[
"# Utilities",
"_____no_output_____"
],
[
"## Configuring Logging\n\nrayml uses [the standard Python logging package](https://docs.python.org/3/library/logging.html). Default logging behavior prints WARNING level logs and above (ERROR and CRITICAL) to stdout. To configure different behavior, please refer to the Python logging documentation.\n\nTo see up-to-date feedback as `AutoMLSearch` runs, use the argument `verbose=True` when instantiating the object. This will temporarily set up a logging object to print INFO level logs and above to stdout, as well as display a graph of the best score over pipeline iterations.",
"_____no_output_____"
],
[
"## System Information\n\nrayml provides a command-line interface (CLI) tool prints the version of rayml and core dependencies installed, as well as some basic system information. To use this tool, just run `rayml info` in your shell or terminal. This could be useful for debugging purposes or tracking down any version-related issues.",
"_____no_output_____"
]
],
[
[
"!rayml info",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
ecce0d1f12b213e723970fd730d1d4b1f440992a | 1,163 | ipynb | Jupyter Notebook | 9-9 Applied Data Science Capstone/Capstone_Project_Notebook.ipynb | MLunov/IBM-Data-Science-Professional-Certificate | 90003843e9a53a2705d9cde6dd4206595fb8a41f | [
"MIT"
] | 1 | 2020-02-25T13:17:10.000Z | 2020-02-25T13:17:10.000Z | 9-9 Applied Data Science Capstone/Capstone_Project_Notebook.ipynb | MLunov/IBM-Data-Science-Professional-Certificate | 90003843e9a53a2705d9cde6dd4206595fb8a41f | [
"MIT"
] | null | null | null | 9-9 Applied Data Science Capstone/Capstone_Project_Notebook.ipynb | MLunov/IBM-Data-Science-Professional-Certificate | 90003843e9a53a2705d9cde6dd4206595fb8a41f | [
"MIT"
] | 2 | 2020-03-12T20:58:56.000Z | 2020-10-12T22:18:43.000Z | 17.358209 | 67 | 0.509888 | [
[
[
"# This notebook will be mainly used for the capstone project",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"print(\"Hello Capstone Project Course!\")",
"Hello Capstone Project Course!\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
]
] |
ecce0f6a019f88518d14b64bfe4c1c49cbbd17e4 | 107,544 | ipynb | Jupyter Notebook | wideresnet/cifar10-wideresnet.ipynb | vicdoja/ComputerVision-Labs | c937c18dca87209435fe980e178c385ac0f9857c | [
"MIT"
] | null | null | null | wideresnet/cifar10-wideresnet.ipynb | vicdoja/ComputerVision-Labs | c937c18dca87209435fe980e178c385ac0f9857c | [
"MIT"
] | null | null | null | wideresnet/cifar10-wideresnet.ipynb | vicdoja/ComputerVision-Labs | c937c18dca87209435fe980e178c385ac0f9857c | [
"MIT"
] | null | null | null | 83.822292 | 19,096 | 0.698486 | [
[
[
"###################################################################################\n##\n## From https://github.com/keras-team/keras/blob/master/examples/cifar10_resnet.py\n##\n###################################################################################\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation, Dropout\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nimport numpy as np\nimport os",
"_____no_output_____"
],
[
"from tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())",
"[name: \"/device:CPU:0\"\ndevice_type: \"CPU\"\nmemory_limit: 268435456\nlocality {\n}\nincarnation: 8538861898910734175\n, name: \"/device:GPU:0\"\ndevice_type: \"GPU\"\nmemory_limit: 3315204096\nlocality {\n bus_id: 1\n links {\n }\n}\nincarnation: 11361429964739130051\nphysical_device_desc: \"device: 0, name: GeForce GTX 970, pci bus id: 0000:01:00.0, compute capability: 5.2\"\n]\n"
],
[
"# Training parameters\nbatch_size = 128 # orig paper trained all networks with batch_size=128\nepochs = 100\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model version\n# Orig paper: version = 1 (ResNet v1), Improved ResNet: version = 2 (ResNet v2)\nversion = 1\n\nwide = True\nfactor = 5\ndrop = True\n\n# Computed depth from supplied model parameter n\nif version == 1:\n depth = n * 6 + 2\nelif version == 2:\n depth = n * 9 + 2\n\n# Model name, depth and version\nif wide:\n model_type = 'Wide-ResNet%dv%d-%d' % (depth, version, factor)\nelse:\n model_type = 'ResNet%dv%d' % (depth, version)",
"_____no_output_____"
],
[
"# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()",
"_____no_output_____"
],
[
"# Input image dimensions.\ninput_shape = x_train.shape[1:]\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)",
"x_train shape: (50000, 32, 32, 3)\n50000 train samples\n10000 test samples\ny_train shape: (50000, 1)\n"
],
[
"def lr_schedule(epoch):\n\n lr = 1e-3\n if epoch > 80:\n lr *= 0.5e-3\n elif epoch > 60:\n lr *= 1e-3\n elif epoch > 40:\n lr *= 1e-2\n elif epoch > 20:\n lr *= 1e-1\n print('Learning rate: ', lr)\n return lr\n\n\ndef resnet_layer(inputs,\n num_filters=16,\n kernel_size=3,\n strides=1,\n activation='relu',\n batch_normalization=True,\n conv_first=True):\n\n conv = Conv2D(num_filters,\n kernel_size=kernel_size,\n strides=strides,\n padding='same',\n kernel_initializer='he_normal',\n kernel_regularizer=l2(1e-4))\n\n x = inputs\n if conv_first:\n x = conv(x)\n if batch_normalization:\n x = BatchNormalization()(x)\n if activation is not None:\n x = Activation(activation)(x)\n else:\n if batch_normalization:\n x = BatchNormalization()(x)\n if activation is not None:\n x = Activation(activation)(x)\n x = conv(x)\n return x\n\n\ndef resnet_v1(input_shape, depth, num_classes=10, wide=False, factor=1, drop=False):\n\n if (depth - 2) % 6 != 0:\n raise ValueError('depth should be 6n+2 (eg 20, 32, 44 in [a])')\n # Start model definition.\n num_filters = 16*factor\n num_res_blocks = int((depth - 2) / 6)\n\n inputs = Input(shape=input_shape)\n x = resnet_layer(inputs=inputs, num_filters=num_filters, conv_first=False)\n # Instantiate the stack of residual units\n for stack in range(3):\n for res_block in range(num_res_blocks):\n strides = 1\n if stack > 0 and res_block == 0: # first layer but not first stack\n strides = 2 # downsample\n y = resnet_layer(inputs=x,\n num_filters=num_filters,\n strides=strides,\n conv_first=False)\n if drop:\n y = Dropout(0.2)(y)\n \n y = resnet_layer(inputs=y,\n num_filters=num_filters,\n activation=None,\n conv_first=False)\n if stack > 0 and res_block == 0: # first layer but not first stack\n # linear projection residual shortcut connection to match\n # changed dims\n x = resnet_layer(inputs=x,\n num_filters=num_filters,\n kernel_size=1,\n strides=strides,\n activation=None,\n batch_normalization=False,\n conv_first=False)\n x = keras.layers.add([x, y])\n x = Activation('relu')(x)\n num_filters *= 2\n\n # Add classifier on top.\n # v1 does not use BN after last shortcut connection-ReLU\n x = AveragePooling2D(pool_size=8)(x)\n y = Flatten()(x)\n outputs = Dense(num_classes,\n activation='softmax',\n kernel_initializer='he_normal')(y)\n\n # Instantiate model.\n model = Model(inputs=inputs, outputs=outputs)\n return model\n\n\ndef resnet_v2(input_shape, depth, num_classes=10, wide=False, factor=1, drop=False):\n\n if (depth - 2) % 9 != 0:\n raise ValueError('depth should be 9n+2 (eg 56 or 110 in [b])')\n # Start model definition.\n num_filters_in = 16\n num_res_blocks = int((depth - 2) / 9)\n\n inputs = Input(shape=input_shape)\n # v2 performs Conv2D with BN-ReLU on input before splitting into 2 paths\n x = resnet_layer(inputs=inputs,\n num_filters=num_filters_in,\n conv_first=True)\n\n # Instantiate the stack of residual units\n for stage in range(3):\n for res_block in range(num_res_blocks):\n activation = 'relu'\n batch_normalization = True\n strides = 1\n if stage == 0:\n num_filters_out = num_filters_in * 4\n if res_block == 0: # first layer and first stage\n activation = None\n batch_normalization = False\n else:\n num_filters_out = num_filters_in * 2\n if res_block == 0: # first layer but not first stage\n strides = 2 # downsample\n\n # bottleneck residual unit\n y = resnet_layer(inputs=x,\n num_filters=num_filters_in,\n kernel_size=1,\n strides=strides,\n activation=activation,\n batch_normalization=batch_normalization,\n conv_first=False)\n y = resnet_layer(inputs=y,\n num_filters=num_filters_in,\n conv_first=False)\n y = resnet_layer(inputs=y,\n num_filters=num_filters_out,\n kernel_size=1,\n conv_first=False)\n if res_block == 0:\n # linear projection residual shortcut connection to match\n # changed dims\n x = resnet_layer(inputs=x,\n num_filters=num_filters_out,\n kernel_size=1,\n strides=strides,\n activation=None,\n batch_normalization=False)\n x = keras.layers.add([x, y])\n\n num_filters_in = num_filters_out\n\n # Add classifier on top.\n # v2 has BN-ReLU before Pooling\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = AveragePooling2D(pool_size=8)(x)\n y = Flatten()(x)\n outputs = Dense(num_classes,\n activation='softmax',\n kernel_initializer='he_normal')(y)\n\n # Instantiate model.\n model = Model(inputs=inputs, outputs=outputs)\n return model",
"_____no_output_____"
],
[
"if version == 2:\n model = resnet_v2(input_shape=input_shape, depth=depth, wide=wide, factor=factor, drop=drop)\nelse:\n model = resnet_v1(input_shape=input_shape, depth=depth, wide=wide, factor=factor, drop=drop)\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer=Adam(learning_rate=lr_schedule(0)),\n metrics=['accuracy'])\nmodel.summary()\nprint(model_type)",
"Learning rate: 0.001\nModel: \"model_8\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_12 (InputLayer) [(None, 32, 32, 3)] 0 \n__________________________________________________________________________________________________\nbatch_normalization_161 (BatchN (None, 32, 32, 3) 12 input_12[0][0] \n__________________________________________________________________________________________________\nactivation_158 (Activation) (None, 32, 32, 3) 0 batch_normalization_161[0][0] \n__________________________________________________________________________________________________\nconv2d_177 (Conv2D) (None, 32, 32, 80) 2240 activation_158[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_162 (BatchN (None, 32, 32, 80) 320 conv2d_177[0][0] \n__________________________________________________________________________________________________\nactivation_159 (Activation) (None, 32, 32, 80) 0 batch_normalization_162[0][0] \n__________________________________________________________________________________________________\nconv2d_178 (Conv2D) (None, 32, 32, 80) 57680 activation_159[0][0] \n__________________________________________________________________________________________________\ndropout_57 (Dropout) (None, 32, 32, 80) 0 conv2d_178[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_163 (BatchN (None, 32, 32, 80) 320 dropout_57[0][0] \n__________________________________________________________________________________________________\nconv2d_179 (Conv2D) (None, 32, 32, 80) 57680 batch_normalization_163[0][0] \n__________________________________________________________________________________________________\nadd_75 (Add) (None, 32, 32, 80) 0 conv2d_177[0][0] \n conv2d_179[0][0] \n__________________________________________________________________________________________________\nactivation_160 (Activation) (None, 32, 32, 80) 0 add_75[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_164 (BatchN (None, 32, 32, 80) 320 activation_160[0][0] \n__________________________________________________________________________________________________\nactivation_161 (Activation) (None, 32, 32, 80) 0 batch_normalization_164[0][0] \n__________________________________________________________________________________________________\nconv2d_180 (Conv2D) (None, 32, 32, 80) 57680 activation_161[0][0] \n__________________________________________________________________________________________________\ndropout_58 (Dropout) (None, 32, 32, 80) 0 conv2d_180[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_165 (BatchN (None, 32, 32, 80) 320 dropout_58[0][0] \n__________________________________________________________________________________________________\nconv2d_181 (Conv2D) (None, 32, 32, 80) 57680 batch_normalization_165[0][0] \n__________________________________________________________________________________________________\nadd_76 (Add) (None, 32, 32, 80) 0 activation_160[0][0] \n conv2d_181[0][0] \n__________________________________________________________________________________________________\nactivation_162 (Activation) (None, 32, 32, 80) 0 add_76[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_166 (BatchN (None, 32, 32, 80) 320 activation_162[0][0] \n__________________________________________________________________________________________________\nactivation_163 (Activation) (None, 32, 32, 80) 0 batch_normalization_166[0][0] \n__________________________________________________________________________________________________\nconv2d_182 (Conv2D) (None, 32, 32, 80) 57680 activation_163[0][0] \n__________________________________________________________________________________________________\ndropout_59 (Dropout) (None, 32, 32, 80) 0 conv2d_182[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_167 (BatchN (None, 32, 32, 80) 320 dropout_59[0][0] \n__________________________________________________________________________________________________\nconv2d_183 (Conv2D) (None, 32, 32, 80) 57680 batch_normalization_167[0][0] \n__________________________________________________________________________________________________\nadd_77 (Add) (None, 32, 32, 80) 0 activation_162[0][0] \n conv2d_183[0][0] \n__________________________________________________________________________________________________\nactivation_164 (Activation) (None, 32, 32, 80) 0 add_77[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_168 (BatchN (None, 32, 32, 80) 320 activation_164[0][0] \n__________________________________________________________________________________________________\nactivation_165 (Activation) (None, 32, 32, 80) 0 batch_normalization_168[0][0] \n__________________________________________________________________________________________________\nconv2d_184 (Conv2D) (None, 16, 16, 160) 115360 activation_165[0][0] \n__________________________________________________________________________________________________\ndropout_60 (Dropout) (None, 16, 16, 160) 0 conv2d_184[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_169 (BatchN (None, 16, 16, 160) 640 dropout_60[0][0] \n__________________________________________________________________________________________________\nconv2d_186 (Conv2D) (None, 16, 16, 160) 12960 activation_164[0][0] \n__________________________________________________________________________________________________\nconv2d_185 (Conv2D) (None, 16, 16, 160) 230560 batch_normalization_169[0][0] \n__________________________________________________________________________________________________\nadd_78 (Add) (None, 16, 16, 160) 0 conv2d_186[0][0] \n conv2d_185[0][0] \n__________________________________________________________________________________________________\nactivation_166 (Activation) (None, 16, 16, 160) 0 add_78[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_170 (BatchN (None, 16, 16, 160) 640 activation_166[0][0] \n__________________________________________________________________________________________________\nactivation_167 (Activation) (None, 16, 16, 160) 0 batch_normalization_170[0][0] \n__________________________________________________________________________________________________\nconv2d_187 (Conv2D) (None, 16, 16, 160) 230560 activation_167[0][0] \n__________________________________________________________________________________________________\ndropout_61 (Dropout) (None, 16, 16, 160) 0 conv2d_187[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_171 (BatchN (None, 16, 16, 160) 640 dropout_61[0][0] \n__________________________________________________________________________________________________\nconv2d_188 (Conv2D) (None, 16, 16, 160) 230560 batch_normalization_171[0][0] \n__________________________________________________________________________________________________\nadd_79 (Add) (None, 16, 16, 160) 0 activation_166[0][0] \n conv2d_188[0][0] \n__________________________________________________________________________________________________\nactivation_168 (Activation) (None, 16, 16, 160) 0 add_79[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_172 (BatchN (None, 16, 16, 160) 640 activation_168[0][0] \n__________________________________________________________________________________________________\nactivation_169 (Activation) (None, 16, 16, 160) 0 batch_normalization_172[0][0] \n__________________________________________________________________________________________________\nconv2d_189 (Conv2D) (None, 16, 16, 160) 230560 activation_169[0][0] \n__________________________________________________________________________________________________\ndropout_62 (Dropout) (None, 16, 16, 160) 0 conv2d_189[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_173 (BatchN (None, 16, 16, 160) 640 dropout_62[0][0] \n__________________________________________________________________________________________________\nconv2d_190 (Conv2D) (None, 16, 16, 160) 230560 batch_normalization_173[0][0] \n__________________________________________________________________________________________________\nadd_80 (Add) (None, 16, 16, 160) 0 activation_168[0][0] \n conv2d_190[0][0] \n__________________________________________________________________________________________________\nactivation_170 (Activation) (None, 16, 16, 160) 0 add_80[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_174 (BatchN (None, 16, 16, 160) 640 activation_170[0][0] \n__________________________________________________________________________________________________\nactivation_171 (Activation) (None, 16, 16, 160) 0 batch_normalization_174[0][0] \n__________________________________________________________________________________________________\nconv2d_191 (Conv2D) (None, 8, 8, 320) 461120 activation_171[0][0] \n__________________________________________________________________________________________________\ndropout_63 (Dropout) (None, 8, 8, 320) 0 conv2d_191[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_175 (BatchN (None, 8, 8, 320) 1280 dropout_63[0][0] \n__________________________________________________________________________________________________\nconv2d_193 (Conv2D) (None, 8, 8, 320) 51520 activation_170[0][0] \n__________________________________________________________________________________________________\nconv2d_192 (Conv2D) (None, 8, 8, 320) 921920 batch_normalization_175[0][0] \n__________________________________________________________________________________________________\nadd_81 (Add) (None, 8, 8, 320) 0 conv2d_193[0][0] \n conv2d_192[0][0] \n__________________________________________________________________________________________________\nactivation_172 (Activation) (None, 8, 8, 320) 0 add_81[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_176 (BatchN (None, 8, 8, 320) 1280 activation_172[0][0] \n__________________________________________________________________________________________________\nactivation_173 (Activation) (None, 8, 8, 320) 0 batch_normalization_176[0][0] \n__________________________________________________________________________________________________\nconv2d_194 (Conv2D) (None, 8, 8, 320) 921920 activation_173[0][0] \n__________________________________________________________________________________________________\ndropout_64 (Dropout) (None, 8, 8, 320) 0 conv2d_194[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_177 (BatchN (None, 8, 8, 320) 1280 dropout_64[0][0] \n__________________________________________________________________________________________________\nconv2d_195 (Conv2D) (None, 8, 8, 320) 921920 batch_normalization_177[0][0] \n__________________________________________________________________________________________________\nadd_82 (Add) (None, 8, 8, 320) 0 activation_172[0][0] \n conv2d_195[0][0] \n__________________________________________________________________________________________________\nactivation_174 (Activation) (None, 8, 8, 320) 0 add_82[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_178 (BatchN (None, 8, 8, 320) 1280 activation_174[0][0] \n__________________________________________________________________________________________________\nactivation_175 (Activation) (None, 8, 8, 320) 0 batch_normalization_178[0][0] \n__________________________________________________________________________________________________\nconv2d_196 (Conv2D) (None, 8, 8, 320) 921920 activation_175[0][0] \n__________________________________________________________________________________________________\ndropout_65 (Dropout) (None, 8, 8, 320) 0 conv2d_196[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_179 (BatchN (None, 8, 8, 320) 1280 dropout_65[0][0] \n__________________________________________________________________________________________________\nconv2d_197 (Conv2D) (None, 8, 8, 320) 921920 batch_normalization_179[0][0] \n__________________________________________________________________________________________________\nadd_83 (Add) (None, 8, 8, 320) 0 activation_174[0][0] \n conv2d_197[0][0] \n__________________________________________________________________________________________________\nactivation_176 (Activation) (None, 8, 8, 320) 0 add_83[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_8 (AveragePoo (None, 1, 1, 320) 0 activation_176[0][0] \n__________________________________________________________________________________________________\nflatten_8 (Flatten) (None, 320) 0 average_pooling2d_8[0][0] \n__________________________________________________________________________________________________\ndense_8 (Dense) (None, 10) 3210 flatten_8[0][0] \n==================================================================================================\nTotal params: 6,767,382\nTrainable params: 6,761,136\nNon-trainable params: 6,246\n__________________________________________________________________________________________________\nWide-ResNet20v1-5\n"
],
[
"# Prepare model model saving directory.\nsave_dir = os.path.join(os.getcwd(), 'saved_models')\nmodel_name = 'cifar10_%s_model.{epoch:03d}.h5' % model_type\nif not os.path.isdir(save_dir):\n os.makedirs(save_dir)\nfilepath = os.path.join(save_dir, model_name)",
"_____no_output_____"
],
[
"# Prepare callbacks for model saving and for learning rate adjustment.\ncheckpoint = ModelCheckpoint(filepath=filepath,\n monitor='val_accuracy',\n verbose=1,\n save_best_only=True)\n\nlr_scheduler = LearningRateScheduler(lr_schedule)\n\nlr_reducer = ReduceLROnPlateau(factor=np.sqrt(0.1),\n cooldown=0,\n patience=5,\n min_lr=0.5e-6)\n\ncallbacks = [checkpoint, lr_reducer, lr_scheduler]",
"_____no_output_____"
],
[
"# Run training, with or without data augmentation.\nif not data_augmentation:\n print('Not using data augmentation.')\n history = model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks)\nelse:\n print('Using real-time data augmentation.')\n # This will do preprocessing and realtime data augmentation:\n datagen = ImageDataGenerator(\n # set input mean to 0 over the dataset\n featurewise_center=False,\n # set each sample mean to 0\n samplewise_center=False,\n # divide inputs by std of dataset\n featurewise_std_normalization=False,\n # divide each input by its std\n samplewise_std_normalization=False,\n # apply ZCA whitening\n zca_whitening=False,\n # epsilon for ZCA whitening\n zca_epsilon=1e-06,\n # randomly rotate images in the range (deg 0 to 180)\n rotation_range=20,\n # randomly shift images horizontally\n width_shift_range=0.1,\n # randomly shift images vertically\n height_shift_range=0.1,\n # set range for random shear\n shear_range=0.1,\n # set range for random zoom\n zoom_range=0.1,\n # set range for random channel shifts\n channel_shift_range=0.1,\n # set mode for filling points outside the input boundaries\n fill_mode='nearest',\n # value used for fill_mode = \"constant\"\n cval=0.,\n # randomly flip images\n horizontal_flip=True,\n # randomly flip images\n vertical_flip=False,\n # set rescaling factor (applied before any other transformation)\n rescale=None,\n # set function that will be applied on each input\n preprocessing_function=None,\n # image data format, either \"channels_first\" or \"channels_last\"\n data_format=None,\n # fraction of images reserved for validation (strictly between 0 and 1)\n validation_split=0.0)\n\n # Compute quantities required for featurewise normalization\n # (std, mean, and principal components if ZCA whitening is applied).\n datagen.fit(x_train)\n\n # Fit the model on the batches generated by datagen.flow().\n history = model.fit(datagen.flow(x_train, y_train, batch_size=batch_size),\n validation_data=(x_test, y_test),\n epochs=epochs, verbose=1, workers=5,\n callbacks=callbacks)",
"Using real-time data augmentation.\nEpoch 1/100\nLearning rate: 0.001\n391/391 [==============================] - 122s 299ms/step - loss: 3.1097 - accuracy: 0.2984 - val_loss: 2.5688 - val_accuracy: 0.4199\n\nEpoch 00001: val_accuracy improved from -inf to 0.41990, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.001.h5\nEpoch 2/100\nLearning rate: 0.001\n391/391 [==============================] - 115s 292ms/step - loss: 2.1647 - accuracy: 0.4970 - val_loss: 2.0077 - val_accuracy: 0.5829\n\nEpoch 00002: val_accuracy improved from 0.41990 to 0.58290, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.002.h5\nEpoch 3/100\nLearning rate: 0.001\n391/391 [==============================] - 116s 293ms/step - loss: 1.8091 - accuracy: 0.6081 - val_loss: 1.7220 - val_accuracy: 0.6694\n\nEpoch 00003: val_accuracy improved from 0.58290 to 0.66940, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.003.h5\nEpoch 4/100\nLearning rate: 0.001\n391/391 [==============================] - 116s 294ms/step - loss: 1.5328 - accuracy: 0.6907 - val_loss: 1.3996 - val_accuracy: 0.7422\n\nEpoch 00004: val_accuracy improved from 0.66940 to 0.74220, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.004.h5\nEpoch 5/100\nLearning rate: 0.001\n391/391 [==============================] - 115s 292ms/step - loss: 1.3351 - accuracy: 0.7417 - val_loss: 1.4880 - val_accuracy: 0.7175\n\nEpoch 00005: val_accuracy did not improve from 0.74220\nEpoch 6/100\nLearning rate: 0.001\n391/391 [==============================] - 117s 295ms/step - loss: 1.2231 - accuracy: 0.7661 - val_loss: 1.3019 - val_accuracy: 0.7568\n\nEpoch 00006: val_accuracy improved from 0.74220 to 0.75680, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.006.h5\nEpoch 7/100\nLearning rate: 0.001\n391/391 [==============================] - 118s 300ms/step - loss: 1.1444 - accuracy: 0.7823 - val_loss: 1.0776 - val_accuracy: 0.8012\n\nEpoch 00007: val_accuracy improved from 0.75680 to 0.80120, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.007.h5\nEpoch 8/100\nLearning rate: 0.001\n391/391 [==============================] - 118s 300ms/step - loss: 1.0824 - accuracy: 0.7963 - val_loss: 1.1084 - val_accuracy: 0.7886\n\nEpoch 00008: val_accuracy did not improve from 0.80120\nEpoch 9/100\nLearning rate: 0.001\n391/391 [==============================] - 116s 294ms/step - loss: 1.0374 - accuracy: 0.8053 - val_loss: 1.1739 - val_accuracy: 0.7697\n\nEpoch 00009: val_accuracy did not improve from 0.80120\nEpoch 10/100\nLearning rate: 0.001\n391/391 [==============================] - 115s 292ms/step - loss: 1.0049 - accuracy: 0.8093 - val_loss: 1.4195 - val_accuracy: 0.7435\n\nEpoch 00010: val_accuracy did not improve from 0.80120\nEpoch 11/100\nLearning rate: 0.001\n391/391 [==============================] - 115s 292ms/step - loss: 0.9771 - accuracy: 0.8162 - val_loss: 1.2742 - val_accuracy: 0.7512\n\nEpoch 00011: val_accuracy did not improve from 0.80120\nEpoch 12/100\nLearning rate: 0.001\n391/391 [==============================] - 114s 289ms/step - loss: 0.9502 - accuracy: 0.8213 - val_loss: 1.1456 - val_accuracy: 0.7766\n\nEpoch 00012: val_accuracy did not improve from 0.80120\nEpoch 13/100\nLearning rate: 0.001\n391/391 [==============================] - 115s 292ms/step - loss: 0.9331 - accuracy: 0.8276 - val_loss: 0.9965 - val_accuracy: 0.8057\n\nEpoch 00013: val_accuracy improved from 0.80120 to 0.80570, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.013.h5\nEpoch 14/100\nLearning rate: 0.001\n391/391 [==============================] - 116s 294ms/step - loss: 0.9249 - accuracy: 0.8294 - val_loss: 1.0641 - val_accuracy: 0.7899\n\nEpoch 00014: val_accuracy did not improve from 0.80570\nEpoch 15/100\nLearning rate: 0.001\n391/391 [==============================] - 116s 293ms/step - loss: 0.9105 - accuracy: 0.8327 - val_loss: 0.9417 - val_accuracy: 0.8287\n\nEpoch 00015: val_accuracy improved from 0.80570 to 0.82870, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.015.h5\nEpoch 16/100\nLearning rate: 0.001\n391/391 [==============================] - 116s 295ms/step - loss: 0.8929 - accuracy: 0.8396 - val_loss: 1.0053 - val_accuracy: 0.8038\n\nEpoch 00016: val_accuracy did not improve from 0.82870\nEpoch 17/100\nLearning rate: 0.001\n391/391 [==============================] - 117s 296ms/step - loss: 0.8886 - accuracy: 0.8394 - val_loss: 1.0696 - val_accuracy: 0.7904\n\nEpoch 00017: val_accuracy did not improve from 0.82870\nEpoch 18/100\nLearning rate: 0.001\n391/391 [==============================] - 115s 291ms/step - loss: 0.8661 - accuracy: 0.8467 - val_loss: 1.0219 - val_accuracy: 0.8079\n\nEpoch 00018: val_accuracy did not improve from 0.82870\nEpoch 19/100\nLearning rate: 0.001\n391/391 [==============================] - 116s 292ms/step - loss: 0.8651 - accuracy: 0.8457 - val_loss: 0.9362 - val_accuracy: 0.8252\n\nEpoch 00019: val_accuracy did not improve from 0.82870\nEpoch 20/100\nLearning rate: 0.001\n391/391 [==============================] - 115s 291ms/step - loss: 0.8493 - accuracy: 0.8500 - val_loss: 0.8966 - val_accuracy: 0.8391\n\nEpoch 00020: val_accuracy improved from 0.82870 to 0.83910, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.020.h5\nEpoch 21/100\nLearning rate: 0.001\n391/391 [==============================] - 115s 293ms/step - loss: 0.8397 - accuracy: 0.8513 - val_loss: 0.9705 - val_accuracy: 0.8199\n\nEpoch 00021: val_accuracy did not improve from 0.83910\nEpoch 22/100\nLearning rate: 0.0001\n391/391 [==============================] - 115s 291ms/step - loss: 0.7396 - accuracy: 0.8847 - val_loss: 0.7168 - val_accuracy: 0.8922\n\nEpoch 00022: val_accuracy improved from 0.83910 to 0.89220, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.022.h5\nEpoch 23/100\nLearning rate: 0.0001\n391/391 [==============================] - 115s 291ms/step - loss: 0.6534 - accuracy: 0.9053 - val_loss: 0.6877 - val_accuracy: 0.8959\n\nEpoch 00023: val_accuracy improved from 0.89220 to 0.89590, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.023.h5\nEpoch 24/100\nLearning rate: 0.0001\n391/391 [==============================] - 114s 290ms/step - loss: 0.6194 - accuracy: 0.9121 - val_loss: 0.6542 - val_accuracy: 0.9046\n\nEpoch 00024: val_accuracy improved from 0.89590 to 0.90460, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.024.h5\nEpoch 25/100\nLearning rate: 0.0001\n391/391 [==============================] - 115s 291ms/step - loss: 0.5937 - accuracy: 0.9169 - val_loss: 0.6384 - val_accuracy: 0.9049\n\nEpoch 00025: val_accuracy improved from 0.90460 to 0.90490, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.025.h5\nEpoch 26/100\nLearning rate: 0.0001\n391/391 [==============================] - 115s 291ms/step - loss: 0.5676 - accuracy: 0.9218 - val_loss: 0.5998 - val_accuracy: 0.9126\n\nEpoch 00026: val_accuracy improved from 0.90490 to 0.91260, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.026.h5\nEpoch 27/100\nLearning rate: 0.0001\n391/391 [==============================] - 115s 291ms/step - loss: 0.5457 - accuracy: 0.9256 - val_loss: 0.5897 - val_accuracy: 0.9120\n\nEpoch 00027: val_accuracy did not improve from 0.91260\nEpoch 28/100\nLearning rate: 0.0001\n391/391 [==============================] - 115s 291ms/step - loss: 0.5336 - accuracy: 0.9243 - val_loss: 0.5815 - val_accuracy: 0.9144\n\nEpoch 00028: val_accuracy improved from 0.91260 to 0.91440, saving model to /home/vicdoja/repos/ComputerVision-Labs/saved_models/cifar10_Wide-ResNet20v1-5_model.028.h5\nEpoch 29/100\nLearning rate: 0.0001\n391/391 [==============================] - 115s 291ms/step - loss: 0.5107 - accuracy: 0.9284 - val_loss: 0.5981 - val_accuracy: 0.9068\n"
],
[
"# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])",
"313/313 [==============================] - 8s 26ms/step - loss: 0.4645 - accuracy: 0.9288\nTest loss: 0.46452197432518005\nTest accuracy: 0.9287999868392944\n"
],
[
"from matplotlib import pyplot as plt\n\n# \"Accuracy\"\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()\n# \"Loss\"\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecce1df366c2cab997d736c5fbc9bd466744c210 | 19,833 | ipynb | Jupyter Notebook | notebooks/GA_update.ipynb | emory-qtm/capstone-neighborhoodnexus-publicneeddashboard | 56ddf51ef8c901bf4fb0a9a9a155f9533fbd241f | [
"BSD-3-Clause"
] | null | null | null | notebooks/GA_update.ipynb | emory-qtm/capstone-neighborhoodnexus-publicneeddashboard | 56ddf51ef8c901bf4fb0a9a9a155f9533fbd241f | [
"BSD-3-Clause"
] | null | null | null | notebooks/GA_update.ipynb | emory-qtm/capstone-neighborhoodnexus-publicneeddashboard | 56ddf51ef8c901bf4fb0a9a9a155f9533fbd241f | [
"BSD-3-Clause"
] | 2 | 2021-04-06T03:44:50.000Z | 2021-06-01T18:29:11.000Z | 53.029412 | 2,513 | 0.502345 | [
[
[
"!pip install pytrends\nfrom pytrends.request import TrendReq\nimport pandas as pd\nfrom datetime import date\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom gspread_dataframe import get_as_dataframe, set_with_dataframe",
"Requirement already satisfied: pytrends in /usr/local/lib/python3.7/dist-packages (4.7.3)\nRequirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from pytrends) (4.2.6)\nRequirement already satisfied: pandas>=0.25 in /usr/local/lib/python3.7/dist-packages (from pytrends) (1.1.5)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pytrends) (2.23.0)\nRequirement already satisfied: numpy>=1.15.4 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.25->pytrends) (1.19.5)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.25->pytrends) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.25->pytrends) (2.8.1)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pytrends) (2.10)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pytrends) (1.24.3)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pytrends) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pytrends) (2020.12.5)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.25->pytrends) (1.15.0)\n"
],
[
"## daily range\ndate_range = pd.date_range(start=\"2020-10-01\", end=\"2020-11-01\")",
"_____no_output_____"
],
[
"## import pytrends, final df format\npytrends = TrendReq(hl='en-US', tz=360)\nfinal_df = pd.DataFrame([], columns = ['geoName', 'geoCode', 'value', 'topic', 'date'])",
"_____no_output_____"
],
[
"## keywords\nkw_list = ['Transportation', \n 'Domestic Violence']\n\ncat_list = ['Transportation', 'Domestic Violence']",
"_____no_output_____"
],
[
"idx = 0\n\nfor i in kw_list:\n ## temporary df format for each topic\n new_df = pd.DataFrame([], columns = ['geoName', 'geoCode', i, 'date'])\n \n for j in range(0, len(date_range)-1):\n tf = '' + date_range[j].strftime('%Y-%m-%d') + ' ' + date_range[j+1].strftime('%Y-%m-%d')\n pytrends.build_payload([i], timeframe = tf, geo='US-GA')\n df = pytrends.interest_by_region(resolution='CITY', inc_low_vol=True, inc_geo_code=True)\n df = df.reset_index()\n\n date = []\n for k in range(0, len(df)):\n date.append(date_range[j].strftime('%Y-%m-%d'))\n \n df['date'] = date\n new_df = new_df.append(df, ignore_index=True)\n \n\n new_df.rename(columns={i: 'value'}, inplace = True)\n\n ## add topic column\n cat = cat_list[idx]\n idx += 1\n topic = []\n for l in range(0, len(new_df)):\n topic.append(cat)\n new_df['topic'] = topic\n \n final_df = final_df.append(new_df, ignore_index= True)",
"_____no_output_____"
],
[
"final_df",
"_____no_output_____"
],
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n"
],
[
"## connecting gspreads\nscope = [\n'https://spreadsheets.google.com/feeds'\n]\njson_file_name = '/directory_stored_json_file/***.json' ## refers to the README to download your own JSON file\ncreds = ServiceAccountCredentials.from_json_keyfile_name(json_file_name, scope)\nclient = gspread.authorize(creds)\n\n## open by url\nspreadsheet_url = 'https://docs.google.com/spreadsheets/d/1y4nR64TtGQ0F9sUvE0hzDN1xh9TZYfb0u9un82TECKY/' # go on link to view dataset\nsheet = client.open_by_url(spreadsheet_url)\nworksheet = sheet.worksheet('Sheet1')\n\n## update google sheet\nexisting = get_as_dataframe(worksheet)\nexisting = existing.dropna(how=\"all\")\nexisting = existing.iloc[:, 0:5]\nupdate = existing.append(final_df, ignore_index= True)\nset_with_dataframe(worksheet, update)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecce328ee675c7c2cf0f5f26f6416480ed89e46d | 12,237 | ipynb | Jupyter Notebook | notebook/2.1-Manometry.ipynb | jdeldre/MAE103 | 1417d573636e7e88fc0dce795073b8f0a82634f2 | [
"MIT"
] | null | null | null | notebook/2.1-Manometry.ipynb | jdeldre/MAE103 | 1417d573636e7e88fc0dce795073b8f0a82634f2 | [
"MIT"
] | 1 | 2021-04-03T22:18:15.000Z | 2021-04-03T22:18:15.000Z | notebook/2.1-Manometry.ipynb | jdeldre/MAE103 | 1417d573636e7e88fc0dce795073b8f0a82634f2 | [
"MIT"
] | null | null | null | 26.091684 | 162 | 0.561657 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
ecce4533b2d12334962a74c0f99f0fda9e95add0 | 10,989 | ipynb | Jupyter Notebook | introductory/Comprehensive_Exercise.ipynb | tmlss2018/PracticalSessions | 7eb4336e96498b486b8ebf5120ade65bffaaba0b | [
"Unlicense"
] | 137 | 2018-07-06T15:46:08.000Z | 2021-11-18T10:50:37.000Z | introductory/Comprehensive_Exercise.ipynb | tmlss2018/PracticalSessions | 7eb4336e96498b486b8ebf5120ade65bffaaba0b | [
"Unlicense"
] | 1 | 2018-08-24T02:08:28.000Z | 2018-09-03T13:13:52.000Z | introductory/Comprehensive_Exercise.ipynb | tmlss2018/PracticalSessions | 7eb4336e96498b486b8ebf5120ade65bffaaba0b | [
"Unlicense"
] | 44 | 2018-07-06T14:29:37.000Z | 2021-08-07T04:09:28.000Z | 27.610553 | 167 | 0.471016 | [
[
[
"# Exercise: putting everything together\n\n\nIn this you will write code for a model that learns to classify mnist digits. You will use sonnet and tensorflow, tracking training progress with matplotlib.",
"_____no_output_____"
]
],
[
[
"# Install dm-sonnet with pip. Include all necessary imports.\n",
"_____no_output_____"
],
[
"tf.reset_default_graph()",
"_____no_output_____"
],
[
"# Fetch the mnist data from tf.keras.datasets.mnist.\n\nmnist_train, mnist_test = tf.keras.datasets.mnist.load_data()\n\n# Check what the data is like:\nprint('Training dataset:')\ntrain_input, train_label = mnist_train\nprint('* input shape:', train_input.shape)\nprint('* input min, mean, max:', train_input.min(), train_input.mean(), train_input.max())\nprint('* input dtype:', train_input.dtype)\nprint('* label shape:', train_label.shape)\nprint('* label min, mean, max:', train_label.min(), train_label.mean(), train_label.max())\nprint('* label dtype:', train_label.dtype)\n\ntest_input, test_label = mnist_test\nprint('Number of test examples:', test_input.shape[0])",
"_____no_output_____"
]
],
[
[
"Normalize the data into the \\[0, 1\\] interval. It's also a good idea to check the class distribution, but here we know that this is OK.\n\n",
"_____no_output_____"
]
],
[
[
"# Normalize both train_input and test_input so that it is in [0, 1].\n#\n# Also ensure the following data types:\n#\n# * train_input and test_input need to be np.float32.\n# * the labels need to be converted to np.int32.\n",
"_____no_output_____"
],
[
"# We can visualize the first few training examples using matplotlib.imshow()\n# in combination with the gallery function we defined.\n#\n# Copy the gallery function in this cell.\n\n",
"_____no_output_____"
],
[
"# Show the first 6 training images on a 1x6 grid.\n# Remember to use grayscale plotting.\n# Also print their corresponding labels in the same order.\n",
"_____no_output_____"
],
[
"# Write a function that turns the data into tensorflow datasets and into\n# tensors corresponding to batches of examples, returning these tensors.\n#\n# The train data should be\n#\n# * shuffled across the full dataset\n# * repeated indefinitely\n# * batched at size 64.\n#\n# Simply batch the test data.\n#\n# IMPORTANT: Add a final (singleton) axis to the inputs; the conv nets that\n# we will use will expect this.\n",
"_____no_output_____"
],
[
"# Make a sonnet module that has the following structure:\n#\n# 1. sonnet Conv2D with 16 channes, kernel shape 3, stride 1, padding 'SAME'\n# 2. max pooling with window_shape [3, 3], srides [2, 2], padding 'SAME'\n# 3. ReLU\n# 4. sonnet Conv2D with 16 channes, kernel shape 3, stride 1, padding 'SAME'\n# 5. Flatten the final conv features using snt.BatchFlatten\n# 5. A (dense) Linear layer with output_size = 10, the number of classes.\n#\n# You can write the sonnet module yourself, or use the helper module\n# snt.Sequential([..layers..to..connect..]).\n\n",
"_____no_output_____"
],
[
"tf.reset_default_graph()\n(train_inputs, train_labels), (test_inputs, test_labels) = get_tf_data()\n",
"_____no_output_____"
],
[
"# 1. Instantiate a model\n# 2. Hook it up to the training data,\n# 3. Use the `tf.nn.sparse_softmax_cross_entropy_with_logits` op to define the loss\n# 4. Define the train_op that minimizes the loss (averaged over the batch)\n# using the `GradientDescentOptimizer`. Set the learning rate to 0.01.\n# 5. Get the initialization op.\n\n",
"_____no_output_____"
],
[
"# Write a function that takes a list of losses and plots them.\n\n",
"_____no_output_____"
],
[
"# Run the training loop, keeping track of losses and potentially the accuracy\n# on the training set. Plot the loss curve intermittently.\n#\n# The simplest solution would add a new plot with each plotting call. You\n# can play with the frequency of plotting (and recording) a bit in order\n# to find something that works.\n#\n# Based on the loss curves, decide how to set your total number of training\n# iterations. Once you are satified, add some code that evaluates your\n# prediction accuracy (not loss!) on the test set.\n#\n# Note that the outputs from the network are logits; for prediction accuracy\n# we can pick the most likely label and see if it is correct.\n\n# The accuracy you should expect:\n#\n# * Roughly 90% after 1000 training steps.\n# * 97-98% after 10k training steps.\n#\n# First iterate with 1k steps, if that works, train for 10k. 10k steps will\n# be roughly 6 minutes on CPU.\n\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecce4ad74cc66052bbc08feeae950794c0dc3a29 | 185,487 | ipynb | Jupyter Notebook | docs/examples/area_calcs.ipynb | ReginaPeralta/ReginaPeralta | 68ab1462083d40d7efb4af77d6fa915ad73de2b8 | [
"MIT"
] | null | null | null | docs/examples/area_calcs.ipynb | ReginaPeralta/ReginaPeralta | 68ab1462083d40d7efb4af77d6fa915ad73de2b8 | [
"MIT"
] | null | null | null | docs/examples/area_calcs.ipynb | ReginaPeralta/ReginaPeralta | 68ab1462083d40d7efb4af77d6fa915ad73de2b8 | [
"MIT"
] | null | null | null | 422.52164 | 21,608 | 0.9393 | [
[
[
"# Specific surface area determination\n\n## BET surface area\n\nLet's do a calculation of the BET surface area for these samples. First, make sure the data is imported by running the previous notebook.",
"_____no_output_____"
]
],
[
[
"%run import.ipynb",
"Selected 5 isotherms with nitrogen at 77K\nSelected 2 room temperature calorimetry isotherms\nSelected 2 isotherms for IAST calculation\nSelected 3 isotherms for isosteric enthalpy calculation\n"
]
],
[
[
"We use the `area_BET` function, and we first want to look at how the framework attempts to calculate the good BET region on its own. For this we pass the `verbose` parameter and then use matplotlib to display the graph.",
"_____no_output_____"
]
],
[
[
"isotherm = next(i for i in isotherms_n2_77k if i.material=='MCM-41')\nprint(isotherm.material)\npygaps.area_BET(isotherm, verbose=True)\nplt.show()",
"MCM-41\nBET surface area: a = 360 m2/g\nMinimum pressure point chosen is 0.034 and maximum is 0.256\nThe slope of the BET fit: s = 268.434\nThe intercept of the BET fit: i = 2.264\nThe BET constant is: C = 119\nAmount for a monolayer: n = 0.00369 mol/g\n"
]
],
[
[
"It looks that the correlation is reasonably good. A warning is emmited if this is not the case. We can also restrict the pressure range manually to see what difference it would make.",
"_____no_output_____"
]
],
[
[
"pygaps.area_BET(isotherm, limits=(0.05, 0.2), verbose=True)\nplt.show()",
"BET surface area: a = 362 m2/g\nMinimum pressure point chosen is 0.051 and maximum is 0.194\nThe slope of the BET fit: s = 267.285\nThe intercept of the BET fit: i = 2.423\nThe BET constant is: C = 111\nAmount for a monolayer: n = 0.00371 mol/g\n"
]
],
[
[
"Now let's do the analysis on all of the nitrogen samples. Instead of sequential calculations, we'll assume the framework makes a reasonably accurate choice. The function returns a dictionary with all the calculated parameters, so we'll just select the BET area from there.",
"_____no_output_____"
]
],
[
[
"results = []\nfor isotherm in isotherms_n2_77k:\n results.append((isotherm.material, pygaps.area_BET(isotherm)))\n \n[(x, y['area']) for (x,y) in results]",
"_____no_output_____"
]
],
[
[
"We also have isotherms which were measured with $CO_2$ at room temperature. While there's no guarantee that the BET method is still applicable with this adsorbate and temperature, the framework can still attempt to perform the calculations.\n\nIt just happens that the carbon sample is the same in both isotherms. Let's see how the $CO_2$ BET surface area looks.",
"_____no_output_____"
]
],
[
[
"isotherm = next(i for i in isotherms_calorimetry if i.material=='Takeda 5A')\nprint(isotherm.material)\npygaps.area_BET(isotherm, verbose=True)\nplt.show()",
"Takeda 5A\nBET surface area: a = 782 m2/g\nMinimum pressure point chosen is 0.027 and maximum is 0.253\nThe slope of the BET fit: s = 125.958\nThe intercept of the BET fit: i = 5.04\nThe BET constant is: C = 26\nAmount for a monolayer: n = 0.00763 mol/g\n"
]
],
[
[
"The surface area obtained with carbon dioxide is around 780 $m^2$. Compared to the nitrogen surface area of 1100 $m^2$, it is much smaller. While the checks implemented did not find anything wrong, this is likely due to interactions between carbon dioxide and the carbon surface leading to the breakdown of the BET theory.\n\nWhile any kind of adsorbate and temperature can be analysed through the framework, result interpretation is left at the discretion of the user.\nMore info can be found in the [documentation of the\nmodule](https://pygaps.readthedocs.io/en/latest/reference/characterisation.html#module-pygaps.characterisation.area_bet).",
"_____no_output_____"
],
[
"## Langmuir surface area\n\nAnother common method of calculating specific surface area relies on fitting the isotherm with a Langmuir model. This model assumes adsorption is confined to a single layer. We use the `area_langmuir` function, and we first want to see the range selected by the standard method. For this we pass the `verbose` parameter and then use matplotlib to display the graph.",
"_____no_output_____"
]
],
[
[
"isotherm = next(i for i in isotherms_n2_77k if i.material=='MCM-41')\nprint(isotherm.material)\npygaps.area_langmuir(isotherm, verbose=True)\nplt.show()",
"MCM-41\nLangmuir surface area: a = 1409 m²/g\nMinimum pressure point chosen is 0.051 and maximum is 0.888\nThe slope of the Langmuir line: s = 69.221\nThe intercept of the Langmuir line: i = 25.424\nThe Langmuir constant is: K = 2\nAmount for a monolayer: n = 0.01445 mol/g\n"
]
],
[
[
"The correlation is not very good due to the mesopore condensation which is not predicted by the Langmuir model. Due to this, the area calculated is not realistic. We can select the a range in the monolayer adsorption regime for a better fit.",
"_____no_output_____"
]
],
[
[
"print(isotherm.material)\npygaps.area_langmuir(isotherm, limits=(0.05, 0.3), verbose=True)\nplt.show()",
"MCM-41\nLangmuir surface area: a = 528 m²/g\nMinimum pressure point chosen is 0.051 and maximum is 0.286\nThe slope of the Langmuir line: s = 184.623\nThe intercept of the Langmuir line: i = 7.389\nThe Langmuir constant is: K = 24\nAmount for a monolayer: n = 0.00542 mol/g\n"
]
],
[
[
"The fit is now better and the calculated area is also realistic. Comparing it to the BET area obtained previously, we see that it is higher by about 150 m2. Since adsoprtion is happening in multiple layers rather than a monolayer, it is likely that the value for complete coverage overshoots the actual value. In general the Langmuir surface area is not as widely applicable as the BET one.\n\nNow let's do the analysis on all of the nitrogen samples and compare the obtained surface areas with the BET ones.",
"_____no_output_____"
]
],
[
[
"area_langmuir = []\narea_langmuir_lim = []\narea_bet = []\nfor isotherm in isotherms_n2_77k:\n area_bet.append(pygaps.area_BET(isotherm)['area'])\n area_langmuir.append(pygaps.area_langmuir(isotherm)['area'])\n area_langmuir_lim.append(pygaps.area_langmuir(isotherm, limits=(0.01, 0.3))['area'])\n\nfig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,5))\nax1.scatter(area_langmuir, area_bet)\nax2.scatter(area_langmuir_lim, area_bet)\n\nax1.set_title('BET v Langmuir area, full range')\nax2.set_title('BET v Langmuir area, low pressure range')\n\nax1.set_xlim(left=0, right=2000)\nax1.set_ylim(bottom=0, top=2000)\nax2.set_xlim(left=0, right=2000)\nax2.set_ylim(bottom=0, top=2000)\n\nax1.set_xlabel('Langmuir surface area')\nax1.set_ylabel('BET surface area')\nax2.set_xlabel('Langmuir surface area')\nax2.set_ylabel('BET surface area')\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"We can see that some points correspond, while others are not as well correlated. Unless the adsorption isotherm respects the Langmuir model, the calculated surface areas do not match. However, if the Langmuir area is calculated in a low pressure regime, ideally before multilayer adsorption or condensation occurs, the two specific areas are better correlated (right graph).\n\n\nMore info can be found in the [documentation of the\nmodule](https://pygaps.readthedocs.io/en/latest/reference/characterisation.html#module-pygaps.characterisation.area_langmuir).",
"_____no_output_____"
]
]
] | [
"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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
ecce57641fcde254386fd16b8f7b706c4fb70ef0 | 2,349 | ipynb | Jupyter Notebook | Blender.ipynb | RayTeoh/blenderGoogleGPU | 57bf1b9b85fe6708b90478e3010f19e3bf597735 | [
"CC0-1.0"
] | null | null | null | Blender.ipynb | RayTeoh/blenderGoogleGPU | 57bf1b9b85fe6708b90478e3010f19e3bf597735 | [
"CC0-1.0"
] | null | null | null | Blender.ipynb | RayTeoh/blenderGoogleGPU | 57bf1b9b85fe6708b90478e3010f19e3bf597735 | [
"CC0-1.0"
] | null | null | null | 22.805825 | 143 | 0.47169 | [
[
[
"#",
"_____no_output_____"
]
],
[
[
"#Download Blender from Repository\n!wget https://download.blender.org/release/Blender2.92/blender-2.92.0-linux64.tar.xz",
"_____no_output_____"
],
[
"#Install Blender \n!tar xf blender-2.92.0-linux64.tar.xz",
"_____no_output_____"
],
[
"#Download some required libraries\n!apt install libboost-all-dev\n!apt install libgl1-mesa-dev",
"_____no_output_____"
],
[
"#Connect Google Drive\nfrom google.colab import drive\ndrive.mount('/gdrive')",
"_____no_output_____"
],
[
"filename = '/gdrive/MyDrive/BlenderRenders/donut.blend'",
"_____no_output_____"
],
[
"#Run Blender\n!sudo ./blender-2.92.0-linux64/blender -b $filename -noaudio -P '/gdrive/MyDrive/BlenderRenders/GPU.py' -E 'CYCLES' -f 1 -F 'PNG'\n#!sudo ./blender-2.92.0-linux64/blender -b $filename -noaudio -- --cycles-device CUDA -E 'CYCLES' -f 1 -F 'PNG'\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecce5cbe840dd2da73c4a22ad9cc6c014f205cd0 | 269,543 | ipynb | Jupyter Notebook | digits_ML_YouTube.ipynb | DhruvKumarPHY/YOUTUBE-CODING_MY_UNIVERSE | b7f7cdf61c9a1fe856834ca6fee3a40f0d4381e4 | [
"MIT"
] | null | null | null | digits_ML_YouTube.ipynb | DhruvKumarPHY/YOUTUBE-CODING_MY_UNIVERSE | b7f7cdf61c9a1fe856834ca6fee3a40f0d4381e4 | [
"MIT"
] | null | null | null | digits_ML_YouTube.ipynb | DhruvKumarPHY/YOUTUBE-CODING_MY_UNIVERSE | b7f7cdf61c9a1fe856834ca6fee3a40f0d4381e4 | [
"MIT"
] | null | null | null | 100.613289 | 82,056 | 0.803352 | [
[
[
"# Digits dataSet Sklearn",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import load_digits\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"digits = load_digits()",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"dir(digits)",
"_____no_output_____"
],
[
"print(digits[\"DESCR\"])",
".. _digits_dataset:\n\nOptical recognition of handwritten digits dataset\n--------------------------------------------------\n\n**Data Set Characteristics:**\n\n :Number of Instances: 1797\n :Number of Attributes: 64\n :Attribute Information: 8x8 image of integer pixels in the range 0..16.\n :Missing Attribute Values: None\n :Creator: E. Alpaydin (alpaydin '@' boun.edu.tr)\n :Date: July; 1998\n\nThis is a copy of the test set of the UCI ML hand-written digits datasets\nhttps://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits\n\nThe data set contains images of hand-written digits: 10 classes where\neach class refers to a digit.\n\nPreprocessing programs made available by NIST were used to extract\nnormalized bitmaps of handwritten digits from a preprinted form. From a\ntotal of 43 people, 30 contributed to the training set and different 13\nto the test set. 32x32 bitmaps are divided into nonoverlapping blocks of\n4x4 and the number of on pixels are counted in each block. This generates\nan input matrix of 8x8 where each element is an integer in the range\n0..16. This reduces dimensionality and gives invariance to small\ndistortions.\n\nFor info on NIST preprocessing routines, see M. D. Garris, J. L. Blue, G.\nT. Candela, D. L. Dimmick, J. Geist, P. J. Grother, S. A. Janet, and C.\nL. Wilson, NIST Form-Based Handprint Recognition System, NISTIR 5469,\n1994.\n\n.. topic:: References\n\n - C. Kaynak (1995) Methods of Combining Multiple Classifiers and Their\n Applications to Handwritten Digit Recognition, MSc Thesis, Institute of\n Graduate Studies in Science and Engineering, Bogazici University.\n - E. Alpaydin, C. Kaynak (1998) Cascading Classifiers, Kybernetika.\n - Ken Tang and Ponnuthurai N. Suganthan and Xi Yao and A. Kai Qin.\n Linear dimensionalityreduction using relevance weighted LDA. School of\n Electrical and Electronic Engineering Nanyang Technological University.\n 2005.\n - Claudio Gentile. A New Approximate Maximal Margin Classification\n Algorithm. NIPS. 2000.\n\n"
],
[
"digits",
"_____no_output_____"
],
[
"plt.matshow(digits.images[100])",
"_____no_output_____"
],
[
"# plt.gray()\nfor i in range(7):\n plt.matshow(digits.images[i]) # here, we have printed first seven digits in the digits dataset.",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"data = digits.data",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"digits.target_names",
"_____no_output_____"
],
[
"digits.feature_names",
"_____no_output_____"
],
[
"digits.target.shape",
"_____no_output_____"
],
[
"df1 = pd.DataFrame(data,digits.target)",
"_____no_output_____"
],
[
"df1.head() # here, have a clear dataset...",
"_____no_output_____"
],
[
"# let's add the Target column in df1\ndf1['target'] = digits.target",
"_____no_output_____"
],
[
"df1.head(20) # now , we hav ethe target column now ....",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"y = digits.target",
"_____no_output_____"
],
[
"X_train , X_test, Y_train, Y_test = train_test_split(df1,y , test_size = 0.3)",
"_____no_output_____"
]
],
[
[
"# rbf model",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# let's load our model \nfrom sklearn.svm import SVC\nrbf_model = SVC(kernel ='rbf')",
"_____no_output_____"
],
[
"rbf_model.fit(X_train,Y_train)",
"_____no_output_____"
],
[
"rbf_model.score(X_test,Y_test) # 97.9 % accuracy",
"_____no_output_____"
]
],
[
[
"# Linear Model",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# Using Linear kernel\nlinear_model = SVC(kernel='linear')",
"_____no_output_____"
],
[
"linear_model.fit(X_train,Y_train)",
"_____no_output_____"
],
[
"linear_model.score(X_test,Y_test) # 97.59% accuracy.",
"_____no_output_____"
]
],
[
[
"# Random Forest Classifier ",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestClassifier",
"_____no_output_____"
],
[
"Rmodel = RandomForestClassifier()",
"_____no_output_____"
],
[
"Rmodel.fit(X_train,Y_train)",
"_____no_output_____"
],
[
"Rmodel.score(X_test,Y_test)",
"_____no_output_____"
]
],
[
[
"# KNN Classifier\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"from sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=10)",
"_____no_output_____"
],
[
"knn.fit(X_train, Y_train)",
"_____no_output_____"
],
[
"knn.score(X_test, Y_test)",
"_____no_output_____"
],
[
"knn.score(X_train, Y_train)",
"_____no_output_____"
]
],
[
[
"# Confusion Matrix",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import confusion_matrix\ny_pred = knn.predict(X_test)\ncm = confusion_matrix(Y_test,y_pred)\ncm",
"_____no_output_____"
],
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sn\nplt.figure(figsize=(15,12))\nsn.heatmap(cm, annot=True)\nplt.xlabel('Predicted')\nplt.ylabel('Truth')",
"_____no_output_____"
]
],
[
[
"# Classification Report",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import classification_report\n\nprint(classification_report(Y_test, y_pred))",
" precision recall f1-score support\n\n 0 1.00 1.00 1.00 48\n 1 0.97 1.00 0.98 56\n 2 1.00 0.98 0.99 53\n 3 1.00 1.00 1.00 56\n 4 1.00 1.00 1.00 51\n 5 1.00 0.96 0.98 54\n 6 0.99 1.00 0.99 66\n 7 0.98 1.00 0.99 52\n 8 1.00 0.96 0.98 55\n 9 0.98 1.00 0.99 49\n\n accuracy 0.99 540\n macro avg 0.99 0.99 0.99 540\nweighted avg 0.99 0.99 0.99 540\n\n"
]
],
[
[
"----------------\n----------\n# Principal Component Analysis",
"_____no_output_____"
],
[
"### PCC makes the calculation much more easy by reducing the dimension of Data that are not that useful.",
"_____no_output_____"
]
],
[
[
"dx = pd.DataFrame(digits.data, columns=digits.feature_names)\ndx.head()",
"_____no_output_____"
],
[
"X = dx\nY = digits.target",
"_____no_output_____"
],
[
"# before using PCC , we have to sacle our data points\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\nX_scaled",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.3)",
"_____no_output_____"
],
[
"from sklearn.linear_model import LogisticRegression\n\nmodel = LogisticRegression()\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)",
"_____no_output_____"
]
],
[
[
"# DIMENTIONALITY REDUCTIONS",
"_____no_output_____"
]
],
[
[
"from sklearn.decomposition import PCA\n# PCA - Principal Component Analysis\n\nmodel = PCA(n_components=2) # here we are taking 2 dimensions instead of 64\ntransformed_data = model.fit_transform(data)",
"_____no_output_____"
],
[
"plt.scatter(transformed_data[:,0],transformed_data[:,1],s = 10,c = Y,cmap=plt.cm.Set3)\nplt.colorbar()\n# Here we can say that the labeled data shows us digits as categories and which can be visualized by colorbar as well",
"_____no_output_____"
],
[
"model.explained_variance_ratio_",
"_____no_output_____"
],
[
"# Let's do it for all 64 dimenssions\nmodel = PCA(n_components=64)\nmodel.fit(data)",
"_____no_output_____"
],
[
"x = model.explained_variance_ratio_ # Variation for each dimension is now given\nx",
"_____no_output_____"
],
[
" # PLOT\nplt.plot(x,\".\")",
"_____no_output_____"
],
[
"from numpy import cumsum\nplt.plot(cumsum(x),\".\") # 80% of the information is contained in 10 dimenssions alone.",
"_____no_output_____"
],
[
"from sklearn.decomposition import PCA\n\npca = PCA(0.95) # it is only going to use 95% of data\nX_pca = pca.fit_transform(X)\nX_pca.shape",
"_____no_output_____"
],
[
"pca.explained_variance_ratio_ # it shows the %age of information contained in each element.(i.e.,29)",
"_____no_output_____"
],
[
"pca.n_components_",
"_____no_output_____"
],
[
"X_pca",
"_____no_output_____"
],
[
"X_train_pca, X_test_pca, y_train, y_test = train_test_split(X_pca, y, test_size=0.2)",
"_____no_output_____"
],
[
"from sklearn.linear_model import LogisticRegression\n\nmodel = LogisticRegression(max_iter=1000)\nmodel.fit(X_train_pca, y_train)\nmodel.score(X_test_pca, y_test)",
"_____no_output_____"
],
[
"pca = PCA(n_components=2)\nX_pca = pca.fit_transform(X)\nX_pca.shape",
"_____no_output_____"
],
[
"X_pca",
"_____no_output_____"
],
[
"pca.explained_variance_ratio_",
"_____no_output_____"
],
[
"X_train_pca, X_test_pca, y_train, y_test = train_test_split(X_pca, y, test_size=0.2, random_state=30)\n\nmodel = LogisticRegression(max_iter=1000)\nmodel.fit(X_train_pca, y_train)\nmodel.score(X_test_pca, y_test)",
"_____no_output_____"
],
[
"%%timeit\nmodel.fit(X_train_pca, y_train)",
"323 ms ± 643 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"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"
]
] |
ecce6574cc93c2cdacd63c976d1f79c70cc3ff4d | 8,073 | ipynb | Jupyter Notebook | notebooks/dev/SDG_index.ipynb | nestauk/sdg-mapping | 9efb95e3e356a6f24f62d7173673f62c7fb80db8 | [
"MIT"
] | 1 | 2020-05-27T10:19:17.000Z | 2020-05-27T10:19:17.000Z | notebooks/dev/ao_01_sdg_index.ipynb | nestauk/sdg-mapping | 9efb95e3e356a6f24f62d7173673f62c7fb80db8 | [
"MIT"
] | 22 | 2020-04-29T15:57:31.000Z | 2021-07-06T16:09:47.000Z | notebooks/dev/ao_01_sdg_index.ipynb | nestauk/sdg-mapping | 9efb95e3e356a6f24f62d7173673f62c7fb80db8 | [
"MIT"
] | null | null | null | 23.4 | 111 | 0.519509 | [
[
[
"## Preamble",
"_____no_output_____"
]
],
[
[
"import sys\nimport os\nimport urllib\n\nimport json\nimport numpy as np\nimport pandas as pd\n\nfrom sdg_mapping import project_dir\nfrom sdg_mapping.utils.misc_utils import fetch",
"_____no_output_____"
]
],
[
[
"## Main",
"_____no_output_____"
]
],
[
[
"print(project_dir)\nyear =2019",
"_____no_output_____"
],
[
"with open(f'{project_dir}/data/aux/sdg_index_url_suffixes.json', 'r') as f:\n sdg_index_url_suffixes = json.load(f)\n print(sdg_index_url_suffixes)",
"_____no_output_____"
],
[
"for i,l in sdg_index_url_suffixes.items():\n print(l)",
"_____no_output_____"
],
[
"url = 'https://github.com/sdsna/2019GlobalIndex/raw/master/2019GlobalIndexResults.xlsx'",
"_____no_output_____"
],
[
"# urllib.request.urlretrieve(url, f'{project_dir}/data/raw/{year}_sdg_index.xlsx')",
"_____no_output_____"
],
[
"def fetch_index(year): #, fout=None\n url = None\n if year == 2019:\n url = 'https://github.com/sdsna/2019GlobalIndex/raw/master/2019GlobalIndexResults.xlsx'\n\n fname = f'{year}_sdg_index.xlsx'\n return urllib.request.urlretrieve(url, f'{project_dir}/data/raw/{fname}')\ndef sdg_index_file_path(year):\n\n fname = f'{year}_sdg_index.xlsx'\n return f'{project_dir}/data/raw/{fname}' #/sdg_index\ndef read_workbook(data_sheet_name, data_path):\n # SDR2019 Data\n df = pd.read_excel(open(data_path, 'rb'),\n sheet_name=data_sheet_name)\n df.columns = df.iloc[0].values\n return df\ndef parse_2019_sdg_index(dataset):\n #{project_dir}\n with open(f'{project_dir}/data/aux/sdg_index_mappings.json', 'r') as f:\n maps = json.load(f)\n \n trend_map = maps['trend_map']\n achievement_map = maps['achievement_map']\n\n sdg_index_19_df = dataset.drop([0]).reset_index(drop=True)\n \n trend_columns = [i for i in sdg_index_19_df.columns if 'Trend' in i]\n dashboard_columns = [i for i in sdg_index_19_df.columns if (('Dashboard' in i) and ('Goal' in i))]\n\n\n for j in trend_columns:\n sdg_index_19_df[j] = sdg_index_19_df[j].map(trend_map)\n for j in dashboard_columns:\n sdg_index_19_df[j] = sdg_index_19_df[j].map(achievement_map)\n\n# sdg_index_19_df.to_csv('test.csv')\n\n return sdg_index_19_df#[trend_columns]",
"_____no_output_____"
],
[
"fetch_index(2019)",
"_____no_output_____"
],
[
"fin = sdg_index_file_path(year)",
"_____no_output_____"
],
[
"df = read_workbook('SDR2019 Data', fin)",
"_____no_output_____"
],
[
"parse_2019_sdg_index(df)",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## Draft code",
"_____no_output_____"
]
],
[
[
"# sdg_index_19 = pd.read_excel(open('../../data/raw/2019GlobalIndexResults.xlsx', 'rb'),\n# sheet_name='SDR2019 Data')\nd ='../../data/raw/2019_sdg_index.xlsx'\nsdg_index_19 = pd.read_excel(open(d, 'rb'),\n sheet_name='SDR2019 Data', header = 1)\n# sdg_index_19.columns = sdg_index_19.iloc[0].values\n",
"_____no_output_____"
],
[
"maps = {\n 'trend_map' : {\n '.': np.nan,\n '↑': 'increasing_on_track',\n '➚': 'increasing_moderately',\n '→': 'stagnant',\n '↓': 'decreasing'\n },\n\n 'achievement_map' : {\n 'green': 'goal_achievement',\n 'yellow': 'challenges_remain',\n 'orange': 'significant_challenges',\n 'red': 'major_challenges'\n }\n}",
"_____no_output_____"
],
[
"with open(f'../../data/aux/sdg_index_mappings.json', 'w') as f:\n json.dump(maps,f)",
"_____no_output_____"
],
[
"with open(f'../../data/aux/sdg_index_mappings.json', 'r') as f:\n# parse_opts = f.read().decode(\"UTF-8\")\n parse_opts = json.load(f)\n",
"_____no_output_____"
],
[
"parse_opts['trend_map']",
"_____no_output_____"
],
[
"trend_map = {\n '.': np.nan,\n '↑': 'increasing_on_track',\n '➚': 'increasing_moderately',\n '→': 'stagnant',\n '↓': 'decreasing'\n}\n\nachievement_map = {\n 'green': 'goal_achievement',\n 'yellow': 'challenges_remain',\n 'orange': 'significant_challenges',\n 'red': 'major_challenges'\n}\n",
"_____no_output_____"
],
[
"sdg_index_19_df = sdg_index_19.drop([0]).reset_index(drop=True)",
"_____no_output_____"
],
[
"sdg_index_19_df.head()",
"_____no_output_____"
],
[
"trend_columns = [i for i in sdg_index_19_df.columns if 'Trend' in i]\ndashboard_columns = [i for i in sdg_index_19_df.columns if (('Dashboard' in i) and ('Goal' in i))]",
"_____no_output_____"
],
[
"for j in trend_columns:\n sdg_index_19_df[j] = sdg_index_19_df[j].map(trend_map)",
"_____no_output_____"
],
[
"for j in dashboard_columns:\n sdg_index_19_df[j] = sdg_index_19_df[j].map(achievement_map)",
"_____no_output_____"
],
[
"sdg_index_19_df[dashboard_columns]#.map(trend_map)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecce69f90b78ceb977a2f8379395992d643cff7b | 143,029 | ipynb | Jupyter Notebook | HW1/hw1.ipynb | bvshih/PHYS434 | c05826052d50e4c93da209e0b3f500453c5bc554 | [
"MIT"
] | null | null | null | HW1/hw1.ipynb | bvshih/PHYS434 | c05826052d50e4c93da209e0b3f500453c5bc554 | [
"MIT"
] | 4 | 2021-11-01T16:56:14.000Z | 2021-12-13T05:02:17.000Z | HW1/hw1.ipynb | bvshih/PHYS434 | c05826052d50e4c93da209e0b3f500453c5bc554 | [
"MIT"
] | null | null | null | 808.073446 | 42,620 | 0.955666 | [
[
[
"import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport scipy\nfrom scipy import stats\n\n#this sets the size of the plot to something useful\nplt.rcParams[\"figure.figsize\"] = (15,10)",
"_____no_output_____"
],
[
"d = stats.norm.rvs(loc = 3.0, scale = .01, size = 100000)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1, 1)\nax.hist(d,50, density=True)\nplt.tick_params(labelsize = 24)\nplt.xlim([2.95,3.05])\nx = np.linspace(2.95,3.05,1000)\nax.plot(x,stats.norm.pdf(x,loc = 3., scale = 0.01),linewidth = 8,alpha = 0.7)\nplt.show()",
"_____no_output_____"
],
[
"ax = plt.hist(d,50, density=True)\nplt.yscale('log')\nplt.tick_params(labelsize = 24)\nplt.xlim([2.95,3.05])\nplt.show()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1, 1)\nax.hist(d,50, density=True)\nplt.yscale('log')\nplt.tick_params(labelsize = 24)\nplt.xlim([2.95,3.05])\nx = np.linspace(2.95,3.05,1000)\nax.plot(x,stats.norm.pdf(x,loc = 3., scale = 0.01),linewidth = 8,alpha = 0.7)\nplt.show()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1, 1)\nax.hist(d,50, density=True)\nplt.semilogy()\nplt.tick_params(labelsize = 24)\nplt.xlim([2.95,3.05])\nx = np.linspace(2.95,3.05,1000)\nax.plot(x,stats.norm.pdf(x,loc = 3., scale = 0.01),linewidth = 8,alpha = 0.7)\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecce88db06c7d166fa0eb23e8ba773384c5f7d7a | 8,782 | ipynb | Jupyter Notebook | examples/widgets/File Upload Widget.ipynb | ptone/ipython | b91d6a658d4526746dcbfb62e653d71c5d84eee9 | [
"BSD-3-Clause-Clear"
] | 2 | 2015-02-10T18:00:31.000Z | 2015-05-01T02:53:46.000Z | examples/widgets/File Upload Widget.ipynb | khinsen/ipython | dfd5cb1d3e34048593ba537dacdbef08fe766624 | [
"BSD-3-Clause-Clear"
] | null | null | null | examples/widgets/File Upload Widget.ipynb | khinsen/ipython | dfd5cb1d3e34048593ba537dacdbef08fe766624 | [
"BSD-3-Clause-Clear"
] | 1 | 2021-05-22T13:52:12.000Z | 2021-05-22T13:52:12.000Z | 35.41129 | 285 | 0.45468 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
eccea2b739e090cc6f6c1e8883c3e2b957ed3be7 | 165,919 | ipynb | Jupyter Notebook | Kopie_van_glm.ipynb | aidenaislinn/python-for-text-analysis | e27fb4a0a982246d2f5c7e9b40de9140f7956cd3 | [
"Apache-2.0"
] | null | null | null | Kopie_van_glm.ipynb | aidenaislinn/python-for-text-analysis | e27fb4a0a982246d2f5c7e9b40de9140f7956cd3 | [
"Apache-2.0"
] | null | null | null | Kopie_van_glm.ipynb | aidenaislinn/python-for-text-analysis | e27fb4a0a982246d2f5c7e9b40de9140f7956cd3 | [
"Apache-2.0"
] | null | null | null | 44.710051 | 996 | 0.572996 | [
[
[
"<a href=\"https://colab.research.google.com/github/aidenaislinn/python-for-text-analysis/blob/master/Kopie_van_glm.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Neuroimaging week 2: modeling fMRI with the GLM\n\nThis week will be all about how most fMRI analyses are done: using the **GLM**.\nWe'll use example data for this notebook, the notebook assumes it's stored in a folder next to the notebook called `data`. You can download these data from Canvas, or the course GitHub page. \n\nWhen you upload these data to CoLab, make sure that you're pointing the data in the right direction. If you've saved the data to your `Colab Notebooks/data` folder, that is the following location: `/content/drive/My Drive/Colab Notebooks/data/`. The code below tries to set it up so that you don't need to worry about it.",
"_____no_output_____"
]
],
[
[
"# this will ask you to authenticate with Google\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\nimport os\nos.chdir('/content/drive/My Drive/Colab Notebooks/')",
"_____no_output_____"
]
],
[
[
"## About this week's lab\nThe GLM, or the General Linear Model, is a statistical model that underlies a range of statistical models that you're probably already familiar with: (M)ANOVA, t-test, F-test, and most importantly ordinary *linear regression*. \n\nBasically, the type of fMRI analysis you are going to learn in this course (often called 'univariate analysis' or 'Statistical Parametric Mapping') is just an ordinary linear regression model adapted to time-series data. We are going to assume that you know the basics of linear regression, such as what a beta-parameter is, what R-squared means, and what residuals are (but we'll give you a short recap on these concepts). \n\nGiven that you have some basic familiarity with these concepts, you will see during this tutorial that univariate fMRI analyses using the GLM are actually very straightforward. However, while relatively simple, it is **VERY** important that you understand all the concepts in this tutorial thoroughly, because it will be the basis for ALL the upcoming lectures and tutorials from this course. You will definitely use what you learn here in the Project. \n\nAs a consequence of the importance of the GLM, this week's lab is probably going to take quite long again (substantially longer than the upcoming weeks). So, you'll have to work hard this week, but it'll definitely pay off. Also, the material will seem quite mathematical, but it often serves a symbolic purpose: to show you how results (e.g. t-statistics) are influenced by different parts of the formulas within the GLM. Moreover, after showing and explaining you the formulas, we'll work it out in code examples (which are often *way* easier to understand!). Also, after explaining a certain aspect of the GLM, we'll ask you to think about it and practice with it in ToThink and ToDo questions.\n\nThat being said, by working through this tutorial and understanding the concepts it will introduce, you will have completed the most difficult and most elaborate part of this course; from here on, it will only get easier (and will take less time)!\n\n## What you'll learn\nAfter this week's lab ... \n* you know how the GLM is applied to fMRI data \n* you are able to implement a univariate (single-voxel) t-test from scratch in Python\n\n**Estimated time needed to complete**: 8-12 hours",
"_____no_output_____"
],
[
"## 1. Recap of linear regression\nTo refresh your memory on linear regression, we'll walk you through a recap of the technique's most important concepts.\nWe are going to work through a simple example. \n\nIn the code below, `y` will denote our *dependent variable* (the variable we try to model/explain) and `X` will denote our *independent variable(s)* (the variables we're using to try to explain `y`). Throughout the entire tutorial will use `X` to refer to our matrix of independent variables (also called \"predictors\" or \"regressors\", or simply \"design matrix\") and use `y` to refer to our dependent variable (also sometimes called \"target\").\n\nMoreover, the independent variables are often grouped in a single matrix (a 2D array, so to speak) - which is sometimes called the \"design matrix\" (because it 'designs' the way we want to model our dependent variable). As stated before, in this tutorial we store our design matrix - the set of our independent variables - in the variable `X` (or slight variations on that, like `X_new` or something). Importantly, it is often assumed (e.g. by statistics functions/software) that the design matrix takes the shape of $N\\ (observations) \\times P\\ (predictors)$. So, the rows refer to the sampled observations (also often called \"samples\", \"instances\", or simply \"data points\"). The columns refer to the separate independent variables that we use to model the dependent variable. For the dependent variable, it is often assumed that this is a single row-vector of shape $N \\times 1$.\n\n### 1.1. Notation\nNext, let's define some more conventions in notation. We will denote the total number of observations with **$N$**. Moreover, we'll denote **$i$** as the index of samples. To give an example, the formula below gives you the sum of our target variable:\n\n\\begin{align}\n\\mathrm{sum}(y) = \\sum_{i=1}^{N} y_{i} \n\\end{align}\n\nLastly, we denote the total number of predictors **$P$** and **$j$** as the index of our predictors. So, for example, if we wanted to sum over our predictors for a given sample **$i$**, we'd write: \n\n\\begin{align}\n\\mathrm{sum}(X_{i}) = \\sum_{j=1}^{P} X_{ij} \n\\end{align}\n\nTo practice with this notation, let's do a ToDo!",
"_____no_output_____"
]
],
[
[
"# First some imports\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nFrom the variable `arr` below (an array of shape $100 \\times 25$), calculate the mean over all samples ($N$) for the predictor at index $j = 4$ (i.e., the fourth predictor). Store the result in a variable named `mean_predictor_4`.\n\nRemember: Python has 0-based indexing!",
"_____no_output_____"
]
],
[
[
"np.random.seed(42)\narr = np.random.normal(0, 1, size=(100, 25))\n# Implement your ToDo here\n\nmean_predictor_4 = ...",
"_____no_output_____"
],
[
"'''Tests the above ToDo. '''\nnp.testing.assert_almost_equal(mean_predictor_4, np.mean(arr[:, 3]))",
"_____no_output_____"
]
],
[
[
"Now, let's look at an example. Throughout the example below, we will gradually explain the components of linear regression. For the example, we will use randomly generated data to create a dependent variable with 30 observations (\"samples\"; $N = 30$) and a single independent variable ($P = 1$) with, of course, also 30 observations. So both the independent and dependent variable are of shape $30 \\times 1$. Alright, let's get started!",
"_____no_output_____"
],
[
"First, we have to import a Python implementation of linear regression. We'll use the `lstsq` (\"least squares\") function from the `linalg` (linear algebra) subpackage of `numpy`, but we could have also used `scipy` or `sklearn` implementations - they're all the same under the hood.",
"_____no_output_____"
]
],
[
[
"from numpy.linalg import lstsq",
"_____no_output_____"
]
],
[
[
"Now, for our example let's create some randomly generated data. As discussed, we'll create two variables (of shape $30\\times 1$), which have a prespecified correlation of 0.8 (normally, you don't know this before doing the analysis of course, but we specify it here for the sake of the example). \n\nWe'll denote our independent variable `X` and our dependent variable `y`.",
"_____no_output_____"
]
],
[
[
"np.random.seed(1)\n\nprespecified_covariance = np.array([[1, .8],\n [.8, 1]])\n\ndata = np.random.multivariate_normal(mean=[3, 7], cov=prespecified_covariance, size=30)\n\n\"\"\" By default, when you slice out a single column (or row), numpy returns\nan array of shape (some_number,) instead of (some_number, 1). However, for our\nexamples, we often actually want shape (some_number, 1) so essentially we want to \n\"add\" an extra axis. This is done by the np.newaxis command. Mess around with\nit yourself to see how it works! \"\"\"\n\nX = data[:, 0, np.newaxis] # Here, we slice the first column (0) and immediately add a new axis!\ny = data[:, 1, np.newaxis] # same here\n\nprint('The shape of X is: %s' % (X.shape,))\nprint('The shape of y is: %s' % (y.shape,))",
"_____no_output_____"
]
],
[
[
"### 1.2. Modeling the intercept (offset)\nAs you probably were told in your previous statistics classes, you should always \"model the intercept\" when running any (regression) model. Technically, the intercept models some of the signal using a constant term. The parameter corresponding to the intercept (as calculated by linear regression), then, refers to *the average value of your $y$ variable when all predictors in $X$ are 0*. So, conceptually, the intercept models the mean when controlling for our (other) predictors.\n\nTo \"model the intercept\", you should add an extra \"constant predictor\" to your design matrix (`X`). This \"constant predictor\" means simply an array of shape $N \\times 1$ with a constant value, usually all ones. (You'll figure out *why* you should do this later in the tutorial.)\n\nRemember from week 1 how to create an array with ones? We can just use `np.ones(shape_of_desired_array)`!",
"_____no_output_____"
]
],
[
[
"n_obs = y.size\nintercept = np.ones((n_obs, 1)) # creates intercept of shape (N, 1)",
"_____no_output_____"
]
],
[
[
"Now, we want to add it to our design matrix (`X`). We can do this using the numpy function `np.hstack` (which is short for \"horizontal stack\", i.e. \"stacking columns horizontally\"). This function takes a tuple with arrays which show have the same amount of rows (for our data: both have 30 rows) and returns the a new array in which the arrays from the tuple are stacked (stacked shape should be $30 \\times 2$):",
"_____no_output_____"
]
],
[
[
"tuple_with_arrays = (intercept, X)\nX_with_icept = np.hstack(tuple_with_arrays)\n\n# Note: you could also simply do ...\n# X_with_icept = np.hstack((np.ones((y.size, 1)), X))\n# ... but arguably this is less 'readable' than the implementation above\n\nprint(\"Shape of X is now: %s\" % (X_with_icept.shape,))",
"_____no_output_____"
]
],
[
[
"Let's take a look at the X matrix (\"design matrix\") we have now. As you'll see, we have two columns: the first one is our intercept-predictor, and the second one is our 'regular' predictor.",
"_____no_output_____"
]
],
[
[
"print(X_with_icept)",
"_____no_output_____"
]
],
[
[
"Now, let's take a look at the data. We'll create a scatter-plot for this (we'll leave out the intercept):",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10, 10))\nplt.scatter(X_with_icept[:, 1], y)\nplt.xlabel('X', fontsize=25)\nplt.ylabel('y', fontsize=25)\nplt.xlim((0, 5))\nplt.ylim((0, 10))\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 1.3. Interpreting parameters in linear regression\nAs you can see, there seems to be some positive linear relationship between $X$ (just the independent variable without the intercept) and $y$. In other words, an increase in $X$ will lead to an increase in $y$. But, at this moment, *how much exactly* $y$ changes for a increase in $X$ is unknown. By doing a linear regression with $X$ as our predictor of $y$, we can quantify this! \n\nThe parameter, i.e. the \"thing\" that quantifies the influence of $X$ on $y$, calculated by this model is often called the **beta-parameter(s)** (but sometimes they're denoted as theta, or any other greek symbol/letter). The beta-parameter quantifies exactly how much $y$ changes if you increase $X$ by 1. Or, in other words, it quantifies how much influence $X$ has on $y$. In a formula ($\\delta$ stands for \"change in\")\\*: \n\n\\begin{align}\n\\beta_{j} = \\frac{\\delta y}{\\delta X_{j}} \n\\end{align}\n\nAs you probably realize, each predictor in $X$ (i.e., $X_{j}$) has a parameter ($\\beta_{j}$) that quantifies how much influence that predictor has on our target variable ($y$). This includes the intercept, our vector of ones (which is in textbooks often denoted by $\\beta_{0}$; they often don't write out $\\beta_{0}X_{0}$ because, if a vector of ones is used, $\\beta_{0}\\cdot 1$ simplifies to $\\beta_{0}$).\n\nThus, linear regression describes a model in which a set of beta-parameters are calculated to characterize the influence of each predictor in $X$ on $y$, that together explain $y$ as well as possible (but the model is usually not perfect, so there will be some *error*, or \"unexplained variance\"). As such, we can formulate the linear regression model as follows:\n\n\\begin{align}\ny = \\beta_{0} + X_{1}\\beta_{1} + X_{2}\\beta_{2} ... + X_{P}\\beta_{P} + \\epsilon\n\\end{align}\n\nwhich is often written out as (and is equivalent to the formula above):\n\n\\begin{align}\ny = \\sum_{j=1}^{P}X_{j}\\beta_{j} + \\epsilon\n\\end{align}\n\nHere, $\\epsilon$ is the variance of $y$ that cannot be explained by our predictors (i.e, the *error*). ",
"_____no_output_____"
],
[
"But how does linear regression calculate the beta-parameters? The method most often used is called **'ordinary least squares'** (OLS; or just 'least squares' - remember the \"`from numpy.linalg import lstsq`\" ?). This method tries to find a \"weight(s)\" for the independent variable(s) such that when you multiply the weight(s) with the independent variable(s), it produces an estimate of $y$ (often denoted as $\\hat{y}$, or \"y-hat\") that is as 'close' to the true $y$ as possible. In other words, least squares tries to 'choose' the beta-parameter(s) such that the difference between $X$ multiplied with the beta(s) (i.e. our best guess of $y$, denoted as $\\hat{y}$) and the true $y$ is minimized\\*. \n\nLet's just formalize this formula for the 'best estimate of $y$' (i.e. $\\hat{y}$):\n\n\\begin{align}\n\\hat{y}_{i} = \\sum_{j=1}^{P}X_{ij}\\beta_{j} \n\\end{align}\n\n--------\n\\* Actually, least squares yields *an estimate* of the \"true\" (i.e. the population) beta-parameter. Usually, therefore, the beta-parameter is denoted with a \"hat\" ($\\hat{\\beta}$), to indicate that it is estimated, but because that clutters the formulas too much, we leave out the hat.",
"_____no_output_____"
],
[
"Before we're going into the estimation of these beta-parameters, let's practice with calculating $\\hat{y}$!",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n <b>ToDo</b> \n</div>\n\nBelow, we've defined a design matrix with two predictors (`this_X`) and an array with beta-estimates (`these_betas`; just pretend that these betas were estimated by us beforehand). Now, given this data, can you calculate the predicted $y$-values (i.e., $\\hat{y}$)? Store these predicted $y$-values in an array named `this_y_hat`.\n\nHint: your `this_y_hat` array should be of shape `(100,)`",
"_____no_output_____"
]
],
[
[
"this_X = np.random.normal(0, 1, (100, 2))\nthese_betas = np.array([5, 3])\n\nthis_y_hat = ...",
"_____no_output_____"
],
[
"''' Tests the above ToDo'''\nnp.testing.assert_array_almost_equal(this_X.dot(these_betas), this_y_hat)",
"_____no_output_____"
]
],
[
[
"In ordinary least squares, the difference that is tried to be minized is expressed as the sum of squared differences (hence the name 'least squares'!): \n\n\\begin{align}\n\\min_{\\beta} \\sum_{i=1}^{N}\\sum_{j=1}^{P}(y_{i} - X_{ij}\\hat{\\beta}_{j})^2 \n\\end{align}\n\nWhile it may look daunting, this formula simply says: \"find the beta(s) that minimize the difference of my prediction of $y$ (calculated as $X \\cdot \\beta$) and the true $y$. While the book describes how OLS finds beta-parameters (namely by the vectorized formula: $\\beta = (\\mathbf{X}'\\mathbf{X})^{-1}\\mathbf{X}'y$), we don't expect you to understand how this works exactly. But you should understand the objective of least squares (minimizing prediction of $y$ and true $y$) and what role the beta-parameters play in this process (i.e. a kind of weighting factor of the predictors).\n\nAlright, that's a lot of text (and math, ugh...). Let's actually run least squares to get the beta-parameters of our model!",
"_____no_output_____"
]
],
[
[
"# Note the inputs to lstsq: the design matrix (X) and the dependent variable (y)\n# We also input \"rcond=None\"; this is only to silence a warning from numpy,\n# it doesn't change the function itself (you can ignore this for now)\n\noutput_lstsq = lstsq(X_with_icept, y, rcond=None)\nbeta = output_lstsq[0]\nprint('The betas of my model are: %r' % beta.tolist())\n\n# Also note that there are more outputs of the function lstsq().\n# For now, we're only interested in the first output, which are the model's estimates betas.\n# To get these, we immediately index the outputs by [0]\n# We could have done this more concisely by (but didn't for clarity):\n# beta = lstsq(X_with_icept, y, rcond=None)[0]",
"_____no_output_____"
]
],
[
[
"\"What? Why are there two beta-parameters?\", you might think. This is of course because you also use the intercept as a predictor, which also has an associated beta-value (weighting factor). Here, the first beta refers to the intercept of the model (because it's the first column in the design-matrix)! The second beta refers to our 'original' predictor. Thus, the model found by least squares for our generated data is (i.e. that leads to our best estimate of $y$, i.e. $\\hat{y}$:\n\n\\begin{align}\n\\hat{y} = X_{1} \\cdot 4.259 + X_{2} \\cdot 0.882 \n\\end{align}\n\nAnd since our intercept (here $X_{1}$) is a vector of ones, the formula simplifies to:\n\n\\begin{align}\n\\hat{y} = 4.259 + X_{2} \\cdot 0.882\n\\end{align}\n\nNow, let's calculate our predicted value of $y$ ($\\hat{y}$) by implementing the above formula by multiplying our betas with the corresponding predictors (intercept and original predictor). Here, because we have two predictors, we simply add the two \"`predictor * beta`\" terms to get the final $\\hat{y}$.",
"_____no_output_____"
]
],
[
[
"y_hat = X_with_icept[:, 0] * beta[0] + X_with_icept[:, 1] * beta[1]\nprint('The predicted y-values are: \\n\\n%r' % y_hat)",
"_____no_output_____"
]
],
[
[
"Actually, using matrix algebra (which is often used in the text book), there is a 'trick' to quickly sum the results of two vector multiplications, called the dot-product. Check it out below:",
"_____no_output_____"
]
],
[
[
"y_hat2 = X_with_icept.dot(beta)\nprint('The predicted y-values (using dot-product) are: \\n\\n%r' % y_hat2.T)",
"_____no_output_____"
]
],
[
[
"In this (and upcoming) tutorials, you probably see the dot-notation for matrix multiplication more often, so understand that it (in this context) simply multiplies the columns of X with the corresponding betas and (element-wise) sums these columns to get the $\\hat{y}$ values! Thus, this notation:\n\n\\begin{align}\n\\hat{y}_{i} = \\sum_{j=1}^{P}X_{ij}\\hat{\\beta}_{j} \n\\end{align}\n\n... is exactly the same as the dot-product notation using matrix algebra:\n\n\\begin{align}\n\\hat{y}_{i} = \\mathbf{X}_{i}\\mathbf{\\hat{\\beta}} \n\\end{align}\n\nYou can usually recognize the implementations in formulas using algebra by the use of bold variables (such as $\\mathbf{X}$) here above.\n\n*You will calculate `y_hat` quite a lot throughout this lab; please use the dot-product-method to calculate `y_hat`, because this will prevent errors in the future!* So, use this ...\n\n```python\ny_hat = X.dot(betas)\n```\n\ninstead of ...\n\n```python\ny_hat = X[:, 0] * betas[0] + X[:, 1] * betas[1]\n```\n\nNow, let's plot the predicted $y$ values ($\\hat{y}$) against the true $y$ values ($y$).",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10, 10))\nplt.scatter(X, y)\nplt.xlabel('X', fontsize=25)\nplt.ylabel('y', fontsize=25)\nx_lim = (0, 5)\nplt.xlim(x_lim)\nplt.ylim((0, 10))\ny_hat = X_with_icept.dot(beta) # using the matrix algebra approach!\nplt.plot(X, y_hat, marker='.', c='tab:orange', markersize=10)\nplt.legend(['Predicted y', 'True y'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"Actually, let's just plot the predicted y-values as a line (effectively interpolating between adjacent predictions) - this gives us the linear regression plot as you've probably seen many times in your statistics classes!",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10, 10))\nplt.scatter(X, y)\nplt.xlabel('X', fontsize=25)\nplt.ylabel('y', fontsize=25)\nplt.xlim(x_lim)\nplt.ylim((0, 10))\ny_min_pred = beta[0] + beta[1] * x_lim[0]\ny_max_pred = beta[0] + beta[1] * x_lim[1]\nplt.plot(x_lim, [y_min_pred, y_max_pred], ls='-', c='tab:orange', lw=3)\nplt.legend(['Predicted y', 'True y'])\nplt.title('Linear regression of X onto y')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 1.4. Residuals and model fit\nAlright, so now we have established the beta-values that lead to the best prediction of $y$ - in other words, the best fit of our model. But how do we quantify the fit of our model? One way is to look at the difference between $\\hat{y}$ and y, which is often referred to as the model's **residuals**. This difference between $\\hat{y}$ and $y$ - the residuals - is the exact same thing as the $\\epsilon$ in the linear regression model, i.e. the **error** of the model. Thus: \n\n\\begin{align}\nresidual = y - \\hat{y} = \\epsilon \n\\end{align}\n\nTo visualize the residuals (plotted as red dashed lines):",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10, 10))\nplt.scatter(X, y)\nplt.xlabel('X')\nplt.ylabel('y')\nplt.xlim(x_lim)\nplt.ylim((0, 10))\ny_min_pred = beta[0] + beta[1] * x_lim[0]\ny_max_pred = beta[0] + beta[1] * x_lim[1]\nplt.plot(x_lim, [y_min_pred, y_max_pred], ls='-', c='orange')\nplt.title('Linear regression of X onto y')\n\nfor i in range(y.size):\n plt.plot((X[i], X[i]), (y_hat[i], y[i]), linestyle='--', c='red', lw=2)\n\nplt.legend(['Predicted y', 'True y', 'Residual'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"In fact, the model fit is often summarized as the **mean of the squared residuals** (also called the 'mean squared error' or MSE), which is thus simply the (length of the) red lines squared and averaged. In other words, the MSE refers to the average squared difference between our predicted $y$ and the true $y$\\*:\n\n\\begin{align}\nMSE = \\frac{1}{N}\\sum_{i=1}^{N} (y_{i} - \\hat{y}_{i})^2\n\\end{align}\n\n\\* The \"$\\frac{1}{N}\\sum_{i=1}^{N}$\" is just a different (but equally correct) way of writing \"the average of all residuals from sample 1 to sample N\".",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nCalculate the MSE for our previous model predictions (`y_hat`) based on our linear regression model predicting `y` from `X_with_intercept`. *Do not use a for-loop for this.* You know how to do this without a loop, using vectorized numpy array math. Store the result in a variable named `mse`.",
"_____no_output_____"
]
],
[
[
"# Implement your ToDo here\nmse = ...",
"_____no_output_____"
],
[
"''' Tests the above ToDo. '''\nnp.testing.assert_almost_equal(mse, np.mean((y - y_hat) ** 2))",
"_____no_output_____"
]
],
[
[
"Another metric for model fit in linear regression is \"R-squared\" ($R²$). R-squared is calculated as follows:\n\n\\begin{align}\nR^2 = 1 - \\frac{\\sum_{i=1}^{N}(y_{i} - X_{i}\\hat{\\beta})^2}{\\sum_{i=1}^{N}(y_{i} - \\bar{y})^2}\n\\end{align}\n\nwhere $\\bar{y}$ represents the mean of $y$. As you can see, the formula for R-squared consists of two parts: the numerator ($\\sum_{i=1}^{N}(y_{i} - \\hat{y}_{i})^2$) and the denominator ($\\sum_{i=1}^{N}(y_{i} - \\bar{y}_{i})^2$). The denominator represents the *total* amount of squared error of the actual values ($y$) relative to the mean ($\\bar{y}$). The numerator represents the *reduced* squared errors when incorporating knowledge from our (weighted) independent variables ($X_{i}\\hat{\\beta}$). So, in a way you can interpret R-squared as *how much better my model is including `X` versus a model that only uses the mean*. Another conventional interpretation of R-squared is the amount of variance our predictors ($X$) together can explain of our target ($y$).\n\nAs expected, the code is quite straightforward:",
"_____no_output_____"
]
],
[
[
"numerator = np.sum((y - y_hat) ** 2) # remember, y_hat equals X * beta\ndenominator = np.sum((y - np.mean(y)) ** 2)\nr_squared = 1 - numerator / denominator\n\nprint('The R² value is: %.3f' % r_squared)",
"_____no_output_____"
]
],
[
[
"<div class='alert alert-warning'>\n <b>ToDo</b> \n</div>\n\nBelow, we've defined a design matrix (`X_test`, including an intercept) and a dependent variable (`y_test`). Run a linear regression model and calculate R-squared. Store the R-squared value (which should be a single number, a float) in a variable named `r_squared_test`.",
"_____no_output_____"
]
],
[
[
"data_tmp = np.load('data/data_todo_rsquared.npz')\nX_test, y_test = data_tmp['X'], data_tmp['y']\n\nb = lstsq...",
"_____no_output_____"
]
],
[
[
"<div class='alert alert-info'>\n<b>ToThink</b>\n</div>\n\nAs discussed earlier, it's important to model the intercept in regression models. This is because it often greatly *improves model fit*! In this ToThink, you have to explain *why* modelling the intercept (usually) improves model fit. \n\nTo give you some clues, we re-did the linear regression computation from above, but now without the intercept in the design matrix. We plotted the data (`X_no_icept`, `y`) and the model fit to get some intuition about the use of an intercept in models. \n\nIn the text-cell below the plot, explain (concisely!) why modelling the intercept (usually) improves model fit (this is not graded).",
"_____no_output_____"
]
],
[
[
"X_no_icept = X_with_icept[:, 1, np.newaxis]\nbeta_no_icept = lstsq(X_no_icept, y, rcond=None)[0]\ny_hat_no_icept = beta_no_icept * X_no_icept\n\nplt.figure(figsize=(10, 10))\nplt.scatter(X, y)\nplt.xlabel('X', fontsize=25)\nplt.ylabel('y', fontsize=25)\nplt.xlim((0, 5))\nplt.ylim((0, 10))\ny_min_pred = beta_no_icept[0] * x_lim[0]\ny_max_pred = beta_no_icept[0] * x_lim[1]\nplt.plot(x_lim, [y_min_pred, y_max_pred], ls='-', c='orange')\nplt.title('Linear regression of X (without intercept!) onto y', fontsize=20)\n\nfor i in range(y.size):\n plt.plot((X[i], X[i]), (y_hat_no_icept[i], y[i]), 'k-', linestyle='--', c='red', lw=2)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"\nA model without an intercept is \"forced\" to draw its line through the origin (0, 0), failing to explain much of the variance of targets (potential $y$ vectors) that have an offset/scale that is clearly far from 0 (which should be clear from the plot.)",
"_____no_output_____"
],
[
"### Summary: linear regression\nAlright, hopefully this short recap on linear regression has refreshed your knowledge and understanding of important concepts such as predictors/design matrix ($X$), target ($y$), least squares, beta-parameters, intercept, $\\hat{y}$, residuals, MSE, and $R^2$. \n\nIn sum, for a linear regression analysis you need some predictors ($X$) to model some target ($y$). You perform ordinary least squares to find the beta-parameters that minimize the sum of squared residuals. To assess model fit, you can look at the mean squared error (mean of $(\\hat{y} - y)^2$) or simply the squared correlation between the the predicted and the actual $y$ values ($R² = corr(\\hat{y}, y)^2$). \n\nIf you understand the above sentence, you're good to go! Before we go on to the real interesting stuff (modelling fMRI data with linear regression), let's test how well you understand linear regression so far.",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nNow, you're going to implement your own linear regression on a new set of variables, but with a twist: you're going to use 5 predictors this time - we've generated the data for you already. You'll notice that the code isn't much different from when you'd implement linear regression for just a single predictor (+ intercept). In the end, you should have calculated MSE and $R^2$, which should be stored in variables named `mse_todo` and `r2_todo` respectively.\n\n*Note, though, that it **isn't** possible to plot the data (either X, y, or y_hat) because we have more than one predictor now; X is 5-dimensional (6-dimensional if you include the intercept) - and it's impossible to plot data in 5 dimensions!*\n\nTo give you some handles on how to approach the problem, you can follow these steps:\n\n1. Check the shape of your data: is the shape of X `(N, P)`? is the shape of y `(N, 1)`?\n2. Add an intercept to the model, use: `np.hstack`;\n3. Calculate the beta-parameters use `lstsq()`;\n4. Evaluate the model fit by calculating the MSE and R-squared;",
"_____no_output_____"
]
],
[
[
"# Here, we load the data\ndata = np.load('ToDo.npz')\nX, y = data['X'], data['y']",
"_____no_output_____"
],
[
"# 1. Check the shape of X and y\n\n",
"_____no_output_____"
],
[
"# 2. Add the intercept (perhaps define N first, so that your code will be more clear?) using np.hstack()\n\n",
"_____no_output_____"
],
[
"# 3. Calculate the betas using lstsq()\n\n",
"_____no_output_____"
],
[
"# 4. Calculate the MSE (store it in a variable named mse_todo)\n\nmse_todo = ...",
"_____no_output_____"
],
[
"# 5. Calculate R-squared (store it in a variable named r2_todo)\n\nr2_todo = ...",
"_____no_output_____"
],
[
"''' Tests the ToDo above, MSE part (only hidden tests). '''\n\nprint(\"Your answer is tested later by hidden tests! \"\n \"(i.e., you can't see whether it's correct at this moment)\")\n\nassert(np.round(mse_todo, 3) == 0.656)",
"_____no_output_____"
],
[
"''' Tests the ToDo above, R2-part part (only hidden tests). '''\n\nprint(\"Your answer is tested later by hidden tests! \"\n \"(i.e., you can't see whether it's correct at this moment)\")\n\nassert(np.round(r2_todo, 4) == 0.3409)\n",
"_____no_output_____"
]
],
[
[
"<div class='alert alert-info'>\n<b>ToThink</b>\n</div>\n\nLet's check whether you understand what a particular beta-parameter means.\n\n- Some of the betas are negative (i.e., $< 0$); what does this tell you about the effect of that particular condition/predictor? (.5 point; first text-cell)\n- The intercept-parameter (i.e., $\\beta_{0}$) should be about 6.6. What does this value tell us about the signal?\n\nWrite your answers in the text-cells below.",
"_____no_output_____"
],
[
"Negative betas simply state that an increase in particular predictor leads to a decrease in the target (and vice versa).",
"_____no_output_____"
],
[
"The intercept-parameter represents the 'baseline' of the signal, i.e., the average activity when there's no event (stimulus). In other words, it represents the average activity of $y$ when all predictors are held constant ($X_{j} = 0$ for every predictor $j$).",
"_____no_output_____"
],
[
"If you've finished the ToDo exercise and you're confident that you understand linear regression, you're ready to start with the fun part: applying linear regression to fMRI data!",
"_____no_output_____"
],
[
"## 2. GLM in fMRI analyses\n\n\nUnivariate fMRI analyses basically use the same linear regression model as we've explained above to model the activation of voxels (with some minor additions) based on some design-matrix.\n\n### 2.1. The target ($y$)\nHowever, compared to \"regular\" data, one major difference is that *the dependent variable ($y$) in fMRI analyses is timeseries data*, which means that the observations of the dependent variable (activation of voxels) vary across time. \n\nHow does such a time-series data look like? Let's look at a (simulated) time-series from a single voxel:",
"_____no_output_____"
]
],
[
[
"# import some stuff if you haven't done that already\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.linalg import lstsq\n%matplotlib inline",
"_____no_output_____"
],
[
"voxel_signal = np.load('data/example_voxel_signal.npy')\nplt.figure(figsize=(25, 5))\nplt.plot(voxel_signal, 'o')\nplt.xlabel('Time points (volumes)', fontsize=20)\nplt.ylabel('Activity (arbitrary units)', fontsize=20)\nx_lim, y_lim = (0, 400), (-2.5, 4)\nplt.xlim(x_lim)\nplt.ylim(y_lim)\nplt.title('Example of voxel signal', fontsize=25)\nplt.show()",
"_____no_output_____"
]
],
[
[
"So, the voxel timeseries (i.e. activation over time; often called 'signal') is our dependent variable ($y$). Thus, the different time points (with corresponding activity values) make up our observations/samples!",
"_____no_output_____"
],
[
"<div class='alert alert-info'>\n<b>ToThink</b>\n</div>\n\nSuppose that the TR (\"time to repetition\", i.e. how long it takes to measure each volume) of our acquisition was 2 seconds and we acquired 400 volumes (measurements) in our fMRI run (as you can see on the x-axis in the plot above) --\nthen how long did the experiment take in *seconds*? (not graded, so you don't have to write anything down!)",
"_____no_output_____"
],
[
"So, in the plot above, the data points represent the activity (in arbitrary units) of a single voxel across time (measured in volumes). This visualization of the time-series data as discrete measurements is not really intuitive. Usually, we plot the data as continuous line over time (but always remember: fMRI data is a discretely sampled signal -- *not* a continuous one). Let's plot it as a line:",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(25, 5))\nplt.plot(voxel_signal)\nplt.xlabel('Time points (volumes)', fontsize=20)\nplt.ylabel('Activity (arbitrary units)', fontsize=20)\nplt.xlim(x_lim)\nplt.ylim(y_lim)\nplt.title('Example of voxel signal', fontsize=25)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Alright, this looks better. \n\nOne important difference between time-series data and \"regular\" (non-time-series) data (as is common in most psychology research) is that *measurements in time-series data are often dependent*, while non-time-series data usually isn't.\n\nFor example, suppose that I measure the height of 100 people (i.e., non-time-series data). My measurement of person 25 is not dependent on the measurement of person 24 or person 26. In other words, it does not matter if I shuffle the measurements (i.e., the vector with 100 height measurements) for my analyses (e.g., if I wanted to do a t-test between the height of men and women in my sample). This is basically what is meant by the statement that the observations are *independent*. \n\nFor time-series data, however, measurements are usually dependent from one observation to the next. For example, if I observe the value of a certain stock on the stock market at a particular day; suppose that I observe that the next day the stock increases slightly in value. It is then (relatively) likely that the stock the day after that again increases in value. In other words, the *measurements are dependent* (in time; another term that is used is, they are \"autocorrelated\"). Consequently, shuffling time-series data will usually mess up analyses.",
"_____no_output_____"
],
[
"### 2.2. The predictors ($X$), or: what should we use to model our signal ($y$)?\nSo, we know what our target is (the time-series data), but what do we use to model/explain our signal? Well, in most neuroimaging research, your predictors are defined by your experimental design! In other words, your predictors consist of *whatever you think influenced your signal*.\n\nThis probably sounds nonsensical, which is likely caused by the fact that we derive our independent variables (predictors) in most (observational) psychological research differently. This is because in (observational) psychological studies *both the independent variables and the dependent variables are __measured__*. In other words, our predictors are just other variables that you measured in your study. \n\nIn neuroimaging research, however, we often derive our predictors not from measures variables but from properties of the particular experiment that we use in the MRI-scanner (or during EEG/MEG acquisiton, for that matter). In other words, we can use any property of the experiment that we believe explains our signal.\n\nAlright, probably still sounds vague. Let's imagine a (hypothetical) experiment in which we show subjects images of either circles or squares during fMRI acquisition, as depicted in the image below:\n\n\n\nNote that the interstimulus interval (ISI, i.e., the time between consecutive stimuli) of 50 seconds, here, is quite unrealistic; often, fMRI experiments have a much shorter ISI (e.g., around 3 seconds). Here, we will use an hypothetical experiment with an ISI of 50 seconds because that simplifies things a bit and will make figures easier to interpret.\n\nAnyway, let's talk about what predictors we could use given our experimental paradigm. One straighforward suggestion about properties that influence our signal is that our signal is influenced by the stimuli we show the participant during the experiment. As such, we could construct a predictor that predicts some response in the signal when a stimulus (here: a square or a circle) is present, and no response when a stimulus is absent.\n\nFortunately, we kept track of the onsets (in seconds!) of our stimuli during the experiment:",
"_____no_output_____"
]
],
[
[
"onsets_squares = np.array([10, 110, 210, 310, 410, 510, 610, 710])\nonsets_circles = np.array([60, 160, 260, 360, 460, 560, 660, 760])",
"_____no_output_____"
]
],
[
[
"In other words, the first circle-stimulus was presented at 60 seconds after the scan started and the last square-stimulus was presented 710 seconds after the can started.\n\nFor now, we'll ignore the difference between square-stimuli and circle-stimuli by creating a predictor that lumps the onsets of these two types of stimuli together in one array. This predictor thus reflects the hypothesis that the signal is affected by the presence of a stimulus (regardless of whether this was a square or a circle). (Later in the tutorial, we'll explain how to *compare* the effects of different conditions.)\n\nWe'll call this predictor simply `onsets_all`:",
"_____no_output_____"
]
],
[
[
"onsets_all = np.concatenate((onsets_squares, onsets_circles))\nprint(onsets_all)",
"_____no_output_____"
]
],
[
[
"Now, we need to do one last thing: convert the `onsets_all` vector into a proper predictor. Right now, the variable contains only the onsets, but a predictor should be an array with the same shape as the target (here: $400 \\times 1$). \n\nGiven that our predictor should represent the hypothesis that the signal responds to the presence of a stimulus (and doesn't respond when a stimulus is absent), we can construct our predictor as a vector of all zeros, except at indices corresponding to the onsets of our stimuli.\n\nWe do this below:",
"_____no_output_____"
]
],
[
[
"predictor_all = np.zeros((800, 1))\n\n# indexing only works with an array/list of integers (we had floats), so we have to convert\n# the datatype of values in onsets_all to int (using the method astype())\npredictor_all[onsets_all.astype(int)] = 1\n\nprint(\"Shape of predictor: %s\" % (predictor_all.shape,))\nprint(\"\\nContents of our predictor array:\\n%r\" % predictor_all.T)",
"_____no_output_____"
]
],
[
[
"However, if you look back at the plot of the voxel signal, you might notice that there is a problem in our stimulus-predictor - it seems to be on a different scale than the signal. And that's true! The signal from the voxel is measured in volumes (in total 400) while the stimulus-onsets are defined in seconds (in total 800)! \n\nWe can solve this by \"downsampling\" our onsets-array to represent the onsets on the scale of our TR. (Usually, you would downsample your onsets/predictors much later in your analysis, but for the sake of the example, we'll do it here already.)\n\nTo downsample, we're simply going to keep only our \"even\" samples (i.e., timepoint 0, 2, 4, ... 798) using a fancy Python slice-operation:",
"_____no_output_____"
]
],
[
[
"predictor_all_ds = predictor_all[0::2]\nprint(\"The downsampled predictor has now a shape of: %s\" % (predictor_all_ds.shape,))",
"_____no_output_____"
]
],
[
[
"Awesome! Now, we have a predictor ($X$) and a target ($y$) of the same shape, so we can apply linear regression! But before we do this, let's plot the predictor and the signal in the same plot:",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(25, 10))\nplt.plot(voxel_signal)\nplt.plot(predictor_all, lw=2)\nplt.xlim(x_lim)\nplt.ylim(y_lim)\nplt.xlabel('Time (in volumes)', fontsize=20)\nplt.ylabel('Activity (A.U.)', fontsize=20)\nplt.legend(['Voxel-timeseries', 'Predictor'], fontsize=15, loc='upper right')\nplt.title(\"Signal and the associated design\", fontsize=25)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Realize that plotting the predictor and the signal in the same plot is different than in the case of non-timeseries data! In non-timeseries data, we would plot a scatterplot with the target ($y$) on the y-axis and the predictor (column of $X$) on the x-axis. This is also possible for timeseries-data, but due to the fact that both the predictor and the target represent values across time, we can plot them \"on the same axis\". The nice thing about this is that for timeseries data, we can plot as many predictors in the same plot as we want!\n\nAnyway, in the above plot the orange line represents our predictor, which represents the hypothesis that the activity of the signal (the blue line) is significantly different when a stimulus is presented (the peaks in the orange line) than when no stimulus is presented (the flat parts of the orange line). \n\nOr, phrased differently (but mathematically equivalent): what is the effect of a unit increase in the predictor ($X = 0 = no\\ stimulus \\rightarrow X = 1 = stimulus$) on the target (the signal)? We can answer this question with linear regression of course!",
"_____no_output_____"
],
[
"### 2.3. Regression on fMRI data & interpretation parameters\nAs said before, applying regression analysis on fMRI data is done largely the same as on regular non-timeseries data. As always, we first need to stack an intercept. ",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nStack an intercept to the predictor (`predictor_all_ds`) and store the result in a variable named `X_simple`. Then, run linear regression on the signal (`voxel_signal`) and save the beta-parameters in a new variable named `betas_simple`. Finally, calculate MSE and $R^ 2$ for this model and store these values in new variables named `mse_simple` and `r2_simple`. ",
"_____no_output_____"
]
],
[
[
"# Implement the ToDo here\n\nX_simple = ...\nbetas_simple = ...\ny_hat_simple = ...\nmse_simple = ...\nr2_simple = ...",
"_____no_output_____"
]
],
[
[
"If you've done the ToDo correctly, you should have found the the following beta-parameters: 0.229 for the intercept and 0.290 for our stimulus-predictor. This means that our linear regression model for that voxel is as follows:\n\n\\begin{align}\ny_{voxel} = \\beta_{intercept} + X_{stim}\\beta_{stim} + \\epsilon = 0.229 + X_{stim}0.290 + \\epsilon\n\\end{align}\n\nThis simply means that for a unit increase in $X$ (i.e., $X = 0 \\rightarrow X = 1$), $y$ increases with 0.290. In other words, on average the signal is 0.290 higher when a stimulus is present compared to when a stimulus is absent!\n\nTo aid interpretation, let's plot the signal ($y$) and the predicted signal ($\\hat{y} = \\beta X$) in the same plot.",
"_____no_output_____"
]
],
[
[
"des = np.hstack((np.ones((400, 1)), predictor_all_ds))\nbetas_simple = np.linalg.lstsq(des, voxel_signal, rcond=None)[0]\nplt.figure(figsize=(25, 10))\nplt.plot(voxel_signal)\nplt.plot(des.dot(betas_simple), lw=2)\nplt.xlabel('Time (in volumes)', fontsize=20)\nplt.ylabel('Activity (A.U.)', fontsize=20)\nplt.xlim(x_lim)\nplt.ylim(y_lim)\nplt.legend(['True signal', 'Predicted signal'], loc='upper right', fontsize=15)\nplt.title(\"Signal and predicted signal\", fontsize=25)",
"_____no_output_____"
]
],
[
[
"The orange line represents the predicted signal, which is based on the original predictor ($X$) multiplied (or \"scaled\") by the associated beta-parameters ($\\beta$). Graphically, you can interpret the beta-parameter of the stimulus-predictor ($\\beta_{stim}$) as the maximum height of the peaks in the orange line\\* and the beta-parameter of the intercept ($\\beta_{intercept}$) as the difference from the flat portion of the orange line and 0 (i.e. the \"offset\" of the signal).\n\n---\n\\* This holds true only when the maximum value of the original predictor is 1 (which is true in our case)",
"_____no_output_____"
],
[
"Let's zoom in on a portion of the data to show this:",
"_____no_output_____"
]
],
[
[
"des = np.hstack((np.ones((400, 1)), predictor_all_ds))\nbetas_simple = np.linalg.lstsq(des, voxel_signal, rcond=None)[0]\ndes = des[20:60, :]\n\nplt.figure(figsize=(10, 5))\nplt.plot(voxel_signal[20:60])\nplt.plot(des.dot(betas_simple), lw=3)\nplt.xlabel('Time (in volumes)', fontsize=20)\nplt.ylabel('Activity (A.U.)', fontsize=20)\nplt.xlim(0, 40)\nplt.ylim(0, 1.1)\nplt.annotate('', xy=(10, betas_simple[0]), xytext=(10, betas_simple[1] + betas_simple[0]),\n arrowprops=dict(arrowstyle='<->', lw=3))\nplt.text(10, betas_simple.sum() + 0.05, r'$\\beta_{stim}$', horizontalalignment='center', fontsize=20)\n\nplt.annotate('', xy=(35, betas_simple[0]), xytext=(35, betas_simple[1] + betas_simple[0]),\n arrowprops=dict(arrowstyle='<->', lw=3))\nplt.text(35, betas_simple.sum() + 0.05, r'$\\beta_{stim}$', horizontalalignment='center', fontsize=20)\n\nplt.annotate('', xy=(12, 0), xytext=(12, betas_simple[0]),\n arrowprops=dict(arrowstyle='<->', lw=2))\nplt.text(12.5, 0.05, r'$\\beta_{intercept}$', fontsize=20)\n\nplt.legend(['True signal', 'Predicted signal'], fontsize=15, loc='upper right')\nplt.xticks(np.arange(0, 41, 5), np.arange(20, 61, 5));",
"_____no_output_____"
]
],
[
[
"Anyway, there seems to be an effect on voxel activity when we show a stimulus (increase of 0.290 in the signal on average), but (if you've done the ToDo correctly) you've also seen that the model fit is quite bad ($R^2 = 0.006$, about 0.6% explained variance) ...\n\nWhat is happening here? Is our voxel just super noisy? Or is something wrong with our model? We'll talk about this in the next section!",
"_____no_output_____"
],
[
"### 2.4. Using the BOLD-response in GLM models\nLet's go back to our original idea behind the predictor we created. We assumed that in order to model activity in response to our stimuli, our predictor should capture an increase/decrease in activity *at the moment of stimulus onset*. But this is, given our knowledge of the BOLD-response, kind of unrealistic to assume: it is impossible to measure instantaneous changes in neural activity in response to stimuli or tasks with fMRI, *because the BOLD-response is quite slow and usually peaks around 5-7 seconds **after** the 'true' neuronal activity (i.e. at cellular level)*. \n\nIn the above model, we have not incorporated either the lag (i.e. ~6 seconds) or the shape of the BOLD-response: we simply modelled activity as a response to an instantaneous stimulus event. \n\nYou can imagine that if you incorporate this knowledge about the BOLD-response into our model, the fit will likely get better! In this section, we'll investigate different ways to incorporate knowledge of the BOLD-response in our predictors.",
"_____no_output_____"
],
[
"#### 2.4.1. The canonical HRF\nThe easiest and most often-used approach to incorporating knowledge about the BOLD-response in univariate analyses of fMRI data is to assume that each voxel responds to a stimulus in a fixed way. In other words, that voxels always respond (activate/deactivate) to a stimulus in the same manner. This is known as using a \"canonical haemodynamic response function (HRF)\". Basically, an HRF is a formalization of how we think the a voxel is going to respond to a stimulus. A *canonical* HRF is the implementation of an HRF in which you use the same HRF for each voxel, participant, and condition. There are other implementations of HRFs (apart from the canonical), in which you can adjust the exact shape of the HRF based on the data you have; examples of these HRFs are *temporal basis sets* and *finite impulse reponse models* (FIR), which we'll discuss later.\n\nThere are different types of (canonical) HRFs; each models the assumed shape of the BOLD-response slightly differently. For this course, we'll use the most often used canonical HRF: the double-gamma HRF (which is a combination of different gamma functions).\n\nThe double-gamma HRF looks like this:",
"_____no_output_____"
]
],
[
[
"def double_gamma(x, lag=6, a2=12, b1=0.9, b2=0.9, c=0.35, scale=True):\n\n a1 = lag\n d1 = a1 * b1 \n d2 = a2 * b2 \n hrf = np.array([(t/(d1))**a1 * np.exp(-(t-d1)/b1) - c*(t/(d2))**a2 * np.exp(-(t-d2)/b2) for t in x])\n \n if scale:\n hrf = (1 - hrf.min()) * (hrf - hrf.min()) / (hrf.max() - hrf.min()) + hrf.min()\n return hrf\n\n\ndef single_gamma(x, lag=6, b=0.9, scale=True):\n b = b \n a = lag \n d = a * b\n hrf = (x/d)**a * np.exp(-(x-d)/b)\n \n if scale:\n hrf = (1 - hrf.min()) * (hrf - hrf.min()) / (hrf.max() - hrf.min()) + hrf.min()\n\n return hrf\n\n\n# Time-points refers to the desired length of the array\n# representing the HRF. Does not matter too much (as long\n# as it incorporates the full shape of the HRF, here: 25 seconds)\ntime_points = np.arange(25) \ndg_hrf = double_gamma(time_points, lag=6)\nplt.plot(dg_hrf)\nplt.xlabel('Time (in seconds!) after stimulus onset')\nplt.ylabel('Activity (A.U.)')\nplt.title('Double gamma HRF');",
"_____no_output_____"
]
],
[
[
"Note that the output of the HRF is defined in seconds! That is, it's at the same scale as our stimulus-predictor (the one that's not yet downsampled).\n\nBut how should we incorporate this HRF into our model? Traditionally, this is done using a mathematical operation called **convolution**. Basically, it \"slides\" the HRF across our 0-1 coded stimulus-vector from left to right and elementwise multiplies the HRF with the stimulus-vector. This is often denoted as:\n\n\\begin{align}\nX_{conv} = \\mathrm{HRF} * X_{original}\n\\end{align}\n\nin which $*$ is the symbol for convolution, $X_{original}$ is the original stimulus-vector, and $X_{conv}$ the result of the convolution.\n\nLet's plot an example to make it clearer. Suppose we have an onset-vector of length 100 (i.e., the experiment was 100 seconds long) with three stimulus presentations: at $t = 10$, $t = 40$, and $t = 70$. The stimulus-vector (upper plot), double-gamma HRF (right plot), and the result of the convolution of the stimulus-vector and the HRF (lower plot) looks as follows:",
"_____no_output_____"
]
],
[
[
"random_stimulus_onsets = [10, 40, 70]\nrandom_stim_vector = np.zeros(400)\nrandom_stim_vector[random_stimulus_onsets] = 1\n\nplt.figure(figsize=(15, 6))\nplt.subplot2grid((3, 3), (0, 0), colspan=2)\nplt.plot(random_stim_vector)\nplt.xlim((0, 100))\nplt.ylim((0, 1))\nplt.ylabel('Activity (A.U.)')\nplt.xlabel('Time (seconds)')\nplt.title('Stimulus events', fontsize=20)\n\nplt.subplot2grid((3, 3), (0, 2), rowspan=2)\nplt.plot(dg_hrf)\nplt.title('HRF', fontsize=20)\nplt.xlim(0, 24)\nplt.xlabel(\"Time (seconds)\")\n\nconvolved_stim_vector = np.convolve(random_stim_vector, dg_hrf, 'full')\nplt.subplot2grid((3, 3), (1, 0), colspan=2)\nplt.plot(convolved_stim_vector)\nplt.title('Convolved stimulus-vector', fontsize=20)\nplt.ylabel('Activity (A.U.)')\nplt.xlabel('Time (seconds)')\nplt.xlim(0, 100)\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"The result -- the convolved stimulus-vector -- is basically the output of a the multiplication of the HRF and the stimulus-events when you would \"slide\" the HRF across the stimulus vector. As you can see, the convolved stimulus-vector correctly shows the to-be-expected lag and shape of the BOLD-response! Given that this new predictor incorporates this knowledge of the to-be expected response, it will probably model the activity of our voxel way better. Note that the temporal resolution of your convolved regressor is necessary limited by the resolution of your data (i.e. the TR of your fMRI acquisition). That's why the convolved regressor doesn't look as \"smooth\" as the HRF. \n\nAs you can see in the code for the plot above, numpy provides us with a function to convolve two arrays:\n\n```python\nnp.convolve(array_1, array_2)\n```\n\nNow, we can convolve the HRF with out stimulus-predictor. Importantly, we want to do this convolution operation in the resolution of our onsets (here: seconds), not in the resolution of our signal (TR) (the reason for this is explained clearly in Jeanette Mumford's [video on the HRF](https://www.youtube.com/watch?v=5JNX34gYG7Q).)\nTherefore, we need to perform the convolution on the variable `predictor_all` (*not* the downsampled variable: `predictor_all_ds`)!\n\nWe'll do this below (we'll reuse the `dg_hrf` variable defined earlier):",
"_____no_output_____"
]
],
[
[
"'''We need to \"squeeze\" out the extra singleton axis, because that's\nwhat the np.convolve function expects, i.e., arrays of shape (N,) and NOT (N, 1)\nTo go from (N, 1) --> (N,) we'll use the squeeze() method'''\npredictor_conv = np.convolve(predictor_all.squeeze(), dg_hrf)\n\nprint(\"The shape of the convolved predictor after convolution: %s\" % (predictor_conv.shape,))\n\n# After convolution, we also neem to \"trim\" off some excess values from\n# the convolved signal (the reason for this is not important to understand)\npredictor_conv = predictor_conv[:predictor_all.size]\n\nprint(\"After trimming, the shape is: %s\" % (predictor_conv.shape,))\n\n# And we have to add a new axis again to go from shape (N,) to (N, 1),\n# which is important for stacking the intercept, later\npredictor_conv = predictor_conv[:, np.newaxis]\n\nprint(\"Shape after adding the new axis: %s\" % (predictor_conv.shape,))",
"_____no_output_____"
]
],
[
[
"It's a bit of a hassle (squeezing out the singleton axis, trimming, adding the axis back ...), but now we have a predictor which includes information about the expected HRF!\n\nLet's look at the predictor before and after convolution in the same plot:",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(25, 5))\nplt.plot(predictor_all)\nplt.plot(predictor_conv)\nplt.xlim(-1, 800)\nplt.title(\"Predictor before and after convolution\", fontsize=25)\nplt.xlabel(\"Time (seconds!)\", fontsize=20)\nplt.ylabel(\"Activity (A.U.)\", fontsize=20)\nplt.legend(['Before', 'After'], loc='upper right', fontsize=15)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Great! Our predictor now includes the expected 'lag' and shape of the HRF, and we can start analyzing our signal with our new convolved predictor! But before we'll do this, there is one more concept that we'll demonstrate. Remember the concept of **linear scaling** of the BOLD-response? This property of the BOLD-response states that it will linearly scale with the input it is given.\n\nLet's see how that works:",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15, 5))\n\none_stim = np.zeros(100)\none_stim[5] = 1\none_stim_conv = np.convolve(one_stim, dg_hrf)[:100]\ntwo_stim = np.zeros(100)\ntwo_stim[[5, 7]] = 1\ntwo_stim_conv = np.convolve(two_stim, dg_hrf)[:100]\nthree_stim = np.zeros(100)\nthree_stim[[5, 7, 9]] = 1\nthree_stim_conv = np.convolve(three_stim, dg_hrf)[:100]\n\nplt.subplot2grid((2, 3), (0, 0))\nplt.plot(one_stim)\nplt.title(\"One stimulus\", fontsize=25)\n\nplt.subplot2grid((2, 3), (0, 1))\nplt.plot(two_stim, c='tab:orange')\nplt.title(\"Two stimuli\", fontsize=25)\n\nplt.subplot2grid((2, 3), (0, 2))\nplt.plot(three_stim, c='tab:green')\nplt.title(\"Three stimuli\", fontsize=25)\n\nplt.subplot2grid((2, 3), (1, 0), colspan=3)\n\nplt.plot(one_stim_conv)\nplt.plot(two_stim_conv)\nplt.plot(three_stim_conv)\nplt.legend(['One stim', 'Two stim', 'Three stim'])\nplt.title('Linear scaling of HRF', fontsize=25)\nplt.ylabel('Activity (A.U.)', fontsize=20)\nplt.xlabel('Time (TR)', fontsize=20)\nplt.xlim(0, 100)\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"Also, in our random stimulus-vector above (and also in the example we showed earlier) we assumed that each image was only showed briefly (i.e. we only modelled the onset) - but what if a stimulus (or task) may take longer, say, 15 seconds? Let's see what happens.",
"_____no_output_____"
]
],
[
[
"random_stimulus_onsets2 = list(range(10, 25)) + list(range(40, 55)) + list(range(70, 85))\nrandom_stim_vector2 = np.zeros(100)\n\nrandom_stim_vector2[random_stimulus_onsets2] = 1\n\nplt.figure(figsize=(10, 6))\nplt.subplot(2, 1, 1)\n\nplt.plot(random_stim_vector2, c='tab:blue')\n\nplt.xlim((0, 100))\nplt.ylim((-.5, 1.2))\nplt.ylabel('Activity (A.U.)', fontsize=15)\n\nplt.title('Stimulus events', fontsize=20)\n\nconvolved_stim_vector2 = np.convolve(random_stim_vector2, dg_hrf)[:random_stim_vector2.size]\nplt.subplot(2, 1, 2)\nplt.plot(convolved_stim_vector2)\nplt.title('Convolved stimulus-vector', fontsize=20)\nplt.ylabel('Activity (A.U.)', fontsize=15)\nplt.xlabel('Time (seconds)', fontsize=15)\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"As you can see, convolution takes care to model the shape of the BOLD-response according to how long you specify the stimulus to take! ",
"_____no_output_____"
],
[
"<div class='alert alert-info'>\n<b>ToThink</b>\n</div>\n\nGiven the properties of the BOLD-response (and assuming linear-time invariance is not violated), would you expect the same or a different BOLD-response in response to 3 consecutive stimuli (of the same condition) of half a second second each (which follow each other immediately, i.e. without interstimulus interval) versus 1 stimulus of 1.5 seconds? Why? (Write your answer in the text-cell below)",
"_____no_output_____"
],
[
"Because the BOLD-response is so slow, it cannot distinguish between short consecutive stimuli and one longer stimulus (which is evident by the fact that after convolution of these two hypothetical stimulus-vectors, they look identical).",
"_____no_output_____"
],
[
"Actually, convolution can model *any* sequence of stimulus events, even stimuli with random onsets - just look at the plot below!\n\n(you can execute this cell below multiple times to see different random regressor shapes!)",
"_____no_output_____"
]
],
[
[
"random_stimulus_onsets3 = np.random.randint(0, 100, 25)\nrandom_stim_vector3 = np.zeros(100)\nrandom_stim_vector3[random_stimulus_onsets3] = 1\n\nplt.figure(figsize=(16, 5))\nplt.subplot(2, 1, 1)\n\nplt.axhline(0)\nfor i, event in enumerate(random_stim_vector3):\n if event != 0.0:\n plt.plot((i, i), (0, 1), 'k-', c='tab:blue')\n\nplt.xlim((0, 100))\nplt.ylim((-0.1, 1.1))\nplt.ylabel('Activity (A.U.)', fontsize=15)\nplt.title('Stimulus events', fontsize=15)\n\nconvolved_stim_vector3 = np.convolve(random_stim_vector3 * .5, dg_hrf, 'full')[:random_stim_vector3.size]\nplt.subplot(2, 1, 2)\nplt.plot(convolved_stim_vector3)\nplt.xlim(0, 100)\nplt.title('Convolved stimulus-vector', fontsize=20)\nplt.ylabel('Activity (A.U.)', fontsize=15)\nplt.xlabel('Time (seconds)', fontsize=15)\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"So, in summary, convolving the stimulus-onsets (and their duration) with the HRF gives us (probably) a better predictor of the voxel signal than just the stimulus-onset, because (1) it models the lag of the BOLD-response and (2) models the shape of the BOLD-response (accounting for the linear scaling principle). \n\nNow, we're *almost* ready to start analyzing our signal with the convolved predictor! The problem, at this moment, however is that the convolved predictor and the signal are on different scales!",
"_____no_output_____"
]
],
[
[
"print(\"Shape of convolved predictor: %s\" % (predictor_conv.shape,))\nprint(\"Shape of signal: %s\" % (voxel_signal.shape,))",
"_____no_output_____"
]
],
[
[
"To fix this, we need to downsample the predictor again, like we did earlier:",
"_____no_output_____"
]
],
[
[
"predictor_conv_ds = predictor_conv[::2]\nplt.figure(figsize=(25, 6))\nplt.plot(predictor_conv_ds)\nplt.xlim(x_lim)\nplt.title(\"Downsampled convolved predictor\", fontsize=25)\nplt.xlabel(\"Time (in volumes!)\", fontsize=20)\nplt.ylabel(\"Activity (A.U.)\", fontsize=20)\nplt.show()\n\nprint(\"Shape of downsampled predictor is now: %s\" % (predictor_all_ds.shape,))",
"_____no_output_____"
]
],
[
[
"Finally ... we're ready to see whether the HRF-based predictor *actually* models our original voxel signal (`voxel_signal`, from earlier in the tutorial) more accurately! Let's create a proper design-matrix ($X$) by stacking an intercept with the stimulus-regressor, perform the regression analysis, and check out the results (by plotting the predicted signal against the true signal). For comparison, we'll also plot the original (unconvolved) model as well!",
"_____no_output_____"
]
],
[
[
"intercept = np.ones((predictor_conv_ds.size, 1))\nX_conv = np.hstack((intercept, predictor_conv_ds))\nbetas_conv = lstsq(X_conv, voxel_signal, rcond=None)[0]\n\nplt.figure(figsize=(19, 8))\n\nplt.subplot(2, 1, 1)\nplt.plot(voxel_signal)\nplt.plot(X_conv.dot(betas_conv))\nplt.xlim(x_lim)\nplt.ylabel(\"Activity (A.U.)\", fontsize=15)\nplt.title(\"Model fit with *convolved* regressor\", fontsize=20)\nplt.legend(['True signal', 'Predicted signal'], fontsize=12, loc='upper right')\n\nplt.subplot(2, 1, 2)\nplt.plot(voxel_signal)\nplt.plot(X_simple.dot(betas_simple))\nplt.xlim(x_lim)\nplt.ylabel(\"Activity (A.U.)\", fontsize=15)\nplt.title(\"Model fit with original (*unconvolved*) regressor\", fontsize=20)\nplt.legend(['True signal', 'Predicted signal'], fontsize=12, loc='upper right')\nplt.xlabel(\"Time (volumes)\", fontsize=15)\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"Wow, that looks much better, right! First, let's inspect the beta-parameters:",
"_____no_output_____"
]
],
[
[
"print('The beta-parameter of our stimulus-predictor is now: %.3f' % betas_conv[1])\nprint('... which is %.3f times larger than the beta of our original '\n 'beta (based on the unconvolved predictors)!' % (betas_conv[1] / 0.290))",
"_____no_output_____"
]
],
[
[
"Like we did before, we'll zoom in and show you how the estimated beta-parameters relate tho the data:",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10, 5))\nplt.plot(voxel_signal[25:65])\nplt.plot(X_conv[25:65, :].dot(betas_conv), lw=3)\nplt.xlabel('Time (in volumes)', fontsize=20)\nplt.ylabel('Activity (A.U.)', fontsize=20)\nplt.xlim(0, 40)\nplt.ylim(-.5, 2)\nplt.annotate('', xy=(8, betas_conv[0]), xytext=(8, betas_conv[1]),\n arrowprops=dict(arrowstyle='<->', lw=3))\nplt.text(8, betas_conv.sum() + 0.05, r'$\\beta_{stim}$', horizontalalignment='center', fontsize=20)\n\nplt.annotate('', xy=(33, betas_conv[0]), xytext=(33, betas_conv[1]),\n arrowprops=dict(arrowstyle='<->', lw=3))\nplt.text(33, betas_conv.sum() + 0.05, r'$\\beta_{stim}$', horizontalalignment='center', fontsize=20)\n\nplt.annotate('', xy=(20, -0.03), xytext=(20, betas_conv[0] + 0.03),\n arrowprops=dict(arrowstyle='<->', lw=1))\nplt.text(20.5, 0.0, r'$\\beta_{intercept}$', fontsize=20)\nplt.axhline(0, ls='--', c='k', lw=0.5)\n\nplt.legend(['True signal', 'Predicted signal'], fontsize=15, loc='upper center')\nplt.xticks(np.arange(0, 41, 5), np.arange(25, 65, 5))\nplt.show()",
"_____no_output_____"
]
],
[
[
"Alright, so we seem to measure a way larger effect of our stimulus on the voxel activity, but is the model fit actually also better? Let's find out.",
"_____no_output_____"
]
],
[
[
"y_hat_conv = X_conv.dot(betas_conv)\ndes_tmp = np.hstack((np.ones((400, 1)), predictor_all_ds))\ny_hat_orig = des_tmp.dot(lstsq(des_tmp, voxel_signal, rcond=None)[0])\n\nMSE_conv = ((y_hat_conv - voxel_signal) ** 2).mean()\nMSE_orig = ((y_hat_orig - voxel_signal) ** 2).mean()\n\nprint(\"MSE of model with convolution is %.3f while the MSE of the model without convolution is %.3f\" %\n (MSE_conv, MSE_orig))\n\nR2_conv = 1 - (np.sum((voxel_signal - y_hat_conv) ** 2) / np.sum((voxel_signal - voxel_signal.mean()) ** 2))\nR2_orig = 1 - (np.sum((voxel_signal - y_hat_orig) ** 2) / np.sum((voxel_signal - voxel_signal.mean()) ** 2))\n\nprint(\"R-squared of model with convolution is %.5f and without convolution it is %.5f\" % \n (R2_conv, R2_orig))",
"_____no_output_____"
]
],
[
[
"From the model fit metrics above, we can safely conclude that (at least for this voxel), a design ($X$) in which we include information about the expected lag/shape of the HRF is *way* better than a 'HRF-naive' design (i.e. an unconvolved design). ",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nSo far, our examples were based on the stimulus-onsets of the two conditions (circles and squares) lumped together. This tested the hypothesis of our voxel responded to *any kind* of stimulus -- regardless of the condition (squares/circles) of the stimulus. Usually, however, you want to estimate the betas for each condition separately (i.e., how much each condition on average activates a voxel) and test the influence of each condition on the voxel separately (but estimated in the same model)! This is what you're going to do in this ToDo.\n\nWe provide you with the predictors for circles (`predictor_circles`) and for squares (`predictor_squares`) below. You have to do the following:\n\n- convolve each predictor with the double-gamma HRF (use `dg_hrf`) separately (don't forget to squeeze, trim, and add the axis back)\n- downsample the convolved predictors\n- stack an intercept and the two predictors **in a single design-matrix** ($X$) -- use `np.hstack((intercept, pred1, pred2))` for this\n- calculate the beta-parameters (estimated in a single model!)\n- calculate MSE (store this in the variable `mse_new`) and $R^2$ (store this in the variable `r2_new`)\n",
"_____no_output_____"
]
],
[
[
"predictor_circles = np.zeros((800, 1))\npredictor_circles[onsets_circles] = 1\n\npredictor_squares = np.zeros((800, 1))\npredictor_squares[onsets_squares] = 1\n\n# Implement your ToDo below\n\npred_circ_conv = ...\npred_squar_conv = ...\nX_new = ...\nX_new = ...\nb_new = ...\ny_hat_new = ...\nmse_new = ...\nr2_new = ...\n",
"_____no_output_____"
]
],
[
[
"<div class='alert alert-info'>\n<b>ToThink</b>\n</div>\n\nIf you've done the above ToDo correctly, you should have found that the model fit of the design-matrix with the circles and squares predictors separately (as you did in the ToDo) leads to a (somewhat) better model fit (lower MSE/higher $R^2$) than the design-matrix with the conditions lumped together in a single predictor (as we did earlier).\n\nArgue why you think this is the case here.",
"_____no_output_____"
],
[
"Because with separate predictors, the model can assign different effects to the two predictors. If the two conditions would in fact have a different effect on the voxel, then this would be impossible to model in the lumped-together scenario, because this model can only explain a \"common\" effect of the conditions.",
"_____no_output_____"
],
[
"#### 2.4.2. Temporal basis functions\nMost studies use a canonical HRF to convolve with their predictors. However, remember that using a canonical HRF assumes that the particular shape of that HRF will be appropriate for each voxel, each condition, and each subject in your study. This is quite a strong assumption. In fact, studies have shown that the exact shape of the HRF often differs between voxels, conditions, and subjects (as is explained in detail by the [video on basis sets](https://www.youtube.com/watch?v=YfeMIcDWwko&index=21&list=PLcvMDPDk-dSmTBejANv7kY2mFo1ni_gkA) by Tor Wager).\n\nIn fact, this might also be the case in our data! If you've done the ToDo correctly, you might have seen that the predictions ($\\hat{y}$) seem to \"peak\" too late for the circle-stimuli... In fact, let's plot the data ($y$) and the prediction based on the circles-predictor ($X_{circles}\\beta_{1}$) and the prediction based on the squares-predictor ($X_{squares}\\beta_{2}$) separately:",
"_____no_output_____"
]
],
[
[
"dg_hrf = double_gamma(np.arange(50)) \npred_circ_conv = np.convolve(predictor_circles.squeeze(), dg_hrf)[:800][:, np.newaxis]\npred_squar_conv = np.convolve(predictor_squares.squeeze(), dg_hrf)[:800][:, np.newaxis]\nX_new = np.hstack((np.ones((800, 1)), pred_circ_conv, pred_squar_conv))\nX_new = X_new[::2, :]\nb_new = np.linalg.lstsq(X_new, voxel_signal, rcond=None)[0]\ncirc_hat = b_new[0] + b_new[1] * X_new[:, 1]\nsquar_hat = b_new[0] + b_new[2] * X_new[:, 2]\ny_hat_new = X_new.dot(b_new)\nplt.figure(figsize=(25, 8))\nplt.plot(voxel_signal[250:])\nplt.plot(circ_hat[250:], lw=3)\nplt.plot(squar_hat[250:], lw=3)\nplt.xticks(np.arange(0, 151, 50), np.arange(250, 401, 50))\nplt.xlim(0, 150)\nplt.xlabel(\"Time (volumes)\", fontsize=20)\nplt.ylabel(\"Activity (A.U.)\", fontsize=20)\nplt.title(\"Model fit per predictor (for last 150 volumes)\", fontsize=25)\nplt.legend(['signal', 'circles-predictor', 'squares-predictor'], fontsize=15)",
"_____no_output_____"
]
],
[
[
"So, what should be do about this? Well, one solution is to use *temporal basis functions* (also called *temporal basis sets*). Temporal basis functions model the HRF as *a combination of (haemodynamic response) functions*. \n\nIn practice, this amounts to convolving your predictor with not one, but multiple HRFs. This results in multiple predictors per stimulus-condition! Each HRF measures a \"part\" (or property) of the total HRF. Together, these predictors aim to estimate the complete HRF for a given stimulus-vector (condition). \n\nWe're going to use *single-gamma basis functions* as an example of a temporal basis set (but there are other sets, like the *sine basis set* and *finite impulse response* set). In this particular basis set, the original single-gamma HRF is used in combination with its first derivative (often called the 'temporal derivative') and its second derivative (the derivative of the derivative, so to say; often called the 'dispersion derivative'). \n\nSuppose we have only one stimulus condition. Then, the signal ($y$) is not modelled by only one convolved predictor ($\\beta X$) but by three predictors: a predictor convolved with the original HRF ($X_{orig}\\beta_{1}$), a predictor convolved with the temporal derivative of the HRF ($X_{temp}\\beta_{2}$), and a predictor convolved with the dispersion derivative of the HRF ($X_{disp}\\beta_{3}$). Formally:\n\n\\begin{align}\ny = \\beta_{0} + X_{orig}\\beta_{1} + X_{temp}\\beta_{2} + X_{disp}\\beta_{3} + \\epsilon\n\\end{align}\n\nAlright, but how do we compute these derivatives and how do they look like? Well, the derivatives are easily computed using the `np.diff` function, which takes an array and returns the value-by-value difference (i.e., for array $x$, it returns for each value $x_{i}$ the value $x_{i} - x_{i+1}$). \n\nLet's calculate and plot the first (temporal) derivative and second (dispersion) derivative:",
"_____no_output_____"
]
],
[
[
"sg_hrf = single_gamma(np.arange(0, 50))\nsg_hrf_temp = np.diff(sg_hrf)\nsg_hrf_disp = np.diff(sg_hrf_temp)\n\n# Differentiation trims of one value, so we need to add that back\nsg_hrf_temp = np.append(sg_hrf_temp, 0)\nsg_hrf_disp = np.append(sg_hrf_disp, [0, 0])\n\nplt.figure(figsize=(20, 5))\nplt.subplot(1, 3, 1)\nplt.plot(sg_hrf, lw=3)\nplt.ylim(-0.3, 1.1)\nplt.ylabel(\"Activity (A.U.)\", fontsize=25)\nplt.xlabel(\"Time (seconds)\", fontsize=15)\nplt.title(\"Original HRF\", fontsize=20)\n\nplt.subplot(1, 3, 2)\nplt.plot(sg_hrf_temp, c='tab:orange', lw=3)\nplt.ylim(-0.3, 1.1)\nplt.xlabel(\"Time (seconds)\", fontsize=15)\nplt.title(\"First (temporal) derivative\", fontsize=20)\n\nplt.subplot(1, 3, 3)\nplt.plot(sg_hrf_disp, c='tab:green', lw=3)\nplt.ylim(-0.3, 1.1)\nplt.xlabel(\"Time (seconds)\", fontsize=15)\nplt.title(\"Second (dispersion) derivative\", fontsize=20)\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"The cool thing about this single-gamma basis set is that the derivatives can (to a certain extent) correct for slight deviations in the lag and shape of the HRF based on the data! Specifically, the first (temporal) derivative can correct for slight differences in lag (compared to the canonical single-gamma HRF) and the second (dispersoin) derivative can correct for slight difference in the width (or \"dispersion\") of the HRF (compared to the canonical single-gamma HRF). \n\n\"How does this 'correction' work, then?\", you might ask. Well, think about it this way: the original (canonical) HRF measures the increase/decrease -- or amplitude -- of the BOLD-response. In a similar way, the temporal derivative measures the *onset* -- or lag -- of the BOLD-response. And finally the dispersion derivative measures the *width* of the BOLD-response. \n\nWhen we use our three predictors (one convolved with the canonical HRF, one with the temporal derivative, and one with the dispersion derivative) in a linear regression model, the model will assign each predictor (each part of the HRF) a beta-weight, as you know. These beta-weights are chosen such that model the data -- some response of the voxel to a stimulus -- as well as possible. Basically, assigning a (relatively) high beta-weight to the predictor convolved with the temporal derivative will \"shift\" the HRF (increases/decreases the onset of the HRF). Assigning a (relatively) high beta-weight to the predictor convolved with the dispersion derivative will increase/decrease the width of the HRF.\n\nAlright, let's visualize this. Suppose we have a voxel that we know does not conform to the specific assumptions about lag (onset) and width of the canonical (single-gamma) HRF. We'll show below that it suboptimally explains this voxel:",
"_____no_output_____"
]
],
[
[
"example_data = np.load('data/voxel_basissets_example.npz')\nexample_vox, onset_array = example_data['example_vox'], example_data['onset_array']\n\n# Then make design-matrix (by convolving the hrf with the onset-array)\npredictor_hrf_canonical = np.convolve(onset_array, sg_hrf)[:example_vox.size]\ndesign_mat = np.hstack((np .ones((example_vox.size, 1)), predictor_hrf_canonical[:, np.newaxis]))\n\n# Do regression \nbeta1 = lstsq(design_mat, example_vox, rcond=None)[0]\nyhat1 = design_mat.dot(beta1)\n\n# Plot the data and the prediction (y_hat)\nplt.figure(figsize=(15, 5))\nplt.plot(example_vox)\nplt.plot(yhat1)\nplt.xlim(0, 98)\nplt.xlabel(\"Time (seconds)\", fontsize=12)\nplt.ylabel(\"Activation (A.U.)\", fontsize=12)\nplt.annotate('', xy=(9, 0), xytext=(7, 0.2),\n arrowprops=dict(arrowstyle='->', lw=2))\nplt.text(8, 0.22, 'Stim\\nonset', horizontalalignment='right', fontsize=15)\nplt.legend(['signal', 'predicted signal'], fontsize=15)\nplt.title(\"Prediction with canonical HRF only\", fontsize=20)\nplt.show()",
"_____no_output_____"
]
],
[
[
"As you can see, the predicted signal (orange line) misses the peak of the BOLD-response and is also slightly too narrow. Now, let's see what happens if we add the temporal derivate to the model and both the temporal and the dispersion derivative:",
"_____no_output_____"
]
],
[
[
"predictor_hrf_temporal = np.convolve(onset_array, sg_hrf_temp)[:example_vox.size]\ndesign_mat2 = np.hstack((design_mat, predictor_hrf_temporal[:, np.newaxis]))\n\n# Do regression with HRF + temp deriv HRF\nbeta2 = lstsq(design_mat2, example_vox, rcond=None)[0]\nyhat2 = design_mat2.dot(beta2)\n\n# Replot the canonical HRF fit\nplt.figure(figsize=(15, 10))\nplt.subplot(3, 1, 1)\nplt.plot(example_vox)\nplt.plot(yhat1)\nplt.xlim(0, 98)\nplt.ylabel(\"Activation (A.U.)\", fontsize=12)\nplt.annotate('', xy=(9, 0), xytext=(7, 0.2),\n arrowprops=dict(arrowstyle='->', lw=2))\nplt.text(8, 0.22, 'Stim\\nonset', horizontalalignment='right', fontsize=15)\nplt.title(\"Prediction with canonical HRF only\", fontsize=20)\nplt.legend(['signal', 'predicted signal'], fontsize=15)\n\n# Plot model with temp deriv HRF\nplt.subplot(3, 1, 2)\nplt.plot(example_vox)\nplt.plot(yhat2)\nplt.xlim(0, 98)\nplt.ylabel(\"Activation (A.U.)\", fontsize=12)\nplt.annotate('', xy=(9, 0), xytext=(7, 0.2),\n arrowprops=dict(arrowstyle='->', lw=2))\nplt.text(8, 0.22, 'Stim\\nonset', horizontalalignment='right', fontsize=15)\nplt.title(\"Prediction with canonical HRF + temporal deriv\", fontsize=20)\n\n# Make dispersion HRF predictor and do regression\npredictor_hrf_dispersion = np.convolve(onset_array, sg_hrf_disp)[:example_vox.size]\ndesign_mat3 = np.hstack((design_mat2, predictor_hrf_dispersion[:, np.newaxis]))\nbeta3 = lstsq(design_mat3, example_vox, rcond=None)[0]\nyhat3 = design_mat3.dot(beta3)\n\n# Plot model with temp deriv HRF + dispersion deriv HRF\nplt.subplot(3, 1, 3)\nplt.plot(example_vox)\nplt.plot(yhat3)\nplt.xlim(0, 98)\nplt.xlabel(\"Time (seconds)\", fontsize=12)\nplt.ylabel(\"Activation (A.U.)\", fontsize=12)\nplt.annotate('', xy=(9, 0), xytext=(7, 0.2),\n arrowprops=dict(arrowstyle='->', lw=2))\nplt.text(8, 0.22, 'Stim\\nonset', horizontalalignment='right', fontsize=15)\nplt.title(\"Prediction with canonical HRF + temporal deriv + dispersion deriv\", fontsize=20)\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"As you can see, the prediction improves quite a bit when including the temporal derivative and (although to a lesser extent) the dispersion derivative! But how should we interpret the beta-parameters? Well, usually people don't really interpret the temporal and dispersion derivative HRFs (unless they're interested in lag/width of the HRF), because most researchers are interesting in the activation/deactivation (the amplitude) of voxels in response to a stimulus, which corresponds to the beta-parameters associated with the canonical HRF. So, basically, the temporal and dispersion derivatives are only used to \"correct\" for deviations in terms of lag/shape from the canonical HRF!\n\nSo, should you then always use a (gamma) basis set? To be honest, people are quite divided on the topic of whether to use basis sets or a canonical HRF. In our experience, derivatives (e.g. in the gamma basis sets) offers little improvement over a canonical HRF, but it doesn't hurt either (given that you have 'enough' degrees of freedom).\n\nAnyway, time for a ToDo!",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n<b>ToDo: Large</b>\n</div>\n\nReanalyze the voxel signal with the separate conditions (like the last ToDo), but this time with a gamma basis set instead of the canonical HRF! Calculate the beta-parameters, MSE, and $R^2$. Store the MSE in a variable named `mse_gbf` and $R^2$ in a variable named `r2_gbf`. \n\nPlease implement this ToDo in \"steps\", such that we can test intermediate output:\n1. Convolve the circle predictor (`predictor_circles`) and the squares predictor (`predictor_squares`) with the three HRF basis functions (canonical, temporal deriv., dispersion deriv.) separately, giving you 6 predictors, stack them together and add an intercept (make sure the intercept is the first column). Store your design matrix in a variable named `X_gbf`; (2 points)\n2. Run linear regression (your DV is the variable `voxel_signal`) and store your betas in a variable named `betas_gbf`; (1 point)\n3. Calculate R-squared and store it in a variable named `r2_gbf`; (1 point)\n4. Calculate MSE and store it in a variable named `mse_gbf`; (1 point)\n\nSome tips:\n- you can use the definitions of the HRFs from earlier (`sg_hrf`, `sg_hrf_temp`, and `sg_hrf_disp`)\n- make sure that your design-matrix has, eventually, 7 colums (3 predictors x 2 conditions + intercept)\n- don't forget to trim and downsample your predictors/design matrix after convolution! (remember: our fMRI signal has 400 samples)",
"_____no_output_____"
]
],
[
[
"# Step 1: convolve the predictors (don't forget to trim and downsample)!\n# Hint: print the shape of your predictors after convolving, trimming, and downsampling - \n# does this shape correspond to the number of datapoints of the experiment?\n\n# We have created the binary predictors for you already\npredictor_circles = np.zeros(800)\npredictor_circles[onsets_circles] = 1\n\npredictor_squares = np.zeros(800)\npredictor_squares[onsets_squares] = 1\n\npred_ci_conv1 = ...\npred_ci_conv2 = ...\npred_ci_conv3 = ...\npred_sq_conv1 = ...\npred_sq_conv2 = ...\npred_sq_conv3 = ...\nicept = np.ones((800, 1))\ndesign_mat_todo = ...\nX_gbf = design_mat_todo[::2, :]",
"_____no_output_____"
],
[
"# Step 2: run linear regression\n\nbetas_gbf = ...\n",
"_____no_output_____"
],
[
"''' Tests the above steps (hidden tests only)'''\nbetas_gbf_ans = ...\n",
"_____no_output_____"
],
[
"# Step 3: calculate R-squared (and store it in a variable named r2_gbf)\n\ny_hat_gbf = ...\nr2_gbf = ...",
"_____no_output_____"
],
[
"''' Tests the above ToDo (only hidden tests)'''\ny_hat_gbf = ...\nr2_gbf_ans = ...\n",
"_____no_output_____"
],
[
"# Step 3: calculate MSE (and store it in a variable named mse_gbf)\n\ny_hat_gbf = ...\nmse_gbf = ...\n",
"_____no_output_____"
],
[
"''' Tests the above ToDo (only hidden tests)'''\ny_hat_gbf = ...\nmse_gbf_ans = ...\n",
"_____no_output_____"
]
],
[
[
"From what we've showed so far, hopefully, you noticed that how linear regression is applied to model a voxel signal is not that much different from 'regular' data, except for the convolution/HRF part. At this moment, you already know 95% of how univariate analysis works! There are, however, still a couple of concepts we need to address, which we'll do in the next section: statistical inference of model parameters.",
"_____no_output_____"
],
[
"## 3. Statistical inference of model parameters\nFrom your statistics classes, you might remember that many software packages (e.g. SPSS or R) do not only return beta-parameters of linear regression models, but also t-values and p-values associated with the beta-parameters. Like beta-parameters, these statistics evaluate whether a beta-parameter (or combination of beta-parameters) differs significantly from 0 (or in fMRI terms: whether a voxel activates/deactivates significantly in response to a stimulus).\n\n\"Why would you need t-values and p-values - can't you just look at the beta-parameters?\", you might ask. Well, the problem is, that **you should never interpret raw beta-values** - not in analyses of regular data nor in analyses of fMRI data. To illustrate the problem with this, let's look at an example.\n\nIn this example, we try to predict someone's height (in meters; y) using someone's weight (in kilos; X). (Note that the data is not really representative of the true relationship between height and weight.)\n\nAnyway, let's run a linear regression using weight (in kilos) as a predictor for height (in meters).",
"_____no_output_____"
]
],
[
[
"data = np.load('data/weight_height_data.npz')\nX, y = data['X'], data['y']\n\nplt.figure(figsize=(10, 6))\nplt.scatter(X, y)\nplt.title('Relation between weight and height (in meters)', y=1.05, fontsize=20)\nplt.xlabel('Weight (kg)', fontsize=20)\nplt.ylabel('Height (meters)', fontsize=20)\n\nXn = np.hstack((np.ones((y.size, 1)), X))\nbeta = lstsq(Xn, y, rcond=None)[0]\ny_hat = Xn.dot(beta)\nmse = np.mean((y_hat - y) ** 2)\nplt.plot(X, Xn.dot(beta))\nplt.xlim((X.min(), X.max()))\nplt.text(70, 1.9, r'$\\beta_{weight} = %.5f$' % beta[1], fontsize=18)\nplt.text(70, 1.8, r'$MSE = %.5f$' % mse, fontsize=18)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"Well, quite a modest beta-parameter on the one hand, but on the other hand the Mean Squared Error is also quite low. \nNow, to illustrate the problem of interpretating 'raw' beta-weights, let's rephrase our objective of predicting height based on weight: we'll try to predict **height in centimeters** based on weight (still in kilos). So, what we'll do is just rescale the data points of y (height in meters) so that they reflect height in centimeters. We can simply do this by multipling our y-variable by 100.",
"_____no_output_____"
]
],
[
[
"y_cm = y * 100",
"_____no_output_____"
]
],
[
[
"Now, you wouldn't expect our model to change, right? We only rescaled our target ... As you'll see below, this actually changes a lot!\n\n<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nRun linear regression like the previous code block, but with `y_cm` instead of `y` as the target variable. You can use the same design (`Xn`). Calculate the beta-parameter and MSE.",
"_____no_output_____"
]
],
[
[
"# implement linear regression for y_cm using Xn here:\n\nbeta_cm = ...\ny_hat_cm = ...\nmse_cm = ...",
"_____no_output_____"
]
],
[
[
"If you did it correctly, when you compare the beta-parameters between the two models (one where y is in meters, and one where y is in centimeters), you see a massive difference - a 100 fold difference to be exact\\*! This is a nice example where you see that the (raw) value of the beta-parameter is completely dependent on the scale of your variables. (Actually, you could either rescale X or y; both will have a similar effect on your estimated beta-parameter.)\n\n-----------\n\\* Note that the MSE is a 100,000 times larger in the model with y_cm compared to y (in meters). This is because the influence of scale (factor 100) is squared when calculating mean **squared** error!",
"_____no_output_____"
],
[
"### 3.1. How to compute statistics of the GLM\nSo, you've seen that interpreting beta-parameters by themselves is useless because their value depends very much on the scale of your variables. But how should we, then, interpret the effects of our predictors on our target-variable? From the plots above, you probably guessed already that it has something to do with the MSE of our model (or, more generally, the model fit). That is indeed the case. As you might have noticed, not only the beta-parameters depend on the scale of your data, the errors (residuals) depend on the scale as well. In other words, not only the *effect* (beta-values) but also the *noise* (errors, MSE) depend on the scale of the variables! \n\n#### 3.1.1. T-values\nIn fact, the key to getting interpretable effects of our predictors is to divide (\"normalize\") our beta-parameter(s) by some quantity that summarizes how well our model describes the data. This quantity is the **standard error of the beta-parameter**, usually denoted by $SE_{\\beta}$. The standard error of the beta-parameter can be computed by taking the square root of the **variance of the beta-parameter**. If we'd divide our beta-estimate with it's standard error, we compute a statistic you are all familiar with: the t-statistic! Formally:\n\n\\begin{align}\nt_{\\hat{\\beta}} = \\frac{\\hat{\\beta}}{SE_{\\hat{\\beta}}} = \\frac{\\hat{\\beta}}{\\sqrt{\\mathrm{variance}(\\hat{\\beta})}}\n\\end{align}\n\n",
"_____no_output_____"
],
[
"<div class='alert alert-info'>\n <b>ToThink</b>\n</div>\n\nSuppose that I know the $SE$ of a particular beta-parameter. How can I derive the variance of that parameter (i.e., how do I go from the $SE$ to the variance)? And yes, the answer is as straightforward as you'd think.",
"_____no_output_____"
],
[
"Another way to think about it is that the t-value is the \"effect\" ($\\hat{\\beta}$) divided by your (un)certainty or confidence in the effect ($SE_{\\hat{\\beta}}$). In a way, you can think of t-values as \"uncertainty-normalized\" effects.\n\nSo, what drives (statistical) uncertainty about \"effects\" (here: $\\hat{\\beta}$ parameters)? To find out, let's dissect the uncertainty term, $SE_{\\beta}$, a little more. The standard error of a parameter can interpreted conceptually as the \"unexplained variance of the model\" (or **noise**) multiplied with the \"design variance\" (or: **the variance of the parameter due to the design**). In this lab, we won't explain what *design variance* means or how to compute this, because it will complicate things too much for now. Next week will be all about this term. \n\nFor now, we treat \"design variance\", here, as some known (constant) value. So, with this information, we can construct a conceptual formula for the standard error of our parameter(s):\n\n\n\\begin{align}\nSE_{\\hat{\\beta}} = \\sqrt{\\mathrm{noise} \\cdot \\mathrm{design\\ variance}}\n\\end{align}\n\nNow we also create a \"conceptual formula\" for the t-statistic:\n\n\\begin{align}\nt_{\\hat{\\beta}} = \\frac{\\hat{\\beta}}{SE_{\\hat{\\beta}}} = \\frac{\\mathrm{effect}}{\\sqrt{\\mathrm{noise} \\cdot \\mathrm{design\\ variance}}}\n\\end{align}\n\nThis (conceptual) formula involving effects, noise, and design variance is probably **the most important concept of this course**. The effects (t-values) we measure in GLM analyses of fMRI data depend on two things: the effect measured ($\\hat{\\beta}$) and the (un)certainty of the effect ($SE_{\\hat{\\beta}}$), of which the latter term can be divided into the unexplained variance (\"noise\") and the design variance (uncertainty of the parameter due to the design).\n\nThese two terms (noise and design variance) will be central to the next couple of weeks of this course. In week 3 (topic: design of experiments), we'll focus on how to optimize our t-values by minimizing the \"design variance\" term. In week 4 (topic: preprocessing), we'll focus on how to optimize our t-values by minimizing the error.\n\nWhile we're going to ignore the design variance, we are, however, going to learn how to calculate the \"noise\" term.\n\nIn fact, the noise term is *very* similar to the MSE, but instead of taking the *mean* of the squared residuals, we sum the squared residuals (\"sums of squared erros\", SSE) and divide it by the model's degrees of freedom (DF). People usually use the $\\hat{\\sigma}^{2}$ symbol for this noise term:\n\n\\begin{align}\n\\mathrm{noise} = \\hat{\\sigma}^{2} = \\frac{\\sum_{i=1}^{N}(\\hat{y_{i}} - y_{i})^2}{\\mathrm{df}} \n\\end{align}\n\nwhere the degrees of freedom (df) are defined as the number of samples ($N$) minus the number of predictors *including the intercept* ($P$):\n\n\\begin{align}\n\\mathrm{df} = N - P\n\\end{align}\n\nSo, the formula of the t-statistic becomes:\n\n\\begin{align}\nt_{\\hat{\\beta}} = \\frac{\\hat{\\beta}}{\\sqrt{\\frac{\\sum_{i=1}^{N}(\\hat{y_{i}} - y_{i})^2}{\\mathrm{df}} \\cdot \\mathrm{design\\ variance}}}\n\\end{align}\n\nAlright, enough formulas. Let's see how we can compute these terms in Python. We're going to calculate the t-statistic of the weight-predictor for both models (the meter and the centimeter model) to see whether we can show that essentially the (normalized) effect of weight on height in meters is the same as the effect on heigh in centimeters; in other words, we are going to investigate whether the conversion to t-values \"normalizes\" the beta-parameters.\n\nFirst, we'll create a function for you to calculate the design-variance. You *don't* have to understand how this works; we're going to explain this to you in detail next week.",
"_____no_output_____"
]
],
[
[
"def design_variance(X, which_predictor=1):\n ''' Returns the design variance of a predictor (or contrast) in X.\n \n Parameters\n ----------\n X : numpy array\n Array of shape (N, P)\n which_predictor : int or list/array\n The index of the predictor you want the design var from.\n Note that 0 refers to the intercept!\n Alternatively, \"which_predictor\" can be a contrast-vector\n (which will be discussed later this lab).\n \n Returns\n -------\n des_var : float\n Design variance of the specified predictor/contrast from X.\n '''\n \n is_single = isinstance(which_predictor, int)\n if is_single:\n idx = which_predictor\n else:\n idx = np.array(which_predictor) != 0\n \n c = np.zeros(X.shape[1])\n c[idx] = 1 if is_single == 1 else which_predictor[idx]\n des_var = c.dot(np.linalg.pinv(X.T.dot(X))).dot(c.T)\n return des_var",
"_____no_output_____"
]
],
[
[
"So, if you want the design variance of the 'weight' parameter in the varianble `Xn` from before, you do:",
"_____no_output_____"
]
],
[
[
"# use which_predictor=1, because the weight-column in Xn is at index 1 (index 0 = intercept)\ndesign_variance_weight_predictor = design_variance(Xn, which_predictor=1)\nprint(\"Design variance of weight predictor is: %.6f \" % design_variance_weight_predictor)",
"_____no_output_____"
]
],
[
[
"Alright, now we only need to calculate our noise-term ($\\hat{\\sigma}^2$):",
"_____no_output_____"
]
],
[
[
"# Let's just redo the linear regression (for clarity)\nbeta_meter = lstsq(Xn, y, rcond=None)[0]\ny_hat_meter = Xn.dot(beta_meter)\n\nN = y.size\nP = Xn.shape[1]\ndf = (N - P)\nprint(\"Degrees of freedom: %i\" % df)\nsigma_hat = np.sum((y - y_hat_meter) ** 2) / df\nprint(\"Sigma-hat (noise) is: %.3f\" % sigma_hat)\ndesign_variance_weight = design_variance(Xn, 1)",
"_____no_output_____"
]
],
[
[
"Now we can calculate the t-value:",
"_____no_output_____"
]
],
[
[
"t_meter = beta_meter[1] / np.sqrt(sigma_hat * design_variance_weight)\nprint(\"The t-value for the weight-parameter (beta = %.3f) is: %.3f\" % (beta_meter[1], t_meter))",
"_____no_output_____"
]
],
[
[
"That's it! There's not much more to calculating t-values in linear regression. Now it's up to you to do the same thing and calculate the t-value for the model of height in centimeters, and check if it is the same as the t-value for the weight parameter in the model with height in meters.",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nCalculate the t-statistic for the beta from the centimeter-model you calculated earlier. Store the value in a new variable named `t_centimeter`. Note: you don't have to calculate the design variance again (because `X` hasn't changed!) - you can reuse the variable `design_variance_weight`.",
"_____no_output_____"
]
],
[
[
"# Calculate the t-value here!\n\n",
"_____no_output_____"
]
],
[
[
"#### 3.2.2. P-values\nAs you can see, calculating t-values completely solves the 'problem' of uninterpretable beta-coefficients! So, remember never to interpret raw beta-coefficients (at least in fMRI), and always to convert them to t-values first!\n\nNow, the last thing you need to know is how to calculate the significance of your t-value, or in other words, how you calculate the corresponding p-value. You probably remember that the p-value corresponds to the area under the curve of a t-distribution associated with your t-value *and more extreme values*: \n\n\nThe function `t.sf(t_value, df)` from the `stats` module of the `scipy` package does exactly this. Importantly, this function ALWAYS returns the right-tailed p-value. For negative t-values, however, you'd want the left-tailed p-value. One way to remedy this, is to always pass the absolute value of your t-value - `np.abs(t_value)` to the `t.sf()` function. Also, the `t.sf()` function by default returns the one-sided p-value. In practice you'd want the two-sided p-value, so what you can simply do is multiply the returned p-value by two to get the corresponding two-sided p-value. \n\nLet's see how we'd do that in practice:",
"_____no_output_____"
]
],
[
[
"from scipy.stats import t\n\n# take the absolute by np.abs(t)\np_value = t.sf(np.abs(t_meter), df) * 2 # multiply by two to create a two-tailed p-value\nprint('The p-value corresponding to t(%i) = %.3f is: %.8f' % (df, t_meter, p_value))",
"_____no_output_____"
]
],
[
[
"<div class='alert alert-info'>\n<b>ToThink</b>\n</div>\n\nSo by now you understand why it is important **not** to interpret raw beta parameters, because these depend heavility on the scale of your data. One could argue that this is not relevant for fMRI data because all data (i.e. different voxels in the brain) all measure the same type of signal, so their scale shouldn't differ that much. This, however, is a false assumption.\n\nThink of two reasons why voxels might differ in their scale and write them down in the text cell below.",
"_____no_output_____"
],
[
"*Some possible answers:*\n\n1. Inhomogeneity of the signal at some spots (lower signal)\n2. Type of scanner.\n3. Different tissue types (white matter, gray matter, CSF, mix)\n4. Closeness to the headcoil (subcortical structures for example have generally a lower SNR)",
"_____no_output_____"
],
[
"### 3.3. Contrasts in the GLM\nWe're almost done! We're really at 99% of what you should know about the GLM and fMRI analysis\\*. The only thing that we need to discuss is **contrasts**. Contrasts are basically follow-up statistical tests of beta-parameter(s), and most importantly, *between* beta-parameters, to test hypotheses you might have about your predictors. Essentially, it is just an extension of the t-test we've explained earlier. \n\n---\n\\* Those who remembered their intro statistics classes accurately might recall the assumptions of linear regression, which as some might have noticed, could be violated in linear regression of fMRI data! This is because one of linear regression's assumptions is about **independent errors**, meaning that their should be no temporal correlation (\"autocorrelation\") between the residuals of a linear regression model. The residuals of univariate fMRI models are, often, autocorrelated due to low-frequency drifts, which make the inference of t-values in fMRI problematic. Fortunately, there are ways to deal with this autocorrelation-issue. This will be explained next week (preprocessing). It is important to realize that, fundamentally, linear regression of univariate fMRI data (or regression of *any* temporal signal, really) likely violates an important assumption, but also realize that the \"mechanics\" and logic of linear regression of how we learned it thus far still holds!",
"_____no_output_____"
],
[
"There are two main types of contrasts for t-tests:\n\n**1. contrast of a beta-parameter 'against baseline'.**\n\nThis type of contrast basically tests the hypothesis: \"Does my predictor(s) have *any* effect on my dependent variable?\" In other words, it tests the following hypothesis:\n* $H_{0}: \\beta = 0$ (our null-hypothesis, i.e. no effect)\n* $H_{a}: \\beta \\neq 0$ (our alternative hypotehsis, i.e. *some* effect)\n\n\n**2. contrast between beta-parameters.**\n\nThis type of contrast basically tests hypotheses such as \"Does predictor 1 have a larger effect on my dependent variable than predictor 1?\". In other words, it tests the following hypothesis:\n* $H_{0}: \\beta_{1} - \\beta_{2} = 0$ (our null-hypothesis, i.e. there is no difference)\n* $H_{a}: \\beta_{1} - \\beta_{2} \\neq 0$ (our alternative hypotehsis, i.e. there is some difference)\n\nLet's look at an example of how we would evaluate a simple hypothesis that a beta has an *some* effect on the dependent variable. Say we'd have an experimental design with 6 conditions:\n\n* condition 1: images of male faces with a happy expression\n* condition 2: images of male faces with a sad expression\n* condition 3: images of male faces with a neutral expression\n* condition 4: images of female faces with a happy expression\n* condition 5: images of female faces with a sad expression\n* condition 6: images of female faces with a neutral expression\n\nLet's assume we have fMRI data from a run with 100 volumes. We then have a target-signal of shape ($100 \\times 1$) and a design-matrix (after convolution with a canonical HRF) of shape ($100 \\times 7$) (the first predictor is the intercept!). We load in this data below:",
"_____no_output_____"
]
],
[
[
"data = np.load('data/data_contrast_example.npz')\nX, y = data['X'], data['y']\n\nprint(\"Shape of X: %s\" % (X.shape,))\nprint(\"Shape of y: %s\" % (y.shape,))",
"_____no_output_____"
]
],
[
[
"After performing linear regression with these 6 predictors (after convolving the stimulus-onset times with an HRF, etc. etc.), you end up with 7 beta values:",
"_____no_output_____"
]
],
[
[
"betas = lstsq(X, y, rcond=None)[0]\nbetas = betas.squeeze() # this is important for later\nprint(\"Betas corresponding to our 6 conditions (and intercept):\\n%r\" % betas.T)",
"_____no_output_____"
]
],
[
[
"The first beta corresponds to the intercept, the second beta to the male/happy predictor, the third beta to the male/sad predictor, etc. etc. Now, suppose that we'd like to test whether images of male faces with a sad expression have an influence on voxel activity (our dependent variable). \n\nThe first thing you need to do is extract this particular beta value from the array with beta values (I know this sounds really trivial, but bear with me):",
"_____no_output_____"
]
],
[
[
"beta_male_sad = betas[2]\nprint(\"The extracted beta is %.3f\" % beta_male_sad)",
"_____no_output_____"
]
],
[
[
"In neuroimaging analyses, however, this is usually done slightly differently: using **contrast-vectors**. Basically, it specifies your specific hypothesis about your beta(s) of interest in a vector. Before explaining it in more detail, let's look at it in a code example:",
"_____no_output_____"
]
],
[
[
"# Again, we'd want to test whether the beta of \"male_sad\" is different from 0\ncontrast_vector = np.array([0, 0, 1, 0, 0, 0, 0])\ncontrast = (betas * contrast_vector).sum() # we simply elementwise multiply the contrast-vector with the betas and sum it!\nprint('The beta-contrast is: %.3f' % contrast)",
"_____no_output_____"
]
],
[
[
"\"Wow, what a tedious way to just select the third value of the beta-array\", you might think. And, in a way, this is indeed somewhat tedious for a contrast against baseline. But let's look at a case where you would want to investigate whether two betas are different - let's say whether male sad faces have a larger effect on our voxel than male happy faces. Again, you *could* do this:",
"_____no_output_____"
]
],
[
[
"beta_difference = betas[2] - betas[1]\nprint(\"Difference between betas: %.3f\" % beta_difference)",
"_____no_output_____"
]
],
[
[
"... but you could also use a contrast-vector:",
"_____no_output_____"
]
],
[
[
"contrast_vector = np.array([0, -1, 1, 0, 0, 0, 0])\ncontrast = (betas * contrast_vector).sum()\nprint('The contrast between beta 2 and beta 1 is: %.3f' % contrast)\nprint('This is exactly the same as beta[2] - beta[1]: %.3f' % (betas[2]-betas[1]))",
"_____no_output_____"
]
],
[
[
"\"Alright, so using contrast-vectors is just a fancy way of extracting and subtracting betas from each other ...\", you might think. In a way, that's true. But you have to realize that once the hypotheses you want to test become more complicated, using contrast-vectors actually starts to make sense.\n\nLet's look at some more elaborate hypotheses. First, let's test whether male faces lead to higher voxel activity than female faces, *regardless of emotion*:",
"_____no_output_____"
]
],
[
[
"# male faces > female faces\ncontrast_vector = [0, 1, 1, 1, -1, -1, -1]\nmale_female_contrast = (contrast_vector * betas).sum()\nprint(\"Male - female contrast (regardless of expression): %.2f\" % male_female_contrast)",
"_____no_output_____"
]
],
[
[
"... or whether emotional faces (regardless of *which* exact emotion) lead to higher activity than neutral faces:",
"_____no_output_____"
]
],
[
[
"# Emotion (regardless of which emotion, i.e., regardless of sad/happy) - neutral\ncontrast_vector = [0, 1, 1, -2, 1, 1, -2]\nemo_neutral_contrast = (contrast_vector * betas).sum()\nprint(\"Emotion - neutral contrast (regardless of which emotion): %.2f\" % emo_neutral_contrast)",
"_____no_output_____"
]
],
[
[
"See how contrast-vectors come in handy when calculating (more intricate) comparisons? In the male-female contrast, for example, instead 'manually' picking out the betas of 'sad_male' and 'happy_male', averaging them, and subtracting their average beta from the average 'female' betas ('happy_female', 'sad_female'), you can simply specify a contrast-vector, multiply it with your betas, and sum them. That's it.",
"_____no_output_____"
],
[
"<div class='alert alert-info'>\n<b>ToThink</b>\n</div>\n\nIn the last contrast (`emo_neural_contrast`), we set all the \"emotional\" predictors (sad/happy) to 1, but the neutral predictors to minus *2* ... Why are these set to -2 and not -1? Write your answer below.",
"_____no_output_____"
],
[
"They have to sum to 0. If you'd use -1, you would \"weigh\" the emotional predictors twice as heavy as the neutral predictors.",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nCreate a contrast vector for the hypothesis: sad faces (regardless whether it's male or female) activate this voxel more than neutral faces (regardless of whether it's male/female). Multiply this contrast vector with the betas and store the result in a variable named `contrast_todo`.",
"_____no_output_____"
]
],
[
[
"# Implement the sad - neutral contrast here:\n\ncvec = ...\ncontrast_todo = ...\n",
"_____no_output_____"
],
[
"''' Tests the above ToDo (only hidden tests). '''\n\nassert(np.round(contrast_todo, 3) == -0.521)\n",
"_____no_output_____"
]
],
[
[
"We're not only telling you about contrasts because we think it's an elegant way of computing beta-comparisons, but also because virtually every major neuroimaging software package uses them, so that you can specify what hypotheses you exactly want to test! You'll also see this when we're going to work with FSL (in week 5!) to perform automated whole-brain linear regression analyses.\n\nKnowing how contrast-vectors work, we now can extend our formula for t-tests of beta-parameters such that they can describe **every possible test** (not only t-tests, but also ANOVAs, F-tests, etc.) of betas (against 'baseline') or between betas that you can think of: \n\nOur 'old' formula of the t-test of a beta-parameter:\n\\begin{align}\nt_{\\hat{\\beta}} = \\frac{\\hat{\\beta}_{j}}{SE_{\\hat{\\beta}}}\n\\end{align}\n\nAnd now our 'generalized' version of the t-test of *any* contrast/hypothesis:\n\n\\begin{align}\nt_{\\mathbf{c}\\hat{\\beta}} = \\frac{\\sum_{j=1}^{P}{c_{j}\\hat{\\beta}_{j}}}{SE_{\\mathbf{c}\\hat{\\beta}}} \n\\end{align}\n\nin which $\\mathbf{c}$ represents the entire contrast-vector, and $c_{j}$ represents the $j^{th}$ value in our contrast vector. By the way, we can simplify the (notation of the) numerator a little bit using some matrix algebra trick. Remember that multiplying two (equal lengt) vectors with each other and then summing the values together is the same thing as the (inner) \"dot product\" between the two vectors? \n\nNote that you can also write this elementwise multiplication and sum of the contrast-vector and the betas in a vectorized way (using the dot-product):\n\n\\begin{align}\nt_{\\mathbf{c}\\hat{\\beta}} = \\frac{\\mathbf{c}\\hat{\\beta}}{SE_{\\mathbf{c}\\hat{\\beta}}} \n\\end{align}",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n <b>ToDo</b>\n</div>\n\nConvince yourself that the elementwise multiplication and sum is mathematically exactly the same as the dot product! Below, we initialized a hypothetical vector with beta-values (`some_betas`) and a hypothetical contrast-vector (`some_cvec`). First, implement the \"multiply and sum\" approach and then implement the \"dot product\" approach. You should find that it gives you exactly the same value: -3.34",
"_____no_output_____"
]
],
[
[
"some_betas = np.array([1.23, 2.95, 3.33, 4.19])\nsome_cvec = np.array([1, 1, -1, -1])\n\n# Try to implement both approaches and convince yourself that it's\n# mathematically the same!\n",
"_____no_output_____"
]
],
[
[
"So, you need the contrast vector in the *numerator* of the t-value formula (i.e., $\\mathbf{c}\\hat{\\beta}$), but it turns out that you actually also need the contrast-vector in the denominator, because it's part of the calculation of design variance. Again, we will discuss how this works exactly next week. In the function `design_variance`, it is also possible to calculate design variance for a particular contrast (not just a single predictor) by passing a contrast vector to the `which_predictor` argument.\n\nWe'll show this below:",
"_____no_output_____"
]
],
[
[
"# E.g., get design-variance of happy/male - sad/male\nc_vec = np.array([0, 1, -1, 0, 0, 0, 0]) # our contrast vector!\ndvar = design_variance(X, which_predictor=c_vec) # pass c_vec to which_predictor\nprint(\"Design variance of happy/male - sad/male: %.3f\" % dvar)",
"_____no_output_____"
]
],
[
[
"For the rest of ToDos this lab (you're almost done, don't worry!), make sure to pass your contrast-vector to the `design_variance` function in order to calculate it correctly.\n\nNow you know enough to do it yourself!",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nCalculate the t-value and p-value for the hypothesis \"sad faces have a larger effect than happy faces (regardless of gender) on our dependent variabe\" (i.e. voxel activity). In other words, test the hypothesis: $\\beta_{sad} - \\beta_{happy} \\neq 0$ (note that this is a two-sided test!).\n\nStore the t-value and p-value in the variables `tval_todo` and `pval_todo` respectively. We reload the variables below (we'll call them `X_new` and `y_new`) to make sure you're working with the correct data. Note that the `X_new` variable already contains an intercept; the other six columns correspond to the different predictors (male/hapy, male/sad, etc.). In summary, you have to do the following:\n\n- (you don't have to calculate the betas; this has already been done (stored in the variable `betas`)\n- calculate \"sigma-hat\" ($SSE / \\mathrm{df}$)\n- calculate design-variance (use the `design_variance` function with a proper contrast-vector)\n- calculate the contrast ($\\mathbf{c}\\hat{\\beta}$)\n- calculate the t-value and p-value",
"_____no_output_____"
]
],
[
[
"data = np.load('data_contrast_example.npz')\nX_new, y_new = data['X'], data['y']\n\nprint(\"Shape of X: %s\" % (X_new.shape,))\nprint(\"Shape of y: %s\" % (y_new.shape,))\n\nfrom scipy.stats import t\n\ncvec = ...\nthis_dvar = ...\ny_hat = ...\nthis_sse = ...\ntval_todo = ...\npval_todo = ...\n",
"_____no_output_____"
],
[
"''' Part 1 of testing the above ToDo (only hidden tests). '''\n\nprint(\"Only hidden tests!\")\n\nnp.testing.assert_almost_equal(tval_todo, 1.2646, decimal=4)",
"_____no_output_____"
],
[
"''' Part 2 of testing the above ToDo (only hidden tests). '''\n\nprint(\"Ony hidden tests!\")\n\nnp.testing.assert_almost_equal(pval_todo, 0.2092, decimal=4)",
"_____no_output_____"
]
],
[
[
"### 3.4. F-tests on contrasts\nIn the previous section we discussed how to calculate t-values for single contrasts. However, sometimes you might have an hypothesis about multiple contrasts at the same time. This may sound weird, but let's consider an experiment.\n\nSuppose you have data from an experiment in which you showed images circles which were either blue, red, or green. In that case, you have three predictors. Then, you could have very specific question, like \"Do blue circles activate a voxel significantly compared to baseline\", which corresponds to the following null and alternative hypothesis:\n\n* $H_{0}: \\beta_{blue} = 0$ (our null-hypothesis, i.e. there is no activation compared to baseline)\n* $H_{a}: \\beta_{blue} > 0$ (our alternative hypotehsis, i.e. blue activates relative to baseline)\n\nHowever, you can also have a more general question, like \"Does the presentation of *any* circle (regardless of color) activate a voxel compared to baseline?\". This question represents the following null and alternative hypothesis:\n\n* $H_{0}: \\beta_{blue} = \\beta_{red} = \\beta_{green} = 0$\n* $H_{a}: (\\beta_{blue} > 0) \\vee (\\beta_{red} > 0) \\vee (\\beta_{green} > 0)$\n\nThe $\\vee$ symbol in the alternative hypothesis means \"or\". So the alternative hypothesis nicely illustrates our question: is there *any* condition (circle) that activates a voxel more than baseline? This hypothesis-test might sound familiar, because it encompasses the **F-test**! In other words, an F-test tests *a collection of contrasts* together. In the example here, the F-test tests the following contrasts together (ignoring the intercept) of our beta-parameters:\n\n* `[1, 0, 0]` ($red > 0$)\n* `[0, 1, 0]` ($blue > 0$)\n* `[0, 0, 1]` ($green > 0$)\n\nThus, a F-test basically tests this contrast-*matrix* all at once! Therefore, the F-tests is a type of \"omnibus test\"! \n\nNow, let's look at the math behind the F-statistic. The F-statistic for set of $K$ contrasts (i.e., the number of rows in the contrast-matrix) is defined as follows:\n\n\\begin{align}\nF = (\\mathbf{c}\\hat{\\beta})'[K\\mathbf{c}((X'X)^{-1}\\hat{\\sigma}^{2})\\mathbf{c}']^{-1}(\\mathbf{c}\\hat{\\beta})\n\\end{align}\n\nWith a little imagination, you can see how the F-test is an extension of the t-test of a single contrast to accomodate testing a set of contrasts together. Don't worry, you don't have to understand how the formula for the F-statistic works mathematically and you don't have to implement this in Python. But you **do** need to understand what type of hypothesis an F-test tests! \n\nLet's practice this in a ToDo!",
"_____no_output_____"
],
[
"<div class='alert alert-warning'>\n<b>ToDo</b>\n</div>\n\nRemember the temporal basis sets from before? Suppose we have an experiment with two conditions (\"A\" and \"B\") and suppose we've created a design matrix based on convolution with a single-gamma basis set (with a canonical HRF, its temporal derivative, and its dispersion derivative). Together with the intercept, the design matrix thus has 7 columns (2 conditions * 3 HRF + intercept).\n\nThe order of the columns is as follows:\n* column 1: intercept\n* column 2: canonical HRF \"A\"\n* column 3: temporal deriv \"A\"\n* column 4: dispersion deriv \"A\"\n* column 5: canonical HRF \"B\"\n* column 6: temporal deriv \"B\"\n* column 7: dispersion deriv \"B\"\n\nSuppose I want to test whether there is *any* difference in response to condition \"A\" ($A > 0$) compared to baseline, and *I don't care what element of the HRF caused it*. I can use an F-test for this. What would the corresponding contrast-*matrix* (in which each row represents a different contrast) look like? \n\nWe've created an 'empty' (all-zeros) 2D matrix below with three rows. It's up to you to fill in the matrix such that it can be used to test the above question/hypothesis.",
"_____no_output_____"
]
],
[
[
"# Fill in the correct values!\ncontrast_matrix = np.array([\n\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]\n\n])\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"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",
"code"
],
[
"markdown",
"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",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"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"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"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"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
ecceb33b451dd5089b1f03831ce79e11150e1a28 | 13,637 | ipynb | Jupyter Notebook | examples/notebook/contrib/nonogram_table.ipynb | tias/or-tools | b37d9c786b69128f3505f15beca09e89bf078a89 | [
"Apache-2.0"
] | 1 | 2021-05-25T01:42:03.000Z | 2021-05-25T01:42:03.000Z | examples/notebook/contrib/nonogram_table.ipynb | tias/or-tools | b37d9c786b69128f3505f15beca09e89bf078a89 | [
"Apache-2.0"
] | null | null | null | examples/notebook/contrib/nonogram_table.ipynb | tias/or-tools | b37d9c786b69128f3505f15beca09e89bf078a89 | [
"Apache-2.0"
] | 1 | 2021-07-24T22:52:41.000Z | 2021-07-24T22:52:41.000Z | 34.788265 | 252 | 0.529149 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
ecceb3c6a6256db38d43f4349acd6955ddfb09b2 | 14,921 | ipynb | Jupyter Notebook | policies/development_policies/build_strategy.ipynb | BayAreaMetro/petrale | ee2c9464f72df09d6a147f60b2865fab9ac74b87 | [
"BSD-3-Clause"
] | 1 | 2021-03-18T22:03:53.000Z | 2021-03-18T22:03:53.000Z | policies/development_policies/build_strategy.ipynb | BayAreaMetro/petrale | ee2c9464f72df09d6a147f60b2865fab9ac74b87 | [
"BSD-3-Clause"
] | null | null | null | policies/development_policies/build_strategy.ipynb | BayAreaMetro/petrale | ee2c9464f72df09d6a147f60b2865fab9ac74b87 | [
"BSD-3-Clause"
] | 5 | 2019-07-09T02:02:23.000Z | 2022-03-07T06:00:01.000Z | 37.024814 | 203 | 0.490852 | [
[
[
"### inclusionary housing setting",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\ndf = pd.read_csv(r'C:\\Users\\ywang\\Box\\Modeling and Surveys\\Urban Modeling\\Bay Area UrbanSim\\PBA50\\Current PBA50 Large General Input Data\\2020_11_10_parcels_geography.csv')\n\n# build lists of fbpchcat with high- and medium-level inclusionary requirements\nhigh = df.loc[(df.fbp_gg_id == 'GG') & df.fbp_tra_id.notnull() & (\n (df.fbp_sesit_id == 'HRADIS') | (df.fbp_sesit_id == 'HRA'))]['fbpchcat'].unique()\n\nmed = df.loc[((df.fbp_gg_id == 'GG') & (df.fbp_tra_id == 'tra1') & ((df.fbp_sesit_id == 'DIS') | df.fbp_sesit_id.isnull())\n ) | (\n (df.fbp_gg_id == 'GG') & ((df.fbp_tra_id == 'tra2a') | (df.fbp_tra_id == 'tra2b') | (df.fbp_tra_id == 'tra2c')) & ((df.fbp_sesit_id == 'DIS') | df.fbp_sesit_id.isnull())\n ) | (\n (df.fbp_gg_id == 'GG') & df.fbp_tra_id.isnull() & ((df.fbp_sesit_id == 'HRADIS') | (df.fbp_sesit_id == 'HRA')))]['fbpchcat'].unique()\n\ndisplay('{} fbpchcats have high-level inclusionary requirement (20%)'.format(len(high)))\ndisplay('{} fbpchcats have medium-level inclusionary requirement (15%)'.format(len(med)))\ndisplay('{} fbpchcats have low-level inclusionary requirement (10%)'.format(len(df.fbpchcat.unique()) - len(high) - len(med)))\n\n# merge the two lists with the entire fbpchcat\nfbpchcat_df = df[['fbpchcat']].drop_duplicates()\n#display(fbpchcat_df.head())\n\nhigh_data = {'fbpchcat':list(high), 'level_h':['high'] * len(high)}\nhigh_df = pd.DataFrame(high_data)\n\nmedium_data = {'fbpchcat':list(med), 'level_m':['medium'] * len(med)}\nmedium_df = pd.DataFrame(medium_data)\n\n# label fbpchcat with low-level inclusionary requirements\nfbpchcat_df = fbpchcat_df.merge(high_df, on='fbpchcat', how = 'left').merge(medium_df, on='fbpchcat', how='left')\nfbpchcat_df['level_l'] = ''\nfbpchcat_df.loc[fbpchcat_df.level_h.isnull() & fbpchcat_df.level_m.isnull(), 'level_l'] = 'low'\nfbpchcat_df['fbpchcat'] = fbpchcat_df['fbpchcat'].apply(lambda x: ' - '+x)\ndisplay(fbpchcat_df)\n\n# export\nfbpchcat_df.to_csv('inclusionary_fbpchcat.csv')",
"C:\\Users\\ywang\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3063: DtypeWarning: Columns (10,20) have mixed types.Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n"
]
],
[
[
"### office lump sum subsidies",
"_____no_output_____"
]
],
[
[
"bonds = {'dublin': 24675325,\n'fremont': 24675325, \n'oakland': 24675325, \n'san_leandro': 24675325, \n'union_city': 24675325, \n'antioch': 24675325,\n'concord': 24675325, \n'el_cerrito': 24675325, \n'lafayette': 24675325,\n'pittsburg': 24675325, \n'richmond': 24675325,\n'san_rafael': 3571429, \n'fairfield': 3571429,\n'vacaville': 3571429,\n'santa_rosa': 3571429}\n\ncities = {'dublin': 'Dublin',\n'fremont': 'Fremont', \n'oakland': 'Oakland', \n'san_leandro': 'San Leandro', \n'union_city': 'Union City', \n'antioch': 'Antioch',\n'concord': 'Concord', \n'el_cerrito': 'El Cerrito', \n'lafayette': 'Lafayette',\n'pittsburg': 'Pittsburg', \n'richmond': 'Richmond',\n'san_rafael': 'San Rafael', \n'fairfield': 'Fairfield',\n'vacaville': 'Vacaville',\n'santa_rosa': 'Santa Rosa'}\n\n\nfor city in bonds.keys():\n print(' {}_office_bond_settings:'.format(city))\n print(' name: \"{} Office Subsidy Bond\"'.format(cities[city]))\n print(' sending_buildings_subaccount_def: \"{}\"'.format(cities[city]))\n print(' total_amount: {}'.format(bonds[city]))\n print(\" receiving_buildings_filter: juris == '{}'\".format(cities[city]))\n print(' enable_in_scenarios: [\"24\"]')",
" dublin_office_bond_settings:\n name: \"Dublin Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Dublin\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'Dublin'\n enable_in_scenarios: [\"24\"]\n fremont_office_bond_settings:\n name: \"Fremont Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Fremont\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'Fremont'\n enable_in_scenarios: [\"24\"]\n oakland_office_bond_settings:\n name: \"Oakland Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Oakland\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'Oakland'\n enable_in_scenarios: [\"24\"]\n san_leandro_office_bond_settings:\n name: \"San Leandro Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"San Leandro\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'San Leandro'\n enable_in_scenarios: [\"24\"]\n union_city_office_bond_settings:\n name: \"Union City Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Union City\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'Union City'\n enable_in_scenarios: [\"24\"]\n antioch_office_bond_settings:\n name: \"Antioch Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Antioch\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'Antioch'\n enable_in_scenarios: [\"24\"]\n concord_office_bond_settings:\n name: \"Concord Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Concord\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'Concord'\n enable_in_scenarios: [\"24\"]\n el_cerrito_office_bond_settings:\n name: \"El Cerrito Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"El Cerrito\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'El Cerrito'\n enable_in_scenarios: [\"24\"]\n lafayette_office_bond_settings:\n name: \"Lafayette Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Lafayette\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'Lafayette'\n enable_in_scenarios: [\"24\"]\n pittsburg_office_bond_settings:\n name: \"Pittsburg Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Pittsburg\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'Pittsburg'\n enable_in_scenarios: [\"24\"]\n richmond_office_bond_settings:\n name: \"Richmond Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Richmond\"\n total_amount: 24675325\n receiving_buildings_filter: juris == 'Richmond'\n enable_in_scenarios: [\"24\"]\n san_rafael_office_bond_settings:\n name: \"San Rafael Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"San Rafael\"\n total_amount: 3571429\n receiving_buildings_filter: juris == 'San Rafael'\n enable_in_scenarios: [\"24\"]\n fairfield_office_bond_settings:\n name: \"Fairfield Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Fairfield\"\n total_amount: 3571429\n receiving_buildings_filter: juris == 'Fairfield'\n enable_in_scenarios: [\"24\"]\n vacaville_office_bond_settings:\n name: \"Vacaville Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Vacaville\"\n total_amount: 3571429\n receiving_buildings_filter: juris == 'Vacaville'\n enable_in_scenarios: [\"24\"]\n santa_rosa_office_bond_settings:\n name: \"Santa Rosa Office Subsidy Bond\"\n sending_buildings_subaccount_def: \"Santa Rosa\"\n total_amount: 3571429\n receiving_buildings_filter: juris == 'Santa Rosa'\n enable_in_scenarios: [\"24\"]\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
eccec8f991f0cf95a8e11444d79f727d214cecb4 | 5,690 | ipynb | Jupyter Notebook | tests/test-wordvector.ipynb | AetherPrior/malaya | 45d37b171dff9e92c5d30bd7260b282cd0912a7d | [
"MIT"
] | 88 | 2021-01-06T10:01:31.000Z | 2022-03-30T17:34:09.000Z | tests/test-wordvector.ipynb | AetherPrior/malaya | 45d37b171dff9e92c5d30bd7260b282cd0912a7d | [
"MIT"
] | 43 | 2021-01-14T02:44:41.000Z | 2022-03-31T19:47:42.000Z | tests/test-wordvector.ipynb | AetherPrior/malaya | 45d37b171dff9e92c5d30bd7260b282cd0912a7d | [
"MIT"
] | 38 | 2021-01-06T07:15:03.000Z | 2022-03-19T05:07:50.000Z | 29.947368 | 271 | 0.58717 | [
[
[
"import sys\nimport os\n\nSOURCE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__name__)))\nsys.path.insert(0, SOURCE_DIR)",
"_____no_output_____"
],
[
"import malaya\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)",
"_____no_output_____"
],
[
"vocab_news, embedded_news = malaya.wordvector.load(model = 'news')\nvocab_wiki, embedded_wiki = malaya.wordvector.load(model = 'wikipedia')",
"DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): f000.backblazeb2.com:443\n"
],
[
"word_vector_news = malaya.wordvector.WordVector(embedded_news, vocab_news)\nword_vector_wiki = malaya.wordvector.WordVector(embedded_wiki, vocab_wiki)",
"_____no_output_____"
],
[
"word = 'anwar'\nprint(\"Embedding layer: 8 closest words to: '%s' using malaya news word2vec\"%(word))\nprint(word_vector_news.n_closest(word=word, num_closest=8, metric='cosine'))",
"Embedding layer: 8 closest words to: 'anwar' using malaya news word2vec\n[['najib', 0.6967672109603882], ['mukhriz', 0.675892174243927], ['azmin', 0.6686884164810181], ['rafizi', 0.6465028524398804], ['muhyiddin', 0.6413404941558838], ['daim', 0.6334482431411743], ['khairuddin', 0.6300410032272339], ['shahidan', 0.6269811391830444]]\n"
],
[
"word = 'anwar'\nprint(\"Embedding layer: 8 closest words to: '%s' using malaya wiki word2vec\"%(word))\nprint(word_vector_wiki.n_closest(word=word, num_closest=8, metric='cosine'))",
"Embedding layer: 8 closest words to: 'anwar' using malaya wiki word2vec\n[['rasulullah', 0.6918460130691528], ['jamal', 0.6604709029197693], ['noraniza', 0.65153968334198], ['khalid', 0.6450133323669434], ['mahathir', 0.6447468400001526], ['sukarno', 0.641593337059021], ['wahid', 0.6359774470329285], ['pekin', 0.6262176036834717]]\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccee263cf0aa2659ff46e61dfc473bfc5a2b341 | 97,431 | ipynb | Jupyter Notebook | data/Ridership Change Season.ipynb | Matthew-Tuazon/C1-MindSumo | 2b949129e1b88a7b0c289872b8f2969121600fb2 | [
"MIT"
] | 1 | 2018-11-11T03:42:35.000Z | 2018-11-11T03:42:35.000Z | data/.ipynb_checkpoints/Ridership Change Season-checkpoint.ipynb | Matthew-Tuazon/C1-MindSumo | 2b949129e1b88a7b0c289872b8f2969121600fb2 | [
"MIT"
] | 1 | 2021-06-01T22:50:19.000Z | 2021-06-01T22:50:19.000Z | data/Ridership Change Season.ipynb | Matthew-Tuazon/C1-MindSumo | 2b949129e1b88a7b0c289872b8f2969121600fb2 | [
"MIT"
] | null | null | null | 28.037698 | 206 | 0.333888 | [
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport collections\nfrom collections import Counter #unique counter for arrays\n#types of passes during season\nspringTrips = []\nsummerTrips = []\nfallTrips = []\nwinterTrips = []\n\n#for trip durations during season\nspringDuration = []\nsummerDuration = []\nfallDuration = []\nwinterDuration = []\n\n#for popular BikeID during season\nspringBike = []\nsummerBike = []\nfallBike = []\nwinterBike = []",
"_____no_output_____"
],
[
"%matplotlib inline\ndf = pd.read_csv('metro-bike-share-trip-data.csv')",
"/Users/matttuazon/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:2785: DtypeWarning: Columns (14) have mixed types. Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n"
],
[
"#Replaces spaces with _ and get rid of parenthesis \ndf.columns = df.columns.str.replace(' ', '_').str.replace('(', '').str.replace(')', '')",
"_____no_output_____"
],
[
"df[\"Trip_ID\"].astype(int)\ndf[\"Duration\"].astype(int)\ndf[\"Start_Time\"].astype(str)\ndf[\"End_Time\"].astype(str)\ndf[\"Starting_Station_ID\"].astype(float)\ndf[\"Starting_Station_Latitude\"].astype(float)\ndf[\"Starting_Station_Longitude\"].astype(float)\ndf[\"Ending_Station_ID\"].astype(float)\ndf[\"Ending_Station_Latitude\"].astype(float)\ndf[\"Ending_Station_Longitude\"].astype(float)\ndf[\"Bike_ID\"].astype(float)\ndf[\"Trip_Route_Category\"].astype(str)\ndf[\"Passholder_Type\"].astype(str)\ndf[\"Starting_Lat-Long\"].astype(str)\ndf[\"Ending_Lat-Long\"].astype(str)",
"_____no_output_____"
],
[
"#converts formatting of Start_Time/End_Time data to dateTime\ndf[\"Start_Time\"] = pd.to_datetime(df['Start_Time'])\ndf[\"End_Time\"] = pd.to_datetime(df['End_Time'])",
"_____no_output_____"
],
[
"#checks season using the dateTime\n#used season time frames based on: https://www.timeanddate.com/calendar/aboutseasons.html\ndef season(datetime):\n if 3 <= datetime.month and datetime.month <= 5:\n return \"Spring\"\n elif 6 <= datetime.month and datetime.month<= 8:\n return \"Summer\"\n elif 9 <= datetime.month and datetime.month<= 11:\n return \"Fall/Autumn\"\n elif 12 == datetime.month or datetime.month <= 2:\n return \"Winter\"\n\n#Adds seasons to df chart\nseasons = pd.Series(map(season,df[\"Start_Time\"]))\ndf[\"Season\"] = seasons",
"_____no_output_____"
],
[
"Spring = df[df.Season == 'Spring']\nSummer = df[df.Season == 'Summer']\nFall = df[df.Season == 'Fall/Autumn']\nWinter = df[df.Season == 'Winter']\n",
"_____no_output_____"
],
[
"#Spring #13906 Trips in Spring\n#Summer #35573 Trips in the Summer\n#Fall #52455 Trips in the Fall\n#Winter #30493 Trips in Winter",
"_____no_output_____"
],
[
"#For Loop to add different types of pass used for each season.\nfor index, row in df.iterrows():\n passUsed = row[\"Passholder_Type\"]\n season = row[\"Season\"]\n if season == \"Spring\":\n springTrips.append(passUsed)\n elif season == \"Summer\":\n summerTrips.append(passUsed)\n elif season == \"Fall/Autumn\":\n fallTrips.append(passUsed)\n elif season == \"Winter\":\n winterTrips.append(passUsed)",
"_____no_output_____"
],
[
"#Different types of passes used per season\nprint (\"Summer Trips Count:\")\nprint (\"Monthly passes count - {}\".format(summerTrips.count(\"Monthly Pass\")))\nprint (\"Flex passes count - {}\".format(summerTrips.count(\"Flex Pass\")))\nprint (\"Walk-up passes count - {}\".format(summerTrips.count(\"Walk-up\")))\nprint (\"Staff Annual passes count - {}\\n\".format(summerTrips.count(\"Staff Annual\")))\nprint (\"Spring Trips Count:\")\nprint (\"Monthly passes count - {}\".format(springTrips.count(\"Monthly Pass\")))\nprint (\"Flex passes count - {}\".format(springTrips.count(\"Flex Pass\")))\nprint (\"Walk-up passes count - {}\".format(springTrips.count(\"Walk-up\")))\nprint (\"Staff Annual passes count - {}\\n\".format(springTrips.count(\"Staff Annual\")))\nprint (\"Fall/Autumn Trips Count:\")\nprint (\"Monthly passes count - {}\".format(fallTrips.count(\"Monthly Pass\")))\nprint (\"Flex passes count - {}\".format(fallTrips.count(\"Flex Pass\")))\nprint (\"Walk-up passes count - {}\".format(fallTrips.count(\"Walk-up\")))\nprint (\"Staff Annual passes count - {}\\n\".format(fallTrips.count(\"Staff Annual\")))\nprint (\"Winter Trips Count:\")\nprint (\"Monthly passes count - {}\".format(winterTrips.count(\"Monthly Pass\")))\nprint (\"Flex passes count - {}\".format(winterTrips.count(\"Flex Pass\")))\nprint (\"Walk-up passes count - {}\".format(winterTrips.count(\"Walk-up\")))\nprint (\"Staff Annual passes count - {}\\n\".format(winterTrips.count(\"Staff Annual\")))",
"Summer Trips Count:\nMonthly passes count - 22548\nFlex passes count - 3253\nWalk-up passes count - 9772\nStaff Annual passes count - 0\n\nSpring Trips Count:\nMonthly passes count - 8451\nFlex passes count - 1023\nWalk-up passes count - 4432\nStaff Annual passes count - 0\n\nFall/Autumn Trips Count:\nMonthly passes count - 30789\nFlex passes count - 3345\nWalk-up passes count - 18071\nStaff Annual passes count - 250\n\nWinter Trips Count:\nMonthly passes count - 19516\nFlex passes count - 1896\nWalk-up passes count - 8949\nStaff Annual passes count - 132\n\n"
],
[
"#For Loop to track the average duration per season \nfor index, row in df.iterrows():\n tripDuration = row[\"Duration\"]\n season = row[\"Season\"]\n if season == \"Spring\":\n springDuration.append(tripDuration)\n elif season == \"Summer\":\n summerDuration.append(tripDuration)\n elif season == \"Fall/Autumn\":\n fallDuration.append(tripDuration)\n elif season == \"Winter\":\n winterDuration.append(tripDuration)",
"_____no_output_____"
],
[
"#Average duration of trips per season\nprint (\"Average spring trip duration - {}\".format(sum(springDuration)/len(springDuration)/60))\nprint (\"Average summer trip duration - {}\".format(sum(summerDuration)/len(summerDuration)/60))\nprint (\"Average fall trip duration - {}\".format(sum(fallDuration)/len(fallDuration)/60))\nprint (\"Average winter trip duration - {}\".format(sum(winterDuration)/len(winterDuration)/60))",
"Average spring trip duration - 30.01618006615849\nAverage summer trip duration - 24.16582801562983\nAverage fall trip duration - 24.66157658945763\nAverage winter trip duration - 28.270521103204015\n"
],
[
"#For Loop to calculate most used Bikes\nfor index, row in df.iterrows():\n tripBikeID = row[\"Bike_ID\"]\n season = row[\"Season\"]\n #print (tripBikeID)\n if season == \"Spring\":\n springBike.append(tripBikeID)\n elif season == \"Summer\":\n summerBike.append(tripBikeID)\n elif season == \"Fall/Autumn\":\n fallBike.append(tripBikeID)\n elif season == \"Winter\":\n winterBike.append(tripBikeID)",
"_____no_output_____"
],
[
"#most popular bike usage in spring, bikeID 5755\nbikeSpringUsage = Counter(springBike)\nbikeSpringUsage.most_common()",
"_____no_output_____"
],
[
"#most popular bike usage in summer, bikeID 6487\nbikeSummerUsage = Counter(summerBike)\nbikeSummerUsage.most_common()",
"_____no_output_____"
],
[
"#most popular bike usage in fall, bikeID 6527\nbikeFallUsage = Counter(fallBike)\nbikeFallUsage.most_common()",
"_____no_output_____"
],
[
"#most popular bike usage in winter, bikeID 4727\nbikeWinterUsage = Counter(winterBike)\nbikeWinterUsage.most_common()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccee5d6b6e015e859ce9deb3c3b72db7746e7d3 | 895,299 | ipynb | Jupyter Notebook | 1/main.ipynb | Pavel3P/Machine-Learning | 441da7de69ebf6cef9ebe54a0b3992918faf1d40 | [
"MIT"
] | null | null | null | 1/main.ipynb | Pavel3P/Machine-Learning | 441da7de69ebf6cef9ebe54a0b3992918faf1d40 | [
"MIT"
] | null | null | null | 1/main.ipynb | Pavel3P/Machine-Learning | 441da7de69ebf6cef9ebe54a0b3992918faf1d40 | [
"MIT"
] | null | null | null | 1,139.057252 | 365,039 | 0.957479 | [
[
[
"# Lab #1\n___\n\n**Task:** Build a Linear Regression model, using given dataset.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom regression import LinearRegression\nfrom bucket import Bucket\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.linear_model import LinearRegression as skLR\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import Ridge",
"_____no_output_____"
]
],
[
[
"## Dataset reading and describing\n___\n\n_Dataset taken from:_ https://www.kaggle.com/mirichoi0218/insurance\n\nIn given dataset we will try to predict value of charges of person depending on given factors:",
"_____no_output_____"
]
],
[
[
"regions = ['southwest', 'southeast', 'northwest', 'northeast']\nsex = ['male', 'female']\ndf = pd.read_csv(\"../datasets/insurance.csv\", converters={\n \"smoker\": lambda val: 1 if val == \"yes\" else 0,\n \"region\": lambda val: regions.index(val),\n \"sex\": lambda val: sex.index(val),\n})\ndf.head()",
"_____no_output_____"
]
],
[
[
"_Interesting observation:_ depending on age, charges separates on three different clusters. Let's divide it, and look on what we will get:",
"_____no_output_____"
]
],
[
[
"sns.pairplot(df)",
"_____no_output_____"
]
],
[
[
"## Clustering\n___\n\nClustering of charges depending on age using dbscan:",
"_____no_output_____"
]
],
[
[
"x = df[[\"age\", \"charges\"]].to_numpy()\nmax_x = np.max(x, axis=0)\nx = x / max_x\ndbscan = DBSCAN(eps=.05, min_samples=5)\ndbscan.fit(x)\n\nclusters = []\nfor label in np.unique(dbscan.labels_):\n if label != -1:\n cluster = dbscan.labels_ == label\n clusters.append(cluster)\n cluster = x[cluster] * max_x\n plt.xlabel(\"Age\")\n plt.ylabel(\"Charges\")\n plt.scatter(cluster[:, 0], cluster[:, 1], label=f\"Cluster: {label}\")\n\nplt.legend()",
"_____no_output_____"
]
],
[
[
"We also can see that points on scatter plot Charges(BMI) got quite reasonable clusterization too:",
"_____no_output_____"
]
],
[
[
"for label in range(len(clusters)):\n cluster = clusters[label]\n _x = df.loc[cluster, \"bmi\"]\n _y = df.loc[cluster, \"charges\"]\n\n plt.xlabel(\"BMI\")\n plt.ylabel(\"Charges\")\n plt.scatter(_x, _y, label=f\"Cluster: {label}\")\n \nplt.legend()",
"_____no_output_____"
]
],
[
[
"## Next research\n___\n\nLet's take a closer look on cluster #1:",
"_____no_output_____"
]
],
[
[
"dataset = df.loc[clusters[1]]\ndataset.reset_index(inplace=True, drop=True)\nsns.pairplot(dataset)",
"_____no_output_____"
]
],
[
[
"Let's look on correlation of predictors and target variable:",
"_____no_output_____"
]
],
[
[
"dataset = dataset[[\"age\", \"bmi\", \"children\", \"region\", \"charges\"]]\nnp.corrcoef(dataset.to_numpy().T).round(3)",
"_____no_output_____"
]
],
[
[
"As we see, 1 of 4 available predictors can help us. So let's choose only it:",
"_____no_output_____"
]
],
[
[
"dataset = dataset[[\"age\", \"charges\"]]",
"_____no_output_____"
],
[
"sns.pairplot(dataset)",
"_____no_output_____"
]
],
[
[
"## Anomaly detection\n___\n\nIt become a little cleaner:",
"_____no_output_____"
]
],
[
[
"to_drop = []\nfor col in dataset.columns[:-1]:\n x = dataset[[col, dataset.columns[-1]]].to_numpy()\n x = x / np.max(x, axis=0)\n\n dbscan = DBSCAN(eps=.03, min_samples=5)\n dbscan.fit(x)\n to_drop = np.append(to_drop, np.argwhere(dbscan.labels_ == -1))\n\ndataset = dataset.drop(np.unique(to_drop.astype(int)))\nsns.pairplot(dataset)",
"_____no_output_____"
]
],
[
[
"## Data normalization\n___\nWe will normalize data values by given formula: $$X = \\frac{X - X_{min}}{X_{max} - X_{min}}$$",
"_____no_output_____"
]
],
[
[
"data = dataset.to_numpy()\nmin_vals = np.min(data, axis=0)\nmax_vals = np.max(data, axis=0)\ndata = (data - min_vals) / (max_vals - min_vals)\ndata",
"_____no_output_____"
]
],
[
[
"## Model fitting\n___\n\nWe will train model type: $$Y = \\omega_{0} + \\omega_{1} * X$$",
"_____no_output_____"
]
],
[
[
"idxs = np.arange(0, len(dataset))\nnp.random.shuffle(idxs)\n\nX = data[:, [0]]\nY = data[:, 1]\n\nn = int(0.5 * len(dataset))\n\nX_train = X[idxs[:n]]\nY_train = Y[idxs[:n]]\n\nX_test = X[idxs[n:]]\nY_test = Y[idxs[n:]]\n\nlinregr = LinearRegression()\nlinregr.train(X_train, Y_train)\n\nlinregr.MSE(X_test, Y_test), linregr.score(X_test, Y_test), linregr.w",
"_____no_output_____"
]
],
[
[
"### Lasso Regression:",
"_____no_output_____"
]
],
[
[
"L1 = np.linspace(0, 1, 50)\nmses = []\nfor l1 in L1:\n lr = LinearRegression(l1=l1)\n lr.train(X_train, Y_train)\n mses.append(lr.MSE(X_test, Y_test))\n \nplt.xlabel(\"L1 coefficient\")\nplt.ylabel(\"MSE\")\nplt.plot(L1, mses)",
"_____no_output_____"
],
[
"linregr_l1 = LinearRegression(l1=.05)\nlinregr_l1.train(X_train, Y_train)\n\nlinregr_l1.MSE(X_test, Y_test), linregr_l1.score(X_test, Y_test), linregr_l1.w",
"_____no_output_____"
]
],
[
[
"### Ridge Regression:",
"_____no_output_____"
]
],
[
[
"L2 = np.linspace(0, 1, 50)\nmses = []\nfor l2 in L2:\n lr = LinearRegression(l2=l2)\n lr.train(X_train, Y_train)\n mses.append(lr.MSE(X_test, Y_test))\n \nplt.xlabel(\"L2 coefficient\")\nplt.ylabel(\"MSE\")\nplt.plot(L2, mses)",
"_____no_output_____"
],
[
"linregr_l2 = LinearRegression(l2=.05)\nlinregr_l2.train(X_train, Y_train)\n\nlinregr_l2.MSE(X_test, Y_test), linregr_l2.score(X_test, Y_test), linregr_l2.w",
"_____no_output_____"
]
],
[
[
"### Bucket of models:",
"_____no_output_____"
]
],
[
[
"weights = np.ones(3) / 3\nbucket = Bucket([linregr, linregr_l1, linregr_l2], weights)\n\nbucket.MSE(X_test, Y_test), bucket.score(X_test, Y_test)",
"_____no_output_____"
]
],
[
[
"### Using sklearn library:",
"_____no_output_____"
],
[
"#### Ordinary Regression:",
"_____no_output_____"
]
],
[
[
"reg = skLR().fit(X_train, Y_train)\nreg.score(X_test, Y_test), reg.coef_, reg.intercept_",
"_____no_output_____"
]
],
[
[
"#### Lasso Regression:",
"_____no_output_____"
]
],
[
[
"lasso_sk = Lasso(alpha=.05).fit(X_train, Y_train)\nlasso_sk.score(X_test, Y_test), lasso_sk.coef_, lasso_sk.intercept_",
"_____no_output_____"
]
],
[
[
"#### Ridge Regression:",
"_____no_output_____"
]
],
[
[
"ridge_sk = Ridge(alpha=.05).fit(X_train, Y_train)\nridge_sk.score(X_test, Y_test), ridge_sk.coef_, ridge_sk.intercept_",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
eccee803df4f8100353bb49801861571c115c4f7 | 584,777 | ipynb | Jupyter Notebook | Face Mask Model(vgg19).ipynb | JokaDPiero/COVID-19-face-mask-detection | 278330cd6aba9d84c4085aa93150c95ecb3bb348 | [
"MIT"
] | null | null | null | Face Mask Model(vgg19).ipynb | JokaDPiero/COVID-19-face-mask-detection | 278330cd6aba9d84c4085aa93150c95ecb3bb348 | [
"MIT"
] | null | null | null | Face Mask Model(vgg19).ipynb | JokaDPiero/COVID-19-face-mask-detection | 278330cd6aba9d84c4085aa93150c95ecb3bb348 | [
"MIT"
] | null | null | null | 867.621662 | 114,488 | 0.952394 | [
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport random",
"_____no_output_____"
],
[
"train_mask=[i for i in os.listdir(\"C:/Users/KIIT/Downloads/Konnections/My model/dataset/with_mask/\")]\ntrain_nomask=[i for i in os.listdir(\"C:/Users/KIIT/Downloads/Konnections/My model/dataset/without_mask/\")]",
"_____no_output_____"
],
[
"train_mask[:5]",
"_____no_output_____"
],
[
"from keras.preprocessing.image import load_img,img_to_array\nfrom keras.applications.vgg19 import preprocess_input\nimport cv2\ndef read_and_process_img(imgset,name):\n dirr=r\"C:/Users/KIIT/Downloads/Konnections/My model/dataset/\"\n X=[]\n y=[]\n undetected=[]\n for img in imgset:\n if img is not None:\n try:\n img=load_img(dirr+name+\"/\"+img,target_size=(224,224))\n \n img=img_to_array(img) #or we can use cv2\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n #img=np.expand_dims(img,axis=0)\n img=preprocess_input(img)\n X.append(img)\n if name=='with_mask':\n y.append('with_mask')\n else:\n y.append('without_mask')\n except:\n undetected.append(img)\n \n print(\"Undetected images - \",len(undetected))\n return X,y",
"_____no_output_____"
],
[
"train_mask,label1=read_and_process_img(train_mask,'with_mask')",
"C:\\Users\\KIIT\\anaconda3\\lib\\site-packages\\PIL\\Image.py:963: UserWarning: Palette images with Transparency expressed in bytes should be converted to RGBA images\n \"Palette images with Transparency expressed in bytes should be \"\n"
],
[
"train_nomask,label2=read_and_process_img(train_nomask,'without_mask')",
"Undetected images - 0\n"
],
[
"len(train_nomask)",
"_____no_output_____"
],
[
"len(train_mask)",
"_____no_output_____"
],
[
"train_set=train_mask+train_nomask\nlabels=label1+label2\nr=random.random()\nrandom.shuffle(train_set,lambda : r)#using same function for both to make shuffle order same\nrandom.shuffle(labels,lambda : r)",
"_____no_output_____"
],
[
"del train_mask,train_nomask",
"_____no_output_____"
],
[
"labels[2:20]",
"_____no_output_____"
],
[
"from keras.preprocessing.image import array_to_img\nfor i in range(2,8):\n #x=np.reshape(train_set[i],(224,224,3))\n x=train_set[i]\n x=array_to_img(x)\n xx=plt.imshow(x)\n plt.title(labels[i])\n plt.show()",
"_____no_output_____"
],
[
"print(len(train_set))\nprint(len(labels))",
"3833\n3833\n"
],
[
"from sklearn.preprocessing import LabelBinarizer\nfrom keras.utils import to_categorical\n\nX=np.array(train_set)\nlb=LabelBinarizer()\nlabels=lb.fit_transform(labels)\ny=to_categorical(labels)\ny=np.array(y)\nprint(X.shape)\nprint(y.shape)",
"(3833, 224, 224, 3)\n(3833, 2)\n"
],
[
"from sklearn.model_selection import train_test_split\nx_train,x_val,y_train,y_val=train_test_split(X,y,random_state=42,test_size=0.3,stratify=y)",
"_____no_output_____"
],
[
"print(x_train.shape)\nprint(y_val.shape)",
"(2683, 224, 224, 3)\n(1150, 2)\n"
],
[
"del train_set,labels\ndel label1,label2",
"_____no_output_____"
],
[
"from keras.preprocessing.image import ImageDataGenerator\ntrain_gen=ImageDataGenerator(\n rescale=1./255, #scaling image between 0 and 1\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2,\n zoom_range=0.2,\n shear_range=0.2,\n horizontal_flip=True,\n vertical_flip=True\n)\nval_gen=ImageDataGenerator(rescale=1.0/255)",
"_____no_output_____"
],
[
"train_generator=train_gen.flow(x_train,y_train,batch_size=10)\nvalid_generator=val_gen.flow(x_val,y_val,batch_size=10)",
"_____no_output_____"
],
[
"from keras.applications.vgg19 import VGG19\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom keras.optimizers import Adam\nopt=Adam(lr=0.0001)\nmod=VGG19(include_top=False,weights=\"imagenet\",input_shape=(224,224,3))\n#mod.trainable=False\nfor layer in mod.layers:\n layer.trainable = False\nmodel=mdl=keras.Sequential([\n mod,\n layers.Flatten(),\n layers.Dropout(rate=0.3),\n layers.Dense(128, activation='relu'),\n layers.Dense(2,activation='softmax')\n])\nmodel.compile(\n loss='binary_crossentropy',\n optimizer=opt,\n metrics=['accuracy']\n)\nmodel.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nvgg19 (Functional) (None, 7, 7, 512) 20024384 \n_________________________________________________________________\nflatten (Flatten) (None, 25088) 0 \n_________________________________________________________________\ndropout (Dropout) (None, 25088) 0 \n_________________________________________________________________\ndense (Dense) (None, 128) 3211392 \n_________________________________________________________________\ndense_1 (Dense) (None, 2) 258 \n=================================================================\nTotal params: 23,236,034\nTrainable params: 3,211,650\nNon-trainable params: 20,024,384\n_________________________________________________________________\n"
],
[
"from tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\nconfig=ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction=0.8\nconfig.gpu_options.allow_growth=True\nsession=InteractiveSession(config=config)",
"_____no_output_____"
],
[
"batch_size=50\nn_train=len(x_train)\nn_val=len(x_val)\nhistory=model.fit(train_generator,\n steps_per_epoch=n_train//batch_size,\n epochs=30,\n validation_data=valid_generator,\n validation_steps=n_val//batch_size\n \n)",
"Epoch 1/30\n53/53 [==============================] - 62s 826ms/step - loss: 0.6813 - accuracy: 0.5946 - val_loss: 0.3128 - val_accuracy: 0.8826\nEpoch 2/30\n53/53 [==============================] - 40s 762ms/step - loss: 0.3768 - accuracy: 0.8837 - val_loss: 0.2310 - val_accuracy: 0.9522\nEpoch 3/30\n53/53 [==============================] - 41s 766ms/step - loss: 0.3430 - accuracy: 0.8632 - val_loss: 0.1465 - val_accuracy: 0.9565\nEpoch 4/30\n53/53 [==============================] - 41s 767ms/step - loss: 0.2870 - accuracy: 0.8894 - val_loss: 0.1789 - val_accuracy: 0.9435\nEpoch 5/30\n53/53 [==============================] - 41s 768ms/step - loss: 0.2745 - accuracy: 0.9086 - val_loss: 0.1227 - val_accuracy: 0.9565\nEpoch 6/30\n53/53 [==============================] - 41s 769ms/step - loss: 0.2497 - accuracy: 0.9027 - val_loss: 0.1521 - val_accuracy: 0.9391\nEpoch 7/30\n53/53 [==============================] - 53s 997ms/step - loss: 0.2079 - accuracy: 0.9233 - val_loss: 0.1075 - val_accuracy: 0.9609\nEpoch 8/30\n53/53 [==============================] - 42s 788ms/step - loss: 0.2068 - accuracy: 0.9117 - val_loss: 0.0986 - val_accuracy: 0.9739\nEpoch 9/30\n53/53 [==============================] - 60s 1s/step - loss: 0.1971 - accuracy: 0.9000 - val_loss: 0.1451 - val_accuracy: 0.9522\nEpoch 10/30\n53/53 [==============================] - 42s 787ms/step - loss: 0.1658 - accuracy: 0.9449 - val_loss: 0.1008 - val_accuracy: 0.9696\nEpoch 11/30\n53/53 [==============================] - 60s 1s/step - loss: 0.2247 - accuracy: 0.9194 - val_loss: 0.0763 - val_accuracy: 0.9739\nEpoch 12/30\n53/53 [==============================] - 47s 891ms/step - loss: 0.2241 - accuracy: 0.9093 - val_loss: 0.0889 - val_accuracy: 0.9696\nEpoch 13/30\n53/53 [==============================] - 57s 1s/step - loss: 0.1462 - accuracy: 0.9506 - val_loss: 0.1003 - val_accuracy: 0.9609\nEpoch 14/30\n53/53 [==============================] - 56s 1s/step - loss: 0.1997 - accuracy: 0.9191 - val_loss: 0.0772 - val_accuracy: 0.9739\nEpoch 15/30\n53/53 [==============================] - 42s 786ms/step - loss: 0.1981 - accuracy: 0.9202 - val_loss: 0.0768 - val_accuracy: 0.9826\nEpoch 16/30\n53/53 [==============================] - 62s 1s/step - loss: 0.1975 - accuracy: 0.9318 - val_loss: 0.0876 - val_accuracy: 0.9739\nEpoch 17/30\n53/53 [==============================] - 47s 895ms/step - loss: 0.1969 - accuracy: 0.9166 - val_loss: 0.1047 - val_accuracy: 0.9609\nEpoch 18/30\n53/53 [==============================] - 55s 1s/step - loss: 0.1521 - accuracy: 0.9464 - val_loss: 0.0618 - val_accuracy: 0.9783\nEpoch 19/30\n53/53 [==============================] - 62s 1s/step - loss: 0.1463 - accuracy: 0.9340 - val_loss: 0.0900 - val_accuracy: 0.9739\nEpoch 20/30\n53/53 [==============================] - 43s 804ms/step - loss: 0.1403 - accuracy: 0.9503 - val_loss: 0.0801 - val_accuracy: 0.9739\nEpoch 21/30\n53/53 [==============================] - 71s 1s/step - loss: 0.2026 - accuracy: 0.9156 - val_loss: 0.0907 - val_accuracy: 0.9696\nEpoch 22/30\n53/53 [==============================] - 44s 833ms/step - loss: 0.1497 - accuracy: 0.9465 - val_loss: 0.0668 - val_accuracy: 0.9826\nEpoch 23/30\n53/53 [==============================] - 62s 1s/step - loss: 0.1149 - accuracy: 0.9532 - val_loss: 0.0602 - val_accuracy: 0.9826\nEpoch 24/30\n53/53 [==============================] - 49s 930ms/step - loss: 0.1526 - accuracy: 0.9477 - val_loss: 0.0454 - val_accuracy: 0.9783\nEpoch 25/30\n53/53 [==============================] - 49s 924ms/step - loss: 0.1507 - accuracy: 0.9438 - val_loss: 0.0804 - val_accuracy: 0.9783\nEpoch 26/30\n53/53 [==============================] - 59s 1s/step - loss: 0.1293 - accuracy: 0.9527 - val_loss: 0.1082 - val_accuracy: 0.9696\nEpoch 27/30\n53/53 [==============================] - 57s 1s/step - loss: 0.1098 - accuracy: 0.9634 - val_loss: 0.1012 - val_accuracy: 0.9739\nEpoch 28/30\n53/53 [==============================] - 47s 884ms/step - loss: 0.2021 - accuracy: 0.9312 - val_loss: 0.0754 - val_accuracy: 0.9696\nEpoch 29/30\n53/53 [==============================] - 57s 1s/step - loss: 0.1388 - accuracy: 0.9495 - val_loss: 0.0799 - val_accuracy: 0.9565\nEpoch 30/30\n53/53 [==============================] - 57s 1s/step - loss: 0.1434 - accuracy: 0.9469 - val_loss: 0.0577 - val_accuracy: 0.9739\n"
],
[
"history_df= pd.DataFrame(history.history)\nhistory_df.loc[:, ['loss', 'val_loss']].plot();\nhistory_df.loc[:, ['accuracy', 'val_accuracy']].plot();\nprint(\"Minimum validation loss: {:.3f}\".format(history_df['val_loss'].min()))\nprint(\"Maximum validation accuracy: {:.3f}\".format(history_df['val_accuracy'].max()))",
"Minimum validation loss: 0.045\nMaximum validation accuracy: 0.983\n"
],
[
"model.save_weights('vgg19_face_model_wieghts.h5')\nmodel.save('vgg19_face_model_keras.h5')",
"_____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"
]
] |
ecceec43ee834ca42b75ad4e853ee19163fdc63f | 531,564 | ipynb | Jupyter Notebook | Shell_Solar_Power_Prediction_Challenge_HackerEarth/Shell_Solar_Power_Prediction.ipynb | PradipKumarDas/Competitions | df9487bbf0e489b3bcbe5239b43d74f410459ae8 | [
"MIT"
] | 1 | 2022-01-16T16:06:59.000Z | 2022-01-16T16:06:59.000Z | Shell_Solar_Power_Prediction_Challenge_HackerEarth/Shell_Solar_Power_Prediction.ipynb | PradipKumarDas/Competitions | df9487bbf0e489b3bcbe5239b43d74f410459ae8 | [
"MIT"
] | null | null | null | Shell_Solar_Power_Prediction_Challenge_HackerEarth/Shell_Solar_Power_Prediction.ipynb | PradipKumarDas/Competitions | df9487bbf0e489b3bcbe5239b43d74f410459ae8 | [
"MIT"
] | 1 | 2022-01-16T16:07:16.000Z | 2022-01-16T16:07:16.000Z | 195.787845 | 198,236 | 0.871654 | [
[
[
"################################################################################\n\n**Author**: _Pradip Kumar Das_\n\n**License:** https://github.com/PradipKumarDas/Competitions/blob/main/LICENSE\n\n**Profile & Contact:** [LinkedIn](https://www.linkedin.com/in/daspradipkumar/) | [GitHub](https://github.com/PradipKumarDas) | [Kaggle](https://www.kaggle.com/pradipkumardas) | [email protected] (Email)\n\n################################################################################\n\n# Shell Solar Power Prediction\n\n**October 07, 2021 - November 07, 2021**\n\n**https://www.hackerearth.com/challenges/competitive/shell-ai-hackathon-2021/**\n\n**_Predicting Cloud Coverage_**\n\n**Sections:**\n- Dependencies\n- Exploratory Data Analysis (EDA) & Data Preprocessing\n- Modeling & Evaluation\n- Submission",
"_____no_output_____"
],
[
"## Dependencies",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\n\nfrom sklearn.preprocessing import StandardScaler\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import Model, Input\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras import layers\n\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\n\nimport os\nimport datetime\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
]
],
[
[
"## Exploratory Data Analysis (EDA) & Dat Preparation",
"_____no_output_____"
]
],
[
[
"# Configures plot styles\n\nplt.style.use(\"seaborn-whitegrid\")\nplt.rc(\n \"figure\",\n autolayout=True,\n figsize=(11, 4),\n titlesize=18,\n titleweight='bold',\n)\nplt.rc(\n \"axes\",\n labelweight=\"bold\",\n labelsize=\"large\",\n titleweight=\"bold\",\n titlesize=16,\n titlepad=10,\n)\n%config InlineBackend.figure_format = 'retina'",
"_____no_output_____"
],
[
"# Loads train dataset\ntrain = pd.read_csv(\"./dataset/train/train.csv\", parse_dates={'Datetime': [0,1]})",
"_____no_output_____"
],
[
"# Views few rows of train dataset\ntrain",
"_____no_output_____"
],
[
"# Checks if the month has 29 days in February\ntrain[\"Datetime\"].str.startswith(\"2/29\").any()",
"_____no_output_____"
],
[
"# Finding 29th days in February, assigns last leap year as time of the dataset\ntrain[\"Datetime\"] = \"2020/\" + train[\"Datetime\"]\n\n# Set column Datetime with appropriate format\ntrain[\"Datetime\"] = pd.to_datetime(train[\"Datetime\"], infer_datetime_format=True)\n\n# Sets column Datetime as index of the dataset\ntrain.set_index([\"Datetime\"], drop=True, inplace=True)\n\n# Sets dataset as periodic\ntrain = train.to_period()",
"_____no_output_____"
],
[
"# Now, checks the basic statistics of the train dataset\ntrain.describe()",
"_____no_output_____"
],
[
"# Noticing large negative values, checks for distribution of these different values\ntrain[train[\"Total Cloud Cover [%]\"] < 0][\"Total Cloud Cover [%]\"].value_counts()",
"_____no_output_____"
],
[
"# Plots count of large negative numbers day wise\ntrain[train[\"Total Cloud Cover [%]\"] < -1].resample(\"D\")[\"Total Cloud Cover [%]\"].count().plot()",
"_____no_output_____"
],
[
"# Replaces large negative values with missing values, and interpolates linearly\nfor resample in train.resample(\"D\")[\"Total Cloud Cover [%]\"]:\n observed_cloud_coverage = resample[1][resample[1] != -1]\n observed_cloud_coverage[observed_cloud_coverage < 0] = np.nan\n observed_cloud_coverage.interpolate(method=\"linear\", inplace=True)\n train[\"Total Cloud Cover [%]\"].update(observed_cloud_coverage)",
"_____no_output_____"
],
[
"# Checks the statistics of the newly interpolated column\ntrain[\"Total Cloud Cover [%]\"].describe()",
"_____no_output_____"
],
[
"# Upon finding large native values for another column for snow depth, too, checks for basic statistics of the column\ntrain[\"Snow Depth [cm]\"].describe()",
"_____no_output_____"
],
[
"# Plots snow depth when it is negative\ntrain[train[\"Snow Depth [cm]\"] < 0][\"Snow Depth [cm]\"].plot()",
"_____no_output_____"
],
[
"# Plots snow depth distribution when it is more than -100\ntrain[train[\"Snow Depth [cm]\"] > -100][\"Snow Depth [cm]\"].plot()",
"_____no_output_____"
],
[
"# Calculates distribution of negative snow depth \ntrain[train[\"Snow Depth [cm]\"] < 0][\"Snow Depth [cm]\"].groupby(\n pd.cut(train[train[\"Snow Depth [cm]\"] < 0][\"Snow Depth [cm]\"], list(range(-1000, 50, 50)))).count()",
"_____no_output_____"
],
[
"# Replaces negative snow depth less than -100 with missing value and then interpolates linearly\n\ntrain[\"Snow Depth [cm]\"].loc[train[\"Snow Depth [cm]\"] < -100] = np.nan\n\ntrain[\"Snow Depth [cm]\"].interpolate(method=\"linear\", inplace=True)",
"_____no_output_____"
],
[
"# Re=plots to ensure interpolates did not affect major distribution for snow depth of values of acceptable range\ntrain[\"Snow Depth [cm]\"].plot()",
"_____no_output_____"
],
[
"# Checks basic statistics of train dataset post interpolating for columns cloud coverage and snow depth\ntrain.describe()",
"_____no_output_____"
],
[
"# Inserts an additional feature column: \n# value 1 indicates cloud coverage is available, and \n# value 0 indicates cloud coverage is not available\ntrain.insert(\n loc=train.columns.get_loc(\"Total Cloud Cover [%]\"), \n column=\"Total Cloud Cover Available\", \n value=train[\"Total Cloud Cover [%]\"].apply(lambda coverage:\n 1 if coverage >= 0 else 0))",
"_____no_output_____"
],
[
"# Saves the features engineered train dataset\ntrain.to_csv(\"./dataset/train/train_interpolated.csv\", index=True)",
"_____no_output_____"
],
[
"# Reloads the featured engineered train dataset\ntrain = pd.read_csv(\n \"./dataset/train/train_interpolated.csv\", \n parse_dates=True, \n index_col=\"Datetime\", \n infer_datetime_format=True).to_period()",
"_____no_output_____"
],
[
"def flag_val_samples(target_col, validation_ratio=0.2):\n # Flags valid samples\n \n # Parameters:\n # target_col (pandas.core.series.Series): target column containing shifted values according to target horizon\n # validation_ratio (float): validation ratio/spit. The default is 0.2 i.e. 20%\n \n # Returns:\n # Returns a new series of bool type containing TRUE against valid samples.\n \n val_samples = pd.Series(False, index=target_col.index)\n available_targets = target_col[target_col != -1]\n random_selected_samples = available_targets.sample(frac = validation_ratio, random_state = 47)\n val_samples[random_selected_samples.index] = True\n return val_samples",
"_____no_output_____"
],
[
"validation_ratio = 0.2",
"_____no_output_____"
],
[
"# Shifts values by target horizons and marks against valid samples\n\ntrain[\"Target_Horizon_30\"] = train[\"Total Cloud Cover [%]\"].shift(-30, fill_value=-1)\ntrain[\"Target_Horizon_30_Val_Flag\"] = flag_val_samples(train[\"Target_Horizon_30\"])\n\ntrain[\"Target_Horizon_60\"] = train[\"Total Cloud Cover [%]\"].shift(-60, fill_value=-1)\ntrain[\"Target_Horizon_60_Val_Flag\"] = flag_val_samples(train[\"Target_Horizon_60\"])\n\ntrain[\"Target_Horizon_90\"] = train[\"Total Cloud Cover [%]\"].shift(-90, fill_value=-1)\ntrain[\"Target_Horizon_90_Val_Flag\"] = flag_val_samples(train[\"Target_Horizon_90\"])\n\ntrain[\"Target_Horizon_120\"] = train[\"Total Cloud Cover [%]\"].shift(-120, fill_value=-1)\ntrain[\"Target_Horizon_120_Val_Flag\"] = flag_val_samples(train[\"Target_Horizon_120\"])",
"_____no_output_____"
]
],
[
[
"## Modeling & Evaluation",
"_____no_output_____"
]
],
[
[
"# Stores model features into list\nmodel_features = train.columns[:16]",
"_____no_output_____"
],
[
"# Standard scales features\n\nmodel_features_scaler = StandardScaler().fit(train[model_features])\ntrain[model_features] = model_features_scaler.transform(train[model_features])",
"_____no_output_____"
],
[
"def sample_generator(\n data, lookback, horizon_col_name, val_flag_col_name, val_samples=False, steps=1, batch_size=128):\n \n # Generates samples\n\n # Inputs:\n # data (pandas.core.frame.DataFrame): data to generate sample from\n # lookback (int): Number of timesteps go back in time\n # horizon_col_name (string): Column name of the series containing target horizon\n # val_flag_col_name (string): Column name of series containing validation flag for the specified horizon\n # val_samples (bool): False to return training samples and True to return validation samples. Default is False.\n # steps (int): <not implemented>\n # batch_size (int): Number of samples in each yield\n\n # Returns:\n # Yields samples each containing samples specified by parameter batch_size\n \n while True:\n samples = []\n targets = []\n rolling_windows = train.rolling(lookback, min_periods=lookback)\n for window in rolling_windows:\n if window.shape[0] != lookback:\n continue\n \n if ((window.iloc[-1][horizon_col_name] != -1) and (window.iloc[-1][val_flag_col_name] != val_samples)):\n samples.append(window[model_features])\n targets.append(window.iloc[-1][horizon_col_name])\n \n if len(samples) == batch_size:\n yield np.asarray(samples), np.asarray(targets)\n samples.clear()\n targets.clear()\n \n yield np.asarray(samples), np.asarray(targets)",
"_____no_output_____"
],
[
"# Sets required variables\n\nlookback = 361\nstep = 1\nbatch_size=128",
"_____no_output_____"
]
],
[
[
"### Modeling to Predict Cloud Coverage at 30 Minutes Horizon",
"_____no_output_____"
]
],
[
[
"# Creates generators for generating samples with target at 30 minutes horizon for both training and validation\n\nhorizon_30_train_sample_generator = sample_generator(\n data=train, lookback=lookback, \n horizon_col_name=\"Target_Horizon_30\", val_flag_col_name=\"Target_Horizon_30_Val_Flag\",\n val_samples=False, steps=1, batch_size=batch_size)\n\nhorizon_30_val_sample_generator = sample_generator(\n data=train, lookback=lookback, \n horizon_col_name=\"Target_Horizon_30\", val_flag_col_name=\"Target_Horizon_30_Val_Flag\",\n val_samples=True, steps=1, batch_size=batch_size)",
"_____no_output_____"
],
[
"# Calculates number of steps to call to iterate all samples for both training and validation data\n\nsteps_per_epoch = round((train[train[\"Target_Horizon_30\"] != -1].shape[0] - lookback + 1) / batch_size)\nvalidation_steps = round(steps_per_epoch * validation_ratio)",
"_____no_output_____"
],
[
"# Views the calculated steps\nsteps_per_epoch, validation_steps",
"_____no_output_____"
],
[
"# Creates neural network model to predict target at 30 minutes horizon\n# Note: Output dimension for second layer GRU should have been 64, but was set to 32 mistakenly.\n\nmodel = Sequential()\nmodel.add(layers.Input(shape=(lookback,len(model_features))))\nmodel.add(layers.GRU(64, return_sequences=True))\nmodel.add(layers.GRU(32, activation=\"relu\"))\nmodel.add(layers.Dense(1))",
"_____no_output_____"
],
[
"# Checks model summary\nmodel.summary()",
"Model: \"sequential_8\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ngru_4 (GRU) (None, 361, 64) 15744 \n_________________________________________________________________\ngru_5 (GRU) (None, 32) 9408 \n_________________________________________________________________\ndense_8 (Dense) (None, 1) 33 \n=================================================================\nTotal params: 25,185\nTrainable params: 25,185\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"# Compiles the model specifying optimizer, loss function and metric\nmodel.compile(optimizer=\"adam\", loss=\"mse\", metrics=\"mae\")",
"_____no_output_____"
],
[
"# Sets model name\nmodel_name = \"horizon-30_gru-64+gru-32-relu+dense\" + \"_\" + datetime.datetime.now().strftime(\"%Y.%m.%d-%H:%M:%S\")\n\n# Fits the model\nhistory = model.fit(\n horizon_30_train_sample_generator, \n steps_per_epoch=steps_per_epoch, \n validation_data=horizon_30_val_sample_generator,\n validation_steps=validation_steps,\n epochs=1,\n callbacks=[\n EarlyStopping(monitor=\"val_loss\", patience=3, mode=\"min\", restore_best_weights=True),\n ModelCheckpoint(filepath=\"./models/\"+model_name, monitor=\"val_loss\", save_best_only=True, save_weights_only=True),\n TensorBoard(\n log_dir=\"./logs/\"+model_name, \n histogram_freq=1, \n update_freq=1)]\n)",
"2021-11-07 19:46:02.771185: I tensorflow/core/profiler/lib/profiler_session.cc:131] Profiler session initializing.\n2021-11-07 19:46:02.771249: I tensorflow/core/profiler/lib/profiler_session.cc:146] Profiler session started.\n2021-11-07 19:46:02.772239: I tensorflow/core/profiler/lib/profiler_session.cc:164] Profiler session tear down.\n"
]
],
[
[
"### Modeling to Predict Cloud Coverage at 60 Minutes Horizon",
"_____no_output_____"
]
],
[
[
"# Creates generators for generating samples with target at 60 minutes horizon for both training and validation\n\nhorizon_60_train_sample_generator = sample_generator(\n data=train, lookback=lookback, \n horizon_col_name=\"Target_Horizon_60\", val_flag_col_name=\"Target_Horizon_60_Val_Flag\",\n val_samples=False, steps=1, batch_size=batch_size)\n\nhorizon_60_val_sample_generator = sample_generator(\n data=train, lookback=lookback, \n horizon_col_name=\"Target_Horizon_60\", val_flag_col_name=\"Target_Horizon_60_Val_Flag\",\n val_samples=True, steps=1, batch_size=batch_size)",
"_____no_output_____"
],
[
"# Calculates number of steps to call to iterate all samples for both training and validation data\n\nsteps_per_epoch = round((train[train[\"Target_Horizon_60\"] != -1].shape[0] - lookback + 1) / batch_size)\nvalidation_steps = round(steps_per_epoch * validation_ratio)",
"_____no_output_____"
],
[
"# Views the calculated steps\nsteps_per_epoch, validation_steps",
"_____no_output_____"
],
[
"# Creates neural network model to predict target at 60 minutes horizon\n\nmodel = Sequential()\nmodel.add(layers.Input(shape=(lookback,len(model_features))))\nmodel.add(layers.GRU(64, return_sequences=True))\nmodel.add(layers.GRU(64, activation=\"relu\"))\nmodel.add(layers.Dense(1))",
"_____no_output_____"
],
[
"# Checks model summary\nmodel.summary()",
"Model: \"sequential_10\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ngru_8 (GRU) (None, 361, 64) 15744 \n_________________________________________________________________\ngru_9 (GRU) (None, 64) 24960 \n_________________________________________________________________\ndense_9 (Dense) (None, 1) 65 \n=================================================================\nTotal params: 40,769\nTrainable params: 40,769\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"# Compiles the model specifying optimizer, loss function and metric\nmodel.compile(optimizer=\"adam\", loss=\"mse\", metrics=\"mae\")",
"_____no_output_____"
],
[
"# Sets model name\nmodel_name = \"horizon-60_gru-64+gru-64-relu+dense\" + \"_\" + datetime.datetime.now().strftime(\"%Y.%m.%d-%H:%M:%S\")\n\n# Fits the model\nhistory = model.fit(\n horizon_60_train_sample_generator, \n steps_per_epoch=steps_per_epoch, \n validation_data=horizon_60_val_sample_generator,\n validation_steps=validation_steps,\n epochs=1,\n callbacks=[\n EarlyStopping(monitor=\"val_loss\", patience=3, mode=\"min\", restore_best_weights=True),\n ModelCheckpoint(filepath=\"./models/\"+model_name, monitor=\"val_loss\", save_best_only=True, save_weights_only=True),\n TensorBoard(\n log_dir=\"./logs/\"+model_name, \n histogram_freq=1, \n update_freq=1)]\n)",
"2021-11-07 20:15:54.873707: I tensorflow/core/profiler/lib/profiler_session.cc:131] Profiler session initializing.\n2021-11-07 20:15:54.873784: I tensorflow/core/profiler/lib/profiler_session.cc:146] Profiler session started.\n2021-11-07 20:15:54.875048: I tensorflow/core/profiler/lib/profiler_session.cc:164] Profiler session tear down.\n"
]
],
[
[
"### Modeling to Predict Cloud Coverage at 90 Minutes Horizon",
"_____no_output_____"
]
],
[
[
"# Creates generators for generating samples with target at 90 minutes horizon for both training and validation\n\nhorizon_90_train_sample_generator = sample_generator(\n data=train, lookback=lookback, \n horizon_col_name=\"Target_Horizon_90\", val_flag_col_name=\"Target_Horizon_90_Val_Flag\",\n val_samples=False, steps=1, batch_size=batch_size)\n\nhorizon_90_val_sample_generator = sample_generator(\n data=train, lookback=lookback, \n horizon_col_name=\"Target_Horizon_90\", val_flag_col_name=\"Target_Horizon_90_Val_Flag\",\n val_samples=True, steps=1, batch_size=batch_size)",
"_____no_output_____"
],
[
"# Calculates number of steps to call to iterate all samples for both training and validation data\n\nsteps_per_epoch = round((train[train[\"Target_Horizon_90\"] != -1].shape[0] - lookback + 1) / batch_size)\nvalidation_steps = round(steps_per_epoch * validation_ratio)",
"_____no_output_____"
],
[
"# Views the calculated steps\nsteps_per_epoch, validation_steps",
"_____no_output_____"
],
[
"# Creates neural network model to predict target at 90 minutes horizon\n\nmodel = Sequential()\nmodel.add(layers.Input(shape=(lookback,len(model_features))))\nmodel.add(layers.GRU(64, return_sequences=True))\nmodel.add(layers.GRU(64, activation=\"relu\"))\nmodel.add(layers.Dense(1))",
"_____no_output_____"
],
[
"# Checks model summary\nmodel.summary()",
"Model: \"sequential_11\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ngru_10 (GRU) (None, 361, 64) 15744 \n_________________________________________________________________\ngru_11 (GRU) (None, 64) 24960 \n_________________________________________________________________\ndense_10 (Dense) (None, 1) 65 \n=================================================================\nTotal params: 40,769\nTrainable params: 40,769\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"# Compiles the model specifying optimizer, loss function and metric\nmodel.compile(optimizer=\"adam\", loss=\"mse\", metrics=\"mae\")",
"_____no_output_____"
],
[
"# Sets model name\nmodel_name = \"horizon-90_gru-64+gru-64-relu+dense\" + \"_\" + datetime.datetime.now().strftime(\"%Y.%m.%d-%H:%M:%S\")\n\n# Fits the model\nhistory = model.fit(\n horizon_90_train_sample_generator, \n steps_per_epoch=steps_per_epoch, \n validation_data=horizon_90_val_sample_generator,\n validation_steps=validation_steps,\n epochs=1,\n callbacks=[\n EarlyStopping(monitor=\"val_loss\", patience=3, mode=\"min\", restore_best_weights=True),\n ModelCheckpoint(filepath=\"./models/\"+model_name, monitor=\"val_loss\", save_best_only=True, save_weights_only=True),\n TensorBoard(\n log_dir=\"./logs/\"+model_name, \n histogram_freq=1, \n update_freq=1)]\n)",
"2021-11-07 20:42:49.828736: I tensorflow/core/profiler/lib/profiler_session.cc:131] Profiler session initializing.\n2021-11-07 20:42:49.828802: I tensorflow/core/profiler/lib/profiler_session.cc:146] Profiler session started.\n2021-11-07 20:42:49.829352: I tensorflow/core/profiler/lib/profiler_session.cc:164] Profiler session tear down.\n"
]
],
[
[
"### Modeling to Predict Cloud Coverage at 120 Minutes Horizon",
"_____no_output_____"
]
],
[
[
"# Creates generators for generating samples with target at 120 minutes horizon for both training and validation\n\nhorizon_120_train_sample_generator = sample_generator(\n data=train, lookback=lookback, \n horizon_col_name=\"Target_Horizon_120\", val_flag_col_name=\"Target_Horizon_120_Val_Flag\",\n val_samples=False, steps=1, batch_size=batch_size)\n\nhorizon_120_val_sample_generator = sample_generator(\n data=train, lookback=lookback, \n horizon_col_name=\"Target_Horizon_120\", val_flag_col_name=\"Target_Horizon_120_Val_Flag\",\n val_samples=True, steps=1, batch_size=batch_size)",
"_____no_output_____"
],
[
"# Calculates number of steps to call to iterate all samples for both training and validation data\n\nsteps_per_epoch = round((train[train[\"Target_Horizon_120\"] != -1].shape[0] - lookback + 1) / batch_size)\nvalidation_steps = round(steps_per_epoch * validation_ratio)",
"_____no_output_____"
],
[
"# Views the calculated steps\nsteps_per_epoch, validation_steps",
"_____no_output_____"
],
[
"# Creates neural network model to predict target at 120 minutes horizon\n\nmodel = Sequential()\nmodel.add(layers.Input(shape=(lookback,len(model_features))))\nmodel.add(layers.GRU(64, return_sequences=True))\nmodel.add(layers.GRU(64, activation=\"relu\"))\nmodel.add(layers.Dense(1))",
"_____no_output_____"
],
[
"# Checks model summary\nmodel.summary()",
"Model: \"sequential_12\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ngru_12 (GRU) (None, 361, 64) 15744 \n_________________________________________________________________\ngru_13 (GRU) (None, 64) 24960 \n_________________________________________________________________\ndense_11 (Dense) (None, 1) 65 \n=================================================================\nTotal params: 40,769\nTrainable params: 40,769\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"# Compiles the model specifying optimizer, loss function and metric\nmodel.compile(optimizer=\"adam\", loss=\"mse\", metrics=\"mae\")",
"_____no_output_____"
],
[
"# Sets model name\nmodel_name = \"horizon-120_gru-64+gru-64-relu+dense\" + \"_\" + datetime.datetime.now().strftime(\"%Y.%m.%d-%H:%M:%S\")\n\n# Fits the model\nhistory = model.fit(\n horizon_120_train_sample_generator, \n steps_per_epoch=steps_per_epoch, \n validation_data=horizon_120_val_sample_generator,\n validation_steps=validation_steps,\n epochs=1,\n callbacks=[\n EarlyStopping(monitor=\"val_loss\", patience=3, mode=\"min\", restore_best_weights=True),\n ModelCheckpoint(filepath=\"./models/\"+model_name, monitor=\"val_loss\", save_best_only=True, save_weights_only=True),\n TensorBoard(\n log_dir=\"./logs/\"+model_name, \n histogram_freq=1, \n update_freq=1)]\n)",
"2021-11-07 21:11:04.474123: I tensorflow/core/profiler/lib/profiler_session.cc:131] Profiler session initializing.\n2021-11-07 21:11:04.474206: I tensorflow/core/profiler/lib/profiler_session.cc:146] Profiler session started.\n2021-11-07 21:11:04.474334: I tensorflow/core/profiler/lib/profiler_session.cc:164] Profiler session tear down.\n"
]
],
[
[
"## Sumbission",
"_____no_output_____"
]
],
[
[
"# Sets test directory path containing test samples\ntest_dir = \"./dataset/test\"",
"_____no_output_____"
],
[
"# Creates a list to contain test samples as tuple having first element as sample index and last element for sample itself\ntest_samples = []\n\n# Iterates over test directories and adds test samples into list\nfor dir in os.listdir(test_dir):\n test_data_file = os.path.join(test_dir, dir, \"weather_data.csv\")\n test = pd.read_csv(test_data_file)\n \n # Drops time column as not required because observations in each sample are already in sequence\n test.drop([\"Time [Mins]\"], axis=1, inplace=True)\n \n # Interpolates values in these two columns as required\n \n observed_cloud_coverage = test[test[\"Total Cloud Cover [%]\"] != -1][\"Total Cloud Cover [%]\"].copy()\n observed_cloud_coverage.loc[observed_cloud_coverage < 0] = np.nan\n observed_cloud_coverage.interpolate(method=\"linear\", inplace=True)\n test[\"Total Cloud Cover [%]\"].update(observed_cloud_coverage)\n \n test.loc[test[\"Albedo (CMP11)\"] < 0, \"Albedo (CMP11)\"] = np.nan\n test[\"Albedo (CMP11)\"].interpolate(method=\"linear\", inplace=True)\n \n # Inserts a column as additional feature, as already done with training data, to indicate if target is available\n test.insert(\n loc=test.columns.get_loc(\"Total Cloud Cover [%]\"), \n column=\"Total Cloud Cover Available\", \n value=test[\"Total Cloud Cover [%]\"].apply(lambda coverage:\n 1 if coverage >= 0 else 0))\n \n # Scales the features\n test[model_features] = model_features_scaler.transform(test[model_features])\n \n # Appends the test sample into the list\n test_samples.append((int(dir), test))",
"_____no_output_____"
],
[
"# Sorts the test samples according to their index number to match submission sequence\ntest_samples = sorted(test_samples, key=lambda scenario: scenario[0])\n\n# Post sorting, only test samples out of thier tuples are extracted\ntest_samples = [test_sample[1] for test_sample in test_samples]\n\n# Converts test samples 3D numpy array to be compatible for model prediction\ntest_samples = np.asarray(test_samples)",
"_____no_output_____"
],
[
"# Checks the shape of the numpy array\ntest_samples.shape",
"_____no_output_____"
]
],
[
[
"### Predicting Cloud Coverage",
"_____no_output_____"
]
],
[
[
"# Note: This step could have been avoided if output nodes were 64 in second layer in each model.\n\nmodel = Sequential()\nmodel.add(layers.Input(shape=(lookback,len(model_features))))\nmodel.add(layers.GRU(64, return_sequences=True))\nmodel.add(layers.GRU(32, activation=\"relu\"))\nmodel.add(layers.Dense(1))\nmodel.compile(optimizer=\"adam\", loss=\"mse\", metrics=\"mae\")",
"_____no_output_____"
],
[
"# Loads weights for best model to predict at 30 minutes horizon\nmodel_name = \"./models/horizon-30_gru-64+gru-32-relu+dense_2021.11.07-19:46:02\"\nmodel.load_weights(model_name)\n\n# Predicting cloud coverage at 30 minutes horizon\nhorizon_30_predictions = model.predict(test_samples).reshape(300,)",
"_____no_output_____"
],
[
"# Note: This step could have been avoided if output nodes were 64 in second layer in each model.\n\nmodel = Sequential()\nmodel.add(layers.Input(shape=(lookback,len(model_features))))\nmodel.add(layers.GRU(64, return_sequences=True))\nmodel.add(layers.GRU(64, activation=\"relu\"))\nmodel.add(layers.Dense(1))\nmodel.compile(optimizer=\"adam\", loss=\"mse\", metrics=\"mae\")",
"_____no_output_____"
],
[
"# Loads weights for best model to predict at 60 minutes horizon\nmodel_name = \"./models/horizon-60_gru-64+gru-64-relu+dense_2021.11.07-20:15:54\"\nmodel.load_weights(model_name)\n\n# Predicting cloud coverage at 60 minutes horizon\nhorizon_60_predictions = model.predict(test_samples).reshape(300,)",
"_____no_output_____"
],
[
"# Loads weights for best model to predict at 90 minutes horizon\nmodel_name = \"./models/horizon-90_gru-64+gru-64-relu+dense_2021.11.07-20:42:49\"\nmodel.load_weights(model_name)\n\n# Predicting cloud coverage at 90 minutes horizon\nhorizon_90_predictions = model.predict(test_samples).reshape(300,)",
"_____no_output_____"
],
[
"# Loads weights for best model to predict at 120 minutes horizon\nmodel_name = \"./models/horizon-120_gru-64+gru-64-relu+dense_2021.11.07-21:11:04\"\nmodel.load_weights(model_name)\n\n# Predicting cloud coverage at 120 minutes horizon\nhorizon_120_predictions = model.predict(test_samples).reshape(300,)",
"_____no_output_____"
],
[
"# Creates dataframe containing predictions for all four horizons\nall_horizon_predictions = pd.DataFrame(\n {\n \"scenario_set\": range(1, 301),\n \"30_min_horizon\": horizon_30_predictions,\n \"60_min_horizon\": horizon_60_predictions,\n \"90_min_horizon\": horizon_90_predictions,\n \"120_min_horizon\": horizon_120_predictions\n }\n )",
"_____no_output_____"
],
[
"# Saves the prediction into file\nall_horizon_predictions.to_csv(\"./submission_2-layers-gru.csv\", index=False)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccef0a0832630fc8275863b99cf0ec9097f6a7f | 87,728 | ipynb | Jupyter Notebook | notebooks/devbook.ipynb | neptune-ml/open-solution-talking-data | 1d68c7b119d3811765046d8506251a0d2ba06c6f | [
"MIT"
] | 8 | 2018-04-16T07:15:23.000Z | 2019-05-26T04:01:06.000Z | notebooks/devbook.ipynb | neptune-ml/open-solution-talking-data | 1d68c7b119d3811765046d8506251a0d2ba06c6f | [
"MIT"
] | 18 | 2018-04-17T22:28:16.000Z | 2018-04-26T16:55:26.000Z | notebooks/devbook.ipynb | neptune-ml/open-solution-talking-data | 1d68c7b119d3811765046d8506251a0d2ba06c6f | [
"MIT"
] | 8 | 2018-04-16T07:15:25.000Z | 2019-06-25T12:42:53.000Z | 96.192982 | 27,606 | 0.746535 | [
[
[
"%load_ext autoreload\n%autoreload 2\n%matplotlib inline\nimport os\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.externals import joblib\nfrom sklearn import metrics\n\nsys.path.append('../')\nfrom visualization import roc_curve_plot, prediction_distribution_plot\nfrom utils import read_csv_time_chunks\nfrom feature_extraction import TimeDeltas",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n"
],
[
"data = read_csv_time_chunks('/mnt/ml-team/minerva/talking_data/files',days=[8],hours=[3])\ndata = data.sample(10000)",
"100%|██████████| 1/1 [00:01<00:00, 1.77s/it]"
],
[
"time_deltas = TimeDeltas(groupby_specs=[['os','app'],['ip','channel']],\n timestamp_column = 'click_time')\n\nX_ = time_deltas.fit_transform(categorical_features=data[['os','app','ip','channel']],\n timestamp_features=data[['click_time']])",
"_____no_output_____"
],
[
"X_['categorical_features']",
"_____no_output_____"
],
[
"res.head()",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"EXPERIMENT_DIR = '/mnt/ml-team/minerva/talking_data/kuba/experiments/'\nEXPERIMENT_NAME = 'baseline'\n\nprediction_filepath = os.path.join(EXPERIMENT_DIR, EXPERIMENT_NAME, 'evaluation_predictions.csv')\nevaluation_predictions = pd.read_csv(prediction_filepath)",
"_____no_output_____"
],
[
"evaluation_predictions.head()",
"_____no_output_____"
],
[
"y_true = evaluation_predictions['is_attributed'].values\ny_pred = evaluation_predictions['y_pred'].values",
"_____no_output_____"
],
[
"fig = roc_curve_plot(y_true, y_pred)",
"_____no_output_____"
],
[
"fig = prediction_distribution_plot(y_true, y_pred, sample=int(10e6), bins=10)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccf1d0c9197895b9108a0cfc61cdd5f4a49b7bd | 10,297 | ipynb | Jupyter Notebook | notebooks/.ipynb_checkpoints/server_00_2_generate_spectrograms-checkpoint.ipynb | marathomas/meerkat_umap | 1c1c23eba6e6219d777464f5afdb6c778198e09e | [
"MIT"
] | null | null | null | notebooks/.ipynb_checkpoints/server_00_2_generate_spectrograms-checkpoint.ipynb | marathomas/meerkat_umap | 1c1c23eba6e6219d777464f5afdb6c778198e09e | [
"MIT"
] | null | null | null | notebooks/.ipynb_checkpoints/server_00_2_generate_spectrograms-checkpoint.ipynb | marathomas/meerkat_umap | 1c1c23eba6e6219d777464f5afdb6c778198e09e | [
"MIT"
] | null | null | null | 29.93314 | 228 | 0.47305 | [
[
[
"# Generate full labelfile",
"_____no_output_____"
],
[
"Script to generate a json file which contains raw audio and spectrogram data for each call.\n\nRequirements:\n\n- A labelfile containing callID_new of all calls (generated with 00_1_generate_call_txts)\n- A folder containig txt audio files of the calls (generated with 00_1_generate_call_txts)\n\nFinal results will be called \"full_labelfile.pkl\" and saved in output directory.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport os\nimport librosa\nimport sys\nimport numpy as np\nimport pickle",
"_____no_output_____"
],
[
"print(\"Please type your path to the EAS server and press enter! \\n For example: \\n /Volumes (on Mac) \\n //10.126.19.90 (on Windows) \\n /home/username/Documents/MPI-Server (when mounted in Documents) \\n\")\nSERVER=input()",
"Please type your path to the EAS server and press enter! \n For example: \n /Volumes (on Mac) \n //10.126.19.90 (on Windows) \n /home/username/Documents/MPI-Server (when mounted in Documents) \n\n/Volumes\n"
],
[
"if not os.path.exists(SERVER):\n print(\"Invalid server path: \", SERVER)\n exit() \n \n# If someone put a slash or backslash in last position\nif SERVER[-1:]==\"/\" or SERVER[-1:]==\"\\n\":\n SERVER = SERVER[:-1]",
"_____no_output_____"
],
[
"HOME = SERVER + os.path.join(os.path.sep, 'EAS_shared',\n 'meerkat','working','processed',\n 'acoustic', 'extract_calls')\n\n# labelfile generated with 00_1_generate_call_txts\nLABELFILE = os.path.join(os.path.sep, HOME,'labelfile.csv')\n\n# location of audio txt files generated with 00_1_generate_call_txts\nTXT_PATH = os.path.join(os.path.sep, HOME,'txts')\n\n# output directory\nOUT = '/home/mthomas/Documents/MPI_work/projects/meerkat/meerkat_umap/meerkat_umap/notebooks'",
"_____no_output_____"
],
[
"# Spectrogramming parameters\nFFT_WIN = 0.03 # FFT_WIN*samplerate = length of fft/n_fft (number of audio frames that go in one fft)\nFFT_HOP = FFT_WIN/8 # FFT_HOP*samplerate = n of audio frames between successive ffts\nN_MELS = 40 # number of mel bins\nWINDOW = 'hann' # each frame of audio is windowed by a window function (its length can also be\n# determined and is then padded with zeros to match n_fft. we use window_length = length of fft\nFMAX = 4000",
"_____no_output_____"
],
[
"def data_from_file(filename):\n \"\"\"\n Function that reads audio data audio\n saved in txt format\n (Helper function for read_wav_txt)\n\n Parameters\n ----------\n data: String\n path to txt file\n \n Returns\n -------\n data : 1D np.array\n Raw audio data (Amplitude)\n \"\"\"\n data = pd.read_csv(filename, skiprows = 1,header = None)\n return np.asarray(data.iloc[:,0])\n\ndef sr_from_file(filename):\n \"\"\"\n Function that reads audio sr from audio\n saved in txt format\n (Helper function for read_wav_txt)\n\n Parameters\n ----------\n data: String\n path to txt file\n \n Returns\n ------- \n sr: numeric (Integer)\n Samplerate (in Hz)\n \"\"\"\n f = open(filename)\n line = f.readline()\n sr = line.split(':')[1]\n return int(sr)\n\ndef read_wav_txt(filename): \n \"\"\"\n Function that reads audio data and sr from audio\n saved in txt format\n\n Parameters\n ----------\n data: String\n path to txt file\n \n Returns\n -------\n data : 1D np.array\n Raw audio data (Amplitude)\n \n sr: numeric (Integer)\n Samplerate (in Hz)\n \"\"\"\n data = \"NA\"\n sr = \"NA\"\n \n if os.path.exists(filename):\n data = data_from_file(filename)\n sr = sr_from_file(filename)\n else:\n print(\"No such file or directory: \", filename)\n data = np.asarray([0])\n sr = 0\n return data, sr\n\ndef generate_mel_spectrogram(data, rate, n_mels, window, fft_win , fft_hop, fmax):\n \n \"\"\"\n Function that generates mel spectrogram from audio data using librosa functions\n\n Parameters\n ----------\n data: 1D numpy array (float)\n Audio data\n rate: numeric(integer)\n samplerate in Hz\n n_mels: numeric (integer)\n number of mel bands\n window: string\n spectrogram window generation type ('hann'...)\n fft_win: numeric (float)\n window length in s\n fft_hop: numeric (float)\n hop between window start in s \n\n Returns\n -------\n result : 2D np.array\n Mel-transformed spectrogram\n\n Example\n -------\n >>> \n \n \"\"\"\n n_fft = int(fft_win * rate) \n hop_length = int(fft_hop * rate) \n \n s = librosa.feature.melspectrogram(y = data ,\n sr = rate, \n n_mels = n_mels , \n fmax = fmax, \n n_fft = n_fft,\n hop_length = hop_length, \n window = window, \n win_length = n_fft)\n\n spectro = librosa.power_to_db(s, ref=np.max)\n\n return spectro",
"_____no_output_____"
]
],
[
[
"# Read in data",
"_____no_output_____"
]
],
[
[
"# Read in labelfile\nlabelfile = pd.read_csv(LABELFILE, sep=\"\\t\")\n# remove zero duration calls\nlabelfile = labelfile.loc[labelfile.duration_s>0,:]\n# remove non-calls\nlabelfile = labelfile.loc[labelfile.isCall==1,:]",
"_____no_output_____"
]
],
[
[
"# Generate audio and samplerate column",
"_____no_output_____"
]
],
[
[
"audios_we_need = [os.path.join(os.path.sep, TXT_PATH, x+'.txt') for x in labelfile.callID_new]\nraw_audio,samplerate_hz = map(list,zip(*[read_wav_txt(x) for x in audios_we_need]))\n\nlabelfile['raw_audio'] = raw_audio\nlabelfile['samplerate_hz'] = samplerate_hz",
"_____no_output_____"
]
],
[
[
"# Generate spectrogram columns",
"_____no_output_____"
]
],
[
[
"spectrograms = labelfile.apply(lambda row: generate_mel_spectrogram(row['raw_audio'],\n row['samplerate_hz'],\n N_MELS,\n WINDOW,\n FFT_WIN,\n FFT_HOP,\n FMAX), \n axis=1)\n\n\nlabelfile['spectrograms'] = spectrograms\n\ndenoised = [(spectrogram - np.median(spectrogram, axis=0)) for spectrogram in labelfile['spectrograms']]\nlabelfile['denoised_spectrograms'] = denoised",
"_____no_output_____"
]
],
[
[
"# Save full labelfile",
"_____no_output_____"
]
],
[
[
"labelfile.to_pickle(os.path.join(os.path.sep, OUT, \"full_labelfile.pkl\"))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
eccf258be3508e20390f8176228b18a6da4f010e | 205,255 | ipynb | Jupyter Notebook | team_project/predictstrom.ipynb | MaengHyoyeol/temp_repo | 775e6c4356081c010dd3f3013fe579fce234bd7d | [
"MIT"
] | null | null | null | team_project/predictstrom.ipynb | MaengHyoyeol/temp_repo | 775e6c4356081c010dd3f3013fe579fce234bd7d | [
"MIT"
] | null | null | null | team_project/predictstrom.ipynb | MaengHyoyeol/temp_repo | 775e6c4356081c010dd3f3013fe579fce234bd7d | [
"MIT"
] | null | null | null | 37.016231 | 269 | 0.266532 | [
[
[
"import csv\nimport pickle\nimport datetime",
"_____no_output_____"
],
[
"%matplotlib inline\n%config InlineBackend.figure_formats = {'png','retina'}",
"_____no_output_____"
],
[
"weather = pd.read_csv('data/weather.csv')",
"_____no_output_____"
],
[
"weather.columns",
"_____no_output_____"
],
[
"weather.date = pd.to_datetime(weather['date'])\n",
"_____no_output_____"
],
[
"weather[\"day_of_year\"] = weather['date'].dt.dayofyear",
"_____no_output_____"
],
[
"weather.head()",
"_____no_output_____"
],
[
"def fulldf(df):\n \n df.snowfall = df.snowfall.replace([\"T\",\" T\"],0.05)\n df.preciptotal = df.preciptotal.replace([\"T\",\" T\"],0.005)\n df.depart = pd.to_numeric(df.depart, errors='coerce')\n \n df = type_change_numeric(df,['station_nbr', 'date', 'tmax', 'tmin', 'tavg', 'depart', 'dewpoint',\\\n 'wetbulb', 'heat', 'cool', 'snowfall',\\\n 'preciptotal', 'stnpressure', 'sealevel', 'resultspeed', 'resultdir',\\\n 'avgspeed'])\n# df['date'] = pd.to_datetime(df['date'])\n# df[\"week_day_name\"] = df['date'].dt.weekday_name\n# df[\"day_of_year\"] = df['date'].dt.dayofyear\n# df[\"year\"] = df['date'].dt.year\n# df['sunrise'] = pd.to_datetime(df['sunrise'])\n# df['sunset'] = pd.to_datetime(df['sunset'])\n \n \n# for idx in range(5, 8):\n# df.iloc[:,idx].fillna(df.groupby([\"day_of_year\",\"store_nbr\"])[df.columns[idx]].\\\n# transform('mean'), inplace=True)\n\n# for idx in range(16, 23):\n# df.iloc[:,idx].fillna(df.groupby([\"day_of_year\",\"store_nbr\"])[df.columns[idx]].\\\n# transform('mean'), inplace=True)\n add_depart1(df)\n \n return df",
"_____no_output_____"
],
[
"def type_change_numeric(df, ls = []): \n #ls에 있는 column name은 numeric형으로 바꾸지 않는다.\n cols = df.columns\n for i in cols:\n if i in ls:\n #df = df.replace([\"M\",None], '')\n df.snowfall = df.snowfall.replace([\"T\",\" T\"],0.05)\n df.preciptotal = df.preciptotal.replace([\"T\",\" T\"],0.005)\n df[i] = pd.to_numeric(df[i], errors='coerce')\n \n return df",
"_____no_output_____"
],
[
"def add_depart1(x):\n x.depart.fillna(x.tavg - x.groupby([\"day_of_year\",\"station_nbr\"])[\"tavg\"].transform('mean'),inplace = True)\n x.depart = x.depart.round(2)\n return x.sort_values([\"station_nbr\",\"date\"])",
"_____no_output_____"
],
[
"weather_df = fulldf(weather)",
"_____no_output_____"
],
[
"weather_df[weather_df.preciptotal.isnull()]",
"_____no_output_____"
],
[
"cont_df = df[sum([df['item_nbr'] == i for i in item_list]).astype(bool)]",
"_____no_output_____"
],
[
"weather_null",
"_____no_output_____"
],
[
"weather_true = weather_df[weather_df.preciptotal != np.NaN]",
"_____no_output_____"
],
[
"del weather_true['depart']",
"_____no_output_____"
],
[
"weather_true = weather_true.dropna()",
"_____no_output_____"
],
[
"weather_true.isnull().any()",
"_____no_output_____"
],
[
"sm.add_constant(weather_true)",
"_____no_output_____"
],
[
"model = sm.OLS.from_formula(\" snowfall ~ C(station_nbr) + scale(dewpoint) + scale(tmax) + scale(tmin) + scale(tavg) + scale(wetbulb) + scale(stnpressure) + scale(sealevel) + scale(resultspeed) + scale(resultdir) + scale(avgspeed) + 0\" , data = weather_true)\n\nresult = model.fit()\nprint(result.summary())",
" OLS Regression Results \n==============================================================================\nDep. Variable: snowfall R-squared: 0.085\nModel: OLS Adj. R-squared: 0.083\nMethod: Least Squares F-statistic: 51.79\nDate: Fri, 06 Jul 2018 Prob (F-statistic): 1.83e-226\nTime: 02:36:14 Log-Likelihood: -8433.7\nNo. Observations: 12927 AIC: 1.692e+04\nDf Residuals: 12903 BIC: 1.709e+04\nDf Model: 23 \nCovariance Type: nonrobust \n======================================================================================\n coef std err t P>|t| [0.025 0.975]\n--------------------------------------------------------------------------------------\nC(station_nbr)[2] 0.7598 0.083 9.196 0.000 0.598 0.922\nC(station_nbr)[3] 0.0733 0.016 4.509 0.000 0.041 0.105\nC(station_nbr)[4] 0.0658 0.015 4.258 0.000 0.036 0.096\nC(station_nbr)[6] -0.2018 0.035 -5.788 0.000 -0.270 -0.133\nC(station_nbr)[7] 1.0483 0.135 7.737 0.000 0.783 1.314\nC(station_nbr)[9] -0.0390 0.118 -0.332 0.740 -0.269 0.191\nC(station_nbr)[11] -0.9322 0.127 -7.331 0.000 -1.181 -0.683\nC(station_nbr)[12] -0.9101 0.125 -7.255 0.000 -1.156 -0.664\nC(station_nbr)[14] 1.0658 0.137 7.801 0.000 0.798 1.334\nC(station_nbr)[15] -0.3669 0.064 -5.716 0.000 -0.493 -0.241\nC(station_nbr)[17] 0.0335 0.015 2.179 0.029 0.003 0.064\nC(station_nbr)[18] -0.2262 0.035 -6.394 0.000 -0.296 -0.157\nC(station_nbr)[19] 0.0761 0.020 3.812 0.000 0.037 0.115\nC(station_nbr)[20] 0.0808 0.016 4.990 0.000 0.049 0.113\nscale(dewpoint) 0.5815 0.039 14.937 0.000 0.505 0.658\nscale(tmax) 0.0279 0.157 0.177 0.859 -0.281 0.336\nscale(tmin) 0.1304 0.153 0.855 0.393 -0.169 0.430\nscale(tavg) 0.2135 0.301 0.710 0.478 -0.376 0.803\nscale(wetbulb) -1.0709 0.068 -15.842 0.000 -1.203 -0.938\nscale(stnpressure) 0.6997 0.089 7.897 0.000 0.526 0.873\nscale(sealevel) -0.3265 0.036 -9.039 0.000 -0.397 -0.256\nscale(resultspeed) 0.0096 0.012 0.818 0.413 -0.013 0.032\nscale(resultdir) -0.0395 0.004 -8.953 0.000 -0.048 -0.031\nscale(avgspeed) 0.0052 0.013 0.414 0.679 -0.019 0.030\n==============================================================================\nOmnibus: 27641.162 Durbin-Watson: 2.009\nProb(Omnibus): 0.000 Jarque-Bera (JB): 122689498.032\nSkew: 19.002 Prob(JB): 0.00\nKurtosis: 478.750 Cond. No. 205.\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n"
],
[
"model2 = sm.OLS.from_formula(\" np.log(preciptotal + 1 ) ~ C(station_nbr) + scale(dewpoint) + scale(wetbulb) + scale(stnpressure) + scale(sealevel) + scale(resultdir) + 0\" , data = weather_true)\n\nresult2 = model2.fit()\nprint(result2.summary())",
" OLS Regression Results \n===================================================================================\nDep. Variable: np.log(preciptotal + 1) R-squared: 0.127\nModel: OLS Adj. R-squared: 0.125\nMethod: Least Squares F-statistic: 104.0\nDate: Fri, 06 Jul 2018 Prob (F-statistic): 0.00\nTime: 02:41:07 Log-Likelihood: 3266.4\nNo. Observations: 12927 AIC: -6495.\nDf Residuals: 12908 BIC: -6353.\nDf Model: 18 \nCovariance Type: nonrobust \n======================================================================================\n coef std err t P>|t| [0.025 0.975]\n--------------------------------------------------------------------------------------\nC(station_nbr)[2] 0.2769 0.033 8.455 0.000 0.213 0.341\nC(station_nbr)[3] 0.0848 0.006 13.054 0.000 0.072 0.098\nC(station_nbr)[4] 0.0807 0.006 13.359 0.000 0.069 0.093\nC(station_nbr)[6] -0.0275 0.014 -2.009 0.045 -0.054 -0.001\nC(station_nbr)[7] 0.4100 0.054 7.654 0.000 0.305 0.515\nC(station_nbr)[9] 0.0351 0.047 0.738 0.461 -0.058 0.128\nC(station_nbr)[11] -0.2437 0.050 -4.846 0.000 -0.342 -0.145\nC(station_nbr)[12] -0.2102 0.050 -4.232 0.000 -0.308 -0.113\nC(station_nbr)[14] 0.4114 0.054 7.615 0.000 0.305 0.517\nC(station_nbr)[15] -0.0907 0.025 -3.608 0.000 -0.140 -0.041\nC(station_nbr)[17] 0.0750 0.006 12.275 0.000 0.063 0.087\nC(station_nbr)[18] 0.0052 0.014 0.367 0.714 -0.023 0.033\nC(station_nbr)[19] 0.0672 0.008 8.501 0.000 0.052 0.083\nC(station_nbr)[20] 0.0908 0.006 14.010 0.000 0.078 0.104\nscale(dewpoint) 0.3371 0.010 34.621 0.000 0.318 0.356\nscale(wetbulb) -0.3334 0.010 -33.500 0.000 -0.353 -0.314\nscale(stnpressure) 0.2178 0.035 6.194 0.000 0.149 0.287\nscale(sealevel) -0.1167 0.014 -8.210 0.000 -0.145 -0.089\nscale(resultdir) -0.0041 0.002 -2.297 0.022 -0.008 -0.001\n==============================================================================\nOmnibus: 10011.279 Durbin-Watson: 1.646\nProb(Omnibus): 0.000 Jarque-Bera (JB): 198105.964\nSkew: 3.668 Prob(JB): 0.00\nKurtosis: 20.720 Cond. No. 110.\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccf2f8fe3f957e02360a45c6efc77011b4ae20a | 17,359 | ipynb | Jupyter Notebook | notebooks/S15E_Efficiency_In_Spark.ipynb | taotangtt/sta-663-2018 | 67dac909477f81d83ebe61e0753de2328af1be9c | [
"BSD-3-Clause"
] | 72 | 2018-01-20T20:50:22.000Z | 2022-02-27T23:24:21.000Z | notebooks/S15E_Efficiency_In_Spark.ipynb | taotangtt/sta-663-2018 | 67dac909477f81d83ebe61e0753de2328af1be9c | [
"BSD-3-Clause"
] | 1 | 2020-02-03T13:43:46.000Z | 2020-02-03T13:43:46.000Z | notebooks/S15E_Efficiency_In_Spark.ipynb | taotangtt/sta-663-2018 | 67dac909477f81d83ebe61e0753de2328af1be9c | [
"BSD-3-Clause"
] | 64 | 2018-01-12T17:13:14.000Z | 2022-03-14T20:22:46.000Z | 26.913178 | 524 | 0.542831 | [
[
[
"# Using Spark Efficiently\n\nFocus in this lecture is on Spark constructs that can make your programs more efficient. In general, this means minimizing the amount of data transfer across nodes, since this is usually the bottleneck for big data analysis problems.\n\n- Shared variables\n - Accumulators\n - Broadcast variables\n- DataFrames\n- Partitioning and the Spark shuffle\n\nSpark tuning and optimization is complicated - this tutorial only touches on some of the basic concepts.\n\nDon't forget the otehr areas of optimizaiton shown in previous notebooks:\n\n- Use DataFrmaes rather than RDDs\n- Use pyspark.sql.functions rather than a Python UDF\n- If you use a UDF, see if you can use a vectorized UDF",
"_____no_output_____"
]
],
[
[
"%%spark",
"Starting Spark application\n"
],
[
"import numpy as np\nimport string",
"_____no_output_____"
]
],
[
[
"Resources\n----\n\n[The Spark Programming Guide](http://spark.apache.org/docs/latest/programming-guide.html)",
"_____no_output_____"
],
[
"## Shared variables\n\nThe second abstraction in Spark are shared variabels, consisting of accumulators and broadcast variables. \n\n\n\nSource: https://jaceklaskowski.gitbooks.io/mastering-apache-spark/content/images/sparkcontext-broadcast-executors.png",
"_____no_output_____"
],
[
"### Accumulators\n\nSpark functions such as `map` can use variables defined in the driver program, but they make local copies of the variable that are not passed back to the driver program. Accumulators are *shared variables* that allow the aggregation of results from workers back to the driver program, for example, as an event counter. Suppose we want to count the number of rows of data with missing information. The most efficient way is to use an **accumulator**.",
"_____no_output_____"
]
],
[
[
"ulysses = sc.textFile('/data/texts/Ulysses.txt')",
"_____no_output_____"
],
[
"ulysses.take(10)",
"[u'', u'The Project Gutenberg EBook of Ulysses, by James Joyce', u'', u'This eBook is for the use of anyone anywhere at no cost and with almost', u'no restrictions whatsoever. You may copy it, give it away or re-use', u'it under the terms of the Project Gutenberg License included with this', u'eBook or online at www.gutenberg.org', u'', u'', u'Title: Ulysses']"
]
],
[
[
"#### Event counting\n\nNotice that we have some empty lines. We want to count the number of non-empty lines.",
"_____no_output_____"
]
],
[
[
"num_lines = sc.accumulator(0)\n\ndef tokenize(line):\n table = dict.fromkeys(map(ord, string.punctuation))\n return line.translate(table).lower().strip().split()\n\ndef tokenize_count(line):\n global num_lines\n \n if line:\n num_lines += 1\n\n return tokenize(line)",
"_____no_output_____"
],
[
"counter = ulysses.flatMap(lambda line: tokenize_count(line)).countByValue()",
"_____no_output_____"
],
[
"counter['circle']",
"20"
],
[
"num_lines.value",
"25510"
]
],
[
[
"### Broadcast Variables\n\nSometimes we need to send a large read only variable to all workers. For example, we might want to share a large feature matrix to all workers as a part of a machine learning application. This same variable will be sent separately for each parallel operation unless you use a **broadcast variable**. Also, the default variable passing mechanism is optimized for small variables and can be slow when the variable is large.",
"_____no_output_____"
]
],
[
[
"from itertools import count\n\ntable = dict(zip(string.ascii_letters, count()))",
"_____no_output_____"
],
[
"def weight_first(line, table):\n words = tokenize(line)\n return sum(table.get(word[0], 0) for word in words if word.isalpha())\n\ndef weight_last(line, table):\n words = tokenize(line)\n return sum(table.get(word[-1], 0) for word in words if word.isalpha())",
"_____no_output_____"
]
],
[
[
"#### The dictionary `table` is sent out twice to worker nodes, one for each call",
"_____no_output_____"
]
],
[
[
"ulysses.map(lambda line: weight_first(line, table)).sum()",
"2868257"
],
[
"ulysses.map(lambda line: weight_last(line, table)).sum()",
"2895879"
]
],
[
[
"#### Converting to use broadast variables is simple and more efficient\n\n- Use SparkContext.broadcast() to create a broadcast variable\n- Where you would use var, use var.value\n- The broadcast variable is sent once to each node and can be re-used",
"_____no_output_____"
]
],
[
[
"table_bc = sc.broadcast(table)",
"_____no_output_____"
],
[
"def weight_first_bc(line, table):\n words = tokenize(line)\n return sum(table.value.get(word[0], 0) for word in words if word.isalpha())\n\ndef weight_last_bc(line, table):\n words = tokenize(line)\n return sum(table.value.get(word[-1], 0) for word in words if word.isalpha())",
"_____no_output_____"
]
],
[
[
"#### table_bc is sent to nodes only once.\n\nAlthough it looks like table_bc is being passed to each function, all that is passed is a path to the table. The worker checks if the path has been cached and uses the cache instead of loading from the path.",
"_____no_output_____"
]
],
[
[
"ulysses.map(lambda line: weight_first_bc(line, table_bc)).sum()",
"2868257"
],
[
"ulysses.map(lambda line: weight_last_bc(line, table_bc)).sum()",
"2895879"
]
],
[
[
"The Spark Shuffle and Partitioning\n----\n\nSome events trigger the redistribution of data across partitions, and involves the (expensive) copying of data across executors and machines. This is known as the **shuffle**. For example, if we do a `reduceByKey` operation on key-value pair RDD, Spark needs to collect all pairs with the same key in the same partition to do the reduction. \n\nFor key-value RDDs, you have some control over the partitioning of the RDDs. In particular, you can ask Spark to partition a set of keys so that they are guaranteed to appear together on some node. This can minimize a lot of data transfer. For example, suppose you have a large key-value RDD consisting of user_name: comments from a web user community. Every night, you want to update with new user comments with a join operation",
"_____no_output_____"
]
],
[
[
"def fake_data(n, val):\n users = list(map(''.join, np.random.choice(list(string.ascii_lowercase), (n,2))))\n comments = [val]*n\n return tuple(zip(users, comments))",
"_____no_output_____"
],
[
"data = fake_data(10000, 'a')\nlist(data)[:10]",
"[('en', 'a'), ('mg', 'a'), ('sn', 'a'), ('ys', 'a'), ('ov', 'a'), ('xp', 'a'), ('hs', 'a'), ('xx', 'a'), ('nb', 'a'), ('te', 'a')]"
],
[
"rdd = sc.parallelize(data).reduceByKey(lambda x, y: x+y)",
"_____no_output_____"
],
[
"new_data = fake_data(1000, 'b')\nlist(new_data)[:10]",
"[('bj', 'b'), ('jb', 'b'), ('ue', 'b'), ('oy', 'b'), ('pe', 'b'), ('zt', 'b'), ('jn', 'b'), ('mn', 'b'), ('ph', 'b'), ('zo', 'b')]"
],
[
"rdd_new = sc.parallelize(new_data).reduceByKey(lambda x, y: x+y).cache()",
"_____no_output_____"
],
[
"rdd_updated = rdd.join(rdd_new)",
"_____no_output_____"
],
[
"rdd_updated.take(10)",
"[('gs', ('aaaaaaaaaaaaa', 'bbbbb')), ('gg', ('aaaaaaaaaaaaaaa', 'bb')), ('yq', ('aaaaaaaa', 'bb')), ('gc', ('aaaaaaaaaaaaaaaaaa', 'b')), ('go', ('aaaaaaaaaaaaaaa', 'b')), ('gk', ('aaaaaaaaaaaaa', 'b')), ('lf', ('aaaaaaaaaaaaaaaa', 'bb')), ('iq', ('aaaaaaaaaaaaaaaaa', 'bbb')), ('ln', ('aaaaaaaaaaaaaaaaa', 'bb')), ('dr', ('aaaaaaaaaaaaa', 'b'))]"
]
],
[
[
"### Using `partitionBy`\n\nThe `join` operation will hash all the keys of both `rdd` and `rdd_nerw`, sending keys with the same hashes to the same node for the actual join operation. There is a lot of unnecessary data transfer. Since `rdd` is a much larger data set than `rdd_new`, we can instead fix the partitioning of `rdd` and just transfer the keys of `rdd_new`. This is done by `rdd.partitionBy(numPartitions)` where `numPartitions` should be at least twice the number of cores.\n\nFrom the R docs for `partitionBy`\n```\nThis function operates on RDDs where every element is of the form list(K, V) or c(K, V). For each element of this RDD, the partitioner is used to compute a hash function and the RDD is partitioned using this hash value.\n```\n\nIn other words, which parittion a data element is sent to depends on the key value.",
"_____no_output_____"
]
],
[
[
"rdd_A = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x))\nfor item in rdd_A.partitionBy(4).glom().collect():\n print(item)",
"[(4, 4), (4, 4)]\n[(1, 1), (1, 1)]\n[(2, 2), (2, 2)]\n[(3, 3)]"
],
[
"rdd_B = sc.parallelize([(4,'a'), (1,'b'), (2, 'c'), (3, 'd'), (4,'e'), (1, 'f')])",
"_____no_output_____"
],
[
"for item in rdd_B.glom().collect():\n print(item)",
"[(4, 'a')]\n[(1, 'b'), (2, 'c')]\n[(3, 'd')]\n[(4, 'e'), (1, 'f')]"
],
[
"rdd_comb = rdd_A.join(rdd_B).glom()",
"_____no_output_____"
]
],
[
[
"**Note**: See how all the items from `rdd_B` have been transferred to the partitions created by `rdd_A`, but the items from `rdd_A` have not moved. If `rdd_A` is much larger than `rdd_B` then this minimizes the amount of data transfer.",
"_____no_output_____"
]
],
[
[
"for item in rdd_comb.collect():\n print(item)",
"[]\n[(1, (1, 'f')), (1, (1, 'b')), (1, (1, 'f')), (1, (1, 'b'))]\n[(2, (2, 'c')), (2, (2, 'c'))]\n[(3, (3, 'd'))]\n[(4, (4, 'a')), (4, (4, 'e')), (4, (4, 'a')), (4, (4, 'e'))]\n[]\n[]\n[]"
]
],
[
[
"Applyin to our word counts",
"_____no_output_____"
]
],
[
[
"rdd2 = sc.parallelize(data).reduceByKey(lambda x, y: x+y)\nrdd2 = rdd2.partitionBy(10).cache()",
"_____no_output_____"
],
[
"rdd2_updated = rdd2.join(rdd_new)",
"_____no_output_____"
],
[
"rdd2_updated.take(10)",
"[('zn', ('aaaaaaaaa', 'bb')), ('cm', ('aaaaaaaaaaaaa', 'b')), ('vh', ('aaaaaaaaaaaaaaaaaaaa', 'b')), ('eg', ('aaaaaaaaaaaaaaa', 'bbb')), ('xf', ('aaaaaaaaaa', 'b')), ('gy', ('aaaaaa', 'bbbb')), ('aq', ('aaaaaaaaaaaaaaaaa', 'b')), ('ik', ('aaaaaaaaaaaaaaaaaaaaaaa', 'b')), ('vv', ('aaaaaaaaa', 'b')), ('eu', ('aaaaaaaaaa', 'b'))]"
],
[
"spark.stop()",
"_____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",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
eccf32d3e1075138e44a6a4a49d1946f74daabd3 | 552,500 | ipynb | Jupyter Notebook | Deep Learning Specialization/1. Neural Networks and Deep Learning/Planar_data_classification_with_onehidden_layer_v6c.ipynb | pablojgm/Coursera | 3835dc774c91e567c477e1e956abbb582aef335c | [
"Unlicense"
] | null | null | null | Deep Learning Specialization/1. Neural Networks and Deep Learning/Planar_data_classification_with_onehidden_layer_v6c.ipynb | pablojgm/Coursera | 3835dc774c91e567c477e1e956abbb582aef335c | [
"Unlicense"
] | null | null | null | Deep Learning Specialization/1. Neural Networks and Deep Learning/Planar_data_classification_with_onehidden_layer_v6c.ipynb | pablojgm/Coursera | 3835dc774c91e567c477e1e956abbb582aef335c | [
"Unlicense"
] | null | null | null | 345.528455 | 320,184 | 0.91343 | [
[
[
"\n### <font color = \"darkblue\">Updates to Assignment</font>\n\n#### If you were working on the older version:\n* Please click on the \"Coursera\" icon in the top right to open up the folder directory. \n* Navigate to the folder: Week 3/ Planar data classification with one hidden layer. You can see your prior work in version 6b: \"Planar data classification with one hidden layer v6b.ipynb\"\n\n#### List of bug fixes and enhancements\n* Clarifies that the classifier will learn to classify regions as either red or blue.\n* compute_cost function fixes np.squeeze by casting it as a float.\n* compute_cost instructions clarify the purpose of np.squeeze.\n* compute_cost clarifies that \"parameters\" parameter is not needed, but is kept in the function definition until the auto-grader is also updated.\n* nn_model removes extraction of parameter values, as the entire parameter dictionary is passed to the invoked functions.",
"_____no_output_____"
],
[
"# Planar data classification with one hidden layer\n\nWelcome to your week 3 programming assignment. It's time to build your first neural network, which will have a hidden layer. You will see a big difference between this model and the one you implemented using logistic regression. \n\n**You will learn how to:**\n- Implement a 2-class classification neural network with a single hidden layer\n- Use units with a non-linear activation function, such as tanh \n- Compute the cross entropy loss \n- Implement forward and backward propagation\n",
"_____no_output_____"
],
[
"## 1 - Packages ##\n\nLet's first import all the packages that you will need during this assignment.\n- [numpy](https://www.numpy.org/) is the fundamental package for scientific computing with Python.\n- [sklearn](http://scikit-learn.org/stable/) provides simple and efficient tools for data mining and data analysis. \n- [matplotlib](http://matplotlib.org) is a library for plotting graphs in Python.\n- testCases provides some test examples to assess the correctness of your functions\n- planar_utils provide various useful functions used in this assignment",
"_____no_output_____"
]
],
[
[
"# Package imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom testCases_v2 import *\nimport sklearn\nimport sklearn.datasets\nimport sklearn.linear_model\nfrom planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets\n\n%matplotlib inline\n\nnp.random.seed(1) # set a seed so that the results are consistent",
"_____no_output_____"
]
],
[
[
"## 2 - Dataset ##\n\nFirst, let's get the dataset you will work on. The following code will load a \"flower\" 2-class dataset into variables `X` and `Y`.",
"_____no_output_____"
]
],
[
[
"X, Y = load_planar_dataset()",
"_____no_output_____"
]
],
[
[
"Visualize the dataset using matplotlib. The data looks like a \"flower\" with some red (label y=0) and some blue (y=1) points. Your goal is to build a model to fit this data. In other words, we want the classifier to define regions as either red or blue.",
"_____no_output_____"
]
],
[
[
"# Visualize the data:\nplt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);",
"_____no_output_____"
]
],
[
[
"You have:\n - a numpy-array (matrix) X that contains your features (x1, x2)\n - a numpy-array (vector) Y that contains your labels (red:0, blue:1).\n\nLets first get a better sense of what our data is like. \n\n**Exercise**: How many training examples do you have? In addition, what is the `shape` of the variables `X` and `Y`? \n\n**Hint**: How do you get the shape of a numpy array? [(help)](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html)",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (≈ 3 lines of code)\nshape_X = X.shape\nshape_Y = Y.shape\nm = X.shape[1] # training set size\n### END CODE HERE ###\n\nprint ('The shape of X is: ' + str(shape_X))\nprint ('The shape of Y is: ' + str(shape_Y))\nprint ('I have m = %d training examples!' % (m))",
"The shape of X is: (2, 400)\nThe shape of Y is: (1, 400)\nI have m = 400 training examples!\n"
]
],
[
[
"**Expected Output**:\n \n<table style=\"width:20%\">\n \n <tr>\n <td>**shape of X**</td>\n <td> (2, 400) </td> \n </tr>\n \n <tr>\n <td>**shape of Y**</td>\n <td>(1, 400) </td> \n </tr>\n \n <tr>\n <td>**m**</td>\n <td> 400 </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"## 3 - Simple Logistic Regression\n\nBefore building a full neural network, lets first see how logistic regression performs on this problem. You can use sklearn's built-in functions to do that. Run the code below to train a logistic regression classifier on the dataset.",
"_____no_output_____"
]
],
[
[
"# Train the logistic regression classifier\nclf = sklearn.linear_model.LogisticRegressionCV();\nclf.fit(X.T, Y.T);",
"_____no_output_____"
]
],
[
[
"You can now plot the decision boundary of these models. Run the code below.",
"_____no_output_____"
]
],
[
[
"# Plot the decision boundary for logistic regression\nplot_decision_boundary(lambda x: clf.predict(x), X, Y)\nplt.title(\"Logistic Regression\")\n\n# Print accuracy\nLR_predictions = clf.predict(X.T)\nprint ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +\n '% ' + \"(percentage of correctly labelled datapoints)\")",
"Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:20%\">\n <tr>\n <td>**Accuracy**</td>\n <td> 47% </td> \n </tr>\n \n</table>\n",
"_____no_output_____"
],
[
"**Interpretation**: The dataset is not linearly separable, so logistic regression doesn't perform well. Hopefully a neural network will do better. Let's try this now! ",
"_____no_output_____"
],
[
"## 4 - Neural Network model\n\nLogistic regression did not work well on the \"flower dataset\". You are going to train a Neural Network with a single hidden layer.\n\n**Here is our model**:\n<img src=\"images/classification_kiank.png\" style=\"width:600px;height:300px;\">\n\n**Mathematically**:\n\nFor one example $x^{(i)}$:\n$$z^{[1] (i)} = W^{[1]} x^{(i)} + b^{[1]}\\tag{1}$$ \n$$a^{[1] (i)} = \\tanh(z^{[1] (i)})\\tag{2}$$\n$$z^{[2] (i)} = W^{[2]} a^{[1] (i)} + b^{[2]}\\tag{3}$$\n$$\\hat{y}^{(i)} = a^{[2] (i)} = \\sigma(z^{ [2] (i)})\\tag{4}$$\n$$y^{(i)}_{prediction} = \\begin{cases} 1 & \\mbox{if } a^{[2](i)} > 0.5 \\\\ 0 & \\mbox{otherwise } \\end{cases}\\tag{5}$$\n\nGiven the predictions on all the examples, you can also compute the cost $J$ as follows: \n$$J = - \\frac{1}{m} \\sum\\limits_{i = 0}^{m} \\large\\left(\\small y^{(i)}\\log\\left(a^{[2] (i)}\\right) + (1-y^{(i)})\\log\\left(1- a^{[2] (i)}\\right) \\large \\right) \\small \\tag{6}$$\n\n**Reminder**: The general methodology to build a Neural Network is to:\n 1. Define the neural network structure ( # of input units, # of hidden units, etc). \n 2. Initialize the model's parameters\n 3. Loop:\n - Implement forward propagation\n - Compute loss\n - Implement backward propagation to get the gradients\n - Update parameters (gradient descent)\n\nYou often build helper functions to compute steps 1-3 and then merge them into one function we call `nn_model()`. Once you've built `nn_model()` and learnt the right parameters, you can make predictions on new data.",
"_____no_output_____"
],
[
"### 4.1 - Defining the neural network structure ####\n\n**Exercise**: Define three variables:\n - n_x: the size of the input layer\n - n_h: the size of the hidden layer (set this to 4) \n - n_y: the size of the output layer\n\n**Hint**: Use shapes of X and Y to find n_x and n_y. Also, hard code the hidden layer size to be 4.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: layer_sizes\n\ndef layer_sizes(X, Y):\n \"\"\"\n Arguments:\n X -- input dataset of shape (input size, number of examples)\n Y -- labels of shape (output size, number of examples)\n \n Returns:\n n_x -- the size of the input layer\n n_h -- the size of the hidden layer\n n_y -- the size of the output layer\n \"\"\"\n ### START CODE HERE ### (≈ 3 lines of code)\n n_x = X.shape[0] # size of input layer\n n_h = 4\n n_y = Y.shape[0] # size of output layer\n ### END CODE HERE ###\n return (n_x, n_h, n_y)",
"_____no_output_____"
],
[
"X_assess, Y_assess = layer_sizes_test_case()\n(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)\nprint(\"The size of the input layer is: n_x = \" + str(n_x))\nprint(\"The size of the hidden layer is: n_h = \" + str(n_h))\nprint(\"The size of the output layer is: n_y = \" + str(n_y))",
"The size of the input layer is: n_x = 5\nThe size of the hidden layer is: n_h = 4\nThe size of the output layer is: n_y = 2\n"
]
],
[
[
"**Expected Output** (these are not the sizes you will use for your network, they are just used to assess the function you've just coded).\n\n<table style=\"width:20%\">\n <tr>\n <td>**n_x**</td>\n <td> 5 </td> \n </tr>\n \n <tr>\n <td>**n_h**</td>\n <td> 4 </td> \n </tr>\n \n <tr>\n <td>**n_y**</td>\n <td> 2 </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"### 4.2 - Initialize the model's parameters ####\n\n**Exercise**: Implement the function `initialize_parameters()`.\n\n**Instructions**:\n- Make sure your parameters' sizes are right. Refer to the neural network figure above if needed.\n- You will initialize the weights matrices with random values. \n - Use: `np.random.randn(a,b) * 0.01` to randomly initialize a matrix of shape (a,b).\n- You will initialize the bias vectors as zeros. \n - Use: `np.zeros((a,b))` to initialize a matrix of shape (a,b) with zeros.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters\n\ndef initialize_parameters(n_x, n_h, n_y):\n \"\"\"\n Argument:\n n_x -- size of the input layer\n n_h -- size of the hidden layer\n n_y -- size of the output layer\n \n Returns:\n params -- python dictionary containing your parameters:\n W1 -- weight matrix of shape (n_h, n_x)\n b1 -- bias vector of shape (n_h, 1)\n W2 -- weight matrix of shape (n_y, n_h)\n b2 -- bias vector of shape (n_y, 1)\n \"\"\"\n \n np.random.seed(2) # we set up a seed so that your output matches ours although the initialization is random.\n \n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = np.random.randn(n_h,n_x) * 0.01\n b1 = np.zeros((n_h,1))\n W2 = np.random.randn(n_y,n_h) * 0.01\n b2 = np.zeros((n_y,1))\n ### END CODE HERE ###\n \n assert (W1.shape == (n_h, n_x))\n assert (b1.shape == (n_h, 1))\n assert (W2.shape == (n_y, n_h))\n assert (b2.shape == (n_y, 1))\n \n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n \n return parameters",
"_____no_output_____"
],
[
"n_x, n_h, n_y = initialize_parameters_test_case()\n\nparameters = initialize_parameters(n_x, n_h, n_y)\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"W1 = [[-0.00416758 -0.00056267]\n [-0.02136196 0.01640271]\n [-0.01793436 -0.00841747]\n [ 0.00502881 -0.01245288]]\nb1 = [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]]\nW2 = [[-0.01057952 -0.00909008 0.00551454 0.02292208]]\nb2 = [[ 0.]]\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:90%\">\n <tr>\n <td>**W1**</td>\n <td> [[-0.00416758 -0.00056267]\n [-0.02136196 0.01640271]\n [-0.01793436 -0.00841747]\n [ 0.00502881 -0.01245288]] </td> \n </tr>\n \n <tr>\n <td>**b1**</td>\n <td> [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]] </td> \n </tr>\n \n <tr>\n <td>**W2**</td>\n <td> [[-0.01057952 -0.00909008 0.00551454 0.02292208]]</td> \n </tr>\n \n\n <tr>\n <td>**b2**</td>\n <td> [[ 0.]] </td> \n </tr>\n \n</table>\n\n",
"_____no_output_____"
],
[
"### 4.3 - The Loop ####\n\n**Question**: Implement `forward_propagation()`.\n\n**Instructions**:\n- Look above at the mathematical representation of your classifier.\n- You can use the function `sigmoid()`. It is built-in (imported) in the notebook.\n- You can use the function `np.tanh()`. It is part of the numpy library.\n- The steps you have to implement are:\n 1. Retrieve each parameter from the dictionary \"parameters\" (which is the output of `initialize_parameters()`) by using `parameters[\"..\"]`.\n 2. Implement Forward Propagation. Compute $Z^{[1]}, A^{[1]}, Z^{[2]}$ and $A^{[2]}$ (the vector of all your predictions on all the examples in the training set).\n- Values needed in the backpropagation are stored in \"`cache`\". The `cache` will be given as an input to the backpropagation function.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: forward_propagation\n\ndef forward_propagation(X, parameters):\n \"\"\"\n Argument:\n X -- input data of size (n_x, m)\n parameters -- python dictionary containing your parameters (output of initialization function)\n \n Returns:\n A2 -- The sigmoid output of the second activation\n cache -- a dictionary containing \"Z1\", \"A1\", \"Z2\" and \"A2\"\n \"\"\"\n # Retrieve each parameter from the dictionary \"parameters\"\n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n ### END CODE HERE ###\n \n # Implement Forward Propagation to calculate A2 (probabilities)\n ### START CODE HERE ### (≈ 4 lines of code)\n Z1 = np.dot(W1, X)+b1\n A1 = np.tanh(Z1)\n Z2 = np.dot(W2, A1)+b2\n A2 = sigmoid(Z2)\n ### END CODE HERE ###\n \n assert(A2.shape == (1, X.shape[1]))\n \n cache = {\"Z1\": Z1,\n \"A1\": A1,\n \"Z2\": Z2,\n \"A2\": A2}\n \n return A2, cache",
"_____no_output_____"
],
[
"X_assess, parameters = forward_propagation_test_case()\nA2, cache = forward_propagation(X_assess, parameters)\n\n# Note: we use the mean here just to make sure that your output matches ours. \nprint(np.mean(cache['Z1']) ,np.mean(cache['A1']),np.mean(cache['Z2']),np.mean(cache['A2']))",
"0.262818640198 0.091999045227 -1.30766601287 0.212877681719\n"
]
],
[
[
"**Expected Output**:\n<table style=\"width:50%\">\n <tr>\n <td> 0.262818640198 0.091999045227 -1.30766601287 0.212877681719 </td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"Now that you have computed $A^{[2]}$ (in the Python variable \"`A2`\"), which contains $a^{[2](i)}$ for every example, you can compute the cost function as follows:\n\n$$J = - \\frac{1}{m} \\sum\\limits_{i = 1}^{m} \\large{(} \\small y^{(i)}\\log\\left(a^{[2] (i)}\\right) + (1-y^{(i)})\\log\\left(1- a^{[2] (i)}\\right) \\large{)} \\small\\tag{13}$$\n\n**Exercise**: Implement `compute_cost()` to compute the value of the cost $J$.\n\n**Instructions**:\n- There are many ways to implement the cross-entropy loss. To help you, we give you how we would have implemented\n$- \\sum\\limits_{i=0}^{m} y^{(i)}\\log(a^{[2](i)})$:\n```python\nlogprobs = np.multiply(np.log(A2),Y)\ncost = - np.sum(logprobs) # no need to use a for loop!\n```\n\n(you can use either `np.multiply()` and then `np.sum()` or directly `np.dot()`). \nNote that if you use `np.multiply` followed by `np.sum` the end result will be a type `float`, whereas if you use `np.dot`, the result will be a 2D numpy array. We can use `np.squeeze()` to remove redundant dimensions (in the case of single float, this will be reduced to a zero-dimension array). We can cast the array as a type `float` using `float()`.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: compute_cost\n\ndef compute_cost(A2, Y, parameters):\n \"\"\"\n Computes the cross-entropy cost given in equation (13)\n \n Arguments:\n A2 -- The sigmoid output of the second activation, of shape (1, number of examples)\n Y -- \"true\" labels vector of shape (1, number of examples)\n parameters -- python dictionary containing your parameters W1, b1, W2 and b2\n [Note that the parameters argument is not used in this function, \n but the auto-grader currently expects this parameter.\n Future version of this notebook will fix both the notebook \n and the auto-grader so that `parameters` is not needed.\n For now, please include `parameters` in the function signature,\n and also when invoking this function.]\n \n Returns:\n cost -- cross-entropy cost given equation (13)\n \n \"\"\"\n \n m = Y.shape[1] # number of example\n\n # Compute the cross-entropy cost\n ### START CODE HERE ### (≈ 2 lines of code)\n logprobs = np.multiply(np.log(A2),Y) + np.multiply((1-Y), np.log(1-A2))\n cost = (-1/m) * np.sum(logprobs) \n ### END CODE HERE ###\n \n cost = float(np.squeeze(cost)) # makes sure cost is the dimension we expect. \n # E.g., turns [[17]] into 17 \n assert(isinstance(cost, float))\n \n return cost",
"_____no_output_____"
],
[
"A2, Y_assess, parameters = compute_cost_test_case()\n\nprint(\"cost = \" + str(compute_cost(A2, Y_assess, parameters)))",
"cost = 0.6930587610394646\n"
]
],
[
[
"**Expected Output**:\n<table style=\"width:20%\">\n <tr>\n <td>**cost**</td>\n <td> 0.693058761... </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"Using the cache computed during forward propagation, you can now implement backward propagation.\n\n**Question**: Implement the function `backward_propagation()`.\n\n**Instructions**:\nBackpropagation is usually the hardest (most mathematical) part in deep learning. To help you, here again is the slide from the lecture on backpropagation. You'll want to use the six equations on the right of this slide, since you are building a vectorized implementation. \n\n<img src=\"images/grad_summary.png\" style=\"width:600px;height:300px;\">\n\n<!--\n$\\frac{\\partial \\mathcal{J} }{ \\partial z_{2}^{(i)} } = \\frac{1}{m} (a^{[2](i)} - y^{(i)})$\n\n$\\frac{\\partial \\mathcal{J} }{ \\partial W_2 } = \\frac{\\partial \\mathcal{J} }{ \\partial z_{2}^{(i)} } a^{[1] (i) T} $\n\n$\\frac{\\partial \\mathcal{J} }{ \\partial b_2 } = \\sum_i{\\frac{\\partial \\mathcal{J} }{ \\partial z_{2}^{(i)}}}$\n\n$\\frac{\\partial \\mathcal{J} }{ \\partial z_{1}^{(i)} } = W_2^T \\frac{\\partial \\mathcal{J} }{ \\partial z_{2}^{(i)} } * ( 1 - a^{[1] (i) 2}) $\n\n$\\frac{\\partial \\mathcal{J} }{ \\partial W_1 } = \\frac{\\partial \\mathcal{J} }{ \\partial z_{1}^{(i)} } X^T $\n\n$\\frac{\\partial \\mathcal{J} _i }{ \\partial b_1 } = \\sum_i{\\frac{\\partial \\mathcal{J} }{ \\partial z_{1}^{(i)}}}$\n\n- Note that $*$ denotes elementwise multiplication.\n- The notation you will use is common in deep learning coding:\n - dW1 = $\\frac{\\partial \\mathcal{J} }{ \\partial W_1 }$\n - db1 = $\\frac{\\partial \\mathcal{J} }{ \\partial b_1 }$\n - dW2 = $\\frac{\\partial \\mathcal{J} }{ \\partial W_2 }$\n - db2 = $\\frac{\\partial \\mathcal{J} }{ \\partial b_2 }$\n \n!-->\n\n- Tips:\n - To compute dZ1 you'll need to compute $g^{[1]'}(Z^{[1]})$. Since $g^{[1]}(.)$ is the tanh activation function, if $a = g^{[1]}(z)$ then $g^{[1]'}(z) = 1-a^2$. So you can compute \n $g^{[1]'}(Z^{[1]})$ using `(1 - np.power(A1, 2))`.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: backward_propagation\n\ndef backward_propagation(parameters, cache, X, Y):\n \"\"\"\n Implement the backward propagation using the instructions above.\n \n Arguments:\n parameters -- python dictionary containing our parameters \n cache -- a dictionary containing \"Z1\", \"A1\", \"Z2\" and \"A2\".\n X -- input data of shape (2, number of examples)\n Y -- \"true\" labels vector of shape (1, number of examples)\n \n Returns:\n grads -- python dictionary containing your gradients with respect to different parameters\n \"\"\"\n m = X.shape[1]\n \n # First, retrieve W1 and W2 from the dictionary \"parameters\".\n ### START CODE HERE ### (≈ 2 lines of code)\n W1 = parameters[\"W1\"]\n W2 = parameters[\"W2\"]\n ### END CODE HERE ###\n \n # Retrieve also A1 and A2 from dictionary \"cache\".\n ### START CODE HERE ### (≈ 2 lines of code)\n A1 = cache[\"A1\"]\n A2 = cache[\"A2\"]\n ### END CODE HERE ###\n \n # Backward propagation: calculate dW1, db1, dW2, db2. \n ### START CODE HERE ### (≈ 6 lines of code, corresponding to 6 equations on slide above)\n dZ2 = A2-Y\n dW2 = (1/m) * np.dot(dZ2, A1.T)\n db2 = (1/m) * np.sum(dZ2, axis = 1, keepdims = True)\n dZ1 = np.multiply( np.dot(W2.T, dZ2), 1-np.power(A1,2) )\n dW1 = (1/m) * np.dot(dZ1, X.T)\n db1 = (1/m) * np.sum(dZ1, axis = 1, keepdims = True)\n ### END CODE HERE ###\n \n grads = {\"dW1\": dW1,\n \"db1\": db1,\n \"dW2\": dW2,\n \"db2\": db2}\n \n return grads",
"_____no_output_____"
],
[
"parameters, cache, X_assess, Y_assess = backward_propagation_test_case()\n\ngrads = backward_propagation(parameters, cache, X_assess, Y_assess)\nprint (\"dW1 = \"+ str(grads[\"dW1\"]))\nprint (\"db1 = \"+ str(grads[\"db1\"]))\nprint (\"dW2 = \"+ str(grads[\"dW2\"]))\nprint (\"db2 = \"+ str(grads[\"db2\"]))",
"dW1 = [[ 0.00301023 -0.00747267]\n [ 0.00257968 -0.00641288]\n [-0.00156892 0.003893 ]\n [-0.00652037 0.01618243]]\ndb1 = [[ 0.00176201]\n [ 0.00150995]\n [-0.00091736]\n [-0.00381422]]\ndW2 = [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]]\ndb2 = [[-0.16655712]]\n"
]
],
[
[
"**Expected output**:\n\n\n\n<table style=\"width:80%\">\n <tr>\n <td>**dW1**</td>\n <td> [[ 0.00301023 -0.00747267]\n [ 0.00257968 -0.00641288]\n [-0.00156892 0.003893 ]\n [-0.00652037 0.01618243]] </td> \n </tr>\n \n <tr>\n <td>**db1**</td>\n <td> [[ 0.00176201]\n [ 0.00150995]\n [-0.00091736]\n [-0.00381422]] </td> \n </tr>\n \n <tr>\n <td>**dW2**</td>\n <td> [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]] </td> \n </tr>\n \n\n <tr>\n <td>**db2**</td>\n <td> [[-0.16655712]] </td> \n </tr>\n \n</table> ",
"_____no_output_____"
],
[
"**Question**: Implement the update rule. Use gradient descent. You have to use (dW1, db1, dW2, db2) in order to update (W1, b1, W2, b2).\n\n**General gradient descent rule**: $ \\theta = \\theta - \\alpha \\frac{\\partial J }{ \\partial \\theta }$ where $\\alpha$ is the learning rate and $\\theta$ represents a parameter.\n\n**Illustration**: The gradient descent algorithm with a good learning rate (converging) and a bad learning rate (diverging). Images courtesy of Adam Harley.\n\n<img src=\"images/sgd.gif\" style=\"width:400;height:400;\"> <img src=\"images/sgd_bad.gif\" style=\"width:400;height:400;\">\n\n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: update_parameters\n\ndef update_parameters(parameters, grads, learning_rate = 1.2):\n \"\"\"\n Updates parameters using the gradient descent update rule given above\n \n Arguments:\n parameters -- python dictionary containing your parameters \n grads -- python dictionary containing your gradients \n \n Returns:\n parameters -- python dictionary containing your updated parameters \n \"\"\"\n # Retrieve each parameter from the dictionary \"parameters\"\n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n ### END CODE HERE ###\n \n # Retrieve each gradient from the dictionary \"grads\"\n ### START CODE HERE ### (≈ 4 lines of code)\n dW1 = grads[\"dW1\"]\n db1 = grads[\"db1\"]\n dW2 = grads[\"dW2\"]\n db2 = grads[\"db2\"]\n ## END CODE HERE ###\n \n # Update rule for each parameter\n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = W1 - learning_rate * dW1\n b1 = b1 - learning_rate * db1\n W2 = W2 - learning_rate * dW2\n b2 = b2 - learning_rate * db2\n ### END CODE HERE ###\n \n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n \n return parameters",
"_____no_output_____"
],
[
"parameters, grads = update_parameters_test_case()\nparameters = update_parameters(parameters, grads)\n\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"W1 = [[-0.00643025 0.01936718]\n [-0.02410458 0.03978052]\n [-0.01653973 -0.02096177]\n [ 0.01046864 -0.05990141]]\nb1 = [[ -1.02420756e-06]\n [ 1.27373948e-05]\n [ 8.32996807e-07]\n [ -3.20136836e-06]]\nW2 = [[-0.01041081 -0.04463285 0.01758031 0.04747113]]\nb2 = [[ 0.00010457]]\n"
]
],
[
[
"**Expected Output**:\n\n\n<table style=\"width:80%\">\n <tr>\n <td>**W1**</td>\n <td> [[-0.00643025 0.01936718]\n [-0.02410458 0.03978052]\n [-0.01653973 -0.02096177]\n [ 0.01046864 -0.05990141]]</td> \n </tr>\n \n <tr>\n <td>**b1**</td>\n <td> [[ -1.02420756e-06]\n [ 1.27373948e-05]\n [ 8.32996807e-07]\n [ -3.20136836e-06]]</td> \n </tr>\n \n <tr>\n <td>**W2**</td>\n <td> [[-0.01041081 -0.04463285 0.01758031 0.04747113]] </td> \n </tr>\n \n\n <tr>\n <td>**b2**</td>\n <td> [[ 0.00010457]] </td> \n </tr>\n \n</table> ",
"_____no_output_____"
],
[
"### 4.4 - Integrate parts 4.1, 4.2 and 4.3 in nn_model() ####\n\n**Question**: Build your neural network model in `nn_model()`.\n\n**Instructions**: The neural network model has to use the previous functions in the right order.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: nn_model\n\ndef nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):\n \"\"\"\n Arguments:\n X -- dataset of shape (2, number of examples)\n Y -- labels of shape (1, number of examples)\n n_h -- size of the hidden layer\n num_iterations -- Number of iterations in gradient descent loop\n print_cost -- if True, print the cost every 1000 iterations\n \n Returns:\n parameters -- parameters learnt by the model. They can then be used to predict.\n \"\"\"\n \n np.random.seed(3)\n n_x = layer_sizes(X, Y)[0]\n n_y = layer_sizes(X, Y)[2]\n \n # Initialize parameters\n ### START CODE HERE ### (≈ 1 line of code)\n parameters = initialize_parameters(n_x, n_h, n_y)\n ### END CODE HERE ###\n \n # Loop (gradient descent)\n\n for i in range(0, num_iterations):\n \n ### START CODE HERE ### (≈ 4 lines of code)\n # Forward propagation. Inputs: \"X, parameters\". Outputs: \"A2, cache\".\n A2, cache = forward_propagation(X, parameters)\n \n # Cost function. Inputs: \"A2, Y, parameters\". Outputs: \"cost\".\n cost = compute_cost(A2, Y, parameters)\n \n # Backpropagation. Inputs: \"parameters, cache, X, Y\". Outputs: \"grads\".\n grads = backward_propagation(parameters, cache, X, Y)\n \n # Gradient descent parameter update. Inputs: \"parameters, grads\". Outputs: \"parameters\".\n parameters = update_parameters(parameters, grads)\n \n ### END CODE HERE ###\n \n # Print the cost every 1000 iterations\n if print_cost and i % 1000 == 0:\n print (\"Cost after iteration %i: %f\" %(i, cost))\n\n return parameters",
"_____no_output_____"
],
[
"X_assess, Y_assess = nn_model_test_case()\nparameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=True)\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"Cost after iteration 0: 0.692739\nCost after iteration 1000: 0.000218\nCost after iteration 2000: 0.000107\nCost after iteration 3000: 0.000071\nCost after iteration 4000: 0.000053\nCost after iteration 5000: 0.000042\nCost after iteration 6000: 0.000035\nCost after iteration 7000: 0.000030\nCost after iteration 8000: 0.000026\nCost after iteration 9000: 0.000023\nW1 = [[-0.65848169 1.21866811]\n [-0.76204273 1.39377573]\n [ 0.5792005 -1.10397703]\n [ 0.76773391 -1.41477129]]\nb1 = [[ 0.287592 ]\n [ 0.3511264 ]\n [-0.2431246 ]\n [-0.35772805]]\nW2 = [[-2.45566237 -3.27042274 2.00784958 3.36773273]]\nb2 = [[ 0.20459656]]\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:90%\">\n\n<tr> \n <td> \n **cost after iteration 0**\n </td>\n <td> \n 0.692739\n </td>\n</tr>\n\n<tr> \n <td> \n <center> $\\vdots$ </center>\n </td>\n <td> \n <center> $\\vdots$ </center>\n </td>\n</tr>\n\n <tr>\n <td>**W1**</td>\n <td> [[-0.65848169 1.21866811]\n [-0.76204273 1.39377573]\n [ 0.5792005 -1.10397703]\n [ 0.76773391 -1.41477129]]</td> \n </tr>\n \n <tr>\n <td>**b1**</td>\n <td> [[ 0.287592 ]\n [ 0.3511264 ]\n [-0.2431246 ]\n [-0.35772805]] </td> \n </tr>\n \n <tr>\n <td>**W2**</td>\n <td> [[-2.45566237 -3.27042274 2.00784958 3.36773273]] </td> \n </tr>\n \n\n <tr>\n <td>**b2**</td>\n <td> [[ 0.20459656]] </td> \n </tr>\n \n</table> ",
"_____no_output_____"
],
[
"### 4.5 Predictions\n\n**Question**: Use your model to predict by building predict().\nUse forward propagation to predict results.\n\n**Reminder**: predictions = $y_{prediction} = \\mathbb 1 \\text{{activation > 0.5}} = \\begin{cases}\n 1 & \\text{if}\\ activation > 0.5 \\\\\n 0 & \\text{otherwise}\n \\end{cases}$ \n \nAs an example, if you would like to set the entries of a matrix X to 0 and 1 based on a threshold you would do: ```X_new = (X > threshold)```",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: predict\n\ndef predict(parameters, X):\n \"\"\"\n Using the learned parameters, predicts a class for each example in X\n \n Arguments:\n parameters -- python dictionary containing your parameters \n X -- input data of size (n_x, m)\n \n Returns\n predictions -- vector of predictions of our model (red: 0 / blue: 1)\n \"\"\"\n \n # Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold.\n ### START CODE HERE ### (≈ 2 lines of code)\n A2, cache = forward_propagation(X, parameters)\n predictions = A2 > 0.5\n ### END CODE HERE ###\n \n return predictions",
"_____no_output_____"
],
[
"parameters, X_assess = predict_test_case()\n\npredictions = predict(parameters, X_assess)\nprint(\"predictions mean = \" + str(np.mean(predictions)))",
"predictions mean = 0.666666666667\n"
]
],
[
[
"**Expected Output**: \n\n\n<table style=\"width:40%\">\n <tr>\n <td>**predictions mean**</td>\n <td> 0.666666666667 </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"It is time to run the model and see how it performs on a planar dataset. Run the following code to test your model with a single hidden layer of $n_h$ hidden units.",
"_____no_output_____"
]
],
[
[
"# Build a model with a n_h-dimensional hidden layer\nparameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)\n\n# Plot the decision boundary\nplot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)\nplt.title(\"Decision Boundary for hidden layer size \" + str(4))",
"Cost after iteration 0: 0.693048\nCost after iteration 1000: 0.288083\nCost after iteration 2000: 0.254385\nCost after iteration 3000: 0.233864\nCost after iteration 4000: 0.226792\nCost after iteration 5000: 0.222644\nCost after iteration 6000: 0.219731\nCost after iteration 7000: 0.217504\nCost after iteration 8000: 0.219471\nCost after iteration 9000: 0.218612\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:40%\">\n <tr>\n <td>**Cost after iteration 9000**</td>\n <td> 0.218607 </td> \n </tr>\n \n</table>\n",
"_____no_output_____"
]
],
[
[
"# Print accuracy\npredictions = predict(parameters, X)\nprint ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')",
"Accuracy: 90%\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:15%\">\n <tr>\n <td>**Accuracy**</td>\n <td> 90% </td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"Accuracy is really high compared to Logistic Regression. The model has learnt the leaf patterns of the flower! Neural networks are able to learn even highly non-linear decision boundaries, unlike logistic regression. \n\nNow, let's try out several hidden layer sizes.",
"_____no_output_____"
],
[
"### 4.6 - Tuning hidden layer size (optional/ungraded exercise) ###\n\nRun the following code. It may take 1-2 minutes. You will observe different behaviors of the model for various hidden layer sizes.",
"_____no_output_____"
]
],
[
[
"# This may take about 2 minutes to run\n\nplt.figure(figsize=(16, 32))\nhidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]\nfor i, n_h in enumerate(hidden_layer_sizes):\n plt.subplot(5, 2, i+1)\n plt.title('Hidden Layer of size %d' % n_h)\n parameters = nn_model(X, Y, n_h, num_iterations = 5000)\n plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)\n predictions = predict(parameters, X)\n accuracy = float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100)\n print (\"Accuracy for {} hidden units: {} %\".format(n_h, accuracy))",
"Accuracy for 1 hidden units: 90.5 %\nAccuracy for 2 hidden units: 90.5 %\nAccuracy for 3 hidden units: 90.5 %\nAccuracy for 4 hidden units: 90.5 %\nAccuracy for 5 hidden units: 90.5 %\nAccuracy for 20 hidden units: 90.5 %\nAccuracy for 50 hidden units: 90.5 %\n"
]
],
[
[
"**Interpretation**:\n- The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models overfit the data. \n- The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits the data well without also incurring noticeable overfitting.\n- You will also learn later about regularization, which lets you use very large models (such as n_h = 50) without much overfitting. ",
"_____no_output_____"
],
[
"**Optional questions**:\n\n**Note**: Remember to submit the assignment by clicking the blue \"Submit Assignment\" button at the upper-right. \n\nSome optional/ungraded questions that you can explore if you wish: \n- What happens when you change the tanh activation for a sigmoid activation or a ReLU activation?\n- Play with the learning_rate. What happens?\n- What if we change the dataset? (See part 5 below!)",
"_____no_output_____"
],
[
"<font color='blue'>\n**You've learnt to:**\n- Build a complete neural network with a hidden layer\n- Make a good use of a non-linear unit\n- Implemented forward propagation and backpropagation, and trained a neural network\n- See the impact of varying the hidden layer size, including overfitting.",
"_____no_output_____"
],
[
"Nice work! ",
"_____no_output_____"
],
[
"## 5) Performance on other datasets",
"_____no_output_____"
],
[
"If you want, you can rerun the whole notebook (minus the dataset part) for each of the following datasets.",
"_____no_output_____"
]
],
[
[
"# Datasets\nnoisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()\n\ndatasets = {\"noisy_circles\": noisy_circles,\n \"noisy_moons\": noisy_moons,\n \"blobs\": blobs,\n \"gaussian_quantiles\": gaussian_quantiles}\n\n### START CODE HERE ### (choose your dataset)\ndataset = \"noisy_moons\"\n### END CODE HERE ###\n\nX, Y = datasets[dataset]\nX, Y = X.T, Y.reshape(1, Y.shape[0])\n\n# make blobs binary\nif dataset == \"blobs\":\n Y = Y%2\n\n# Visualize the data\nplt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);",
"_____no_output_____"
]
],
[
[
"Congrats on finishing this Programming Assignment!\n\nReference:\n- http://scs.ryerson.ca/~aharley/neural-networks/\n- http://cs231n.github.io/neural-networks-case-study/",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
eccf3618a2094ed1e7e9d94cd91df34e8dd6240d | 217,740 | ipynb | Jupyter Notebook | docs/notebooks/Coverage.ipynb | cn-fairy/fuzzingbook | 49c7194604caecc2a062cb56dcd39e093f5b103d | [
"MIT"
] | null | null | null | docs/notebooks/Coverage.ipynb | cn-fairy/fuzzingbook | 49c7194604caecc2a062cb56dcd39e093f5b103d | [
"MIT"
] | null | null | null | docs/notebooks/Coverage.ipynb | cn-fairy/fuzzingbook | 49c7194604caecc2a062cb56dcd39e093f5b103d | [
"MIT"
] | null | null | null | 42.938276 | 15,768 | 0.658969 | [
[
[
"# Code Coverage\n\nIn the [previous chapter](Fuzzer.ipynb), we introduced _basic fuzzing_ – that is, generating random inputs to test programs. How do we measure the effectiveness of these tests? One way would be to check the number (and seriousness) of bugs found; but if bugs are scarce, we need a _proxy for the likelihood of a test to uncover a bug._ In this chapter, we introduce the concept of *code coverage*, measuring which parts of a program are actually executed during a test run. Measuring such coverage is also crucial for test generators that attempt to cover as much code as possible.",
"_____no_output_____"
]
],
[
[
"from bookutils import YouTubeVideo",
"_____no_output_____"
],
[
"YouTubeVideo('2lfgI9KdARs')",
"_____no_output_____"
]
],
[
[
"**Prerequisites**\n\n* You need some understanding of how a program is executed.\n* You should have learned about basic fuzzing in the [previous chapter](Fuzzer.ipynb).",
"_____no_output_____"
],
[
"## Synopsis\n<!-- Automatically generated. Do not edit. -->\n\nTo [use the code provided in this chapter](Importing.ipynb), write\n\n```python\n>>> from fuzzingbook.Coverage import <identifier>\n```\n\nand then make use of the following features.\n\n\nThis chapter introduces a `Coverage` class allowing you to measure coverage for Python programs. Within the context of this book, we use coverage information to guide fuzzing towards uncovered locations.\n\nThe typical usage of the `Coverage` class is in conjunction with a `with` clause:\n\n```python\n>>> with Coverage() as cov:\n>>> cgi_decode(\"a+b\")\n```\nPrinting out a coverage object shows the covered functions, with covered lines prefixed as `#`:\n\n```python\n>>> print(cov)\n 1 def cgi_decode(s: str) -> str:\n 2 \"\"\"Decode the CGI-encoded string `s`:\n 3 * replace '+' by ' '\n 4 * replace \"%xx\" by the character with hex number xx.\n 5 Return the decoded string. Raise `ValueError` for invalid inputs.\"\"\"\n 6 \n 7 # Mapping of hex digits to their integer values\n# 8 hex_values = {\n# 9 '0': 0, '1': 1, '2': 2, '3': 3, '4': 4,\n# 10 '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,\n# 11 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15,\n# 12 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15,\n 13 }\n 14 \n# 15 t = \"\"\n# 16 i = 0\n# 17 while i < len(s):\n# 18 c = s[i]\n# 19 if c == '+':\n# 20 t += ' '\n# 21 elif c == '%':\n 22 digit_high, digit_low = s[i + 1], s[i + 2]\n 23 i += 2\n 24 if digit_high in hex_values and digit_low in hex_values:\n 25 v = hex_values[digit_high] * 16 + hex_values[digit_low]\n 26 t += chr(v)\n 27 else:\n 28 raise ValueError(\"Invalid encoding\")\n 29 else:\n# 30 t += c\n# 31 i += 1\n# 32 return t\n\n\n```\nThe `trace()` method returns the _trace_ – that is, the list of locations executed in order. Each location comes as a pair (`function name`, `line`).\n\n```python\n>>> cov.trace()\n[('cgi_decode', 9),\n ('cgi_decode', 10),\n ('cgi_decode', 11),\n ('cgi_decode', 12),\n ('cgi_decode', 8),\n ('cgi_decode', 15),\n ('cgi_decode', 16),\n ('cgi_decode', 17),\n ('cgi_decode', 18),\n ('cgi_decode', 19),\n ('cgi_decode', 21),\n ('cgi_decode', 30),\n ('cgi_decode', 31),\n ('cgi_decode', 17),\n ('cgi_decode', 18),\n ('cgi_decode', 19),\n ('cgi_decode', 20),\n ('cgi_decode', 31),\n ('cgi_decode', 17),\n ('cgi_decode', 18),\n ('cgi_decode', 19),\n ('cgi_decode', 21),\n ('cgi_decode', 30),\n ('cgi_decode', 31),\n ('cgi_decode', 17),\n ('cgi_decode', 32)]\n```\nThe `coverage()` method returns the _coverage_, that is, the set of locations in the trace executed at least once:\n\n```python\n>>> cov.coverage()\n{('cgi_decode', 8),\n ('cgi_decode', 9),\n ('cgi_decode', 10),\n ('cgi_decode', 11),\n ('cgi_decode', 12),\n ('cgi_decode', 15),\n ('cgi_decode', 16),\n ('cgi_decode', 17),\n ('cgi_decode', 18),\n ('cgi_decode', 19),\n ('cgi_decode', 20),\n ('cgi_decode', 21),\n ('cgi_decode', 30),\n ('cgi_decode', 31),\n ('cgi_decode', 32)}\n```\nCoverage sets can be subject to set operations, such as _intersection_ (which locations are covered in multiple executions) and _difference_ (which locations are covered in run _a_, but not _b_).\n\nThe chapter also discusses how to obtain such coverage from C programs.\n\n\n\n",
"_____no_output_____"
]
],
[
[
"import bookutils",
"_____no_output_____"
],
[
"# ignore\nfrom typing import Any, Optional, Callable, List, Type, Set, Tuple",
"_____no_output_____"
]
],
[
[
"## A CGI Decoder\n\nWe start by introducing a simple Python function that decodes a CGI-encoded string. CGI encoding is used in URLs (i.e., Web addresses) to encode characters that would be invalid in a URL, such as blanks and certain punctuation:\n\n* Blanks are replaced by `'+'`\n* Other invalid characters are replaced by '`%xx`', where `xx` is the two-digit hexadecimal equivalent.\n\nIn CGI encoding, the string `\"Hello, world!\"` would thus become `\"Hello%2c+world%21\"` where `2c` and `21` are the hexadecimal equivalents of `','` and `'!'`, respectively.\n\nThe function `cgi_decode()` takes such an encoded string and decodes it back to its original form. Our implementation replicates the code from \\cite{Pezze2008}. (It even includes its bugs – but we won't reveal them at this point.)",
"_____no_output_____"
]
],
[
[
"def cgi_decode(s: str) -> str:\n \"\"\"Decode the CGI-encoded string `s`:\n * replace '+' by ' '\n * replace \"%xx\" by the character with hex number xx.\n Return the decoded string. Raise `ValueError` for invalid inputs.\"\"\"\n\n # Mapping of hex digits to their integer values\n hex_values = {\n '0': 0, '1': 1, '2': 2, '3': 3, '4': 4,\n '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,\n 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15,\n 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15,\n }\n\n t = \"\"\n i = 0\n while i < len(s):\n c = s[i]\n if c == '+':\n t += ' '\n elif c == '%':\n digit_high, digit_low = s[i + 1], s[i + 2]\n i += 2\n if digit_high in hex_values and digit_low in hex_values:\n v = hex_values[digit_high] * 16 + hex_values[digit_low]\n t += chr(v)\n else:\n raise ValueError(\"Invalid encoding\")\n else:\n t += c\n i += 1\n return t",
"_____no_output_____"
]
],
[
[
"Here is an example of how `cgi_decode()` works:",
"_____no_output_____"
]
],
[
[
"cgi_decode(\"Hello+world\")",
"_____no_output_____"
]
],
[
[
"If we want to systematically test `cgi_decode()`, how would we proceed?",
"_____no_output_____"
],
[
"The testing literature distinguishes two ways of deriving tests: _Black-box testing_ and _White-box testing._",
"_____no_output_____"
],
[
"## Black-Box Testing\n\nThe idea of *black-box testing* is to derive tests from the _specification_. In the above case, we thus would have to test `cgi_decode()` by the features specified and documented, including\n\n* testing for correct replacement of `'+'`;\n* testing for correct replacement of `\"%xx\"`;\n* testing for non-replacement of other characters; and\n* testing for recognition of illegal inputs.\n\nHere are four assertions (tests) that cover these four features. We can see that they all pass:",
"_____no_output_____"
]
],
[
[
"assert cgi_decode('+') == ' '\nassert cgi_decode('%20') == ' '\nassert cgi_decode('abc') == 'abc'\n\ntry:\n cgi_decode('%?a')\n assert False\nexcept ValueError:\n pass",
"_____no_output_____"
]
],
[
[
"The advantage of black-box testing is that it finds errors in the _specified_ behavior. It is independent from a given implementation, and thus allows to create test even before implementation. The downside is that _implemented_ behavior typically covers more ground than _specified_ behavior, and thus tests based on specification alone typically do not cover all implementation details.",
"_____no_output_____"
],
[
"## White-Box Testing\n\nIn contrast to black-box testing, *white-box testing* derives tests from the _implementation_, notably the internal structure. White-Box testing is closely tied to the concept of _covering_ structural features of the code. If a statement in the code is not executed during testing, for instance, this means that an error in this statement cannot be triggered either. White-Box testing thus introduces a number of *coverage criteria* that have to be fulfilled before the test can be said to be sufficient. The most frequently used coverage criteria are\n\n* *Statement coverage* – each statement in the code must be executed by at least one test input.\n* *Branch coverage* – each branch in the code must be taken by at least one test input. (This translates to each `if` and `while` decision once being true, and once being false.)\n\nBesides these, there are far more coverage criteria, including sequences of branches taken, loop iterations taken (zero, one, many), data flows between variable definitions and usages, and many more; \\cite{Pezze2008} has a great overview.",
"_____no_output_____"
],
[
"Let us consider `cgi_decode()`, above, and reason what we have to do such that each statement of the code is executed at least once. We'd have to cover\n\n* The block following `if c == '+'`\n* The two blocks following `if c == '%'` (one for valid input, one for invalid)\n* The final `else` case for all other characters.\n\nThis results in the same conditions as with black-box testing, above; again, the assertions above indeed would cover every statement in the code. Such a correspondence is actually pretty common, since programmers tend to implement different behaviors in different code locations; and thus, covering these locations will lead to test cases that cover the different (specified) behaviors.\n\nThe advantage of white-box testing is that it finds errors in _implemented_ behavior. It can be conducted even in cases where the specification does not provide sufficient details; actually, it helps in identifying (and thus specifying) corner cases in the specification. The downside is that it may miss _non-implemented_ behavior: If some specified functionality is missing, white-box testing will not find it.",
"_____no_output_____"
],
[
"## Tracing Executions\n\nOne nice feature of white-box testing is that one can actually automatically assess whether some program feature was covered. To this end, one _instruments_ the execution of the program such that during execution, a special functionality keeps track of which code was executed. After testing, this information can be passed to the programmer, who can then focus on writing tests that cover the yet uncovered code.",
"_____no_output_____"
],
[
"In most programming languages, it is rather difficult to set up programs such that one can trace their execution. Not so in Python. The function `sys.settrace(f)` allows to define a *tracing function* `f()` that is called for each and every line executed. Even better, it gets access to the current function and its name, current variable contents, and more. It is thus an ideal tool for *dynamic analysis* – that is, the analysis of what actually happens during an execution.",
"_____no_output_____"
],
[
"To illustrate how this works, let us again look into a specific execution of `cgi_decode()`.",
"_____no_output_____"
]
],
[
[
"cgi_decode(\"a+b\")",
"_____no_output_____"
]
],
[
[
"To track how the execution proceeds through `cgi_decode()`, we make use of `sys.settrace()`. First, we define the _tracing function_ that will be called for each line. It has three parameters: \n\n* The `frame` parameter gets you the current _frame_, allowing access to the current location and variables:\n * `frame.f_code` is the currently executed code with `frame.f_code.co_name` being the function name;\n * `frame.f_lineno` holds the current line number; and\n * `frame.f_locals` holds the current local variables and arguments.\n* The `event` parameter is a string with values including `\"line\"` (a new line has been reached) or `\"call\"` (a function is being called).\n* The `arg` parameter is an additional _argument_ for some events; for `\"return\"` events, for instance, `arg` holds the value being returned.",
"_____no_output_____"
],
[
"We use the tracing function for simply reporting the current line executed, which we access through the `frame` argument.",
"_____no_output_____"
]
],
[
[
"from types import FrameType, TracebackType",
"_____no_output_____"
],
[
"coverage = []",
"_____no_output_____"
],
[
"def traceit(frame: FrameType, event: str, arg: Any) -> Optional[Callable]:\n \"\"\"Trace program execution. To be passed to sys.settrace().\"\"\"\n if event == 'line':\n global coverage\n function_name = frame.f_code.co_name\n lineno = frame.f_lineno\n coverage.append(lineno)\n\n return traceit",
"_____no_output_____"
]
],
[
[
"We can switch tracing on and off with `sys.settrace()`:",
"_____no_output_____"
]
],
[
[
"import sys",
"_____no_output_____"
],
[
"def cgi_decode_traced(s: str) -> None:\n global coverage\n coverage = []\n sys.settrace(traceit) # Turn on\n cgi_decode(s)\n sys.settrace(None) # Turn off",
"_____no_output_____"
]
],
[
[
"When we compute `cgi_decode(\"a+b\")`, we can now see how the execution progresses through `cgi_decode()`. After the initialization of `hex_values`, `t`, and `i`, we see that the `while` loop is taken three times – one for every character in the input.",
"_____no_output_____"
]
],
[
[
"cgi_decode_traced(\"a+b\")\nprint(coverage)",
"[9, 10, 11, 12, 8, 15, 16, 17, 18, 19, 21, 30, 31, 17, 18, 19, 20, 31, 17, 18, 19, 21, 30, 31, 17, 32]\n"
]
],
[
[
"Which lines are these, actually? To this end, we get the source code of `cgi_decode_code` and encode it into an array `cgi_decode_lines`, which we will then annotate with coverage information. First, let us get the source code of `cgi_encode`:",
"_____no_output_____"
]
],
[
[
"import inspect",
"_____no_output_____"
],
[
"cgi_decode_code = inspect.getsource(cgi_decode)",
"_____no_output_____"
]
],
[
[
"`cgi_decode_code` is a string holding the source code. We can print it out with Python syntax highlighting:",
"_____no_output_____"
]
],
[
[
"from bookutils import print_content, print_file",
"_____no_output_____"
],
[
"print_content(cgi_decode_code[:300] + \"...\", \".py\")",
"\u001b[34mdef\u001b[39;49;00m \u001b[32mcgi_decode\u001b[39;49;00m(s: \u001b[36mstr\u001b[39;49;00m) -> \u001b[36mstr\u001b[39;49;00m:\n \u001b[33m\"\"\"Decode the CGI-encoded string `s`:\u001b[39;49;00m\n\u001b[33m * replace '+' by ' '\u001b[39;49;00m\n\u001b[33m * replace \"%xx\" by the character with hex number xx.\u001b[39;49;00m\n\u001b[33m Return the decoded string. Raise `ValueError` for invalid inputs.\"\"\"\u001b[39;49;00m\n\n \u001b[37m# Mapping of hex digits to their integer values\u001b[39;49;00m\n hex_v..."
]
],
[
[
"Using `splitlines()`, we split the code into an array of lines, indexed by line number.",
"_____no_output_____"
]
],
[
[
"cgi_decode_lines = [\"\"] + cgi_decode_code.splitlines()",
"_____no_output_____"
]
],
[
[
"`cgi_decode_lines[L]` is line L of the source code.",
"_____no_output_____"
]
],
[
[
"cgi_decode_lines[1]",
"_____no_output_____"
]
],
[
[
"We see that the first line (9) executed is actually the initialization of `hex_values`...",
"_____no_output_____"
]
],
[
[
"cgi_decode_lines[9:13]",
"_____no_output_____"
]
],
[
[
"... followed by the initialization of `t`:",
"_____no_output_____"
]
],
[
[
"cgi_decode_lines[15]",
"_____no_output_____"
]
],
[
[
"To see which lines actually have been covered at least once, we can convert `coverage` into a set:",
"_____no_output_____"
]
],
[
[
"covered_lines = set(coverage)\nprint(covered_lines)",
"{32, 8, 9, 10, 11, 12, 15, 16, 17, 18, 19, 20, 21, 30, 31}\n"
]
],
[
[
"Let us print out the full code, annotating lines not covered with '#':",
"_____no_output_____"
]
],
[
[
"for lineno in range(1, len(cgi_decode_lines)):\n if lineno not in covered_lines:\n print(\"# \", end=\"\")\n else:\n print(\" \", end=\"\")\n print(\"%2d \" % lineno, end=\"\")\n print_content(cgi_decode_lines[lineno], '.py')\n print()",
"# 1 \u001b[34mdef\u001b[39;49;00m \u001b[32mcgi_decode\u001b[39;49;00m(s: \u001b[36mstr\u001b[39;49;00m) -> \u001b[36mstr\u001b[39;49;00m:\n# 2 \u001b[33m\"\"\"\u001b[39;49;00m\u001b[33mDecode the CGI-encoded string `s`:\u001b[39;49;00m\u001b[33m\u001b[39;49;00m\n# 3 * replace \u001b[33m'\u001b[39;49;00m\u001b[33m+\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m by \u001b[33m'\u001b[39;49;00m\u001b[33m \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m\n# 4 * replace \u001b[33m\"\u001b[39;49;00m\u001b[33m%x\u001b[39;49;00m\u001b[33mx\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m by the character \u001b[34mwith\u001b[39;49;00m \u001b[36mhex\u001b[39;49;00m number xx.\n# 5 Return the decoded string. Raise \u001b[04m\u001b[91m`\u001b[39;49;00m\u001b[36mValueError\u001b[39;49;00m\u001b[04m\u001b[91m`\u001b[39;49;00m \u001b[34mfor\u001b[39;49;00m invalid inputs.\u001b[33m\"\"\"\u001b[39;49;00m\u001b[33m\u001b[39;49;00m\n# 6 \n# 7 \u001b[37m# Mapping of hex digits to their integer values\u001b[39;49;00m\n 8 hex_values = {\n 9 \u001b[33m'\u001b[39;49;00m\u001b[33m0\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m0\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33m1\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m1\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33m2\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m2\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33m3\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m3\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33m4\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m4\u001b[39;49;00m,\n 10 \u001b[33m'\u001b[39;49;00m\u001b[33m5\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m5\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33m6\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m6\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33m7\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m7\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33m8\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m8\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33m9\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m9\u001b[39;49;00m,\n 11 \u001b[33m'\u001b[39;49;00m\u001b[33ma\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m10\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33mb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m11\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33mc\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m12\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33md\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m13\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33me\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m14\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33mf\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m15\u001b[39;49;00m,\n 12 \u001b[33m'\u001b[39;49;00m\u001b[33mA\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m10\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33mB\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m11\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33mC\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m12\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33mD\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m13\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33mE\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m14\u001b[39;49;00m, \u001b[33m'\u001b[39;49;00m\u001b[33mF\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m: \u001b[34m15\u001b[39;49;00m,\n# 13 }\n# 14 \n 15 t = \u001b[33m\"\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\n 16 i = \u001b[34m0\u001b[39;49;00m\n 17 \u001b[34mwhile\u001b[39;49;00m i < \u001b[36mlen\u001b[39;49;00m(s):\n 18 c = s[i]\n 19 \u001b[34mif\u001b[39;49;00m c == \u001b[33m'\u001b[39;49;00m\u001b[33m+\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m:\n 20 t += \u001b[33m'\u001b[39;49;00m\u001b[33m \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m\n 21 \u001b[34melif\u001b[39;49;00m c == \u001b[33m'\u001b[39;49;00m\u001b[33m%\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m:\n# 22 digit_high, digit_low = s[i + \u001b[34m1\u001b[39;49;00m], s[i + \u001b[34m2\u001b[39;49;00m]\n# 23 i += \u001b[34m2\u001b[39;49;00m\n# 24 \u001b[34mif\u001b[39;49;00m digit_high \u001b[35min\u001b[39;49;00m hex_values \u001b[35mand\u001b[39;49;00m digit_low \u001b[35min\u001b[39;49;00m hex_values:\n# 25 v = hex_values[digit_high] * \u001b[34m16\u001b[39;49;00m + hex_values[digit_low]\n# 26 t += \u001b[36mchr\u001b[39;49;00m(v)\n# 27 \u001b[34melse\u001b[39;49;00m:\n# 28 \u001b[34mraise\u001b[39;49;00m \u001b[36mValueError\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mInvalid encoding\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n# 29 \u001b[34melse\u001b[39;49;00m:\n 30 t += c\n 31 i += \u001b[34m1\u001b[39;49;00m\n 32 \u001b[34mreturn\u001b[39;49;00m t\n"
]
],
[
[
"We see that a number of lines (notably comments) have not been executed, simply because they are not executable. However, we also see that the lines under `if c == '%'` have _not_ been executed yet. If `\"a+b\"` were our only test case so far, this missing coverage would now encourage us to create another test case that actually covers these lines.",
"_____no_output_____"
],
[
"## A Coverage Class\n\nIn this book, we will make use of coverage again and again – to _measure_ the effectiveness of different test generation techniques, but also to _guide_ test generation towards code coverage. Our previous implementation with a global `coverage` variable is a bit cumbersome for that. We therefore implement some functionality that will help us measuring coverage easily.",
"_____no_output_____"
],
[
"The key idea of getting coverage is to make use of the Python `with` statement. The general form\n\n```python\nwith OBJECT [as VARIABLE]:\n BODY\n```\n\nexecutes `BODY` with `OBJECT` being defined (and stored in `VARIABLE`). The interesting thing is that at the beginning and end of `BODY`, the special methods `OBJECT.__enter__()` and `OBJECT.__exit__()` are automatically invoked; even if `BODY` raises an exception. This allows us to define a `Coverage` object where `Coverage.__enter__()` automatically turns on tracing and `Coverage.__exit__()` automatically turns off tracing again. After tracing, we can make use of special methods to access the coverage. This is what this looks like during usage:\n\n```python\nwith Coverage() as cov:\n function_to_be_traced()\nc = cov.coverage()\n```\n\nHere, tracing is automatically turned on during `function_to_be_traced()` and turned off again after the `with` block; afterwards, we can access the set of lines executed.",
"_____no_output_____"
],
[
"Here's the full implementation with all its bells and whistles. You don't have to get everything; it suffices that you know how to use it:",
"_____no_output_____"
]
],
[
[
"Location = Tuple[str, int]",
"_____no_output_____"
],
[
"class Coverage:\n \"\"\"Track coverage within a `with` block. Use as\n ```\n with Coverage() as cov:\n function_to_be_traced()\n c = cov.coverage()\n ```\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Constructor\"\"\"\n self._trace: List[Location] = []\n\n # Trace function\n def traceit(self, frame: FrameType, event: str, arg: Any) -> Optional[Callable]:\n \"\"\"Tracing function. To be overloaded in subclasses.\"\"\"\n if self.original_trace_function is not None:\n self.original_trace_function(frame, event, arg)\n\n if event == \"line\":\n function_name = frame.f_code.co_name\n lineno = frame.f_lineno\n if function_name != '__exit__': # avoid tracing ourselves:\n self._trace.append((function_name, lineno))\n\n return self.traceit\n\n def __enter__(self) -> Any:\n \"\"\"Start of `with` block. Turn on tracing.\"\"\"\n self.original_trace_function = sys.gettrace()\n sys.settrace(self.traceit)\n return self\n\n def __exit__(self, exc_type: Type, exc_value: BaseException, \n tb: TracebackType) -> Optional[bool]:\n \"\"\"End of `with` block. Turn off tracing.\"\"\"\n sys.settrace(self.original_trace_function)\n return None # default: pass all exceptions\n\n def trace(self) -> List[Location]:\n \"\"\"The list of executed lines, as (function_name, line_number) pairs\"\"\"\n return self._trace\n\n def coverage(self) -> Set[Location]:\n \"\"\"The set of executed lines, as (function_name, line_number) pairs\"\"\"\n return set(self.trace())\n\n def function_names(self) -> Set[str]:\n \"\"\"The set of function names seen\"\"\"\n return set(function_name for (function_name, line_number) in self.coverage())\n\n def __repr__(self) -> str:\n \"\"\"Return a string representation of this object.\n Show covered (and uncovered) program code\"\"\"\n t = \"\"\n for function_name in self.function_names():\n # Similar code as in the example above\n try:\n fun = eval(function_name)\n except Exception as exc:\n t += f\"Skipping {function_name}: {exc}\"\n continue\n\n source_lines, start_line_number = inspect.getsourcelines(fun)\n for lineno in range(start_line_number, start_line_number + len(source_lines)):\n if (function_name, lineno) in self.trace():\n t += \"# \"\n else:\n t += \" \"\n t += \"%2d \" % lineno\n t += source_lines[lineno - start_line_number]\n\n return t",
"_____no_output_____"
]
],
[
[
"Let us put this to use:",
"_____no_output_____"
]
],
[
[
"with Coverage() as cov:\n cgi_decode(\"a+b\")\n\nprint(cov.coverage())",
"{('cgi_decode', 11), ('cgi_decode', 17), ('cgi_decode', 30), ('cgi_decode', 20), ('cgi_decode', 10), ('cgi_decode', 19), ('cgi_decode', 32), ('cgi_decode', 16), ('cgi_decode', 12), ('cgi_decode', 9), ('cgi_decode', 15), ('cgi_decode', 31), ('cgi_decode', 18), ('cgi_decode', 8), ('cgi_decode', 21)}\n"
]
],
[
[
"As you can see, the `Coverage()` class not only keeps track of lines executed, but also of function names. This is useful if you have a program that spans multiple files.",
"_____no_output_____"
],
[
"For interactive use, we can simply print the coverage object, and obtain a listing of the code, with covered lines marked as `#`.",
"_____no_output_____"
]
],
[
[
"print(cov)",
" 1 def cgi_decode(s: str) -> str:\n 2 \"\"\"Decode the CGI-encoded string `s`:\n 3 * replace '+' by ' '\n 4 * replace \"%xx\" by the character with hex number xx.\n 5 Return the decoded string. Raise `ValueError` for invalid inputs.\"\"\"\n 6 \n 7 # Mapping of hex digits to their integer values\n# 8 hex_values = {\n# 9 '0': 0, '1': 1, '2': 2, '3': 3, '4': 4,\n# 10 '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,\n# 11 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15,\n# 12 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15,\n 13 }\n 14 \n# 15 t = \"\"\n# 16 i = 0\n# 17 while i < len(s):\n# 18 c = s[i]\n# 19 if c == '+':\n# 20 t += ' '\n# 21 elif c == '%':\n 22 digit_high, digit_low = s[i + 1], s[i + 2]\n 23 i += 2\n 24 if digit_high in hex_values and digit_low in hex_values:\n 25 v = hex_values[digit_high] * 16 + hex_values[digit_low]\n 26 t += chr(v)\n 27 else:\n 28 raise ValueError(\"Invalid encoding\")\n 29 else:\n# 30 t += c\n# 31 i += 1\n# 32 return t\n\n"
]
],
[
[
"## Comparing Coverage\n\nSince we represent coverage as a set of executed lines, we can also apply _set operations_ on these. For instance, we can find out which lines are covered by individual test cases, but not others:",
"_____no_output_____"
]
],
[
[
"with Coverage() as cov_plus:\n cgi_decode(\"a+b\")\nwith Coverage() as cov_standard:\n cgi_decode(\"abc\")\n\ncov_plus.coverage() - cov_standard.coverage()",
"_____no_output_____"
]
],
[
[
"This is the single line in the code that is executed only in the `'a+b'` input.",
"_____no_output_____"
],
[
"We can also compare sets to find out which lines still need to be covered. Let us define `cov_max` as the maximum coverage we can achieve. (Here, we do this by executing the \"good\" test cases we already have. In practice, one would statically analyze code structure, which we introduce in [the chapter on symbolic testing](SymbolicFuzzer.ipynb).)",
"_____no_output_____"
]
],
[
[
"with Coverage() as cov_max:\n cgi_decode('+')\n cgi_decode('%20')\n cgi_decode('abc')\n try:\n cgi_decode('%?a')\n except Exception:\n pass",
"_____no_output_____"
]
],
[
[
"Then, we can easily see which lines are _not_ yet covered by a test case:",
"_____no_output_____"
]
],
[
[
"cov_max.coverage() - cov_plus.coverage()",
"_____no_output_____"
]
],
[
[
"Again, these would be the lines handling `\"%xx\"`, which we have not yet had in the input.",
"_____no_output_____"
],
[
"## Coverage of Basic Fuzzing\n\nWe can now use our coverage tracing to assess the _effectiveness_ of testing methods – in particular, of course, test _generation_ methods. Our challenge is to achieve maximum coverage in `cgi_decode()` just with random inputs. In principle, we should _eventually_ get there, as eventually, we will have produced every possible string in the universe – but exactly how long is this? To this end, let us run just one fuzzing iteration on `cgi_decode()`:",
"_____no_output_____"
]
],
[
[
"from Fuzzer import fuzzer",
"_____no_output_____"
],
[
"sample = fuzzer()\nsample",
"_____no_output_____"
]
],
[
[
"Here's the invocation and the coverage we achieve. We wrap `cgi_decode()` in a `try...except` block such that we can ignore `ValueError` exceptions raised by illegal `%xx` formats.",
"_____no_output_____"
]
],
[
[
"with Coverage() as cov_fuzz:\n try:\n cgi_decode(sample)\n except:\n pass\ncov_fuzz.coverage()",
"_____no_output_____"
]
],
[
[
"Is this already the maximum coverage? Apparently, there are still lines missing:",
"_____no_output_____"
]
],
[
[
"cov_max.coverage() - cov_fuzz.coverage()",
"_____no_output_____"
]
],
[
[
"Let us try again, increasing coverage over 100 random inputs. We use an array `cumulative_coverage` to store the coverage achieved over time; `cumulative_coverage[0]` is the total number of lines covered after input 1, \n`cumulative_coverage[1]` is the number of lines covered after inputs 1–2, and so on.",
"_____no_output_____"
]
],
[
[
"trials = 100",
"_____no_output_____"
],
[
"def population_coverage(population: List[str], function: Callable) \\\n -> Tuple[Set[Location], List[int]]:\n cumulative_coverage: List[int] = []\n all_coverage: Set[Location] = set()\n\n for s in population:\n with Coverage() as cov:\n try:\n function(s)\n except:\n pass\n all_coverage |= cov.coverage()\n cumulative_coverage.append(len(all_coverage))\n\n return all_coverage, cumulative_coverage",
"_____no_output_____"
]
],
[
[
"Let us create a hundred inputs to determine how coverage increases:",
"_____no_output_____"
]
],
[
[
"def hundred_inputs() -> List[str]:\n population = []\n for i in range(trials):\n population.append(fuzzer())\n return population",
"_____no_output_____"
]
],
[
[
"Here's how the coverage increases with each input:",
"_____no_output_____"
]
],
[
[
"all_coverage, cumulative_coverage = \\\n population_coverage(hundred_inputs(), cgi_decode)",
"_____no_output_____"
],
[
"%matplotlib inline",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt # type: ignore",
"_____no_output_____"
],
[
"plt.plot(cumulative_coverage)\nplt.title('Coverage of cgi_decode() with random inputs')\nplt.xlabel('# of inputs')\nplt.ylabel('lines covered')",
"_____no_output_____"
]
],
[
[
"This is just _one_ run, of course; so let's repeat this a number of times and plot the averages.",
"_____no_output_____"
]
],
[
[
"runs = 100\n\n# Create an array with TRIALS elements, all zero\nsum_coverage = [0] * trials\n\nfor run in range(runs):\n all_coverage, coverage = population_coverage(hundred_inputs(), cgi_decode)\n assert len(coverage) == trials\n for i in range(trials):\n sum_coverage[i] += coverage[i]\n\naverage_coverage = []\nfor i in range(trials):\n average_coverage.append(sum_coverage[i] / runs)",
"_____no_output_____"
],
[
"plt.plot(average_coverage)\nplt.title('Average coverage of cgi_decode() with random inputs')\nplt.xlabel('# of inputs')\nplt.ylabel('lines covered')",
"_____no_output_____"
]
],
[
[
"We see that on average, we get full coverage after 40–60 fuzzing inputs.",
"_____no_output_____"
],
[
"## Getting Coverage from External Programs\n\nOf course, not all the world is programming in Python. The good news is that the problem of obtaining coverage is ubiquitous, and almost every programming language has some facility to measure coverage. Just as an example, let us therefore demonstrate how to obtain coverage for a C program.",
"_____no_output_____"
],
[
"Our C program (again) implements `cgi_decode`; this time as a program to be executed from the command line:\n\n```shell\n$ ./cgi_decode 'Hello+World'\nHello World\n```",
"_____no_output_____"
],
[
"Here comes the C code, first as a Python string. We start with the usual C includes:",
"_____no_output_____"
]
],
[
[
"cgi_c_code = \"\"\"\n/* CGI decoding as C program */\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\n\"\"\"",
"_____no_output_____"
]
],
[
[
"Here comes the initialization of `hex_values`:",
"_____no_output_____"
]
],
[
[
"cgi_c_code += r\"\"\"\nint hex_values[256];\n\nvoid init_hex_values() {\n for (int i = 0; i < sizeof(hex_values) / sizeof(int); i++) {\n hex_values[i] = -1;\n }\n hex_values['0'] = 0; hex_values['1'] = 1; hex_values['2'] = 2; hex_values['3'] = 3;\n hex_values['4'] = 4; hex_values['5'] = 5; hex_values['6'] = 6; hex_values['7'] = 7;\n hex_values['8'] = 8; hex_values['9'] = 9;\n\n hex_values['a'] = 10; hex_values['b'] = 11; hex_values['c'] = 12; hex_values['d'] = 13;\n hex_values['e'] = 14; hex_values['f'] = 15;\n\n hex_values['A'] = 10; hex_values['B'] = 11; hex_values['C'] = 12; hex_values['D'] = 13;\n hex_values['E'] = 14; hex_values['F'] = 15;\n}\n\"\"\"",
"_____no_output_____"
]
],
[
[
"Here's the actual implementation of `cgi_decode()`, using pointers for input source (`s`) and output target (`t`):",
"_____no_output_____"
]
],
[
[
"cgi_c_code += r\"\"\"\nint cgi_decode(char *s, char *t) {\n while (*s != '\\0') {\n if (*s == '+')\n *t++ = ' ';\n else if (*s == '%') {\n int digit_high = *++s;\n int digit_low = *++s;\n if (hex_values[digit_high] >= 0 && hex_values[digit_low] >= 0) {\n *t++ = hex_values[digit_high] * 16 + hex_values[digit_low];\n }\n else\n return -1;\n }\n else\n *t++ = *s;\n s++;\n }\n *t = '\\0';\n return 0;\n}\n\"\"\"",
"_____no_output_____"
]
],
[
[
"Finally, here's a driver which takes the first argument and invokes `cgi_decode` with it:",
"_____no_output_____"
]
],
[
[
"cgi_c_code += r\"\"\"\nint main(int argc, char *argv[]) {\n init_hex_values();\n\n if (argc >= 2) {\n char *s = argv[1];\n char *t = malloc(strlen(s) + 1); /* output is at most as long as input */\n int ret = cgi_decode(s, t);\n printf(\"%s\\n\", t);\n return ret;\n }\n else\n {\n printf(\"cgi_decode: usage: cgi_decode STRING\\n\");\n return 1;\n }\n}\n\"\"\"",
"_____no_output_____"
]
],
[
[
"Let us create the C source code: (Note that the following commands will overwrite the file `cgi_decode.c`, if it already exists in the current working directory. Be aware of this, if you downloaded the notebooks and are working locally.)",
"_____no_output_____"
]
],
[
[
"with open(\"cgi_decode.c\", \"w\") as f:\n f.write(cgi_c_code)",
"_____no_output_____"
]
],
[
[
"And here we have the C code with its syntax highlighted:",
"_____no_output_____"
]
],
[
[
"from bookutils import print_file",
"_____no_output_____"
],
[
"print_file(\"cgi_decode.c\")",
"\u001b[37m/* CGI decoding as C program */\u001b[39;49;00m\u001b[37m\u001b[39;49;00m\n\u001b[37m\u001b[39;49;00m\n\u001b[36m#\u001b[39;49;00m\u001b[36minclude\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[37m<stdlib.h>\u001b[39;49;00m\u001b[36m\u001b[39;49;00m\n\u001b[36m#\u001b[39;49;00m\u001b[36minclude\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[37m<string.h>\u001b[39;49;00m\u001b[36m\u001b[39;49;00m\n\u001b[36m#\u001b[39;49;00m\u001b[36minclude\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[37m<stdio.h>\u001b[39;49;00m\u001b[36m\u001b[39;49;00m\n\u001b[37m\u001b[39;49;00m\n\u001b[37m\u001b[39;49;00m\n\u001b[36mint\u001b[39;49;00m\u001b[37m \u001b[39;49;00mhex_values[\u001b[34m256\u001b[39;49;00m];\u001b[37m\u001b[39;49;00m\n\u001b[37m\u001b[39;49;00m\n\u001b[36mvoid\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[32minit_hex_values\u001b[39;49;00m()\u001b[37m \u001b[39;49;00m{\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34mfor\u001b[39;49;00m\u001b[37m \u001b[39;49;00m(\u001b[36mint\u001b[39;49;00m\u001b[37m \u001b[39;49;00mi\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m0\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mi\u001b[37m \u001b[39;49;00m<\u001b[37m \u001b[39;49;00m\u001b[34msizeof\u001b[39;49;00m(hex_values)\u001b[37m \u001b[39;49;00m/\u001b[37m \u001b[39;49;00m\u001b[34msizeof\u001b[39;49;00m(\u001b[36mint\u001b[39;49;00m);\u001b[37m \u001b[39;49;00mi++)\u001b[37m \u001b[39;49;00m{\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mhex_values[i]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m-1\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m}\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m0\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m0\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m1\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m1\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m2\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m2\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m3\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m3\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m4\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m4\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m5\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m5\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m6\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m6\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m7\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m7\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m8\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m8\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33m9\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m9\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33ma\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m10\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33mb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m11\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33mc\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m12\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33md\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m13\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33me\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m14\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33mf\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m15\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33mA\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m10\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33mB\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m11\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33mC\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m12\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33mD\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m13\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33mE\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m14\u001b[39;49;00m;\u001b[37m \u001b[39;49;00mhex_values[\u001b[33m'\u001b[39;49;00m\u001b[33mF\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m]\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[34m15\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n}\u001b[37m\u001b[39;49;00m\n\u001b[37m\u001b[39;49;00m\n\u001b[36mint\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[32mcgi_decode\u001b[39;49;00m(\u001b[36mchar\u001b[39;49;00m\u001b[37m \u001b[39;49;00m*s,\u001b[37m \u001b[39;49;00m\u001b[36mchar\u001b[39;49;00m\u001b[37m \u001b[39;49;00m*t)\u001b[37m \u001b[39;49;00m{\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34mwhile\u001b[39;49;00m\u001b[37m \u001b[39;49;00m(*s\u001b[37m \u001b[39;49;00m!=\u001b[37m \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m\u001b[33m\\0\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\u001b[37m \u001b[39;49;00m{\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34mif\u001b[39;49;00m\u001b[37m \u001b[39;49;00m(*s\u001b[37m \u001b[39;49;00m==\u001b[37m \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m\u001b[33m+\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m*t++\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m\u001b[33m \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34melse\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[34mif\u001b[39;49;00m\u001b[37m \u001b[39;49;00m(*s\u001b[37m \u001b[39;49;00m==\u001b[37m \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m\u001b[33m%\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\u001b[37m \u001b[39;49;00m{\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[36mint\u001b[39;49;00m\u001b[37m \u001b[39;49;00mdigit_high\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m*++s;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[36mint\u001b[39;49;00m\u001b[37m \u001b[39;49;00mdigit_low\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m*++s;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34mif\u001b[39;49;00m\u001b[37m \u001b[39;49;00m(hex_values[digit_high]\u001b[37m \u001b[39;49;00m>=\u001b[37m \u001b[39;49;00m\u001b[34m0\u001b[39;49;00m\u001b[37m \u001b[39;49;00m&&\u001b[37m \u001b[39;49;00mhex_values[digit_low]\u001b[37m \u001b[39;49;00m>=\u001b[37m \u001b[39;49;00m\u001b[34m0\u001b[39;49;00m)\u001b[37m \u001b[39;49;00m{\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m*t++\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00mhex_values[digit_high]\u001b[37m \u001b[39;49;00m*\u001b[37m \u001b[39;49;00m\u001b[34m16\u001b[39;49;00m\u001b[37m \u001b[39;49;00m+\u001b[37m \u001b[39;49;00mhex_values[digit_low];\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m}\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34melse\u001b[39;49;00m\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34mreturn\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[34m-1\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m}\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34melse\u001b[39;49;00m\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m*t++\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m*s;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00ms++;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m}\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m*t\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m\u001b[33m\\0\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34mreturn\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[34m0\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n}\u001b[37m\u001b[39;49;00m\n\u001b[37m\u001b[39;49;00m\n\u001b[36mint\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[32mmain\u001b[39;49;00m(\u001b[36mint\u001b[39;49;00m\u001b[37m \u001b[39;49;00margc,\u001b[37m \u001b[39;49;00m\u001b[36mchar\u001b[39;49;00m\u001b[37m \u001b[39;49;00m*argv[])\u001b[37m \u001b[39;49;00m{\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00minit_hex_values();\u001b[37m\u001b[39;49;00m\n\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34mif\u001b[39;49;00m\u001b[37m \u001b[39;49;00m(argc\u001b[37m \u001b[39;49;00m>=\u001b[37m \u001b[39;49;00m\u001b[34m2\u001b[39;49;00m)\u001b[37m \u001b[39;49;00m{\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[36mchar\u001b[39;49;00m\u001b[37m \u001b[39;49;00m*s\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00margv[\u001b[34m1\u001b[39;49;00m];\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[36mchar\u001b[39;49;00m\u001b[37m \u001b[39;49;00m*t\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00mmalloc(strlen(s)\u001b[37m \u001b[39;49;00m+\u001b[37m \u001b[39;49;00m\u001b[34m1\u001b[39;49;00m);\u001b[37m \u001b[39;49;00m\u001b[37m/* output is at most as long as input */\u001b[39;49;00m\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[36mint\u001b[39;49;00m\u001b[37m \u001b[39;49;00mret\u001b[37m \u001b[39;49;00m=\u001b[37m \u001b[39;49;00mcgi_decode(s,\u001b[37m \u001b[39;49;00mt);\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mprintf(\u001b[33m\"\u001b[39;49;00m\u001b[33m%s\u001b[39;49;00m\u001b[33m\\n\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\u001b[37m \u001b[39;49;00mt);\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34mreturn\u001b[39;49;00m\u001b[37m \u001b[39;49;00mret;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m}\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34melse\u001b[39;49;00m\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m{\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00mprintf(\u001b[33m\"\u001b[39;49;00m\u001b[33mcgi_decode: usage: cgi_decode STRING\u001b[39;49;00m\u001b[33m\\n\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m);\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m\u001b[34mreturn\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[34m1\u001b[39;49;00m;\u001b[37m\u001b[39;49;00m\n\u001b[37m \u001b[39;49;00m}\u001b[37m\u001b[39;49;00m\n}\u001b[37m\u001b[39;49;00m"
]
],
[
[
"We can now compile the C code into an executable. The `--coverage` option instructs the C compiler to instrument the code such that at runtime, coverage information will be collected. (The exact options vary from compiler to compiler.)",
"_____no_output_____"
]
],
[
[
"!cc --coverage -o cgi_decode cgi_decode.c",
"_____no_output_____"
]
],
[
[
"When we now execute the program, coverage information will automatically be collected and stored in auxiliary files:",
"_____no_output_____"
]
],
[
[
"!./cgi_decode 'Send+mail+to+me%40fuzzingbook.org'",
"Send mail to [email protected]\r\n"
]
],
[
[
"The coverage information is collected by the `gcov` program. For every source file given, it produces a new `.gcov` file with coverage information.",
"_____no_output_____"
]
],
[
[
"!gcov cgi_decode.c",
"File 'cgi_decode.c'\r\nLines executed:92.50% of 40\r\nCreating 'cgi_decode.c.gcov'\r\n\r\n"
]
],
[
[
"In the `.gcov` file, each line is prefixed with the number of times it was called (`-` stands for a non-executable line, `#####` stands for zero) as well as the line number. We can take a look at `cgi_decode()`, for instance, and see that the only code not executed yet is the `return -1` for an illegal input.",
"_____no_output_____"
]
],
[
[
"lines = open('cgi_decode.c.gcov').readlines()\nfor i in range(30, 50):\n print(lines[i], end='')",
" 1: 26:int cgi_decode(char *s, char *t) {\n 32: 27: while (*s != '\\0') {\n 31: 28: if (*s == '+')\n 3: 29: *t++ = ' ';\n 28: 30: else if (*s == '%') {\n 1: 31: int digit_high = *++s;\n 1: 32: int digit_low = *++s;\n 1: 33: if (hex_values[digit_high] >= 0 && hex_values[digit_low] >= 0) {\n 1: 34: *t++ = hex_values[digit_high] * 16 + hex_values[digit_low];\n 1: 35: }\n -: 36: else\n #####: 37: return -1;\n 1: 38: }\n -: 39: else\n 27: 40: *t++ = *s;\n 31: 41: s++;\n -: 42: }\n 1: 43: *t = '\\0';\n 1: 44: return 0;\n 1: 45:}\n"
]
],
[
[
"Let us read in this file to obtain a coverage set:",
"_____no_output_____"
]
],
[
[
"def read_gcov_coverage(c_file):\n gcov_file = c_file + \".gcov\"\n coverage = set()\n with open(gcov_file) as file:\n for line in file.readlines():\n elems = line.split(':')\n covered = elems[0].strip()\n line_number = int(elems[1].strip())\n if covered.startswith('-') or covered.startswith('#'):\n continue\n coverage.add((c_file, line_number))\n return coverage",
"_____no_output_____"
],
[
"coverage = read_gcov_coverage('cgi_decode.c')",
"_____no_output_____"
],
[
"list(coverage)[:5]",
"_____no_output_____"
]
],
[
[
"With this set, we can now do the same coverage computations as with our Python programs.",
"_____no_output_____"
],
[
"## Finding Errors with Basic Fuzzing\n\nGiven sufficient time, we can indeed cover each and every line within `cgi_decode()`, whatever the programming language would be. This does not mean that they would be error-free, though. Since we do not check the result of `cgi_decode()`, the function could return any value without us checking or noticing. To catch such errors, we would have to set up a *results checker* (commonly called an *oracle*) that would verify test results. In our case, we could compare the C and Python implementations of `cgi_decode()` and see whether both produce the same results.",
"_____no_output_____"
],
[
"Where fuzzing is great at, though, is in finding _internal errors_ that can be detected even without checking the result. Actually, if one runs our `fuzzer()` on `cgi_decode()`, one quickly finds such an error, as the following code shows:",
"_____no_output_____"
]
],
[
[
"from ExpectError import ExpectError",
"_____no_output_____"
],
[
"with ExpectError():\n for i in range(trials):\n try:\n s = fuzzer()\n cgi_decode(s)\n except ValueError:\n pass",
"Traceback (most recent call last):\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_10316/2238772797.py\", line 5, in <module>\n cgi_decode(s)\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_10316/1071239422.py\", line 22, in cgi_decode\n digit_high, digit_low = s[i + 1], s[i + 2]\nIndexError: string index out of range (expected)\n"
]
],
[
[
"So, it is possible to cause `cgi_decode()` to crash. Why is that? Let's take a look at its input:",
"_____no_output_____"
]
],
[
[
"s",
"_____no_output_____"
]
],
[
[
"The problem here is at the end of the string. After a `'%'` character, our implementation will always attempt to access two more (hexadecimal) characters, but if these are not there, we will get an `IndexError` exception. ",
"_____no_output_____"
],
[
"This problem is also present in our C variant, which inherits it from the original implementation \\cite{Pezze2008}:\n\n```c\nint digit_high = *++s;\nint digit_low = *++s;\n```\n\nHere, `s` is a pointer to the character to be read; `++` increments it by one character.\nIn the C implementation, the problem is actually much worse. If the `'%'` character is at the end of the string, the above code will first read a terminating character (`'\\0'` in C strings) and then the following character, which may be any memory content after the string, and which thus may cause the program to fail uncontrollably. The somewhat good news is that `'\\0'` is not a valid hexadecimal character, and thus, the C version will \"only\" read one character beyond the end of the string.",
"_____no_output_____"
],
[
"Interestingly enough, none of the manual tests we had designed earlier would trigger this bug. Actually, neither statement nor branch coverage, nor any of the coverage criteria commonly discussed in literature would find it. However, a simple fuzzing run can identify the error with a few runs – _if_ appropriate run-time checks are in place that find such overflows. This definitely calls for more fuzzing!",
"_____no_output_____"
],
[
"## Synopsis\n\nThis chapter introduces a `Coverage` class allowing you to measure coverage for Python programs. Within the context of this book, we use coverage information to guide fuzzing towards uncovered locations.",
"_____no_output_____"
],
[
"The typical usage of the `Coverage` class is in conjunction with a `with` clause:",
"_____no_output_____"
]
],
[
[
"with Coverage() as cov:\n cgi_decode(\"a+b\")",
"_____no_output_____"
]
],
[
[
"Printing out a coverage object shows the covered functions, with covered lines prefixed as `#`:",
"_____no_output_____"
]
],
[
[
"print(cov)",
" 1 def cgi_decode(s: str) -> str:\n 2 \"\"\"Decode the CGI-encoded string `s`:\n 3 * replace '+' by ' '\n 4 * replace \"%xx\" by the character with hex number xx.\n 5 Return the decoded string. Raise `ValueError` for invalid inputs.\"\"\"\n 6 \n 7 # Mapping of hex digits to their integer values\n# 8 hex_values = {\n# 9 '0': 0, '1': 1, '2': 2, '3': 3, '4': 4,\n# 10 '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,\n# 11 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15,\n# 12 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15,\n 13 }\n 14 \n# 15 t = \"\"\n# 16 i = 0\n# 17 while i < len(s):\n# 18 c = s[i]\n# 19 if c == '+':\n# 20 t += ' '\n# 21 elif c == '%':\n 22 digit_high, digit_low = s[i + 1], s[i + 2]\n 23 i += 2\n 24 if digit_high in hex_values and digit_low in hex_values:\n 25 v = hex_values[digit_high] * 16 + hex_values[digit_low]\n 26 t += chr(v)\n 27 else:\n 28 raise ValueError(\"Invalid encoding\")\n 29 else:\n# 30 t += c\n# 31 i += 1\n# 32 return t\n\n"
]
],
[
[
"The `trace()` method returns the _trace_ – that is, the list of locations executed in order. Each location comes as a pair (`function name`, `line`).",
"_____no_output_____"
]
],
[
[
"cov.trace()",
"_____no_output_____"
]
],
[
[
"The `coverage()` method returns the _coverage_, that is, the set of locations in the trace executed at least once:",
"_____no_output_____"
]
],
[
[
"cov.coverage()",
"_____no_output_____"
]
],
[
[
"Coverage sets can be subject to set operations, such as _intersection_ (which locations are covered in multiple executions) and _difference_ (which locations are covered in run _a_, but not _b_).",
"_____no_output_____"
],
[
"The chapter also discusses how to obtain such coverage from C programs.",
"_____no_output_____"
]
],
[
[
"# ignore\nfrom ClassDiagram import display_class_hierarchy",
"_____no_output_____"
],
[
"# ignore\ndisplay_class_hierarchy(Coverage,\n public_methods=[\n Coverage.__init__,\n Coverage.__enter__,\n Coverage.__exit__,\n Coverage.coverage,\n Coverage.trace,\n Coverage.function_names,\n Coverage.__repr__,\n ],\n types={'Location': Location},\n project='fuzzingbook')",
"_____no_output_____"
]
],
[
[
"## Lessons Learned\n\n* Coverage metrics are a simple and fully automated means to approximate how much functionality of a program is actually executed during a test run.\n* A number of coverage metrics exist, the most important ones being statement coverage and branch coverage.\n* In Python, it is very easy to access the program state during execution, including the currently executed code.",
"_____no_output_____"
],
[
"At the end of the day, let's clean up: (Note that the following commands will delete all files in the current working directory that fit the pattern `cgi_decode.*`. Be aware of this, if you downloaded the notebooks and are working locally.)",
"_____no_output_____"
]
],
[
[
"import os\nimport glob",
"_____no_output_____"
],
[
"for file in glob.glob(\"cgi_decode\") + glob.glob(\"cgi_decode.*\"):\n os.remove(file)",
"_____no_output_____"
]
],
[
[
"## Next Steps\n\nCoverage is not only a tool to _measure_ test effectiveness, but also a great tool to _guide_ test generation towards specific goals – in particular uncovered code. We use coverage to\n\n* [guide _mutations_ of existing inputs towards better coverage in the chapter on mutation fuzzing](MutationFuzzer.ipynb)\n",
"_____no_output_____"
],
[
"## Background\n\nCoverage is a central concept in systematic software testing. For discussions, see the books in the [Introduction to Testing](Intro_Testing.ipynb).",
"_____no_output_____"
],
[
"## Exercises",
"_____no_output_____"
],
[
"### Exercise 1: Fixing `cgi_decode()`\n\nCreate an appropriate test to reproduce the `IndexError` discussed above. Fix `cgi_decode()` to prevent the bug. Show that your test (and additional `fuzzer()` runs) no longer expose the bug. Do the same for the C variant.",
"_____no_output_____"
],
[
"**Solution.** Here's a test case:",
"_____no_output_____"
]
],
[
[
"with ExpectError():\n assert cgi_decode('%') == '%'",
"Traceback (most recent call last):\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_10316/1102034435.py\", line 2, in <module>\n assert cgi_decode('%') == '%'\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_10316/1071239422.py\", line 22, in cgi_decode\n digit_high, digit_low = s[i + 1], s[i + 2]\nIndexError: string index out of range (expected)\n"
],
[
"with ExpectError():\n assert cgi_decode('%4') == '%4'",
"Traceback (most recent call last):\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_10316/2291699482.py\", line 2, in <module>\n assert cgi_decode('%4') == '%4'\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_10316/1071239422.py\", line 22, in cgi_decode\n digit_high, digit_low = s[i + 1], s[i + 2]\nIndexError: string index out of range (expected)\n"
],
[
"assert cgi_decode('%40') == '@'",
"_____no_output_____"
]
],
[
[
"Here's a fix:",
"_____no_output_____"
]
],
[
[
"def fixed_cgi_decode(s):\n \"\"\"Decode the CGI-encoded string `s`:\n * replace \"+\" by \" \"\n * replace \"%xx\" by the character with hex number xx.\n Return the decoded string. Raise `ValueError` for invalid inputs.\"\"\"\n\n # Mapping of hex digits to their integer values\n hex_values = {\n '0': 0, '1': 1, '2': 2, '3': 3, '4': 4,\n '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,\n 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15,\n 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15,\n }\n\n t = \"\"\n i = 0\n while i < len(s):\n c = s[i]\n if c == '+':\n t += ' '\n elif c == '%' and i + 2 < len(s): # <--- *** FIX ***\n digit_high, digit_low = s[i + 1], s[i + 2]\n i += 2\n if digit_high in hex_values and digit_low in hex_values:\n v = hex_values[digit_high] * 16 + hex_values[digit_low]\n t += chr(v)\n else:\n raise ValueError(\"Invalid encoding\")\n else:\n t += c\n i += 1\n return t",
"_____no_output_____"
],
[
"assert fixed_cgi_decode('%') == '%'",
"_____no_output_____"
],
[
"assert fixed_cgi_decode('%4') == '%4'",
"_____no_output_____"
],
[
"assert fixed_cgi_decode('%40') == '@'",
"_____no_output_____"
]
],
[
[
"Here's the test:",
"_____no_output_____"
]
],
[
[
"for i in range(trials):\n try:\n s = fuzzer()\n fixed_cgi_decode(s)\n except ValueError:\n pass",
"_____no_output_____"
]
],
[
[
"For the C variant, the following will do:",
"_____no_output_____"
]
],
[
[
"cgi_c_code = cgi_c_code.replace(\n r\"if (*s == '%')\", # old code\n r\"if (*s == '%' && s[1] != '\\0' && s[2] != '\\0')\" # new code\n)",
"_____no_output_____"
]
],
[
[
"Go back to the above compilation commands and recompile `cgi_decode`.",
"_____no_output_____"
],
[
"### Exercise 2: Branch Coverage\n\nBesides statement coverage, _branch coverage_ is one of the most frequently used criteria to determine the quality of a test. In a nutshell, branch coverage measures how many different _control decisions_ are made in code. In the statement\n\n```python\nif CONDITION:\n do_a()\nelse:\n do_b()\n```\n\nfor instance, both the cases where `CONDITION` is true (branching to `do_a()`) and where `CONDITION` is false (branching to `do_b()`) have to be covered. This holds for all control statements with a condition (`if`, `while`, etc.).\n\nHow is branch coverage different from statement coverage? In the above example, there is actually no difference. In this one, though, there is:\n\n```python\nif CONDITION:\n do_a()\nsomething_else()\n```\n\nUsing statement coverage, a single test case where `CONDITION` is true suffices to cover the call to `do_a()`. Using branch coverage, however, we would also have to create a test case where `do_a()` is _not_ invoked.",
"_____no_output_____"
],
[
"Using our `Coverage` infrastructure, we can simulate branch coverage by considering _pairs of subsequent lines executed_. The `trace()` method gives us the list of lines executed one after the other:",
"_____no_output_____"
]
],
[
[
"with Coverage() as cov:\n cgi_decode(\"a+b\")\ntrace = cov.trace()\ntrace[:5]",
"_____no_output_____"
]
],
[
[
"#### Part 1: Compute branch coverage\n\nDefine a function `branch_coverage()` that takes a trace and returns the set of pairs of subsequent lines in a trace – in the above example, this would be \n\n```python\nset(\n(('cgi_decode', 9), ('cgi_decode', 10)),\n(('cgi_decode', 10), ('cgi_decode', 11)),\n# more_pairs\n)\n```\n\nBonus for advanced Python programmers: Define `BranchCoverage` as a subclass of `Coverage` and make `branch_coverage()` as above a `coverage()` method of `BranchCoverage`.",
"_____no_output_____"
],
[
"**Solution.** Here's a simple definition of `branch_coverage()`:",
"_____no_output_____"
]
],
[
[
"def branch_coverage(trace):\n coverage = set()\n past_line = None\n for line in trace:\n if past_line is not None:\n coverage.add((past_line, line))\n past_line = line\n\n return coverage",
"_____no_output_____"
],
[
"branch_coverage(trace)",
"_____no_output_____"
]
],
[
[
"Here's a definition as a class:",
"_____no_output_____"
]
],
[
[
"class BranchCoverage(Coverage):\n def coverage(self):\n \"\"\"The set of executed line pairs\"\"\"\n coverage = set()\n past_line = None\n for line in self.trace():\n if past_line is not None:\n coverage.add((past_line, line))\n past_line = line\n\n return coverage",
"_____no_output_____"
]
],
[
[
"#### Part 2: Comparing statement coverage and branch coverage\n\nUse `branch_coverage()` to repeat the experiments in this chapter with branch coverage rather than statement coverage. Do the manually written test cases cover all branches?",
"_____no_output_____"
],
[
"**Solution.** Let's repeat the above experiments with `BranchCoverage`:",
"_____no_output_____"
]
],
[
[
"with BranchCoverage() as cov:\n cgi_decode(\"a+b\")\n\nprint(cov.coverage())",
"{(('cgi_decode', 9), ('cgi_decode', 10)), (('cgi_decode', 19), ('cgi_decode', 20)), (('cgi_decode', 8), ('cgi_decode', 15)), (('cgi_decode', 16), ('cgi_decode', 17)), (('cgi_decode', 21), ('cgi_decode', 30)), (('cgi_decode', 30), ('cgi_decode', 31)), (('cgi_decode', 17), ('cgi_decode', 32)), (('cgi_decode', 10), ('cgi_decode', 11)), (('cgi_decode', 12), ('cgi_decode', 8)), (('cgi_decode', 18), ('cgi_decode', 19)), (('cgi_decode', 20), ('cgi_decode', 31)), (('cgi_decode', 17), ('cgi_decode', 18)), (('cgi_decode', 31), ('cgi_decode', 17)), (('cgi_decode', 11), ('cgi_decode', 12)), (('cgi_decode', 15), ('cgi_decode', 16)), (('cgi_decode', 19), ('cgi_decode', 21))}\n"
],
[
"with BranchCoverage() as cov_plus:\n cgi_decode(\"a+b\")\nwith BranchCoverage() as cov_standard:\n cgi_decode(\"abc\")\n\ncov_plus.coverage() - cov_standard.coverage()",
"_____no_output_____"
],
[
"with BranchCoverage() as cov_max:\n cgi_decode('+')\n cgi_decode('%20')\n cgi_decode('abc')\n try:\n cgi_decode('%?a')\n except:\n pass",
"_____no_output_____"
],
[
"cov_max.coverage() - cov_plus.coverage()",
"_____no_output_____"
],
[
"sample",
"_____no_output_____"
],
[
"with BranchCoverage() as cov_fuzz:\n try:\n cgi_decode(s)\n except:\n pass\ncov_fuzz.coverage()",
"_____no_output_____"
],
[
"cov_max.coverage() - cov_fuzz.coverage()",
"_____no_output_____"
],
[
"def population_branch_coverage(population, function):\n cumulative_coverage = []\n all_coverage = set()\n\n for s in population:\n with BranchCoverage() as cov:\n try:\n function(s)\n except Exception:\n pass\n all_coverage |= cov.coverage()\n cumulative_coverage.append(len(all_coverage))\n\n return all_coverage, cumulative_coverage",
"_____no_output_____"
],
[
"all_branch_coverage, cumulative_branch_coverage = population_branch_coverage(\n hundred_inputs(), cgi_decode)",
"_____no_output_____"
],
[
"plt.plot(cumulative_branch_coverage)\nplt.title('Branch coverage of cgi_decode() with random inputs')\nplt.xlabel('# of inputs')\nplt.ylabel('line pairs covered')",
"_____no_output_____"
],
[
"len(cov_max.coverage())",
"_____no_output_____"
],
[
"all_branch_coverage - cov_max.coverage()",
"_____no_output_____"
]
],
[
[
"The additional coverage comes from the exception raised via an illegal input (say, `%g`).",
"_____no_output_____"
]
],
[
[
"cov_max.coverage() - all_branch_coverage",
"_____no_output_____"
]
],
[
[
"This is an artefact coming from the subsequent execution of `cgi_decode()` when computing `cov_max`.",
"_____no_output_____"
],
[
"#### Part 3: Average coverage\n\nAgain, repeat the above experiments with branch coverage. Does `fuzzer()` cover all branches, and if so, how many tests does it take on average?",
"_____no_output_____"
],
[
"**Solution.** We repeat the experiments we ran with line coverage with branch coverage.",
"_____no_output_____"
]
],
[
[
"runs = 100\n\n# Create an array with TRIALS elements, all zero\nsum_coverage = [0] * trials\n\nfor run in range(runs):\n all_branch_coverage, coverage = population_branch_coverage(\n hundred_inputs(), cgi_decode)\n assert len(coverage) == trials\n for i in range(trials):\n sum_coverage[i] += coverage[i]\n\naverage_coverage = []\nfor i in range(trials):\n average_coverage.append(sum_coverage[i] / runs)",
"_____no_output_____"
],
[
"plt.plot(average_coverage)\nplt.title('Average branch coverage of cgi_decode() with random inputs')\nplt.xlabel('# of inputs')\nplt.ylabel('line pairs covered')",
"_____no_output_____"
]
],
[
[
"We see that achieving branch coverage takes longer than statement coverage; it simply is a more difficult criterion to satisfy with random inputs.",
"_____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",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
eccf3fc85564555c1e66827dac055acabbb4aae9 | 57,914 | ipynb | Jupyter Notebook | Aprendizaje_Automatica/Actividades/T1/T1-Manuel_Pasieka.ipynb | mapa17/UNIR-IA | d8c899e21c8cf8ddeb78803cd4c633c6dce2b121 | [
"MIT"
] | null | null | null | Aprendizaje_Automatica/Actividades/T1/T1-Manuel_Pasieka.ipynb | mapa17/UNIR-IA | d8c899e21c8cf8ddeb78803cd4c633c6dce2b121 | [
"MIT"
] | null | null | null | Aprendizaje_Automatica/Actividades/T1/T1-Manuel_Pasieka.ipynb | mapa17/UNIR-IA | d8c899e21c8cf8ddeb78803cd4c633c6dce2b121 | [
"MIT"
] | null | null | null | 76.504624 | 24,314 | 0.745502 | [
[
[
"import pandas as pd\nimport numpy as np\nimport sklearn",
"_____no_output_____"
]
],
[
[
"# Loading Data\n* Load the data\n* Split features from predictor class\n* Encode features\n* Filter outliers",
"_____no_output_____"
]
],
[
[
"raw_data = pd.read_csv('data/house-votes-84.data.txt', \\\n names=['party'] + ['v%02d'%x for x in range(16)])\nraw_data.head()",
"_____no_output_____"
],
[
"# Split the data into party affiliation (output variable) and votes (features)\nparty = raw_data['party']\nvotes = raw_data.drop('party', axis=1)",
"_____no_output_____"
],
[
"print(f'# Entries {raw_data.shape[0]}, # Features {raw_data.shape[1]-1}')\nprint(f'\\nClass distribution: \\n{party.value_counts()}')\nprint(f'\\nFeature distribution: \\n{pd.Series(votes.values.flatten()).value_counts()}')",
"# Entries 435, # Features 16\n\nClass distribution: \ndemocrat 267\nrepublican 168\nName: party, dtype: int64\n\nFeature distribution: \ny 3421\nn 3147\n? 392\ndtype: int64\n"
],
[
"# Map the votes to easy to process feature values\nfeatures = votes.apply(lambda x: x.map({'n':0, '?':1, 'y':2}), axis=1)\nfeatures.head()",
"_____no_output_____"
],
[
"voting_treshold = 4\n\n# Filter votes, that have than half of missing votes\n# (keep those that have less than 8 missing votes)\nnmissing_votes = (features == 1).sum(axis=1)\nkeep = nmissing_votes <= voting_treshold\n\nprint(f'Dropping {keep.shape[0] - keep.sum()} rows because to \\\nmore than {voting_treshold} missing votes!')\n\nparty = party[keep]\nvotes = votes[keep]\nfeatures = features[keep]",
"Dropping 14 rows because to more than 4 missing votes!\n"
]
],
[
[
"# Handle missing values\nTwo datasets will be generated, using two different methods to handle the missing data\n\n* Process each vote/column seperatly and fill entries based on the most common value of the 5 closest neighbours. Neighbours are calculated has most similar encoding.\n* Random selection of yes or no votes",
"_____no_output_____"
]
],
[
[
"def nn_fill(table, N=5, missing_value=0):\n # Store results here\n cleaned = table.copy()\n\n for column_idx in range(table.shape[1]):\n\n has_missing = (table.iloc[:, column_idx] == missing_value)\n print(f'Found #{has_missing.sum()} missing valuesin column \\\n {column_idx}. Start filling them ...')\n\n missing = table[has_missing].drop(table.columns[column_idx], axis=1)\n # Get all neighbours, dropping the column that needs prediction\n neighbours = table[~has_missing].drop(table.columns[column_idx], axis=1)\n\n # For each missing, calculate its neighbour distance\n for i, s in missing.iterrows():\n # Calculate the distance as the absolute numeric difference\n distance = neighbours.apply(lambda x: abs(x - s).sum(), axis=1)\n\n # Find the most common value among the N closest neighbours\n most_common = table.loc[distance.sort_values()[0:N].index, \\\n table.columns[column_idx]].mode().values[0]\n\n #print(f'for row {i} we found the most common value to be {most_common}')\n cleaned.loc[i, table.columns[column_idx]] = most_common\n\n print('All done!')\n \n return cleaned\n\ndef random_fill(table, seed=42, missing_value=0, values=[-1, 1]):\n # Initalize random generator\n np.random.seed(seed)\n \n # Which rows and colums need filling\n missing_r, missing_col = np.where(features.values == missing_value)\n \n # Generate some random sequence\n rand_idx = np.random.randint(0, len(values), size=missing_r.size)\n\n # Store result here\n random_fill = features.copy()\n for vote, row, column in zip(rand_idx, missing_r, missing_col):\n random_fill.iloc[row, column] = values[vote]\n \n return random_fill",
"_____no_output_____"
],
[
"# Number of nearest neighbours to use\ncleaned_features = nn_fill(features, N=5, missing_value=1)\nrandom_features = random_fill(features, seed=8888, missing_value=1, values=[0, 2])",
"Found #5 missing valuesin column 0. Start filling them ...\nFound #39 missing valuesin column 1. Start filling them ...\nFound #6 missing valuesin column 2. Start filling them ...\nFound #6 missing valuesin column 3. Start filling them ...\nFound #10 missing valuesin column 4. Start filling them ...\nFound #6 missing valuesin column 5. Start filling them ...\nFound #8 missing valuesin column 6. Start filling them ...\nFound #8 missing valuesin column 7. Start filling them ...\nFound #18 missing valuesin column 8. Start filling them ...\nFound #3 missing valuesin column 9. Start filling them ...\nFound #11 missing valuesin column 10. Start filling them ...\nFound #22 missing valuesin column 11. Start filling them ...\nFound #18 missing valuesin column 12. Start filling them ...\nFound #10 missing valuesin column 13. Start filling them ...\nFound #20 missing valuesin column 14. Start filling them ...\nFound #92 missing valuesin column 15. Start filling them ...\nAll done!\n"
]
],
[
[
"# Building a classifier\n* Split data into training and test set\n* Train a Naive Bayes Classifier with bernoulli distribution",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.naive_bayes import MultinomialNB\n\n# Use 20% for testing\ntraining_test_ratio = 0.2\n\ntrain_idx, test_idx = train_test_split(party.index, test_size=training_test_ratio, random_state=1001)",
"_____no_output_____"
],
[
"# Train classifier\ndata = cleaned_features\n#data = random_features\n\nclf = BernoulliNB().fit(data.loc[train_idx], party.loc[train_idx])",
"_____no_output_____"
],
[
"# Perform prediction\nprediction = clf.predict(data.loc[test_idx])\ntruth = party.loc[test_idx].values",
"_____no_output_____"
]
],
[
[
"# Evaluate prediction quality",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import confusion_matrix\nimport seaborn as sns\nsns.set()",
"/Users/manuel.pasieka/anaconda3/envs/py3/lib/python3.6/site-packages/IPython/html.py:14: ShimWarning: The `IPython.html` package has been deprecated since IPython 4.0. You should import from `notebook` instead. `IPython.html.widgets` has moved to `ipywidgets`.\n \"`IPython.html.widgets` has moved to `ipywidgets`.\", ShimWarning)\n"
],
[
"labels = ['democrat', 'republican']\nmat = confusion_matrix(truth, prediction)\nsns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False,\n xticklabels=labels, yticklabels=labels)\nplt.xlabel('true label')\nplt.ylabel('predicted label');\nplt.show()",
"_____no_output_____"
],
[
"accurracy = (mat[0, 0] + mat[1, 1]) / mat.sum()\nprint(f'Accuracy {accurracy*100.0:2.0f}%')",
"Accuracy 91%\n"
]
],
[
[
"# Cross Validation\nUse cross validation with a 5 fold to estimate accuracy, comparing the different variations of classifiers, and data sets.",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\n\nF = 5 \n\nnn_scores_b = cross_val_score(BernoulliNB(), cleaned_features, party, cv=F)\nrand_scores_b = cross_val_score(BernoulliNB(), random_features, party, cv=F)\n\nnn_scores_g = cross_val_score(GaussianNB(), cleaned_features, party, cv=F)\nrand_scores_g = cross_val_score(GaussianNB(), random_features, party, cv=F)\n\nnn_scores_m = cross_val_score(MultinomialNB(), cleaned_features, party, cv=F)\nrand_scores_m = cross_val_score(MultinomialNB(), random_features, party, cv=F)\n\nscores = [nn_scores_b, rand_scores_b, nn_scores_g, rand_scores_g, nn_scores_m, rand_scores_m]\nscores_labels = ['NN - Bernoulli', 'Random - Bernoulli', 'NN - Gausian', \\\n 'Random - Gausian', 'NN - MultiN', 'Random - MultiN']",
"_____no_output_____"
],
[
"# Plot cross validation result\nfig, axs = plt.subplots(1, 1, figsize=(10, 7))\nbp = axs.boxplot(scores, 0, labels=scores_labels, positions=range(len(scores)))\nfor i, sv in enumerate(scores):\n axs.scatter([i]*len(sv), sv)\naxs.set_ylim(0.5, 1.0)\naxs.set_xlabel('Classifiers')\naxs.set_ylabel('Accuracy')\naxs.set_title('Cross validation comparison')\nplt.show()",
"_____no_output_____"
],
[
"for sn, sv in zip(scores_labels, scores):\n print(f'{sn}: mean {sv.mean():2.3f}, var {sv.var():2.3f}')",
"NN - Bernoulli: mean 0.905, var 0.002\nRandom - Bernoulli: mean 0.905, var 0.001\nNN - Gausian: mean 0.940, var 0.001\nRandom - Gausian: mean 0.943, var 0.001\nNN - MultiN: mean 0.907, var 0.002\nRandom - MultiN: mean 0.907, var 0.002\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
eccf4026410d77223826e4ac7d90e344f78697ea | 11,677 | ipynb | Jupyter Notebook | extraction/ld-extract.ipynb | cosgriffc/lactate-discordance | 31450e75e5c587fab3daff523a5f326e5eea0660 | [
"MIT"
] | null | null | null | extraction/ld-extract.ipynb | cosgriffc/lactate-discordance | 31450e75e5c587fab3daff523a5f326e5eea0660 | [
"MIT"
] | null | null | null | extraction/ld-extract.ipynb | cosgriffc/lactate-discordance | 31450e75e5c587fab3daff523a5f326e5eea0660 | [
"MIT"
] | null | null | null | 31.559459 | 369 | 0.558791 | [
[
[
"# Lactate Discordance Project\n## Cohort Extraction\n### C.V. Cosgriff, MIT Critcial Data\n\nThe goal of this preliminary work is to extract vital signs, lab data, and diagnosis data in an attempt to model what we have termed _lactate discordance_. We define this as patients who have a lactate level that is discordant with their severity of illness. This definition will be further defined other notebooks. The stages of the extraction are as follows:\n\n1. Build materialized views for first day vitals, labs, vasopressor and ventilation status.\n * Of note, vitals and labs have built sanity checks for the values.\n * The cohort has flags for certain exclusion criteria.\n2. For diagnosis groups, a prior exploratory analysis was carried out in R, and that code was utilized to generate an R script which outputs a csv file with the first day diagnosis groups. Briefly this script:\n * Uses regular expressions to identify eICU diagnosis strings corresponding to different diagnostic groupings weakly based on the Elixhauser AHRQ groupings.\n * The strings are then used to bin the first day diagnoses of all ICU patients.\n * Final a CSV file is output.\n3. We'll then grab the APACHE result tabl in order to attain APACHE IVa scores.\n4. After the views are built we'll load them into a `DataFrame` and then merge them.\n5. Finally, we'll pull in the patients table, exclude patients under a certain age and with stays that are too short and merge it with all of the other data.",
"_____no_output_____"
],
[
"## Step 0: Environment Setup",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport psycopg2\n\n# postgres envrionment setup; placeholds here, place your own info\nsqluser = 'mimicuser'\nuserpass = 'harvardmit2018'\ndbname = 'eicu'\nschema_name = 'eicu_crd'\nhost = '10.8.0.1'\n\nquery_schema = 'SET search_path TO ' + schema_name + ';'\n\n# connect to the database\ncon = psycopg2.connect(dbname = dbname, user = sqluser, host = host, password = userpass)",
"_____no_output_____"
]
],
[
[
"## Step 1: Materialized Views & Diagnosis Group Data",
"_____no_output_____"
],
[
"The views we will generate are as follows:\n1. Vitals, first day (`vitalsfirstday`)\n2. Labs, first day (`labsfirstday`)\n3. Vasoressors, first day (`pressorfirstday`)\n4. Ventilation, first day (`ventfirstday`)\n\nEach of these scripts was written in SQL and is based off similar MIMIC-III scripts.",
"_____no_output_____"
]
],
[
[
"def execute_query_safely(sql, con):\n cur = con.cursor()\n try:\n cur.execute(sql)\n except:\n # if an exception, rollback, rethrow the exception - finally closes the connection\n cur.execute('rollback;')\n raise\n finally:\n cur.close()\n return\n\ndef generate_materialized_view(query_file, query_schema):\n with open(query_file) as fp:\n query = ''.join(fp.readlines())\n print('Generating materialized view using {} ...'.format(query_file), end = ' ')\n execute_query_safely(query_schema + query, con)\n print('done.')\n \ngenerate_materialized_view('./sql/vitalsfirstday.sql', query_schema)\ngenerate_materialized_view('./sql/labsfirstday.sql', query_schema)\ngenerate_materialized_view('./sql/pressorfirstday.sql', query_schema)\ngenerate_materialized_view('./sql/ventfirstday.sql', query_schema)",
"_____no_output_____"
]
],
[
[
"For the diagnosis groups, we use the R script, `diagnosis_groups.R`, which is the local directory in the `R/` folder. It requires that you have `RPostgresSQL`, and the `tidyverse` packages. And of course you need R installed. \n\n_Note: make sure to edit the R script to work with your database environment._",
"_____no_output_____"
]
],
[
[
"!Rscript ./R/diagnosis_groups.R",
"_____no_output_____"
]
],
[
[
"That concludes scripts we need to run to generate the data. We can next load these scripts into dataframes.",
"_____no_output_____"
],
[
"## Step 2: Construct Cohort",
"_____no_output_____"
],
[
"We'll start by generating a query to pull in the base cohort, and the data from the materialized views.",
"_____no_output_____"
]
],
[
[
"query = query_schema + '''\nWITH apache AS (\n SELECT patientunitstayid, apachescore\n FROM apachepatientresult\n WHERE apacheversion = 'IVa'\n )\n \nSELECT p.patientunitstayid, p.age, p.ethnicity\n , CASE \n WHEN p.gender = 'Male' THEN 1\n ELSE 0\n END AS male_gender\n , vs.HR_Min\n , vs.HR_Max\n , vs.HR_Mean\n , vs.SBP_periodic_Min\n , vs.SBP_periodic_Max\n , vs.SBP_periodic_Mean\n , vs.DBP_periodic_Min\n , vs.DBP_periodic_Max\n , vs.DBP_periodic_Mean\n , vs.MAP_periodic_Min\n , vs.MAP_periodic_Max\n , vs.MAP_periodic_Mean\n , vs.SBP_aperiodic_Min\n , vs.SBP_aperiodic_Max\n , vs.SBP_aperiodic_Mean\n , vs.DBP_aperiodic_Min\n , vs.DBP_aperiodic_Max\n , vs.DBP_aperiodic_Mean\n , vs.MAP_aperiodic_Min\n , vs.MAP_aperiodic_Max\n , vs.MAP_aperiodic_Mean\n , vs.RR_Min\n , vs.RR_Max\n , vs.RR_Mean\n , vs.SpO2_Min \n , vs.SpO2_Max\n , vs.SpO2_Mean \n , vs.TempC_Min\n , vs.TempC_Max\n , vs.TempC_Mean\n , la.ALBUMIN_min -- dropped anion gap\n , la.ALBUMIN_max -- will be too colinear\n , la.BANDS_min\n , la.BANDS_max\n , la.BICARBONATE_min\n , la.BICARBONATE_max\n , la.BILIRUBIN_min\n , la.BILIRUBIN_max\n , la.CREATININE_min\n , la.CREATININE_max\n , la.CHLORIDE_min\n , la.CHLORIDE_max\n , la.GLUCOSE_min\n , la.GLUCOSE_max\n , la.HEMATOCRIT_min\n , la.HEMATOCRIT_max\n , la.HEMOGLOBIN_min\n , la.HEMOGLOBIN_max\n , la.LACTATE_min\n , la.LACTATE_max\n , la.PLATELET_min\n , la.PLATELET_max\n , la.POTASSIUM_min\n , la.POTASSIUM_max\n , la.PTT_min\n , la.PTT_max\n , la.INR_min\n , la.INR_max\n , la.PT_min\n , la.PT_max\n , la.SODIUM_min\n , la.SODIUM_max\n , la.BUN_min\n , la.BUN_max\n , la.WBC_min\n , la.WBC_max\n , pr.pressor\n , mv.oobintubday1\n , ap.apachescore\n , CASE\n WHEN p.unitdischargeoffset < 240 THEN 1\n ELSE 0\n END AS short_los\nFROM patient p\nINNER JOIN vitalsfirstday vs\nON p.patientunitstayid = vs.patientunitstayid\nINNER JOIN labsfirstday la\nON p.patientunitstayid = la.patientunitstayid\nLEFT JOIN pressorfirstday pr\nON p.patientunitstayid = pr.patientunitstayid\nINNER JOIN ventfirstday mv\nON p.patientunitstayid = mv.patientunitstayid\nINNER JOIN apache ap\nON p.patientunitstayid = ap.patientunitstayid;\n'''\n\nbase_cohort = pd.read_sql_query(query, con)",
"_____no_output_____"
]
],
[
[
"We next load in the diagnoses table.",
"_____no_output_____"
]
],
[
[
"dx_table = pd.read_csv('./dx-firstday_groupings.csv')\ndel dx_table['Unnamed: 0'] # gets rid of firs column which is a duplicate index",
"_____no_output_____"
]
],
[
[
"We can then join this with the cohort.",
"_____no_output_____"
]
],
[
[
"cohort = base_cohort.merge(dx_table, on = 'patientunitstayid')",
"_____no_output_____"
]
],
[
[
"## Step 3: Apply Exclusion and Basic Cleaning\n\n1. Exclude if any LoS flags are valued to 1\n2. Convert age from character to numeric, excluding <16, >89\n3. Exclude patients without a lactate measurement\n4. Change NA's for vasopressors to 0 since NA here just meant no infusions recorded\n\nWe can print the shape at each point in order to track exclusions.",
"_____no_output_____"
]
],
[
[
"print(cohort.shape)\ncohort = cohort[cohort.short_los == 0]\nprint(cohort.shape)\ncohort = cohort[(cohort.age != '> 89') & (cohort.age != '')]\nprint(cohort.shape)\ncohort.age = cohort.age.astype(float)\ncohort = cohort[cohort.age >= 16.]\nprint(cohort.shape)\ncohort = cohort[(pd.isna(cohort.lactate_max) == False) & (pd.isnull(cohort.lactate_max) == False)]\nprint(cohort.shape)\ncohort.loc[pd.isna(cohort.pressor), 'pressor'] = 0",
"_____no_output_____"
]
],
[
[
"Finally, we can save this to a file for analysis.",
"_____no_output_____"
],
[
"## Step 4: Save File",
"_____no_output_____"
]
],
[
[
"cohort.to_csv('cohort.csv', index = False)",
"_____no_output_____"
]
],
[
[
"And that brings us to the analysis phase.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
eccf5144084ead9f0912c2f0c0b74d960f3875e9 | 152,590 | ipynb | Jupyter Notebook | Chapter2/defense_posion_attacks/poisoning_defense_deep_partition_aggregation.ipynb | PacktPublishing/Designing-Models-for-Responsible-AI | 36b60f1e3e9db8b3d2db3ace873dbdee1b076b74 | [
"MIT"
] | null | null | null | Chapter2/defense_posion_attacks/poisoning_defense_deep_partition_aggregation.ipynb | PacktPublishing/Designing-Models-for-Responsible-AI | 36b60f1e3e9db8b3d2db3ace873dbdee1b076b74 | [
"MIT"
] | null | null | null | Chapter2/defense_posion_attacks/poisoning_defense_deep_partition_aggregation.ipynb | PacktPublishing/Designing-Models-for-Responsible-AI | 36b60f1e3e9db8b3d2db3ace873dbdee1b076b74 | [
"MIT"
] | 2 | 2022-01-17T07:28:22.000Z | 2022-01-30T00:12:53.000Z | 63.315353 | 5,048 | 0.592208 | [
[
[
"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os, sys\nfrom os.path import abspath\n\nmodule_path = os.path.abspath(os.path.join('..'))\nif module_path not in sys.path:\n sys.path.append(module_path)\n\nimport warnings\nwarnings.filterwarnings('ignore')\nimport keras.backend as k\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport tensorflow as tf\ntf.compat.v1.disable_eager_execution()\ntf.get_logger().setLevel('ERROR')\n\nfrom art.estimators.classification import KerasClassifier\nfrom art.attacks.poisoning import PoisoningAttackBackdoor, PoisoningAttackCleanLabelBackdoor\nfrom art.attacks.poisoning.perturbations import add_pattern_bd\nfrom art.utils import load_mnist, preprocess, to_categorical\nfrom art.defences.trainer import AdversarialTrainerMadryPGD\n\n\nfrom art.estimators.classification.deep_partition_ensemble import DeepPartitionEnsemble",
"_____no_output_____"
]
],
[
[
"# Load the Data",
"_____no_output_____"
]
],
[
[
"(x_raw, y_raw), (x_raw_test, y_raw_test), min_, max_ = load_mnist(raw=True)\n\n# Random Selection:\nn_train = np.shape(x_raw)[0]\nnum_selection = 10000\nrandom_selection_indices = np.random.choice(n_train, num_selection)\nx_raw = x_raw[random_selection_indices]\ny_raw = y_raw[random_selection_indices]\n\n# Poison training data\npercent_poison = .33\nx_train, y_train = preprocess(x_raw, y_raw)\nx_train = np.expand_dims(x_train, axis=3)\n\nx_test, y_test = preprocess(x_raw_test, y_raw_test)\nx_test = np.expand_dims(x_test, axis=3)\n\n# Shuffle training data\nn_train = np.shape(y_train)[0]\nshuffled_indices = np.arange(n_train)\nnp.random.shuffle(shuffled_indices)\nx_train = x_train[shuffled_indices]\ny_train = y_train[shuffled_indices]",
"_____no_output_____"
]
],
[
[
"# Initialize the Model Architecture",
"_____no_output_____"
]
],
[
[
"# Create Keras convolutional neural network - basic architecture from Keras examples\n# Source here: https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py\ndef create_model(): \n model = Sequential()\n model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=x_train.shape[1:]))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(10, activation='softmax'))\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model",
"_____no_output_____"
]
],
[
[
"# Set up the Model Backdoor",
"_____no_output_____"
]
],
[
[
"backdoor = PoisoningAttackBackdoor(add_pattern_bd)\nexample_target = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\npdata, plabels = backdoor.poison(x_test, y=example_target)\n\nplt.imshow(pdata[0].squeeze())",
"_____no_output_____"
]
],
[
[
"# Create the poison data\nFor this example, we will select 9 as the target class. Thus, the adversary's goal is to poison the model so adding a trigger will result in the trained model misclassifying the triggered input as a 9.\n\nFirst, the adversary will create a proxy classifier (i.e., a classifier that is similar to the target classifier). As the clean label attack generates noise using PGD in order to encourage the trained classifier to rely on the trigger, it is important that the generated noise be transferable. Thus, adversarial training is used.",
"_____no_output_____"
]
],
[
[
"# Poison some percentage of all non-nines to nines\ntargets = to_categorical([9], 10)[0] \n\nproxy = AdversarialTrainerMadryPGD(KerasClassifier(create_model()), nb_epochs=10, eps=0.15, eps_step=0.001)\nproxy.fit(x_train, y_train)",
"_____no_output_____"
],
[
"attack = PoisoningAttackCleanLabelBackdoor(backdoor=backdoor, proxy_classifier=proxy.get_classifier(),\n target=targets, pp_poison=percent_poison, norm=2, eps=5,\n eps_step=0.1, max_iter=200)\npdata, plabels = attack.poison(x_train, y_train)",
"_____no_output_____"
],
[
"poisoned = pdata[np.all(plabels == targets, axis=1)]\npoisoned_labels = plabels[np.all(plabels == targets, axis=1)]\nprint(len(poisoned))\nfor i in range(len(poisoned)):\n if poisoned[i][0][0] != 0:\n plt.imshow(poisoned[i].squeeze())\n plt.show()\n print(f\"Index: {i} Label: {np.argmax(poisoned_labels[i])}\")\n break",
"1020\n"
]
],
[
[
"# Initialize the classification models\nWe will initialize four models. The first is a single model architecture. The other three are DPA models with varying ensemble sizes to demonstrate the tradeoff between clean accuracy and poison accuracy. This make take some time because of the model copying.",
"_____no_output_____"
]
],
[
[
"model = KerasClassifier(create_model())\ndpa_model_10 = DeepPartitionEnsemble(model, ensemble_size=10)\ndpa_model_20 = DeepPartitionEnsemble(model, ensemble_size=20)\ndpa_model_30 = DeepPartitionEnsemble(model, ensemble_size=30)\n",
"_____no_output_____"
]
],
[
[
"Train the models on the poisoned data",
"_____no_output_____"
]
],
[
[
"model.fit(pdata, plabels, nb_epochs=10)\ndpa_model_10.fit(pdata, plabels, nb_epochs=10)\ndpa_model_20.fit(pdata, plabels, nb_epochs=10)\ndpa_model_30.fit(pdata, plabels, nb_epochs=10)",
"Train on 10000 samples\nEpoch 1/10\n10000/10000 [==============================] - 9s 901us/sample - loss: 0.6975 - accuracy: 0.7831\nEpoch 2/10\n10000/10000 [==============================] - 8s 808us/sample - loss: 0.2377 - accuracy: 0.9326\nEpoch 3/10\n10000/10000 [==============================] - 7s 746us/sample - loss: 0.1533 - accuracy: 0.9562\nEpoch 4/10\n10000/10000 [==============================] - 8s 849us/sample - loss: 0.1103 - accuracy: 0.9690\nEpoch 5/10\n10000/10000 [==============================] - 8s 822us/sample - loss: 0.0774 - accuracy: 0.9755 - loss: 0.078\nEpoch 6/10\n10000/10000 [==============================] - 8s 796us/sample - loss: 0.0713 - accuracy: 0.9783\nEpoch 7/10\n10000/10000 [==============================] - 8s 787us/sample - loss: 0.0625 - accuracy: 0.9804\nEpoch 8/10\n10000/10000 [==============================] - 8s 832us/sample - loss: 0.0504 - accuracy: 0.9833\nEpoch 9/10\n10000/10000 [==============================] - 8s 768us/sample - loss: 0.0423 - accuracy: 0.9870\nEpoch 10/10\n10000/10000 [==============================] - 8s 778us/sample - loss: 0.0407 - accuracy: 0.9861\nTrain on 956 samples\nEpoch 1/10\n956/956 [==============================] - 1s 1ms/sample - loss: 1.9388 - accuracy: 0.3661\nEpoch 2/10\n956/956 [==============================] - 1s 855us/sample - loss: 1.0092 - accuracy: 0.6757\nEpoch 3/10\n956/956 [==============================] - 1s 828us/sample - loss: 0.6682 - accuracy: 0.7793\nEpoch 4/10\n956/956 [==============================] - 1s 780us/sample - loss: 0.5114 - accuracy: 0.8295\nEpoch 5/10\n956/956 [==============================] - 1s 810us/sample - loss: 0.4082 - accuracy: 0.8651\nEpoch 6/10\n956/956 [==============================] - 1s 912us/sample - loss: 0.3170 - accuracy: 0.8985\nEpoch 7/10\n956/956 [==============================] - 1s 913us/sample - loss: 0.2708 - accuracy: 0.9069\nEpoch 8/10\n956/956 [==============================] - 1s 892us/sample - loss: 0.2395 - accuracy: 0.9079\nEpoch 9/10\n956/956 [==============================] - 1s 833us/sample - loss: 0.2065 - accuracy: 0.9372\nEpoch 10/10\n956/956 [==============================] - 1s 775us/sample - loss: 0.1856 - accuracy: 0.9456\nTrain on 956 samples\nEpoch 1/10\n956/956 [==============================] - 1s 1ms/sample - loss: 1.9525 - accuracy: 0.3766\nEpoch 2/10\n956/956 [==============================] - 1s 756us/sample - loss: 1.0183 - accuracy: 0.6621\nEpoch 3/10\n956/956 [==============================] - 1s 766us/sample - loss: 0.7071 - accuracy: 0.7730\nEpoch 4/10\n956/956 [==============================] - 1s 792us/sample - loss: 0.5469 - accuracy: 0.8305\nEpoch 5/10\n956/956 [==============================] - 1s 751us/sample - loss: 0.4330 - accuracy: 0.8588\nEpoch 6/10\n956/956 [==============================] - 1s 756us/sample - loss: 0.3588 - accuracy: 0.8870\nEpoch 7/10\n956/956 [==============================] - 1s 761us/sample - loss: 0.3235 - accuracy: 0.8985\nEpoch 8/10\n956/956 [==============================] - 1s 764us/sample - loss: 0.2827 - accuracy: 0.9236\nEpoch 9/10\n956/956 [==============================] - 1s 760us/sample - loss: 0.2361 - accuracy: 0.9341\nEpoch 10/10\n956/956 [==============================] - 1s 747us/sample - loss: 0.1976 - accuracy: 0.9372\nTrain on 1034 samples\nEpoch 1/10\n1034/1034 [==============================] - 2s 1ms/sample - loss: 1.8231 - accuracy: 0.4255\nEpoch 2/10\n1034/1034 [==============================] - 1s 829us/sample - loss: 1.0318 - accuracy: 0.6412\nEpoch 3/10\n1034/1034 [==============================] - 1s 770us/sample - loss: 0.6984 - accuracy: 0.7834\nEpoch 4/10\n1034/1034 [==============================] - 1s 795us/sample - loss: 0.5508 - accuracy: 0.8191\nEpoch 5/10\n1034/1034 [==============================] - 1s 817us/sample - loss: 0.4628 - accuracy: 0.8520\nEpoch 6/10\n1034/1034 [==============================] - 1s 777us/sample - loss: 0.3868 - accuracy: 0.8752\nEpoch 7/10\n1034/1034 [==============================] - 1s 771us/sample - loss: 0.3158 - accuracy: 0.9023\nEpoch 8/10\n1034/1034 [==============================] - 1s 761us/sample - loss: 0.2612 - accuracy: 0.9159\nEpoch 9/10\n1034/1034 [==============================] - 1s 788us/sample - loss: 0.2253 - accuracy: 0.9304\nEpoch 10/10\n1034/1034 [==============================] - 1s 824us/sample - loss: 0.1963 - accuracy: 0.9323\nTrain on 973 samples\nEpoch 1/10\n973/973 [==============================] - 1s 1ms/sample - loss: 1.9346 - accuracy: 0.3710\nEpoch 2/10\n973/973 [==============================] - 1s 775us/sample - loss: 1.0221 - accuracy: 0.6773\nEpoch 3/10\n973/973 [==============================] - 1s 775us/sample - loss: 0.6739 - accuracy: 0.7718\nEpoch 4/10\n973/973 [==============================] - 1s 767us/sample - loss: 0.5436 - accuracy: 0.8345\nEpoch 5/10\n973/973 [==============================] - 1s 774us/sample - loss: 0.4171 - accuracy: 0.8684\nEpoch 6/10\n973/973 [==============================] - 1s 752us/sample - loss: 0.3605 - accuracy: 0.8849\nEpoch 7/10\n973/973 [==============================] - 1s 760us/sample - loss: 0.2986 - accuracy: 0.9054\nEpoch 8/10\n973/973 [==============================] - 1s 746us/sample - loss: 0.2782 - accuracy: 0.9106\nEpoch 9/10\n973/973 [==============================] - 1s 754us/sample - loss: 0.2159 - accuracy: 0.9301\nEpoch 10/10\n973/973 [==============================] - 1s 785us/sample - loss: 0.1947 - accuracy: 0.9383\nTrain on 980 samples\nEpoch 1/10\n980/980 [==============================] - 1s 1ms/sample - loss: 1.9523 - accuracy: 0.3469\nEpoch 2/10\n980/980 [==============================] - 1s 886us/sample - loss: 1.0069 - accuracy: 0.6837\nEpoch 3/10\n980/980 [==============================] - 1s 816us/sample - loss: 0.6799 - accuracy: 0.7622\nEpoch 4/10\n980/980 [==============================] - 1s 762us/sample - loss: 0.5566 - accuracy: 0.8173\nEpoch 5/10\n980/980 [==============================] - 1s 755us/sample - loss: 0.4789 - accuracy: 0.8520\nEpoch 6/10\n980/980 [==============================] - 1s 753us/sample - loss: 0.3763 - accuracy: 0.8939\nEpoch 7/10\n980/980 [==============================] - 1s 748us/sample - loss: 0.3459 - accuracy: 0.8949\nEpoch 8/10\n980/980 [==============================] - 1s 750us/sample - loss: 0.2966 - accuracy: 0.9041\nEpoch 9/10\n980/980 [==============================] - 1s 745us/sample - loss: 0.2407 - accuracy: 0.9173\nEpoch 10/10\n980/980 [==============================] - 1s 751us/sample - loss: 0.2220 - accuracy: 0.9327\nTrain on 980 samples\nEpoch 1/10\n980/980 [==============================] - 1s 1ms/sample - loss: 1.9361 - accuracy: 0.3490\nEpoch 2/10\n980/980 [==============================] - 1s 748us/sample - loss: 0.9982 - accuracy: 0.6898\nEpoch 3/10\n980/980 [==============================] - 1s 749us/sample - loss: 0.6464 - accuracy: 0.7786\nEpoch 4/10\n980/980 [==============================] - 1s 744us/sample - loss: 0.5195 - accuracy: 0.8286\nEpoch 5/10\n980/980 [==============================] - 1s 746us/sample - loss: 0.4367 - accuracy: 0.8663\nEpoch 6/10\n980/980 [==============================] - 1s 750us/sample - loss: 0.3483 - accuracy: 0.8827\nEpoch 7/10\n980/980 [==============================] - 1s 867us/sample - loss: 0.3233 - accuracy: 0.8878\nEpoch 8/10\n980/980 [==============================] - 1s 772us/sample - loss: 0.2601 - accuracy: 0.9173\nEpoch 9/10\n980/980 [==============================] - 1s 749us/sample - loss: 0.1993 - accuracy: 0.9408\nEpoch 10/10\n980/980 [==============================] - 1s 742us/sample - loss: 0.1578 - accuracy: 0.9592\nTrain on 994 samples\nEpoch 1/10\n994/994 [==============================] - 1s 1ms/sample - loss: 1.8779 - accuracy: 0.4175\nEpoch 2/10\n994/994 [==============================] - 1s 759us/sample - loss: 0.9426 - accuracy: 0.6932\nEpoch 3/10\n994/994 [==============================] - 1s 780us/sample - loss: 0.6534 - accuracy: 0.7827\nEpoch 4/10\n994/994 [==============================] - 1s 794us/sample - loss: 0.5421 - accuracy: 0.8290\nEpoch 5/10\n994/994 [==============================] - 1s 763us/sample - loss: 0.4522 - accuracy: 0.8521\nEpoch 6/10\n994/994 [==============================] - 1s 759us/sample - loss: 0.3542 - accuracy: 0.8773\nEpoch 7/10\n"
]
],
[
[
"# Evaluate the performance of the trained models on unpoisoned data\nThe performance of the models appears normal. We see that for the DPA models, the performance drops slightly as the ensemble size increases",
"_____no_output_____"
]
],
[
[
"clean_preds = np.argmax(model.predict(x_test), axis=1)\nclean_correct = np.sum(clean_preds == np.argmax(y_test, axis=1))\nclean_total = y_test.shape[0]\n\nclean_acc = clean_correct / clean_total\nprint(\"\\nClean test set accuracy (model): %.2f%%\" % (clean_acc * 100))\n\n# Display image, label, and prediction for a clean sample to show how the poisoned model classifies a clean sample\n\nc = 0 # class to display\ni = 0 # image of the class to display\n\nc_idx = np.where(np.argmax(y_test, 1) == c)[0][i] # index of the image in clean arrays\n\nplt.imshow(x_test[c_idx].squeeze())\nplt.show()\nclean_label = c\nprint(\"Prediction: \" + str(clean_preds[c_idx]))",
"\nClean test set accuracy (model): 98.12%\n"
],
[
"clean_preds = np.argmax(dpa_model_10.predict(x_test), axis=1)\nclean_correct = np.sum(clean_preds == np.argmax(y_test, axis=1))\nclean_total = y_test.shape[0]\n\nclean_acc = clean_correct / clean_total\nprint(\"\\nClean test set accuracy (DPA model_10): %.2f%%\" % (clean_acc * 100))\n\n# Display image, label, and prediction for a clean sample to show how the poisoned model classifies a clean sample\n\nc = 0 # class to display\ni = 0 # image of the class to display\n\nc_idx = np.where(np.argmax(y_test, 1) == c)[0][i] # index of the image in clean arrays\n\nplt.imshow(x_test[c_idx].squeeze())\nplt.show()\nclean_label = c\nprint(\"Prediction: \" + str(clean_preds[c_idx]))",
"\nClean test set accuracy (DPA model_10): 93.98%\n"
],
[
"clean_preds = np.argmax(dpa_model_20.predict(x_test), axis=1)\nclean_correct = np.sum(clean_preds == np.argmax(y_test, axis=1))\nclean_total = y_test.shape[0]\n\nclean_acc = clean_correct / clean_total\nprint(\"\\nClean test set accuracy (DPA model_20): %.2f%%\" % (clean_acc * 100))\n\n# Display image, label, and prediction for a clean sample to show how the poisoned model classifies a clean sample\n\nc = 0 # class to display\ni = 0 # image of the class to display\n\nc_idx = np.where(np.argmax(y_test, 1) == c)[0][i] # index of the image in clean arrays\n\nplt.imshow(x_test[c_idx].squeeze())\nplt.show()\nclean_label = c\nprint(\"Prediction: \" + str(clean_preds[c_idx]))",
"\nClean test set accuracy (DPA model_20): 90.98%\n"
],
[
"clean_preds = np.argmax(dpa_model_30.predict(x_test), axis=1)\nclean_correct = np.sum(clean_preds == np.argmax(y_test, axis=1))\nclean_total = y_test.shape[0]\n\nclean_acc = clean_correct / clean_total\nprint(\"\\nClean test set accuracy (DPA model_30): %.2f%%\" % (clean_acc * 100))\n\n# Display image, label, and prediction for a clean sample to show how the poisoned model classifies a clean sample\n\nc = 0 # class to display\ni = 0 # image of the class to display\n\nc_idx = np.where(np.argmax(y_test, 1) == c)[0][i] # index of the image in clean arrays\n\nplt.imshow(x_test[c_idx].squeeze())\nplt.show()\nclean_label = c\nprint(\"Prediction: \" + str(clean_preds[c_idx]))",
"\nClean test set accuracy (DPA model_30): 89.54%\n"
]
],
[
[
"# Evaluate the performance of the trained models on poisoned data\nWhen the trigger is added, we see a shift in performance. The single model performs the worst as no defense is in place to mitigate the effect of the poisoned. The DPA models show some robustnesss to the poison as they partition the training data, which spreads the effect of the poison between models in the ensemble.",
"_____no_output_____"
]
],
[
[
"not_target = np.logical_not(np.all(y_test == targets, axis=1))\npx_test, py_test = backdoor.poison(x_test[not_target], y_test[not_target])\n\npoison_preds = np.argmax(model.predict(px_test), axis=1)\nclean_correct = np.sum(poison_preds == np.argmax(y_test[not_target], axis=1))\nclean_total = y_test.shape[0]\n\nclean_acc = clean_correct / clean_total\nprint(\"\\nPoison test set accuracy (model): %.2f%%\" % (clean_acc * 100))\n\nc = 0 # index to display\nplt.imshow(px_test[c].squeeze())\nplt.show()\nclean_label = c\nprint(\"Prediction: \" + str(poison_preds[c]))",
"\nPoison test set accuracy (model): 0.00%\n"
],
[
"poison_preds = np.argmax(dpa_model_10.predict(px_test), axis=1)\nclean_correct = np.sum(poison_preds == np.argmax(y_test[not_target], axis=1))\nclean_total = y_test.shape[0]\n\nclean_acc = clean_correct / clean_total\nprint(\"\\nPoison test set accuracy (DPA model_10): %.2f%%\" % (clean_acc * 100))\n\nc = 0 # index to display\nplt.imshow(px_test[c].squeeze())\nplt.show()\nclean_label = c\nprint(\"Prediction: \" + str(poison_preds[c]))",
"\nPoison test set accuracy (DPA model_10): 59.01%\n"
],
[
"poison_preds = np.argmax(dpa_model_20.predict(px_test), axis=1)\nclean_correct = np.sum(poison_preds == np.argmax(y_test[not_target], axis=1))\nclean_total = y_test.shape[0]\n\nclean_acc = clean_correct / clean_total\nprint(\"\\nPoison test set accuracy (DPA model_20): %.2f%%\" % (clean_acc * 100))\n\nc = 0 # index to display\nplt.imshow(px_test[c].squeeze())\nplt.show()\nclean_label = c\nprint(\"Prediction: \" + str(poison_preds[c]))",
"\nPoison test set accuracy (DPA model_20): 68.60%\n"
],
[
"poison_preds = np.argmax(dpa_model_30.predict(px_test), axis=1)\nclean_correct = np.sum(poison_preds == np.argmax(y_test[not_target], axis=1))\nclean_total = y_test.shape[0]\n\nclean_acc = clean_correct / clean_total\nprint(\"\\nPoison test set accuracy (DPA model_30): %.2f%%\" % (clean_acc * 100))\n\nc = 0 # index to display\nplt.imshow(px_test[c].squeeze())\nplt.show()\nclean_label = c\nprint(\"Prediction: \" + str(poison_preds[c]))",
"\nPoison test set accuracy (DPA model_30): 70.40%\n"
]
]
] | [
"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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
eccf64504af0d8c65897481138aba52e4f518568 | 58,978 | ipynb | Jupyter Notebook | tutorials/training/source_zh_cn/quick_start/linear_regression.ipynb | firmiana/docs | f1bd3c122931fe7654e684ac2a1f879c82a62550 | [
"Apache-2.0",
"CC-BY-4.0"
] | 1 | 2021-01-25T06:05:55.000Z | 2021-01-25T06:05:55.000Z | tutorials/training/source_zh_cn/quick_start/linear_regression.ipynb | firmiana/docs | f1bd3c122931fe7654e684ac2a1f879c82a62550 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | tutorials/training/source_zh_cn/quick_start/linear_regression.ipynb | firmiana/docs | f1bd3c122931fe7654e684ac2a1f879c82a62550 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | 90.457055 | 14,864 | 0.847418 | [
[
[
"# 实现简单线性函数拟合\n\n作者:[杨奕](https://github.com/helloyesterday) 编辑:[吕明赋](https://gitee.com/lvmingfu)\n\n`Linux` `Windows` `Ascend` `GPU` `CPU` `全流程` `初级` `中级` `高级`\n\n[](https://gitee.com/mindspore/docs/blob/master/tutorials/training/source_zh_cn/quick_start/linear_regression.ipynb) [](https://obs.dualstack.cn-north-4.myhuaweicloud.com/mindspore-website/notebook/master/mindspore_linear_regression.ipynb) [](https://console.huaweicloud.com/modelarts/?region=cn-north-4#/notebook/loading?share-url-b64=aHR0cHM6Ly9vYnMuZHVhbHN0YWNrLmNuLW5vcnRoLTQubXlodWF3ZWljbG91ZC5jb20vbWluZHNwb3JlLXdlYnNpdGUvbm90ZWJvb2svbW9kZWxhcnRzL21pbmRzcG9yZV9saW5lYXJfcmVncmVzc2lvbi5pcHluYg==&image_id=65f636a0-56cf-49df-b941-7d2a07ba8c8c) [](https://www.huaweicloud.com/ascend/codeLab_MindSpore/Linear_Regression)",
"_____no_output_____"
],
[
"## 概述\n\n回归问题算法通常是利用一系列属性来预测一个值,预测的值是连续的。例如给出一套房子的一些特征数据,如面积、卧室数等等来预测房价,利用最近一周的气温变化和卫星云图来预测未来的气温情况等。如果一套房子实际价格为500万元,通过回归分析的预测值为499万元,则认为这是一个比较好的回归分析。在机器学习问题中,常见的回归分析有线性回归、多项式回归、逻辑回归等。本例子介绍线性回归算法,并通过MindSpore进行线性回归AI训练体验。\n\n整体流程如下:\n\n1. 生成数据集\n2. 定义训练网络\n3. 定义前向传播网络与反向传播网络并关联\n4. 拟合过程可视化准备\n5. 执行训练",
"_____no_output_____"
],
[
"> 本文档适用于CPU、GPU和Ascend环境。本例的源代码地址:<https://gitee.com/mindspore/docs/blob/master/tutorials/tutorial_code/linear_regression.py>。",
"_____no_output_____"
],
[
"## 环境准备\n\n设置MindSpore运行配置",
"_____no_output_____"
]
],
[
[
"from mindspore import context\n\ncontext.set_context(mode=context.GRAPH_MODE, device_target=\"CPU\")",
"_____no_output_____"
]
],
[
[
"`GRAPH_MODE`:图模式。\n\n`device_target`:设置MindSpore的训练硬件为CPU。\n\n> 本教程代码依赖`matplotlib`第三方支持包,可使用命令`pip install matplotlib`安装。",
"_____no_output_____"
],
[
"## 生成数据集\n\n### 定义数据集生成函数\n\n`get_data`用于生成训练数据集和测试数据集。由于拟合的是线性数据,假定要拟合的目标函数为:$f(x)=2x+3$,那么我们需要的训练数据集应随机分布于函数周边,这里采用了$f(x)=2x+3+noise$的方式生成,其中`noise`为遵循标准正态分布规律的随机数值。",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\ndef get_data(num, w=2.0, b=3.0):\n for _ in range(num):\n x = np.random.uniform(-10.0, 10.0)\n noise = np.random.normal(0, 1)\n y = x * w + b + noise\n yield np.array([x]).astype(np.float32), np.array([y]).astype(np.float32)",
"_____no_output_____"
]
],
[
[
"使用`get_data`生成50组测试数据,并可视化。",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n\neval_data = list(get_data(50))\nx_target_label = np.array([-10, 10, 0.1])\ny_target_label = x_target_label * 2 + 3\nx_eval_label,y_eval_label = zip(*eval_data)\n\nplt.scatter(x_eval_label, y_eval_label, color=\"red\", s=5)\nplt.plot(x_target_label, y_target_label, color=\"green\")\nplt.title(\"Eval data\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"上图中绿色线条部分为目标函数,红点部分为验证数据`eval_data`。",
"_____no_output_____"
],
[
"### 定义数据增强函数\n\n使用MindSpore的数据增强函数,将数据进行增强操作,操作解释如下:\n\n- `ds.GeneratorDataset`:将生成的数据转换为MindSpore的数据集,并且将生成的数据的x,y值存入到`data`和`label`的数组中。\n- `batch`:将`batch_size`个数据组合成一个batch。\n- `repeat`:将数据集数量倍增。",
"_____no_output_____"
]
],
[
[
"from mindspore import dataset as ds\n\ndef create_dataset(num_data, batch_size=16, repeat_size=1):\n input_data = ds.GeneratorDataset(list(get_data(num_data)), column_names=['data','label'])\n input_data = input_data.batch(batch_size)\n input_data = input_data.repeat(repeat_size)\n return input_data",
"_____no_output_____"
]
],
[
[
"使用数据集增强函数生成训练数据,并查看训练数据的格式。",
"_____no_output_____"
]
],
[
[
"data_number = 1600\nbatch_number = 16\nrepeat_number = 1\n\nds_train = create_dataset(data_number, batch_size=batch_number, repeat_size=repeat_number) \nprint(\"The dataset size of ds_train:\", ds_train.get_dataset_size())\ndict_datasets = next(ds_train.create_dict_iterator())\n\nprint(dict_datasets.keys())\nprint(\"The x label value shape:\", dict_datasets[\"data\"].shape)\nprint(\"The y label value shape:\", dict_datasets[\"label\"].shape)",
"The dataset size of ds_train: 100\ndict_keys(['data', 'label'])\nThe x label value shape: (16, 1)\nThe y label value shape: (16, 1)\n"
]
],
[
[
"通过定义的`create_dataset`将生成的1600个数据增强为了100组shape为16x1的数据集。",
"_____no_output_____"
],
[
"## 定义训练网络\n\n在MindSpore中使用`nn.Dense`生成单个数据输入,单个数据输出的线性函数模型:\n\n$$f(x)=wx+b\\tag{1}$$\n\n并使用Normal算子随机初始化权重$w$和$b$。",
"_____no_output_____"
]
],
[
[
"from mindspore.common.initializer import Normal\nfrom mindspore import nn\n\nclass LinearNet(nn.Cell):\n def __init__(self):\n super(LinearNet, self).__init__()\n self.fc = nn.Dense(1, 1, Normal(0.02), Normal(0.02))\n \n def construct(self, x):\n x = self.fc(x)\n return x",
"_____no_output_____"
]
],
[
[
"调用网络查看初始化的模型参数。",
"_____no_output_____"
]
],
[
[
"net = LinearNet()\nmodel_params = net.trainable_params()\nfor param in model_params:\n print(param, param.asnumpy())",
"Parameter (name=fc.weight) [[-0.02289871]]\nParameter (name=fc.bias) [0.01492652]\n"
]
],
[
[
"初始化网络模型后,接下来将初始化的网络函数和训练数据集进行可视化,了解拟合前的模型函数情况。",
"_____no_output_____"
]
],
[
[
"from mindspore import Tensor\n\nx_model_label = np.array([-10, 10, 0.1])\ny_model_label = (x_model_label * Tensor(model_params[0]).asnumpy()[0][0] + \n Tensor(model_params[1]).asnumpy()[0])\n\nplt.axis([-10, 10, -20, 25])\nplt.scatter(x_eval_label, y_eval_label, color=\"red\", s=5)\nplt.plot(x_model_label, y_model_label, color=\"blue\")\nplt.plot(x_target_label, y_target_label, color=\"green\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"从上图中可以看出,蓝色线条的初始化模型函数与绿色线条的目标函数还是有较大的差别的。",
"_____no_output_____"
],
[
"## 定义前向传播网络与反向传播网络并关联",
"_____no_output_____"
],
[
"接下来需要定义模型的损失函数,这里采用均方误差(MSE,Mean Squared Error)的方法用于判断拟合的效果如何,即均方误差值越小,拟合的效果越好,其损失损失函数公式为:\n\n$$J(w)=\\frac{1}{2m}\\sum_{i=1}^m(h(x_i)-y^{(i)})^2\\tag{2}$$\n\n假设训练数据第$i$个数据为$(x_i,y^{(i)})$,公式2中的参数解释如下:\n\n- $J(w)$为损失值。\n\n- $m$为样本数据的数量,本例中$m$的值为`batch_number`。\n\n- $h(x_i)$为第$i$个数据的$x_i$值代入模型网络(公式1)后的预测值。\n\n- $y^{(i)}$为第$i$个数据中的$y^{(i)}$值(label值)。\n\n### 定义前向传播网络\n\n前向传播网络包含两个部分,其中:\n\n1. 将参数带入到模型网络中得出预测值。\n2. 使用预测值和训练数据计算出loss值。\n\n在MindSpore中使用如下方式实现。",
"_____no_output_____"
]
],
[
[
"net = LinearNet()\nnet_loss = nn.loss.MSELoss()",
"_____no_output_____"
]
],
[
[
"### 定义反向传播网络\n\n反向传播网络的目标是不断变换权重值,使得loss值取得最小值,一般的在线性网络中采用权重更新公式:\n\n$$w_{t}=w_{t-1}-\\alpha\\frac{\\partial{J(w_{t-1})}}{\\partial{w}}\\tag{3}$$\n\n公式3参数解释:\n\n- $w_{t}$为迭代后的权重值。\n- $w_{t-1}$为迭代前的权重值。\n- $\\alpha$为学习率。\n- $\\frac{\\partial{J(w_{t-1}\\ )}}{\\partial{w}}$为损失函数对权重$w_{t-1}$的微分。\n\n函数中所有的权重值更新完成后,将值传入到模型函数中,这个过程就是反向传播过程,实现此过程需要使用MindSpore中的优化器函数,如下:",
"_____no_output_____"
]
],
[
[
"opt = nn.Momentum(net.trainable_params(), learning_rate=0.005, momentum=0.9)",
"_____no_output_____"
]
],
[
[
"### 关联前向和反向传播网络\n\n定义完成前向传播和反向传播后,在MindSpore中需要调用`Model`函数,将前面定义的网络,损失函数,优化器函数关联起来,使之变成完整的计算网络。",
"_____no_output_____"
]
],
[
[
"from mindspore import Model\n\nmodel = Model(net, net_loss, opt)",
"_____no_output_____"
]
],
[
[
"## 拟合过程可视化准备\n\n### 定义绘图函数\n\n为了使得整个训练过程更容易理解,需要将训练过程的测试数据、目标函数和模型网络进行可视化,这里定义了可视化函数,将在每个step训练结束后调用,展示模型网络的拟合过程。",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport time\n\ndef plot_model_and_datasets(net, eval_data):\n weight = net.trainable_params()[0]\n bias = net.trainable_params()[1]\n x = np.arange(-10, 10, 0.1)\n y = x * Tensor(weight).asnumpy()[0][0] + Tensor(bias).asnumpy()[0]\n x1, y1 = zip(*eval_data)\n x_target = x\n y_target = x_target * 2 + 3\n \n plt.axis([-11, 11, -20, 25])\n plt.scatter(x1, y1, color=\"red\", s=5)\n plt.plot(x, y, color=\"blue\")\n plt.plot(x_target, y_target, color=\"green\")\n plt.show()\n time.sleep(0.2)",
"_____no_output_____"
]
],
[
[
"### 定义回调函数\n\nMindSpore提供的工具,可对模型训练过程进行自定义控制,这里在`step_end`中调用可视化函数,展示拟合过程。更多的使用可参考[官网说明](https://www.mindspore.cn/tutorial/training/zh-CN/master/advanced_use/custom_debugging_info.html#callback)\n\n- `display.clear_output`:清除打印内容,实现动态拟合效果。",
"_____no_output_____"
]
],
[
[
"from IPython import display\nfrom mindspore.train.callback import Callback\n\nclass ImageShowCallback(Callback):\n def __init__(self, net, eval_data):\n self.net = net\n self.eval_data = eval_data\n \n def step_end(self, run_context):\n plot_model_and_datasets(self.net, self.eval_data)\n display.clear_output(wait=True)",
"_____no_output_____"
]
],
[
[
"## 执行训练\n\n完成以上过程后,可以使用训练数`ds_train`对模型训练,这里调用`model.train`进行,其中参数解释:\n\n- `epoch`:训练迭代的整个数据集的次数。\n- `ds_train`:训练数据集。\n- `callbacks`:训练过程中需要调用的回调函数。\n- `dataset_sink_model`:数据集下沉模式,支持Ascend、GPU计算平台,本例为CPU计算平台设置为False。",
"_____no_output_____"
]
],
[
[
"\nfrom mindspore.train.callback import LossMonitor\n\nepoch = 1\nimageshow_cb = ImageShowCallback(net, eval_data)\nmodel.train(epoch, ds_train, callbacks=[imageshow_cb], dataset_sink_mode=False)\n\nplot_model_and_datasets(net, eval_data)\nfor net_param in net.trainable_params():\n print(net_param, net_param.asnumpy())",
"_____no_output_____"
]
],
[
[
"训练完成后打印出最终模型的权重参数,其中weight接近于2.0,bias接近于3.0,模型训练完成,符合预期。",
"_____no_output_____"
],
[
"## 总结\n\n本次体验我们了解了线性拟合的算法原理,并在MindSpore框架下实现了相应的算法定义,了解了线性拟合这类的线性回归模型在MindSpore中的训练过程,并最终拟合出了一条接近目标函数的模型函数。另外有兴趣的可以调整数据集的生成区间从(-10,10)扩展到(-100,100),看看权重值是否更接近目标函数;调整学习率大小,看看拟合的效率是否有变化;当然也可以探索如何使用MindSpore拟合$f(x)=ax^2+bx+c$这类的二次函数或者更高次的函数。",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
eccf6d7e6b184d6818de7df2c642ea21a82bcc6f | 13,867 | ipynb | Jupyter Notebook | examples/colab/Recall_constraint_estimator.ipynb | RMKruse/tensorflow_constrained_optimization | e7c3c3deec305fb91193e7b063062e11b7398e5f | [
"Apache-2.0"
] | 276 | 2019-01-24T19:49:49.000Z | 2022-03-29T15:50:58.000Z | examples/colab/Recall_constraint_estimator.ipynb | RMKruse/tensorflow_constrained_optimization | e7c3c3deec305fb91193e7b063062e11b7398e5f | [
"Apache-2.0"
] | 13 | 2019-04-29T00:25:36.000Z | 2022-03-18T23:13:16.000Z | examples/colab/Recall_constraint_estimator.ipynb | RMKruse/tensorflow_constrained_optimization | e7c3c3deec305fb91193e7b063062e11b7398e5f | [
"Apache-2.0"
] | 51 | 2019-01-26T00:45:01.000Z | 2022-02-16T11:38:33.000Z | 34.239506 | 319 | 0.542078 | [
[
[
"##### Copyright 2021 The TensorFlow Constrained Optimization Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n> http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.",
"_____no_output_____"
],
[
"## Problem Setup\n\nIn this colab, we'll show how to use the TF Constrained Optimization (TFCO) library with canned TF estimators. We demonstrate this on a simple recall-constrained optimization problem on simulated data: we seek a classifier that minimizes the average hinge loss while constraining recall to be at least 90%.\n\nWe'll start with the required imports:",
"_____no_output_____"
]
],
[
[
"import math\nimport numpy as np\nimport os\nimport shutil\nimport tensorflow.compat.v2 as tf",
"_____no_output_____"
],
[
"# Tensorflow constrained optimization library\n!pip install git+https://github.com/google-research/tensorflow_constrained_optimization\nimport tensorflow_constrained_optimization as tfco",
"_____no_output_____"
]
],
[
[
"We'll next create a simple simulated dataset by sampling 1000 random 10-dimensional feature vectors from a Gaussian, finding their labels using a random \"ground truth\" linear model, and then adding noise by randomly flipping 200 labels.",
"_____no_output_____"
]
],
[
[
"# Create a simulated 10-dimensional training dataset consisting of 1000 labeled\n# examples, of which 800 are labeled correctly and 200 are mislabeled.\nnum_examples = 1000\nnum_mislabeled_examples = 200\ndimension = 10\n# We will constrain the recall to be at least 90%.\nrecall_lower_bound = 0.9\n\n# Create random \"ground truth\" parameters for a linear model.\nground_truth_weights = np.random.normal(size=dimension) / math.sqrt(dimension)\nground_truth_threshold = 0\n\n# Generate a random set of features for each example.\nfeatures = np.random.normal(size=(num_examples, dimension)).astype(\n np.float32) / math.sqrt(dimension)\n# Compute the labels from these features given the ground truth linear model.\nlabels = (np.matmul(features, ground_truth_weights) >\n ground_truth_threshold).astype(np.float32)\n# Add noise by randomly flipping num_mislabeled_examples labels.\nmislabeled_indices = np.random.choice(\n num_examples, num_mislabeled_examples, replace=False)\nlabels[mislabeled_indices] = 1 - labels[mislabeled_indices]\n\n# Constant Tensors containing the labels and features.\nconstant_labels = tf.constant(labels, dtype=tf.float32)\nconstant_features = tf.constant(features, dtype=tf.float32)",
"_____no_output_____"
]
],
[
[
"## Training with a Canned Estimator\n\nWe now show how to train a canned `LinearEstimator` using the custom head that TFCO provides. For this, we'll need to create function that takes \"logits\", \"labels\", \"features\", and an (optional) \"weight_column\", and returns a\n`RateMinimizationProblem`.",
"_____no_output_____"
]
],
[
[
"def problem_fn(logits, labels, features, weight_column=None):\n # Minimize error rate s.t. recall >= recall_lower_bound.\n del features, weight_column\n context = tfco.rate_context(logits, labels)\n objective = tfco.error_rate(context)\n constraints = [tfco.recall(context) >= recall_lower_bound]\n return tfco.RateMinimizationProblem(objective, constraints)",
"_____no_output_____"
]
],
[
[
"Next, we create a custom `tfco.Head` that wraps around an existing binary classification head.",
"_____no_output_____"
]
],
[
[
"binary_head = tf.estimator.BinaryClassHead()\nhead = tfco.HeadV2(binary_head, problem_fn)",
"_____no_output_____"
]
],
[
[
"All that remains is to set up the input pipeline. We first create `feature_columns` to convert the dataset into a format that can be processed by an estimator.",
"_____no_output_____"
]
],
[
[
"feature_columns = []\nfor ii in range(features.shape[-1]):\n feature_columns.append(\n tf.feature_column.numeric_column(str(ii), dtype=tf.float32))",
"_____no_output_____"
]
],
[
[
"We next construct the input functions that return the data to be used by the estimator for training and evaluation.",
"_____no_output_____"
]
],
[
[
"def make_input_fn(\n data_df, label_df, num_epochs=10, shuffle=True, batch_size=32):\n def input_fn():\n features_dict = {\n str(ii): features[:, ii] for ii in range(features.shape[-1])}\n ds = tf.data.Dataset.from_tensor_slices((features_dict, labels))\n if shuffle:\n ds = ds.shuffle(1000)\n ds = ds.batch(batch_size).repeat(num_epochs)\n return ds\n return input_fn\n\ntrain_input_fn = make_input_fn(features, labels, num_epochs=1000)\ntest_input_fn = make_input_fn(features, labels, num_epochs=1, shuffle=False)",
"_____no_output_____"
]
],
[
[
"We are now ready to train the estimator. We'll pass the `ProxyLagrangianOptimizer` that TFCO provides to the estimator. We could also instead use a standard TF optimizer here.",
"_____no_output_____"
]
],
[
[
"# Create a temporary model directory.\nmodel_dir = \"tfco_tmp\"\nif os.path.exists(model_dir):\n shutil.rmtree(model_dir)\n\n# Train estimator with TFCO's custom optimizer.\noptimizer = tfco.ProxyLagrangianOptimizer(\n tf.keras.optimizers.Adagrad(1))\nestimator = tf.estimator.LinearEstimator(\n head, feature_columns, model_dir=model_dir, \n optimizer=optimizer)\nestimator.train(train_input_fn, steps=1000) ",
"_____no_output_____"
],
[
"estimator.evaluate(test_input_fn)",
"_____no_output_____"
]
],
[
[
"Notice that the recall is close to 90% as desired.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
eccf712d0331e6b9d977d48272d465ec43c1b3bd | 8,071 | ipynb | Jupyter Notebook | dataset.ipynb | tvotan/mlugs_gnn | efd7afab6f47a9f388ae4783314d4ac77bfb53fa | [
"MIT"
] | null | null | null | dataset.ipynb | tvotan/mlugs_gnn | efd7afab6f47a9f388ae4783314d4ac77bfb53fa | [
"MIT"
] | null | null | null | dataset.ipynb | tvotan/mlugs_gnn | efd7afab6f47a9f388ae4783314d4ac77bfb53fa | [
"MIT"
] | null | null | null | 34.939394 | 93 | 0.33069 | [
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"df = pd.read_csv('delaney-processed.csv')\ndf.head()",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1128 entries, 0 to 1127\nData columns (total 10 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Compound ID 1128 non-null object \n 1 ESOL predicted log solubility in mols per litre 1128 non-null float64\n 2 Minimum Degree 1128 non-null int64 \n 3 Molecular Weight 1128 non-null float64\n 4 Number of H-Bond Donors 1128 non-null int64 \n 5 Number of Rings 1128 non-null int64 \n 6 Number of Rotatable Bonds 1128 non-null int64 \n 7 Polar Surface Area 1128 non-null float64\n 8 measured log solubility in mols per litre 1128 non-null float64\n 9 smiles 1128 non-null object \ndtypes: float64(4), int64(4), object(2)\nmemory usage: 88.2+ KB\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
eccf7950830e937428e67f1e34577c5595b6b0cf | 40,926 | ipynb | Jupyter Notebook | notebooks/pier_hdf5.ipynb | pdubeau/MMS21 | 2297defa6c7d1694be2122df3b9e33a99f89e720 | [
"Apache-2.0"
] | null | null | null | notebooks/pier_hdf5.ipynb | pdubeau/MMS21 | 2297defa6c7d1694be2122df3b9e33a99f89e720 | [
"Apache-2.0"
] | null | null | null | notebooks/pier_hdf5.ipynb | pdubeau/MMS21 | 2297defa6c7d1694be2122df3b9e33a99f89e720 | [
"Apache-2.0"
] | null | null | null | 52.604113 | 1,541 | 0.430655 | [
[
[
"import sklearn",
"_____no_output_____"
],
[
"sklearn.__version__",
"_____no_output_____"
],
[
"conda list",
"# packages in environment at C:\\Users\\Pierre\\Anaconda3:\nNote: you may need to restart the kernel to use updated packages.\n\n#\n# Name Version Build Channel\n_anaconda_depends 2019.03 py37_0 \n_ipyw_jlab_nb_ext_conf 0.1.0 py37_0 \nalabaster 0.7.12 py37_0 \nanaconda custom py37_1 \nanaconda-client 1.7.2 py37_0 \nanaconda-navigator 1.9.7 py37_0 \nanaconda-project 0.8.4 py_0 \nargh 0.26.2 py37_0 \nasn1crypto 1.3.0 py37_0 \nastroid 2.3.3 py37_0 \nastropy 3.1.2 py37he774522_0 \natomicwrites 1.3.0 py37_1 \nattrs 19.3.0 py_0 \nautopep8 1.4.4 py_0 \nbabel 2.8.0 py_0 \nbackcall 0.1.0 py37_0 \nbackports 1.0 py_2 \nbackports.os 0.1.1 py37_0 \nbackports.shutil_get_terminal_size 1.0.0 py37_2 \nbcrypt 3.1.7 py37he774522_0 \nbeautifulsoup4 4.8.2 py37_0 \nbitarray 1.2.1 py37he774522_0 \nbkcharts 0.2 py37_0 \nblas 1.0 mkl \nbleach 3.1.0 py37_0 \nblosc 1.16.3 h7bd577a_0 \nbokeh 1.0.4 py37_0 \nboto 2.49.0 py37_0 \nbottleneck 1.2.1 py37h452e1ab_1 \nbzip2 1.0.8 he774522_0 \nca-certificates 2020.1.1 0 \ncertifi 2020.4.5.1 py37_0 \ncffi 1.14.0 py37h7a1dbc1_0 \nchardet 3.0.4 py37_1003 \nchart-studio 1.0.0 pypi_0 pypi\nclick 7.1.1 py_0 \ncloudpickle 1.3.0 py_0 \nclyent 1.2.2 py37_1 \ncolorama 0.4.3 py_0 \ncomtypes 1.1.7 py37_0 \nconda 4.8.3 py37_0 \nconda-build 3.17.8 py37_0 \nconda-env 2.6.0 1 \nconda-package-handling 1.6.0 py37h62dcd97_0 \nconda-verify 3.1.1 py37_0 \nconsole_shortcut 0.1.1 3 \ncontextlib2 0.6.0.post1 py_0 \ncryptography 2.8 py37h7a1dbc1_0 \ncurl 7.69.1 h2a8f88b_0 \ncycler 0.10.0 py37_0 \ncython 0.29.15 py37ha925a31_0 \ncytoolz 0.10.1 py37he774522_0 \ndask 1.1.4 py37_1 \ndask-core 1.1.4 py37_1 \ndecorator 4.4.2 py_0 \ndefusedxml 0.6.0 py_0 \ndiff-match-patch 20181111 py_0 \ndistributed 1.28.1 py37_0 \ndocutils 0.16 py37_0 \nentrypoints 0.3 py37_0 \net_xmlfile 1.0.1 py37_0 \nfastcache 1.1.0 py37he774522_0 \nfilelock 3.0.12 py_0 \nflake8 3.7.9 py37_0 \nflask 1.1.1 py_1 \nfreetype 2.9.1 ha9979f8_1 \nfuture 0.18.2 py37_0 \nget_terminal_size 1.0.0 h38e98db_0 \ngevent 1.4.0 py37he774522_0 \nglob2 0.7 py_0 \ngreenlet 0.4.15 py37hfa6e2cd_0 \nh5py 2.9.0 py37h5e291fa_0 \nhdf5 1.10.4 h7ebc959_0 \nheapdict 1.0.1 py_0 \nhtml5lib 1.0.1 py37_0 \nicc_rt 2019.0.0 h0cc432a_1 \nicu 58.2 ha66f8fd_1 \nidna 2.9 py_1 \nimageio 2.5.0 py37_0 \nimagesize 1.2.0 py_0 \nimportlib_metadata 1.5.0 py37_0 \nintel-openmp 2020.0 166 \nintervaltree 3.0.2 py_0 \nipykernel 5.1.4 py37h39e3cac_0 \nipython 7.13.0 py37h5ca1d4c_0 \nipython_genutils 0.2.0 py37_0 \nipywidgets 7.5.1 py_0 \nisort 4.3.21 py37_0 \nitsdangerous 1.1.0 py37_0 \njdcal 1.4.1 py_0 \njedi 0.15.2 py37_0 \njinja2 2.11.1 py_0 \njoblib 0.13.2 pypi_0 pypi\njpeg 9b hb83a4c4_2 \njson5 0.9.4 py_0 \njsonschema 3.2.0 py37_0 \njupyter 1.0.0 py37_7 \njupyter_client 6.1.2 py_0 \njupyter_console 6.1.0 py_0 \njupyter_core 4.6.3 py37_0 \njupyterlab 1.2.6 pyhf63ae98_0 \njupyterlab_server 1.1.0 py_0 \nkeyring 21.1.1 py37_2 \nkiwisolver 1.1.0 py37ha925a31_0 \nkrb5 1.17.1 hc04afaa_0 \nlazy-object-proxy 1.4.3 py37he774522_0 \nlibarchive 3.3.3 h0643e63_5 \nlibcurl 7.69.1 h2a8f88b_0 \nlibiconv 1.15 h1df5818_7 \nliblief 0.9.0 ha925a31_3 \nlibpng 1.6.37 h2a8f88b_0 \nlibsodium 1.0.16 h9d3ae62_0 \nlibspatialindex 1.9.3 h33f27b4_0 \nlibssh2 1.9.0 h7a1dbc1_1 \nlibtiff 4.1.0 h56a325e_0 \nlibxml2 2.9.9 h464c3ec_0 \nlibxslt 1.1.33 h579f668_0 \nllvmlite 0.28.0 py37ha925a31_0 \nlocket 0.2.0 py37_1 \nlxml 4.5.0 py37h1350720_0 \nlz4-c 1.8.1.2 h2fa13f4_0 \nlzo 2.10 h6df0209_2 \nm2w64-gcc-libgfortran 5.3.0 6 \nm2w64-gcc-libs 5.3.0 7 \nm2w64-gcc-libs-core 5.3.0 7 \nm2w64-gmp 6.1.0 2 \nm2w64-libwinpthread-git 5.0.0.4634.697f757 2 \nmarkupsafe 1.1.1 py37he774522_0 \nmatplotlib 3.0.3 py37hc8f65d3_0 \nmccabe 0.6.1 py37_1 \nmenuinst 1.4.16 py37he774522_0 \nmistune 0.8.4 py37he774522_0 \nmkl 2020.0 166 \nmkl-service 2.3.0 py37hb782905_0 \nmkl_fft 1.0.10 py37h14836fe_0 \nmkl_random 1.0.2 py37h343c172_0 \nmore-itertools 8.2.0 py_0 \nmpmath 1.1.0 py37_0 \nmsgpack-python 1.0.0 py37h74a9793_1 \nmsys2-conda-epoch 20160418 1 \nmultipledispatch 0.6.0 py37_0 \nnavigator-updater 0.2.1 py37_0 \nnbconvert 5.6.1 py37_0 \nnbformat 5.0.4 py_0 \nnetworkx 2.4 py_0 \nnltk 3.4.5 py37_0 \nnose 1.3.7 py37_2 \nnotebook 6.0.3 py37_0 \nnumba 0.43.1 py37hf9181ef_0 \nnumexpr 2.6.9 py37hdce8814_0 \nnumpy 1.16.3 pypi_0 pypi\nnumpy-base 1.16.2 py37hc3f5095_0 \nnumpydoc 0.9.2 py_0 \nolefile 0.46 py37_0 \nopenpyxl 3.0.3 py_0 \nopenssl 1.1.1f he774522_0 "
],
[
"conda activate myenv",
"\npackaging 20.3 py_0 \npandas 0.24.2 py37ha925a31_0 \npandoc 2.2.3.2 0 \npandocfilters 1.4.2 py37_1 \nparamiko 2.7.1 py_0 \nparso 0.5.2 py_0 \npartd 1.1.0 py_0 \npath 13.1.0 py37_0 \npath.py 12.4.0 0 \npathlib2 2.3.5 py37_0 \npathtools 0.1.2 py_1 \npatsy 0.5.1 py37_0 \npep8 1.7.1 py37_0 \npexpect 4.8.0 py37_0 \npickleshare 0.7.5 py37_0 \npillow 7.0.0 py37hcc1f983_0 \npip 20.0.2 pypi_0 pypi\npkginfo 1.5.0.1 py37_0 \nplotly 4.0.0 pypi_0 pypi\npluggy 0.13.1 py37_0 \nply 3.11 py37_0 \npowershell_shortcut 0.0.1 2 \nprometheus_client 0.7.1 py_0 \nprompt-toolkit 3.0.4 py_0 \nprompt_toolkit 3.0.4 0 \npsutil 5.7.0 py37he774522_0 \npy 1.8.1 py_0 \npy-lief 0.9.0 py37ha925a31_3 \npycodestyle 2.5.0 py37_0 \npycosat 0.6.3 py37he774522_0 \npycparser 2.20 py_0 \npycrypto 2.6.1 py37hfa6e2cd_9 \npycurl 7.43.0.5 py37h7a1dbc1_0 \npydocstyle 4.0.1 py_0 \npyflakes 2.1.1 py37_0 \npygments 2.6.1 py_0 \npylint 2.4.4 py37_0 \npynacl 1.3.0 py37h62dcd97_0 \npyodbc 4.0.30 py37ha925a31_0 \npyopenssl 19.1.0 py37_0 \npyparsing 2.4.6 py_0 \npyqt 5.9.2 py37h6538335_2 \npyreadline 2.1 py37_1 \npyrsistent 0.16.0 py37he774522_0 \npysocks 1.7.1 py37_0 \npytables 3.5.1 py37h1da0976_0 \npytest 5.4.1 py37_0 \npytest-arraydiff 0.3 py37h39e3cac_0 \npytest-astropy 0.5.0 py37_0 \npytest-doctestplus 0.3.0 py37_0 \npytest-openfiles 0.4.0 py_0 \npytest-remotedata 0.3.2 py37_0 \npython 3.7.3 h8c8aaf0_0 \npython-dateutil 2.8.1 py_0 \npython-jsonrpc-server 0.3.4 py_0 \npython-language-server 0.31.9 py37_0 \npython-libarchive-c 2.8 py37_13 \npytz 2019.3 py_0 \npywavelets 1.0.2 py37h8c2d366_0 \npywin32 227 py37he774522_1 \npywin32-ctypes 0.2.0 py37_1000 \npywinpty 0.5.7 py37_0 \npyyaml 5.3.1 py37he774522_0 \npyzmq 18.1.1 py37ha925a31_0 \nqdarkstyle 2.8 py_0 \nqt 5.9.7 vc14h73c81de_0 \nqtawesome 0.7.0 py_0 \nqtconsole 4.7.2 py_0 \nqtpy 1.9.0 py_0 \nrequests 2.23.0 py37_0 \nretrying 1.3.3 pypi_0 pypi\nrope 0.16.0 py_0 \nrtree 0.9.3 py37h21ff451_0 \nruamel_yaml 0.15.87 py37he774522_0 \nscikit-image 0.14.2 py37ha925a31_0 \nscikit-learn 0.21.1 pypi_0 pypi\nscipy 1.3.0 pypi_0 pypi\nseaborn 0.9.0 py37_0 \nsend2trash 1.5.0 py37_0 \nsetuptools 46.1.3 py37_0 \nsimplegeneric 0.8.1 py37_2 \nsingledispatch 3.4.0.3 py37_0 \nsip 4.19.8 py37h6538335_0 \nsix 1.14.0 py37_0 \nsnappy 1.1.7 h777316e_3 \nsnowballstemmer 2.0.0 py_0 \nsortedcollections 1.1.2 py37_0 \nsortedcontainers 2.1.0 py37_0 \nsoupsieve 2.0 py_0 \nsphinx 2.4.4 py_0 \nsphinxcontrib 1.0 py37_1 \nsphinxcontrib-applehelp 1.0.2 py_0 \nsphinxcontrib-devhelp 1.0.2 py_0 \nsphinxcontrib-htmlhelp 1.0.3 py_0 \nsphinxcontrib-jsmath 1.0.1 py_0 \nsphinxcontrib-qthelp 1.0.3 py_0 \nsphinxcontrib-serializinghtml 1.1.4 py_0 \nsphinxcontrib-websupport 1.2.1 py_0 \nspyder 4.1.2 py37_0 \nspyder-kernels 1.9.0 py37_0 \nsqlalchemy 1.3.15 py37he774522_1 \nsqlite 3.31.1 he774522_0 \nstatsmodels 0.9.0 py37h452e1ab_0 \nsympy 1.5.1 py37_0 \ntbb 2020.0 h74a9793_0 \ntblib 1.6.0 py_0 \nterminado 0.8.3 py37_0 \ntestpath 0.4.4 py_0 \ntk 8.6.8 hfa6e2cd_0 \ntoolz 0.10.0 py_0 \ntornado 6.0.4 py37he774522_1 \ntqdm 4.44.1 py_0 \ntraitlets 4.3.3 py37_0 \nujson 1.35 py37hfa6e2cd_0 \nunicodecsv 0.14.1 py37_0 \nurllib3 1.25.8 py37_0 \nvc 14.1 h0510ff6_4 \nvs2015_runtime 14.16.27012 hf0eaf9b_1 \nwatchdog 0.10.2 py37_0 \nwcwidth 0.1.9 py_0 \nwebencodings 0.5.1 py37_1 \nwerkzeug 1.0.1 py_0 \nwheel 0.34.2 py37_0 \nwidgetsnbextension 3.5.1 py37_0 \nwin_inet_pton 1.1.0 py37_0 \nwin_unicode_console 0.5 py37_0 \nwincertstore 0.2 py37_0 \nwinpty 0.4.3 4 \nwrapt 1.12.1 py37he774522_1 \nxlrd 1.2.0 py37_0 \nxlsxwriter 1.2.8 py_0 \nxlwings 0.18.0 py37_0 \nxlwt 1.3.0 py37_0 \nxz 5.2.4 h2fa13f4_4 \nyaml 0.1.7 hc54c509_2 \nyapf 0.28.0 py_0 \nzeromq 4.3.1 h33f27b4_3 \nzict 2.0.0 py_0 \nzipp 2.2.0 py_0 \nzlib 1.2.11 h62dcd97_3 \nzstd 1.3.7 h508b16e_0 \n"
],
[
"import numpy as np",
"_____no_output_____"
],
[
"import h5py",
"_____no_output_____"
],
[
"matrix1 = np.random.random(size = (1000,1000))\nmatrix2 = np.random.random(size = (10000, 100))",
"_____no_output_____"
],
[
"with h5py.File('/Users/Pierre/Desktop/hdf5_data.h5', 'w') as hdf:\n hdf.create_dataset('dataset1', data=matrix1)\n hdf.create_dataset('dataset2', data=matrix2)\n ",
"_____no_output_____"
],
[
"with h5py.File('/Users/Pierre/Desktop/hdf5_data.h5', 'r') as hdf:\n ls = list(hdf.keys())\n print('List of datasets in this file: \\n', ls)\n data = hdf.get('dataset1')\n dataset1 = np.array(data)\n print('Shape of dataset1: \\n', dataset1.shape)",
"List of datasets in this file: \n ['dataset1', 'dataset2']\nShape of dataset1: \n (1000, 1000)\n"
],
[
"dataset1",
"_____no_output_____"
],
[
"f = h5py.File('/Users/Pierre/Desktop/hdf5_data.h5', 'r')\nls = list(f.keys())\nf.close()",
"_____no_output_____"
],
[
"ls",
"_____no_output_____"
],
[
"matrix1 = np.random.random(size = (1000,1000))\nmatrix2 = np.random.random(size = (1000,1000))\nmatrix3 = np.random.random(size = (1000,1000))\nmatrix4 = np.random.random(size = (1000,1000))",
"_____no_output_____"
],
[
"with h5py.File('/Users/Pierre/Desktop/hdf5_data1.h5', 'w') as hdf:\n G1 = hdf.create_group('Group1')\n G1.create_dataset('dataset1', data = matrix1)\n G1.create_dataset('dataset4', data = matrix4)\n G21 = hdf.create_group('Group2/SubGroup1')\n G21.create_dataset('dataset3', data = matrix3)\n G22 = hdf.create_group('Group2/SubGroup2')\n G22.create_dataset('dataset2', data = matrix2)",
"_____no_output_____"
],
[
"matrix3",
"_____no_output_____"
],
[
"with h5py.File('/Users/Pierre/Desktop/hdf5_data1.h5', 'r') as hdf:\n base_items = list(hdf.items())\n print('Items in the base directory:', base_items)\n G1 = hdf.get('Group1')\n G1_items = list(G1.items())\n print('Items in Group1:', G1_items)\n dataset4 = np.array(G1.get('dataset4'))\n print(dataset4.shape)\n# print(dataset4.head)",
"Items in the base directory: [('Group1', <HDF5 group \"/Group1\" (2 members)>), ('Group2', <HDF5 group \"/Group2\" (2 members)>)]\nItems in Group1: [('dataset1', <HDF5 dataset \"dataset1\": shape (1000, 1000), type \"<f8\">), ('dataset4', <HDF5 dataset \"dataset4\": shape (1000, 1000), type \"<f8\">)]\n(1000, 1000)\n"
],
[
"with h5py.File('/Users/Pierre/Desktop/hdf5_data1.h5', 'r') as hdf:\n base_items = list(hdf.items())\n print('Items in the base directory:', base_items)\n# G1 = hdf.get('Group1')\n# G1_items = list(G1.items())\n# print('Items in Group1:', G1_items)\n# dataset4 = np.array(G1.get('dataset4'))\n# print(dataset4.shape)\n \n G2 = hdf.get('Group2')\n G2_items = list(G2.items())\n print('Items in Group2:', G2_items)\n G21 = G2.get('/Group2/SubGroup1')\n G21_items = list(G21_items())\n print('Items in Group21:', G21_items)\n dataset3 = np.array(G21.get('dataset3'))\n print(dataset3.shape)",
"Items in the base directory: [('Group1', <HDF5 group \"/Group1\" (2 members)>), ('Group2', <HDF5 group \"/Group2\" (2 members)>)]\nItems in Group2: [('SubGroup1', <HDF5 group \"/Group2/SubGroup1\" (1 members)>), ('SubGroup2', <HDF5 group \"/Group2/SubGroup2\" (1 members)>)]\n"
],
[
"matrix1 = np.random.random(size = (1000,1000))\nmatrix2 = np.random.random(size = (10000, 100))",
"_____no_output_____"
],
[
"# Create the HDF5 file\nhdf = h5py.File('/Users/Pierre/Desktop/test2.h5', 'w')\n\n# Create the datasets\ndataset1 = hdf.create_dataset('dataset1', data=matrix1)\ndataset2 = hdf.create_dataset('dataset2', data=matrix2)\n\n# Set attributes\ndataset1.attrs['CLASS'] = 'DATA MATRIX'\ndataset1.attrs['VERSION'] = '1.1'\n\nhdf.close()",
"_____no_output_____"
],
[
"# Read the HDF5 file\nhdf = h5py.File('/Users/Pierre/Desktop/test.h5', 'r')\nls = list(hdf.keys())\nprint('List of datasets in this file: \\n', ls)\ndata = hdf.get('dataset1')\ndataset1 = np.array(data)\nprint('Shape of dataset1: \\n', dataset1.shape)\n# Read the attributes\nk = list(data.attrs.keys())\nv = list(data.attrs.values())\nprint(k[0])\nprint(v[0])\nprint(data.attrs[k[0]])\n\nhdf.close()",
"List of datasets in this file: \n ['dataset1', 'dataset2']\nShape of dataset1: \n (1000, 1000)\nCLASS\nDATA MATRIX\nDATA MATRIX\n"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"file_path = \"K:/Data/Project/AHT9034-NV/C_Raster/A_Source/GEDI/GEDI02_A_2019191051321_O03251_T04484_02_001_01.h5\"",
"_____no_output_____"
],
[
"hdf = pd.HDFStore(file_path, mode = 'r')",
"_____no_output_____"
],
[
"hdf.groups()",
"_____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"
]
] |
eccf827c822d2a1ba7b0284aaa74fc2ebcadb13b | 2,815 | ipynb | Jupyter Notebook | Day1/Python-Programming-Tutorials-master/a__intro.ipynb | pash20/python-training | 7d63039160dcc2a89b0347d2cfed432c6f31bf6f | [
"Unlicense"
] | null | null | null | Day1/Python-Programming-Tutorials-master/a__intro.ipynb | pash20/python-training | 7d63039160dcc2a89b0347d2cfed432c6f31bf6f | [
"Unlicense"
] | null | null | null | Day1/Python-Programming-Tutorials-master/a__intro.ipynb | pash20/python-training | 7d63039160dcc2a89b0347d2cfed432c6f31bf6f | [
"Unlicense"
] | null | null | null | 37.533333 | 891 | 0.676377 | [
[
[
"## Introduction",
"_____no_output_____"
],
[
"Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.\n\nOften, programmers fall in love with Python because of the increased productivity it provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is written in Python itself, testifying to Python's introspective power. On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.\n\nIn this series of examples you will learns the programming concepts of python.",
"_____no_output_____"
],
[
"### Hello World In Python",
"_____no_output_____"
]
],
[
[
"print(\"Hello World\")",
"Hello World\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
eccf9059326fe634344cc648d0fd4ce62f8b4d67 | 4,814 | ipynb | Jupyter Notebook | examples/Predict/ColabModelCDPrediction.ipynb | kapoorlab/VollSeg | af0a765d76423e52c6470da5bd923e4477746d6e | [
"BSD-3-Clause"
] | 7 | 2021-05-25T14:04:27.000Z | 2022-03-16T07:44:04.000Z | examples/Predict/ColabModelCDPrediction.ipynb | kapoorlab/VollSeg | af0a765d76423e52c6470da5bd923e4477746d6e | [
"BSD-3-Clause"
] | 3 | 2021-11-14T09:50:27.000Z | 2021-12-21T22:37:15.000Z | examples/Predict/ColabModelCDPrediction.ipynb | kapoorlab/VollSeg | af0a765d76423e52c6470da5bd923e4477746d6e | [
"BSD-3-Clause"
] | 1 | 2021-11-22T19:04:48.000Z | 2021-11-22T19:04:48.000Z | 26.021622 | 145 | 0.583506 | [
[
[
"from google.colab import drive\ndrive.mount('/content/drive', force_remount = True)\n%tensorflow_version 2.x\n",
"_____no_output_____"
],
[
"!pip install tiffile\n\n\n!pip install gputools\n\n!pip install imagecodecs\n!pip install vollseg",
"_____no_output_____"
],
[
"import os\nimport glob\nimport sys\nimport numpy as np\nfrom tqdm import tqdm\nfrom tifffile import imread, imwrite\nfrom stardist.models import StarDist3D\nfrom csbdeep.models import Config, CARE\nfrom vollseg import SmartSeedPrediction3D\nos.environ[\"HDF5_USE_FILE_LOCKING\"] = \"FALSE\"\nfrom pathlib import Path\n",
"_____no_output_____"
],
[
"ImageDir = '/content/drive/My Drive/Jakub_Mari_Varun_Analysis/Movies_to_Segment/'\nModel_Dir = '/content/drive/My Drive/Jakub_Mari_Varun_Analysis/TrainedModels/'\n\nSaveDir = ImageDir + 'Results/'\n\nNoiseModelName = 'Marid3f48'\nUNETModelName = 'UNETMariNucleiSeg'\nStarModelName = 'MariNucleiSeg'\nUnetModel = CARE(config = None, name = UNETModelName, basedir = Model_Dir)\nStarModel = StarDist3D(config = None, name = StarModelName, basedir = Model_Dir)\nNoiseModel = CARE(config=None, name=NoiseModelName, basedir=Model_Dir)",
"_____no_output_____"
],
[
"Raw_path = os.path.join(ImageDir, '*.tif')\nfilesRaw = glob.glob(Raw_path)\nfilesRaw.sort\nmin_size = 100\nn_tiles = (1,4,4)\n\nfor fname in filesRaw:\n \n SmartSeedPrediction3D(SaveDir, fname, UnetModel, StarModel,NoiseModel, min_size = min_size, n_tiles = n_tiles, UseProbability = True)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
eccf9064c38c560ca7b37246d093c5e1493a3f7d | 2,761 | ipynb | Jupyter Notebook | sqlite3/db2_to_sqlite.ipynb | pybokeh/jupyter-sql | 5510dbd0ba14794fe530f4dfe3b61911cd26dea5 | [
"MIT"
] | 1 | 2022-03-15T23:03:29.000Z | 2022-03-15T23:03:29.000Z | sqlite3/db2_to_sqlite.ipynb | pybokeh/jupyter-sql | 5510dbd0ba14794fe530f4dfe3b61911cd26dea5 | [
"MIT"
] | null | null | null | sqlite3/db2_to_sqlite.ipynb | pybokeh/jupyter-sql | 5510dbd0ba14794fe530f4dfe3b61911cd26dea5 | [
"MIT"
] | null | null | null | 21.570313 | 118 | 0.533502 | [
[
[
"# PURPOSE",
"_____no_output_____"
],
[
"#### Extract data from mainframe DB2 and then upload to sqlite",
"_____no_output_____"
]
],
[
[
"from sqlalchemy import create_engine\nimport os\nimport pandas as pd\nimport pyodbc",
"_____no_output_____"
],
[
"dsn = 'your_dsn'\nuser = os.getenv('windowsuser')\npwd = os.getenv('mainframepwd')",
"_____no_output_____"
],
[
"with pyodbc.connect(f'DSN={dsn};UID={user};PWD={pwd}') as conn:\n sql = \"\"\"\n SELECT\n some_columns\n FROM\n some_table\n WHERE\n some_criteria\n FOR READ ONLY WITH UR\n \"\"\"\n df = pd.read_sql(sql, conn)",
"_____no_output_____"
],
[
"df = pd.read_clipboard()",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
],
[
"with create_engine('sqlite:///C:/Users/some_user/<path_to_your>/sc_roster.db', echo=False).connect() as conn:\n df.to_sql('sc_associates', conn, if_exists='replace')",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccfa05549d8554840232ca84356b4f17fb78680 | 65,625 | ipynb | Jupyter Notebook | src/reddit/LDA News Articles - Data Set Compilation.ipynb | berkeley-politics-capstone/politics-capstone | 503efa66a930dbf913bad67daa4b38876586949c | [
"MIT"
] | 1 | 2020-07-18T20:25:58.000Z | 2020-07-18T20:25:58.000Z | src/reddit/LDA News Articles - Data Set Compilation.ipynb | berkeley-politics-capstone/politics-capstone | 503efa66a930dbf913bad67daa4b38876586949c | [
"MIT"
] | null | null | null | src/reddit/LDA News Articles - Data Set Compilation.ipynb | berkeley-politics-capstone/politics-capstone | 503efa66a930dbf913bad67daa4b38876586949c | [
"MIT"
] | null | null | null | 62.559581 | 26,016 | 0.663528 | [
[
[
"import gensim\nimport pandas as pd\nimport pickle\nimport seaborn as sns\nimport pyLDAvis.gensim\n\nfrom tqdm._tqdm_notebook import tqdm_notebook as tqdm\n#initialize tqdm\ntqdm.pandas()\nsns.set_style('darkgrid')",
"_____no_output_____"
],
[
"len(topic_titles)",
"_____no_output_____"
],
[
"DATA_DIR = '../../data/reddit/Article_data_2019/'\nuseful_topics = [2,4,6,7,8,9,12,13,14,17,18,19,20,21,22,23,24,26,28,29,30,31,32,33,34,35,38,42,44,45,46,47,48,50,51,\n 52,53,55,58,61,62,63,64,66,67,68,69,70,71,75,77,78,79,80,85,86,87,88,89,91,92,93,96,99]\n\ntopic_titles = ['2020 election', 'trump administration', 'climate change', 'trump foreign policy', 'mueller report', \n 'cohen', 'williamson', '2018 congress', 'border', 'first debate', 'hunder biden', 'town hall', \n 'first debate', 'biden busing', 'female congresswomen', 'nxivm sex cult', 'auto industry', \n 'assange', 'healthcare', 'de blasio', 'buttigieg', 'impeachment', \n 'us economy (socialism vs captialism)', 'economic foreign policy', 'iowa caucus', \n 'north carolina voter fraud', 'north korea', 'jean carroll', '2020 election', 'kavanaugh', \n 'harris', 'mccain', 'aoc', 'sanders', 'border', 'prison reform', 'getty', 'graham', \n '2020 democratic primary', 'stephanopoulos', 'tax fact check', 'generic words', 'o\\'rourke', \n 'media words', 'drugs', 'venezuela', 'tech', 'iran', 'assange', 'random', 'healthcare', \n 'harris', 'student debt', 'russian interference', 'politico', 'booker', 'socialism', \n 'megan davis', 'lgbtq', 'swalwell', 'former counsel for mueller report', 'trump racist', \n 'sanders', 'sanders', 'puerto rico', 'reuters', 'hickenlooper', 'tax return', 'supreme court', \n '2020 democratic primary', 'electoral college', 'inslee', 'gravel', 'generic words', 'socialism', \n 'marijuana', 'maher', 'gun laws', 'yang', 'unions', '2020 democratic primary', 'media words', \n 'hamilton musical??', 'pundits', 'stacey abrams', 'trump', 'warren', 'israel', 'congress', 'harris', \n 'southern racism', 'civil rights', 'busing', 'north korea', 'gold', 'stufff', 'mcconnell', 'stuffs', \n 'generic words', 'iran/afghanistan']\n\ncandidates = [\"SANDERS\",\"DELANEY\",\"WARREN\",\"HARRIS\",\"GILLIBRAND\",\"O'ROURKE\",\"KLOBUCHAR\",\"BOOKER\",\n \"BUTTIGIEG\",\"GABBARD\",\"YANG\",\"INSLEE\",\"HICKENLOOPER\",\"WILLIAMSON\",\"TULSI\",\"CASTRO\",\"BIDEN\", \"BERNIE\",\n \"BETO\", \"ROURKE\", \"BENNETT\", \"BULLOCK\", \"BLASIO\", \"TIM RYAN\", \"GRAVEL\"]\ncandidates = set([x.lower() for x in candidates])\n\ncandidate_dict = {'klobuchar': 'klobuchar',\n 'bennett': 'bennett',\n 'booker': 'booker',\n 'warren': 'warren',\n 'castro': 'castro',\n 'williamson': 'williamson',\n 'gabbard': 'gabbard',\n 'bernie': 'sanders',\n \"o'rourke\": \"o_rourke\",\n 'bullock': 'bullock',\n #'tim ryan': 'tim_ryan',\n 'sanders': 'sanders',\n 'biden': 'biden',\n 'hickenlooper': 'hickenlooper',\n 'blasio': 'de_blasio',\n 'yang': 'yang',\n 'delaney': 'delaney',\n 'gillibrand': 'gillibrand',\n 'beto': 'o_rourke',\n 'harris': 'harris',\n 'inslee': 'inslee',\n 'rourke': 'o_rourke',\n 'gravel': 'gravel',\n 'tulsi': 'gabbard',\n 'buttigieg': 'buttigieg'}",
"_____no_output_____"
],
[
"# source data\nfilename = DATA_DIR + 'LDA/df.pkl'\ndf = pd.read_pickle(filename)",
"_____no_output_____"
],
[
"# model and corpus\nmodel = gensim.models.LdaModel.load(DATA_DIR + '/LDA/models/100_model_10_article_text_2019_candidate_only_len4.gensim')\ndictionary = gensim.corpora.Dictionary.load(DATA_DIR + 'LDA/article_text_2019_candidate_only_dictionary.gensim')\ncorpus = pickle.load(open(DATA_DIR + 'LDA/article_text_2019_candidate_only' + '_corpus.pkl', 'rb'))\np = pyLDAvis.gensim.prepare(model, corpus, dictionary)\npyLDAvis.save_html(p, DATA_DIR + 'LDA/lda_vis.html')",
"/usr/local/lib/python3.7/site-packages/smart_open/smart_open_lib.py:398: UserWarning: This function is deprecated, use smart_open.open instead. See the migration notes for details: https://github.com/RaRe-Technologies/smart_open/blob/master/README.rst#migrating-to-the-new-open-function\n 'See the migration notes for details: %s' % _MIGRATION_NOTES_URL\n/usr/local/lib/python3.7/site-packages/smart_open/smart_open_lib.py:398: UserWarning: This function is deprecated, use smart_open.open instead. See the migration notes for details: https://github.com/RaRe-Technologies/smart_open/blob/master/README.rst#migrating-to-the-new-open-function\n 'See the migration notes for details: %s' % _MIGRATION_NOTES_URL\n/usr/local/lib/python3.7/site-packages/pyLDAvis/_prepare.py:257: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version\nof pandas will change to not sort by default.\n\nTo accept the future behavior, pass 'sort=False'.\n\nTo retain the current behavior and silence the warning, pass 'sort=True'.\n\n return pd.concat([default_term_info] + list(topic_dfs))\n"
],
[
"df['corpus'] = df.text_lemmas.progress_map(lambda x: dictionary.doc2bow(x))\ndf['topics'] = df.corpus.progress_map(lambda x: list(filter(lambda y: y[0] in useful_topics,model[x])))",
"_____no_output_____"
],
[
"def vector_concatenator(vector):\n v = [(topic_titles[y[0]], y[1]) for y in vector]\n v_final = dict()\n for t in v:\n if t[0] in v_final.keys():\n v_final[t[0]] += t[1]\n else:\n v_final[t[0]] = t[1]\n return list(zip(v_final.keys(), v_final.values()))\n\ndf['topic_titles'] = df.topics.progress_map(vector_concatenator)",
"_____no_output_____"
],
[
"def intersection(lemma): \n lemma = [token.lower() for token in lemma]\n intersect = candidates.intersection(lemma)\n return {candidate_dict[x] for x in intersect}\n\ndf['candidate_title'] = df['title_lemmas'].progress_map(intersection)\ndf['candidate_text'] = df['text_lemmas'].progress_map(intersection)",
"_____no_output_____"
],
[
"df.to_csv(DATA_DIR + 'final_top_topics_news_articles.csv')\ndf.to_pickle(DATA_DIR + 'final_top_topics_news_articles.pkl')",
"_____no_output_____"
],
[
"df = pd.read_pickle(DATA_DIR + 'final_top_topics_news_articles.csv')",
"_____no_output_____"
]
],
[
[
"### Aggregated in Time Series",
"_____no_output_____"
]
],
[
[
"### get date dataframes\ndf_date = pd.read_pickle(DATA_DIR + 'reddit_2019jun16tojul1_dates.pkl')\ndf_date = df_date.append(pd.read_pickle(DATA_DIR + 'reddit_2019_dates.pkl'))\ndf_date = df_date.append(pd.read_csv(DATA_DIR + 'dates_missing_ids.csv', index_col=0))",
"_____no_output_____"
],
[
"df2 = df.merge(df_date, on='id', how='left') #df.join(df_date, on='id', how='left')\ndf2['day'] = pd.to_datetime(df2['created_utc'], yearfirst=True).dt.round('d')\ndf2['week']= df2['day'] - pd.to_timedelta(df2['day'].dt.dayofweek, unit='d')\ndf2['candidate_text'] = df2.candidate_text.map(lambda x: list(x))\ndf2['counter'] = 1\ndf2.counter = df2.counter.astype('object')",
"_____no_output_____"
],
[
"time = 'week' # day\n\ndef vector_concatenator(row):\n vector = row.topic_titles\n v_final = dict()\n for t in vector:\n if t[0] in v_final.keys():\n v_final[t[0]] += t[1]\n else:\n v_final[t[0]] = t[1]\n return list(zip(v_final.keys(), map(lambda x: x/row.counter, v_final.values())))\n\ndef vector_counter(row):\n vector = row.candidate_text\n v_final = dict()\n for t in vector:\n if t in v_final.keys():\n v_final[t] += 1\n else:\n v_final[t] = 1\n return list(zip(v_final.keys(), map(lambda x: x/row.counter, v_final.values())))\n\ndef normalize_topics(row):\n tt = row.topic_titles.copy()\n s = 0\n for x in tt:\n s += x[1]\n \n for i in range(len(tt)):\n tt[i] = (tt[i][0], tt[i][1]*(1.0/s))\n \n return tt\n\ncandidate_dfs = dict()\nfor candidate in set(candidate_dict.values()):\n candidate_dfs[candidate] = df2[df2.candidate_text.map(lambda x: candidate in x)]\\\n [['counter', 'score', 'candidate_text', 'topic_titles', time]]\\\n .groupby(time).agg(sum)\n candidate_dfs[candidate].topic_titles = candidate_dfs[candidate].apply(vector_concatenator, axis=1)\n candidate_dfs[candidate].candidate_text = candidate_dfs[candidate].apply(vector_counter, axis=1)\n candidate_dfs[candidate].topic_titles = candidate_dfs[candidate].apply(normalize_topics, axis=1)\ndf2_agg = df2[['counter', 'score', 'candidate_text', 'topic_titles', time]].groupby(time).agg(sum)\ndf2_agg.topic_titles = df2_agg.apply(vector_concatenator, axis=1)\ndf2_agg.candidate_text = df2_agg.apply(vector_counter, axis=1)\ndf2_agg.topic_titles = df2_agg.apply(normalize_topics, axis=1)\ncandidate_dfs['none'] = df2_agg",
"_____no_output_____"
],
[
"!mkdir {DATA_DIR + 'candidate_aggregation/'}\nfor candidate in set(candidate_dict.values()):\n candidate_dfs[candidate].to_csv(DATA_DIR + 'candidate_aggregation/' + candidate + '.csv')",
"mkdir: ../../data/reddit/Article_data_2019/candidate_aggregation/: File exists\r\n"
],
[
"candidate_dfs = dict()\nfor candidate in set(candidate_dict.values()):\n candidate_dfs[candidate] = pd.read_csv(DATA_DIR + 'candidate_aggregation/' + candidate + '.csv')",
"_____no_output_____"
],
[
"candidate_dfs['harris']",
"_____no_output_____"
],
[
"idxs = [2,4,6,7,8,9,12,13,14,17,18,19,20,21,22,23,24,26,28,29,30,31,32,33,34,35,38,42,44,45,46,47,48,50,51,\n 52,53,55,58,61,62,63,64,66,67,68,69,70,71,75,77,78,79,80,85,86,87,88,89,91,92,93,96,99]\n{topic_titles[i] for i in useful_topics}",
"_____no_output_____"
],
[
"def plot_topic_df(dataframe, topic):\n\n def extract_topic(row):\n topic_list = list(filter(lambda y: y[0] == topic, row.topic_titles))\n if len(topic_list) == 0:\n return 0\n else:\n return topic_list[0][1]\n \n\n dataframe[dataframe.counter > 10]\\\n .apply(extract_topic, axis =1)\\\n .plot(title='{} Topic Frequency'.format(topic).title())\n \n#df2_agg\nc = 'none'\nplot_topic_df(candidate_dfs[c][candidate_dfs[c].counter > 10], 'mueller report')",
"_____no_output_____"
],
[
"def topic_df(dataframe, topic):\n\n def extract_topic(row):\n topic_list = list(filter(lambda y: y[0] == topic, row.topic_titles))\n if len(topic_list) == 0:\n return 0\n else:\n return topic_list[0][1]\n \n\n return dataframe[dataframe.counter > 10]\\\n .apply(extract_topic, axis =1)\ntopic_df(candidate_dfs[c][candidate_dfs[c].counter > 10], 'israel')",
"_____no_output_____"
],
[
"df2[(df2.candidate_text.map(lambda x: c in x)) & (df2.day == '2019-01-25')].loc[8293]",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccfaa3d186196dfb4fd66ae9ef60b2d0295ecdf | 2,465 | ipynb | Jupyter Notebook | DEM/run/hybrid/figures.ipynb | plaveczlambert/nonlinearbubbledynamics | 190c5170f7ff6068badeee818c01226c55aaec97 | [
"MIT"
] | null | null | null | DEM/run/hybrid/figures.ipynb | plaveczlambert/nonlinearbubbledynamics | 190c5170f7ff6068badeee818c01226c55aaec97 | [
"MIT"
] | null | null | null | DEM/run/hybrid/figures.ipynb | plaveczlambert/nonlinearbubbledynamics | 190c5170f7ff6068badeee818c01226c55aaec97 | [
"MIT"
] | null | null | null | 23.037383 | 104 | 0.517647 | [
[
[
"%matplotlib notebook\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\nimport h5py\nplt.rcParams.update({\n \"text.usetex\": True,\n \"font.family\": \"sans-serif\",\n \"font.sans-serif\": [\"Helvetica\"],\n \"font.size\": 12.0})",
"_____no_output_____"
],
[
"dem = np.genfromtxt('simulations/bub_hybrid_test.txt', usecols=(0,1,2,3))",
"_____no_output_____"
],
[
"euler = np.loadtxt('simulations/bub_euler_1e-5.txt')",
"_____no_output_____"
],
[
"dopri = np.loadtxt('../../data/bubble_sim_p0.5_f100_Re10_N16_t5_x2_0.txt', delimiter=',')",
"_____no_output_____"
],
[
"plt.figure(num=\"Comparison\")\nplt.plot(dopri[:,0], dopri[:,1], color=\"black\", label=\"Dopri\")\n#plt.plot(euler[:,0],euler[:,1], color=\"purple\", label=\"Euler\")\nplt.plot(dem[:,0],dem[:,1], linestyle=\"--\", dashes=(5,5), color=\"orange\", label=\"Hybrid\")\nplt.xlabel(\"$t$\")\nplt.ylabel(\"$x_1$\")\nplt.xlim((0,5))\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"dt = dem[1:,0] - dem[:-1,0]\nprint(np.max(dt))\nprint(np.min(dt))\nprint(np.mean(dt))",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccfb3a38aef02e0e620888c50ad2e0317dbb860 | 1,630 | ipynb | Jupyter Notebook | eg/synopsis-1.ipynb | p6steve/perl6-Physics-Measure-JupyterBinder | 797bf679816a32237bd9a2520d888ec752fde6e0 | [
"Artistic-2.0"
] | 1 | 2020-11-05T09:41:13.000Z | 2020-11-05T09:41:13.000Z | eg/synopsis-1.ipynb | p6steve/raku-Physics-Measure-Jupyter | 561d65661425b50b9e61b790a18899bc28769eab | [
"Artistic-2.0"
] | 1 | 2021-02-10T21:08:50.000Z | 2021-02-11T20:48:37.000Z | eg/synopsis-1.ipynb | p6steve/raku-Physics-Measure-Jupyter | 561d65661425b50b9e61b790a18899bc28769eab | [
"Artistic-2.0"
] | null | null | null | 21.447368 | 99 | 0.388344 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
eccfbcea4add78c5c3bdb964d646d200b89af484 | 3,491 | ipynb | Jupyter Notebook | kernel/Dot/l_mykernel.ipynb | nufeng1999/Myjupyter-kernel | 7862ce8afae139d39ad2896f3e36a19b5df9923e | [
"MIT"
] | null | null | null | kernel/Dot/l_mykernel.ipynb | nufeng1999/Myjupyter-kernel | 7862ce8afae139d39ad2896f3e36a19b5df9923e | [
"MIT"
] | null | null | null | kernel/Dot/l_mykernel.ipynb | nufeng1999/Myjupyter-kernel | 7862ce8afae139d39ad2896f3e36a19b5df9923e | [
"MIT"
] | null | null | null | 30.094828 | 168 | 0.49556 | [
[
[
"## new kernel.py\n##%overwritefile\n##%file:../../../jupyter-MyDot-kernel/jupyter_MyDot_kernel/kernel.py\n###%file:dot_kernel.py\n##%noruncode\n#\n# MyDot Jupyter Kernel\n# generated by MyPython\n#\n##%include:../../src/head.py\nfrom .MyKernel import MyKernel\nfrom . import imgsize\nfrom graphviz import Source\n\nclass DotKernel(MyKernel):\n kernel_info={\n 'info':'[MyDot Kernel]',\n 'extension':'.dot',\n 'execsuffix':'',\n 'needmain':'',\n 'compiler':{\n 'cmd':'',\n 'outfileflag':'',\n 'clargs':[],\n 'crargs':[],\n },\n 'interpreter':{\n 'cmd':'',\n 'clargs':'',\n 'crargs':'',\n },\n }\n implementation = 'jupyter_MyDot_kernel'\n implementation_version = '1.0'\n language = 'Dot'\n language_version = ''\n language_info = {'name': 'text/dot',\n 'mimetype': 'text/dot',\n 'file_extension': kernel_info['extension']}\n runfiletype='script'\n banner = \"Dot kernel.\\n\" \\\n \"Dot language - render graph using graphviz, and creates source code files and executables in temporary folder.\\n\"\n\n main_head = \"\\n\\nint main(List<String> arguments){\\n\"\n main_foot = \"\\nreturn 0;\\n}\"\n \n## //%include:../../src/comm_attribute.py\n## __init__\n def __init__(self, *args, **kwargs):\n super(DotKernel, self).__init__(*args, **kwargs)\n self.runfiletype='script'\n self.kernelinfo=\"[MyDotKernel{0}]\".format(time.strftime(\"%H%M%S\", time.localtime()))\n## #############################################\n##%include:src/compile_out_file.py\n##%include:src/compile_with_sc.py\n##%include:src/c_exec_sc_.py\n\n##%include:src/do_dot_runcode.py\n##%include:src/do_dot_compilecode.py\n##%include:src/do_dot_create_codefile.py\n##%include:src/do_dot_preexecute.py\n\n",
"[MyPythonKernel101858] Info:file h:\\Jupyter\\Myjupyter-kernel\\kernel\\Dot\\../../../jupyter-MyDot-kernel/jupyter_MyDot_kernel/kernel.py created successfully\n"
]
]
] | [
"code"
] | [
[
"code"
]
] |
eccfc58e66dcc48e7dc5d6bea2c505a6d2d3a085 | 7,047 | ipynb | Jupyter Notebook | numba_vs_cython.ipynb | josephcslater/Introduction_to_Python | 0d30771ed135432fe27ec830c741eb7c30a1ec3c | [
"Unlicense"
] | 3 | 2018-10-08T00:48:12.000Z | 2021-02-05T20:20:39.000Z | numba_vs_cython.ipynb | josephcslater/Introduction_to_Python | 0d30771ed135432fe27ec830c741eb7c30a1ec3c | [
"Unlicense"
] | 1 | 2020-09-04T18:29:42.000Z | 2020-09-04T18:29:42.000Z | numba_vs_cython.ipynb | josephcslater/Introduction_to_Python | 0d30771ed135432fe27ec830c741eb7c30a1ec3c | [
"Unlicense"
] | 2 | 2019-01-23T17:13:28.000Z | 2020-07-29T18:59:28.000Z | 26.197026 | 350 | 0.523769 | [
[
[
"This simple notebook is an update of the notebook by Jake Vanderplas at https://jakevdp.github.io/blog/2013/06/15/numba-vs-cython-take-2/ to run on Python 3.5. It compares usage of cython and numba illustrating the ability to vastly increase speed of computation with some simple tricks. \n",
"_____no_output_____"
],
[
"A very pithy description of this is that `X` contains $1000$ points in 3D space. The Euclidian distance between any two points can be calculated (vector length). This can be represented by a 1000 $\\times$ 1000 array containing all possible pairs. Calculating this in Python is slow. This can be easily sped up by \"precompiling\" the code. \n\nFor more details on how to migrate to compiled code see [Hans Lantangen's tutorial](http://hplgit.github.io/primer.html/doc/pub/cython/cython-solarized.html).",
"_____no_output_____"
]
],
[
[
"# We are going to load the Cython extension for Jupyter. This allows us to \n# put a few things into Python code. Cython then turns it into C code, \n# compiles it, and runs it in the background. \n\n%load_ext Cython\n\nimport numpy as np\nX = np.random.random((1000, 3))\nD = np.empty((1000, 1000))",
"The Cython extension is already loaded. To reload it, use:\n %reload_ext Cython\n"
],
[
"# Pure python version\n\ndef pairwise_python(X, D):\n M = X.shape[0]\n N = X.shape[1]\n for i in range(M):\n for j in range(M):\n d = 0.0\n for k in range(N):\n tmp = X[i, k] - X[j, k]\n d += tmp * tmp\n D[i, j] = np.sqrt(d)\n return D",
"_____no_output_____"
],
[
"# numba version\n\nimport numpy as np\nfrom numba import double\nfrom numba.decorators import jit\n\n# The next line is the only \"change to the code\"\n@jit # (arg_types=[double[:,:], double[:,:]])\ndef pairwise_numba(X, D):\n M = X.shape[0]\n N = X.shape[1]\n for i in range(M):\n for j in range(M):\n d = 0.0\n for k in range(N):\n tmp = X[i, k] - X[j, k]\n d += tmp * tmp\n D[i, j] = np.sqrt(d)\n return D",
"_____no_output_____"
],
[
"%%cython\n# The above declares that this cell is Cython code.\n\n# Load some cheats that help cython\ncimport cython\n\n# Load the sqrt function, but with cimport, also import knowledge of the variable \n# type used (it's a floating point)\nfrom libc.math cimport sqrt\n\n# Tell cython not to check if my indices called ae actually inside the array\n# This is a good move if you are ABSOLUTELY sure of it. It's a bad move otherwise. \[email protected](False)\n\n# This disallows use of negative indices. \[email protected](False)\ndef pairwise_cython(double[:, ::1] X, double[:, ::1] D):\n cdef int M = X.shape[0]\n cdef int N = X.shape[1]\n cdef double tmp, d\n for i in range(M):\n for j in range(M):\n d = 0.0\n for k in range(N):\n tmp = X[i, k] - X[j, k]\n d += tmp * tmp\n D[i, j] = sqrt(d)\n return D",
"_____no_output_____"
],
[
"%timeit pairwise_python(X, D)",
"3.83 s ± 139 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
],
[
"%timeit pairwise_numba(X, D)",
"2.72 ms ± 92.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
],
[
"%timeit pairwise_cython(X, D)",
"2.82 ms ± 123 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccfd0604f1cc0227f0c2aa78ae3e26b4a8be58e | 20,209 | ipynb | Jupyter Notebook | Restricted_Boltzmann_Machine.ipynb | JosephGatto/Simplified-Restricted-Boltzmann-Machines | 915610be516fab3b55487b7ee04ab8eb015cc100 | [
"MIT"
] | 9 | 2018-07-24T20:53:06.000Z | 2021-12-21T17:56:23.000Z | Restricted_Boltzmann_Machine.ipynb | JosephGatto/Simplified-Restricted-Boltzmann-Machines | 915610be516fab3b55487b7ee04ab8eb015cc100 | [
"MIT"
] | 1 | 2021-12-21T17:55:30.000Z | 2021-12-21T17:55:30.000Z | Restricted_Boltzmann_Machine.ipynb | JosephGatto/Simplified-Restricted-Boltzmann-Machines | 915610be516fab3b55487b7ee04ab8eb015cc100 | [
"MIT"
] | 2 | 2021-02-05T13:46:27.000Z | 2021-06-02T15:40:55.000Z | 60.687688 | 851 | 0.624524 | [
[
[
"## Import Libraries",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf #Deep learning library\nimport numpy as np #Matrix algebra library\nfrom tensorflow.examples.tutorials.mnist import input_data #Import training data\nimport pandas as pd #Database management library\nimport matplotlib.pyplot as plt #Visualization library \n%matplotlib inline \nfrom sklearn.svm import LinearSVC #For linear image classification\nfrom sklearn.model_selection import GridSearchCV #For hyperparameter optimization",
"_____no_output_____"
]
],
[
[
"## Load MNIST Dataset & Prepare Data for RBM \n\nWe will be building this RBM in Tensorflow and testing it on the MNIST dataset. We will not need one_hot encoding as we will be using our RBM to extract important features from our image data to be used in a linear classifier. ",
"_____no_output_____"
]
],
[
[
"mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=False) \ntrX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels",
"Extracting MNIST_data/train-images-idx3-ubyte.gz\nExtracting MNIST_data/train-labels-idx1-ubyte.gz\nExtracting MNIST_data/t10k-images-idx3-ubyte.gz\nExtracting MNIST_data/t10k-labels-idx1-ubyte.gz\n"
]
],
[
[
"# Restricted Boltzmann Machine\n\n### Who is this explanation for? \n\nAt the risk of sacrificing some important information, I will be discussing this with you as I would a close friend who knew a little about deep learning. Sometimes, I think its nice to get a general overview of how something works before diving into the specifics. If you are someone like me who was taking Geoffrey Hinton's Coursera course and had no idea what he was talking about when he got into Restricted Boltzmann Machines...keep reading! \n\n### How will we be utilizing this RBM?\n\nWhen my research team began developing a new method of feature engineering for image classification, they were very interested to see how it compared to the classic RBM. Naturally, I was given the tedious task of building one and producing benchmarks for a variety of datasets. The goal of this tutorial is to utilize the RBM to extract important features from an image, and then use those features in a simple linear classifier. We want to take image data that is NOT linearly seperable and attempt to make it... more linearly seperable by using the RBM as a feature engineering tool. This is only one of many use cases for the RBM.\n\n\n### How do we do that? \n\nThe RBM is an unsupervised model, meaning, there is no known output we are mapping our data to. We have our input layer (which is just the pixels of our image) and a hidden layer which will, over time, be learning what the most important features are. Now I know I said I am assuming you know a little about deep learning, but before we get into how RBMs work we should probably set a few definitions. \n\nBack propagation: This is a tool that updates the weights of our neural network in a direction that minimizes our error. Over time, these weights will allow our neural network (or RBM in this case) to learn whatever it is we are asking it to learn. \n\nDense layer: In our case, this simply means that every neuron in the input layer is connected to every neuron of the hidden layer. This does not mean that neurons in the input layer are connected to other neurons in the input layer. Input layer neurons are only connected to neurons in the hidden layer. \n\nInput Layer: The layer of the RBM that contains the original image data. \n\nHidden Layer: The layer of the RBM that is extracting the key features from the image. The goal of the hidden layer is to eventually reconstruct what it sees in the input layer without using all of the original pixels. It only uses features it deems most important. Lets talk about how this happens.\n\n### Inside of the RBM\n\nSo this is what's going down. Lets take one image from the MNIST dataset and discuss what happens as it goes through a restricted boltzmann machine. MNIST is full of 28x28 images of hand-written digits. First, we take our 28x28 image and flatten it to a 1D array of length 784 (because 28*28 = 784). Now, if you are picturing an artificial neural network in your head, these are all of the neurons of the input layer. Now we need to decide how many neurons we wish to have in the hidden layer. \n\nThe hidden layer is a magical place. A place where you can reconstruct the original image with less neurons than you started with. What?!??!? Thats right! The goal of the hidden layer is to extract the most important features from the original image and then use those features to reconstruct the original image! So earlier I asked the question: How many neurons should we have in the hidden layer? The answer: I dont know. As you may know by now, machine learning is an iterative process and finding the magic number will take some time. Often, people will reduce the number of neurons in the hidden layer, for example, going from 784 neurons to 650 neurons. Thus, the RBM now has to work hard to capture the essence of the original image in only 650 neurons. How does it do this? Well, lets stop and recap what we are currently looking at. \n\n1) Image gets flattened into a 784 length array and prepared for the input layer of the RBM. \n\n2) We decided that the hidden layer size is 650. So now we will randomly initalize our weights that are connecting each neuron from the input layer to each neuron of the hidden layer. \n\nThese weights connecting the two layers are what is going to allow the RBM to model the original image with a smaller amount of neurons. Using back propagation, the weights will, over time, learn how to help the hidden layer represent the original image with a smaller number of pixels. \n\n### How do we know if it's working? \n\nSo we have inputted our image, created our hidden layer, and our weights are randomly initalized and ready to go. Now what? Well, the RBM is going to attempt to reconstruct the original 28*28 image with only 650 neurons. On its first go around, it will probably do pretty bad considering we gave the model random weights to work with. We can check how bad it did by measuring the difference between the hidden layer reconstruction and the original image. After that, the RBM will go through another iteration, this time updating the weights to help the hidden layer reconstruction better represent the original image, and again, we check to see the difference between the original image and the reconstruction. This proceess goes on and on until we find that our error is low and the reconstructed image closely resembles the original image.\n\n### Linear classification time! \n\nNow that our hidden layer is able to reconstruct the original image extremely well with only 650 neurons, lets see how these 650 neurons perform in a linear classifier. With no feature engineering, meaning, just using our 784 original neurons as our training data, I was able to get 91% accuracy using a LinearSVC. After running the RBM, extracting the 650 neurons containing our high quality features from the hidden layer, and using those features as training data, I got 97% accuracy! I could probably get better results if I experimented with different numbers of neurons in my hidden layer. Let me know if you beat 97%!\n\n### Now its your turn!\n\nFollow along with the code below. I have heavily commented it for you and if you have any questions feel free to email me. \n\n### Contrastive Divergence\n\nIf you are going through Geoffrey Hinton's course and learned about Contrastive Divergence, I have a tensorflow implementation for you. Feel free to try it out. I personally have never come across a time where CD-n for n > 1 performed better than n = 1 but after hearing so much about it I had to try. \n\nFor those wondering, all Contrastive Divergence means is, instead of the RBM iterating over and over again going from original input to reconstruction > original input to better reconstruction and so on... now you are using the reconstruction as the input layer in the second iteration... so original input to reconstruction to reconstruction of the reconstruction and so on. It's not very popular but can be fun to play with! \n\n",
"_____no_output_____"
]
],
[
[
"class RBM(object):\n def __init__(self, input_size, output_size, learning_rate, batch_size):\n self.input_size = input_size #Size of the input layer\n self.output_size = output_size #Size of the hidden layer\n self.epochs = 2 #How many times we will update the weights \n self.learning_rate = learning_rate #How big of a weight update we will perform \n self.batch_size = batch_size #How many images will we \"feature engineer\" at at time \n self.new_input_layer = None #Initalize new input layer variable for k-step contrastive divergence \n self.new_hidden_layer = None\n self.new_test_hidden_layer = None\n \n #Here we initialize the weights and biases of our RBM\n #If you are wondering, the 0 is the mean of the distribution we are getting our random weights from. \n #The .01 is the standard deviation.\n self.w = np.random.normal(0,.01,[input_size,output_size]) #weights\n self.hb = np.random.normal(0,.01,[output_size]) #hidden layer bias\n self.vb = np.random.normal(0,.01,[input_size]) #input layer bias (sometimes called visible layer)\n \n \n #Calculates the sigmoid probabilities of input * weights + bias\n #Here we multiply the input layer by the weights and add the bias\n #This is the phase that creates the hidden layer\n def prob_h_given_v(self, visible, w, hb):\n return tf.nn.sigmoid(tf.matmul(visible, w) + hb)\n \n #Calculates the sigmoid probabilities of input * weights + bias\n #Here we multiply the hidden layer by the weights and add the input layer bias\n #This is the reconstruction phase that recreates the original image from the hidden layer\n def prob_v_given_h(self, hidden, w, vb):\n return tf.nn.sigmoid(tf.matmul(hidden, tf.transpose(w)) + vb)\n \n #Returns new layer binary values\n #This function returns a 0 or 1 based on the sign of the probabilities passed to it\n #Our RBM will be utilizing binary features to represent the images\n #This function just converts the features we have learned into a binary representation \n def sample_prob(self, probs):\n return tf.nn.relu(tf.sign(probs - tf.random_uniform(tf.shape(probs))))\n \n def train(self, X, teX):\n #Initalize placeholder values for graph\n #If this looks strange to you, then you have not used Tensorflow before\n _w = tf.placeholder(tf.float32, shape = [self.input_size, self.output_size])\n _vb = tf.placeholder(tf.float32, shape = [self.input_size])\n _hb = tf.placeholder(tf.float32, shape = [self.output_size])\n \n \n #initalize previous variables\n #we will be saving the weights of the previous and current iterations\n pre_w = np.random.normal(0,.01, size = [self.input_size,self.output_size])\n pre_vb = np.random.normal(0, .01, size = [self.input_size])\n pre_hb = np.random.normal(0, .01, size = [self.output_size])\n \n #initalize current variables\n #we will be saving the weights of the previous and current iterations\n cur_w = np.random.normal(0, .01, size = [self.input_size,self.output_size])\n cur_vb = np.random.normal(0, .01, size = [self.input_size])\n cur_hb = np.random.normal(0, .01, size = [self.output_size])\n \n #Plaecholder variable for input layer\n v0 = tf.placeholder(tf.float32, shape = [None, self.input_size])\n \n #pass probabilities of input * w + b into sample prob to get binary values of hidden layer\n h0 = self.sample_prob(self.prob_h_given_v(v0, _w, _hb ))\n \n #pass probabilities of new hidden unit * w + b into sample prob to get new reconstruction\n v1 = self.sample_prob(self.prob_v_given_h(h0, _w, _vb))\n \n #Just get the probailities of the next hidden layer. We wont need the binary values. \n #The probabilities here help calculate the gradients during back prop \n h1 = self.prob_h_given_v(v1, _w, _hb)\n \n \n #Contrastive Divergence\n positive_grad = tf.matmul(tf.transpose(v0), h0) #input' * hidden0\n negative_grad = tf.matmul(tf.transpose(v1), h1) #reconstruction' * hidden1\n #(pos_grad - neg_grad) / total number of input samples \n CD = (positive_grad - negative_grad) / tf.to_float(tf.shape(v0)[0]) \n \n #This is just the definition of contrastive divergence \n update_w = _w + self.learning_rate * CD\n update_vb = _vb + tf.reduce_mean(v0 - v1, 0)\n update_hb = _hb + tf.reduce_mean(h0 - h1, 0)\n \n #MSE - This is our error function\n err = tf.reduce_mean(tf.square(v0 - v1))\n \n #Will hold new visible layer.\n errors = []\n hidden_units = []\n reconstruction = []\n \n test_hidden_units = []\n test_reconstruction=[]\n \n \n #The next four lines of code intitalize our Tensorflow graph and create mini batches\n #The mini batch code is from cognitive class. I love the way they did this. Just giving credit! \n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(self.epochs):\n for start, end in zip(range(0, len(X), self.batch_size), range(self.batch_size, len(X), self.batch_size)):\n batch = X[start:end] #Mini batch of images taken from training data\n \n #Feed in batch, previous weights/bias, update weights and store them in current weights\n cur_w = sess.run(update_w, feed_dict = {v0:batch, _w:pre_w , _vb:pre_vb, _hb:pre_hb})\n cur_hb = sess.run(update_hb, feed_dict = {v0:batch, _w:pre_w , _vb:pre_vb, _hb:pre_hb})\n cur_vb = sess.run(update_vb, feed_dict = {v0:batch, _w:pre_w , _vb:pre_vb, _hb:pre_hb})\n \n #Save weights \n pre_w = cur_w\n pre_hb = cur_hb\n pre_vb = cur_vb\n \n #At the end of each iteration, the reconstructed images are stored and the error is outputted \n reconstruction.append(sess.run(v1, feed_dict={v0: X, _w: cur_w, _vb: cur_vb, _hb: cur_hb})) \n print('Learning Rate: {}: Batch Size: {}: Hidden Layers: {}: Epoch: {}: Error: {}:'.format(self.learning_rate, self.batch_size, \n self.output_size, (epoch+1),\n sess.run(err, feed_dict={v0: X, _w: cur_w, _vb: cur_vb, _hb: cur_hb})))\n \n #Store final reconstruction in RBM object\n self.new_input_layer = reconstruction[-1]\n \n #Store weights in RBM object\n self.w = pre_w\n self.hb = pre_hb\n self.vb = pre_vb\n \n #This is used for Contrastive Divergence.\n #This function makes the reconstruction your new input layer. \n def rbm_output(self, X):\n input_x = tf.constant(X)\n _w = tf.constant(self.w)\n _hb = tf.constant(self.hb)\n _vb = tf.constant(self.vb)\n \n out = tf.nn.sigmoid(tf.matmul(input_x, _w) + _hb)\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n return sess.run(out)\n ",
"_____no_output_____"
],
[
"#A function for training your RBM\n#Keep k at 1 for a traditional RBM. \ndef train_cd_k(k, input_size, output_size, trX, teX, learning_rate, batch_size):\n cdk_train_input = trX #Training data\n cdk_test_input = teX #Testing data\n cdk_train_hidden = None #Variable to store hidden layer for training data\n cdk_test_hidden = None #Variable to store hidden layer for testing data\n \n rbm = RBM(input_size, output_size, learning_rate, batch_size)\n \n #Loop for contrastive divergence. \n for i in range(k):\n print('CD: {}'.format(int(i+1)))\n rbm.train(cdk_train_input, cdk_test_input) #Using reconstruction as input layer for CD\n cdk_train_input = rbm.new_input_layer\n cdk_train_hidden = rbm.rbm_output(cdk_train_input)\n cdk_test_hidden = rbm.rbm_output(cdk_test_input)\n \n return [cdk_train_hidden, cdk_test_hidden, cdk_train_input]\n ",
"_____no_output_____"
],
[
"with tf.Graph().as_default():\n temp = train_cd_k(1,784,650,trX,teX,.001,32)\n lsvc_RBM = LinearSVC()\n lsvc_RBM.fit(temp[cdk_train_hidden], trY)\n lsvc_RBM.score(temp[cdk_test_hidden], teY)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
eccfd17e8cd2cbb2e68315c9c812f1defc71ce0e | 8,484 | ipynb | Jupyter Notebook | docs/visualization/plotting/plotting-2d-data.ipynb | mlund/scipp | 26648fdcda49b21a7aacdafd58625fab7ee3403b | [
"BSD-3-Clause"
] | null | null | null | docs/visualization/plotting/plotting-2d-data.ipynb | mlund/scipp | 26648fdcda49b21a7aacdafd58625fab7ee3403b | [
"BSD-3-Clause"
] | null | null | null | docs/visualization/plotting/plotting-2d-data.ipynb | mlund/scipp | 26648fdcda49b21a7aacdafd58625fab7ee3403b | [
"BSD-3-Clause"
] | null | null | null | 26.104615 | 335 | 0.539486 | [
[
[
"# Plotting 2-D data\n\nScipp uses the `imshow` function from the `matplotlib` library to visualize 2-D data.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport scipp as sc",
"_____no_output_____"
]
],
[
[
"## Basic image plot\n\n2-D variables are plotted as images, with a colormap:",
"_____no_output_____"
]
],
[
[
"N = 100\nM = 50\nxx = np.arange(N, dtype=np.float64)\nyy = np.arange(M, dtype=np.float64)\nx, y = np.meshgrid(xx, yy)\nb = N/20.0\nc = M/2.0\nr = np.sqrt(((x-c)/b)**2 + (y/b)**2)\na = np.sin(r)\nd1 = sc.Dataset()\nd1['Signal'] = sc.Variable(dims=['y', 'x'], values=a, unit=sc.units.K)\nd1.coords['x'] = sc.Variable(dims=['x'], values=xx, unit=sc.units.m)\nd1.coords['y'] = sc.Variable(dims=['y'], values=yy, unit=sc.units.m)\nsc.plot(d1)",
"_____no_output_____"
]
],
[
[
"The dimension displayed along each axis of the image can changed using the tranpose buttons in the toolbar to the left of the figure, or by transposing the input data:",
"_____no_output_____"
]
],
[
[
"d1['Signal'].transpose().plot()",
"_____no_output_____"
]
],
[
[
"## Changing the colorscale\n\nChanging the colorscale is handled in a similar way to [Matplotlib syntax](https://matplotlib.org/tutorials/colors/colormaps.html).\nThe colormap is defined by the `cmap` argument:",
"_____no_output_____"
]
],
[
[
"sc.plot(d1, cmap='magma')",
"_____no_output_____"
]
],
[
[
"A logarithmic colorscale is obtained by setting `norm` to `'log'`:",
"_____no_output_____"
]
],
[
[
"sc.plot(d1, norm='log')",
"_____no_output_____"
]
],
[
[
"Upper and lower limits on the colorscale can be placed using `vmin` and `vmax`:",
"_____no_output_____"
]
],
[
[
"sc.plot(d1, vmin=0*sc.Unit('K'), vmax=0.5*sc.Unit('K'))",
"_____no_output_____"
]
],
[
[
"## Using labels along some axis\n\nJust like in the 1d plots, we can use labels along a chosen dimension:",
"_____no_output_____"
]
],
[
[
"d1.coords['somelabels'] = sc.Variable(dims=['x'],\n values=np.linspace(101., 155., N),\n unit=sc.units.s)\nsc.plot(d1, labels={'x': 'somelabels'})",
"_____no_output_____"
]
],
[
[
"## Collapsing dimensions\n\nSometimes it is useful to collapse one or more of the data's dimensions, if for instance most detector pixels contain noise, but one specific channel contains a strong signal. This is done by specifying the dimension to be displayed along the x axis as a keyword argument to `sc.collapse`. All other dimensions will be collapsed.",
"_____no_output_____"
]
],
[
[
"N = 40\nM = 5\nx = np.arange(N).astype(np.float64)\nb = 0.5 * N\na = 4.0*np.random.rand(M, N)\na[2, :] = np.abs(10.0 * np.cos((x-b)*2.0/b))\nd2 = sc.Dataset()\nd2['sample'] = sc.Variable(dims=['x', 'tof'], values=a,\n variances=0.1*np.random.rand(M, N))\nd2.coords['tof'] = sc.Variable(dims=['tof'], values=x, unit=sc.units.us)\nd2.coords['x'] = sc.Variable(dims=['x'], values=np.arange(M).astype(np.float64),\n unit=sc.units.m)\nsc.plot(d2)",
"_____no_output_____"
],
[
"sc.plot(sc.collapse(d2['sample'], keep='tof'))",
"_____no_output_____"
]
],
[
[
"## Image aspect ratio\nBy default, the aspect ratio of 2D images is not preserved; images are stretched to the size of the figure.\nYou can choose to preserve the aspect ratio via the `aspect` keyword argument.\nThe default value for `aspect` is `auto` which allows for scaling.",
"_____no_output_____"
]
],
[
[
"sc.plot(d2, aspect='equal')",
"_____no_output_____"
]
],
[
[
"You can also make this a permanent setting by editing scipp's [configuration](../../reference/runtime-configuration.ipynb) (possible options are `'equal'` and `'auto'`):",
"_____no_output_____"
]
],
[
[
"sc.config['plot']['aspect'] = 'equal'\n# or\nsc.config['plot']['aspect'] = 'auto'",
"_____no_output_____"
]
],
[
[
"## Plotting masks\n\nIf a dataset contains masks, they will appear as greyed out on the image:",
"_____no_output_____"
]
],
[
[
"N = 100\nM = 50\nxx = np.arange(N, dtype=np.float64)\nyy = np.arange(M, dtype=np.float64)\nx, y = np.meshgrid(xx, yy)\nb = N/20.0\nc = M/2.0\nr = np.sqrt(((x-c)/b)**2 + (y/b)**2)\na = np.sin(r)\nd3 = sc.DataArray(data=sc.Variable(dims=['y', 'x'], values=a, unit=sc.units.K))\nd3.coords['x'] = sc.Variable(dims=['x'], values=xx, unit=sc.units.m)\nd3.coords['y'] = sc.Variable(dims=['y'], values=yy, unit=sc.units.m)\nd3.masks['mask1'] = sc.Variable(dims=['y', 'x'], values=np.where(a < 0, True, False))\nsc.plot(d3)",
"_____no_output_____"
]
],
[
[
"Note that hovering over a masked region still yields the underlying value of the element on the display.\n\nA toggle button below the plot can be used to hide/show the masks.\n\nThe mask can be represented as a solid color with",
"_____no_output_____"
]
],
[
[
"sc.plot(d3, masks={'color': 'magenta'})",
"_____no_output_____"
]
],
[
[
"We also note that any 1D mask will automatically broadcast onto a 2D image.\nThis is due to underlying behavior of scipp around broadcasting rather than special handling in plotting:",
"_____no_output_____"
]
],
[
[
"d3.masks['mask1'] = sc.Variable(dims=['x'], values=np.where(np.abs(xx-50) < 10, True, False))\nsc.plot(d3)",
"_____no_output_____"
]
],
[
[
"## Saving figures\nStatic `pdf` or `png` copies of the figures can be saved to file (note that any buttons displayed under a figure are not saved to file). This is achieved as follows:",
"_____no_output_____"
]
],
[
[
"sc.plot(d3, filename='my_2d_figure.pdf')",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
eccfe1b1d81a91fb24caf9dbc650b50a4df7a061 | 238,879 | ipynb | Jupyter Notebook | 2016_05_Halifax/Day3/matplotlib_figures.ipynb | mne-tools/mne-workshops | 5852ab2c1b351dd13efcc794032f2967cb0819d8 | [
"BSD-3-Clause"
] | 21 | 2019-05-31T03:47:12.000Z | 2022-03-06T23:08:58.000Z | 2016_05_Halifax/Day3/matplotlib_figures.ipynb | berdakh/mne-workshops | 5852ab2c1b351dd13efcc794032f2967cb0819d8 | [
"BSD-3-Clause"
] | 1 | 2019-08-16T13:59:53.000Z | 2019-08-19T16:37:35.000Z | mne-workshops-master/2016_05_Halifax/Day3/matplotlib_figures.ipynb | GanshengT/INSERM_EEG_Enrico_Proc | 343edc32e5c9705213189a088855c635b31ca22b | [
"CNRI-Python"
] | 16 | 2019-08-30T11:07:10.000Z | 2022-03-27T20:13:16.000Z | 385.28871 | 42,418 | 0.927197 | [
[
[
"# Making publication ready figures with matplotlib\n\n`\nAuthors:\nAlexandre Gramfort\n`",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"import mne\nfrom mne.datasets import sample\nmne.set_log_level('warning')\ndata_path = sample.data_path()\nevoked_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'\nevoked = mne.read_evokeds(evoked_fname, condition='Left Auditory', baseline=(None, 0))",
"_____no_output_____"
],
[
"evoked.pick_types(meg='grad')\nevoked.plot();",
"_____no_output_____"
]
],
[
[
"Set the figure size, add t=0 vertical line, add text",
"_____no_output_____"
]
],
[
[
"def my_plot():\n fig, ax = plt.subplots(1, 1, figsize=(6, 3))\n evoked.pick_types(meg='grad')\n evoked.plot(axes=ax, show=False)\n ax.axvline(0., color='r');\n ax.text(x=0.02, y=0.05, s='Left Auditory', transform=ax.transAxes)\n\nmy_plot()",
"_____no_output_____"
]
],
[
[
"## Change matplotlib style using seaborn",
"_____no_output_____"
]
],
[
[
"import seaborn as sns",
"_____no_output_____"
],
[
"def set_style():\n # This sets reasonable defaults for font size for\n # a figure that will go in a paper\n sns.set_context(\"paper\")\n # Set the font to be serif, rather than sans\n sns.set(font='serif', font_scale=1.2)\n sns.set_palette('muted')\n # Make the background white, and specify the\n # specific font family\n sns.set_style(\"whitegrid\", {\n \"font.family\": \"serif\",\n \"font.serif\": [\"Times\", \"Palatino\", \"serif\"]\n })\n\n\nset_style()",
"_____no_output_____"
],
[
"my_plot()",
"_____no_output_____"
]
],
[
[
"## Fine customization of your plots\n\nWhat have every text in magenta? and the lines in red?\n\nUse the `findobj` figure method.",
"_____no_output_____"
]
],
[
[
"import matplotlib as mpl\n\nsns.set_style(\"white\")\n\nfig = evoked.plot(show=False) # butterfly plots\n\n\nfig.subplots_adjust(hspace=1.0)\nfor text in fig.findobj(mpl.text.Text):\n text.set_fontsize(18)\n text.set_color('blue')\n\nfor line in fig.findobj(mpl.lines.Line2D):\n line.set_color('yellow')",
"_____no_output_____"
]
],
[
[
"## Teaser on seaborn with Pandas",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"evoked_peak = evoked.copy().crop(0.07, 0.1)\ndata = evoked_peak.data",
"_____no_output_____"
],
[
"peaks = np.max(data, axis=1)\npeaks.shape",
"_____no_output_____"
],
[
"latencies = evoked_peak.times[np.argmax(data, axis=1)]\nlatencies.shape",
"_____no_output_____"
],
[
"ch_names = evoked.ch_names\nlen(ch_names)",
"_____no_output_____"
],
[
"layout = mne.find_layout(evoked.info)\nlayout",
"_____no_output_____"
],
[
"idx = [k for k, n in enumerate(layout.names) if n in ch_names]\nlen(idx)",
"_____no_output_____"
],
[
"pos_x, pos_y, _, _ = layout.pos[idx].T\npos_x.shape",
"_____no_output_____"
],
[
"df = pd.DataFrame(dict(ch_names=ch_names, peaks=1e13 * peaks,\n latencies=1e3 * latencies,\n pos_x=pos_x, pos_y=pos_y))\ndf.head()",
"_____no_output_____"
],
[
"df.peaks.describe()",
"_____no_output_____"
],
[
"sns.set_palette('muted')\ndf.plot.scatter('pos_x', 'pos_y')",
"_____no_output_____"
],
[
"sns.lmplot(x=\"latencies\", y=\"peaks\", data=df);",
"_____no_output_____"
],
[
"sns.set_style(\"whitegrid\")\nsns.lmplot(x=\"latencies\", y=\"pos_x\", data=df[df.peaks > 50]);",
"_____no_output_____"
],
[
"m = np.mean(df.pos_x)\nprint(m)\ndf['laterality'] = [('Left' if p < m else 'Right') for p in df.pos_x]",
"0.403390651112\n"
],
[
"sns.set_style(\"whitegrid\")\nsns.set_palette('Set2')\nsns.barplot(data=df, x='laterality', y='latencies');",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccfe50db3e852d823e2bf98f59460e60adf5c01 | 6,152 | ipynb | Jupyter Notebook | deep-learning/Faster R-CNN/preprocess_data.ipynb | georgepachitariu/machine-learning-portfolio | 47452524b0f2ccf409ba12e6a717157e569d62e1 | [
"Apache-2.0"
] | 2 | 2020-11-25T11:27:34.000Z | 2021-01-19T17:42:47.000Z | deep-learning/Faster R-CNN/preprocess_data.ipynb | georgepachitariu/machine-learning-portfolio | 47452524b0f2ccf409ba12e6a717157e569d62e1 | [
"Apache-2.0"
] | null | null | null | deep-learning/Faster R-CNN/preprocess_data.ipynb | georgepachitariu/machine-learning-portfolio | 47452524b0f2ccf409ba12e6a717157e569d62e1 | [
"Apache-2.0"
] | null | null | null | 42.427586 | 132 | 0.526008 | [
[
[
"#### This module preprocesses the data to create the regression and classification labels used by the Region Proposing Network",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nSCALE = 600/18\nOUT_LEN = 17\n\ndef get_box_extra(y1, x1, y2, x2):\n center_x = (x1 + x2) // 2\n center_y = (y1 + y2) // 2\n width = x2 - x1\n height = y2 - y1 \n return center_x, center_y, width, height\n\ndef create_anchors_map():\n anchors_map = np.zeros((17, 17, 3, 3), dtype=[('y1', 'i4'),('x1', 'i4'), ('y2', 'i4'), ('x2', 'i4')])\n for i in range(17):\n for j in range(17):\n for r, ratio in enumerate(((1, 1), (0.75, 1.5), (1.5, 0.75))):\n for s, size in enumerate((128, 256, 512)):\n anchor_x_center = i * SCALE\n anchor_x1 = anchor_x_center - ratio[1] * size / 2\n anchor_x2 = anchor_x_center + ratio[1] * size / 2\n \n anchor_y_center = j * SCALE\n anchor_y1 = anchor_y_center - ratio[0] * size / 2\n anchor_y2 = anchor_y_center + ratio[0] * size / 2\n \n anchors_map[i][j][r][s] = (anchor_y1, anchor_x1, anchor_y2, anchor_x2)\n return anchors_map\n \nanchors_map = create_anchors_map()",
"_____no_output_____"
],
[
"def prepare_output_values(row_dict):\n # output of last regression layer per image: (17, 17, 36) \n # 17 anchors and 4 (dimensions) * 9 (scales & sizes)\n\n y_regr = np.zeros((17,17,3,3,4)) + 100\n y_class = np.zeros((17,17,3,3))\n \n for obj in row_dict['objects']['bbox']:\n \n groundtruth_y1, groundtruth_x1, groundtruth_y2, groundtruth_x2 = bbox_perc_to_pixels(obj)\n groundtruth_center_x, groundtruth_center_y, groundtruth_width, groundtruth_height = get_box_extra(\n groundtruth_y1, groundtruth_x1, groundtruth_y2, groundtruth_x2)\n ###################\n ## REGRESSION\n anchor_center_x = (anchors_map['x1'] + anchors_map['x2']) // 2\n anchor_center_y = (anchors_map['y1'] + anchors_map['y2']) // 2\n anchor_width = anchors_map['x2'] - anchors_map['x1']\n anchor_height = anchors_map['y2'] - anchors_map['y1']\n\n current_r = np.zeros(y_regr.shape)\n current_r[:,:,:,:,0] = (groundtruth_center_x - anchor_center_x) / anchor_width # t_x\n current_r[:,:,:,:,1] = (groundtruth_center_y - anchor_center_y) / anchor_height # t_y\n current_r[:,:,:,:,2] = np.log(groundtruth_width / anchor_width) # t_w\n current_r[:,:,:,:,3] = np.log(groundtruth_height / anchor_height) # t_h\n \n # Overwrite anchors distances closer to ground-truth object.\n # cloer = minimum sum of (t_x, t_y, t_w, t_h)\n current_r_sum = np.sum(np.abs(current_r), axis = -1)\n y_regr_sum = np.sum(np.abs(y_regr), axis = -1) \n y_regr[current_r_sum < y_regr_sum] = current_r[current_r_sum < y_regr_sum] # TODO Is this correct?\n # Doesn't it overwrite only the last axis?\n \n ###################\n ## CLASSIFICATION\n x1 = np.maximum(groundtruth_x1, anchors_map['x1'])\n y1 = np.maximum(groundtruth_y1, anchors_map['y1'])\n x2 = np.minimum(groundtruth_x2, anchors_map['x2'])\n y2 = np.minimum(groundtruth_y2, anchors_map['y2']) \n intersection_area = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1)\n \n # Intersection over Union\n groundtruth_area = (groundtruth_x2 - groundtruth_x1) * (groundtruth_y2 - groundtruth_y1)\n anchor_area = anchor_width * anchor_height\n current_iou = intersection_area / (groundtruth_area + anchor_area - intersection_area) \n \n # Overwrite the IOU if ground-truth objects with higher iou were found\n y_class = np.maximum(y_class, current_iou)\n\n return y_regr, y_class\n\n\ndef anchor_and_distance_to_groundtruth(anchor_y1, anchor_x1, anchor_y2, anchor_x2, distance):\n t_x, t_y, t_w, t_h = distance\n \n anchor_center_x, anchor_center_y, anchor_width, anchor_height = get_box_extra(\n anchor_y1, anchor_x1, anchor_y2, anchor_x2)\n \n groundtruth_center_x = anchor_center_x + t_x * anchor_width\n groundtruth_center_y = anchor_center_y + t_y * anchor_height\n groundtruth_width = anchor_width * np.e ** t_w\n groundtruth_height = anchor_height * np.e ** t_h\n \n return groundtruth_center_x - groundtruth_width / 2, \\\n groundtruth_center_y - groundtruth_height / 2, groundtruth_width, groundtruth_height ",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
]
] |
eccfe9cea1e90d2990c63328de811b4415b6ac6f | 26,168 | ipynb | Jupyter Notebook | examples/devlop/devlop-axline.ipynb | mwshinn/mpl-interactions | 9d05431d3fcdd167192604a1baa63e0226ec9805 | [
"BSD-3-Clause"
] | null | null | null | examples/devlop/devlop-axline.ipynb | mwshinn/mpl-interactions | 9d05431d3fcdd167192604a1baa63e0226ec9805 | [
"BSD-3-Clause"
] | null | null | null | examples/devlop/devlop-axline.ipynb | mwshinn/mpl-interactions | 9d05431d3fcdd167192604a1baa63e0226ec9805 | [
"BSD-3-Clause"
] | null | null | null | 49.560606 | 1,469 | 0.57941 | [
[
[
"%matplotlib ipympl\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n%load_ext autoreload\n%autoreload 2\nfrom mpl_interactions import *",
"_____no_output_____"
],
[
"fig, ax = plt.subplots()\ndef y(heck):\n return heck\ndef xmin(heck):\n return heck\n# controls = interactive_axhline(y,0,1, heck=(0,1))\ncontrols = interactive_axhline(y,xmin,1, heck=(0,1))\n# ret.set_ydata([.5,1])",
"_____no_output_____"
],
[
"plt.axhline()",
"_____no_output_____"
],
[
"\n\ndef interactive_axhline(\n y=0,\n xmin=0,\n xmax=1,\n ax=None,\n slider_formats=None,\n title=None,\n force_ipywidgets=False,\n play_buttons=False,\n play_button_pos=\"right\",\n controls=None,\n display_controls=True,\n **kwargs,\n):\n \"\"\"\n Control an horizontal line using widgets.\n\n parameters\n ----------\n y : float or function\n y position in data coordinates of the horizontal line.\n xmin : float or function\n Should be between 0 and 1, 0 being the far left of the plot, 1 the\n far right of the plot.\n xmax : float or function\n Should be between 0 and 1, 0 being the far left of the plot, 1 the\n far right of the plot.\n ax : matplotlib axis, optional\n If None a new figure and axis will be created\n slider_formats : None, string, or dict\n If None a default value of decimal points will be used. Uses the new {} style formatting\n force_ipywidgets : boolean\n If True ipywidgets will always be used, even if not using the ipympl backend.\n If False the function will try to detect if it is ok to use ipywidgets\n If ipywidgets are not used the function will fall back on matplotlib widgets\n play_buttons : bool or dict, optional\n Whether to attach an ipywidgets.Play widget to any sliders that get created.\n If a boolean it will apply to all kwargs, if a dictionary you choose which sliders you\n want to attach play buttons too.\n play_button_pos : str, or dict, or list(str)\n 'left' or 'right'. Whether to position the play widget(s) to the left or right of the slider(s)\n controls : mpl_interactions.controller.Controls\n An existing controls object if you want to tie multiple plot elements to the same set of\n controls\n display_controls : boolean\n Whether the controls should display themselve on creation. Ignored if controls is specified.\n\n returns\n -------\n controls\n \"\"\"\n ipympl = notebook_backend()\n fig, ax = gogogo_figure(ipympl, ax)\n use_ipywidgets = ipympl or force_ipywidgets\n slider_formats = create_slider_format_dict(slider_formats)\n\n controls, params = gogogo_controls(\n kwargs, controls, display_controls, slider_formats, play_buttons, play_button_pos\n )\n\n def update(params, indices, cache):\n if title is not None:\n ax.set_title(title.format(**params))\n y_ = callable_else_value(y, params, cache).item()\n line.set_ydata([y_, y_])\n xmin_ = callable_else_value(xmin, params, cache).item()\n xmax_ = callable_else_value(xmax, params, cache).item()\n line.set_xdata([xmin_, xmax_])\n # TODO consider updating just the ydatalim here\n\n controls.register_function(update, fig, params)\n line = ax.axhline(\n callable_else_value(y, params).item(),\n callable_else_value(xmin, params).item(),\n callable_else_value(xmax, params).item(),\n )\n return controls\n\n\ndef interactive_axvline(\n x=0,\n ymin=0,\n ymax=1,\n ax=None,\n slider_formats=None,\n title=None,\n force_ipywidgets=False,\n play_buttons=False,\n play_button_pos=\"right\",\n controls=None,\n display_controls=True,\n **kwargs,\n):\n ipympl = notebook_backend()\n fig, ax = gogogo_figure(ipympl, ax)\n use_ipywidgets = ipympl or force_ipywidgets\n slider_formats = create_slider_format_dict(slider_formats)\n\n controls, params = gogogo_controls(\n kwargs, controls, display_controls, slider_formats, play_buttons, play_button_pos\n )\n\n def update(params, indices, cache):\n if title is not None:\n ax.set_title(title.format(**params))\n x_ = callable_else_value(x, params, cache).item()\n line.set_ydata([x_, x_])\n ymin_ = callable_else_value(ymin, params, cache).item()\n ymax_ = callable_else_value(ymax, params, cache).item()\n line.set_xdata([ymin_, ymax_])\n # TODO consider updating just the ydatalim here\n\n controls.register_function(update, fig, params)\n line = ax.axvline(\n callable_else_value(x, params).item(),\n callable_else_value(ymin, params).item(),\n callable_else_value(ymax, params).item(),\n )\n return controls",
"_____no_output_____"
],
[
"ret.set_ydata([0.5, 1])",
"_____no_output_____"
],
[
"ret = ax.axhline(0,np.array(0),1)",
"_____no_output_____"
],
[
"arr = np.array(0)\narr.item()",
"_____no_output_____"
],
[
"np.asscalar(arr)",
"_____no_output_____"
],
[
"ret.set_xdata([0,1.5])",
"_____no_output_____"
],
[
"def axhline(y=0, xmin=0, xmax=1):\n ",
"_____no_output_____"
],
[
"ret.get_ydata()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccfea85cafb4d837a319f6c48c27f667e3c92c9 | 14,784 | ipynb | Jupyter Notebook | code/chap20.ipynb | arunkhattri/ModSimPy | f90be88fd401edf11d16c72b11934f1e7160aeb5 | [
"MIT"
] | 1 | 2020-04-26T20:48:26.000Z | 2020-04-26T20:48:26.000Z | code/chap20.ipynb | arunkhattri/ModSimPy | f90be88fd401edf11d16c72b11934f1e7160aeb5 | [
"MIT"
] | null | null | null | code/chap20.ipynb | arunkhattri/ModSimPy | f90be88fd401edf11d16c72b11934f1e7160aeb5 | [
"MIT"
] | null | null | null | 21.837518 | 244 | 0.540923 | [
[
[
"# Modeling and Simulation in Python\n\nChapter 20\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n",
"_____no_output_____"
]
],
[
[
"# Configure Jupyter so figures appear in the notebook\n%matplotlib inline\n\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import functions from the modsim.py module\nfrom modsim import *",
"_____no_output_____"
]
],
[
[
"### Dropping pennies\n\nI'll start by getting the units we need from Pint.",
"_____no_output_____"
]
],
[
[
"m = UNITS.meter\ns = UNITS.second",
"_____no_output_____"
]
],
[
[
"And defining the initial state.",
"_____no_output_____"
]
],
[
[
"init = State(y=381 * m, \n v=0 * m/s)",
"_____no_output_____"
]
],
[
[
"Acceleration due to gravity is about 9.8 m / s$^2$.",
"_____no_output_____"
]
],
[
[
"g = 9.8 * m/s**2",
"_____no_output_____"
]
],
[
[
"When we call `odeint`, we need an array of timestamps where we want to compute the solution.\n\nI'll start with a duration of 10 seconds.",
"_____no_output_____"
]
],
[
[
"t_end = 10 * s",
"_____no_output_____"
]
],
[
[
"Now we make a `System` object.",
"_____no_output_____"
]
],
[
[
"system = System(init=init, g=g, t_end=t_end)",
"_____no_output_____"
]
],
[
[
"And define the slope function.",
"_____no_output_____"
]
],
[
[
"def slope_func(state, t, system):\n \"\"\"Compute derivatives of the state.\n \n state: position, velocity\n t: time\n system: System object containing `g`\n \n returns: derivatives of y and v\n \"\"\"\n y, v = state\n unpack(system) \n\n dydt = v\n dvdt = -g\n \n return dydt, dvdt",
"_____no_output_____"
]
],
[
[
"It's always a good idea to test the slope function with the initial conditions.",
"_____no_output_____"
]
],
[
[
"dydt, dvdt = slope_func(init, 0, system)\nprint(dydt)\nprint(dvdt)",
"_____no_output_____"
]
],
[
[
"Now we're ready to call `run_ode_solver`",
"_____no_output_____"
]
],
[
[
"results, details = run_ode_solver(system, slope_func, max_step=0.5*s)\ndetails.message",
"_____no_output_____"
]
],
[
[
"Here are the results:",
"_____no_output_____"
]
],
[
[
"results",
"_____no_output_____"
]
],
[
[
"And here's position as a function of time:",
"_____no_output_____"
]
],
[
[
"def plot_position(results):\n plot(results.y, label='y')\n decorate(xlabel='Time (s)',\n ylabel='Position (m)')\n\nplot_position(results)\nsavefig('figs/chap09-fig01.pdf')",
"_____no_output_____"
]
],
[
[
"### Onto the sidewalk\n\nTo figure out when the penny hit the sidewalk, we can use `crossings`, which finds the times where a `Series` passes through a given value.",
"_____no_output_____"
]
],
[
[
"t_crossings = crossings(results.y, 0)",
"_____no_output_____"
]
],
[
[
"For this example there should be just one crossing, the time when the penny hits the sidewalk.",
"_____no_output_____"
]
],
[
[
"t_sidewalk = t_crossings[0] * s",
"_____no_output_____"
]
],
[
[
"We can compare that to the exact result. Without air resistance, we have\n\n$v = -g t$\n\nand\n\n$y = 381 - g t^2 / 2$\n\nSetting $y=0$ and solving for $t$ yields\n\n$t = \\sqrt{\\frac{2 y_{init}}{g}}$",
"_____no_output_____"
]
],
[
[
"sqrt(2 * init.y / g)",
"_____no_output_____"
]
],
[
[
"The estimate is accurate to about 10 decimal places.",
"_____no_output_____"
],
[
"## Events\n\nInstead of running the simulation until the penny goes through the sidewalk, it would be better to detect the point where the penny hits the sidewalk and stop. `run_ode_solver` provides exactly the tool we need, **event functions**.\n\nHere's an event function that returns the height of the penny above the sidewalk:",
"_____no_output_____"
]
],
[
[
"def event_func(state, t, system):\n \"\"\"Return the height of the penny above the sidewalk.\n \"\"\"\n y, v = state\n return y",
"_____no_output_____"
]
],
[
[
"And here's how we pass it to `run_ode_solver`. The solver should run until the event function returns 0, and then terminate.",
"_____no_output_____"
]
],
[
[
"results, details = run_ode_solver(system, slope_func, events=event_func)\ndetails",
"_____no_output_____"
]
],
[
[
"The message from the solver indicates the solver stopped because the event we wanted to detect happened.\n\nHere are the results:",
"_____no_output_____"
]
],
[
[
"results",
"_____no_output_____"
]
],
[
[
"With the `events` option, the solver returns the actual time steps it computed, which are not necessarily equally spaced. \n\nThe last time step is when the event occurred:",
"_____no_output_____"
]
],
[
[
"t_sidewalk = get_last_label(results) * s",
"_____no_output_____"
]
],
[
[
"Unfortunately, `run_ode_solver` does not carry the units through the computation, so we have to put them back at the end.\n\nWe could also get the time of the event from `details`, but it's a minor nuisance because it comes packed in an array:",
"_____no_output_____"
]
],
[
[
"details.t_events[0][0] * s",
"_____no_output_____"
]
],
[
[
"The result is accurate to about 15 decimal places.\n\nWe can also check the velocity of the penny when it hits the sidewalk:",
"_____no_output_____"
]
],
[
[
"v_sidewalk = get_last_value(results.v) * m / s",
"_____no_output_____"
]
],
[
[
"And convert to kilometers per hour.",
"_____no_output_____"
]
],
[
[
"km = UNITS.kilometer\nh = UNITS.hour\nv_sidewalk.to(km / h)",
"_____no_output_____"
]
],
[
[
"If there were no air resistance, the penny would hit the sidewalk (or someone's head) at more than 300 km/h.\n\nSo it's a good thing there is air resistance.",
"_____no_output_____"
],
[
"## Under the hood\n\nHere is the source code for `crossings` so you can see what's happening under the hood:",
"_____no_output_____"
]
],
[
[
"%psource crossings",
"_____no_output_____"
]
],
[
[
"The [documentation of InterpolatedUnivariateSpline is here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.InterpolatedUnivariateSpline.html).\n\nAnd you can read the [documentation of `scipy.integrate.solve_ivp`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html) to learn more about how `run_ode_solver` works.",
"_____no_output_____"
],
[
"### Exercises\n\n**Exercise:** Here's a question from the web site [Ask an Astronomer](http://curious.astro.cornell.edu/about-us/39-our-solar-system/the-earth/other-catastrophes/57-how-long-would-it-take-the-earth-to-fall-into-the-sun-intermediate):\n\n\"If the Earth suddenly stopped orbiting the Sun, I know eventually it would be pulled in by the Sun's gravity and hit it. How long would it take the Earth to hit the Sun? I imagine it would go slowly at first and then pick up speed.\"\n\nUse `run_ode_solver` to answer this question.\n\nHere are some suggestions about how to proceed:\n\n1. Look up the Law of Universal Gravitation and any constants you need. I suggest you work entirely in SI units: meters, kilograms, and Newtons.\n\n2. When the distance between the Earth and the Sun gets small, this system behaves badly, so you should use an event function to stop when the surface of Earth reaches the surface of the Sun.\n\n3. Express your answer in days, and plot the results as millions of kilometers versus days.\n\nIf you read the reply by Dave Rothstein, you will see other ways to solve the problem, and a good discussion of the modeling decisions behind them.\n\nYou might also be interested to know that [it's actually not that easy to get to the Sun](https://www.theatlantic.com/science/archive/2018/08/parker-solar-probe-launch-nasa/567197/).",
"_____no_output_____"
]
],
[
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccfeb579683eb9d18db078ed09d97771554f429 | 15,645 | ipynb | Jupyter Notebook | notebooks/load matrix data.ipynb | MTES-MCT/sparte | 3b8ae6d21da81ca761d64ae9dfe2c8f54487211c | [
"MIT"
] | null | null | null | notebooks/load matrix data.ipynb | MTES-MCT/sparte | 3b8ae6d21da81ca761d64ae9dfe2c8f54487211c | [
"MIT"
] | 3 | 2022-02-10T11:47:58.000Z | 2022-02-23T18:50:24.000Z | notebooks/load matrix data.ipynb | MTES-MCT/sparte | 3b8ae6d21da81ca761d64ae9dfe2c8f54487211c | [
"MIT"
] | null | null | null | 30.261122 | 148 | 0.499585 | [
[
[
"import csv\nfrom public_data.storages import DataStorage\nfrom prettytable import PrettyTable\nfrom public_data.models import CouvertureSol, UsageSol, CouvertureUsageMatrix\n\nfilename = \"Artif_conso_NAF.csv\"\nstorage = DataStorage()\n",
"_____no_output_____"
],
[
"file_stream = storage.open(filename)\nlines = file_stream.read()\nlines = lines.decode('utf-8-sig')\nlines = lines.splitlines(True)\nlines[0] = lines[0].replace(\" \", \".\")\nlines",
"_____no_output_____"
],
[
"headers = lines[0].split(\";\")\nheaders = [_.replace(\"\\r\\n\", \"\") for _ in headers if _]\nheaders",
"_____no_output_____"
],
[
"reader = csv.DictReader(lines, delimiter=';')\nitems = []\nfor row in reader:\n usage_code = row['']\n for couv_code in headers:\n if row[couv_code]:\n items.append((usage_code, couv_code, row[couv_code]))\n\nitems.append((\"US2\", \"CS1.1.2.2\", \"Artif\")) \n\nprint(len(items))\nitems[:10]",
"192\n"
],
[
"def get_all_children(cs):\n children = []\n for cs_child in cs.children.all():\n children += get_all_children(cs_child)\n children.append(cs_child)\n return children\n\nfor usage_code, couv_code, label in items:\n cs = CouvertureSol.objects.get(code_prefix=couv_code)\n us = UsageSol.objects.get(code_prefix=usage_code)\n all_cs = get_all_children(cs) + [cs]\n all_us = get_all_children(us) + [us]\n all = list(zip(all_cs, all_us))\n if len(all) > 1:\n print(usage_code, couv_code, label)\n print(all)\nlen(items) ",
"_____no_output_____"
],
[
"for usage_code, couv_code, label in items:\n try:\n matrix = CouvertureUsageMatrix.objects.get(\n couverture__code_prefix=couv_code, usage__code_prefix=usage_code\n )\n except CouvertureUsageMatrix.DoesNotExist:\n print(usage_code, couv_code, label)",
"_____no_output_____"
],
[
"labels = set([item[2] for item in items])\nlabels",
"_____no_output_____"
],
[
"transco = {\n 'Artif': CouvertureUsageMatrix.LabelChoices.ARTIFICIAL,\n 'Artif non conso': CouvertureUsageMatrix.LabelChoices.ARTIF_NOT_CONSUMED,\n 'Conso': CouvertureUsageMatrix.LabelChoices.CONSUMED,\n 'NAF': CouvertureUsageMatrix.LabelChoices.NAF,\n}\ntransco",
"_____no_output_____"
],
[
"for usage_code, couv_code, label in items:\n matrix = CouvertureUsageMatrix.objects.get(couverture__code_prefix=couv_code, usage__code_prefix=usage_code)\n matrix.label = transco[label]\n matrix.compute()\n print(label, matrix)\n matrix.save()",
"Artif non conso CS1.1.1.1-US1.1:a\nArtif CS1.1.1.2-US1.1:ac\nArtif CS1.1.2.1-US1.1:ac\nNAF CS1.2.2-US1.1:n\nNAF CS2.1.1.1-US1.1:n\nNAF CS2.1.2-US1.1:n\nNAF CS2.1.3-US1.1:n\nNAF CS2.2.1-US1.1:n\nNAF CS2.2.2-US1.1:n\nArtif non conso CS1.1.1.1-US1.2:a\nArtif CS1.1.1.2-US1.2:ac\nArtif CS1.1.2.1-US1.2:ac\nNAF CS2.1.1.1-US1.2:n\nNAF CS2.1.1.2-US1.2:n\nNAF CS2.1.1.3-US1.2:n\nNAF CS2.1.2-US1.2:n\nArtif CS1.1.1.1-US1.3:ac\nArtif CS1.1.1.2-US1.3:ac\nArtif CS1.1.2.1-US1.3:ac\nNAF CS1.2.2-US1.3:n\nNAF CS2.1.1.1-US1.3:n\nNAF CS2.1.1.2-US1.3:n\nNAF CS2.1.1.3-US1.3:n\nNAF CS2.1.2-US1.3:n\nNAF CS2.2.1-US1.3:n\nNAF CS2.2.2-US1.3:n\nArtif CS1.1.1.1-US1.4:ac\nArtif CS1.1.1.2-US1.4:ac\nArtif CS1.1.2.1-US1.4:ac\nNAF CS1.2.2-US1.4:n\nNAF CS2.1.1.1-US1.4:n\nNAF CS2.1.1.2-US1.4:n\nNAF CS2.1.1.3-US1.4:n\nNAF CS2.1.2-US1.4:n\nNAF CS2.2.1-US1.4:n\nArtif CS1.1.1.1-US1.5:ac\nArtif CS1.1.1.2-US1.5:ac\nArtif CS1.1.2.1-US1.5:ac\nNAF CS2.1.1.1-US1.5:n\nNAF CS2.1.1.2-US1.5:n\nNAF CS2.1.1.3-US1.5:n\nNAF CS2.1.2-US1.5:n\nNAF CS2.2.1-US1.5:n\nArtif CS1.1.1.1-US235:ac\nArtif CS1.1.1.2-US235:ac\nArtif CS1.1.2.1-US235:ac\nArtif CS1.1.2.2-US235:ac\nNAF CS1.2.1-US235:n\nNAF CS1.2.2-US235:n\nConso CS2.1.1.1-US235:cn\nConso CS2.1.1.2-US235:cn\nConso CS2.1.1.3-US235:cn\nConso CS2.1.2-US235:cn\nConso CS2.1.3-US235:cn\nConso CS2.2.1-US235:cn\nArtif CS1.1.1.1-US2:ac\nArtif CS1.1.1.2-US2:ac\nArtif CS1.1.2.1-US2:ac\nNAF CS1.2.1-US2:n\nNAF CS1.2.2-US2:n\nConso CS2.1.1.1-US2:cn\nConso CS2.1.1.2-US2:cn\nConso CS2.1.1.3-US2:cn\nConso CS2.1.2-US2:cn\nConso CS2.1.3-US2:cn\nConso CS2.2.1-US2:cn\nArtif CS1.1.1.1-US3:ac\nArtif CS1.1.1.2-US3:ac\nArtif CS1.1.2.1-US3:ac\nArtif CS1.1.2.2-US3:ac\nNAF CS1.2.1-US3:n\nNAF CS1.2.2-US3:n\nConso CS2.1.1.1-US3:cn\nConso CS2.1.1.2-US3:cn\nConso CS2.1.1.3-US3:cn\nConso CS2.1.2-US3:cn\nConso CS2.1.3-US3:cn\nConso CS2.2.1-US3:cn\nArtif CS1.1.1.1-US5:ac\nArtif CS1.1.1.2-US5:ac\nArtif CS1.1.2.1-US5:ac\nArtif CS1.1.2.2-US5:ac\nNAF CS1.2.1-US5:n\nNAF CS1.2.2-US5:n\nConso CS2.1.1.1-US5:cn\nConso CS2.1.1.2-US5:cn\nConso CS2.1.1.3-US5:cn\nConso CS2.1.2-US5:cn\nConso CS2.1.3-US5:cn\nConso CS2.2.1-US5:cn\nArtif CS1.1.1.1-US4.1.1:ac\nArtif CS1.1.1.2-US4.1.1:ac\nArtif CS1.1.2.1-US4.1.1:ac\nNAF CS1.2.2-US4.1.1:n\nConso CS2.1.1.1-US4.1.1:cn\nConso CS2.1.1.2-US4.1.1:cn\nConso CS2.1.1.3-US4.1.1:cn\nConso CS2.1.2-US4.1.1:cn\nConso CS2.1.3-US4.1.1:cn\nConso CS2.2.1-US4.1.1:cn\nConso CS2.2.2-US4.1.1:cn\nArtif CS1.1.1.1-US4.1.2:ac\nArtif CS1.1.1.2-US4.1.2:ac\nArtif CS1.1.2.1-US4.1.2:ac\nConso CS2.1.1.1-US4.1.2:cn\nConso CS2.1.1.2-US4.1.2:cn\nConso CS2.1.1.3-US4.1.2:cn\nConso CS2.1.2-US4.1.2:cn\nConso CS2.1.3-US4.1.2:cn\nConso CS2.2.1-US4.1.2:cn\nConso CS2.2.2-US4.1.2:cn\nArtif CS1.1.1.1-US4.1.3:ac\nArtif CS1.1.1.2-US4.1.3:ac\nArtif CS1.1.2.1-US4.1.3:ac\nConso CS2.1.1.1-US4.1.3:cn\nConso CS2.1.1.2-US4.1.3:cn\nConso CS2.1.1.3-US4.1.3:cn\nConso CS2.1.2-US4.1.3:cn\nConso CS2.2.1-US4.1.3:cn\nArtif CS1.1.1.1-US4.1.4:ac\nArtif CS1.1.1.2-US4.1.4:ac\nArtif CS1.1.2.1-US4.1.4:ac\nNAF CS1.2.2-US4.1.4:n\nConso CS2.1.1.1-US4.1.4:cn\nConso CS2.1.1.2-US4.1.4:cn\nConso CS2.1.1.3-US4.1.4:cn\nConso CS2.1.2-US4.1.4:cn\nConso CS2.1.3-US4.1.4:cn\nConso CS2.2.1-US4.1.4:cn\nConso CS2.2.2-US4.1.4:cn\nArtif CS1.1.1.1-US4.1.5:ac\nArtif CS1.1.1.2-US4.1.5:ac\nArtif CS1.1.2.1-US4.1.5:ac\nConso CS2.1.1.1-US4.1.5:cn\nConso CS2.1.1.2-US4.1.5:cn\nConso CS2.1.1.3-US4.1.5:cn\nConso CS2.1.2-US4.1.5:cn\nConso CS2.1.3-US4.1.5:cn\nConso CS2.2.1-US4.1.5:cn\nConso CS2.2.2-US4.1.5:cn\nArtif CS1.1.1.1-US4.2:ac\nArtif CS1.1.1.2-US4.2:ac\nArtif CS1.1.2.1-US4.2:ac\nConso CS2.1.2-US4.2:cn\nConso CS2.2.1-US4.2:cn\nArtif CS1.1.1.1-US4.3:ac\nArtif CS1.1.1.2-US4.3:ac\nArtif CS1.1.2.1-US4.3:ac\nArtif CS1.1.2.2-US4.3:ac\nNAF CS1.2.2-US4.3:n\nConso CS2.1.1.1-US4.3:cn\nConso CS2.1.1.2-US4.3:cn\nConso CS2.1.1.3-US4.3:cn\nConso CS2.1.2-US4.3:cn\nConso CS2.2.1-US4.3:cn\nArtif CS1.1.1.1-US6.1:ac\nArtif CS1.1.1.2-US6.1:ac\nArtif CS1.1.2.1-US6.1:ac\nConso CS2.1.2-US6.1:cn\nConso CS2.2.1-US6.1:cn\nArtif CS1.1.1.1-US6.2:ac\nArtif CS1.1.1.2-US6.2:ac\nArtif CS1.1.2.1-US6.2:ac\nArtif CS1.1.2.2-US6.2:ac\nConso CS2.1.1.1-US6.2:cn\nConso CS2.1.1.2-US6.2:cn\nConso CS2.1.1.3-US6.2:cn\nConso CS2.1.2-US6.2:cn\nConso CS2.2.1-US6.2:cn\nArtif CS1.1.2.1-US6.3:ac\nNAF CS1.2.1-US6.3:n\nNAF CS1.2.2-US6.3:n\nNAF CS1.2.3-US6.3:n\nNAF CS2.1.1.1-US6.3:n\nNAF CS2.1.1.2-US6.3:n\nNAF CS2.1.1.3-US6.3:n\nNAF CS2.1.2-US6.3:n\nNAF CS2.2.1-US6.3:n\nNAF CS2.2.2-US6.3:n\nArtif CS1.1.1.2-US6.6:ac\nArtif CS1.1.2.1-US6.6:ac\nArtif CS1.1.2.2-US6.6:ac\nNAF CS1.2.1-US6.6:n\nNAF CS1.2.2-US6.6:n\nNAF CS2.1.1.1-US6.6:n\nNAF CS2.1.1.2-US6.6:n\nNAF CS2.1.1.3-US6.6:n\nNAF CS2.1.2-US6.6:n\nNAF CS2.1.3-US6.6:n\nNAF CS2.2.1-US6.6:n\nNAF CS2.2.2-US6.6:n\nArtif CS1.1.2.2-US2:ac\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
eccfecb47856550db16de0fa865705849618ef15 | 664,246 | ipynb | Jupyter Notebook | 1. FUNDAMENTOS/3. PROGRAMACION ESTADISTICA CON PYTHON/4. work in groups/spotify.ipynb | alvarochiqui/edem | d28861b04d9053848e26c24056395e5381ed398e | [
"Apache-2.0"
] | null | null | null | 1. FUNDAMENTOS/3. PROGRAMACION ESTADISTICA CON PYTHON/4. work in groups/spotify.ipynb | alvarochiqui/edem | d28861b04d9053848e26c24056395e5381ed398e | [
"Apache-2.0"
] | null | null | null | 1. FUNDAMENTOS/3. PROGRAMACION ESTADISTICA CON PYTHON/4. work in groups/spotify.ipynb | alvarochiqui/edem | d28861b04d9053848e26c24056395e5381ed398e | [
"Apache-2.0"
] | null | null | null | 202.328967 | 74,966 | 0.869121 | [
[
[
"#Descripción del dataset\n",
"_____no_output_____"
],
[
"Hemos escogido este dataset porque nos parecía muy interesante el hecho de poder analizar las causas por las que una canción se hace popular en Spotify, plataforma de música en streaming usada en todo el mundo.\n\nContamos con las siguientes variables:\n\n* **Popularidad (popu)**: mide la popularidad de una canción en una escala de 0 a 100. Cuanto más cerca del 100, más popular es la canción.\n\n* **Género musical (genre)**: ha sido dividido en **pop** y **no pop** para simplificar el análisis, ya que los géneros **no pop** eran muchos y muy dispersos.\n\n* **Año (year)**: los años van desde el 2010 hasta el 2019 ambos inclusive, y han sido agrupados en dos grupos: de **2010 a 2014** y de **2015 a 2019**. De esta manera agrupamos los datos en \"más actuales\" y \"más antiguos\" y podremos observar claramente las disferencias en el caso de que las hubiera.\n* **Pulsaciones por minuto (bpm)**: es el tempo de la canción. Esta medido en una escala de 0 al 210. Cuanto más alto el valor, más beats per minute.\n* **Energía (nrgy)**: mide la cuán energética es la cancion en una escala de 0 a 100. Cuanto más alto sea el valor, más energía tendrá la canción.\n* **Bailabilidad (dnce)**: mide lo bailable que pueda ser una canción en una escala de 0 a 100. A mayor puntuación, más fácil será bailar esa canción.\n* **Valencia (val)**: mide el \"estado de ánimo\" de la canción en una escala de 0 a 100. Cuanto más cerca del 100, más positiva será la canción. Esta variable ha sido categorizada para obtener una variable cualitativa más. \n* **Duración (dur)**: representa lo larga que es la canción en segundos. Esta variable ha sido categorizada para agrupar las canciones según su mayor o menor duración, ya que hemos considerado que los segundos exactos no son relevantes.\n* **Letra (lyrics)**: indica en un índice de 0 a 100 la parte cantada de una canción. A mayor puntuación, mayor parte cantada tendrá esa canción.\n\n\n",
"_____no_output_____"
]
],
[
[
"import os\nimport numpy as np\nimport pandas as pd\nfrom pandas.api.types import CategoricalDtype\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy.stats as stats \nfrom scipy.stats.stats import pearsonr\nfrom statsmodels.formula.api import ols\n\nfrom google.colab import drive",
"_____no_output_____"
],
[
"drive.mount('mydrive')",
"Drive already mounted at mydrive; to attempt to forcibly remount, call drive.mount(\"mydrive\", force_remount=True).\n"
],
[
"spoti = pd.read_csv (\"/content/mydrive/MyDrive/EDEM/PEP/spotify.csv\", sep= \";\")\nspoti",
"_____no_output_____"
]
],
[
[
"#Formulación de Hipótesis preanálisis",
"_____no_output_____"
],
[
"H1. Cuando la canción sea pop, más popular será.\n\nH2. Cuando más actual sea el año, más índice de popularidad.\n\nH3. Si la canción tiene más ritmo, más popular será.\n\nH4. Si la canción es más energética, más popular será.\n\nH5. Cuanto más bailable sea la canción, más popularidad.\n\nH6. Cuanto menos triste sea la canción, más popularidad.\n\nH7. Si la canción es larga, más popular será.\n\nH8. Si la canción tiene más contenido cantable (lyrics), más popular será.",
"_____no_output_____"
],
[
"# 1.Popularidad (Variable Target)\n",
"_____no_output_____"
],
[
"###Descripción",
"_____no_output_____"
]
],
[
[
"popu = spoti['popu'].describe()\npopu",
"_____no_output_____"
],
[
"n = popu[0]\nm_popu = popu[1]\nsd_popu = popu[2]",
"_____no_output_____"
]
],
[
[
"###Gráfico",
"_____no_output_____"
]
],
[
[
"popularidad = spoti['popu']\nplt.hist(popularidad, bins=15, edgecolor='black')\nplt.xlabel('Popularidad')\nplt.xticks(np.arange(0, 100, step= 10))\nplt.ylabel('Frequencia')\nprops = dict(boxstyle= 'round', facecolor='white', lw=0.5)\nplt.text(2,100,'Media:66.62''\\n''N:603' '\\n' 'SD: 14.26', bbox=props)\nplt.title('Figura 1: Número de canciones por popularidad ''\\n')\nplt.axvline(66.52, linewidth=1, linestyle='solid', color = 'red')\nplt.axvline(52, linewidth=1, linestyle= 'dashed', color= 'green')\nplt.axvline(81.04, linewidth=1, linestyle= 'dashed', color= 'green')\nplt.legend(labels=['Media', 'SD ± Media'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"# 2.Género",
"_____no_output_____"
],
[
"###Descripción",
"_____no_output_____"
]
],
[
[
"gen = spoti.genre.describe()\ngen",
"_____no_output_____"
],
[
"gen_table = spoti.groupby(['genre']).size()\nprint(gen_table)\nn=gen_table.sum()\ngen_table2 = (gen_table/n)*100\nprint(gen_table2)\nn=gen_table.sum()",
"genre\nno pop 135\npop 468\ndtype: int64\ngenre\nno pop 22.38806\npop 77.61194\ndtype: float64\n"
]
],
[
[
"###Gráfico",
"_____no_output_____"
]
],
[
[
"bar_list = ['no pop', 'pop']\nplt.bar(bar_list, gen_table2, edgecolor='black')\nplt.title(\"Figura 2.1. Porcentaje canciones no pop y pop\")\nplt.ylabel('Porcentaje')\nplt.xlabel('Género')\nplt.text(0,50,'n: 603')\nprops = dict(boxstyle='round', facecolor='white',lw=0.5)\ntextstr = '$\\mathrm{n}=%.0f$'%(n)\nplt.text (0,50, textstr , bbox=props)\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Comparación con popu",
"_____no_output_____"
]
],
[
[
"pop_no_popu=spoti.loc[spoti.genre=='no pop', \"popu\"]\npop_popu=spoti.loc[spoti.genre=='pop', \"popu\"] \n\nres = stats.f_oneway(pop_no_popu,pop_popu)\nprint(res)",
"F_onewayResult(statistic=0.013964697187775635, pvalue=0.9059706057171695)\n"
],
[
"plt.figure(figsize=(4,4))\nax = sns.pointplot(x=\"genre\", y=\"popu\", data=spoti,capsize=0.05, ci=95, join=0, order=['no pop', 'pop'])\nax.set_ylabel('Popularidad')\nplt.yticks(np.arange(60, 80, step=5))\nplt.axhline(y=spoti['popu'].mean(),linewidth=1,linestyle= 'dashed',color=\"green\")\nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\nplt.text(0.9,72,'Mean:66.52''\\n''n:603''\\n' 'Pval.:0.84', bbox=props)\nplt.xlabel('Género')\nplt.title('Figura 2.2. Media de popularidad según el género.''\\n')\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Miniconclusión",
"_____no_output_____"
],
[
"Como el p valor es mayor de 0.05, aceptamos la hipótesis nula. La popularidad no cambia significativamente si una canción es pop o no pop.",
"_____no_output_____"
],
[
"#3.Año",
"_____no_output_____"
],
[
"###Descripción",
"_____no_output_____"
]
],
[
[
"spoti.year.describe()\nmytable = spoti.groupby(['year']).size()\nprint(mytable)\nn = mytable.sum()\nmytable2 = (mytable/n)*100\nprint(mytable2)",
"year\n2010 51\n2011 53\n2012 35\n2013 71\n2014 58\n2015 95\n2016 80\n2017 65\n2018 64\n2019 31\ndtype: int64\nyear\n2010 8.457711\n2011 8.789386\n2012 5.804312\n2013 11.774461\n2014 9.618574\n2015 15.754561\n2016 13.266998\n2017 10.779436\n2018 10.613599\n2019 5.140962\ndtype: float64\n"
],
[
"spoti.loc[(spoti['year']==2010),\"year2\"] = \"2010-2014\"\nspoti.loc[(spoti['year']==2011),\"year2\"] = \"2010-2014\"\nspoti.loc[(spoti['year']==2012),\"year2\"] = \"2010-2014\"\nspoti.loc[(spoti['year']==2013),\"year2\"] = \"2010-2014\"\nspoti.loc[(spoti['year']==2014),\"year2\"] = \"2010-2014\"\nspoti.loc[(spoti['year']==2015),\"year2\"] = \"2015-2019\"\nspoti.loc[(spoti['year']==2016),\"year2\"] = \"2015-2019\"\nspoti.loc[(spoti['year']==2017),\"year2\"] = \"2015-2019\"\nspoti.loc[(spoti['year']==2018),\"year2\"] = \"2015-2019\"\nspoti.loc[(spoti['year']==2019),\"year2\"] = \"2015-2019\"\n\npd.crosstab(spoti.year, spoti.year2)",
"_____no_output_____"
],
[
"spoti.year2.describe()\nmytable3 = spoti.groupby(['year2']).size()\nn = mytable.sum()\nmytable4 = (mytable3/n)*100",
"_____no_output_____"
]
],
[
[
"###Gráfico",
"_____no_output_____"
]
],
[
[
"barlist = ['2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019']\nplt.bar(barlist, mytable2)\nplt.ylabel('Percentage')\nplt.xlabel('Year')\nplt.title('Figura 3.1. Porcentaje de canciones cada año')\nplt.text(0.5,15,'n: 603')\nprops = dict(boxstyle='round', facecolor='white',lw=0.5)\ntextstr = '$\\mathrm{n}=%.0f$'%(n)\nplt.text (0.5,15, textstr , bbox=props)\nplt.show()",
"_____no_output_____"
],
[
"barlist2 = ['1: 2010-2014', '2: 2015-2019']\nplt.bar(barlist2, mytable4)\nplt.ylabel('Percentage')\nplt.xlabel('Years')\nplt.title('Figura 3.2. Porcentaje de canciones por años')\nplt.text(0,50,'n: 603')\nprops = dict(boxstyle='round', facecolor='white',lw=0.5)\ntextstr = '$\\mathrm{n}=%.0f$'%(n)\nplt.text (0,50, textstr , bbox=props)\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Comparación con popu",
"_____no_output_____"
]
],
[
[
"spoti.groupby('year2').popu.mean()",
"_____no_output_____"
],
[
"popu10_14 = spoti.loc[spoti.year2=='2010-2014', 'popu']\npopu15_19 = spoti.loc[spoti.year2=='2015-2019', 'popu']\n\nres= stats.stats.ttest_ind(popu10_14, popu15_19, equal_var=False)\nprint(round(res[1],3), round(res[0],3))",
"0.0 -4.328\n"
],
[
"plt.figure(figsize=(5,5))\nax = sns.pointplot(x= 'year2', y= 'popu',\n data= spoti, ci= 99, join=0)\n\nplt.yticks(np.arange(60,80, step=5))\nplt.axhline(y=spoti.popu.mean(), linewidth=1, linestyle = 'dashed', color='green')\nax.set_ylabel('Popularidad')\n\nprops= dict(boxstyle='round', facecolor='white', lw=0.5)\nplt.text(0.05,70,'Media: 66.5' '\\n' 'n: 603' '\\n' 't: -4.11' '\\n' 'Pval: 0.00', bbox=props)\nplt.xlabel('Años')\nplt.title('Figura 3.3. Popularidad media por años''\\n')\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Miniconclusión",
"_____no_output_____"
],
[
"Concluimos que las variables año y popularidad están relacionadas y que existen diferencias estadísticamente significativas entre los grupos. Podemos afirmar esto basándonos en el p valor menor a 0,05 que nos ha devuelto la prueba estadística t-student, el cual rechaza la H0 de que los grupos son iguales.",
"_____no_output_____"
],
[
"#4.Beats per minute (bpm)\n",
"_____no_output_____"
],
[
"###Descripción",
"_____no_output_____"
]
],
[
[
"res = spoti.bpm.describe().round(3)\nres",
"_____no_output_____"
],
[
"m = res[1]\nsd = res[2]\nn = res[0]\nprint(\"Mean:\",m,\"\\n\",\"Standard Deviation:\",sd,\"\\n\",\"N:\",n)",
"Mean: 118.736 \n Standard Deviation: 24.32 \n N: 603.0\n"
]
],
[
[
"###Gráfico",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(5,5))\nx=spoti.bpm\nplt.hist (x, bins=10,edgecolor=\"black\")\nplt.title(\"Figura 4.1, Ritmo (bpm) de las canciones de Spotify.\")\nplt.xlabel(\"Beats per minute (bpm)\")\nplt.ylabel(\"Canciones\")\nprops = dict (boxstyle=\"round\", facecolor =\"white\", lw =1)\nplt.xticks(np.arange(50, 225, step=25))\nplt.yticks(np.arange(0, 225, step=25))\nplt.text(45, 170, \"n: 603\" \"\\n\" \"Mean: 118.74\" \"\\n\" \"std: 24.32\", bbox=props)\nplt.axvline(x=m, linewidth=1, linestyle= 'solid',color=\"red\", label='Mean')\nplt.axvline(x=(m+sd) , linewidth=1, linestyle= 'dashed',color=\"darkgreen\", label='m + sd')\nplt.axvline(x=(m-sd), linewidth=1, linestyle= 'dashed',color=\"darkgreen\", label='m - sd')\nplt.legend(labels=['Media', 'SD ± Media'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Comparación con popu",
"_____no_output_____"
]
],
[
[
"x= spoti.bpm\ny=spoti[\"popu\"]\npearsonr (x,y)\nr, p_val = pearsonr(x,y)\nn = len(spoti[\"popu\"])\nprint('r:', round(r,3), 'P.Val:', round(p_val,3), 'n:', n)",
"r: -0.018 P.Val: 0.659 n: 603\n"
],
[
"plt.figure(figsize=(5,5))\nx= spoti.bpm\ny=spoti[\"popu\"]\nplt.scatter (x, y, s=20, facecolors=\"none\", edgecolors=\"C0\")\nplt.xticks(np.arange(0,225,step=25))\nplt.yticks(np.arange(0,110,step=10))\nplt.title(\"Figura 4.2, Popularidad de las canciones sobre su ritmo (bpm)\")\nplt.xlabel(\"Beats per minute (bpm)\")\nplt.ylabel(\"Popularidad\")\nprops =dict(boxstyle =\"round\", facecolor =\"white\", lw=0.5)\ntextstr = '$\\mathrm{r}=%.2f$\\n$\\mathrm{P.Val:}=%.3f$\\n$\\mathrm{n}=%.0f$'%(r, p_val, n)\nplt.text (10,10, textstr , bbox=props)\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Miniconclusión",
"_____no_output_____"
],
[
"Al ser el p-value mayor de 0.05, no se rechaza la hipótesis nula. El ritmo de las canciones (bpm), no tiene relación con la popularidad de las canciones.",
"_____no_output_____"
],
[
"#5.Energía",
"_____no_output_____"
],
[
"###Descripción",
"_____no_output_____"
]
],
[
[
"res= spoti.nrgy.describe().round(3)\nres",
"_____no_output_____"
],
[
"m = res[1]\nsd = res[2]\nn = res[0]\nprint(\"Mean:\",m,\"\\n\",\"Standard Deviation:\",sd,\"\\n\",\"N:\",n)",
"Mean: 70.62 \n Standard Deviation: 16.055 \n N: 603.0\n"
]
],
[
[
"###Gráfico",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(5,5))\nx=spoti.nrgy\nplt.hist (x, bins=10,edgecolor=\"black\")\nplt.title(\"Figura 5.1, Energía de las canciones de Spotify.\")\nplt.xlabel(\"Energía\")\nplt.ylabel(\"Canciones\")\nprops = dict (boxstyle=\"round\", facecolor =\"white\", lw =1)\nplt.xticks(np.arange(0, 101, step=10))\nplt.yticks(np.arange(0, 175, step=10))\nplt.text(10, 110, \"n: 603\" \"\\n\" \"Mean: 70.602\" \"\\n\" \"std: 16.055\", bbox=props)\nplt.axvline(x=m, linewidth=1, linestyle= 'solid',color=\"red\", label='Mean')\nplt.axvline(x=(m+sd) , linewidth=1, linestyle= 'dashed',color=\"darkgreen\", label='m + sd')\nplt.axvline(x=(m-sd), linewidth=1, linestyle= 'dashed',color=\"darkgreen\", label='m - sd')\nplt.legend(labels=['Media', 'SD ± Media'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Comparación con popu",
"_____no_output_____"
]
],
[
[
"x= spoti.nrgy\ny=spoti[\"popu\"]\npearsonr (x,y)\nr, p_val = pearsonr(x,y)\nn = len(spoti[\"popu\"])\nprint('r:', round(r,3), 'P.Val:', round(p_val,3), 'n:', n)",
"r: -0.094 P.Val: 0.021 n: 603\n"
],
[
"plt.figure(figsize=(5,5))\nx= spoti.nrgy\ny=spoti[\"popu\"]\nplt.scatter (x, y, s=20, facecolors=\"none\", edgecolors=\"C0\")\nplt.xticks(np.arange(0,110,step=10))\nplt.yticks(np.arange(0,110,step=10))\nplt.title(\"Figura 5.2, Popularidad de las canciones sobre su energía\")\nplt.xlabel(\"Energía\")\nplt.ylabel(\"Popularidad\")\nprops =dict(boxstyle =\"round\", facecolor =\"white\", lw=0.5)\ntextstr = '$\\mathrm{r}=%.2f$\\n$\\mathrm{P.Val:}=%.3f$\\n$\\mathrm{n}=%.0f$'%(r, p_val, n)\nplt.text (10,10, textstr , bbox=props)\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Miniconclusión",
"_____no_output_____"
],
[
"Como el p-value es menor que 0.05, se rechaza la hipótesis nula. La energía de la canciones tiene relación con la popularidad de las canciones.\n",
"_____no_output_____"
],
[
"#6.Danzabilidad",
"_____no_output_____"
],
[
"###Descripción",
"_____no_output_____"
]
],
[
[
"dance = spoti['dnce'].describe()\ndance",
"_____no_output_____"
],
[
"n = dance[0]\nm_dance = dance[1]\nsd_dance = dance[2]",
"_____no_output_____"
]
],
[
[
"###Gráfico",
"_____no_output_____"
]
],
[
[
"x=spoti['dnce']\nplt.hist(x,edgecolor='black',bins=20)\nplt.xticks(np.arange(0,100, step=10))\nplt.title(\"Figura 6.1. Danzabilidad\")\nplt.ylabel('Frecuencia')\nplt.xlabel('Nivel de danzabilidad')\nprops=dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr= '$\\mathrm{Media}=%.2f$\\n$\\mathrm{SD}=%.3f$\\n$\\mathrm{N}=%.0f$'%(m_dance, sd_dance, n)\nplt.text (3,55, textstr , bbox=props)\nplt.axvline(x=m_popu, linewidth=1, linestyle= 'solid', color=\"red\", label='Mean')\nplt.axvline(x=m_popu-sd_popu, linewidth=1, linestyle= 'dashed', color=\"green\", label='- 1 S.D.')\nplt.axvline(x=m_popu + sd_popu, linewidth=1, linestyle= 'dashed', color=\"green\", label='+ 1 S.D.')\nplt.legend(labels=['Media', 'SD ± Media'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Comparación con popu",
"_____no_output_____"
]
],
[
[
"x=spoti['dnce']\ny=spoti['popu']\npearsonr(x,y)\n\nr, p_val=pearsonr(x,y)\n\nprint(r,p_val)\n\nprint ('r:', round(r,3), 'P.Val:', round(p_val,3), 'n:', n)",
"0.08314615964216698 0.04124678792324346\nr: 0.083 P.Val: 0.041 n: 603.0\n"
],
[
"plt.figure(figsize=(5,5))\nplt.scatter(spoti['dnce'], spoti['popu'], s=20, facecolors='none', edgecolors='C0')\nplt.xticks(np.arange(0, 110, step=10))\nplt.yticks(np.arange(0, 110, step=10))\nplt.title(\"Figura 6.2. Popularidad según la danzabilidad\")\nplt.ylabel('Popularidad')\nplt.xlabel('Danzabilidad')\nprops=dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr= '$\\mathrm{r}=%.2f$\\n$\\mathrm{P.Val:}=%.3f$\\n$\\mathrm{n}=%.0f$'%(r, p_val, n)\nplt.text (10,10, textstr , bbox=props)\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Miniconclusión",
"_____no_output_____"
],
[
"Como el p valor es menor de 0.05, rechazamos la hipótesis nula y decimos que las variables tienen diferencias estadísticamente significativas.",
"_____no_output_____"
],
[
"#7.Valencia",
"_____no_output_____"
],
[
"###Descripcion",
"_____no_output_____"
]
],
[
[
"res= spoti.val.describe()\nprint(res)\nm = res[1]\nsd = res[2]\nn = res[0]",
"count 603.000000\nmean 52.308458\nstd 22.412200\nmin 4.000000\n25% 35.000000\n50% 52.000000\n75% 69.000000\nmax 98.000000\nName: val, dtype: float64\n"
]
],
[
[
"###Recodificación",
"_____no_output_____"
]
],
[
[
"spoti.loc[(spoti['val']<(m-sd)),\"val2\"] = \"Puntuación Baja\"\nspoti.loc[(spoti['val']>=(m-sd)) & (spoti['val']<(m+sd)),\"val2\"] = \"Puntuación Media\"\nspoti.loc[(spoti['val']>(m+sd)),\"val2\"] = \"Puntuación Alta\"\n\nmy_categories=[\"Puntuación Baja\", \"Puntuación Media\", \"Puntuación Alta\"]\nval_type = CategoricalDtype(categories=my_categories, ordered=True)\nspoti[\"val2\"]=spoti.val2.astype(val_type)\nspoti.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 603 entries, 0 to 602\nData columns (total 14 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 ID 603 non-null int64 \n 1 title 603 non-null object \n 2 artist 603 non-null object \n 3 genre 603 non-null object \n 4 year 603 non-null int64 \n 5 bpm 603 non-null int64 \n 6 nrgy 603 non-null int64 \n 7 dnce 603 non-null int64 \n 8 val 603 non-null int64 \n 9 dur 603 non-null int64 \n 10 lyrics 603 non-null int64 \n 11 popu 603 non-null int64 \n 12 year2 603 non-null object \n 13 val2 603 non-null category\ndtypes: category(1), int64(9), object(4)\nmemory usage: 62.1+ KB\n"
],
[
"plt.scatter(spoti.val, spoti.val2)\nplt.show()",
"_____no_output_____"
],
[
"spoti.val2.describe()\nmytable = spoti.groupby(['val2']).size()\nn = mytable.sum()\nmytable2 = (mytable/n)*100\nprint(mytable2)",
"val2\nPuntuación Baja 18.242123\nPuntuación Media 63.018242\nPuntuación Alta 18.739635\ndtype: float64\n"
]
],
[
[
"###Gráfico",
"_____no_output_____"
]
],
[
[
"barlist = [\"Puntuación Baja\", \"Puntuación Media\", \"Puntuación Alta\"]\nplt.bar(barlist, mytable2)\nplt.ylabel('Percentage')\nplt.xlabel('Valence')\nplt.yticks(np.arange(0, 100, step= 10))\nprops = dict(boxstyle='round', facecolor='white',lw=0.5)\ntextstr = '$\\mathrm{Mean}=%.1f$\\n$\\mathrm{S.D.}=%.1f$\\n$\\mathrm{n}=%.0f$'%(m, sd, n)\nplt.text (0.2,70, textstr , bbox=props)\nplt.title('Figura 7.1: Porcentaje de canciones por índice de valencia''\\n')\n\n\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Comparación con popu",
"_____no_output_____"
]
],
[
[
"spoti.groupby('val2').popu.mean()\n\npopu_high = spoti.loc[spoti.val2=='Puntuación Alta', 'popu']\npopu_avg = spoti.loc[spoti.val2=='Puntuación Media', 'popu']\npopu_low = spoti.loc[spoti.val2=='Puntuación Baja', 'popu']\n\nres= stats.f_oneway(popu_low,popu_avg,popu_high)\nprint(round(res[0],3),'\\n',round(res[1],3))",
"1.186 \n 0.306\n"
],
[
"plt.figure(figsize=(5,5))\nax = sns.pointplot(x= 'val2', y= 'popu',\n data= spoti, ci= 99, join=0)\n\nplt.yticks(np.arange(50,90, step=5))\nplt.axhline(y=spoti.popu.mean(), linewidth=1, linestyle = 'dashed', color='green')\nax.set_ylabel('Popularidad')\n\nprops= dict(boxstyle='round', facecolor='white', lw=0.5)\nplt.text(0.01,75,'Mean: 66.5' '\\n' 'n: 603' '\\n' 't: 1.766' '\\n' 'Pval: 0.172', bbox=props)\nplt.xlabel('Año')\nplt.title('Figura 7.2. Popularidad media por valencia''\\n')\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Miniconclusion",
"_____no_output_____"
],
[
"Gracias al p valor mayor a 0,05, aceptamos la H0 y concluimos en que las variables no están relacionadas y no existen diferencias significativamente estadísticas.",
"_____no_output_____"
],
[
"#8.Durabilidad",
"_____no_output_____"
],
[
"###Descripción",
"_____no_output_____"
]
],
[
[
"print(spoti.dur.describe())",
"count 603.000000\nmean 224.674959\nstd 34.130059\nmin 134.000000\n25% 202.000000\n50% 221.000000\n75% 239.500000\nmax 424.000000\nName: dur, dtype: float64\n"
],
[
"plt.figure(figsize=(15, 5))\nsns.set_theme()\n\nax = plt.hist(x=spoti['dur'], density=True, bins=range(130,430,10), align=\"left\")\nax = sns.kdeplot(data=spoti, x='dur', bw_adjust = 1.3, cut = 0, palette=\"crest\")\nax.axvline(x=spoti.dur.mean(), color='black', linestyle=\"--\")\nax.axvline(x=spoti.dur.median(), color='red', linestyle=\"--\")\nax.legend(labels=['Distribución', 'Media', 'Mediana'])\nplt.title('Figura 8.1. Popularidad por durabilidad de la canción''\\n')\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Recodificación",
"_____no_output_____"
],
[
"Para la categorización de la variable cuantitativa \"durabilidad\", se ha optado a escoger la mediana como criterio de recodificación puesto que la durabilidad no sigue una distribución normal, como se observa en la figura anterior. De la misma manera, se tendrán en cuenta los cuartiles en la subdivisión del dataset.",
"_____no_output_____"
]
],
[
[
"\nspoti.loc[(spoti.dur<=(spoti.dur.describe()[5])), \"dur_cat_d\"]= \"Short\"\nspoti.loc[(spoti.dur>=(spoti.dur.describe()[5])), \"dur_cat_d\"]= \"Long\"\n\nspoti.loc[spoti.dur_cat_d=='Short', \"dur_cat_n\"]= 0\nspoti.loc[spoti.dur_cat_d=='Long', \"dur_cat_n\"]= 1\n\nspoti.loc[(spoti.dur<=(spoti.dur.describe()[4])), \"dur_cat\"]= \"Short\"\nspoti.loc[((spoti.dur>(spoti.dur.describe()[4])) & (spoti.dur<(spoti.dur.describe()[6]))), \"dur_cat\"]= \"Average\"\nspoti.loc[(spoti.dur>=(spoti.dur.describe()[6])), \"dur_cat\"]= \"Long\"",
"_____no_output_____"
]
],
[
[
"###Comparación con popu",
"_____no_output_____"
]
],
[
[
"t, p = stats.ttest_ind(spoti.loc[spoti.dur_cat_d == 'Short']['popu'], spoti.loc[spoti.dur_cat_d == 'Long']['popu'])\nn = len(spoti.dur)\nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr = '$\\mathrm{r}=%.2f$\\n$\\mathrm{P.Val:}=%.3f$\\n$\\mathrm{n}=%.0f$'%(t, p, n)\nax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14, verticalalignment='top', bbox=props)",
"_____no_output_____"
],
[
"plt.figure(figsize=(15,7))\nsns.set_theme()\n\nplt.suptitle('Figura 8.2. Popularidad por durabilidad de la canción''\\n')\n\nplt.subplot(1,2,1)\nax = sns.pointplot(x='dur_cat', y='popu', data=spoti, join=0, order=['Short', 'Average', 'Long'])\nax.axhline(y=spoti['popu'].mean(), linewidth=1, linestyle='dashed', color='green')\n\nt, p = stats.f_oneway(spoti.loc[spoti.dur_cat == 'Short']['popu'], spoti.loc[spoti.dur_cat == 'Average']['popu'], spoti.loc[spoti.dur_cat == 'Long']['popu'])\nn = len(spoti.dur)\nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr = '$\\mathrm{Estadístico}=%.2f$\\n$\\mathrm{P.Val:}=%.4f$\\n$\\mathrm{n}=%.0f$'%(t, p, n)\nax.text(0.05, 0.05, textstr, transform=ax.transAxes, fontsize=14, bbox=props)\nax.set_xlabel('Durabilidad')\nax.set_ylabel('Popularidad')\nax.set_title('Tres categorías')\n\nplt.subplot(1,2,2)\nax = sns.pointplot(x='dur_cat_d', y='popu', data=spoti, join=0, order=['Short', 'Long'])\nax.axhline(y=spoti['popu'].mean(), linewidth=1, linestyle='dashed', color='green')\n\nt, p = stats.ttest_ind(spoti.loc[spoti.dur_cat_d == 'Short']['popu'], spoti.loc[spoti.dur_cat_d == 'Long']['popu'])\nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr = '$\\mathrm{Estadístico}=%.2f$\\n$\\mathrm{P.Val:}=%.4f$\\n$\\mathrm{n}=%.0f$'%(t, p, n)\nax.text(0.05, 0.05, textstr, transform=ax.transAxes, fontsize=14, bbox=props)\nax.set_xlabel('Durabilidad')\nax.set_ylabel('Popularidad')\nax.set_title('Dos categorías')\n\nplt.show()\n\n\nsns.reset_orig()",
"_____no_output_____"
]
],
[
[
"###Miniconclusión",
"_____no_output_____"
],
[
"Con los resultados obtenidos en los análisis estadísticos, rechazando la hipótesis nula del segundo t-test, se confirma la existencia de una relación altamente significativa, aunque bastante débil (como se verá en la regresión lineal), entre la duración de una canción con su popularidad.\n\nConcretamente, de media, las canciones de menor duración serán más populares que las largas.",
"_____no_output_____"
],
[
"#9.Lyrics",
"_____no_output_____"
],
[
"###Descripción",
"_____no_output_____"
]
],
[
[
"print(spoti.lyrics.describe())",
"count 603.000000\nmean 8.374793\nstd 7.475686\nmin 3.000000\n25% 4.000000\n50% 5.000000\n75% 9.000000\nmax 48.000000\nName: lyrics, dtype: float64\n"
]
],
[
[
"###Gráfico",
"_____no_output_____"
]
],
[
[
"lyr = spoti['lyrics']\nplt.hist(lyr, bins=15, edgecolor='black')\nplt.xlabel('Lyrics')\nplt.xticks(np.arange(0, 48, step=5))\nplt.ylabel('Frecuencia')\nprops = dict(boxstyle= 'round', facecolor='white', lw=0.5)\nplt.text(40.5,200,'Media:8.37''\\n''N:603' '\\n' 'SD: 7.48', bbox=props)\nplt.title('Figura 9.1: Número de canciones por speechness score''\\n')\nplt.axvline(8.37, linewidth=1, linestyle='solid', color = 'red')\nplt.axvline(0.88, linewidth=1, linestyle= 'dashed', color= 'green')\nplt.axvline(15.84, linewidth=1, linestyle= 'dashed', color= 'green')\nplt.legend(labels=['Media', 'SD ± Media'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Comparación con popu",
"_____no_output_____"
]
],
[
[
"lyr= spoti[\"lyrics\"]\npopularidad=spoti[\"popu\"]\npearsonr (lyr,popularidad)\nr, p_val = pearsonr(lyr,popularidad)\nn = len(spoti[\"popu\"])\nprint('r:', round(r,3), 'P.Val:', round(p_val,3), 'n:', n)",
"r: -0.051 P.Val: 0.21 n: 603\n"
],
[
"plt.figure(figsize=(5,5))\nplt.scatter(lyr,popularidad, s=20, facecolors='none', edgecolors='C0')\nplt.title('Figura 9.2: Popularidad de las canciones por sus lyrics') \nplt.ylabel('Popularidad') \nplt.xlabel('Lyrics') \nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr = '$\\mathrm{r}=%.2f$\\n$\\mathrm{P.Val:}=%.3f$\\n$\\mathrm{n}=%.0f$'%(r, p_val, n)\nplt.text (14,6, textstr , bbox=props)\nplt.show()",
"_____no_output_____"
]
],
[
[
"###Miniconclusion",
"_____no_output_____"
],
[
"Al ser el p-value mayor que nuestro nivel de significación (0.05), aceptamos la hipotesis nula. Por lo tanto, la cantidad de letra de las canciones no influye en su popularidad.",
"_____no_output_____"
],
[
"#Regresión Lineal",
"_____no_output_____"
]
],
[
[
"from statsmodels.formula.api import ols\nmodel1 = ols('popu ~ year2 + dnce + dur + nrgy + bpm + val + genre + lyrics', data=spoti).fit()\nprint(model1.summary2())",
" Results: Ordinary least squares\n==================================================================\nModel: OLS Adj. R-squared: 0.037 \nDependent Variable: popu AIC: 4902.7315\nDate: 2021-12-24 12:31 BIC: 4942.3488\nNo. Observations: 603 Log-Likelihood: -2442.4 \nDf Model: 8 F-statistic: 3.889 \nDf Residuals: 594 Prob (F-statistic): 0.000174 \nR-squared: 0.050 Scale: 195.95 \n------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n------------------------------------------------------------------\nIntercept 71.6704 7.0612 10.1499 0.0000 57.8024 85.5384\nyear2[T.2015-2019] 4.1771 1.2144 3.4396 0.0006 1.7920 6.5622\ngenre[T.pop] -0.5793 1.4115 -0.4104 0.6817 -3.3514 2.1929\ndnce 0.0645 0.0522 1.2351 0.2173 -0.0381 0.1670\ndur -0.0300 0.0180 -1.6685 0.0958 -0.0653 0.0053\nnrgy -0.0872 0.0396 -2.2051 0.0278 -0.1649 -0.0095\nbpm 0.0099 0.0242 0.4087 0.6829 -0.0376 0.0574\nval 0.0242 0.0331 0.7309 0.4651 -0.0409 0.0893\nlyrics -0.0745 0.0779 -0.9567 0.3391 -0.2275 0.0784\n------------------------------------------------------------------\nOmnibus: 182.048 Durbin-Watson: 0.459 \nProb(Omnibus): 0.000 Jarque-Bera (JB): 524.249\nSkew: -1.474 Prob(JB): 0.000 \nKurtosis: 6.490 Condition No.: 3450 \n==================================================================\n* The condition number is large (3e+03). This might indicate\nstrong multicollinearity or other numerical problems.\n"
],
[
"spoti['nrgy_sqr'] = spoti.nrgy**2\n\nmodel2 = ols('popu ~ year2 + dnce + nrgy_sqr', data=spoti).fit()\nprint(model2.summary2())",
" Results: Ordinary least squares\n==================================================================\nModel: OLS Adj. R-squared: 0.039 \nDependent Variable: popu AIC: 4896.4092\nDate: 2021-12-24 12:31 BIC: 4914.0169\nNo. Observations: 603 Log-Likelihood: -2444.2 \nDf Model: 3 F-statistic: 9.179 \nDf Residuals: 599 Prob (F-statistic): 6.04e-06 \nR-squared: 0.044 Scale: 195.51 \n------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n------------------------------------------------------------------\nIntercept 61.8986 3.1633 19.5679 0.0000 55.6862 68.1111\nyear2[T.2015-2019] 4.3240 1.1730 3.6864 0.0002 2.0203 6.6276\ndnce 0.0889 0.0438 2.0287 0.0429 0.0028 0.1749\nnrgy_sqr -0.0007 0.0003 -2.2933 0.0222 -0.0012 -0.0001\n------------------------------------------------------------------\nOmnibus: 178.534 Durbin-Watson: 0.442 \nProb(Omnibus): 0.000 Jarque-Bera (JB): 506.329\nSkew: -1.451 Prob(JB): 0.000 \nKurtosis: 6.426 Condition No.: 31427 \n==================================================================\n* The condition number is large (3e+04). This might indicate\nstrong multicollinearity or other numerical problems.\n"
],
[
"spoti['dnce_sqr'] = spoti.dnce**2\nspoti['val_sqr'] = spoti.val**2\nspoti['dur_sqr'] = spoti.dur**2\n\nmodel3 = ols('popu ~ year2 + dnce + nrgy_sqr', data=spoti).fit()\nprint(model3.summary2())",
" Results: Ordinary least squares\n==================================================================\nModel: OLS Adj. R-squared: 0.039 \nDependent Variable: popu AIC: 4896.4092\nDate: 2021-12-24 12:31 BIC: 4914.0169\nNo. Observations: 603 Log-Likelihood: -2444.2 \nDf Model: 3 F-statistic: 9.179 \nDf Residuals: 599 Prob (F-statistic): 6.04e-06 \nR-squared: 0.044 Scale: 195.51 \n------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n------------------------------------------------------------------\nIntercept 61.8986 3.1633 19.5679 0.0000 55.6862 68.1111\nyear2[T.2015-2019] 4.3240 1.1730 3.6864 0.0002 2.0203 6.6276\ndnce 0.0889 0.0438 2.0287 0.0429 0.0028 0.1749\nnrgy_sqr -0.0007 0.0003 -2.2933 0.0222 -0.0012 -0.0001\n------------------------------------------------------------------\nOmnibus: 178.534 Durbin-Watson: 0.442 \nProb(Omnibus): 0.000 Jarque-Bera (JB): 506.329\nSkew: -1.451 Prob(JB): 0.000 \nKurtosis: 6.426 Condition No.: 31427 \n==================================================================\n* The condition number is large (3e+04). This might indicate\nstrong multicollinearity or other numerical problems.\n"
],
[
"spoti['bpm_sqr'] = spoti.bpm**2\n\nmodel4 = ols('popu ~ year2 + nrgy_sqr + dur_sqr', data=spoti).fit()\nprint(model4.summary2())",
" Results: Ordinary least squares\n==================================================================\nModel: OLS Adj. R-squared: 0.041 \nDependent Variable: popu AIC: 4895.0489\nDate: 2021-12-24 12:31 BIC: 4912.6566\nNo. Observations: 603 Log-Likelihood: -2443.5 \nDf Model: 3 F-statistic: 9.651 \nDf Residuals: 599 Prob (F-statistic): 3.15e-06 \nR-squared: 0.046 Scale: 195.07 \n------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n------------------------------------------------------------------\nIntercept 72.3360 2.8618 25.2764 0.0000 66.7156 77.9564\nyear2[T.2015-2019] 3.9582 1.1932 3.3174 0.0010 1.6149 6.3016\nnrgy_sqr -0.0007 0.0003 -2.4888 0.0131 -0.0013 -0.0002\ndur_sqr -0.0001 0.0000 -2.3404 0.0196 -0.0001 -0.0000\n------------------------------------------------------------------\nOmnibus: 178.049 Durbin-Watson: 0.447 \nProb(Omnibus): 0.000 Jarque-Bera (JB): 500.514\nSkew: -1.451 Prob(JB): 0.000 \nKurtosis: 6.392 Condition No.: 281009 \n==================================================================\n* The condition number is large (3e+05). This might indicate\nstrong multicollinearity or other numerical problems.\n"
],
[
"\nspoti['nrgy_sqr3'] = spoti.nrgy**3\nspoti['dnce_sqr3'] = spoti.dnce**3\nspoti['val_sqr3'] = spoti.val**3\nspoti['dur_sqr3'] = spoti.dur**3\nspoti['bpm_sqr3'] = spoti.bpm**3\n\nmodel5 = ols('popu ~ year2 + nrgy_sqr3 + dur_sqr3', data=spoti).fit()\nprint(model5.summary2())",
" Results: Ordinary least squares\n==================================================================\nModel: OLS Adj. R-squared: 0.043 \nDependent Variable: popu AIC: 4893.8996\nDate: 2021-12-24 12:31 BIC: 4911.5073\nNo. Observations: 603 Log-Likelihood: -2442.9 \nDf Model: 3 F-statistic: 10.05 \nDf Residuals: 599 Prob (F-statistic): 1.81e-06 \nR-squared: 0.048 Scale: 194.69 \n------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n------------------------------------------------------------------\nIntercept 69.9625 2.0426 34.2519 0.0000 65.9510 73.9740\nyear2[T.2015-2019] 3.8974 1.1921 3.2693 0.0011 1.5561 6.2387\nnrgy_sqr3 -0.0000 0.0000 -2.7412 0.0063 -0.0000 -0.0000\ndur_sqr3 -0.0000 0.0000 -2.3434 0.0194 -0.0000 -0.0000\n------------------------------------------------------------------\nOmnibus: 177.847 Durbin-Watson: 0.449 \nProb(Omnibus): 0.000 Jarque-Bera (JB): 499.340 \nSkew: -1.449 Prob(JB): 0.000 \nKurtosis: 6.387 Condition No.: 53337107\n==================================================================\n* The condition number is large (5e+07). This might indicate\nstrong multicollinearity or other numerical problems.\n"
],
[
"model6 = ols('popu ~ year2 + nrgy_sqr3 + dur_sqr', data=spoti).fit()\nprint(model6.summary2())\n",
" Results: Ordinary least squares\n==================================================================\nModel: OLS Adj. R-squared: 0.044 \nDependent Variable: popu AIC: 4893.5908\nDate: 2021-12-24 12:31 BIC: 4911.1984\nNo. Observations: 603 Log-Likelihood: -2442.8 \nDf Model: 3 F-statistic: 10.16 \nDf Residuals: 599 Prob (F-statistic): 1.56e-06 \nR-squared: 0.048 Scale: 194.59 \n------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n------------------------------------------------------------------\nIntercept 71.8535 2.6113 27.5168 0.0000 66.7252 76.9819\nyear2[T.2015-2019] 3.8389 1.1955 3.2110 0.0014 1.4909 6.1868\nnrgy_sqr3 -0.0000 0.0000 -2.7676 0.0058 -0.0000 -0.0000\ndur_sqr -0.0001 0.0000 -2.4086 0.0163 -0.0002 -0.0000\n------------------------------------------------------------------\nOmnibus: 177.416 Durbin-Watson: 0.450 \nProb(Omnibus): 0.000 Jarque-Bera (JB): 497.002\nSkew: -1.447 Prob(JB): 0.000 \nKurtosis: 6.378 Condition No.: 2173554\n==================================================================\n* The condition number is large (2e+06). This might indicate\nstrong multicollinearity or other numerical problems.\n"
],
[
"from numpy import log\nspoti['nrgy_log'] = log(spoti.nrgy)\nspoti['dnce_log'] = log(spoti.dnce)\nspoti['val_log'] = log(spoti.val)\nspoti['dur_log'] = log(spoti.dur)\nspoti['bpm_log'] = log(spoti.bpm)\n\nmodel7 = ols('popu ~ year2 + nrgy_sqr3 + dur_sqr + dnce_log', data=spoti).fit()\nprint(model7.summary2())",
" Results: Ordinary least squares\n==================================================================\nModel: OLS Adj. R-squared: 0.048 \nDependent Variable: popu AIC: 4891.6660\nDate: 2021-12-24 12:31 BIC: 4913.6755\nNo. Observations: 603 Log-Likelihood: -2440.8 \nDf Model: 4 F-statistic: 8.631 \nDf Residuals: 598 Prob (F-statistic): 8.91e-07 \nR-squared: 0.055 Scale: 193.66 \n------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n------------------------------------------------------------------\nIntercept 51.1532 10.7944 4.7389 0.0000 29.9537 72.3528\nyear2[T.2015-2019] 3.7263 1.1940 3.1209 0.0019 1.3814 6.0713\nnrgy_sqr3 -0.0000 0.0000 -2.9439 0.0034 -0.0000 -0.0000\ndur_sqr -0.0001 0.0000 -2.0800 0.0379 -0.0001 -0.0000\ndnce_log 4.9291 2.4944 1.9761 0.0486 0.0303 9.8279\n------------------------------------------------------------------\nOmnibus: 181.549 Durbin-Watson: 0.468 \nProb(Omnibus): 0.000 Jarque-Bera (JB): 523.536\nSkew: -1.469 Prob(JB): 0.000 \nKurtosis: 6.494 Condition No.: 8958633\n==================================================================\n* The condition number is large (9e+06). This might indicate\nstrong multicollinearity or other numerical problems.\n"
]
],
[
[
"Modelo 8",
"_____no_output_____"
]
],
[
[
"model8 = ols('popu ~ year2 + nrgy_sqr3 + dur_sqr + dnce_log', data=spoti).fit()\nprint(model8.summary2())\n",
" Results: Ordinary least squares\n==================================================================\nModel: OLS Adj. R-squared: 0.048 \nDependent Variable: popu AIC: 4891.6660\nDate: 2021-12-24 12:31 BIC: 4913.6755\nNo. Observations: 603 Log-Likelihood: -2440.8 \nDf Model: 4 F-statistic: 8.631 \nDf Residuals: 598 Prob (F-statistic): 8.91e-07 \nR-squared: 0.055 Scale: 193.66 \n------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n------------------------------------------------------------------\nIntercept 51.1532 10.7944 4.7389 0.0000 29.9537 72.3528\nyear2[T.2015-2019] 3.7263 1.1940 3.1209 0.0019 1.3814 6.0713\nnrgy_sqr3 -0.0000 0.0000 -2.9439 0.0034 -0.0000 -0.0000\ndur_sqr -0.0001 0.0000 -2.0800 0.0379 -0.0001 -0.0000\ndnce_log 4.9291 2.4944 1.9761 0.0486 0.0303 9.8279\n------------------------------------------------------------------\nOmnibus: 181.549 Durbin-Watson: 0.468 \nProb(Omnibus): 0.000 Jarque-Bera (JB): 523.536\nSkew: -1.469 Prob(JB): 0.000 \nKurtosis: 6.494 Condition No.: 8958633\n==================================================================\n* The condition number is large (9e+06). This might indicate\nstrong multicollinearity or other numerical problems.\n"
],
[
"spoti['val_inv'] = 1/spoti.val\nspoti['bpm_inv'] = 1/spoti.bpm\nspoti['dur_inv'] = 1/spoti.dur\n\nmodel9 = ols('popu ~ year2 + nrgy_sqr3 + dur_sqr + dnce_log +val_inv', data=spoti).fit()\nprint(model9.summary2())",
" Results: Ordinary least squares\n====================================================================\nModel: OLS Adj. R-squared: 0.050 \nDependent Variable: popu AIC: 4891.5436\nDate: 2021-12-24 12:31 BIC: 4917.9551\nNo. Observations: 603 Log-Likelihood: -2439.8 \nDf Model: 5 F-statistic: 7.339 \nDf Residuals: 597 Prob (F-statistic): 1.09e-06 \nR-squared: 0.058 Scale: 193.30 \n--------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n--------------------------------------------------------------------\nIntercept 60.3798 12.5199 4.8227 0.0000 35.7915 84.9682\nyear2[T.2015-2019] 3.8223 1.1947 3.1993 0.0015 1.4759 6.1687\nnrgy_sqr3 -0.0000 0.0000 -3.2296 0.0013 -0.0000 -0.0000\ndur_sqr -0.0001 0.0000 -1.9135 0.0562 -0.0001 0.0000\ndnce_log 2.9916 2.8273 1.0581 0.2904 -2.5611 8.5443\nval_inv -40.6742 28.0350 -1.4508 0.1474 -95.7334 14.3849\n--------------------------------------------------------------------\nOmnibus: 183.606 Durbin-Watson: 0.474 \nProb(Omnibus): 0.000 Jarque-Bera (JB): 538.838 \nSkew: -1.478 Prob(JB): 0.000 \nKurtosis: 6.564 Condition No.: 23426082\n====================================================================\n* The condition number is large (2e+07). This might indicate\nstrong multicollinearity or other numerical problems.\n"
]
],
[
[
"El modelo a elegir es el modelo 8 porque es el que tiene más variables significativas y la r cuadrado mayor.\n\nCabe destacar que la r cuadrado es muy bajita, lo que implica que las variables escogidas no son muy representativas a la hora de explicar la variabilidad de los datos de la variable popularidad. De hecho, nuestro modelo de regresión solamente explica el 5,5% de la varianza de la popularidad.\n\nPara conseguir este porcentaje, hemos tenido que transformar las variables para que, al combinarlas, nos diese el p valor menor a 0,05. Las transformaciones que hemos hecho han sido:\n\n* La energía al cubo\n* La duración al cuadrado\n* El logaritmo de la danzabilidad\n\nLa ecuación del modelo de regresión quedaría de la siguiente manera:\n\n\\\n$$popu = 51.15 + 3.73* year2 - 0* nrgy\\_sqr3 - 0.0001* dur\\_sqr + 4.93* dnce\\_log$$\n\n\\\nLa popularidad aumentará en 3.73 puntos si el año pertenece al grupo 2015-2019.\n\nLa popularidad disminuirá en 0.0 puntos por cada unidad que aumente la energía al cubo.\n\nLa polularidad disminuirá en 0.0001 puntos por cada unidad que aumente la duración de la canción al cuadrado.\n\nLa popularidad aumentará en 4.93 puntos por cada unidad que aumente el logaritmo de la bailabilidad.\n\nSi las variables predictoras valiesen todas 0, la popularidad seria de 51.15 puntos.\n",
"_____no_output_____"
],
[
"#Conclusiones",
"_____no_output_____"
],
[
"Teniendo en cuenta los resultados anteriores y el análisis de las variables del dataset, se ha comprobado que las mismas tienen un impacto muy débil en la popularidad de una canción.",
"_____no_output_____"
],
[
"Las variables que han resultado significativas en nuestro dataset han sido Eneregía, Danzabilidad y Año. Ademas, estas variables nos han servido para nuestro modelo de regresión aunque hayan tenido que ser transformadas.\n\nA pesar de todo, el impacto de estas variables en la popularidad de una canción no han sido muy alto.",
"_____no_output_____"
],
[
"En la propuesta de un posible trabajo que mejore el modelo de predicción, podría ser bastante interesante la obtención e incorporación de nuevas variables como:\n- La temática de la canción\n- Registro del lenguaje empleado\n- Idioma\n- Armonía empleada en la canción\n- Acordes\n- Tipo de voz de los cantantes\n\nPara recabar dichos datos, sería necesario el empleo de modelos de inteligencia artificial avanzados (como podría ser el de procesamiento de lenguaje natural) que quedan fuera del alcance del presente trabajo.",
"_____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"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
ecd000f2291c449bba6fbeb52ea9586687176a71 | 206,086 | ipynb | Jupyter Notebook | Seaborn - Controlling Aesthetics.ipynb | seanreed1111/Seaborn-Tutorial | fd562f8c662b0d3805a2b0a5bd848b2e318d0f06 | [
"MIT"
] | 163 | 2018-06-08T17:21:50.000Z | 2022-03-26T15:04:17.000Z | Seaborn - Controlling Aesthetics.ipynb | seanreed1111/Seaborn-Tutorial | fd562f8c662b0d3805a2b0a5bd848b2e318d0f06 | [
"MIT"
] | 1 | 2020-10-02T02:37:59.000Z | 2020-10-02T04:19:49.000Z | Seaborn - Controlling Aesthetics.ipynb | seanreed1111/Seaborn-Tutorial | fd562f8c662b0d3805a2b0a5bd848b2e318d0f06 | [
"MIT"
] | 83 | 2018-07-01T14:10:55.000Z | 2022-03-11T02:00:32.000Z | 453.933921 | 80,268 | 0.941243 | [
[
[
"# Seaborn | Part-2: Controlling Aesthetics of Seaborn Plots",
"_____no_output_____"
],
[
"One of the biggest advantages of Seaborn over Matplotlib is that its default aesthetics are visually far more appealing. Undoubtedly Matplotlib is highly customizable, but sometimes it may get difficult to know exact settings to tweak in order to achieve an attractive plot. Whereas, Seaborn comes with a number of customized themes and a high-level interface for controlling the look of same matplotlib figures.\n\nSeaborn splits Matplotlib parameters into two independent groups: *First* group sets the aesthetic style of the plot; and *second* scales various elements of the figure to get easily incorporated into different contexts.",
"_____no_output_____"
],
[
"Seaborn doesn’t take away any of Matplotlib credits, but rather adds some nice default aesthetics and built-in plots that complement and sometimes replace the complicated Matplotlib code professionals needed to write. *Facet plots* and *Regression plots* are an example of that. In this lecture I shall show how easy it is to build a *Regression plot* using Seaborn and then let us compare it by building something similar in Matplotlib.",
"_____no_output_____"
],
[
"Quick Note (for non-native English speakers): The term *Aesthetics* just refers to the appearance of the figure/plot.",
"_____no_output_____"
]
],
[
[
"# Importing intrinsic libraries:\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
]
],
[
[
"Now, once we have imported necessary libraries, let us begin talking about aesthetics with those 2 special lines of code we had added in our previous lecture. Our first line of code was:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"`%matplotlib` is one of the *magic function* of Jupyter Notebook that along with `inline` [sets the backend of matplotlib](http://ipython.readthedocs.io/en/stable/interactive/plotting.html) to the *inline* backend within Jupyter notebook. If we look into relevant documentation, it says:\n\n>IPython has a set of predefined ‘magic functions’ that you can call with a command line style syntax. There are two kinds of magics, line-oriented and cell-oriented. Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Lines magics can return results and can be used in the right hand side of an assignment. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.\n\n>With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.<\n\nFurthermore, if we want interactivity as well, we can use `nbagg` backend with `%matplotlib` notebook (in IPython 3.x). Though we won't be getting into that extremely advanced level of Matplotlib specific presentation here, but if that interest you, please check [here](https://matplotlib.org/users/whats_new.html#the-nbagg-backend).\n\nLet us now move on to our second line of code:\n",
"_____no_output_____"
]
],
[
[
"sns.set()",
"_____no_output_____"
]
],
[
[
"Seaborn runs on top of Matplotlib and with that as a default comes a *White* background for each of our plot, that looks pretty dull. With this line of code, we switch our plot to Seaborn default using `.set()` function. Let us look into what it yields, using one of the built-in dataset:",
"_____no_output_____"
]
],
[
[
"tips = sns.load_dataset(\"tips\")\n\nsns.barplot(x = \"day\", y = \"total_bill\", data = tips)",
"_____no_output_____"
]
],
[
[
"Quick Note: `sns.set()` needs to be explicitly called ONLY in Seaborn v0.8 and above.",
"_____no_output_____"
],
[
"With both the lines of code explained, let us now look into what else can we do to vary appearance of our plot. Earlier we spoke about Seaborn segregating Matplotlib parameters into 2 independent groups: *Styling* and *Scaling* of figures.\n\nLet us begin by delving into *Styling* aspect, that is controlled by using `sns.axes_style()` and `sns.set_style()` functions.",
"_____no_output_____"
]
],
[
[
"sns.set_style(\"whitegrid\")\nsns.boxplot(x = \"day\", y = \"total_bill\", data = tips)",
"_____no_output_____"
]
],
[
[
"Few common background options include: `whitegrid` (as shown above), `dark` (for solid grey color), `white` (this is default) and `ticks`. Let us explore an example with `ticks` as background and then try to remove top and right axes spines:",
"_____no_output_____"
]
],
[
[
"sns.set_style(\"ticks\")\nsns.boxplot(x=\"day\", y=\"total_bill\", data=tips)",
"_____no_output_____"
]
],
[
[
"In the above plot we observe 2 changes:\n\n- There are no horizontal line/grid in the background, that we had in previous figure.\n- There are `ticks` on X and Y axes, representing the axis interval.\n\nWe still have top and right axes spine so let's get rid of that now:",
"_____no_output_____"
]
],
[
[
"sns.set_style(\"ticks\")\nsns.boxplot(x=\"day\", y=\"total_bill\", data=tips)\nsns.despine()",
"_____no_output_____"
]
],
[
[
"If we also want to despine left axis, we just need to alter our last line of code by adding a parameter: `(left=True)`, and it shall fetch:",
"_____no_output_____"
]
],
[
[
"sns.set_style(\"ticks\")\nsns.boxplot(x=\"day\", y=\"total_bill\", data=tips)\nsns.despine(left=True)",
"_____no_output_____"
]
],
[
[
"Now let us try to temporarily visualize two types of background in a single plot. For this, we shall use `.axes_style()` as follows:",
"_____no_output_____"
]
],
[
[
"# This function shall help us plot some offset sine waves:\ndef sinplot(flip=1):\n x = np.linspace(0, 14, 100)\n for i in range(1, 7):\n plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)\n\nwith sns.axes_style(\"darkgrid\"):\n plt.subplot(211)\n sinplot()\nplt.subplot(212)\nsinplot(-1)",
"_____no_output_____"
]
],
[
[
"Let us now look into other independent group of Matplotlib parameters created by Seaborn, i.e. *Scaling* of plot elements; that is controlled using `.plotting_context()` and `.set_context()` functions.\n\nThe four preset contexts, in order of relative size, are `paper`, `notebook`, `talk`, and `poster`. The `notebook` style is default, and was used in the plots above. At first let’s reset the default parameters by calling `sns.set()` & then play around with other contexts for scaling, starting with `paper`:",
"_____no_output_____"
]
],
[
[
"sns.set()",
"_____no_output_____"
],
[
"sns.set_context(\"paper\")\nsns.set_style(\"whitegrid\")\n\nsns.boxplot(x = \"day\", y = \"total_bill\", data = tips)",
"_____no_output_____"
]
],
[
[
"I am pretty sure you must be thinking that this figure/plot in no ways is scaled as it looks similar to our previous plot outputs. So, I shall clarify that right away:\n\nJupyter Notebook scales down large images in the notebook cell output. This is generally done because past a certain size, we get automatic figure scaling. For exploratory analysis, we prefer iterating quickly over a number of different analyses and it's more useful to have [facets](https://dictionary.cambridge.org/dictionary/english/facet) that are of similar size; than to have overall figures that are same size in a particular context.\n\nWhen we're in a situation where we need to have something that's exactly a certain size overall; ideally we:\n- know precisely what you want and\n- can afford to take off some time and work through the calculations.\n\nWith all that being said, if we plot the same figure in an Editor like *Anaconda Spyder* or *JetBrains' PyCharm* or *IntelliJ*, we shall be able to visualize them in their original size. Hence what needs to be our take-away from scaling segment, is that an addition of a line of code can fetch the size of image as per our requirement and we may experiment accordingly.",
"_____no_output_____"
],
[
"In practical world, we also add a dictionary of parameters using `rc` to have a finer control over the aesthetics. Let me show you an example with the same _sinplot_ function we defined earlier:",
"_____no_output_____"
]
],
[
[
"sns.set(style='whitegrid', rc={\"grid.linewidth\": 1.5})\nsns.set_context(\"poster\", font_scale=2.5, rc={\"lines.linewidth\": 5.0})\nsinplot()",
"_____no_output_____"
]
],
[
[
"Though our Notebook didn't display enlarged (scaled) plot, we may notice how in the backend (in memory) it has created the figure as per our instructions. We have *thick lines* now in our plot because I set `linewidth` to `5`, *font size* on axes have thickened because of `font_scale`. Generally we don't use anything more than that during data analysis although exceptional scenarios may demand few more parameters as per requirement. ",
"_____no_output_____"
],
[
">IMPORTANT NOTE: `%matplotlib inline` just needs to be called once in a kernel unless we refresh/restart the kernel. This is a function that works only in Jupyter Notebook. In other IDE, you will have to explicitly mention either `sns.plt.show()` or just `plt.show()` at the end of your code for plot/figure to be displayed.\nAlso, style and context once set remains defined unless we explicitly call for a change. If never called in a kernel, Seaborn will work with it's defaults: Matplotlib 'white' background without grids, and 'notebook' scale size.",
"_____no_output_____"
],
[
"In the next lecture, we shall see the difference in coding between matplotlib and Seaborn to achieve a certain goal (Regression plot illustration). Till then, happy visualizing!",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
ecd0066929bf38563ff5707b9e2825cab2bc9c0f | 452,370 | ipynb | Jupyter Notebook | plotting-exp-1.ipynb | quantshah/qdp-lab | 4637ba1dabf08fb31b9cd5b61e09173da7b690de | [
"MIT"
] | null | null | null | plotting-exp-1.ipynb | quantshah/qdp-lab | 4637ba1dabf08fb31b9cd5b61e09173da7b690de | [
"MIT"
] | null | null | null | plotting-exp-1.ipynb | quantshah/qdp-lab | 4637ba1dabf08fb31b9cd5b61e09173da7b690de | [
"MIT"
] | null | null | null | 792.241681 | 28,082 | 0.950664 | [
[
[
"import matplotlib.pyplot as plt\n\nimport numpy as np\nfrom scipy import optimize\n\nimport time\n\nfrom datetime import datetime\nfrom time import mktime\n\nfrom scipy.optimize import curve_fit, least_squares",
"_____no_output_____"
],
[
"def model(params, x):\n \"\"\"[summary]\n\n Args:\n params ([type]): [description]\n x ([type]): [description]\n \"\"\"\n a, b, lam = params\n ypred = a * (1 - b * np.exp(-x/lam))\n return ypred\n\n\ndef error_func(params, x, y):\n \"\"\"Least squares error function\n\n Args:\n x ([type]): [description]\n a ([type]): [description]\n b ([type]): [description]\n c ([type]): [description]\n \"\"\"\n ypred = model(params, x)\n return np.abs(ypred - y)\n\n\ndef get_times(timestamps):\n \"\"\"Get the time stamps in seconds.\n\n Args:\n timestamps (list): A list of unix time stamps\n \n Returns:\n times (list): A list of times starting from 0 in seconds\n \"\"\"\n times = [time.gmtime(td) for td in timestamps]\n dt = [datetime.fromtimestamp(mktime(struct)) for struct in times]\n diff = np.array([(dt[i] - dt[0]).total_seconds() for i in range(1, len(dt))])\n\n # start from 0 and add the differences to make the list of times (in s)\n return np.concatenate([[2], diff])\n\nfnames = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12]\ncurrents = [0, 3.16/1e3, 31.6/1e3, 31.6/1e3, 316./1e3, 1., 3.16, 6, 10, 10, 0] #mA\n\nfor i, idx in enumerate(fnames):\n datafile_path = 'temperature_measurement_T(P)_09_2021-10-20-Sweep0{}.txt'.format(str(idx))\n data = np.loadtxt(datafile_path)\n\n tprobe = data[:, -1]*1e3\n tmixer = data[:, -2]*1e3\n\n print(tprobe[-1])\n\n tlist = get_times(data[:, -3])\n\n plt.title(r\"I = {} mA; |$\\Delta T$| = {:.2f} mK\".format(currents[i], np.abs(tprobe[-1] - tmixer[-1])))\n plt.plot(tlist, tprobe, label='probe')\n plt.plot(tlist, tmixer, label='mixer')\n\n plt.xlabel(\"time, t (s)\")\n plt.ylabel(\"Temperature, T (mK)\")\n\n plt.legend()\n plt.show()",
"18.9415\n"
],
[
"tempfull = np.array([])\nbreaks = [0]\n\n\nfor i, idx in enumerate(fnames):\n datafile_path = 'temperature_measurement_T(P)_09_2021-10-20-Sweep0{}.txt'.format(str(idx))\n\n data = np.loadtxt(datafile_path)\n tprobe = data[:, -1]*1e3\n tmixer = data[:, -2]*1e3\n \n break_val = breaks[-1] + len(tmixer)\n breaks.append(break_val)\n\n tempfull = np.concatenate([tempfull.ravel(), tprobe.ravel()])",
"_____no_output_____"
],
[
"dt = 10\nxarr = [0 + (i - 1)*dt for i in range(len(tempfull))]\n\nfor i in range(1, len(breaks)):\n x = np.array(xarr[breaks[i-1]:breaks[i]])\n y = np.array(tempfull[breaks[i-1]:breaks[i]])\n plt.plot(x, y, label=\"{} mA\".format(currents[i-1]))\n\nplt.xlabel(\"time (s)\")\nplt.ylabel(\"Temperature (mK)\")\nplt.legend()",
"_____no_output_____"
],
[
"fnames = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12]\ncurrents = [0, 3.16/1e3, 31.6/1e3, 31.6/1e3, 316./1e3, 1., 3.16, 6, 10, 10, 0] #mA\n\nfor i, idx in enumerate(fnames):\n datafile_path = 'temperature_measurement_T(P)_09_2021-10-20-Sweep0{}.txt'.format(str(idx))\n data = np.loadtxt(datafile_path)\n\n tprobe = data[:, -1]*1e3\n tmixer = data[:, -2]*1e3\n\n tlist = get_times(data[:, -3])\n\n plt.title(r\"I = {} mA; |$\\Delta T$| = {:.2f} mK\".format(currents[i], np.abs(tprobe[-1] - tmixer[-1])))\n plt.plot(tlist, tprobe, label='probe')\n # plt.plot(tlist, tmixer, label='mixer')\n\n plt.xlabel(\"time, t (s)\")\n plt.ylabel(\"Temperature, T (mK)\")\n\n\n\n x = tlist\n y = tprobe\n\n x0 = [y[-1], y[-1]/2, (x[-1] - x[0])/2]\n res = least_squares(error_func,\n x0, args=[x, y])\n ypred = model(res.x, x)\n\n plt.plot(x, ypred, label='Fit (probe)')\n # plt.text(x[-1] -100 , y[-1]-20, \"{:.2f}\".format(res.x[2]))\n\n plt.text(400, 60, \"T(t) = {:.2f}(1 - {:.2f} exp(-t/{:.2f}))\".format(*res.x))\n\n plt.xlim(0, 1000)\n plt.ylim(0, 600)\n plt.legend()\n plt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
ecd009213fbc2b3fbdf0e470984c27584154abb5 | 471 | ipynb | Jupyter Notebook | codes/NoisyDQN/task0_train.ipynb | johnjim0816/rl-tutorials | 5d271a43e7b24e9b0d982636d44159e25d4ae30e | [
"MIT"
] | 33 | 2021-11-09T03:14:49.000Z | 2022-03-29T03:31:04.000Z | NoisyDQN/task0_train.ipynb | Rainxyh/rl-tutorials | 194b8e1f10118f0368a25126e35ae4470d6fd5d9 | [
"MIT"
] | 3 | 2021-11-16T08:52:00.000Z | 2022-02-25T09:09:37.000Z | NoisyDQN/task0_train.ipynb | Rainxyh/rl-tutorials | 194b8e1f10118f0368a25126e35ae4470d6fd5d9 | [
"MIT"
] | 11 | 2021-11-01T15:36:25.000Z | 2022-03-29T03:06:45.000Z | 18.115385 | 58 | 0.545648 | [
[
[
"import sys\nfrom pathlib import Path\ncurr_path = str(Path().absolute()) # 当前路径\nparent_path = str(Path().absolute().parent) # 父路径\nsys.path.append(parent_path) # 添加路径到系统路径",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
ecd02471d251aaa21f7556838dcd3ef357a7d700 | 144,202 | ipynb | Jupyter Notebook | Data Clustering.ipynb | ijzepeda/MIA | e34a2fe829dcad0e3d3f436eb217d127a6ea1380 | [
"MIT"
] | null | null | null | Data Clustering.ipynb | ijzepeda/MIA | e34a2fe829dcad0e3d3f436eb217d127a6ea1380 | [
"MIT"
] | null | null | null | Data Clustering.ipynb | ijzepeda/MIA | e34a2fe829dcad0e3d3f436eb217d127a6ea1380 | [
"MIT"
] | null | null | null | 873.951515 | 74,328 | 0.953947 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn import metrics\n",
"_____no_output_____"
],
[
"#load input data\nX = np.loadtxt('data_quality.txt',delimiter=',') #data_clustering\n#Define k clusters\nnum_clusters=6\n#plot data\nplt.figure()\nplt.scatter(X[:,0], X[:,1], marker='o', facecolors='none', edgecolors='black', s=80)\nx_min, x_max = X[:,0].min() - 1, X[:,0].max()+1\ny_min, y_max = X[:,1].min() -1, X[:,1].max()+1\nplt.title(\"Input data\")\nplt.xlim(x_min,x_max)\nplt.ylim(y_min,y_max)\nplt.xticks(())\nplt.yticks(())",
"_____no_output_____"
],
[
"#Create KMean object ||\\\\\\|| KMEANS++ ajsuta automaticamente a los grupos de manera mas inteligente, para cubrir todo mas rapido\nkmeans= KMeans(init='k-means++',n_clusters=num_clusters, n_init=10)\n#Create the kmean clustering model\nkmeans.fit(X)\n#To visualize boundaries, we need to create a grid of points and evalueate the model \n#Step size of the mesh\nstep_size= 0.01\n#Define the grid of points to plot the boundaries\nx_min, x_max = X[:,0].min()-1, X[:,0].max()+1\ny_min,y_max= X[:,1].min()-1, X[:,1].max()+1\nx_vals, y_vals = np.meshgrid(np.arange(x_min, x_max, step_size), np.arange(y_min, y_max, step_size))\n\n#predict output lables for all the points on the grid\noutput= kmeans.predict(np.c_[x_vals.ravel(),y_vals.ravel()])\nprint(\"shape\",x_vals.shape)\nprint(\"shape\",output.shape)\nprint(type(x_vals))\nprint(type(output))\n#plot different regions and color them\noutput = output.reshape(x_vals.shape)\nplt.figure()\nplt.clf()\nplt.imshow(output, interpolation='nearest', extent=(x_vals.min(), x_vals.max(), y_vals.min(), y_vals.max()),\ncmap=plt.cm.Paired, aspect='auto',origin='lower')\n\n#Overlay input points\nplt.scatter(X[:,0],X[:,1], marker='o', facecolors='none', edgecolors='black',s=80)\n\n#Plot the center of clusters\ncluster_centers = kmeans.cluster_centers_\nplt.scatter(cluster_centers[:,0], cluster_centers[:,1],\n marker='o',facecolors='black', s=210, linewidths=4, color='blue', zorder=12)\n\nx_min, x_max = X[:,0].min()-1, X[:,0].max() + 1\nx_min, y_max = X[:, 1].min()-1, X[:,1].max()+1\nplt.title(\"boundaries of clusters\")\nplt.xlim(x_min, x_max)\nplt.ylim(y_min,y_max)\nplt.xticks(())\nplt.yticks(())\nplt.show()",
"shape (1136, 1388)\nshape (1576768,)\n<class 'numpy.ndarray'>\n<class 'numpy.ndarray'>\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
ecd02e76628d77aa0c35f197846606492aff0e40 | 272,066 | ipynb | Jupyter Notebook | process_afdb_2017_vfdb_cudb.ipynb | shanthakumar21/OptimizedArrhythmiaDetection | cb6e9d9bb1d1fcfdcf30f91f98bb751c2a5aaec6 | [
"MIT"
] | 1 | 2022-01-01T07:33:01.000Z | 2022-01-01T07:33:01.000Z | process_afdb_2017_vfdb_cudb.ipynb | shanthakumar21/OptimizedArrhythmiaDetection | cb6e9d9bb1d1fcfdcf30f91f98bb751c2a5aaec6 | [
"MIT"
] | null | null | null | process_afdb_2017_vfdb_cudb.ipynb | shanthakumar21/OptimizedArrhythmiaDetection | cb6e9d9bb1d1fcfdcf30f91f98bb751c2a5aaec6 | [
"MIT"
] | null | null | null | 32.373394 | 239 | 0.355263 | [
[
[
"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"df = pd.read_csv(\"/hdd/physio/vf/finaldfs/trybonsaifeatures3.csv\", index_col = 0)\ndf",
"_____no_output_____"
],
[
"%%time\nfinal = pd.read_csv(\"/hdd/physio/af/rpeakdf.csv\", index_col = 0)\nfinal",
"CPU times: user 1min 16s, sys: 3.41 s, total: 1min 20s\nWall time: 1min 21s\n"
],
[
"np.isfinite(df).values.all()",
"_____no_output_____"
],
[
"df.replace([np.inf, -np.inf], np.nan, inplace=True)\ndf = df.dropna(how=\"all\", inplace = False)\ndf.drop(columns = ['mean_hr', 'max_hr', 'triangular_index'], inplace = True)",
"_____no_output_____"
],
[
"df.drop(columns = ['pnni_50', 'pnni_20'], inplace = True)\ndf",
"_____no_output_____"
],
[
"# df = df[df.columns[:17]]\ndf",
"_____no_output_____"
],
[
"# split the data into train and test set\ntrain, test = train_test_split(finaldf, test_size=0.2, random_state=42, shuffle=True)",
"_____no_output_____"
],
[
"train = train.to_numpy()\n# test2 = test2.to_numpy()\n\npath = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/try8\"\n# path = \"/hdd/physio/edgeml/examples/pytorch/FastCells/tryforbonsai1\"\n\nnp.save(path + '/train.npy', train)\n# np.save(path + '/test.npy', test)",
"_____no_output_____"
]
],
[
[
"<h2><ins>NORMALIZATION:</ins></h2>",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import MinMaxScaler\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"df = pd.read_csv(\"/hdd/physio/vf/finaldfs/trybonsaifeatures.csv\", index_col = 0)\ndf.replace([np.inf, -np.inf], np.nan, inplace=True)\ndf = df.dropna(how=\"any\", inplace = False)\n# df.drop(columns = ['mean_hr', 'max_hr', 'triangular_index', 'pnni_50', 'pnni_20'], inplace = True)",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"train, test = train_test_split(finaldf, test_size=0.2, random_state=42, shuffle=True)\n# scaler = MinMaxScaler()\ntrain[train.columns[1:]] = scaler.fit_transform(train[train.columns[1:]])\ntest[test.columns[1:]] = scaler.transform(test[test.columns[1:]])",
"_____no_output_____"
],
[
"train = train.to_numpy()\ntest = test.to_numpy()\n\npath = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/try1-af\"\n# path = \"/hdd/physio/edgeml/examples/pytorch/FastCells/tryforbonsai1\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
],
[
"%%time\ndef featureExtraction(df, fs):\n df1 = df.af.copy()\n df.drop(columns = ['af'], inplace = True)\n final = list()\n for i in range(len(df)):\n peaks = []\n peaks = df.loc[i][df.loc[i] == 1].index.values\n peaks = [int(x) for x in peaks]\n if (len(peaks) == 0 or len(peaks) == 1):\n continue\n af = df1.loc[i]\n rr = np.diff(peaks) / fs \n hr = 60 / rr\n rmssd = np.sqrt(np.mean(np.square(rr)))\n sdnn = np.std(rr)\n mean_rr = np.mean(rr)\n mean_hr = np.mean(hr)\n std_hr = np.std(hr)\n min_hr = np.min(hr)\n max_hr = np.max(hr)\n# print(rmssd, sdnn, mean_rr, mean_hr, std_hr, min_hr, max_hr); break\n single_window_df = pd.DataFrame([[rmssd, sdnn, mean_rr, mean_hr, std_hr, min_hr, max_hr]], columns = ['RMSSD', 'STDNN', 'MEAN_RR', 'MEAN_HR', 'STD_HR', 'MIN_HR', 'MAX_HR'])\n# single_window_df = single_window_df.transpose()\n# columns = single_window_df.iloc[0]\n# single_window_df = single_window_df[1:]\n# single_window_df.columns = columns\n# single_window_df.drop(columns = ['std_hr', 'tinn', 'lf_hf_ratio', 'lfnu', 'hfnu'], inplace = True)\n single_window_df.insert(0, 'vf', af)\n final.append(single_window_df)\n del single_window_df\n return pd.concat(final)\n\n# start = time()\nfinaldf = featureExtraction(final, 250)\nfinaldf.reset_index(drop = True, inplace = True)\n# print(\"Executed in {0} seconds\".format((time() - start)))",
"CPU times: user 46 s, sys: 2.91 s, total: 48.9 s\nWall time: 48.8 s\n"
],
[
"finaldf",
"_____no_output_____"
],
[
"df = pd.read_csv(\"/hdd/physio/af/rpeakdf.csv\", index_col = 0)\ndf",
"_____no_output_____"
],
[
"%%time\n\nnewdf_list = list()\naf_column = df.af.copy()\nfor i in range(1, len(df.columns)-9, 10):\n# print((df[i:i+10]).mean(axis = 1)); break\n newdf_list.append((df[df.columns[i:i+11]]).mean(axis = 1))\n\nnewdf4 = pd.concat(newdf_list, axis = 1)\nnewdf4.insert(0, 'af', af_column)\nnewdf4",
"CPU times: user 4.45 s, sys: 727 ms, total: 5.17 s\nWall time: 5.37 s\n"
],
[
"newdf4.to_csv('/hdd/physio/af/hugedfby10.csv')",
"_____no_output_____"
],
[
"newdf4.isna().values.any()",
"_____no_output_____"
],
[
"newdf4 = pd.read_csv('/hdd/physio/af/hugedfby10.csv')",
"_____no_output_____"
],
[
"newdf4",
"_____no_output_____"
],
[
"df.dropna(how = 'any', inplace = True)\ndf.reset_index(drop = True, inplace = True)\ndf",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"train, test = train_test_split(newdf3, test_size=0.2, random_state=42, shuffle=True)\n\ntrain = train.to_numpy()\ntest = test.to_numpy()\n\n# path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/try7\"\npath = \"/hdd/physio/edgeml/examples/pytorch/FastCells/try7-af\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
],
[
"from imblearn.under_sampling import TomekLinks\ntomek = TomekLinks()",
"_____no_output_____"
],
[
"%%time\ndf = pd.read_csv('/hdd/physio/af/hugedfby10.csv', index_col = 0)\ndf\n\ntrain, test = train_test_split(df, test_size=0.2, random_state=42, shuffle=True)\n\ntrain = train.to_numpy()\ntest = test.to_numpy()\n\npath = \"/hdd/physio/edgeml/examples/pytorch/FastCells/tryaffast\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"CPU times: user 5.12 s, sys: 188 ms, total: 5.31 s\nWall time: 6.9 s\n"
],
[
"df",
"_____no_output_____"
]
],
[
[
"<h1><ins>VF+AF</ins></h1>",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import StandardScaler\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"scaler = StandardScaler()",
"_____no_output_____"
],
[
"%%time\nafdf = pd.read_csv('/hdd/physio/af/rpeakdf.csv', index_col = 0)\nvfd = pd.read_csv(\"/hdd/physio/vf/finaldfs/trybonsaifeatures3.csv\", index_col = 0)",
"CPU times: user 49.8 s, sys: 812 ms, total: 50.6 s\nWall time: 52.3 s\n"
],
[
"%%time\ndef featureExtraction(df, fs):\n df1 = df.af.copy()\n df.drop(columns = ['af'], inplace = True)\n final = list()\n for i in range(len(df)):\n peaks = []\n peaks = df.loc[i][df.loc[i] == 1].index.values\n peaks = [int(x) for x in peaks]\n if (len(peaks) == 0 or len(peaks) == 1):\n continue\n af = df1.loc[i]\n rr = np.diff(peaks) / fs \n hr = 60 / rr\n rmssd = np.sqrt(np.mean(np.square(rr)))\n sdnn = np.std(rr)\n mean_rr = np.mean(rr)\n mean_hr = np.mean(hr)\n std_hr = np.std(hr)\n min_hr = np.min(hr)\n max_hr = np.max(hr)\n single_window_df = pd.DataFrame([[rmssd, sdnn, mean_rr, mean_hr, std_hr, min_hr, max_hr]], columns = ['RMSSD', 'STDNN', 'MEAN_RR', 'MEAN_HR', 'STD_HR', 'MIN_HR', 'MAX_HR'])\n single_window_df.insert(0, 'ground_truth', af)\n final.append(single_window_df)\n del single_window_df\n return pd.concat(final)\n\n# afd = featureExtraction(afdf, 250)\n# afd.reset_index(drop = True, inplace = True)\nvfd = featureExtraction(vfdf, 250)\nvfd.reset_index(drop = True, inplace = True)",
"CPU times: user 32.7 s, sys: 213 ms, total: 32.9 s\nWall time: 32.9 s\n"
],
[
"vfd.rename(columns = {'vf': 'ground_truth'}, inplace = True)\nvfd",
"_____no_output_____"
],
[
"data = pd.concat([afd, vfd[:2000]], axis = 0)\ndata",
"_____no_output_____"
],
[
"# train, test = train_test_split(data, test_size=0.2, random_state=42, shuffle=True)\n\n# train = data\n# train = train.to_numpy()\ntest = vfd[2000:]\ntest = test.to_numpy()\n\npath = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/try2vfaf\"\n\n# np.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
],
[
"frame = pd.read_csv('/hdd/physio/vf2/rpeakfeats40df.csv', index_col = 0)\ndat = pd.read_csv('/hdd/physio/vf/finaldfs/trybonsaifeatures3.csv', index_col = 0)\ndat",
"_____no_output_____"
],
[
"frame.describe()",
"_____no_output_____"
],
[
"dat.describe()",
"_____no_output_____"
],
[
"frame.vf.value_counts()",
"_____no_output_____"
],
[
"dat.vf.value_counts()",
"_____no_output_____"
],
[
"dat = dat.drop(dat[dat['vf'].eq(0)].sample(750).index)\ndat.reset_index(drop = True, inplace = True)",
"_____no_output_____"
],
[
"train, frame = train_test_split(frame, test_size=0.2, random_state=42, shuffle=True)",
"_____no_output_____"
],
[
"# train, test = train_test_split(frame, test_size=0.2, random_state=42, shuffle=True)\n\ntrain = dat\n# train[train.columns[1:]] = scaler.fit_transform(train[train.columns[1:]])\ntrain = train.to_numpy()\ntest = frame\n# test[test.columns[1:]] = scaler.transform(test[test.columns[1:]])\ntest = test.to_numpy()\n\npath = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/try2vfcu\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
],
[
"frame.vf.value_counts()",
"_____no_output_____"
],
[
"frame.vf.value_counts(), dat.vf.value_counts()",
"_____no_output_____"
]
],
[
[
"## <ins>Andha equal splitting vf and cu</ins>",
"_____no_output_____"
]
],
[
[
"print(dat.vf.value_counts(), '\\n', frame.vf.value_counts())",
"0 2585\n1 1143\nName: vf, dtype: int64 \n 0 16275\n1 2244\nName: vf, dtype: int64\n"
],
[
"dat0 = dat[dat.vf == 0][:1143].reset_index(drop = True)\ndat1 = dat[dat.vf == 1].reset_index(drop = True)",
"_____no_output_____"
],
[
"dat0",
"_____no_output_____"
],
[
"frame0 = frame[frame.vf == 0][:1143].reset_index(drop = True)\nframe1 = frame[frame.vf == 1][:1143].reset_index(drop = True)",
"_____no_output_____"
],
[
"# train\n\ndef _train(df, split):\n return df[df.index < (split * len(df))]\n\n# test\n\ndef _test(df, split):\n return df[df.index > (split * len(df))]\n\ntrain, test = list(), list()\nfor d in [dat0, dat1]:\n train.append(_train(d, 0.8))\n\ntrain = pd.concat(train, axis = 0).reset_index(drop = True)\n \nfor d in [frame0, frame1]:\n test.append(_test(d, 0.8))\n \ntest = pd.concat(test, axis = 0).reset_index(drop = True)",
"_____no_output_____"
],
[
"train.vf.value_counts()",
"_____no_output_____"
],
[
"test.vf.value_counts()",
"_____no_output_____"
],
[
"train = train.to_numpy()\ntest = test.to_numpy()\n\npath = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/tryeqsplitvfcu\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
],
[
"# train, test = train_test_split(dat, test_size = 0.2, shuffle = True)\n\ntrain = train.to_numpy()\ntest = test.to_numpy()\n\npath = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/try8\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
],
[
"dat.vf.value_counts()",
"_____no_output_____"
],
[
"data0 = dat[dat.vf == 0][:1143].reset_index(drop = True)\ndata1 = dat[dat.vf == 1].reset_index(drop = True)",
"_____no_output_____"
],
[
"# train\n\ndef _train(df, split):\n return df[df.index < (split * len(df))]\n\n# test\n\ndef _test(df, split):\n return df[df.index > (split * len(df))]\n\ntrain, test = list(), list()\nfor d in [data0, data1]:\n train.append(_train(d, 0.8))\n\ntrain = pd.concat(train, axis = 0).reset_index(drop = True)\n \nfor d in [data0, data1]:\n test.append(_test(d, 0.8))\n \ntest = pd.concat(test, axis = 0).reset_index(drop = True)",
"_____no_output_____"
],
[
"train.vf.value_counts()",
"_____no_output_____"
],
[
"test.vf.value_counts()",
"_____no_output_____"
],
[
"newdf = pd.read_csv('/hdd/physio/vf/finaldfs/CUDB_Bonsai_time_frequency_features.csv')\nnewdf",
"_____no_output_____"
],
[
"_1 = newdf[newdf.vf == 1].reset_index(drop = True)\n_0 = newdf[newdf.vf == 0].reset_index(drop = True)[:1143]\nnewdf = pd.concat([_1, _0], axis = 0)",
"_____no_output_____"
],
[
"# train, test = train_test_split(newdf, test_size = 0.1, shuffle = True)\n\ntrain = pd.concat([_1[:1000], _0[:1000]])\ntrain = train.sample(frac = 1).reset_index(drop = True)\ntrain = train.to_numpy()\n\ntest = pd.concat([_1[1000:], _0[1000:]])\ntest = test.sample(frac = 1).reset_index(drop = True)\ntest = test.to_numpy()\n\npath = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_CUDB_test_CUDB\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
]
],
[
[
"## Train, Test => AFDB, 2017",
"_____no_output_____"
],
[
"### Feature Extraction:",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom numpy.lib.stride_tricks import as_strided as strided",
"_____no_output_____"
],
[
"%%time\nafdb = pd.read_csv('/hdd/physio/af/hugedfrpeak5sec.csv', index_col = 0).reset_index(drop = True)\nchdb = pd.read_csv('/hdd/physio/af2/finaldfs/2017final_normal_rpeak_L5_S1.csv')",
"CPU times: user 2min 2s, sys: 1min 1s, total: 3min 4s\nWall time: 3min 20s\n"
],
[
"afdb.shape, chdb.shape",
"_____no_output_____"
],
[
"afdb.af.value_counts(), chdb.af.value_counts()",
"_____no_output_____"
],
[
"%%time\ndef featureExtraction(df, fs):\n df1 = df.af.copy()\n df.drop(columns = ['af'], inplace = True)\n final = list()\n for i in range(len(df)):\n peaks = []\n peaks = df.loc[i][df.loc[i] == 1].index.values\n peaks = [int(x) for x in peaks]\n if (len(peaks) == 0 or len(peaks) == 1):\n continue\n af = df1.loc[i]\n rr = np.diff(peaks) / fs \n hr = 60 / rr\n rmssd = np.sqrt(np.mean(np.square(rr)))\n sdnn = np.std(rr)\n mean_rr = np.mean(rr)\n mean_hr = np.mean(hr)\n std_hr = np.std(hr)\n min_hr = np.min(hr)\n max_hr = np.max(hr)\n single_window_df = pd.DataFrame([[rmssd, sdnn, mean_rr, mean_hr, std_hr, min_hr, max_hr]], columns = ['RMSSD', 'STDNN', 'MEAN_RR', 'MEAN_HR', 'STD_HR', 'MIN_HR', 'MAX_HR'])\n single_window_df.insert(0, 'af', af)\n final.append(single_window_df)\n del single_window_df\n return pd.concat(final)\n\nafd = featureExtraction(afdb, 250)\nafd.reset_index(drop = True, inplace = True)\nchd = featureExtraction(chdb, 250)\nchd.reset_index(drop = True, inplace = True)",
"CPU times: user 31min 58s, sys: 24.1 s, total: 32min 22s\nWall time: 32min 36s\n"
],
[
"afd.shape, chd.shape",
"_____no_output_____"
],
[
"afd.to_csv('/hdd/physio/af/hugedf5secfeatures.csv', index = False)",
"_____no_output_____"
],
[
"chd.to_csv('/hdd/physio/af2/finaldfs/2017features.csv', index = False)",
"_____no_output_____"
]
],
[
[
"### Train AFDB, Test 2017, Run Bonsai",
"_____no_output_____"
]
],
[
[
"%%time\nafd = pd.read_csv('/hdd/physio/af/hugedf5secfeatures.csv')\nchd = pd.read_csv('/hdd/physio/af2/finaldfs/2017features.csv')",
"CPU times: user 838 ms, sys: 85.5 ms, total: 924 ms\nWall time: 1.72 s\n"
],
[
"%%time\n_0 = afd[afd.af == 0].sample(n = 15000).reset_index(drop = True)\n_1 = afd[afd.af == 1].sample(n = 15000).reset_index(drop = True)\ntrain = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntrain = train.to_numpy()\n_0 = chd[chd.af == 0].sample(n = 1000).reset_index(drop = True)\n_1 = chd[chd.af == 1].sample(n = 1000).reset_index(drop = True)\ntest = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntest = test.to_numpy()",
"CPU times: user 69.6 ms, sys: 230 µs, total: 69.8 ms\nWall time: 68.6 ms\n"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_AFDB_test_2017\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
]
],
[
[
"Train: 0, 1 = 15000, 15000\nClass 0:\np, r, f, s = 0.90, 0.92, 0.91, 1000\nClass 1:\np, r, f, s = 0.92, 0.90, 0.91, 1000",
"_____no_output_____"
]
],
[
[
"## Train 2017, Test 2017",
"_____no_output_____"
]
],
[
[
"%%time\nchd = pd.read_csv('/hdd/physio/af2/finaldfs/2017features.csv')",
"CPU times: user 313 ms, sys: 0 ns, total: 313 ms\nWall time: 318 ms\n"
],
[
"%%time\n_0 = chd[chd.af == 0].sample(n = 15000).reset_index(drop = True)\n_1 = chd[chd.af == 1].sample(n = 15000).reset_index(drop = True)\ntrain = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntrain = train.to_numpy()\n_0 = chd[chd.af == 0].sample(n = 1000).reset_index(drop = True)\n_1 = chd[chd.af == 1].sample(n = 1000).reset_index(drop = True)\ntest = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntest = test.to_numpy()",
"CPU times: user 41.3 ms, sys: 0 ns, total: 41.3 ms\nWall time: 41.3 ms\n"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_2017_test_2017\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
]
],
[
[
"## Train 2017, Test AFDB",
"_____no_output_____"
]
],
[
[
"%%time\nchd = pd.read_csv('/hdd/physio/af/hugedf5secfeatures.csv')\nafd = pd.read_csv('/hdd/physio/af2/finaldfs/2017features.csv')",
"CPU times: user 1.23 s, sys: 77.3 ms, total: 1.31 s\nWall time: 1.65 s\n"
],
[
"%%time\n_0 = afd[afd.af == 0].sample(n = 15000).reset_index(drop = True)\n_1 = afd[afd.af == 1].sample(n = 15000).reset_index(drop = True)\ntrain = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntrain = train.to_numpy()\n_0 = chd[chd.af == 0].sample(n = 1000).reset_index(drop = True)\n_1 = chd[chd.af == 1].sample(n = 1000).reset_index(drop = True)\ntest = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntest = test.to_numpy()",
"CPU times: user 117 ms, sys: 0 ns, total: 117 ms\nWall time: 290 ms\n"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_2017_test_AFDB\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
]
],
[
[
"## Train CUDB, Test VFDB",
"_____no_output_____"
]
],
[
[
"vfdb = pd.read_csv('/hdd/physio/vf2/rpeakfeats40df.csv', index_col = 0)\ncudb = pd.read_csv('/hdd/physio/vf/finaldfs/trybonsaifeatures3.csv', index_col = 0)",
"_____no_output_____"
],
[
"vfdb.vf.value_counts()",
"_____no_output_____"
],
[
"cudb.vf.value_counts()",
"_____no_output_____"
],
[
"%%time\n# _0 = cudb[cudb.vf == 0].sample(n = 1143).reset_index(drop = True)\n# _1 = cudb[cudb.vf == 1].sample(n = 1143).reset_index(drop = True)\n# train = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\n# train = train.to_numpy()\n# _0 = vfdb[vfdb.vf == 0].sample(n = 500).reset_index(drop = True)\n# _1 = vfdb[vfdb.vf == 1].sample(n = 500).reset_index(drop = True)\n# test = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\n# test = test.to_numpy()\n\ntrain = cudb.to_numpy()\ntest = vfdb.to_numpy()",
"CPU times: user 1.19 ms, sys: 546 µs, total: 1.73 ms\nWall time: 1.02 ms\n"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_CUDB_test_VFDB\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
]
],
[
[
"## Train AFDB, Test AFDB (5 second length, 1 second stride)",
"_____no_output_____"
]
],
[
[
"%%time\nafd = pd.read_csv('/hdd/physio/af/hugedf5secfeatures.csv')",
"CPU times: user 717 ms, sys: 24.6 ms, total: 742 ms\nWall time: 740 ms\n"
],
[
"%%time\n_0 = afd[afd.af == 0].sample(n = 18000).reset_index(drop = True)\n_1 = afd[afd.af == 1].sample(n = 18000).reset_index(drop = True)\ndata = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ndata.to_csv('/hdd/physio/af/finalscore.csv', index = False)",
"CPU times: user 386 ms, sys: 15.5 ms, total: 402 ms\nWall time: 401 ms\n"
],
[
"d = pd.read_csv('/hdd/physio/af/finalscore.csv')",
"_____no_output_____"
],
[
"d.af.value_counts()",
"_____no_output_____"
],
[
"%%time\n_0 = afd[afd.af == 0].sample(n = 15000).reset_index(drop = True)\n_1 = afd[afd.af == 1].sample(n = 15000).reset_index(drop = True)\ntrain = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntrain = train.to_numpy()\n_0 = afd[afd.af == 0].sample(n = 1000).reset_index(drop = True)\n_1 = afd[afd.af == 1].sample(n = 1000).reset_index(drop = True)\ntest = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntest = test.to_numpy()",
"CPU times: user 166 ms, sys: 0 ns, total: 166 ms\nWall time: 201 ms\n"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_AFDB_test_AFDB\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
]
],
[
[
"## Train VFDB, Test VFDB",
"_____no_output_____"
]
],
[
[
"%%time\nvfdb = pd.read_csv('/hdd/physio/vf2/rpeakfeats40df.csv', index_col = 0)",
"CPU times: user 12.6 ms, sys: 962 µs, total: 13.6 ms\nWall time: 13.9 ms\n"
],
[
"vfdb",
"_____no_output_____"
],
[
"%%time\n# _0 = afd[afd.af == 0].sample(n = 15000).reset_index(drop = True)\n# _1 = afd[afd.af == 1].sample(n = 15000).reset_index(drop = True)\n# train = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\n# train = train.to_numpy()\n# _0 = afd[afd.af == 0].sample(n = 1000).reset_index(drop = True)\n# _1 = afd[afd.af == 1].sample(n = 1000).reset_index(drop = True)\n# test = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\n# test = test.to_numpy()\ntrain, test = train_test_split(vfdb, test_size = 0.2, random_state = 42)",
"CPU times: user 4.86 ms, sys: 0 ns, total: 4.86 ms\nWall time: 4.38 ms\n"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_VFDB_test_VFDB\"\n\nnp.save(path + '/train.npy', train.to_numpy())\nnp.save(path + '/test.npy', test.to_numpy())",
"_____no_output_____"
]
],
[
[
"## Train CUDB, Test CUDB",
"_____no_output_____"
]
],
[
[
"%%time\ncudb = pd.read_csv('/hdd/physio/vf/finaldfs/trybonsaifeatures3.csv', index_col = 0)",
"CPU times: user 14.5 ms, sys: 0 ns, total: 14.5 ms\nWall time: 13.3 ms\n"
],
[
"train, test = train_test_split(cudb, test_size = 0.1, random_state = 42)\nprint(train.vf.value_counts(), test.vf.value_counts())",
"0 2325\n1 1030\nName: vf, dtype: int64 0 260\n1 113\nName: vf, dtype: int64\n"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_CUDB_test_CUDB\"\n\nnp.save(path + '/train.npy', train.to_numpy())\nnp.save(path + '/test.npy', test.to_numpy())",
"_____no_output_____"
]
],
[
[
"## Train CUDB, Test VFDB",
"_____no_output_____"
]
],
[
[
"%%time\nvfdb = pd.read_csv('/hdd/physio/vf2/rpeakfeats40df.csv', index_col = 0)\ncudb = pd.read_csv('/hdd/physio/vf/finaldfs/trybonsaifeatures3.csv', index_col = 0)",
"CPU times: user 22.1 ms, sys: 0 ns, total: 22.1 ms\nWall time: 21.2 ms\n"
],
[
"_0 = cudb[cudb.vf == 0].sample(n = 1143).reset_index(drop = True)\n_1 = cudb[cudb.vf == 1].sample(n = 1143).reset_index(drop = True)\ntrain = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntrain = train.to_numpy()\n_0 = vfdb[vfdb.vf == 0].sample(n = 2244).reset_index(drop = True)\n_1 = vfdb[vfdb.vf == 1].sample(n = 2244).reset_index(drop = True)\ntest = pd.concat([_0, _1], axis = 0).sample(frac = 1).reset_index(drop = True)\ntest = test.to_numpy()\n\n# train = cudb.to_numpy()\n# test = vfdb.to_numpy()",
"_____no_output_____"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_CUDB_test_VFDB\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
],
[
"cudb.vf.value_counts(), vfdb.vf.value_counts()",
"_____no_output_____"
]
],
[
[
"## Train VFDB, Test CUDB",
"_____no_output_____"
]
],
[
[
"%%time\nvfdb = pd.read_csv('/hdd/physio/vf2/rpeakfeats40df.csv', index_col = 0)\ncudb = pd.read_csv('/hdd/physio/vf/finaldfs/trybonsaifeatures3.csv', index_col = 0)",
"CPU times: user 24.8 ms, sys: 0 ns, total: 24.8 ms\nWall time: 24.2 ms\n"
],
[
"train = vfdb.to_numpy()\ntest = cudb.to_numpy()",
"_____no_output_____"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/train_VFDB_test_CUDB\"\n\nnp.save(path + '/train.npy', train)\nnp.save(path + '/test.npy', test)",
"_____no_output_____"
]
],
[
[
"## Trying time+freq domain features",
"_____no_output_____"
],
[
"### Train CUDB, Test CUDB",
"_____no_output_____"
]
],
[
[
"cu = pd.read_csv('/hdd/physio/vf/finaldfs/time_freq_features.csv', index_col = 0)\ncu",
"_____no_output_____"
],
[
"train, test = train_test_split(cu, test_size = 0.1, random_state = 42)\nprint(train.vf.value_counts(), test.vf.value_counts())",
"0 2326\n1 1018\nName: vf, dtype: int64 0 257\n1 115\nName: vf, dtype: int64\n"
],
[
"path = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/freq_train_CUDB_test_CUDB\"\n\nnp.save(path + '/train.npy', train.to_numpy())\nnp.save(path + '/test.npy', test.to_numpy())",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"pd.read_csv('/hdd/physio/vf/finaldfs/time_freq_features.csv', index_col = 0)",
"_____no_output_____"
],
[
"pd.read_csv('/hdd/physio/vf2/time_freq_features.csv')",
"_____no_output_____"
]
],
[
[
"## All detectors rpeak databases feature extraction",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport os\nimport numpy as np\nfrom ecgdetectors import Detectors\nfrom time import time as time\nimport seaborn as sns\nfrom hrvanalysis import remove_outliers, remove_ectopic_beats, interpolate_nan_values, get_time_domain_features, get_geometrical_features, get_frequency_domain_features, get_csi_cvi_features, get_poincare_plot_features, get_sampen\nfrom time import time as time\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"path = '/hdd/physio/vf/finaldfs/'\nfs = 250",
"_____no_output_____"
],
[
"df = pd.read_csv(path + 'finalrpeak5secpt.csv', index_col = 0)\ndf",
"_____no_output_____"
],
[
"%%time\ndef featureExtraction(df, fs):\n df1 = df.vf.copy()\n df.drop(columns = ['vf'], inplace = True)\n final = list()\n for i in range(len(df)):\n peaks = []\n peaks = df.loc[i][df.loc[i] == 1].index.values\n peaks = [int(x) for x in peaks]\n if (len(peaks) == 0 or len(peaks) == 1):\n continue\n vf = df1.loc[i]\n rr = np.diff(peaks) / fs \n hr = np.diff(peaks) / fs \n hr = 60 / rr\n rmssd = np.sqrt(np.mean(np.square(rr)))\n sdnn = np.std(rr)\n mean_rr = np.mean(rr)\n mean_hr = np.mean(hr)\n std_hr = np.std(hr)\n min_hr = np.min(hr)\n max_hr = np.max(hr)\n time_domain_features = {'RMSSD': rmssd, 'SDNN': sdnn, 'MEAN_RR': mean_rr, 'MEAN_HR': mean_hr, 'STD_HR': std_hr, 'MIN_HR': min_hr, 'MAX_HR': max_hr}\n frequency_domain_features = get_frequency_domain_features(peaks)\n features = [time_domain_features, frequency_domain_features]\n del peaks\n new = {}\n for x in features:\n for y in x:\n new[y] = x[y]\n\n single_window_df = pd.DataFrame(list(new.items()))\n single_window_df = single_window_df.transpose()\n columns = single_window_df.iloc[0]\n single_window_df = single_window_df[1:]\n single_window_df.columns = columns\n single_window_df.drop(columns = ['lfnu', 'hfnu'], inplace = True)\n single_window_df.insert(0, 'vf', vf)\n final.append(single_window_df)\n del single_window_df\n return pd.concat(final)\n\nfinaldf = featureExtraction(df, fs)\nfinaldf.reset_index(drop = True, inplace = True)",
"CPU times: user 20 s, sys: 7.67 ms, total: 20 s\nWall time: 20 s\n"
],
[
"finaldf = finaldf.dropna(how='any')\nfinaldf",
"_____no_output_____"
],
[
"finaldf.to_csv('/hdd/physio/vf/pttimefreqfeatures.csv', index = False)",
"_____no_output_____"
]
],
[
[
"## Use all detectors to train and test",
"_____no_output_____"
]
],
[
[
"hs = pd.read_csv('/hdd/physio/vf/hstimefreqfeatures.csv')\npt = pd.read_csv('/hdd/physio/vf/pttimefreqfeatures.csv')\nsswt = pd.read_csv('/hdd/physio/vf/sswttimefreqfeatures.csv')",
"_____no_output_____"
],
[
"train, test = train_test_split(sswt, test_size = 0.1, random_state = 42)\n\npath = \"/hdd/physio/edgeml/examples/pytorch/Bonsai/sswt_freq_train_CUDB_test_CUDB\"\n\nnp.save(path + '/train.npy', train.to_numpy())\nnp.save(path + '/test.npy', test.to_numpy())",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"raw",
"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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"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"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"raw"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ecd03688a29c5b9375c8c13b1ee02346c173bd16 | 47,866 | ipynb | Jupyter Notebook | notebooks/rip_postprocess_testlib.ipynb | malfarasplux/biofeatures | 90cba009a34dbaf35ec112edc8f2e93a72563c5b | [
"ISC"
] | null | null | null | notebooks/rip_postprocess_testlib.ipynb | malfarasplux/biofeatures | 90cba009a34dbaf35ec112edc8f2e93a72563c5b | [
"ISC"
] | null | null | null | notebooks/rip_postprocess_testlib.ipynb | malfarasplux/biofeatures | 90cba009a34dbaf35ec112edc8f2e93a72563c5b | [
"ISC"
] | 1 | 2020-02-10T09:55:58.000Z | 2020-02-10T09:55:58.000Z | 42.585409 | 5,243 | 0.509736 | [
[
[
"import numpy as np\nimport csv as csv\nimport json \nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"import biosppy.signals.resp as resp\n# Returns\n# -------\n# ts : array\n# Signal time axis reference (seconds).\n# filtered : array\n# Filtered Respiration signal.\n# zeros : array\n# Indices of Respiration zero crossings.\n# resp_rate_ts : array\n# Respiration rate time axis reference (seconds).\n# resp_rate : array\n# Instantaneous respiration rate (Hz).",
"_____no_output_____"
],
[
"def moving_average(x, w):\n return np.convolve(x, np.ones(w), 'valid') / w",
"_____no_output_____"
]
],
[
[
"### Read header",
"_____no_output_____"
]
],
[
[
"# fname = 'https://github.com/malfarasplux/biofeatures/tree/master/riot_rip_acquisition/ak/opensignals_192.168.1.1008888_2020-02-05_11-54-42.txt'\nfname = '../riot_rip_acquisition/ak/opensignals_192.168.1.1008888_2020-02-05_11-54-42.txt'\nwith open(fname) as datafile:\n readdata = csv.reader(datafile, delimiter='\\t')\n header = [next(readdata), next(readdata), next(readdata)]\n header_json = json.loads(header[1][0][1:])\nprint(header_json)",
"{'192.168.1.100:8888': {'sensor': ['RIOT', 'RIOT', 'RIOT', 'RIOT', 'RIOT'], 'device name': '192.168.1.100:8888', 'column': ['nSeq', 'DI', 'ACCx', 'ACCy', 'ACCz', 'ANALOG1', 'ANALOG2'], 'sync interval': 2, 'time': '11:54:43.221', 'comments': '', 'device connection': '192.168.1.100:8888', 'channels': [1, 2, 3, 13, 14], 'keywords': '', 'convertedValues': 0, 'mode': 0, 'digital IO': [0, 1], 'firmware version': 'riot', 'device': 'riot', 'position': 0, 'sampling rate': 200, 'label': ['ACCx', 'ACCy', 'ACCz', 'ANALOG1', 'ANALOG2'], 'resolution': [1, 1, 1, 1, 1], 'date': '2020-2-5', 'special': [{}, {}, {}, {}, {}]}}\n"
]
],
[
[
"### Read data",
"_____no_output_____"
]
],
[
[
"data = np.genfromtxt(fname)\nprint(data.shape)",
"(48150, 7)\n"
],
[
"# Locate the sampling rate \nsrate = header_json[list(header_json.keys())[0]]['sampling rate']\nsrate",
"_____no_output_____"
],
[
"# Locate the analog channel\ncol_num = header_json[list(header_json.keys())[0]]['column'].index('ANALOG1')\ncol_num",
"_____no_output_____"
],
[
"ripdata = data[:,col_num]",
"_____no_output_____"
]
],
[
[
"### Test the library",
"_____no_output_____"
]
],
[
[
"import biofeatures",
"_____no_output_____"
],
[
"B = biofeatures.breathing(ripdata[:2000])",
"_____no_output_____"
],
[
"B.resp_intervals(data=B.data)",
"_____no_output_____"
],
[
"B.resp_features()",
"_____no_output_____"
],
[
"B.features",
"_____no_output_____"
],
[
"B.interval_breathe_in",
"_____no_output_____"
],
[
"B.interval_lengths",
"_____no_output_____"
],
[
"np.sum(B.interval_lengths[B.interval_breathe_in])/B.srate",
"_____no_output_____"
],
[
"np.sum(B.interval_lengths[np.logical_not(B.interval_breathe_in)])/B.srate",
"_____no_output_____"
],
[
"B.feature_names",
"_____no_output_____"
],
[
"B.resp_rate*60",
"_____no_output_____"
]
],
[
[
"### Simulate real time",
"_____no_output_____"
]
],
[
[
"import time",
"_____no_output_____"
],
[
"ti = time.time()",
"_____no_output_____"
],
[
"tf = time.time()\nind = 10000\nts = 0.5\n\n# 5 seconds, every 0.5\nwhile tf-ti < 5:\n B.data = ripdata[ind-B.buffer_length:ind]\n ind += int(ts*B.srate)\n B.resp_intervals(data=B.data)\n B.resp_features()\n print(B.features)\n time.sleep(ts)\n tf = time.time()\n",
"_____no_output_____"
],
[
"B.buffer_length\n",
"_____no_output_____"
],
[
"from pythonosc import dispatcher, osc_server\nfrom pythonosc.udp_client import SimpleUDPClient\nimport time\n",
"_____no_output_____"
],
[
"riot_ip = '192.168.0.102'\nriot_port = 31000\nactuator_port = 12000\nactuator_ip = '192.168.0.103'\n\nclient = SimpleUDPClient(riot_ip, riot_port) \nresp_data = []",
"_____no_output_____"
],
[
"def process_riot_data(unused_addr, *values):\n global resp_data, last_update, client\n global t0, B\n \n \n new_data = values[12]\n resp_data.append(new_data)\n if B.WU:\n B.data = resp_data[-B.buffer_length:]\n# print(new_data)\n\n warmup = 10\n tf = time.time()\n\n# dmax = 15\n# if tf-ti > 0.5 and tf-t0 < warmup+dmax and tf-t0 > warmup: \n# print(tf-t0)\n# real_time_feat()\n# ti = time.time()\n\n\n if tf-t0 > warmup: \n if not B.WU:\n print(\"WARMUP\")\n B = biofeatures.breathing(data = resp_data)\n B.WU = True\n B.update_loop()\n\n \n# if len(resp_data) > 200*10 and time.time() - last_update > update_freq:\n# last_int, breathe_in = biofeatures.calc_resp_intervals(resp_data, last_breath = True)\n \n# if breathe_in:\n# print(\"Breathing in\")\n# client.send_message(\"/actuator/inflate\", 100.0)\n# else:\n# print(\"Breathing out\")\n# client.send_message(\"/actuator/inflate\", -100.0)\n \n# last_update = time.time()\n \n # only save the last 5 min of data\n if len(resp_data) > 200 * 60 * 5:\n resp_data = resp_data[-200*60*5:]",
"_____no_output_____"
],
[
"t0 = time.time()\nti = time.time()\nriot_dispatcher = dispatcher.Dispatcher()\nriot_dispatcher.map(\"/*/raw\", process_riot_data)\n\nserver = osc_server.ThreadingOSCUDPServer((riot_ip, riot_port), riot_dispatcher)\nprint(\"Serving on {}\".format(server.server_address))\nserver.serve_forever()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecd039de8a50b737441d49912a5dd5a1c0e7676e | 104,949 | ipynb | Jupyter Notebook | User Independence Analysis/ipynb/.ipynb_checkpoints/Forward Selection 4 class-checkpoint.ipynb | ramanathanmurugappan/User-Independent-Human-Stress-Detection | 56d8fc52ecc3e8751ef07304eb349f88ab5d08df | [
"MIT"
] | null | null | null | User Independence Analysis/ipynb/.ipynb_checkpoints/Forward Selection 4 class-checkpoint.ipynb | ramanathanmurugappan/User-Independent-Human-Stress-Detection | 56d8fc52ecc3e8751ef07304eb349f88ab5d08df | [
"MIT"
] | null | null | null | User Independence Analysis/ipynb/.ipynb_checkpoints/Forward Selection 4 class-checkpoint.ipynb | ramanathanmurugappan/User-Independent-Human-Stress-Detection | 56d8fc52ecc3e8751ef07304eb349f88ab5d08df | [
"MIT"
] | 3 | 2020-09-29T17:48:39.000Z | 2021-05-06T17:55:53.000Z | 63.108238 | 1,159 | 0.51687 | [
[
[
"%%time\nimport pandas as pd\nimport numpy as np\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom imblearn.over_sampling import SMOTE,RandomOverSampler\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.preprocessing import Normalizer\nfrom itertools import combinations \nfrom mlxtend.classifier import StackingClassifier\nfrom sklearn import model_selection\nimport copy ",
"Using TensorFlow backend.\n/home/sf/.local/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/home/sf/.local/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/home/sf/.local/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/home/sf/.local/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/home/sf/.local/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/home/sf/.local/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"
],
[
"df=pd.read_csv('60s_window_wrist_chest.csv',index_col=0)\n",
"_____no_output_____"
],
[
"df['label'].value_counts()",
"_____no_output_____"
],
[
"features=df.columns.tolist()\nfeatures\n\nremoved = ['label']\nfor rem in removed:\n features.remove(rem)\n\nfeatures_with_sub=[]\nfeatures_with_sub[:]=features\nremoved = ['subject']\nfor rem in removed:\n features.remove(rem)\n\nfeature=features\nprint(len(feature))\nlen(features_with_sub)\n",
"70\n"
],
[
"sm = SMOTE(random_state=2)\nX, y= sm.fit_sample(df[features_with_sub], df['label'])\ndf_new=pd.concat([pd.DataFrame(X,columns=features_with_sub),pd.DataFrame(y,columns=['label'])],axis=1)\ndf_new",
"_____no_output_____"
],
[
"for i in range (len(list(df_new['subject']))):\n df_new['subject'][i] = min([2,3,4,5,6,7,8,9,10,11,13,14,15,16,17], key=lambda x:abs(x-df_new['subject'][i]))\ndf_new['subject']=df_new['subject'].astype(int)",
"/home/sf/.local/lib/python3.6/site-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n"
],
[
"p_d=pd.read_csv('personal_detail.csv',index_col=0)",
"_____no_output_____"
],
[
"df_new_1=df_new.merge(p_d,on='subject')\ndf_new_1",
"_____no_output_____"
],
[
"df_new_1['label'].value_counts()",
"_____no_output_____"
],
[
"features=df_new_1.columns.tolist()\nfeatures\n\nremoved = ['label']\nfor rem in removed:\n features.remove(rem)\nfeatures_with_sub=[]\nfeatures_with_sub[:]=features\nremoved = ['subject']\nfor rem in removed:\n features.remove(rem)\n\nfeature=features\nprint(len(feature))\nlen(features_with_sub)",
"79\n"
],
[
"train=df_new_1[df_new_1['subject']<=9]\ntest=df_new_1[df_new_1['subject']>9]",
"_____no_output_____"
],
[
"scaler = Normalizer()\nscaled_data_train = scaler.fit_transform(train[feature])\nscaled_data_test = scaler.transform(test[feature])",
"_____no_output_____"
],
[
"et = ExtraTreesClassifier(n_estimators=100,n_jobs=10,random_state=56)\net.fit(scaled_data_train,train['label'])\ny_pred=et.predict(scaled_data_test)",
"_____no_output_____"
],
[
"print(classification_report(test['label'],y_pred))",
" precision recall f1-score support\n\n 0 0.77 0.62 0.69 147\n 1 0.90 0.92 0.91 161\n 2 0.65 0.79 0.71 146\n 3 0.76 0.74 0.75 149\n\n accuracy 0.77 603\n macro avg 0.77 0.77 0.77 603\nweighted avg 0.77 0.77 0.77 603\n\n"
],
[
"feature_importances = pd.DataFrame(et.feature_importances_,index = feature,columns=['importance']).sort_values('importance', ascending=False)",
"_____no_output_____"
],
[
"feature_importances",
"_____no_output_____"
]
],
[
[
"# Feature Selection with feature_importances\n",
"_____no_output_____"
]
],
[
[
"all_features = feature_importances.index",
"_____no_output_____"
],
[
"temp = []\nfor i in all_features:\n temp.append(i)\n# print (temp)\n scalerr = Normalizer()\n scaled_data_trainn = scalerr.fit_transform(train[temp])\n scaled_data_testt = scalerr.transform(test[temp])\n \n ett = ExtraTreesClassifier(n_estimators=100,n_jobs=10,random_state=56)\n ett.fit(scaled_data_trainn,train['label'])\n y_pred=ett.predict(scaled_data_testt)\n \n rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy']\n \n if rpt >= 0.75:\n print (len(temp))\n print (classification_report(test['label'],y_pred))\n \n ",
"/home/sf/.local/lib/python3.6/site-packages/sklearn/metrics/classification.py:1437: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n"
]
],
[
[
"# Feature Selection with feature_importances using forward Selection\n",
"_____no_output_____"
]
],
[
[
"all_features_c = copy.deepcopy(all_features)\nmas = []\n\nwhile len(all_features_c)!=0:\n temp = []\n acc_list = []\n all_features_c = [x for x in all_features_c if x not in mas]\n print (\"**************************\",len(all_features_c))\n\n for i in all_features_c:\n temp.append(i)\n temp = temp + mas\n# print (temp)\n scalerr = Normalizer()\n scaled_data_trainn = scalerr.fit_transform(train[temp])\n scaled_data_testt = scalerr.transform(test[temp])\n\n ett = ExtraTreesClassifier(n_estimators=100,n_jobs=10,random_state=56)\n ett.fit(scaled_data_trainn,train['label'])\n y_pred=ett.predict(scaled_data_testt)\n\n acc_list.append(classification_report(test['label'],y_pred,output_dict=True)['accuracy'])\n\n ind = acc_list.index(min(acc_list))\n val = all_features_c[ind]\n mas.append(val)\n all_features_c.remove(val)\n print (\"**************************\",mas,min(acc_list))",
"************************** 79\n"
],
[
"sel_fea = ['EDA_tonic_mean','EDA_smna_mean','EDA_tonic_min','EDA_phasic_mean','TEMP_std','BVP_peak_freq','smoker_YES','ACC_y_min','ACC_x_mean','weight','gender_ female','c_Temp_max','ACC_x_max','TEMP_mean',\n 'c_ACC_y_std','net_acc_max','Resp_std']\n\nprint (len(sel_fea))\n",
"17\n"
],
[
"#56\nfor i in range (0,101):\n scaler = Normalizer()\n scaled_data_train = scaler.fit_transform(train[sel_fea])\n scaled_data_test = scaler.transform(test[sel_fea])\n\n ett = ExtraTreesClassifier(n_estimators=100,n_jobs=10,random_state=i)\n ett.fit(scaled_data_train,train['label'])\n y_pred=ett.predict(scaled_data_test)\n\n rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy']\n \n if rpt >= 0.78:\n print (i)\n print (classification_report(test['label'],y_pred))",
"47\n precision recall f1-score support\n\n 0 0.87 0.72 0.79 147\n 1 0.86 0.93 0.89 161\n 2 0.62 0.75 0.68 146\n 3 0.82 0.72 0.77 149\n\n accuracy 0.78 603\n macro avg 0.79 0.78 0.78 603\nweighted avg 0.79 0.78 0.78 603\n\n61\n precision recall f1-score support\n\n 0 0.88 0.71 0.78 147\n 1 0.84 0.93 0.88 161\n 2 0.68 0.74 0.71 146\n 3 0.79 0.77 0.78 149\n\n accuracy 0.79 603\n macro avg 0.80 0.79 0.79 603\nweighted avg 0.80 0.79 0.79 603\n\n78\n precision recall f1-score support\n\n 0 0.89 0.67 0.77 147\n 1 0.81 0.90 0.85 161\n 2 0.65 0.81 0.72 146\n 3 0.85 0.75 0.80 149\n\n accuracy 0.79 603\n macro avg 0.80 0.78 0.78 603\nweighted avg 0.80 0.79 0.79 603\n\n95\n precision recall f1-score support\n\n 0 0.87 0.67 0.75 147\n 1 0.84 0.91 0.88 161\n 2 0.62 0.85 0.72 146\n 3 0.87 0.68 0.77 149\n\n accuracy 0.78 603\n macro avg 0.80 0.78 0.78 603\nweighted avg 0.80 0.78 0.78 603\n\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
ecd047807cbf6835d98d64f829069b959558a82b | 54,859 | ipynb | Jupyter Notebook | aoc2021.ipynb | jduncan8142/advent_of_code_2021 | 58dee98b78e6eaba37e8bd5e1bd4eab2a75a9e4f | [
"MIT"
] | null | null | null | aoc2021.ipynb | jduncan8142/advent_of_code_2021 | 58dee98b78e6eaba37e8bd5e1bd4eab2a75a9e4f | [
"MIT"
] | null | null | null | aoc2021.ipynb | jduncan8142/advent_of_code_2021 | 58dee98b78e6eaba37e8bd5e1bd4eab2a75a9e4f | [
"MIT"
] | null | null | null | 28.827641 | 435 | 0.46182 | [
[
[
"# Day 1: Sonar Sweep\n## Part 1\nYou're minding your own business on a ship at sea when the overboard alarm goes off! You rush to see if you can help. Apparently, one of the Elves tripped and accidentally sent the sleigh keys flying into the ocean!\n\nBefore you know it, you're inside a submarine the Elves keep ready for situations like this. It's covered in Christmas lights (because of course it is), and it even has an experimental antenna that should be able to track the keys if you can boost its signal strength high enough; there's a little meter that indicates the antenna's signal strength by displaying 0-50 stars.\n\nYour instincts tell you that in order to save Christmas, you'll need to get all fifty stars by December 25th.\n\nCollect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!\n\nAs the submarine drops below the surface of the ocean, it automatically performs a sonar sweep of the nearby sea floor. On a small screen, the sonar sweep report (your puzzle input) appears: each line is a measurement of the sea floor depth as the sweep looks further and further away from the submarine.\n\nFor example, suppose you had the following report:\n```\n199\n200\n208\n210\n200\n207\n240\n269\n260\n263\n```\nThis report indicates that, scanning outward from the submarine, the sonar sweep found depths of 199, 200, 208, 210, and so on.\n\nThe first order of business is to figure out how quickly the depth increases, just so you know what you're dealing with - you never know if the keys will get carried into deeper water by an ocean current or a fish or something.\n\nTo do this, count the number of times a depth measurement increases from the previous measurement. (There is no measurement before the first measurement.) In the example above, the changes are as follows:\n```\n199 (N/A - no previous measurement)\n200 (increased)\n208 (increased)\n210 (increased)\n200 (decreased)\n207 (increased)\n240 (increased)\n269 (increased)\n260 (decreased)\n263 (increased)\n```\nIn this example, there are 7 measurements that are larger than the previous measurement.\n\n`How many measurements are larger than the previous measurement?`\n\nAnswer: `1602`",
"_____no_output_____"
]
],
[
[
"input_file1 = open(\"aoc2021_day1_input.txt\", \"r\")\ndata1 = [int(x.strip(\" \\n\\r\\t\")) for x in input_file1.readlines()]",
"_____no_output_____"
],
[
"count_larger = 0\nlast_value = None\nfor i in data1:\n if last_value is None:\n last_value = i\n elif i > last_value:\n count_larger += 1\n last_value = i\n\nprint(count_larger)",
"1602\n"
]
],
[
[
"## Part 2\nConsidering every single measurement isn't as useful as you expected: there's just too much noise in the data.\n\nInstead, consider sums of a three-measurement sliding window. Again considering the above example:\n\n```\n199 A \n200 A B \n208 A B C \n210 B C D\n200 E C D\n207 E F D\n240 E F G \n269 F G H\n260 G H\n263 H\n```\nStart by comparing the first and second three-measurement windows. The measurements in the first window are marked A (199, 200, 208); their sum is 199 + 200 + 208 = 607. The second window is marked B (200, 208, 210); its sum is 618. The sum of measurements in the second window is larger than the sum of the first, so this first comparison increased.\n\nYour goal now is to count the number of times the sum of measurements in this sliding window increases from the previous sum. So, compare A with B, then compare B with C, then C with D, and so on. Stop when there aren't enough measurements left to create a new three-measurement sum.\n\nIn the above example, the sum of each three-measurement window is as follows:\n\nA: 607 (N/A - no previous sum)\nB: 618 (increased)\nC: 618 (no change)\nD: 617 (decreased)\nE: 647 (increased)\nF: 716 (increased)\nG: 769 (increased)\nH: 792 (increased)\nIn this example, there are 5 sums that are larger than the previous sum.\n\nConsider sums of a three-measurement sliding window. How many sums are larger than the previous sum?\n\nAnswer: `1633`",
"_____no_output_____"
]
],
[
[
"count_larger = 0\nlast_values = None\ncurrent_values = [0, 0, 0]\nlast_sum = None\ncurrent_sum = 0\nfor index, value in enumerate(data1):\n current_values = data1[index:index+3]\n current_sum = sum(current_values)\n if last_values is None or last_sum is None:\n last_values = current_values\n last_sum = current_sum\n elif current_sum > last_sum:\n count_larger += 1\n last_values = current_values\n last_sum = current_sum\n\nprint(count_larger)",
"1633\n"
]
],
[
[
"# Day 2: Dive!\n## Part 1\nNow, you need to figure out how to pilot this thing.\n\nIt seems like the submarine can take a series of commands like forward 1, down 2, or up 3:\n\nforward X increases the horizontal position by X units.\ndown X increases the depth by X units.\nup X decreases the depth by X units.\nNote that since you're on a submarine, down and up affect your depth, and so they have the opposite result of what you might expect.\n\nThe submarine seems to already have a planned course (your puzzle input). You should probably figure out where it's going. For example:\n```\nforward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2\n```\nYour horizontal position and depth both start at 0. The steps above would then modify them as follows:\n\n```\nforward 5 adds 5 to your horizontal position, a total of 5.\ndown 5 adds 5 to your depth, resulting in a value of 5.\nforward 8 adds 8 to your horizontal position, a total of 13.\nup 3 decreases your depth by 3, resulting in a value of 2.\ndown 8 adds 8 to your depth, resulting in a value of 10.\nforward 2 adds 2 to your horizontal position, a total of 15.\n```\nAfter following these instructions, you would have a horizontal position of 15 and a depth of 10. (Multiplying these together produces 150.)\n\nCalculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth?\n\nAnswer: `2117664`",
"_____no_output_____"
]
],
[
[
"input_file2 = open(\"aoc2021_day2_input.txt\", \"r\")\ndata2 = [x.strip(\" \\n\\r\\t\") for x in input_file2.readlines()]",
"_____no_output_____"
],
[
"hp = 0\nvp = 0\nfor i in data2:\n direction, value = i.split(\" \")\n direction = direction.lower()\n value = int(value)\n if direction == \"forward\":\n hp = hp + value\n elif direction == \"down\":\n vp = vp + value\n elif direction == \"up\":\n vp = vp - value\n else:\n print(f\"We didn't handle this case > Direction: {direction} <> Value: {value}\")\nfp = hp * vp\nprint(fp)",
"2117664\n"
]
],
[
[
"## Part Two\nBased on your calculations, the planned course doesn't seem to make any sense. You find the submarine manual and discover that the process is actually slightly more complicated.\n\nIn addition to horizontal position and depth, you'll also need to track a third value, aim, which also starts at 0. The commands also mean something entirely different than you first thought:\n```\ndown X increases your aim by X units.\nup X decreases your aim by X units.\nforward X does two things:\nIt increases your horizontal position by X units.\nIt increases your depth by your aim multiplied by X.\n```\nAgain note that since you're on a submarine, down and up do the opposite of what you might expect: \"down\" means aiming in the positive direction.\n\nNow, the above example does something different:\n```\nforward 5 adds 5 to your horizontal position, a total of 5. Because your aim is 0, your depth does not change.\ndown 5 adds 5 to your aim, resulting in a value of 5.\nforward 8 adds 8 to your horizontal position, a total of 13. Because your aim is 5, your depth increases by 8*5=40.\nup 3 decreases your aim by 3, resulting in a value of 2.\ndown 8 adds 8 to your aim, resulting in a value of 10.\nforward 2 adds 2 to your horizontal position, a total of 15. Because your aim is 10, your depth increases by 2*10=20 to a total of 60.\n```\nAfter following these new instructions, you would have a horizontal position of 15 and a depth of 60. (Multiplying these produces 900.)\n\nUsing this new interpretation of the commands, calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth?\n\nAnswer: `2073416724`",
"_____no_output_____"
]
],
[
[
"hp = 0\nvp = 0\naim = 0\nfor i in data2:\n direction, value = i.split(\" \")\n direction = direction.lower()\n value = int(value)\n if direction == \"forward\":\n hp = hp + value\n vp = vp + (aim * value)\n elif direction == \"down\":\n aim = aim + value\n elif direction == \"up\":\n aim = aim - value\n else:\n print(f\"We didn't handle this case > Direction: {direction} <> Value: {value}\")\nfp = hp * vp\nprint(fp)",
"2073416724\n"
]
],
[
[
"# Day 3: Binary Diagnostic\n\n## Part 1\nThe submarine has been making some odd creaking noises, so you ask it to produce a diagnostic report just in case.\n\nThe diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things about the conditions of the submarine. The first parameter to check is the power consumption.\n\nYou need to use the binary numbers in the diagnostic report to generate two new binary numbers (called the gamma rate and the epsilon rate). The power consumption can then be found by multiplying the gamma rate by the epsilon rate.\n\nEach bit in the gamma rate can be determined by finding the most common bit in the corresponding position of all numbers in the diagnostic report. For example, given the following diagnostic report:\n```\n00100\n11110\n10110\n10111\n10101\n01111\n00111\n11100\n10000\n11001\n00010\n01010\n```\nConsidering only the first bit of each number, there are five 0 bits and seven 1 bits. Since the most common bit is 1, the first bit of the gamma rate is 1.\n\nThe most common second bit of the numbers in the diagnostic report is 0, so the second bit of the gamma rate is 0.\n\nThe most common value of the third, fourth, and fifth bits are 1, 1, and 0, respectively, and so the final three bits of the gamma rate are 110.\n\nSo, the gamma rate is the binary number 10110, or 22 in decimal.\n\nThe epsilon rate is calculated in a similar way; rather than use the most common bit, the least common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal. Multiplying the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198.\n\nUse the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate, then multiply them together. What is the power consumption of the submarine? (Be sure to represent your answer in decimal, not binary.)\n\nAnswer: `845186`",
"_____no_output_____"
]
],
[
[
"input_file3 = open(\"aoc2021_day3_input.txt\", \"r\")\ndata3 = [x.strip(\" \\n\\r\\t\") for x in input_file3.readlines()]",
"_____no_output_____"
],
[
"gamma_b = []\nepsilon_b = []\ngamma_d = 0\nepsilon_d = 0\npc = 0\nbc = len(data3[0])\n\nfor col in range(bc):\n bits = [i[col] for i in data3]\n gamma_b.append(max(set(bits), key=bits.count))\n epsilon_b.append(min(set(bits), key=bits.count))\n\nprint(\"\".join(gamma_b), \"\".join(epsilon_b))\nprint(int(\"\".join(gamma_b), base=2), int(\"\".join(epsilon_b), base=2))\ngamma_d = int(\"\".join(gamma_b), base=2)\nepsilon_d = int(\"\".join(epsilon_b), base=2)\npc = gamma_d * epsilon_d\nprint(pc)\n\n",
"000011011010 111100100101\n218 3877\n845186\n"
]
],
[
[
"## Part Two\nNext, you should verify the life support rating, which can be determined by multiplying the oxygen generator rating by the CO2 scrubber rating.\n\nBoth the oxygen generator rating and the CO2 scrubber rating are values that can be found in your diagnostic report - finding them is the tricky part. Both values are located using a similar process that involves filtering out values until only one remains. Before searching for either rating value, start with the full list of binary numbers from your diagnostic report and consider just the first bit of those numbers. Then:\n\nKeep only numbers selected by the bit criteria for the type of rating value for which you are searching. Discard numbers which do not match the bit criteria.\nIf you only have one number left, stop; this is the rating value for which you are searching.\nOtherwise, repeat the process, considering the next bit to the right.\nThe bit criteria depends on which type of rating value you want to find:\n\nTo find oxygen generator rating, determine the most common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 1 in the position being considered.\nTo find CO2 scrubber rating, determine the least common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 0 in the position being considered.\nFor example, to determine the oxygen generator rating value using the same example diagnostic report from above:\n\nStart with all 12 numbers and consider only the first bit of each number. There are more 1 bits (7) than 0 bits (5), so keep only the 7 numbers with a 1 in the first position: \n```\n11110\n10110\n10111\n10101\n11100\n10000\n11001\n```\n\nThen, consider the second bit of the 7 remaining numbers: there are more 0 bits (4) than 1 bits (3), so keep only the 4 numbers with a 0 in the second position: 10110, 10111, 10101, and 10000.\nIn the third position, three of the four numbers have a 1, so keep those three: 10110, 10111, and 10101.\nIn the fourth position, two of the three numbers have a 1, so keep those two: 10110 and 10111.\nIn the fifth position, there are an equal number of 0 bits and 1 bits (one each). So, to find the oxygen generator rating, keep the number with a 1 in that position: 10111.\nAs there is only one number left, stop; the oxygen generator rating is 10111, or 23 in decimal.\nThen, to determine the CO2 scrubber rating value from the same example above:\n\nStart again with all 12 numbers and consider only the first bit of each number. There are fewer 0 bits (5) than 1 bits (7), so keep only the 5 numbers with a 0 in the first position: 00100, 01111, 00111, 00010, and 01010.\nThen, consider the second bit of the 5 remaining numbers: there are fewer 1 bits (2) than 0 bits (3), so keep only the 2 numbers with a 1 in the second position: 01111 and 01010.\nIn the third position, there are an equal number of 0 bits and 1 bits (one each). So, to find the CO2 scrubber rating, keep the number with a 0 in that position: 01010.\nAs there is only one number left, stop; the CO2 scrubber rating is 01010, or 10 in decimal.\nFinally, to find the life support rating, multiply the oxygen generator rating (23) by the CO2 scrubber rating (10) to get 230.\n\nUse the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating, then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in decimal, not binary.)\n\nAnswer: ``",
"_____no_output_____"
]
],
[
[
"from collections import Counter\n\nlsr = 0 # Life Support Rating\nogr = None # Oxygen Generator Rating\ncsr = None # CO2 Scrubber Rating\nbc = len(data3[0])\nmcb_data = lcb_data = data3\n\nwhile ogr is None or csr is None:\n for col in range(bc):\n mcbc = Counter([i[col] for i in mcb_data]).most_common()\n mcb = 1 if mcbc[0][1] == mcbc[-1][1] else mcbc[0][0]\n lcbc = Counter([i[col] for i in lcb_data]).most_common()\n lcb = 0 if lcbc[0][1] == lcbc[-1][1] else lcbc[-1][0]\n if len(mcb_data) > 1:\n mcb_data = [value for value in mcb_data if value[col] == str(mcb)]\n if len(lcb_data) > 1:\n lcb_data = [value for value in lcb_data if value[col] == str(lcb)]\n ogr = int(\"\".join(mcb_data[0]), base=2) if len(mcb_data) == 1 else None\n csr = int(\"\".join(lcb_data[0]), base=2) if len(lcb_data) == 1 else None\n\nlsr = ogr * csr\nprint(f\"OGR: {ogr} <> CSR: {csr} <> LSR: {lsr}\")",
"OGR: 1459 <> CSR: 3178 <> LSR: 4636702\n"
]
],
[
[
"# Day 4: Giant Squid\n## Part 1\nYou're already almost 1.5km (almost a mile) below the surface of the ocean, already so deep that you can't see any sunlight. What you can see, however, is a giant squid that has attached itself to the outside of your submarine.\n\nMaybe it wants to play bingo?\n\nBingo is played on a set of boards each consisting of a 5x5 grid of numbers. Numbers are chosen at random, and the chosen number is marked on all boards on which it appears. (Numbers may not appear on all boards.) If all numbers in any row or any column of a board are marked, that board wins. (Diagonals don't count.)\n\nThe submarine has a bingo subsystem to help passengers (currently, you and the giant squid) pass the time. It automatically generates a random order in which to draw numbers and a random set of boards (your puzzle input). For example:\n\n```\n7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1\n\n22 13 17 11 0\n 8 2 23 4 24\n21 9 14 16 7\n 6 10 3 18 5\n 1 12 20 15 19\n\n 3 15 0 2 22\n 9 18 13 17 5\n19 8 7 25 23\n20 11 10 24 4\n14 21 16 12 6\n\n14 21 17 24 4\n10 16 15 9 19\n18 8 23 26 20\n22 11 13 6 5\n 2 0 12 3 7\n ```\nAfter the first five numbers are drawn (7, 4, 9, 5, and 11), there are no winners, but the boards are marked as follows (shown here adjacent to each other to save space):\n\n22 13 17 **11** 0 \n8 2 23 **4** 24 \n21 **9** 14 16 **7** \n6 10 3 18 **5** \n1 12 20 15 19 \n\n 3 15 0 2 22 \n**9** 18 13 17 **5** \n19 8 **7** 25 23 \n20 **11** 10 24 **4** \n14 21 16 12 6 \n\n14 21 17 24 **4**\n10 16 15 **9** 19\n18 8 23 26 20\n22 **11** 13 6 **5**\n 2 0 12 3 **7**\n\nAfter the next six numbers are drawn (17, 23, 2, 0, 14, and 21), there are still no winners:\n\n22 13 17 11 0 3 15 0 2 22 14 21 17 24 4\n 8 2 23 4 24 9 18 13 17 5 10 16 15 9 19\n21 9 14 16 7 19 8 7 25 23 18 8 23 26 20\n 6 10 3 18 5 20 11 10 24 4 22 11 13 6 5\n 1 12 20 15 19 14 21 16 12 6 2 0 12 3 7\nFinally, 24 is drawn:\n\n22 13 17 11 0 3 15 0 2 22 14 21 17 24 4\n 8 2 23 4 24 9 18 13 17 5 10 16 15 9 19\n21 9 14 16 7 19 8 7 25 23 18 8 23 26 20\n 6 10 3 18 5 20 11 10 24 4 22 11 13 6 5\n 1 12 20 15 19 14 21 16 12 6 2 0 12 3 7\nAt this point, the third board wins because it has at least one complete row or column of marked numbers (in this case, the entire top row is marked: 14 21 17 24 4).\n\nThe score of the winning board can now be calculated. Start by finding the sum of all unmarked numbers on that board; in this case, the sum is 188. Then, multiply that sum by the number that was just called when the board won, 24, to get the final score, 188 * 24 = 4512.\n\nTo guarantee victory against the giant squid, figure out which board will win first. What will your final score be if you choose that board?",
"_____no_output_____"
]
],
[
[
"input_file4 = open(\"aoc2021_day4_input.txt\", \"r\")\ndata4 = [x.strip(\" \\n\\r\\t\") for x in input_file4.readlines()]\ncalls = data4[0].split(\",\")\nboards = []\n\nclass Cell:\n def __init__(self, value: int) -> None:\n self.value: int = int(value)\n self.marked: bool = False\n \n def check(self, called_value: int) -> None:\n if not self.marked:\n if called_value == self.value:\n self.marked = True\n\nclass Column(Cell):\n def __init__(self) -> None:\n self.column: list[Cell] = []\n self.marked_column = False\n \n def create_column(self, values: list[int]) -> list:\n for value in values:\n self.column.append(Cell(value=value))\n \n def check(self, called_value: int) -> None:\n if not self.marked_column:\n for c in self.column:\n c.check(called_value=called_value)\n if all([x.marked for x in self.column]):\n self.marked_column = True\n\nclass Row(Cell):\n def __init__(self) -> None:\n self.row: list[Cell] = []\n self.marked_row = False\n \n def create_row(self, values) -> list:\n for value in values:\n self.row.append(Cell(value=value))\n\n def check(self, called_value: int) -> None:\n if not self.marked_row:\n for c in self.row:\n c.check(called_value=called_value)\n if all([x.marked for x in self.row]):\n self.marked_row = True\n\nclass Board:\n def __init__(self, data: list[list], width: int = 5, height: int = 5) -> None:\n self.raw_data: list[list] = data\n self.rows: list[Row]\n self.columns: list[Column]\n self.winner: bool = False\n self.score: int = 0\n self.width: int = width\n self.height: int = height\n\n def create_board(self) -> None:\n for row in self.raw_data:\n if row != \"\":\n for row_values in i.split(\" \"):\n self.rows.append(Row().create_row(values=row_values))\n\nclass Game:\n def __init__(self, input_file: str, width: int = 5, height: int = 5) -> None:\n self.input_file = open(input_file, \"r\")\n self.data: list = [x.strip(\" \\n\\r\\t\") for x in self.input_file.readlines() if x.strip(\" \\n\\r\\t\") != \"\"]\n self.calls: list = [int(x) for x in self.data[0].split(\",\")]\n self.winner: bool = False\n self.width: int = width\n self.height: int = height\n self.boards: list[Board] = []\n \n def create_boards(self) -> None:\n _rows = []\n count = 0\n while count < self.height:\n for i in self.data[1:]:\n _rows.append(i.split(\" \"))\n count += 1\n ",
"10,80,6,69,22,99,63,92,30,67,28,93,0,50,65,87,38,7,91,60,57,40,84,51,27,12,44,88,64,35,39,74,61,55,31,48,81,89,62,37,94,43,29,14,95,8,78,49,90,97,66,70,25,68,75,45,42,23,9,96,56,72,59,32,85,3,71,79,18,24,33,19,15,20,82,26,21,13,4,98,83,34,86,5,2,73,17,54,1,77,52,58,76,36,16,46,41,47,11,53\n\n3 82 18 50 90\n16 37 52 67 28\n30 54 80 11 10\n60 79 7 65 58\n76 83 38 51 1\n\n83 63 60 88 98\n70 87 5 99 14\n85 3 11 16 33\n72 69 97 36 49\n26 17 58 13 2\n\n30 80 64 53 69\n36 0 32 46 70\n13 31 22 95 15\n12 35 5 84 21\n39 60 68 83 47\n\n77 93 26 62 88\n87 76 80 10 63\n32 7 28 82 44\n43 30 31 16 74\n33 86 42 45 47\n\n95 86 93 45 67\n20 58 63 35 97\n84 79 10 54 49\n48 66 75 23 61\n5 30 6 56 71\n\n75 8 85 12 98\n37 51 91 24 23\n50 54 81 53 33\n72 57 52 25 6\n56 40 95 87 22\n\n52 19 53 9 32\n23 99 48 26 73\n10 8 54 20 79\n49 45 34 74 90\n27 72 30 13 57\n\n1 60 72 85 64\n62 39 56 93 78\n90 17 87 48 7\n9 13 45 23 69\n44 80 86 55 21\n\n86 57 25 98 18\n42 75 38 9 66\n54 19 99 87 49\n33 32 53 8 6\n17 68 24 58 95\n\n2 5 80 10 61\n27 16 40 67 78\n66 13 24 42 75\n25 7 35 11 85\n93 38 4 31 77\n\n52 81 68 88 95\n82 50 46 87 20\n3 54 59 75 51\n92 93 38 72 4\n8 77 61 31 56\n\n45 16 8 44 62\n92 23 42 20 74\n73 83 65 9 84\n55 13 21 70 59\n34 2 98 47 37\n\n3 54 85 79 76\n42 29 45 12 46\n60 59 24 67 80\n89 15 99 68 48\n40 7 95 44 70\n\n75 31 99 16 32\n80 56 43 30 36\n66 73 35 20 61\n67 28 89 23 54\n47 26 69 70 50\n\n35 91 81 13 15\n73 1 37 68 28\n98 29 9 22 56\n12 59 82 67 31\n77 47 32 79 52\n\n22 73 39 14 46\n99 0 27 34 40\n4 5 38 23 18\n64 26 89 59 79\n71 76 53 49 62\n\n14 37 27 67 94\n76 16 79 61 83\n8 43 36 28 75\n10 4 24 56 44\n26 1 88 9 86\n\n14 78 43 10 30\n56 29 1 61 9\n7 95 39 35 25\n33 87 71 97 21\n72 0 4 2 24\n\n88 0 72 42 6\n53 79 58 80 20\n57 84 15 21 64\n98 17 43 8 95\n2 22 59 63 78\n\n78 21 33 57 72\n10 69 85 73 16\n92 60 87 39 63\n40 15 77 80 56\n6 62 99 50 3\n\n38 72 34 41 74\n90 29 9 6 91\n94 39 56 71 67\n53 21 22 32 10\n73 48 79 47 85\n\n5 49 73 24 8\n75 12 11 47 69\n66 70 89 62 48\n99 3 29 88 30\n10 40 32 33 43\n\n61 93 2 58 84\n47 62 51 16 82\n80 22 50 31 65\n76 85 83 4 40\n86 59 68 14 69\n\n52 5 74 9 72\n84 69 38 1 27\n78 90 46 97 95\n57 21 32 93 29\n11 66 20 51 48\n\n2 3 58 18 53\n11 96 63 33 13\n55 47 30 9 46\n98 85 79 19 65\n87 94 77 27 75\n\n54 97 46 33 90\n99 93 22 0 51\n83 53 34 29 38\n35 65 80 82 9\n56 30 19 49 15\n\n43 40 51 67 37\n4 30 85 24 21\n83 94 69 91 99\n13 32 82 86 12\n66 9 60 65 97\n\n71 96 55 92 6\n83 8 63 56 18\n4 0 74 70 34\n15 87 44 80 29\n68 33 99 14 47\n\n76 86 46 6 8\n90 80 77 30 62\n97 66 55 59 36\n1 43 27 15 57\n54 70 38 21 89\n\n75 96 97 54 29\n62 43 69 57 88\n36 46 73 84 28\n18 98 38 63 4\n59 35 99 90 58\n\n66 29 60 25 95\n91 4 87 76 41\n26 19 45 96 74\n7 82 3 81 31\n17 64 51 93 71\n\n41 51 14 70 26\n35 38 50 25 13\n95 60 88 36 24\n66 94 62 97 83\n21 10 37 1 96\n\n38 90 81 96 14\n40 82 71 18 83\n78 17 65 46 84\n7 92 63 79 49\n55 21 89 95 72\n\n60 35 26 67 42\n59 77 15 6 75\n18 16 21 55 4\n98 49 38 43 30\n0 85 69 96 19\n\n93 22 87 66 94\n7 43 98 18 57\n29 20 91 60 21\n28 51 17 10 14\n96 12 15 25 37\n\n12 69 27 41 36\n58 11 42 44 9\n8 56 33 7 30\n70 64 78 17 61\n22 28 94 0 99\n\n16 64 88 22 48\n65 42 23 7 26\n97 12 63 57 45\n29 94 91 21 54\n95 43 0 85 46\n\n9 50 54 98 35\n45 37 84 87 5\n40 23 14 17 18\n73 43 86 41 59\n69 77 78 15 60\n\n79 9 45 59 85\n38 56 64 95 60\n39 22 14 57 66\n98 53 83 76 16\n62 94 72 54 82\n\n77 44 6 66 46\n9 89 11 84 63\n81 94 87 83 21\n22 90 1 93 92\n24 65 34 45 99\n\n36 93 59 5 43\n76 49 51 0 68\n71 34 55 7 73\n14 10 45 63 95\n30 94 79 67 11\n\n93 98 82 96 91\n3 79 55 70 24\n68 56 87 12 76\n19 31 67 1 54\n49 62 23 15 10\n\n10 74 98 15 6\n14 31 66 38 86\n68 84 60 80 26\n34 72 87 92 61\n81 56 73 12 53\n\n11 69 4 6 23\n38 47 16 99 96\n7 13 40 41 78\n12 5 1 18 88\n20 42 10 82 73\n\n66 97 72 55 99\n26 59 6 79 53\n74 80 98 28 69\n25 95 17 29 34\n85 64 84 90 42\n\n95 50 58 51 66\n48 27 81 94 0\n35 82 57 71 16\n32 93 70 40 25\n31 73 46 12 90\n\n39 94 52 9 88\n3 23 59 77 29\n2 40 93 85 38\n74 97 12 50 1\n22 36 68 65 37\n\n70 15 44 90 55\n42 20 82 0 78\n10 49 62 3 22\n91 73 84 40 28\n72 13 11 60 19\n\n58 95 66 36 22\n91 99 77 94 44\n70 14 85 13 52\n49 6 2 50 35\n47 42 15 98 63\n\n35 1 99 21 68\n93 32 30 76 5\n79 96 10 85 16\n19 69 81 78 70\n66 36 26 94 39\n\n78 51 55 4 97\n21 36 53 1 26\n77 42 20 12 65\n17 52 6 40 16\n19 85 2 24 23\n\n95 68 76 14 30\n19 11 64 99 60\n63 55 8 40 65\n41 75 62 53 83\n26 34 46 72 79\n\n68 6 35 62 77\n43 14 88 7 11\n40 45 98 86 64\n3 53 56 87 30\n28 37 48 10 72\n\n13 69 72 93 17\n1 46 8 56 37\n78 27 49 64 59\n81 99 33 76 79\n84 98 51 82 31\n\n57 41 45 15 10\n65 72 79 17 29\n67 0 33 32 69\n56 96 92 46 53\n88 3 18 87 51\n\n97 52 58 67 17\n51 69 43 20 63\n1 26 27 47 99\n53 23 14 90 86\n4 56 13 36 11\n\n88 11 57 73 89\n43 34 91 15 58\n9 39 18 12 14\n1 98 29 77 52\n84 97 96 68 10\n\n99 5 69 53 45\n10 43 24 60 55\n64 57 30 3 0\n22 65 68 32 83\n52 38 74 97 20\n\n27 25 33 41 67\n54 42 3 1 55\n66 92 44 98 35\n14 82 5 10 39\n52 79 69 76 48\n\n64 58 60 91 42\n45 55 35 9 72\n36 74 99 33 26\n67 4 25 50 14\n15 2 96 82 11\n\n34 84 90 95 26\n8 66 52 43 63\n79 98 36 85 41\n47 24 33 88 71\n86 91 83 40 18\n\n79 68 49 64 35\n23 57 27 77 71\n95 39 43 19 98\n78 62 65 58 60\n52 73 82 4 32\n\n22 54 57 45 3\n43 85 30 60 94\n35 46 28 55 6\n82 42 13 83 59\n76 70 41 61 1\n\n76 89 34 96 1\n95 60 55 23 88\n37 13 61 92 62\n98 77 32 82 31\n33 74 71 58 86\n\n73 91 92 49 44\n53 6 29 8 95\n4 31 54 20 97\n98 57 2 65 75\n43 88 1 58 0\n\n49 91 70 1 79\n17 90 33 65 54\n56 47 63 83 52\n8 45 72 84 39\n43 37 71 97 59\n\n90 93 20 31 96\n98 84 2 87 73\n97 16 19 24 38\n14 11 94 92 36\n4 10 27 44 30\n\n20 77 81 80 28\n35 51 93 24 62\n54 56 41 68 79\n29 67 89 60 12\n63 91 18 90 99\n\n28 48 94 50 73\n20 27 34 59 43\n66 55 35 98 57\n40 53 21 99 4\n17 74 80 5 12\n\n76 22 6 61 23\n70 67 69 33 9\n87 2 12 68 27\n13 52 82 15 84\n24 51 89 53 38\n\n96 23 91 97 10\n50 8 68 67 0\n65 3 92 4 70\n53 77 59 86 66\n41 78 44 52 71\n\n62 19 17 63 75\n43 88 15 84 13\n41 7 47 16 23\n12 71 8 83 50\n36 31 22 5 79\n\n71 95 17 90 63\n64 52 32 3 93\n70 13 99 40 5\n22 18 83 11 55\n47 59 78 45 29\n\n9 98 73 46 79\n5 51 84 26 40\n64 62 0 66 18\n33 83 47 1 63\n89 31 99 54 36\n\n98 15 86 9 50\n67 7 75 85 17\n96 27 64 81 19\n80 30 29 54 52\n49 25 36 5 90\n\n39 29 40 16 69\n38 55 67 71 59\n42 72 51 10 45\n94 75 21 27 0\n84 6 22 33 30\n\n33 64 82 97 39\n79 7 62 49 99\n26 3 13 66 10\n37 98 15 80 47\n1 35 30 50 43\n\n56 92 41 82 34\n68 79 11 0 65\n70 84 26 76 96\n1 72 31 80 8\n9 38 98 17 7\n\n12 19 6 29 89\n96 87 70 75 77\n84 74 64 54 13\n16 68 44 79 43\n61 47 69 26 50\n\n43 20 45 21 87\n80 50 83 26 49\n64 99 71 75 9\n18 96 6 94 88\n76 97 51 11 74\n\n85 47 25 72 93\n96 36 81 55 27\n63 18 57 1 29\n9 35 83 88 98\n90 21 3 67 82\n\n58 94 55 10 98\n2 24 71 93 57\n74 34 21 35 73\n89 88 6 16 8\n76 81 38 28 83\n\n36 53 63 67 18\n51 74 60 69 85\n32 22 80 58 98\n34 92 13 12 26\n46 61 31 96 47\n\n90 1 5 10 48\n12 76 95 83 17\n24 84 65 44 28\n81 80 41 79 15\n29 61 75 94 40\n\n65 22 40 75 86\n93 77 46 35 87\n88 5 91 48 74\n92 28 66 47 30\n69 2 29 67 94\n\n78 38 1 53 68\n84 70 26 7 72\n92 87 55 47 6\n51 82 36 73 28\n75 58 35 49 56\n\n61 85 60 19 24\n16 23 71 74 33\n42 7 57 82 70\n14 97 59 99 49\n46 30 89 79 41\n\n5 24 92 19 65\n0 80 33 78 23\n4 37 31 16 41\n79 73 88 36 67\n86 29 62 61 71\n\n40 51 27 57 85\n53 68 31 60 83\n48 69 24 17 96\n54 89 22 77 64\n95 26 21 65 41\n\n48 7 20 68 21\n31 22 1 99 96\n82 63 78 2 70\n18 83 58 92 51\n81 64 98 44 89\n\n23 74 99 75 6\n81 14 37 8 85\n12 36 55 20 47\n88 7 90 87 43\n3 44 83 15 2\n\n97 15 69 76 95\n13 44 31 10 14\n40 83 49 11 65\n43 98 55 92 89\n90 33 73 32 53\n\n25 79 77 83 68\n5 10 23 15 19\n18 4 92 51 76\n17 90 70 49 39\n74 63 75 42 67\n\n46 66 18 17 28\n75 76 78 72 44\n57 39 97 27 99\n36 58 62 90 82\n14 45 48 64 1\n\n51 90 58 6 37\n28 30 57 54 10\n45 80 39 4 0\n29 17 66 18 55\n96 44 36 76 34\n\n94 50 0 71 99\n11 67 96 87 64\n48 30 31 68 40\n89 55 23 92 42\n16 62 37 83 33\n\n66 42 91 70 72\n28 69 96 17 71\n99 5 2 26 19\n60 87 51 83 76\n77 33 64 61 54\n\n61 93 90 82 88\n80 11 25 40 28\n60 29 34 39 21\n24 13 72 77 2\n19 95 47 17 0\n\n86 97 50 42 87\n7 18 80 23 30\n41 6 96 92 98\n36 45 77 71 38\n19 40 47 39 53\n\n83 7 80 86 65\n37 22 19 84 92\n29 17 76 4 33\n97 50 1 12 21\n15 58 39 38 74\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ecd05a768e3d546faeb63ecb6deea2c2455eb9dc | 2,774 | ipynb | Jupyter Notebook | implementations/pix2pix/pix2pix.ipynb | derwind/PyTorch-GAN | b08d6b0eb081fcf43bc044f5f0c1f9164ad7de66 | [
"MIT"
] | null | null | null | implementations/pix2pix/pix2pix.ipynb | derwind/PyTorch-GAN | b08d6b0eb081fcf43bc044f5f0c1f9164ad7de66 | [
"MIT"
] | null | null | null | implementations/pix2pix/pix2pix.ipynb | derwind/PyTorch-GAN | b08d6b0eb081fcf43bc044f5f0c1f9164ad7de66 | [
"MIT"
] | null | null | null | 21.015152 | 244 | 0.526316 | [
[
[
"<a href=\"https://colab.research.google.com/github/derwind/PyTorch-GAN/blob/study/implementations/pix2pix/pix2pix.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Install",
"_____no_output_____"
]
],
[
[
"!git clone https://github.com/derwind/PyTorch-GAN.git",
"_____no_output_____"
],
[
"import os\nos.chdir(\"PyTorch-GAN\")",
"_____no_output_____"
],
[
"!pip install -r requirements.txt",
"_____no_output_____"
]
],
[
[
"# Training",
"_____no_output_____"
]
],
[
[
"os.chdir(\"implementations/pix2pix\")",
"_____no_output_____"
],
[
"os.makedirs(\"../../data/facades\", exist_ok=True)\n!curl http://efrosgans.eecs.berkeley.edu/pix2pix/datasets/facades.tar.gz -o ../../data/facades.tar.gz\n!tar xf ../../data/facades.tar.gz -C ../../data/\n!rm ../../data/facades.tar.gz\n",
"_____no_output_____"
],
[
"!python pix2pix.py",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
ecd05c604f149606a15a96fb331ef28ca5f19167 | 78,896 | ipynb | Jupyter Notebook | notebooks/Interesting solutions.ipynb | H00N24/IV127-Adaptive-Learning-Seminar | 30a4abe3339ba225e1bfd039f44d6d064c1da01c | [
"BSD-3-Clause"
] | null | null | null | notebooks/Interesting solutions.ipynb | H00N24/IV127-Adaptive-Learning-Seminar | 30a4abe3339ba225e1bfd039f44d6d064c1da01c | [
"BSD-3-Clause"
] | 2 | 2020-03-31T11:29:37.000Z | 2020-04-05T09:34:13.000Z | notebooks/Interesting solutions.ipynb | H00N24/IV127-Adaptive-Learning-Seminar | 30a4abe3339ba225e1bfd039f44d6d064c1da01c | [
"BSD-3-Clause"
] | null | null | null | 36.525926 | 1,113 | 0.328699 | [
[
[
"%load_ext nb_black",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import IsolationForest",
"_____no_output_____"
],
[
"code_frame = pd.read_csv(\"../data/code_frame.csv\", header=0)\nsolutions_frame = pd.read_csv(\"../data/solutions_frame.csv\", header=0)",
"_____no_output_____"
],
[
"interesting = [\n (73, 74, \"Vnořené čtverce\"),\n (72, 73, \"Velká šachovnice\"),\n (70, 71, \"Sudoku řádek\"),\n (68, 69, \"Rozklad na prvočísla\"),\n (65, 66, \"Kámen, nůžky, papír\"),\n (56, 57, \"Sudá čísla\"),\n (55, 56, \"Čísla pozpátku\"),\n (52, 53, \"Prostřední z trojice\"),\n (42, 43, \"Lichá a sudá\"),\n (38, 39, \"Ohrožení dámou\"),\n (29, 30, \"Nejčastější prvek\"),\n (28, 29, \"Unikátní prvky\"),\n (27, 28, \"Zipování řetězců\"),\n (22, 23, \"Největší společný dělitel\"),\n]\n\ninteresting_id = {i[0] for i in interesting}\n",
"_____no_output_____"
],
[
"for solution_row in solutions_frame.itertuples():\n if solution_row[0] not in interesting_id:\n continue\n selected_frame = code_frame[code_frame[\"item\"] == solution_row[1]]\n if selected_frame.shape[0] == 0:\n continue\n\n id_cols = [\n \"id\",\n \"item\",\n \"correct\",\n \"dec_answer\",\n \"ast_clean\",\n ]\n\n data_cols = [\n x\n for x in selected_frame.columns\n if x not in id_cols and np.any(selected_frame[x] != 0)\n ]\n\n isoforest = IsolationForest()\n predicted = isoforest.fit_predict(selected_frame[data_cols])\n\n scores = isoforest.score_samples(selected_frame[data_cols])\n\n print(solution_row[2])\n print(solution_row[3])\n print(\"-\" * 20)\n\n for _, id, correct, solution in selected_frame.iloc[np.argsort(scores)[:5]][\n [\"id\", \"correct\", \"dec_answer\"]\n ].itertuples():\n print(id, correct, solution)\n print()",
"Největší společný dělitel\ndef greatest_common_divisor(a, b):\n while a:\n (a, b) = ((b % a), a)\n return b\n\n--------------------\n26824 1 def greatest_common_divisor(a, b):\n x = list()\n y = list()\n for i in range(1, (a + 1)):\n if (a % i) == 0:\n x.append(i)\n for j in range(1, (b + 1)):\n if (b % j) == 0:\n y.append(j)\n x.sort(reverse=True)\n y.sort(reverse=True)\n index1 = len(x)\n index2 = len(y)\n for i in range(0, index1):\n for j in range(0, index2):\n if ((x[i] % y[j]) == 0) and ((y[j] % x[i]) == 0):\n return x[i]\n\n\n61983 1 def greatest_common_divisor(a, b):\n x = 1\n while (a != 1) or (b != 1):\n if ((a % 2) == 0) and ((b % 2) == 0):\n x = x * 2\n a = a / 2\n b = b / 2\n elif ((a % 3) == 0) and ((b % 3) == 0):\n x = x * 3\n a = a / 3\n b = b / 3\n elif ((a % 5) == 0) and ((b % 5) == 0):\n x = x * 5\n a = a / 5\n b = b / 5\n elif ((a % 7) == 0) and ((b % 7) == 0):\n x = x * 7\n a = a / 7\n b = b / 7\n elif a == b:\n x = x * a\n a = a / a\n b = b / b\n elif (a % 2) == 0:\n a = a / 2\n elif (a % 3) == 0:\n a = a / 3\n elif (a % 5) == 0:\n a = a / 5\n elif (a % 7) == 0:\n a = a / 7\n elif (b % 2) == 0:\n b = b / 2\n elif (b % 3) == 0:\n b = b / 3\n elif (b % 5) == 0:\n b = b / 5\n elif (b % 7) == 0:\n b = b / 7\n else:\n a = a / a\n b = b / b\n return x\n\n\n42940 0 def greatest_common_divisor(a, b):\n delitele_a = []\n delitele_b = []\n for i in range(1, (a + 1)):\n if (a % i) == 0:\n delitele_a.append(i)\n for i in range(1, (b + 1)):\n if (b % i) == 0:\n delitele_b.append(i)\n if len(delitele_a) > len(delitele_b):\n for i in range((len(delitele_b) - 1), (-1), (-1)):\n if delitele_b[i] == delitele_a[i]:\n return delitele_b[i]\n else:\n for i in range((len(delitele_a) - 1), (-1), (-1)):\n if delitele_b[i] == delitele_a[i]:\n return delitele_b[i]\n\n\n59290 0 def greatest_common_divisor(a, b):\n pom = a * b\n if (a % b) == 0:\n print(b)\n elif (b % a) == 0:\n print(a)\n else:\n while True:\n pom -= 1\n if ((a % pom) == 0) and ((b % pom) == 0):\n break\n return pom\n\n\n58269 1 def greatest_common_divisor(a, b):\n divisors_a = []\n divisors_b = []\n for i in range(1, (a + 1)):\n if (a % i) == 0:\n divisors_a.append(i)\n for j in range(1, (b + 1)):\n if (b % j) == 0:\n divisors_b.append(j)\n divisors_c = list(set(divisors_a).intersection(divisors_b))\n return max(divisors_c)\n\n\nZipování řetězců\ndef string_zip(text1, text2):\n result = \"\"\n for i in range(max(len(text1), len(text2))):\n if i < len(text1):\n result += text1[i]\n if i < len(text2):\n result += text2[i]\n return result\n\n--------------------\n19820 1 def string_zip(text1, text2):\n (one, two) = (True, True)\n i = 0\n new = \"\"\n while one or two:\n if one:\n new += text1[i]\n if len(text1) == (i + 1):\n one = False\n if two:\n new += text2[i]\n if len(text2) == (i + 1):\n two = False\n i += 1\n return new\n\n\n51533 1 def string_zip(text1, text2):\n vystup = \"\"\n x = max(len(text1), len(text2))\n for i in range(x):\n try:\n vystup += text1[i]\n except:\n pass\n try:\n vystup += text2[i]\n except:\n pass\n return vystup\n\n\n53310 1 def string_zip(t1, t2):\n max_l = len(t1) if (len(t1) > len(t2)) else len(t2)\n out = \"\"\n for i in range(max_l):\n try:\n out += t1[i]\n except:\n pass\n try:\n out += t2[i]\n except:\n pass\n return out\n return \"\"\n\n\n55010 1 def string_zip(text1, text2):\n lenght_1 = len(text1)\n lenght_2 = len(text2)\n marging_lenght = min(lenght_1, lenght_2)\n new_string = \" \"\n longer_string = \" \"\n if lenght_1 > lenght_2:\n longer_string = longer_string + text1\n if lenght_2 > lenght_1:\n longer_string = longer_string + text2\n for i in range(0, marging_lenght):\n new_string = (new_string + text1[i]) + text2[i]\n if longer_string != \" \":\n for e in range((marging_lenght + 1), len(longer_string)):\n new_string = new_string + longer_string[e]\n return new_string\n\n\n20039 0 def string_zip(text1, text2):\n alist = \"\"\n for i in range(len(text1)):\n alist += str(text1[i])\n alist += str(text2[i])\n return alist\n\n\nUnikátní prvky\ndef unique(mylist):\n result = []\n for i in range(len(mylist)):\n if mylist[i] not in result:\n result.append(mylist[i])\n return result\n\n--------------------\n58682 0 def main(sez):\n pom = []\n for n in range(len(sez)):\n for i in range(len(sez)):\n if (sez[i] == sez[n]) and (i != n):\n if sez[i] in pom:\n pass\n else:\n pom.append(sez[i])\n for i in pom:\n sez.remove(i)\n return sez\n\n\ndef unique(sez):\n pom = []\n n = 0\n while True:\n pom.append(sez)\n sez = main(sez)\n if (n > 0) and (pom[n] == pom[(n - 1)]):\n break\n n += 1\n return sorted(sez)\n\n\n60234 1 def unique(mylist):\n len_mylist = len(mylist)\n i = 0\n while i < (len_mylist - 1):\n j = i + 1\n while j < len_mylist:\n if mylist[j] == mylist[i]:\n mylist.pop(j)\n len_mylist = len(mylist)\n j += 0\n else:\n len_mylist = len(mylist)\n j += 1\n len_mylist = len(mylist)\n i += 1\n return mylist\n\n\n58681 0 def main(sez):\n pom = []\n for n in range(len(sez)):\n for i in range(len(sez)):\n if (sez[i] == sez[n]) and (i != n):\n if sez[i] in pom:\n pass\n else:\n pom.append(sez[i])\n for i in pom:\n sez.remove(i)\n return sez\n\n\ndef unique(sez):\n pom = []\n n = 0\n while True:\n pom.append(sez)\n sez = main(sez)\n if (n > 0) and (pom[n] == pom[(n - 1)]):\n break\n n += 1\n return sez\n\n\n58683 0 def main(sez):\n pom = []\n for n in range(len(sez)):\n for i in range(len(sez)):\n if (sez[i] == sez[n]) and (i != n):\n if sez[i] in pom:\n pass\n else:\n pom.append(sez[i])\n for i in pom:\n sez.remove(i)\n return sez\n\n\ndef unique(sez):\n pom = []\n n = 0\n while True:\n pom.append(sez)\n sez = main(sez)\n if (n > 0) and (pom[n] == pom[(n - 1)]):\n break\n n += 1\n return sez\n\n\n13649 1 def unique(mylist):\n whitelist = []\n for i in mylist:\n if contains(whitelist, i) == False:\n whitelist.append(i)\n return whitelist\n\n\ndef contains(summary, element):\n result = False\n for x in summary:\n if x != element:\n result = False\n else:\n return True\n return result\n\n\nNejčastější prvek\ndef most_common(mylist):\n mylist = sorted(mylist)\n (max_value, max_count) = (None, 0)\n (current_value, current_count) = (None, 0)\n for value in mylist:\n if value == current_value:\n current_count += 1\n else:\n current_value = value\n current_count = 1\n if current_count > max_count:\n max_value = current_value\n max_count = current_count\n return max_value\n\n--------------------\n61521 1 def most_common(mylist):\n return count_seen_rec(mylist, 0, 0, {}, 0)\n\n\ndef count_seen_rec(mylist, most_freq, m_f_count, dic, i):\n if i < len(mylist):\n if mylist[i] not in dic:\n dic[mylist[i]] = 1\n else:\n dic[mylist[i]] += 1\n if i < len(mylist):\n if dic[mylist[i]] > m_f_count:\n return count_seen_rec(mylist, mylist[i], dic[mylist[i]], dic, (i + 1))\n elif dic[mylist[i]] == m_f_count:\n return count_seen_rec(\n mylist, min(mylist[i], most_freq), dic[mylist[i]], dic, (i + 1)\n )\n return count_seen_rec(mylist, most_freq, m_f_count, dic, (i + 1))\n return most_freq\n\n\n61520 0 def most_common(mylist):\n return count_seen_rec(mylist, 0, 0, {}, 0)\n\n\ndef count_seen_rec(mylist, most_freq, m_f_count, dic, i):\n if i < len(mylist):\n if mylist[i] not in dic:\n dic[mylist[i]] = 1\n else:\n dic[mylist[i]] += 1\n if dic[mylist[i]] > m_f_count:\n return count_seen_rec(mylist, mylist[i], dic[mylist[i]], dic, (i + 1))\n elif dic[mylist[i]] == m_f_count:\n return count_seen_rec(\n mylist, min(mylist[i], most_freq), dic[mylist[i]], dic, (i + 1)\n )\n return most_freq\n\n\n41526 1 def most_common(mylist):\n numbers = list()\n counts = list()\n for number in mylist:\n if number in numbers:\n i = numbers.index(number)\n counts[i] += 1\n else:\n numbers.append(number)\n counts.append(1)\n most_index = 0\n most = 0\n for i in range(len(counts)):\n if counts[i] > most:\n most_index = i\n most = counts[i]\n most_numbers = list()\n for k in range(len(counts)):\n if counts[k] == most:\n most_numbers.append(numbers[k])\n smallest_number = 0\n for j in range(len(most_numbers)):\n if j == 0:\n smallest_number = most_numbers[j]\n elif smallest_number > most_numbers[j]:\n smallest_number = most_numbers[j]\n return smallest_number\n\n\n20680 1 def most_common(mylist):\n nums = {}\n for num in mylist:\n if num in nums:\n curr_value = nums.pop(num)\n new_value = int(curr_value) + 1\n nums[num] = new_value\n else:\n nums[num] = 1\n new_nums = sorted(nums, key=(lambda x: nums[x]), reverse=True)\n max_num = new_nums[0]\n for i in range(len(new_nums)):\n if nums[max_num] == nums[new_nums[i]]:\n if new_nums[i] < max_num:\n max_num = new_nums[i]\n return max_num\n\n\n58725 0 def most_common(mylist):\n dict = {}\n better = sorted(mylist)\n for number in better:\n if number not in dict:\n dict[number] = 1\n else:\n dict[number] += 1\n sth = sorted(dict.items(), key=(lambda x: x[0]), reverse=False)\n result = sorted(sth, key=(lambda x: x[1]), reverse=True)\n\n\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
ecd08f57c3b8cd5704330c719d62cc3f3eca57f0 | 11,876 | ipynb | Jupyter Notebook | 7_calculabilite/3_pb_de_l_arret.ipynb | efloti/cours-nsi-terminale | 091df5518c25b50ef523a803ac747c63be76f670 | [
"CC0-1.0"
] | null | null | null | 7_calculabilite/3_pb_de_l_arret.ipynb | efloti/cours-nsi-terminale | 091df5518c25b50ef523a803ac747c63be76f670 | [
"CC0-1.0"
] | null | null | null | 7_calculabilite/3_pb_de_l_arret.ipynb | efloti/cours-nsi-terminale | 091df5518c25b50ef523a803ac747c63be76f670 | [
"CC0-1.0"
] | null | null | null | 40.257627 | 604 | 0.615106 | [
[
[
"# Machine de Turing Universelle et problème de l'arrêt",
"_____no_output_____"
],
[
"## Machines de Turing Universelles (UTM)",
"_____no_output_____"
],
[
"À force de «jouer» avec ces machines abstraites, Alan Turing s'est demandé s'il pouvait «construire» (mathématiquement!) une machine («de Turing») $U$ qui:\n- reçevrait en entrée (sur son ruban):\n - une description d'une *machine* de Turing $T$ notée $d_T$,\n - une donnée $d$ pour celle-ci.\n- et qui produirait comme résultat sur son ruban ... celui que **produirait** la machine $T$ agissant sur l'entrée $d$.",
"_____no_output_____"
],
[
"Bref, une machine capable de **simuler** n'importe quelle autre machine travaillant sur son entrée; on appelle cela une **machine de Turing Universelle (UTM)**.",
"_____no_output_____"
],
[
"$$\\begin{eqnarray}{\\bf UTM}: (\\text{description d'une machine }T, \\text{donnée }d) &\\longmapsto& \\text{résultat de }T \\text{ appliqué à «donnée»}\\cr (d_T, d)&\\longmapsto& T d\\end{eqnarray}$$",
"_____no_output_____"
],
[
"Bien évidemment, il est parvenu à «construire» de telles machines et cela ne devrait pas trop vous surprendre ... ",
"_____no_output_____"
],
[
"... puisque nous avons précisément fait cela avec Python!(simulateur) - mais souvenez-vous que l'ordinateur n'existait pas encore à l'époque (environ 1936).",
"_____no_output_____"
],
[
"*Notes*: pour les septiques qui se disent qu'il y a «anguille sous roche» ou «affabulation de penseurs perdus dans je ne sais quel cosmos»:\n1. Votre ordinateur et Python ne savent pas calculer plus de choses qu'une machine de Turing, or il nous ont permis de construire une UTM...,\n2. Lorsque vous vous évertuez à comprendre les machines de Turing, vous êtes *vous-même* une sorte d'UTM...\n3. Si vous souhaitez comprendre comment Turing s'y est prit - c'est merveilleux et ce n'est pas pour rien que le prix ultime en informatique s'appelle le *prix Turing* - je ne peux que vous conseiller de lire:\n > «**Leçons Sur l'Informatique** de *Richard Feynman* (prix Nobel de ... physique): *leçon 3 - la théorie du calcul informatique*» (je peux vous le prêter).",
"_____no_output_____"
],
[
"## Le problème de l'arrêt (*the halting problem*)",
"_____no_output_____"
],
[
"Fort de ses machines universelles, Turing s'est demandé s'il était possible de construire:\n\n> une machine $A$ capable de «calculer» si une autre machine $T$ appliquée à une donnée $d$ **terminerait** (plutôt que d'entrer dans une boucle infinie)",
"_____no_output_____"
],
[
"Il arriva à la conclusion que ce problème de «décision» n'est **pas calculable**; autrement dit qu'une telle machine *ne peut pas exister*.",
"_____no_output_____"
],
[
"**Problème de décision**: problème pour lequel le résultat est simplement «oui» ou «non»; *exemple*: «$n$ (entier) est-il pair?» (est calculable); «la machine $T$ appliquée à la donnée $d$ terminera-t-elle?» (incalculable).",
"_____no_output_____"
],
[
"Pour parvenir à ce résultat, il utilise un **raisonnement par l'absurde**: \n\n> On appelle ainsi un raisonnement où on part d'une certaine hypothèse $\\color{red}{H}$ (donc considérée comme Vraie) et où l'exploitation de cette hypothèse en conjonction avec d'autres «théorèmes» (résultats déjà démontrés) $T_1$, $T_2$, ... etc. aboutit à une **aporie** ou **contradiction** ou **impossibilité**.\n\n$$\\color{red}{H}, T_1, T_2, \\dots \\implies\\cdots\\implies \\text{«impossibilité»}$$",
"_____no_output_____"
],
[
"La **conclusion logique** (puisque $T_1, T_2,\\dots$ sont vrais car démontrés) dans une telle situation est que:\n\n> l'hypothèse faite au départ $\\color{red}{H}$ est **Fausse**.",
"_____no_output_____"
],
[
"#### Exemple classique de raisonnement par l'absurde",
"_____no_output_____"
],
[
"Exemple célèbre (5e siècle avant JC): \n\n> «*$\\sqrt{2}$ est rationnel i.e on peut l'écrire $\\dfrac{p}{q}$ avec $p$ et $q$ entiers*» est FAUX. \n\nMontrons que c'est **faux** par l'absurde; *supposons* que ce soit vrai c'est-à-dire qu'on a l'égalité:\n\n$$\\sqrt{2}=\\dfrac{p}{q}\\quad (\\color{red}{H}) \\iff 2 =\\dfrac{p^2}{q^2} \\iff p^2=2q^2\\quad (*)$$",
"_____no_output_____"
],
[
"$T_1$: *Toute fraction d'entiers peut être rendue irréductible*. \n\nOn peut donc supposer que $\\dfrac{p}{q}$ a déjà été réduites et qu'elle est donc *irréductible*: *$p$ et $q$ n'ont aucun diviseurs communs*.",
"_____no_output_____"
],
[
"$T_2$: pour $x$ entier: «$x^2$ pair ssi $x$ pair».",
"_____no_output_____"
],
[
"L'égalité $(*)$ montre que $p^2$ est pair (c'est un multiple de $2$) et donc $p$ aussi ($T_2$); mais alors $p=2p'$ et donc:\n\n$$(*)\\quad p^2=2q^2 \\iff (2p')^2=2q^2 \\iff 4p'^2=2q^2 \\iff 2p'^2=q^2$$\n\nDonc $q$ est pair aussi... STOP: c'est impossible (absurde)! ... puisque $p$ et $q$ seraient tous deux divisibles par $2$ or ils n'avaient aucun diviseurs communs.",
"_____no_output_____"
],
[
"#### Retour au raisonnement de Turing sur l'incalculabilité de l'arrêt.",
"_____no_output_____"
],
[
"$\\color{red}{H}$: Turing suppose **qu'il existe** une machine $A$ (pour arrêt) qui, étant donnés:\n- (la description) d'une machine $T$ et une donnée $d$ \n- calcule si $T$ appliquée à $d$ \n - s'arrête auquel cas elle répond «oui» (ou 1),\n - «boucle à l'infini» auquel cas elle répond «non» (ou 0)",
"_____no_output_____"
],
[
"Turing va alors exhiber un **paradoxe**. Pour cela, il construit une machine $P$ (pour «paradoxe) qui prend en entrée (la description) d'une machine $T$ et une donnée $d$; elle réalise le calcul suivant:\n\n Si la machine A appliquée à la description de T et d répond oui (arrêt):\n je rentre dans une boucle infinie\n Sinon:\n je me met sur mon état final (donc je m'arrête)",
"_____no_output_____"
],
[
"*Note1*: pour la boucle infinie, il suffit d'entrer dans un état où la machine réécrit ce qu'elle lit quoi qu'elle lise et se déplace vers la droite tout en restant dans le même état.",
"_____no_output_____"
],
[
"*Note2*: Vous pouvez vous demander si une telle machine est réalisable mais le raisonnement de Turing qui prouve l'existence d'UTM montre qu'une telle machine est très simple à réaliser à partir d'une UTM. D'ailleurs, on peut facilement l'exprimer en Python:\n\n```python\ndef paradoxe(d_T, d):\n if arret(d_T, d): # on suppose que la fonction arret existe (c'est l'hypothèse)\n while True:\n pass\n else:\n return\n```",
"_____no_output_____"
],
[
"Revenons à nos moutons. $P$ est une machine ... donc on peut lui fournir sa propre description $d_{P}$ comme premier paramètre et aussi comme second paramètre car **la description d'une machine est une donnée comme une autre**...!.",
"_____no_output_____"
],
[
"Que se passe-t-il alors? Il n'y a que deux cas possibles:\n\nSi $P$ s'*arrête*:\n\n> cela signifie que $A$ appliquée à $d_P$, $d_P$ répond «non» ... mais cela veut dire que si on applique $P$ à sa propre description et à celle-ci comme donnée, elle ne s'arrête pas... c'est contradictoire avec l'hypothèse de départ et donc impossible!\n\nSi $P$ ne s'*arrête pas*:\n\n> cela signifie que $A$ appliquée à $d_P$, $d_P$ répond «oui» ... mais cela veut dire que si on applique $P$ à sa propre description et à celle-ci comme donnée, elle s'arrête... encore en contradiction avec l'hypothèse de départ!",
"_____no_output_____"
],
[
"Voilà notre absurdité: dans le cas de figure considéré «$P$ s'arrête si et seulement si $P$ ne s'arrête pas!»",
"_____no_output_____"
],
[
"Nous sommes donc obliger de conclure que $\\color{red}{H}$ est donc *fausse* c'est-à-dire que:\n\n> Il ne peut exister de machine de Turing (de programme) qui, prenant en entrée la description d'une machine de Turing et une donnée, nous dise si oui ou non cette dernière va s'arrêter en traitant cette donnée. ",
"_____no_output_____"
],
[
"Ça doit un peu plâner sous la carafe ... rassurez-vous c'est parfaitement normal ... alors voyez si [cette sympathique petite vidéo vous aide à comprendre le «truc»](https://www.youtube.com/watch?v=92WHN-pAFCs).",
"_____no_output_____"
],
[
"*Note*: Le procédé technique utilisé par Turing est connu en mathématique sous le nom de **«diagonalisation»**, il permet de montrer de nombreuses choses par l'absurde; par exemple:\n- qu'il y a «beaucoup plus» de réels que d'entiers et donc que tous les infinis «ne se valent pas» (l'infini des entiers est dit dénombrable tandis que celui des réels est dit avoir la puissance du continu et $\\infty_{\\mathbb{N}} < \\infty_{\\mathbb{R}}$). Voir par exemple cette vidéo géniale [l'hôtel de Hilbert]( https://www.youtube.com/watch?v=N_cDA6tF-40&list=PLlrxd3f47yy2mvLivlFU1a9ukoG8-Dkvs&index=18). C'est en se servant de ces idées que Turing montre, par exemple, que certains nombres réels sont incalculables: en montrant que ses machines sont en nombre $\\infty_{\\mathbb{N}}$...\n- qu'il ne peut exister d'ensemble contenant tous les ensembles... connu sous le nom de *paradoxe de Russel* (établi en 1901): autrement, on pourrait considérer l'ensemble $P$ de tous les ensembles qui ne se contiennent pas eux-même, il ferait partie de l'ensemble de tous les ensembles (par définition). Mais de deux choses l'une: ou $P$ appartient à lui-même, ou non... et là les problèmes commencent (voir [par ici](https://www.youtube.com/watch?v=xqSKawORrPo&list=PLtzmb84AoqRRgqV5DfE_ykuGQK-vCJ_0t&index=16)).\n- et bien d'autres choses...",
"_____no_output_____"
]
]
] | [
"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"
]
] |
ecd0a7a553ae1a2b2ea1a79294efc9d4642860a8 | 120,155 | ipynb | Jupyter Notebook | models/src/notebooks/Los Angeles Air Quality.ipynb | vbgupta/DS440-Transfer-Learning-Address-Sustainability-Issues | b6ef51fa1e4253e92b8179b1953c43e6b983b944 | [
"MIT"
] | null | null | null | models/src/notebooks/Los Angeles Air Quality.ipynb | vbgupta/DS440-Transfer-Learning-Address-Sustainability-Issues | b6ef51fa1e4253e92b8179b1953c43e6b983b944 | [
"MIT"
] | null | null | null | models/src/notebooks/Los Angeles Air Quality.ipynb | vbgupta/DS440-Transfer-Learning-Address-Sustainability-Issues | b6ef51fa1e4253e92b8179b1953c43e6b983b944 | [
"MIT"
] | 1 | 2022-02-05T19:39:59.000Z | 2022-02-05T19:39:59.000Z | 69.695476 | 31,354 | 0.687837 | [
[
[
"# Import Dependencies\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pathlib\npd.set_option('display.max_columns', None)",
"_____no_output_____"
],
[
"# Get Data\nAir_Qual_combined = pd.read_csv(\"/Users/vbgupta/Desktop/Code/PennState/DS440/DS440-Transfer-Learning-Address-Sustainability-Issues/project/data/AQI/LAAQI.csv\")\nprint(Air_Qual_combined.columns)",
"Index(['Unnamed: 0', 'Header.status', 'Header.request_time', 'Header.url',\n 'Header.rows', 'Data.state_code', 'Data.county_code',\n 'Data.site_number', 'Data.parameter_code', 'Data.poc', 'Data.latitude',\n 'Data.longitude', 'Data.datum', 'Data.parameter', 'Data.date_local',\n 'Data.time_local', 'Data.date_gmt', 'Data.time_gmt',\n 'Data.sample_measurement', 'Data.units_of_measure',\n 'Data.units_of_measure_code', 'Data.sample_duration',\n 'Data.sample_duration_code', 'Data.sample_frequency',\n 'Data.detection_limit', 'Data.uncertainty', 'Data.qualifier',\n 'Data.method_type', 'Data.method', 'Data.method_code', 'Data.state',\n 'Data.county', 'Data.date_of_last_change', 'Data.cbsa_code'],\n dtype='object')\n"
],
[
"# 2019\nAir_Qual_combined_2019 = Air_Qual_combined.loc[Air_Qual_combined['Data.date_gmt'].str.contains('2019')]\nAir_Qual_combined_2019.head()",
"_____no_output_____"
],
[
"print(len(Air_Qual_combined_2019))",
"28511\n"
],
[
"# Columns - County, City, AQI_weekly, AQI_month, AQI_year, AQI_lat, AQI_long, feature_name, Feature_val, Feature_month, feature_lat, feature_long, feature_time\n\nAir_Qual_combined_2019 = Air_Qual_combined_2019[['Data.state', 'Data.county', 'Data.sample_frequency',\n 'Data.longitude', 'Data.latitude', 'Data.date_gmt',\n 'Data.sample_measurement', 'Data.time_local']]\nAir_Qual_combined_2019.head(3)",
"_____no_output_____"
],
[
"# Rename Columns:\n\nAir_Qual_combined_2019 = Air_Qual_combined_2019.rename(columns = {\n 'Data.state': 'State', 'Data.county': 'County', 'Data.sample_frequency': 'Sample Frequency',\n 'Data.longitude': 'AQI_lat', 'Data.latitude': 'AQI_long', 'Data.date_gmt': 'Date',\n 'Data.sample_measurement': 'AQI_Value', 'Data.time_local': 'Time_Local'\n})\nAir_Qual_combined_2019.head(3)",
"_____no_output_____"
],
[
"Air_Qual_combined_2019['Date'] = pd.to_datetime(Air_Qual_combined_2019.Date)",
"_____no_output_____"
],
[
"df_2019 = Air_Qual_combined_2019.groupby(Air_Qual_combined_2019.Date.dt.isocalendar().week)['AQI_Value'].mean().rename_axis('AQI_month').reset_index(name='AQI_weekly')\ndf_2019.head()",
"_____no_output_____"
],
[
"df_2019['AQI_year'] = 2019\ndf_2019.head()",
"_____no_output_____"
],
[
"# 2020\nAir_Qual_combined_2020 = Air_Qual_combined.loc[Air_Qual_combined['Data.date_gmt'].str.contains('2020')]\nAir_Qual_combined_2020 = Air_Qual_combined_2020[['Data.state', 'Data.county', 'Data.sample_frequency',\n 'Data.longitude', 'Data.latitude', 'Data.date_gmt',\n 'Data.sample_measurement', 'Data.time_local']]\nAir_Qual_combined_2020 = Air_Qual_combined_2020.rename(columns = {\n 'Data.state': 'State', 'Data.county': 'County', 'Data.sample_frequency': 'Sample Frequency',\n 'Data.longitude': 'AQI_lat', 'Data.latitude': 'AQI_long', 'Data.date_gmt': 'Date',\n 'Data.sample_measurement': 'AQI_Value', 'Data.time_local': 'Time_Local'\n})\nAir_Qual_combined_2020['Date'] = pd.to_datetime(Air_Qual_combined_2020.Date)\nprint(Air_Qual_combined_2020.head())\ndf_2020 = Air_Qual_combined_2020.groupby(Air_Qual_combined_2020.Date.dt.isocalendar().week)['AQI_Value'].mean().rename_axis('AQI_month').reset_index(name='AQI_weekly')\ndf_2020.head()\nlen(df_2020)\ndf_2020['AQI_year'] = 2020",
" State County Sample Frequency AQI_lat AQI_long \\\n10642 California Los Angeles HOURLY -118.17533 33.79236 \n10643 California Los Angeles HOURLY -118.17533 33.79236 \n10644 California Los Angeles HOURLY -118.17533 33.79236 \n10645 California Los Angeles HOURLY -118.17533 33.79236 \n10646 California Los Angeles HOURLY -118.17533 33.79236 \n\n Date AQI_Value Time_Local \n10642 2020-01-01 1.7 16:00 \n10643 2020-01-01 0.9 17:00 \n10644 2020-01-01 6.1 18:00 \n10645 2020-01-01 40.1 19:00 \n10646 2020-01-01 68.6 20:00 \n"
],
[
"# 2021\nAir_Qual_combined_2021 = Air_Qual_combined.loc[Air_Qual_combined['Data.date_gmt'].str.contains('2021')]\nAir_Qual_combined_2021 = Air_Qual_combined_2021[['Data.state', 'Data.county', 'Data.sample_frequency',\n 'Data.longitude', 'Data.latitude', 'Data.date_gmt',\n 'Data.sample_measurement', 'Data.time_local']]\nAir_Qual_combined_2021 = Air_Qual_combined_2021.rename(columns = {\n 'Data.state': 'State', 'Data.county': 'County', 'Data.sample_frequency': 'Sample Frequency',\n 'Data.longitude': 'AQI_lat', 'Data.latitude': 'AQI_long', 'Data.date_gmt': 'Date',\n 'Data.sample_measurement': 'AQI_Value', 'Data.time_local': 'Time_Local'\n})\nAir_Qual_combined_2021['Date'] = pd.to_datetime(Air_Qual_combined_2021.Date)\nprint(Air_Qual_combined_2021.head())\ndf_2021 = Air_Qual_combined_2021.groupby(Air_Qual_combined_2021.Date.dt.isocalendar().week)['AQI_Value'].mean().rename_axis('AQI_month').reset_index(name='AQI_weekly')\ndf_2021.head()\nlen(df_2021)\ndf_2021['AQI_year'] = 2021",
" State County Sample Frequency AQI_lat AQI_long \\\n39150 California Los Angeles HOURLY -118.17533 33.79236 \n39151 California Los Angeles HOURLY -118.17533 33.79236 \n39152 California Los Angeles HOURLY -118.17533 33.79236 \n39153 California Los Angeles HOURLY -118.17533 33.79236 \n39154 California Los Angeles HOURLY -118.17533 33.79236 \n\n Date AQI_Value Time_Local \n39150 2021-01-01 6.6 16:00 \n39151 2021-01-01 9.0 17:00 \n39152 2021-01-01 11.2 18:00 \n39153 2021-01-01 13.4 19:00 \n39154 2021-01-01 53.8 20:00 \n"
],
[
"df_2019.head(3), df_2020.head(3), df_2021.head()",
"_____no_output_____"
],
[
"frames = [df_2019, df_2020, df_2021]\n\nresult = pd.concat(frames)",
"_____no_output_____"
],
[
"result",
"_____no_output_____"
],
[
"result['Longitude'] = Air_Qual_combined_2019['AQI_long']\nresult['Latitude'] = Air_Qual_combined_2019['AQI_lat']\nresult['State'] = Air_Qual_combined_2019['State']\nresult['County'] = Air_Qual_combined_2019['County']\nresult['Time'] = Air_Qual_combined_2019['Time_Local']\nresult.head()",
"_____no_output_____"
],
[
"len(result)",
"_____no_output_____"
],
[
"result.AQI_month = result.AQI_month.map({\n 1: 'Jan', 2: 'Jan', 3: 'Jan', 4: 'Jan',\n 5: 'Feb', 6: 'Feb', 7: 'Feb', 8: 'Feb',\n 9: 'Mar', 10: 'Mar', 11: 'Mar', 12: 'Mar',\n 13: 'Apr', 14: 'Apr', 15: 'Apr', 16: 'Apr',\n 17: 'May', 18: 'May', 19: 'May', 20: 'May',\n 21: 'Jun', 22: 'Jun', 23: 'Jun', 24: 'Jun',\n 25: 'Jul', 26: 'Jul', 27: 'Jul', 28: 'Jul',\n 29: 'Aug', 30: 'Aug', 31: 'Aug', 32: 'Aug',\n 33: 'Sept', 34: 'Sept', 35: 'Sept', 36: 'Sept',\n 37: 'Oct', 38: 'Feb', 39: 'Feb', 40: 'Feb',\n 41: 'Nov', 42: 'Nov', 43: 'Nov', 44: 'Nov',\n 45: 'Feb', 46: 'Feb', 47: 'Feb', 48: 'Feb',\n 49: 'Dec', 50: 'Dec', 51: 'Dec', 52: 'Dec',\n\n})\nresult.head()",
"_____no_output_____"
],
[
"result['State'] = 'Los Angeles'\nresult = result.rename(columns = {'State': 'City'})\nresult.head()",
"_____no_output_____"
],
[
"result = result.drop('Time', axis = 1)\nresult.head()",
"_____no_output_____"
],
[
"result.to_csv('LA_AQI_Final.csv')",
"_____no_output_____"
],
[
"sns.lineplot(data = result['AQI_weekly'])",
"_____no_output_____"
],
[
"sns.barplot(x = \"AQI_month\", y = \"AQI_weekly\", data = result)",
"_____no_output_____"
],
[
"plt.figure(figsize = (10,5))\nsns.lineplot(x = \"AQI_year\", y = \"AQI_weekly\", data = result.groupby('AQI_year').mean('AQI_weekly'))",
"_____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"
]
] |
ecd0b2261520e5f45c52a2ff222d6c5717a1510a | 474,033 | ipynb | Jupyter Notebook | 20180914_Bai2018_Article_AutomatedCardiovascularMagneti.ipynb | manigalati/ukbb_cardiac | 119d390ba9699459e0a0c4e213e3756ee82bf37b | [
"Apache-2.0"
] | null | null | null | 20180914_Bai2018_Article_AutomatedCardiovascularMagneti.ipynb | manigalati/ukbb_cardiac | 119d390ba9699459e0a0c4e213e3756ee82bf37b | [
"Apache-2.0"
] | null | null | null | 20180914_Bai2018_Article_AutomatedCardiovascularMagneti.ipynb | manigalati/ukbb_cardiac | 119d390ba9699459e0a0c4e213e3756ee82bf37b | [
"Apache-2.0"
] | null | null | null | 82.01263 | 302 | 0.671742 | [
[
[
"!rm -r sample_data",
"_____no_output_____"
],
[
"!nvidia-smi -L",
"GPU 0: Tesla P100-PCIE-16GB (UUID: GPU-b55addb2-7708-2c33-a4af-604e8c75875f)\n"
],
[
"%tensorflow_version 1.x\nimport tensorflow as tf\nprint('Tensorflow version: {}'.format(tf.__version__))",
"TensorFlow 1.x selected.\nTensorflow version: 1.15.2\n"
],
[
"#mount drive\nfrom google.colab import drive\ndrive.mount('/content/drive')",
"Mounted at /content/drive\n"
]
],
[
[
"## Install requirements",
"_____no_output_____"
]
],
[
[
"!pip install pydicom\n!pip install SimpleITK\n!pip install vtk",
"Collecting pydicom\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/d3/56/342e1f8ce5afe63bf65c23d0b2c1cd5a05600caad1c211c39725d3a4cc56/pydicom-2.0.0-py3-none-any.whl (35.4MB)\n\u001b[K |████████████████████████████████| 35.5MB 91kB/s \n\u001b[?25hInstalling collected packages: pydicom\nSuccessfully installed pydicom-2.0.0\nCollecting SimpleITK\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/f8/d8/53338c34f71020725ffb3557846c80af96c29c03bc883551a2565aa68a7c/SimpleITK-1.2.4-cp36-cp36m-manylinux1_x86_64.whl (42.5MB)\n\u001b[K |████████████████████████████████| 42.5MB 72kB/s \n\u001b[?25hInstalling collected packages: SimpleITK\nSuccessfully installed SimpleITK-1.2.4\nCollecting vtk\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/f9/3e/fa760bdbcc20d9f2fedebace22ffc575335bb5f281e98ca9831475ff3f09/vtk-9.0.1-cp36-cp36m-manylinux2010_x86_64.whl (103.4MB)\n\u001b[K |████████████████████████████████| 103.4MB 30kB/s \n\u001b[?25hInstalling collected packages: vtk\nSuccessfully installed vtk-9.0.1\n"
],
[
"import os\nos.environ['PYTHONPATH'] += \":/content\"\n!echo $PYTHONPATH",
"/tensorflow-1.15.2/python3.6:/env/python:/content\n"
]
],
[
[
"## Import data",
"_____no_output_____"
]
],
[
[
"!git clone https://github.com/manigalati/ukbb_cardiac",
"Cloning into 'ukbb_cardiac'...\nremote: Enumerating objects: 89, done.\u001b[K\nremote: Counting objects: 100% (89/89), done.\u001b[K\nremote: Compressing objects: 100% (50/50), done.\u001b[K\nremote: Total 466 (delta 66), reused 47 (delta 39), pack-reused 377\u001b[K\nReceiving objects: 100% (466/466), 398.25 KiB | 758.00 KiB/s, done.\nResolving deltas: 100% (279/279), done.\n"
]
],
[
[
"## Prepare dataset",
"_____no_output_____"
]
],
[
[
"%cd /content/ukbb_cardiac/",
"/content/ukbb_cardiac\n"
],
[
"!mkdir dataset & unzip -q \"/content/drive/My Drive/tesi/training.zip\" -d dataset/\n!mv dataset/training dataset/train ",
"_____no_output_____"
],
[
"!cp -r dataset/train dataset/validation ",
"_____no_output_____"
],
[
"!unzip -q \"/content/drive/My Drive/tesi/testing.zip\" -d dataset/ \n!mv dataset/testing/testing dataset/tmp && rm -r dataset/testing && mv dataset/tmp dataset/test",
"_____no_output_____"
]
],
[
[
"## Training\n",
"_____no_output_____"
]
],
[
[
"!python common/train_network.py",
"\u001b[1;30;43mOutput streaming troncato alle ultime 5000 righe.\u001b[0m\n training loss:\t\t0.048585\n training accuracy:\t\t98.74%\nIteration 278: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\nIteration 278 of 1000 took 0.168s\n training loss:\t\t0.072324\n training accuracy:\t\t97.91%\nIteration 279: training...\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\nIteration 279 of 1000 took 0.190s\n training loss:\t\t0.071810\n training accuracy:\t\t97.71%\nIteration 280: training...\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\nIteration 280: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient081/patient081_frame01_gt.nii.gz\nIteration 280 of 1000 took 0.674s\n training loss:\t\t0.072625\n training accuracy:\t\t97.47%\n validation loss: \t\t0.237610\n validation accuracy:\t\t92.65%\n validation Dice LV:\t\t0.348721\n validation Dice Myo:\t\t0.319202\n validation Dice RV:\t\t0.419967\n\nIteration 281: training...\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01_gt.nii.gz\nIteration 281 of 1000 took 0.221s\n training loss:\t\t0.068135\n training accuracy:\t\t97.77%\nIteration 282: training...\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 282 of 1000 took 0.211s\n training loss:\t\t0.093423\n training accuracy:\t\t97.45%\nIteration 283: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\nIteration 283 of 1000 took 0.201s\n training loss:\t\t0.056842\n training accuracy:\t\t98.25%\nIteration 284: training...\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\nIteration 284 of 1000 took 0.203s\n training loss:\t\t0.068632\n training accuracy:\t\t97.93%\nIteration 285: training...\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\nIteration 285 of 1000 took 0.189s\n training loss:\t\t0.080068\n training accuracy:\t\t97.47%\nIteration 286: training...\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\nIteration 286 of 1000 took 0.211s\n training loss:\t\t0.075184\n training accuracy:\t\t97.53%\nIteration 287: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\nIteration 287 of 1000 took 0.228s\n training loss:\t\t0.054285\n training accuracy:\t\t98.30%\nIteration 288: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\nIteration 288 of 1000 took 0.236s\n training loss:\t\t0.133147\n training accuracy:\t\t95.19%\nIteration 289: training...\n Select /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 289 of 1000 took 0.180s\n training loss:\t\t0.052452\n training accuracy:\t\t98.53%\nIteration 290: training...\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 290: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient076/patient076_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient076/patient076_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient057/patient057_frame01_gt.nii.gz\nIteration 290 of 1000 took 0.327s\n training loss:\t\t0.071554\n training accuracy:\t\t97.81%\n validation loss: \t\t0.673497\n validation accuracy:\t\t84.17%\n validation Dice LV:\t\t0.000000\n validation Dice Myo:\t\t0.000000\n validation Dice RV:\t\t0.000000\n\nIteration 291: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\nIteration 291 of 1000 took 0.203s\n training loss:\t\t0.077921\n training accuracy:\t\t97.49%\nIteration 292: training...\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\nIteration 292 of 1000 took 0.218s\n training loss:\t\t0.062940\n training accuracy:\t\t97.97%\nIteration 293: training...\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 293 of 1000 took 0.185s\n training loss:\t\t0.062424\n training accuracy:\t\t98.14%\nIteration 294: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\nIteration 294 of 1000 took 0.214s\n training loss:\t\t0.081475\n training accuracy:\t\t97.34%\nIteration 295: training...\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\nIteration 295 of 1000 took 0.215s\n training loss:\t\t0.048116\n training accuracy:\t\t98.65%\nIteration 296: training...\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\nIteration 296 of 1000 took 0.200s\n training loss:\t\t0.070964\n training accuracy:\t\t97.56%\nIteration 297: training...\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 297 of 1000 took 0.207s\n training loss:\t\t0.053479\n training accuracy:\t\t98.25%\nIteration 298: training...\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\nIteration 298 of 1000 took 0.246s\n training loss:\t\t0.502265\n training accuracy:\t\t86.26%\nIteration 299: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\nIteration 299 of 1000 took 0.231s\n training loss:\t\t0.055121\n training accuracy:\t\t98.17%\nIteration 300: training...\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\nIteration 300: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient018/patient018_frame01_gt.nii.gz\nIteration 300 of 1000 took 0.288s\n training loss:\t\t0.058227\n training accuracy:\t\t98.23%\n validation loss: \t\t0.165501\n validation accuracy:\t\t95.15%\n validation Dice LV:\t\t0.009550\n validation Dice Myo:\t\t0.470988\n validation Dice RV:\t\t0.731762\n\nIteration 301: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\nIteration 301 of 1000 took 0.215s\n training loss:\t\t0.170128\n training accuracy:\t\t94.54%\nIteration 302: training...\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\nIteration 302 of 1000 took 0.221s\n training loss:\t\t0.097928\n training accuracy:\t\t97.50%\nIteration 303: training...\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 303 of 1000 took 0.218s\n training loss:\t\t0.102542\n training accuracy:\t\t96.39%\nIteration 304: training...\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\nIteration 304 of 1000 took 0.178s\n training loss:\t\t0.076517\n training accuracy:\t\t97.65%\nIteration 305: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 305 of 1000 took 0.187s\n training loss:\t\t0.073218\n training accuracy:\t\t97.77%\nIteration 306: training...\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 306 of 1000 took 0.225s\n training loss:\t\t0.107664\n training accuracy:\t\t96.90%\nIteration 307: training...\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\nIteration 307 of 1000 took 0.283s\n training loss:\t\t0.072672\n training accuracy:\t\t97.72%\nIteration 308: training...\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 308 of 1000 took 0.203s\n training loss:\t\t0.084334\n training accuracy:\t\t97.47%\nIteration 309: training...\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\nIteration 309 of 1000 took 0.186s\n training loss:\t\t0.082625\n training accuracy:\t\t97.32%\nIteration 310: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\nIteration 310: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient078/patient078_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient049/patient049_frame01_gt.nii.gz\nIteration 310 of 1000 took 0.296s\n training loss:\t\t0.064798\n training accuracy:\t\t98.08%\n validation loss: \t\t0.200214\n validation accuracy:\t\t93.37%\n validation Dice LV:\t\t0.033147\n validation Dice Myo:\t\t0.137895\n validation Dice RV:\t\t0.208991\n\nIteration 311: training...\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\nIteration 311 of 1000 took 0.295s\n training loss:\t\t0.075964\n training accuracy:\t\t97.44%\nIteration 312: training...\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\nIteration 312 of 1000 took 0.196s\n training loss:\t\t0.069330\n training accuracy:\t\t97.64%\nIteration 313: training...\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\nIteration 313 of 1000 took 0.231s\n training loss:\t\t0.082446\n training accuracy:\t\t97.33%\nIteration 314: training...\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\nIteration 314 of 1000 took 0.234s\n training loss:\t\t0.075064\n training accuracy:\t\t97.52%\nIteration 315: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\nIteration 315 of 1000 took 0.187s\n training loss:\t\t0.068976\n training accuracy:\t\t97.63%\nIteration 316: training...\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 316 of 1000 took 0.221s\n training loss:\t\t0.052108\n training accuracy:\t\t98.34%\nIteration 317: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\nIteration 317 of 1000 took 0.201s\n training loss:\t\t0.054636\n training accuracy:\t\t98.45%\nIteration 318: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\nIteration 318 of 1000 took 0.248s\n training loss:\t\t0.046066\n training accuracy:\t\t98.78%\nIteration 319: training...\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\nIteration 319 of 1000 took 0.278s\n training loss:\t\t0.056823\n training accuracy:\t\t98.25%\nIteration 320: training...\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 320: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient074/patient074_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient053/patient053_frame01_gt.nii.gz\nIteration 320 of 1000 took 0.282s\n training loss:\t\t0.093640\n training accuracy:\t\t96.82%\n validation loss: \t\t0.093746\n validation accuracy:\t\t97.01%\n validation Dice LV:\t\t0.727852\n validation Dice Myo:\t\t0.548546\n validation Dice RV:\t\t0.824345\n\nIteration 321: training...\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\nIteration 321 of 1000 took 0.211s\n training loss:\t\t0.073093\n training accuracy:\t\t97.51%\nIteration 322: training...\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\nIteration 322 of 1000 took 0.199s\n training loss:\t\t0.064059\n training accuracy:\t\t98.01%\nIteration 323: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\nIteration 323 of 1000 took 0.180s\n training loss:\t\t0.088475\n training accuracy:\t\t96.82%\nIteration 324: training...\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\nIteration 324 of 1000 took 0.237s\n training loss:\t\t0.053745\n training accuracy:\t\t98.40%\nIteration 325: training...\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 325 of 1000 took 0.265s\n training loss:\t\t0.039554\n training accuracy:\t\t98.83%\nIteration 326: training...\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 326 of 1000 took 0.215s\n training loss:\t\t0.041766\n training accuracy:\t\t98.75%\nIteration 327: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\nIteration 327 of 1000 took 0.158s\n training loss:\t\t0.057113\n training accuracy:\t\t98.28%\nIteration 328: training...\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 328 of 1000 took 0.207s\n training loss:\t\t0.084938\n training accuracy:\t\t97.20%\nIteration 329: training...\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 329 of 1000 took 0.222s\n training loss:\t\t0.052998\n training accuracy:\t\t98.27%\nIteration 330: training...\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 330: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient029/patient029_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient046/patient046_frame01_gt.nii.gz\nIteration 330 of 1000 took 0.291s\n training loss:\t\t0.067012\n training accuracy:\t\t97.97%\n validation loss: \t\t0.179851\n validation accuracy:\t\t94.75%\n validation Dice LV:\t\t0.205169\n validation Dice Myo:\t\t0.312486\n validation Dice RV:\t\t0.625032\n\nIteration 331: training...\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\nIteration 331 of 1000 took 0.204s\n training loss:\t\t0.056537\n training accuracy:\t\t98.32%\nIteration 332: training...\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\nIteration 332 of 1000 took 0.255s\n training loss:\t\t0.232877\n training accuracy:\t\t92.48%\nIteration 333: training...\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\nIteration 333 of 1000 took 0.234s\n training loss:\t\t0.066198\n training accuracy:\t\t97.98%\nIteration 334: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 334 of 1000 took 0.207s\n training loss:\t\t0.051834\n training accuracy:\t\t98.40%\nIteration 335: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\nIteration 335 of 1000 took 0.232s\n training loss:\t\t0.068358\n training accuracy:\t\t97.55%\nIteration 336: training...\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\nIteration 336 of 1000 took 0.231s\n training loss:\t\t0.060836\n training accuracy:\t\t98.17%\nIteration 337: training...\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\nIteration 337 of 1000 took 0.215s\n training loss:\t\t0.069721\n training accuracy:\t\t97.91%\nIteration 338: training...\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\nIteration 338 of 1000 took 0.173s\n training loss:\t\t0.055592\n training accuracy:\t\t98.39%\nIteration 339: training...\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\nIteration 339 of 1000 took 0.252s\n training loss:\t\t0.052908\n training accuracy:\t\t98.42%\nIteration 340: training...\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 340: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient075/patient075_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient017/patient017_frame01_gt.nii.gz\nIteration 340 of 1000 took 0.301s\n training loss:\t\t0.058341\n training accuracy:\t\t98.26%\n validation loss: \t\t0.156510\n validation accuracy:\t\t95.04%\n validation Dice LV:\t\t0.185293\n validation Dice Myo:\t\t0.286574\n validation Dice RV:\t\t0.434358\n\nIteration 341: training...\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\nIteration 341 of 1000 took 0.207s\n training loss:\t\t0.068238\n training accuracy:\t\t97.81%\nIteration 342: training...\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\nIteration 342 of 1000 took 0.216s\n training loss:\t\t0.073202\n training accuracy:\t\t97.59%\nIteration 343: training...\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\nIteration 343 of 1000 took 0.213s\n training loss:\t\t0.058570\n training accuracy:\t\t98.19%\nIteration 344: training...\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\nIteration 344 of 1000 took 0.300s\n training loss:\t\t0.051419\n training accuracy:\t\t98.41%\nIteration 345: training...\n Select /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\nIteration 345 of 1000 took 0.206s\n training loss:\t\t0.043624\n training accuracy:\t\t98.64%\nIteration 346: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\nIteration 346 of 1000 took 0.227s\n training loss:\t\t0.052537\n training accuracy:\t\t98.23%\nIteration 347: training...\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\nIteration 347 of 1000 took 0.221s\n training loss:\t\t0.052344\n training accuracy:\t\t98.37%\nIteration 348: training...\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 348 of 1000 took 0.297s\n training loss:\t\t0.065830\n training accuracy:\t\t97.98%\nIteration 349: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\nIteration 349 of 1000 took 0.200s\n training loss:\t\t0.042103\n training accuracy:\t\t98.71%\nIteration 350: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\nIteration 350: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient087/patient087_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient051/patient051_frame01_gt.nii.gz\nIteration 350 of 1000 took 0.305s\n training loss:\t\t0.099520\n training accuracy:\t\t96.47%\n validation loss: \t\t0.216438\n validation accuracy:\t\t94.32%\n validation Dice LV:\t\t0.179344\n validation Dice Myo:\t\t0.193070\n validation Dice RV:\t\t0.328167\n\nIteration 351: training...\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\nIteration 351 of 1000 took 0.184s\n training loss:\t\t0.065037\n training accuracy:\t\t97.78%\nIteration 352: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 352 of 1000 took 0.230s\n training loss:\t\t0.059014\n training accuracy:\t\t98.12%\nIteration 353: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 353 of 1000 took 0.225s\n training loss:\t\t0.116611\n training accuracy:\t\t95.96%\nIteration 354: training...\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\nIteration 354 of 1000 took 0.248s\n training loss:\t\t0.044502\n training accuracy:\t\t98.65%\nIteration 355: training...\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\nIteration 355 of 1000 took 0.288s\n training loss:\t\t0.045619\n training accuracy:\t\t98.71%\nIteration 356: training...\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\nIteration 356 of 1000 took 0.189s\n training loss:\t\t0.049658\n training accuracy:\t\t98.29%\nIteration 357: training...\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\nIteration 357 of 1000 took 0.221s\n training loss:\t\t0.055086\n training accuracy:\t\t98.19%\nIteration 358: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 358 of 1000 took 0.221s\n training loss:\t\t0.049827\n training accuracy:\t\t98.45%\nIteration 359: training...\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\nIteration 359 of 1000 took 0.233s\n training loss:\t\t0.050171\n training accuracy:\t\t98.34%\nIteration 360: training...\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\nIteration 360: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient066/patient066_frame01_gt.nii.gz\nIteration 360 of 1000 took 0.267s\n training loss:\t\t0.056550\n training accuracy:\t\t98.10%\n validation loss: \t\t0.107828\n validation accuracy:\t\t96.16%\n validation Dice LV:\t\t0.351188\n validation Dice Myo:\t\t0.497241\n validation Dice RV:\t\t0.757809\n\nIteration 361: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\nIteration 361 of 1000 took 0.168s\n training loss:\t\t0.053854\n training accuracy:\t\t98.21%\nIteration 362: training...\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\nIteration 362 of 1000 took 0.207s\n training loss:\t\t0.050215\n training accuracy:\t\t98.30%\nIteration 363: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 363 of 1000 took 0.181s\n training loss:\t\t0.079531\n training accuracy:\t\t97.45%\nIteration 364: training...\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\nIteration 364 of 1000 took 0.192s\n training loss:\t\t0.051359\n training accuracy:\t\t98.37%\nIteration 365: training...\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 365 of 1000 took 0.258s\n training loss:\t\t0.045357\n training accuracy:\t\t98.59%\nIteration 366: training...\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\nIteration 366 of 1000 took 0.252s\n training loss:\t\t0.066584\n training accuracy:\t\t98.46%\nIteration 367: training...\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 367 of 1000 took 0.233s\n training loss:\t\t0.199780\n training accuracy:\t\t93.19%\nIteration 368: training...\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\nIteration 368 of 1000 took 0.257s\n training loss:\t\t0.050356\n training accuracy:\t\t98.34%\nIteration 369: training...\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\nIteration 369 of 1000 took 0.248s\n training loss:\t\t0.047410\n training accuracy:\t\t98.58%\nIteration 370: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 370: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient064/patient064_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient052/patient052_frame01_gt.nii.gz\nIteration 370 of 1000 took 0.279s\n training loss:\t\t0.109646\n training accuracy:\t\t96.05%\n validation loss: \t\t0.098445\n validation accuracy:\t\t97.01%\n validation Dice LV:\t\t0.551903\n validation Dice Myo:\t\t0.612001\n validation Dice RV:\t\t0.797175\n\nIteration 371: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\nIteration 371 of 1000 took 0.223s\n training loss:\t\t0.047302\n training accuracy:\t\t98.51%\nIteration 372: training...\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\nIteration 372 of 1000 took 0.211s\n training loss:\t\t0.050460\n training accuracy:\t\t98.50%\nIteration 373: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\nIteration 373 of 1000 took 0.211s\n training loss:\t\t0.049538\n training accuracy:\t\t98.48%\nIteration 374: training...\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\nIteration 374 of 1000 took 0.231s\n training loss:\t\t0.105512\n training accuracy:\t\t95.80%\nIteration 375: training...\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 375 of 1000 took 0.177s\n training loss:\t\t0.061311\n training accuracy:\t\t97.89%\nIteration 376: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\nIteration 376 of 1000 took 0.200s\n training loss:\t\t0.046689\n training accuracy:\t\t98.56%\nIteration 377: training...\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\nIteration 377 of 1000 took 1.262s\n training loss:\t\t0.047008\n training accuracy:\t\t98.43%\nIteration 378: training...\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\nIteration 378 of 1000 took 0.269s\n training loss:\t\t0.048029\n training accuracy:\t\t98.54%\nIteration 379: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 379 of 1000 took 0.199s\n training loss:\t\t0.057641\n training accuracy:\t\t98.06%\nIteration 380: training...\n Select /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\nIteration 380: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient038/patient038_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient013/patient013_frame01_gt.nii.gz\nIteration 380 of 1000 took 0.301s\n training loss:\t\t0.040077\n training accuracy:\t\t98.77%\n validation loss: \t\t0.314357\n validation accuracy:\t\t89.01%\n validation Dice LV:\t\t0.265396\n validation Dice Myo:\t\t0.197294\n validation Dice RV:\t\t0.178974\n\nIteration 381: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\nIteration 381 of 1000 took 0.264s\n training loss:\t\t0.036549\n training accuracy:\t\t98.99%\nIteration 382: training...\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\nIteration 382 of 1000 took 0.182s\n training loss:\t\t0.043934\n training accuracy:\t\t98.64%\nIteration 383: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 383 of 1000 took 0.244s\n training loss:\t\t0.033184\n training accuracy:\t\t99.11%\nIteration 384: training...\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\nIteration 384 of 1000 took 0.213s\n training loss:\t\t0.103473\n training accuracy:\t\t96.16%\nIteration 385: training...\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\nIteration 385 of 1000 took 0.248s\n training loss:\t\t0.057877\n training accuracy:\t\t97.94%\nIteration 386: training...\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\nIteration 386 of 1000 took 0.232s\n training loss:\t\t0.039618\n training accuracy:\t\t98.66%\nIteration 387: training...\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 387 of 1000 took 0.269s\n training loss:\t\t0.036148\n training accuracy:\t\t98.97%\nIteration 388: training...\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\nIteration 388 of 1000 took 0.193s\n training loss:\t\t0.053340\n training accuracy:\t\t98.16%\nIteration 389: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\nIteration 389 of 1000 took 0.198s\n training loss:\t\t0.039606\n training accuracy:\t\t98.76%\nIteration 390: training...\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 390: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient022/patient022_frame01_gt.nii.gz\nIteration 390 of 1000 took 0.259s\n training loss:\t\t0.040419\n training accuracy:\t\t98.83%\n validation loss: \t\t0.136275\n validation accuracy:\t\t95.58%\n validation Dice LV:\t\t0.605480\n validation Dice Myo:\t\t0.486143\n validation Dice RV:\t\t0.560502\n\nIteration 391: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 391 of 1000 took 0.267s\n training loss:\t\t0.048523\n training accuracy:\t\t98.46%\nIteration 392: training...\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\nIteration 392 of 1000 took 0.182s\n training loss:\t\t0.072678\n training accuracy:\t\t97.33%\nIteration 393: training...\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\nIteration 393 of 1000 took 0.190s\n training loss:\t\t0.050057\n training accuracy:\t\t98.38%\nIteration 394: training...\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\nIteration 394 of 1000 took 0.208s\n training loss:\t\t0.057193\n training accuracy:\t\t98.01%\nIteration 395: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 395 of 1000 took 0.209s\n training loss:\t\t0.057351\n training accuracy:\t\t97.93%\nIteration 396: training...\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\nIteration 396 of 1000 took 0.206s\n training loss:\t\t0.088638\n training accuracy:\t\t97.16%\nIteration 397: training...\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\nIteration 397 of 1000 took 0.217s\n training loss:\t\t0.041336\n training accuracy:\t\t98.65%\nIteration 398: training...\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\nIteration 398 of 1000 took 0.208s\n training loss:\t\t0.042130\n training accuracy:\t\t98.67%\nIteration 399: training...\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\nIteration 399 of 1000 took 0.214s\n training loss:\t\t0.047873\n training accuracy:\t\t98.38%\nIteration 400: training...\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\nIteration 400: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient087/patient087_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient001/patient001_frame01_gt.nii.gz\nIteration 400 of 1000 took 0.296s\n training loss:\t\t0.048971\n training accuracy:\t\t98.43%\n validation loss: \t\t0.119222\n validation accuracy:\t\t96.05%\n validation Dice LV:\t\t0.367056\n validation Dice Myo:\t\t0.593303\n validation Dice RV:\t\t0.769749\n\nIteration 401: training...\n Select /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\nIteration 401 of 1000 took 0.194s\n training loss:\t\t0.046957\n training accuracy:\t\t98.46%\nIteration 402: training...\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\nIteration 402 of 1000 took 0.233s\n training loss:\t\t0.059823\n training accuracy:\t\t98.04%\nIteration 403: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\nIteration 403 of 1000 took 0.196s\n training loss:\t\t0.054816\n training accuracy:\t\t98.13%\nIteration 404: training...\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 404 of 1000 took 0.282s\n training loss:\t\t0.045401\n training accuracy:\t\t98.52%\nIteration 405: training...\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\nIteration 405 of 1000 took 0.222s\n training loss:\t\t0.087877\n training accuracy:\t\t96.87%\nIteration 406: training...\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\nIteration 406 of 1000 took 0.173s\n training loss:\t\t0.037638\n training accuracy:\t\t98.81%\nIteration 407: training...\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 407 of 1000 took 0.206s\n training loss:\t\t0.052888\n training accuracy:\t\t98.20%\nIteration 408: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\nIteration 408 of 1000 took 0.199s\n training loss:\t\t0.045238\n training accuracy:\t\t98.64%\nIteration 409: training...\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\nIteration 409 of 1000 took 0.202s\n training loss:\t\t0.037390\n training accuracy:\t\t98.92%\nIteration 410: training...\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\nIteration 410: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient014/patient014_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient082/patient082_frame01_gt.nii.gz\nIteration 410 of 1000 took 0.276s\n training loss:\t\t0.070542\n training accuracy:\t\t97.53%\n validation loss: \t\t0.118851\n validation accuracy:\t\t95.84%\n validation Dice LV:\t\t0.393374\n validation Dice Myo:\t\t0.497723\n validation Dice RV:\t\t0.726762\n\nIteration 411: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\nIteration 411 of 1000 took 0.252s\n training loss:\t\t0.054392\n training accuracy:\t\t98.19%\nIteration 412: training...\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\nIteration 412 of 1000 took 0.205s\n training loss:\t\t0.057740\n training accuracy:\t\t98.03%\nIteration 413: training...\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\nIteration 413 of 1000 took 0.209s\n training loss:\t\t0.045266\n training accuracy:\t\t98.64%\nIteration 414: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\nIteration 414 of 1000 took 0.222s\n training loss:\t\t0.055311\n training accuracy:\t\t98.08%\nIteration 415: training...\n Select /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\nIteration 415 of 1000 took 0.313s\n training loss:\t\t0.043257\n training accuracy:\t\t98.67%\nIteration 416: training...\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 416 of 1000 took 0.221s\n training loss:\t\t0.043359\n training accuracy:\t\t98.59%\nIteration 417: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 417 of 1000 took 0.210s\n training loss:\t\t0.052676\n training accuracy:\t\t98.20%\nIteration 418: training...\n Select /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\nIteration 418 of 1000 took 0.207s\n training loss:\t\t0.047860\n training accuracy:\t\t98.44%\nIteration 419: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\nIteration 419 of 1000 took 0.228s\n training loss:\t\t0.058205\n training accuracy:\t\t97.85%\nIteration 420: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\nIteration 420: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient081/patient081_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient100/patient100_frame01_gt.nii.gz\nIteration 420 of 1000 took 0.318s\n training loss:\t\t0.049777\n training accuracy:\t\t98.29%\n validation loss: \t\t0.077111\n validation accuracy:\t\t97.05%\n validation Dice LV:\t\t0.459717\n validation Dice Myo:\t\t0.620079\n validation Dice RV:\t\t0.696660\n\nIteration 421: training...\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\nIteration 421 of 1000 took 0.215s\n training loss:\t\t0.057319\n training accuracy:\t\t98.00%\nIteration 422: training...\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\nIteration 422 of 1000 took 0.219s\n training loss:\t\t0.042819\n training accuracy:\t\t98.62%\nIteration 423: training...\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\nIteration 423 of 1000 took 0.220s\n training loss:\t\t0.075103\n training accuracy:\t\t97.53%\nIteration 424: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\nIteration 424 of 1000 took 0.202s\n training loss:\t\t0.047259\n training accuracy:\t\t98.41%\nIteration 425: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 425 of 1000 took 0.178s\n training loss:\t\t0.048577\n training accuracy:\t\t98.52%\nIteration 426: training...\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\nIteration 426 of 1000 took 0.289s\n training loss:\t\t0.061201\n training accuracy:\t\t98.12%\nIteration 427: training...\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\nIteration 427 of 1000 took 0.238s\n training loss:\t\t0.044837\n training accuracy:\t\t98.59%\nIteration 428: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\nIteration 428 of 1000 took 0.213s\n training loss:\t\t0.065189\n training accuracy:\t\t97.66%\nIteration 429: training...\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\nIteration 429 of 1000 took 0.168s\n training loss:\t\t0.045440\n training accuracy:\t\t98.51%\nIteration 430: training...\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 430: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient077/patient077_frame01_gt.nii.gz\nIteration 430 of 1000 took 0.302s\n training loss:\t\t0.048496\n training accuracy:\t\t98.42%\n validation loss: \t\t0.057267\n validation accuracy:\t\t98.08%\n validation Dice LV:\t\t0.827863\n validation Dice Myo:\t\t0.776804\n validation Dice RV:\t\t0.921502\n\nIteration 431: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 431 of 1000 took 0.209s\n training loss:\t\t0.039385\n training accuracy:\t\t98.78%\nIteration 432: training...\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\nIteration 432 of 1000 took 0.259s\n training loss:\t\t0.070482\n training accuracy:\t\t97.72%\nIteration 433: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\nIteration 433 of 1000 took 0.207s\n training loss:\t\t0.040683\n training accuracy:\t\t98.72%\nIteration 434: training...\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\nIteration 434 of 1000 took 0.220s\n training loss:\t\t0.042940\n training accuracy:\t\t98.60%\nIteration 435: training...\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\nIteration 435 of 1000 took 0.211s\n training loss:\t\t0.039717\n training accuracy:\t\t98.63%\nIteration 436: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\nIteration 436 of 1000 took 0.195s\n training loss:\t\t0.118501\n training accuracy:\t\t96.10%\nIteration 437: training...\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\nIteration 437 of 1000 took 0.265s\n training loss:\t\t0.039742\n training accuracy:\t\t98.77%\nIteration 438: training...\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 438 of 1000 took 0.274s\n training loss:\t\t0.062335\n training accuracy:\t\t97.72%\nIteration 439: training...\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\nIteration 439 of 1000 took 0.215s\n training loss:\t\t0.051742\n training accuracy:\t\t98.09%\nIteration 440: training...\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\nIteration 440: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient047/patient047_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient038/patient038_frame01_gt.nii.gz\nIteration 440 of 1000 took 0.353s\n training loss:\t\t0.058187\n training accuracy:\t\t98.07%\n validation loss: \t\t0.115533\n validation accuracy:\t\t95.85%\n validation Dice LV:\t\t0.533026\n validation Dice Myo:\t\t0.730002\n validation Dice RV:\t\t0.914723\n\nIteration 441: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\nIteration 441 of 1000 took 0.234s\n training loss:\t\t0.061318\n training accuracy:\t\t97.96%\nIteration 442: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\nIteration 442 of 1000 took 0.270s\n training loss:\t\t0.048416\n training accuracy:\t\t98.52%\nIteration 443: training...\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\nIteration 443 of 1000 took 0.226s\n training loss:\t\t0.064184\n training accuracy:\t\t97.85%\nIteration 444: training...\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\nIteration 444 of 1000 took 0.240s\n training loss:\t\t0.069929\n training accuracy:\t\t97.70%\nIteration 445: training...\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\nIteration 445 of 1000 took 0.240s\n training loss:\t\t0.037565\n training accuracy:\t\t98.81%\nIteration 446: training...\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\nIteration 446 of 1000 took 0.177s\n training loss:\t\t0.043499\n training accuracy:\t\t98.58%\nIteration 447: training...\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\nIteration 447 of 1000 took 0.167s\n training loss:\t\t0.054063\n training accuracy:\t\t98.22%\nIteration 448: training...\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\nIteration 448 of 1000 took 0.177s\n training loss:\t\t0.047913\n training accuracy:\t\t98.52%\nIteration 449: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\nIteration 449 of 1000 took 0.213s\n training loss:\t\t0.033589\n training accuracy:\t\t98.97%\nIteration 450: training...\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\nIteration 450: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient023/patient023_frame01_gt.nii.gz\nIteration 450 of 1000 took 0.308s\n training loss:\t\t0.026046\n training accuracy:\t\t99.36%\n validation loss: \t\t0.057120\n validation accuracy:\t\t98.19%\n validation Dice LV:\t\t0.720611\n validation Dice Myo:\t\t0.675656\n validation Dice RV:\t\t0.759112\n\nIteration 451: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\nIteration 451 of 1000 took 0.208s\n training loss:\t\t0.031744\n training accuracy:\t\t99.01%\nIteration 452: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\nIteration 452 of 1000 took 0.220s\n training loss:\t\t0.036197\n training accuracy:\t\t98.94%\nIteration 453: training...\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\nIteration 453 of 1000 took 0.224s\n training loss:\t\t0.074851\n training accuracy:\t\t97.43%\nIteration 454: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 454 of 1000 took 0.211s\n training loss:\t\t0.076231\n training accuracy:\t\t97.36%\nIteration 455: training...\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\nIteration 455 of 1000 took 0.224s\n training loss:\t\t0.082798\n training accuracy:\t\t97.28%\nIteration 456: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\nIteration 456 of 1000 took 0.237s\n training loss:\t\t0.060071\n training accuracy:\t\t97.88%\nIteration 457: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\nIteration 457 of 1000 took 0.209s\n training loss:\t\t0.043089\n training accuracy:\t\t98.51%\nIteration 458: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\nIteration 458 of 1000 took 0.290s\n training loss:\t\t0.036267\n training accuracy:\t\t98.87%\nIteration 459: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\nIteration 459 of 1000 took 0.197s\n training loss:\t\t0.045001\n training accuracy:\t\t98.45%\nIteration 460: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\nIteration 460: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient074/patient074_frame01_gt.nii.gz\nIteration 460 of 1000 took 0.312s\n training loss:\t\t0.249068\n training accuracy:\t\t91.47%\n validation loss: \t\t0.069910\n validation accuracy:\t\t97.63%\n validation Dice LV:\t\t0.786191\n validation Dice Myo:\t\t0.669059\n validation Dice RV:\t\t0.851905\n\nIteration 461: training...\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\nIteration 461 of 1000 took 0.310s\n training loss:\t\t0.059851\n training accuracy:\t\t98.18%\nIteration 462: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 462 of 1000 took 0.208s\n training loss:\t\t0.043864\n training accuracy:\t\t98.56%\nIteration 463: training...\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 463 of 1000 took 0.202s\n training loss:\t\t0.050097\n training accuracy:\t\t98.28%\nIteration 464: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 464 of 1000 took 0.174s\n training loss:\t\t0.078487\n training accuracy:\t\t97.10%\nIteration 465: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\nIteration 465 of 1000 took 0.203s\n training loss:\t\t0.095196\n training accuracy:\t\t96.69%\nIteration 466: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 466 of 1000 took 0.240s\n training loss:\t\t0.081600\n training accuracy:\t\t97.08%\nIteration 467: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\nIteration 467 of 1000 took 0.215s\n training loss:\t\t0.058262\n training accuracy:\t\t97.93%\nIteration 468: training...\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 468 of 1000 took 0.211s\n training loss:\t\t0.054940\n training accuracy:\t\t98.16%\nIteration 469: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\nIteration 469 of 1000 took 0.185s\n training loss:\t\t0.046125\n training accuracy:\t\t98.51%\nIteration 470: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\nIteration 470: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient016/patient016_frame01_gt.nii.gz\nIteration 470 of 1000 took 0.287s\n training loss:\t\t0.119699\n training accuracy:\t\t95.84%\n validation loss: \t\t0.202515\n validation accuracy:\t\t93.37%\n validation Dice LV:\t\t0.229153\n validation Dice Myo:\t\t0.244475\n validation Dice RV:\t\t0.308911\n\nIteration 471: training...\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 471 of 1000 took 0.211s\n training loss:\t\t0.058746\n training accuracy:\t\t97.92%\nIteration 472: training...\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\nIteration 472 of 1000 took 0.219s\n training loss:\t\t0.049948\n training accuracy:\t\t98.27%\nIteration 473: training...\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 473 of 1000 took 0.200s\n training loss:\t\t0.049712\n training accuracy:\t\t98.49%\nIteration 474: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\nIteration 474 of 1000 took 0.207s\n training loss:\t\t0.063094\n training accuracy:\t\t98.01%\nIteration 475: training...\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\nIteration 475 of 1000 took 0.229s\n training loss:\t\t0.084695\n training accuracy:\t\t97.27%\nIteration 476: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\nIteration 476 of 1000 took 0.226s\n training loss:\t\t0.067897\n training accuracy:\t\t97.58%\nIteration 477: training...\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\nIteration 477 of 1000 took 0.182s\n training loss:\t\t0.065838\n training accuracy:\t\t97.59%\nIteration 478: training...\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\nIteration 478 of 1000 took 0.227s\n training loss:\t\t0.093656\n training accuracy:\t\t97.05%\nIteration 479: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\nIteration 479 of 1000 took 0.235s\n training loss:\t\t0.070929\n training accuracy:\t\t97.44%\nIteration 480: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\nIteration 480: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient046/patient046_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient052/patient052_frame01_gt.nii.gz\nIteration 480 of 1000 took 0.262s\n training loss:\t\t0.046508\n training accuracy:\t\t98.40%\n validation loss: \t\t0.154910\n validation accuracy:\t\t94.23%\n validation Dice LV:\t\t0.560904\n validation Dice Myo:\t\t0.588527\n validation Dice RV:\t\t0.826870\n\nIteration 481: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01_gt.nii.gz\nIteration 481 of 1000 took 0.206s\n training loss:\t\t0.053198\n training accuracy:\t\t98.18%\nIteration 482: training...\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\nIteration 482 of 1000 took 0.212s\n training loss:\t\t0.052793\n training accuracy:\t\t98.29%\nIteration 483: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\nIteration 483 of 1000 took 0.237s\n training loss:\t\t0.034076\n training accuracy:\t\t99.01%\nIteration 484: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\nIteration 484 of 1000 took 0.189s\n training loss:\t\t0.048877\n training accuracy:\t\t98.60%\nIteration 485: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 485 of 1000 took 0.169s\n training loss:\t\t0.059894\n training accuracy:\t\t98.05%\nIteration 486: training...\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\nIteration 486 of 1000 took 0.320s\n training loss:\t\t0.061700\n training accuracy:\t\t97.92%\nIteration 487: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\nIteration 487 of 1000 took 0.235s\n training loss:\t\t0.039562\n training accuracy:\t\t98.83%\nIteration 488: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\nIteration 488 of 1000 took 0.184s\n training loss:\t\t0.068721\n training accuracy:\t\t97.34%\nIteration 489: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\nIteration 489 of 1000 took 0.233s\n training loss:\t\t0.067467\n training accuracy:\t\t97.72%\nIteration 490: training...\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 490: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient006/patient006_frame01_gt.nii.gz\nIteration 490 of 1000 took 0.396s\n training loss:\t\t0.054894\n training accuracy:\t\t98.34%\n validation loss: \t\t0.103652\n validation accuracy:\t\t96.32%\n validation Dice LV:\t\t0.713913\n validation Dice Myo:\t\t0.568220\n validation Dice RV:\t\t0.782769\n\nIteration 491: training...\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 491 of 1000 took 0.208s\n training loss:\t\t0.072747\n training accuracy:\t\t97.53%\nIteration 492: training...\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\nIteration 492 of 1000 took 0.255s\n training loss:\t\t0.050540\n training accuracy:\t\t98.16%\nIteration 493: training...\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\nIteration 493 of 1000 took 0.317s\n training loss:\t\t0.035256\n training accuracy:\t\t98.99%\nIteration 494: training...\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\nIteration 494 of 1000 took 0.271s\n training loss:\t\t0.046247\n training accuracy:\t\t98.42%\nIteration 495: training...\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\nIteration 495 of 1000 took 0.184s\n training loss:\t\t0.046225\n training accuracy:\t\t98.60%\nIteration 496: training...\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 496 of 1000 took 0.234s\n training loss:\t\t0.053623\n training accuracy:\t\t98.08%\nIteration 497: training...\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\nIteration 497 of 1000 took 0.278s\n training loss:\t\t0.034716\n training accuracy:\t\t98.91%\nIteration 498: training...\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\nIteration 498 of 1000 took 0.218s\n training loss:\t\t0.051606\n training accuracy:\t\t98.42%\nIteration 499: training...\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\nIteration 499 of 1000 took 0.220s\n training loss:\t\t0.041791\n training accuracy:\t\t98.54%\nIteration 500: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\nIteration 500: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient060/patient060_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient042/patient042_frame01_gt.nii.gz\nIteration 500 of 1000 took 0.278s\n training loss:\t\t0.041958\n training accuracy:\t\t98.56%\n validation loss: \t\t0.046418\n validation accuracy:\t\t98.57%\n validation Dice LV:\t\t0.849198\n validation Dice Myo:\t\t0.697748\n validation Dice RV:\t\t0.945784\n\nIteration 501: training...\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\nIteration 501 of 1000 took 0.221s\n training loss:\t\t0.128668\n training accuracy:\t\t95.31%\nIteration 502: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 502 of 1000 took 0.188s\n training loss:\t\t0.038734\n training accuracy:\t\t98.81%\nIteration 503: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\nIteration 503 of 1000 took 0.204s\n training loss:\t\t0.034135\n training accuracy:\t\t98.88%\nIteration 504: training...\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\nIteration 504 of 1000 took 0.222s\n training loss:\t\t0.066649\n training accuracy:\t\t98.08%\nIteration 505: training...\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\nIteration 505 of 1000 took 0.236s\n training loss:\t\t0.047460\n training accuracy:\t\t98.54%\nIteration 506: training...\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\nIteration 506 of 1000 took 0.228s\n training loss:\t\t0.051352\n training accuracy:\t\t98.11%\nIteration 507: training...\n Select /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\nIteration 507 of 1000 took 0.185s\n training loss:\t\t0.038120\n training accuracy:\t\t98.70%\nIteration 508: training...\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\nIteration 508 of 1000 took 0.228s\n training loss:\t\t0.059055\n training accuracy:\t\t97.89%\nIteration 509: training...\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\nIteration 509 of 1000 took 0.169s\n training loss:\t\t0.031882\n training accuracy:\t\t99.09%\nIteration 510: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\nIteration 510: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient055/patient055_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient053/patient053_frame01_gt.nii.gz\nIteration 510 of 1000 took 0.274s\n training loss:\t\t0.038407\n training accuracy:\t\t98.75%\n validation loss: \t\t0.067680\n validation accuracy:\t\t97.87%\n validation Dice LV:\t\t0.815679\n validation Dice Myo:\t\t0.685677\n validation Dice RV:\t\t0.873970\n\nIteration 511: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\nIteration 511 of 1000 took 0.200s\n training loss:\t\t0.044332\n training accuracy:\t\t98.49%\nIteration 512: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\nIteration 512 of 1000 took 0.236s\n training loss:\t\t0.039259\n training accuracy:\t\t98.64%\nIteration 513: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\nIteration 513 of 1000 took 0.161s\n training loss:\t\t0.043816\n training accuracy:\t\t98.56%\nIteration 514: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\nIteration 514 of 1000 took 0.234s\n training loss:\t\t0.050790\n training accuracy:\t\t98.21%\nIteration 515: training...\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\nIteration 515 of 1000 took 0.222s\n training loss:\t\t0.043296\n training accuracy:\t\t98.50%\nIteration 516: training...\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\nIteration 516 of 1000 took 0.212s\n training loss:\t\t0.063271\n training accuracy:\t\t97.78%\nIteration 517: training...\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\nIteration 517 of 1000 took 0.206s\n training loss:\t\t0.036770\n training accuracy:\t\t98.76%\nIteration 518: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 518 of 1000 took 0.219s\n training loss:\t\t0.050015\n training accuracy:\t\t98.21%\nIteration 519: training...\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\nIteration 519 of 1000 took 0.209s\n training loss:\t\t0.034577\n training accuracy:\t\t98.92%\nIteration 520: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\nIteration 520: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient028/patient028_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient031/patient031_frame01_gt.nii.gz\nIteration 520 of 1000 took 0.240s\n training loss:\t\t0.063973\n training accuracy:\t\t97.93%\n validation loss: \t\t0.050103\n validation accuracy:\t\t98.32%\n validation Dice LV:\t\t0.826667\n validation Dice Myo:\t\t0.753838\n validation Dice RV:\t\t0.912512\n\nIteration 521: training...\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\nIteration 521 of 1000 took 0.232s\n training loss:\t\t0.050924\n training accuracy:\t\t98.22%\nIteration 522: training...\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\nIteration 522 of 1000 took 0.238s\n training loss:\t\t0.036932\n training accuracy:\t\t98.90%\nIteration 523: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\nIteration 523 of 1000 took 0.205s\n training loss:\t\t0.042601\n training accuracy:\t\t98.59%\nIteration 524: training...\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\nIteration 524 of 1000 took 0.179s\n training loss:\t\t0.040341\n training accuracy:\t\t98.59%\nIteration 525: training...\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\nIteration 525 of 1000 took 0.201s\n training loss:\t\t0.117414\n training accuracy:\t\t95.85%\nIteration 526: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\nIteration 526 of 1000 took 0.218s\n training loss:\t\t0.086522\n training accuracy:\t\t97.19%\nIteration 527: training...\n Select /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\nIteration 527 of 1000 took 0.255s\n training loss:\t\t0.032367\n training accuracy:\t\t99.00%\nIteration 528: training...\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\nIteration 528 of 1000 took 0.220s\n training loss:\t\t0.052758\n training accuracy:\t\t98.13%\nIteration 529: training...\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\nIteration 529 of 1000 took 0.228s\n training loss:\t\t0.058027\n training accuracy:\t\t97.99%\nIteration 530: training...\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\nIteration 530: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient029/patient029_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient057/patient057_frame01_gt.nii.gz\nIteration 530 of 1000 took 0.345s\n training loss:\t\t0.038475\n training accuracy:\t\t98.80%\n validation loss: \t\t0.506988\n validation accuracy:\t\t87.19%\n validation Dice LV:\t\t0.028948\n validation Dice Myo:\t\t0.297404\n validation Dice RV:\t\t0.174865\n\nIteration 531: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\nIteration 531 of 1000 took 0.184s\n training loss:\t\t0.050570\n training accuracy:\t\t98.23%\nIteration 532: training...\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 532 of 1000 took 0.202s\n training loss:\t\t0.076261\n training accuracy:\t\t97.11%\nIteration 533: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\nIteration 533 of 1000 took 0.204s\n training loss:\t\t0.029753\n training accuracy:\t\t99.03%\nIteration 534: training...\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\nIteration 534 of 1000 took 0.278s\n training loss:\t\t0.068514\n training accuracy:\t\t97.50%\nIteration 535: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\nIteration 535 of 1000 took 0.215s\n training loss:\t\t0.051864\n training accuracy:\t\t98.31%\nIteration 536: training...\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 536 of 1000 took 0.227s\n training loss:\t\t0.024958\n training accuracy:\t\t99.21%\nIteration 537: training...\n Select /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\nIteration 537 of 1000 took 0.213s\n training loss:\t\t0.036288\n training accuracy:\t\t98.74%\nIteration 538: training...\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\nIteration 538 of 1000 took 0.241s\n training loss:\t\t0.277433\n training accuracy:\t\t91.22%\nIteration 539: training...\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 539 of 1000 took 0.227s\n training loss:\t\t0.051570\n training accuracy:\t\t98.11%\nIteration 540: training...\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\nIteration 540: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient033/patient033_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient044/patient044_frame01_gt.nii.gz\nIteration 540 of 1000 took 0.344s\n training loss:\t\t0.040521\n training accuracy:\t\t98.60%\n validation loss: \t\t0.377635\n validation accuracy:\t\t86.46%\n validation Dice LV:\t\t0.244787\n validation Dice Myo:\t\t0.334657\n validation Dice RV:\t\t0.615524\n\nIteration 541: training...\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\nIteration 541 of 1000 took 0.185s\n training loss:\t\t0.083639\n training accuracy:\t\t97.20%\nIteration 542: training...\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\nIteration 542 of 1000 took 0.233s\n training loss:\t\t0.048653\n training accuracy:\t\t98.26%\nIteration 543: training...\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\nIteration 543 of 1000 took 0.292s\n training loss:\t\t0.066023\n training accuracy:\t\t97.82%\nIteration 544: training...\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 544 of 1000 took 0.222s\n training loss:\t\t0.042565\n training accuracy:\t\t98.59%\nIteration 545: training...\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\nIteration 545 of 1000 took 0.195s\n training loss:\t\t0.084426\n training accuracy:\t\t96.82%\nIteration 546: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\nIteration 546 of 1000 took 0.202s\n training loss:\t\t0.059404\n training accuracy:\t\t97.97%\nIteration 547: training...\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\nIteration 547 of 1000 took 0.217s\n training loss:\t\t0.059199\n training accuracy:\t\t98.11%\nIteration 548: training...\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\nIteration 548 of 1000 took 0.280s\n training loss:\t\t0.050105\n training accuracy:\t\t98.28%\nIteration 549: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\nIteration 549 of 1000 took 0.228s\n training loss:\t\t0.056032\n training accuracy:\t\t98.09%\nIteration 550: training...\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\nIteration 550: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient011/patient011_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient060/patient060_frame01_gt.nii.gz\nIteration 550 of 1000 took 0.339s\n training loss:\t\t0.066791\n training accuracy:\t\t97.62%\n validation loss: \t\t0.111327\n validation accuracy:\t\t96.25%\n validation Dice LV:\t\t0.438852\n validation Dice Myo:\t\t0.490684\n validation Dice RV:\t\t0.615959\n\nIteration 551: training...\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\nIteration 551 of 1000 took 0.288s\n training loss:\t\t0.041030\n training accuracy:\t\t98.63%\nIteration 552: training...\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\nIteration 552 of 1000 took 0.263s\n training loss:\t\t0.040474\n training accuracy:\t\t98.82%\nIteration 553: training...\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 553 of 1000 took 0.214s\n training loss:\t\t0.042429\n training accuracy:\t\t98.61%\nIteration 554: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 554 of 1000 took 0.189s\n training loss:\t\t0.035409\n training accuracy:\t\t98.77%\nIteration 555: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 555 of 1000 took 0.209s\n training loss:\t\t0.055950\n training accuracy:\t\t98.00%\nIteration 556: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\nIteration 556 of 1000 took 0.205s\n training loss:\t\t0.091626\n training accuracy:\t\t97.32%\nIteration 557: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\nIteration 557 of 1000 took 0.193s\n training loss:\t\t0.039021\n training accuracy:\t\t98.74%\nIteration 558: training...\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\nIteration 558 of 1000 took 0.226s\n training loss:\t\t0.055054\n training accuracy:\t\t98.32%\nIteration 559: training...\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 559 of 1000 took 0.259s\n training loss:\t\t0.044795\n training accuracy:\t\t98.46%\nIteration 560: training...\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01_gt.nii.gz\nIteration 560: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient070/patient070_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient070/patient070_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient004/patient004_frame01_gt.nii.gz\nIteration 560 of 1000 took 0.309s\n training loss:\t\t0.044620\n training accuracy:\t\t98.46%\n validation loss: \t\t0.196037\n validation accuracy:\t\t94.95%\n validation Dice LV:\t\t0.196495\n validation Dice Myo:\t\t0.312463\n validation Dice RV:\t\t0.466397\n\nIteration 561: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 561 of 1000 took 0.187s\n training loss:\t\t0.042404\n training accuracy:\t\t98.54%\nIteration 562: training...\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\nIteration 562 of 1000 took 0.268s\n training loss:\t\t0.033635\n training accuracy:\t\t98.96%\nIteration 563: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\nIteration 563 of 1000 took 0.234s\n training loss:\t\t0.072526\n training accuracy:\t\t97.26%\nIteration 564: training...\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 564 of 1000 took 0.227s\n training loss:\t\t0.063314\n training accuracy:\t\t97.73%\nIteration 565: training...\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\nIteration 565 of 1000 took 0.270s\n training loss:\t\t0.050254\n training accuracy:\t\t98.30%\nIteration 566: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\nIteration 566 of 1000 took 0.209s\n training loss:\t\t0.041476\n training accuracy:\t\t98.55%\nIteration 567: training...\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\nIteration 567 of 1000 took 1.167s\n training loss:\t\t0.047943\n training accuracy:\t\t98.38%\nIteration 568: training...\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\nIteration 568 of 1000 took 0.250s\n training loss:\t\t0.036343\n training accuracy:\t\t98.78%\nIteration 569: training...\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\nIteration 569 of 1000 took 0.300s\n training loss:\t\t0.032700\n training accuracy:\t\t98.97%\nIteration 570: training...\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01_gt.nii.gz\nIteration 570: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient076/patient076_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient076/patient076_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01_gt.nii.gz\nIteration 570 of 1000 took 0.314s\n training loss:\t\t0.043810\n training accuracy:\t\t98.47%\n validation loss: \t\t0.057604\n validation accuracy:\t\t97.95%\n validation Dice LV:\t\t0.645304\n validation Dice Myo:\t\t0.740031\n validation Dice RV:\t\t0.885322\n\nIteration 571: training...\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\nIteration 571 of 1000 took 0.265s\n training loss:\t\t0.049102\n training accuracy:\t\t98.35%\nIteration 572: training...\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 572 of 1000 took 0.212s\n training loss:\t\t0.134326\n training accuracy:\t\t95.36%\nIteration 573: training...\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\nIteration 573 of 1000 took 0.211s\n training loss:\t\t0.041746\n training accuracy:\t\t98.55%\nIteration 574: training...\n Select /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\nIteration 574 of 1000 took 0.206s\n training loss:\t\t0.061122\n training accuracy:\t\t97.79%\nIteration 575: training...\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\nIteration 575 of 1000 took 0.212s\n training loss:\t\t0.045965\n training accuracy:\t\t98.47%\nIteration 576: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\nIteration 576 of 1000 took 0.258s\n training loss:\t\t0.040392\n training accuracy:\t\t98.63%\nIteration 577: training...\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 577 of 1000 took 0.218s\n training loss:\t\t0.054076\n training accuracy:\t\t98.02%\nIteration 578: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\nIteration 578 of 1000 took 0.204s\n training loss:\t\t0.037397\n training accuracy:\t\t98.84%\nIteration 579: training...\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 579 of 1000 took 0.231s\n training loss:\t\t0.034176\n training accuracy:\t\t98.84%\nIteration 580: training...\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\nIteration 580: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient017/patient017_frame01_gt.nii.gz\nIteration 580 of 1000 took 0.294s\n training loss:\t\t0.075189\n training accuracy:\t\t97.18%\n validation loss: \t\t0.152702\n validation accuracy:\t\t95.55%\n validation Dice LV:\t\t0.176331\n validation Dice Myo:\t\t0.554303\n validation Dice RV:\t\t0.698433\n\nIteration 581: training...\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\nIteration 581 of 1000 took 0.232s\n training loss:\t\t0.050108\n training accuracy:\t\t98.29%\nIteration 582: training...\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\nIteration 582 of 1000 took 0.233s\n training loss:\t\t0.044980\n training accuracy:\t\t98.46%\nIteration 583: training...\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 583 of 1000 took 0.229s\n training loss:\t\t0.036105\n training accuracy:\t\t98.76%\nIteration 584: training...\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\nIteration 584 of 1000 took 0.192s\n training loss:\t\t0.036832\n training accuracy:\t\t98.83%\nIteration 585: training...\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\nIteration 585 of 1000 took 0.281s\n training loss:\t\t0.033957\n training accuracy:\t\t98.86%\nIteration 586: training...\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 586 of 1000 took 0.191s\n training loss:\t\t0.036836\n training accuracy:\t\t98.76%\nIteration 587: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\nIteration 587 of 1000 took 0.238s\n training loss:\t\t0.054157\n training accuracy:\t\t98.09%\nIteration 588: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\nIteration 588 of 1000 took 0.190s\n training loss:\t\t0.042413\n training accuracy:\t\t98.60%\nIteration 589: training...\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\nIteration 589 of 1000 took 0.225s\n training loss:\t\t0.031233\n training accuracy:\t\t98.95%\nIteration 590: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\nIteration 590: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient075/patient075_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient014/patient014_frame01_gt.nii.gz\nIteration 590 of 1000 took 0.328s\n training loss:\t\t0.040647\n training accuracy:\t\t98.71%\n validation loss: \t\t0.097645\n validation accuracy:\t\t96.85%\n validation Dice LV:\t\t0.503174\n validation Dice Myo:\t\t0.670481\n validation Dice RV:\t\t0.764511\n\nIteration 591: training...\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\nIteration 591 of 1000 took 0.219s\n training loss:\t\t0.038664\n training accuracy:\t\t98.71%\nIteration 592: training...\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\nIteration 592 of 1000 took 0.191s\n training loss:\t\t0.063116\n training accuracy:\t\t97.38%\nIteration 593: training...\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\nIteration 593 of 1000 took 0.206s\n training loss:\t\t0.034903\n training accuracy:\t\t98.79%\nIteration 594: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\nIteration 594 of 1000 took 0.219s\n training loss:\t\t0.048574\n training accuracy:\t\t98.23%\nIteration 595: training...\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 595 of 1000 took 0.226s\n training loss:\t\t0.039516\n training accuracy:\t\t98.60%\nIteration 596: training...\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\nIteration 596 of 1000 took 0.211s\n training loss:\t\t0.107394\n training accuracy:\t\t96.13%\nIteration 597: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\nIteration 597 of 1000 took 0.163s\n training loss:\t\t0.023694\n training accuracy:\t\t99.29%\nIteration 598: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\nIteration 598 of 1000 took 0.206s\n training loss:\t\t0.043940\n training accuracy:\t\t98.50%\nIteration 599: training...\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\nIteration 599 of 1000 took 0.181s\n training loss:\t\t0.031257\n training accuracy:\t\t99.03%\nIteration 600: training...\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\nIteration 600: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient048/patient048_frame01_gt.nii.gz\nIteration 600 of 1000 took 0.248s\n training loss:\t\t0.038065\n training accuracy:\t\t98.72%\n validation loss: \t\t0.047636\n validation accuracy:\t\t98.38%\n validation Dice LV:\t\t0.595196\n validation Dice Myo:\t\t0.716789\n validation Dice RV:\t\t0.813724\n\nIteration 601: training...\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\nIteration 601 of 1000 took 0.214s\n training loss:\t\t0.033823\n training accuracy:\t\t98.88%\nIteration 602: training...\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\nIteration 602 of 1000 took 0.219s\n training loss:\t\t0.096870\n training accuracy:\t\t96.31%\nIteration 603: training...\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\nIteration 603 of 1000 took 0.229s\n training loss:\t\t0.076081\n training accuracy:\t\t97.67%\nIteration 604: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 604 of 1000 took 0.224s\n training loss:\t\t0.037109\n training accuracy:\t\t98.66%\nIteration 605: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\nIteration 605 of 1000 took 0.188s\n training loss:\t\t0.037628\n training accuracy:\t\t98.73%\nIteration 606: training...\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\nIteration 606 of 1000 took 0.227s\n training loss:\t\t0.036460\n training accuracy:\t\t98.69%\nIteration 607: training...\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\nIteration 607 of 1000 took 0.211s\n training loss:\t\t0.039340\n training accuracy:\t\t98.69%\nIteration 608: training...\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01_gt.nii.gz\nIteration 608 of 1000 took 0.170s\n training loss:\t\t0.031924\n training accuracy:\t\t98.96%\nIteration 609: training...\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\nIteration 609 of 1000 took 0.230s\n training loss:\t\t0.036749\n training accuracy:\t\t98.71%\nIteration 610: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\nIteration 610: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01_gt.nii.gz\nIteration 610 of 1000 took 0.280s\n training loss:\t\t0.046334\n training accuracy:\t\t98.26%\n validation loss: \t\t0.059458\n validation accuracy:\t\t98.02%\n validation Dice LV:\t\t0.705999\n validation Dice Myo:\t\t0.695273\n validation Dice RV:\t\t0.861784\n\nIteration 611: training...\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\nIteration 611 of 1000 took 0.220s\n training loss:\t\t0.034747\n training accuracy:\t\t98.82%\nIteration 612: training...\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\nIteration 612 of 1000 took 0.173s\n training loss:\t\t0.052909\n training accuracy:\t\t98.19%\nIteration 613: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\nIteration 613 of 1000 took 0.231s\n training loss:\t\t0.038768\n training accuracy:\t\t98.66%\nIteration 614: training...\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\nIteration 614 of 1000 took 0.176s\n training loss:\t\t0.049270\n training accuracy:\t\t98.12%\nIteration 615: training...\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 615 of 1000 took 0.295s\n training loss:\t\t0.034999\n training accuracy:\t\t98.78%\nIteration 616: training...\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\nIteration 616 of 1000 took 0.197s\n training loss:\t\t0.027006\n training accuracy:\t\t99.16%\nIteration 617: training...\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01_gt.nii.gz\nIteration 617 of 1000 took 0.229s\n training loss:\t\t0.038202\n training accuracy:\t\t98.76%\nIteration 618: training...\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\nIteration 618 of 1000 took 0.230s\n training loss:\t\t0.188218\n training accuracy:\t\t93.65%\nIteration 619: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\nIteration 619 of 1000 took 0.201s\n training loss:\t\t0.032354\n training accuracy:\t\t99.01%\nIteration 620: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\nIteration 620: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient033/patient033_frame01_gt.nii.gz\nIteration 620 of 1000 took 0.312s\n training loss:\t\t0.029564\n training accuracy:\t\t99.04%\n validation loss: \t\t0.036092\n validation accuracy:\t\t98.90%\n validation Dice LV:\t\t0.802158\n validation Dice Myo:\t\t0.831804\n validation Dice RV:\t\t0.902197\n\nIteration 621: training...\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\nIteration 621 of 1000 took 0.207s\n training loss:\t\t0.039233\n training accuracy:\t\t98.65%\nIteration 622: training...\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\nIteration 622 of 1000 took 0.174s\n training loss:\t\t0.036862\n training accuracy:\t\t98.74%\nIteration 623: training...\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 623 of 1000 took 0.292s\n training loss:\t\t0.037732\n training accuracy:\t\t98.69%\nIteration 624: training...\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\nIteration 624 of 1000 took 0.214s\n training loss:\t\t0.041353\n training accuracy:\t\t98.52%\nIteration 625: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\nIteration 625 of 1000 took 0.231s\n training loss:\t\t0.041699\n training accuracy:\t\t98.72%\nIteration 626: training...\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\nIteration 626 of 1000 took 0.193s\n training loss:\t\t0.054494\n training accuracy:\t\t98.13%\nIteration 627: training...\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\nIteration 627 of 1000 took 0.264s\n training loss:\t\t0.038513\n training accuracy:\t\t98.72%\nIteration 628: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\nIteration 628 of 1000 took 0.215s\n training loss:\t\t0.032959\n training accuracy:\t\t98.90%\nIteration 629: training...\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\nIteration 629 of 1000 took 0.207s\n training loss:\t\t0.038861\n training accuracy:\t\t98.71%\nIteration 630: training...\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\nIteration 630: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient012/patient012_frame01_gt.nii.gz\nIteration 630 of 1000 took 0.277s\n training loss:\t\t0.033877\n training accuracy:\t\t98.81%\n validation loss: \t\t0.039261\n validation accuracy:\t\t98.65%\n validation Dice LV:\t\t0.870788\n validation Dice Myo:\t\t0.730741\n validation Dice RV:\t\t0.930185\n\nIteration 631: training...\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\nIteration 631 of 1000 took 0.298s\n training loss:\t\t0.034360\n training accuracy:\t\t98.95%\nIteration 632: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\nIteration 632 of 1000 took 0.246s\n training loss:\t\t0.030108\n training accuracy:\t\t99.02%\nIteration 633: training...\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\nIteration 633 of 1000 took 0.185s\n training loss:\t\t0.040321\n training accuracy:\t\t98.57%\nIteration 634: training...\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\nIteration 634 of 1000 took 0.247s\n training loss:\t\t0.038899\n training accuracy:\t\t98.78%\nIteration 635: training...\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\nIteration 635 of 1000 took 0.212s\n training loss:\t\t0.035365\n training accuracy:\t\t98.84%\nIteration 636: training...\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\nIteration 636 of 1000 took 0.224s\n training loss:\t\t0.037939\n training accuracy:\t\t98.63%\nIteration 637: training...\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\nIteration 637 of 1000 took 0.278s\n training loss:\t\t0.033682\n training accuracy:\t\t98.98%\nIteration 638: training...\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\nIteration 638 of 1000 took 0.212s\n training loss:\t\t0.035113\n training accuracy:\t\t98.87%\nIteration 639: training...\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 639 of 1000 took 0.237s\n training loss:\t\t0.045418\n training accuracy:\t\t98.34%\nIteration 640: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\nIteration 640: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient055/patient055_frame01_gt.nii.gz\nIteration 640 of 1000 took 0.262s\n training loss:\t\t0.039641\n training accuracy:\t\t98.59%\n validation loss: \t\t0.047626\n validation accuracy:\t\t98.42%\n validation Dice LV:\t\t0.887857\n validation Dice Myo:\t\t0.715881\n validation Dice RV:\t\t0.909374\n\nIteration 641: training...\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\nIteration 641 of 1000 took 0.216s\n training loss:\t\t0.035215\n training accuracy:\t\t98.78%\nIteration 642: training...\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01_gt.nii.gz\nIteration 642 of 1000 took 0.216s\n training loss:\t\t0.063014\n training accuracy:\t\t97.70%\nIteration 643: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 643 of 1000 took 0.209s\n training loss:\t\t0.033866\n training accuracy:\t\t98.89%\nIteration 644: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\nIteration 644 of 1000 took 0.290s\n training loss:\t\t0.030045\n training accuracy:\t\t98.96%\nIteration 645: training...\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 645 of 1000 took 0.212s\n training loss:\t\t0.031088\n training accuracy:\t\t98.98%\nIteration 646: training...\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\nIteration 646 of 1000 took 0.329s\n training loss:\t\t0.038280\n training accuracy:\t\t98.65%\nIteration 647: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 647 of 1000 took 0.212s\n training loss:\t\t0.029027\n training accuracy:\t\t99.02%\nIteration 648: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 648 of 1000 took 0.224s\n training loss:\t\t0.035312\n training accuracy:\t\t98.70%\nIteration 649: training...\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\nIteration 649 of 1000 took 0.203s\n training loss:\t\t0.030526\n training accuracy:\t\t98.97%\nIteration 650: training...\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 650: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient074/patient074_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient091/patient091_frame01_gt.nii.gz\nIteration 650 of 1000 took 0.277s\n training loss:\t\t0.028998\n training accuracy:\t\t98.99%\n validation loss: \t\t0.078536\n validation accuracy:\t\t97.23%\n validation Dice LV:\t\t0.631721\n validation Dice Myo:\t\t0.671571\n validation Dice RV:\t\t0.729168\n\nIteration 651: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\nIteration 651 of 1000 took 0.294s\n training loss:\t\t0.030086\n training accuracy:\t\t99.00%\nIteration 652: training...\n Select /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\nIteration 652 of 1000 took 0.171s\n training loss:\t\t0.032027\n training accuracy:\t\t98.88%\nIteration 653: training...\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 653 of 1000 took 0.219s\n training loss:\t\t0.082360\n training accuracy:\t\t97.10%\nIteration 654: training...\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 654 of 1000 took 0.190s\n training loss:\t\t0.028582\n training accuracy:\t\t98.98%\nIteration 655: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\nIteration 655 of 1000 took 0.167s\n training loss:\t\t0.051758\n training accuracy:\t\t98.04%\nIteration 656: training...\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\nIteration 656 of 1000 took 0.218s\n training loss:\t\t0.041979\n training accuracy:\t\t98.49%\nIteration 657: training...\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\nIteration 657 of 1000 took 0.181s\n training loss:\t\t0.059024\n training accuracy:\t\t97.75%\nIteration 658: training...\n Select /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 658 of 1000 took 0.228s\n training loss:\t\t0.029139\n training accuracy:\t\t98.91%\nIteration 659: training...\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 659 of 1000 took 0.227s\n training loss:\t\t0.033757\n training accuracy:\t\t98.90%\nIteration 660: training...\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\nIteration 660: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01_gt.nii.gz\nIteration 660 of 1000 took 0.257s\n training loss:\t\t0.032389\n training accuracy:\t\t98.85%\n validation loss: \t\t0.028637\n validation accuracy:\t\t99.01%\n validation Dice LV:\t\t0.883898\n validation Dice Myo:\t\t0.799387\n validation Dice RV:\t\t0.928038\n\nIteration 661: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\nIteration 661 of 1000 took 0.233s\n training loss:\t\t0.038233\n training accuracy:\t\t98.62%\nIteration 662: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\nIteration 662 of 1000 took 0.255s\n training loss:\t\t0.038004\n training accuracy:\t\t98.59%\nIteration 663: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\nIteration 663 of 1000 took 0.219s\n training loss:\t\t0.032207\n training accuracy:\t\t98.85%\nIteration 664: training...\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\nIteration 664 of 1000 took 0.213s\n training loss:\t\t0.043994\n training accuracy:\t\t98.43%\nIteration 665: training...\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 665 of 1000 took 0.223s\n training loss:\t\t0.064946\n training accuracy:\t\t97.58%\nIteration 666: training...\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\nIteration 666 of 1000 took 0.227s\n training loss:\t\t0.036584\n training accuracy:\t\t98.85%\nIteration 667: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 667 of 1000 took 0.209s\n training loss:\t\t0.039024\n training accuracy:\t\t98.70%\nIteration 668: training...\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\nIteration 668 of 1000 took 0.244s\n training loss:\t\t0.036712\n training accuracy:\t\t98.67%\nIteration 669: training...\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\nIteration 669 of 1000 took 0.210s\n training loss:\t\t0.053251\n training accuracy:\t\t98.32%\nIteration 670: training...\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\nIteration 670: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient013/patient013_frame01_gt.nii.gz\nIteration 670 of 1000 took 0.255s\n training loss:\t\t0.066602\n training accuracy:\t\t97.63%\n validation loss: \t\t0.026311\n validation accuracy:\t\t99.11%\n validation Dice LV:\t\t0.908095\n validation Dice Myo:\t\t0.878553\n validation Dice RV:\t\t0.952471\n\nIteration 671: training...\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 671 of 1000 took 0.208s\n training loss:\t\t0.029343\n training accuracy:\t\t99.01%\nIteration 672: training...\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01_gt.nii.gz\nIteration 672 of 1000 took 0.215s\n training loss:\t\t0.041567\n training accuracy:\t\t98.56%\nIteration 673: training...\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\nIteration 673 of 1000 took 0.265s\n training loss:\t\t0.038834\n training accuracy:\t\t98.70%\nIteration 674: training...\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\nIteration 674 of 1000 took 0.271s\n training loss:\t\t0.028316\n training accuracy:\t\t99.14%\nIteration 675: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\nIteration 675 of 1000 took 0.204s\n training loss:\t\t0.053731\n training accuracy:\t\t98.03%\nIteration 676: training...\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 676 of 1000 took 0.214s\n training loss:\t\t0.034637\n training accuracy:\t\t98.79%\nIteration 677: training...\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\nIteration 677 of 1000 took 0.217s\n training loss:\t\t0.044850\n training accuracy:\t\t98.30%\nIteration 678: training...\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\nIteration 678 of 1000 took 0.213s\n training loss:\t\t0.038357\n training accuracy:\t\t98.65%\nIteration 679: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\nIteration 679 of 1000 took 0.215s\n training loss:\t\t0.034439\n training accuracy:\t\t98.76%\nIteration 680: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\nIteration 680: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient062/patient062_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01_gt.nii.gz\nIteration 680 of 1000 took 0.286s\n training loss:\t\t0.030474\n training accuracy:\t\t98.94%\n validation loss: \t\t0.033576\n validation accuracy:\t\t98.86%\n validation Dice LV:\t\t0.896566\n validation Dice Myo:\t\t0.790325\n validation Dice RV:\t\t0.930715\n\nIteration 681: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\nIteration 681 of 1000 took 0.199s\n training loss:\t\t0.054088\n training accuracy:\t\t98.02%\nIteration 682: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\nIteration 682 of 1000 took 0.188s\n training loss:\t\t0.032057\n training accuracy:\t\t98.84%\nIteration 683: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\nIteration 683 of 1000 took 0.194s\n training loss:\t\t0.035443\n training accuracy:\t\t98.75%\nIteration 684: training...\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\nIteration 684 of 1000 took 0.202s\n training loss:\t\t0.026274\n training accuracy:\t\t99.11%\nIteration 685: training...\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\nIteration 685 of 1000 took 0.261s\n training loss:\t\t0.030420\n training accuracy:\t\t98.99%\nIteration 686: training...\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\nIteration 686 of 1000 took 0.219s\n training loss:\t\t0.034199\n training accuracy:\t\t98.80%\nIteration 687: training...\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\nIteration 687 of 1000 took 0.211s\n training loss:\t\t0.030910\n training accuracy:\t\t98.91%\nIteration 688: training...\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\nIteration 688 of 1000 took 0.333s\n training loss:\t\t0.037071\n training accuracy:\t\t98.70%\nIteration 689: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\nIteration 689 of 1000 took 0.205s\n training loss:\t\t0.036855\n training accuracy:\t\t98.72%\nIteration 690: training...\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 690: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient004/patient004_frame01_gt.nii.gz\nIteration 690 of 1000 took 0.316s\n training loss:\t\t0.028230\n training accuracy:\t\t98.99%\n validation loss: \t\t0.038304\n validation accuracy:\t\t98.70%\n validation Dice LV:\t\t0.870301\n validation Dice Myo:\t\t0.757832\n validation Dice RV:\t\t0.942541\n\nIteration 691: training...\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\nIteration 691 of 1000 took 0.225s\n training loss:\t\t0.030308\n training accuracy:\t\t98.92%\nIteration 692: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 692 of 1000 took 0.207s\n training loss:\t\t0.034169\n training accuracy:\t\t98.83%\nIteration 693: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\nIteration 693 of 1000 took 0.300s\n training loss:\t\t0.028504\n training accuracy:\t\t99.09%\nIteration 694: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\nIteration 694 of 1000 took 0.205s\n training loss:\t\t0.049786\n training accuracy:\t\t98.16%\nIteration 695: training...\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\nIteration 695 of 1000 took 0.193s\n training loss:\t\t0.158850\n training accuracy:\t\t94.51%\nIteration 696: training...\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\nIteration 696 of 1000 took 0.283s\n training loss:\t\t0.033842\n training accuracy:\t\t98.75%\nIteration 697: training...\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\nIteration 697 of 1000 took 0.233s\n training loss:\t\t0.034416\n training accuracy:\t\t98.76%\nIteration 698: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\nIteration 698 of 1000 took 0.234s\n training loss:\t\t0.031086\n training accuracy:\t\t98.97%\nIteration 699: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\nIteration 699 of 1000 took 0.174s\n training loss:\t\t0.055860\n training accuracy:\t\t97.99%\nIteration 700: training...\n Select /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\nIteration 700: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient028/patient028_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient094/patient094_frame01_gt.nii.gz\nIteration 700 of 1000 took 0.266s\n training loss:\t\t0.042116\n training accuracy:\t\t98.50%\n validation loss: \t\t0.078457\n validation accuracy:\t\t97.33%\n validation Dice LV:\t\t0.593385\n validation Dice Myo:\t\t0.596077\n validation Dice RV:\t\t0.735857\n\nIteration 701: training...\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\nIteration 701 of 1000 took 0.243s\n training loss:\t\t0.035790\n training accuracy:\t\t98.81%\nIteration 702: training...\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\nIteration 702 of 1000 took 0.209s\n training loss:\t\t0.032728\n training accuracy:\t\t98.88%\nIteration 703: training...\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\nIteration 703 of 1000 took 0.206s\n training loss:\t\t0.037539\n training accuracy:\t\t98.74%\nIteration 704: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 704 of 1000 took 0.204s\n training loss:\t\t0.029661\n training accuracy:\t\t99.02%\nIteration 705: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\nIteration 705 of 1000 took 0.207s\n training loss:\t\t0.032035\n training accuracy:\t\t98.88%\nIteration 706: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\nIteration 706 of 1000 took 0.159s\n training loss:\t\t0.035668\n training accuracy:\t\t98.87%\nIteration 707: training...\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\nIteration 707 of 1000 took 0.210s\n training loss:\t\t0.038832\n training accuracy:\t\t98.60%\nIteration 708: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\nIteration 708 of 1000 took 0.194s\n training loss:\t\t0.049813\n training accuracy:\t\t98.52%\nIteration 709: training...\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\nIteration 709 of 1000 took 0.193s\n training loss:\t\t0.040467\n training accuracy:\t\t98.58%\nIteration 710: training...\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\nIteration 710: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient042/patient042_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient025/patient025_frame01_gt.nii.gz\nIteration 710 of 1000 took 0.309s\n training loss:\t\t0.033366\n training accuracy:\t\t98.80%\n validation loss: \t\t0.041230\n validation accuracy:\t\t98.53%\n validation Dice LV:\t\t0.854269\n validation Dice Myo:\t\t0.758530\n validation Dice RV:\t\t0.945900\n\nIteration 711: training...\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\nIteration 711 of 1000 took 0.203s\n training loss:\t\t0.040448\n training accuracy:\t\t98.49%\nIteration 712: training...\n Select /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\nIteration 712 of 1000 took 0.214s\n training loss:\t\t0.039622\n training accuracy:\t\t98.57%\nIteration 713: training...\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient036/patient036_frame01_gt.nii.gz\nIteration 713 of 1000 took 0.201s\n training loss:\t\t0.044189\n training accuracy:\t\t98.38%\nIteration 714: training...\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\nIteration 714 of 1000 took 0.182s\n training loss:\t\t0.036331\n training accuracy:\t\t98.75%\nIteration 715: training...\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\nIteration 715 of 1000 took 0.227s\n training loss:\t\t0.034926\n training accuracy:\t\t98.76%\nIteration 716: training...\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 716 of 1000 took 0.209s\n training loss:\t\t0.025821\n training accuracy:\t\t99.14%\nIteration 717: training...\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\nIteration 717 of 1000 took 0.285s\n training loss:\t\t0.049107\n training accuracy:\t\t98.31%\nIteration 718: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\nIteration 718 of 1000 took 0.186s\n training loss:\t\t0.042426\n training accuracy:\t\t98.50%\nIteration 719: training...\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 719 of 1000 took 0.214s\n training loss:\t\t0.035623\n training accuracy:\t\t98.77%\nIteration 720: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\nIteration 720: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01_gt.nii.gz\nIteration 720 of 1000 took 0.254s\n training loss:\t\t0.046836\n training accuracy:\t\t98.37%\n validation loss: \t\t0.048363\n validation accuracy:\t\t98.34%\n validation Dice LV:\t\t0.804110\n validation Dice Myo:\t\t0.655107\n validation Dice RV:\t\t0.922731\n\nIteration 721: training...\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\nIteration 721 of 1000 took 0.202s\n training loss:\t\t0.031197\n training accuracy:\t\t98.89%\nIteration 722: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 722 of 1000 took 0.214s\n training loss:\t\t0.028906\n training accuracy:\t\t99.01%\nIteration 723: training...\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\nIteration 723 of 1000 took 0.203s\n training loss:\t\t0.028827\n training accuracy:\t\t99.01%\nIteration 724: training...\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\nIteration 724 of 1000 took 0.224s\n training loss:\t\t0.060661\n training accuracy:\t\t97.97%\nIteration 725: training...\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\nIteration 725 of 1000 took 0.198s\n training loss:\t\t0.057007\n training accuracy:\t\t97.93%\nIteration 726: training...\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\nIteration 726 of 1000 took 0.213s\n training loss:\t\t0.037417\n training accuracy:\t\t98.74%\nIteration 727: training...\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\nIteration 727 of 1000 took 0.306s\n training loss:\t\t0.029241\n training accuracy:\t\t99.00%\nIteration 728: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 728 of 1000 took 0.170s\n training loss:\t\t0.038154\n training accuracy:\t\t98.70%\nIteration 729: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\nIteration 729 of 1000 took 0.232s\n training loss:\t\t0.037650\n training accuracy:\t\t98.59%\nIteration 730: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 730: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient025/patient025_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient055/patient055_frame01_gt.nii.gz\nIteration 730 of 1000 took 0.254s\n training loss:\t\t0.020223\n training accuracy:\t\t99.33%\n validation loss: \t\t0.127867\n validation accuracy:\t\t95.79%\n validation Dice LV:\t\t0.443285\n validation Dice Myo:\t\t0.360526\n validation Dice RV:\t\t0.769225\n\nIteration 731: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 731 of 1000 took 0.208s\n training loss:\t\t0.031788\n training accuracy:\t\t98.88%\nIteration 732: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\nIteration 732 of 1000 took 0.223s\n training loss:\t\t0.035081\n training accuracy:\t\t98.67%\nIteration 733: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\nIteration 733 of 1000 took 0.228s\n training loss:\t\t0.039908\n training accuracy:\t\t98.52%\nIteration 734: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 734 of 1000 took 0.222s\n training loss:\t\t0.028147\n training accuracy:\t\t99.01%\nIteration 735: training...\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\nIteration 735 of 1000 took 0.260s\n training loss:\t\t0.025048\n training accuracy:\t\t99.20%\nIteration 736: training...\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\nIteration 736 of 1000 took 0.213s\n training loss:\t\t0.029974\n training accuracy:\t\t99.00%\nIteration 737: training...\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\nIteration 737 of 1000 took 0.238s\n training loss:\t\t0.024624\n training accuracy:\t\t99.15%\nIteration 738: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 738 of 1000 took 0.212s\n training loss:\t\t0.035714\n training accuracy:\t\t98.75%\nIteration 739: training...\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\nIteration 739 of 1000 took 0.203s\n training loss:\t\t0.029393\n training accuracy:\t\t99.05%\nIteration 740: training...\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\nIteration 740: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient009/patient009_frame01_gt.nii.gz\nIteration 740 of 1000 took 0.327s\n training loss:\t\t0.046721\n training accuracy:\t\t98.43%\n validation loss: \t\t0.028735\n validation accuracy:\t\t99.03%\n validation Dice LV:\t\t0.890969\n validation Dice Myo:\t\t0.832312\n validation Dice RV:\t\t0.966858\n\nIteration 741: training...\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\nIteration 741 of 1000 took 0.243s\n training loss:\t\t0.033333\n training accuracy:\t\t98.76%\nIteration 742: training...\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01_gt.nii.gz\nIteration 742 of 1000 took 0.192s\n training loss:\t\t0.029284\n training accuracy:\t\t98.95%\nIteration 743: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01_gt.nii.gz\nIteration 743 of 1000 took 0.162s\n training loss:\t\t0.028259\n training accuracy:\t\t99.02%\nIteration 744: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\nIteration 744 of 1000 took 0.204s\n training loss:\t\t0.022757\n training accuracy:\t\t99.27%\nIteration 745: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\nIteration 745 of 1000 took 0.176s\n training loss:\t\t0.027890\n training accuracy:\t\t99.03%\nIteration 746: training...\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\nIteration 746 of 1000 took 0.257s\n training loss:\t\t0.029062\n training accuracy:\t\t98.98%\nIteration 747: training...\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 747 of 1000 took 0.213s\n training loss:\t\t0.031592\n training accuracy:\t\t98.90%\nIteration 748: training...\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01_gt.nii.gz\nIteration 748 of 1000 took 0.225s\n training loss:\t\t0.022698\n training accuracy:\t\t99.26%\nIteration 749: training...\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\nIteration 749 of 1000 took 0.211s\n training loss:\t\t0.046107\n training accuracy:\t\t98.36%\nIteration 750: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\nIteration 750: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient023/patient023_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient025/patient025_frame01_gt.nii.gz\nIteration 750 of 1000 took 0.270s\n training loss:\t\t0.025430\n training accuracy:\t\t99.12%\n validation loss: \t\t0.045728\n validation accuracy:\t\t98.36%\n validation Dice LV:\t\t0.776086\n validation Dice Myo:\t\t0.782999\n validation Dice RV:\t\t0.923680\n\nIteration 751: training...\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 751 of 1000 took 0.277s\n training loss:\t\t0.030097\n training accuracy:\t\t98.93%\nIteration 752: training...\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\nIteration 752 of 1000 took 0.269s\n training loss:\t\t0.036533\n training accuracy:\t\t98.67%\nIteration 753: training...\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 753 of 1000 took 0.210s\n training loss:\t\t0.022145\n training accuracy:\t\t99.23%\nIteration 754: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\nIteration 754 of 1000 took 0.295s\n training loss:\t\t0.024298\n training accuracy:\t\t99.20%\nIteration 755: training...\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\nIteration 755 of 1000 took 0.187s\n training loss:\t\t0.031678\n training accuracy:\t\t98.93%\nIteration 756: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\nIteration 756 of 1000 took 0.210s\n training loss:\t\t0.029973\n training accuracy:\t\t98.97%\nIteration 757: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 757 of 1000 took 0.229s\n training loss:\t\t0.037628\n training accuracy:\t\t98.64%\nIteration 758: training...\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\nIteration 758 of 1000 took 0.218s\n training loss:\t\t0.039701\n training accuracy:\t\t98.49%\nIteration 759: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\nIteration 759 of 1000 took 0.179s\n training loss:\t\t0.039363\n training accuracy:\t\t98.64%\nIteration 760: training...\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\nIteration 760: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient011/patient011_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01_gt.nii.gz\nIteration 760 of 1000 took 0.282s\n training loss:\t\t0.035176\n training accuracy:\t\t98.77%\n validation loss: \t\t0.030517\n validation accuracy:\t\t98.76%\n validation Dice LV:\t\t0.789955\n validation Dice Myo:\t\t0.793041\n validation Dice RV:\t\t0.950482\n\nIteration 761: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\nIteration 761 of 1000 took 0.194s\n training loss:\t\t0.036337\n training accuracy:\t\t98.61%\nIteration 762: training...\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 762 of 1000 took 0.203s\n training loss:\t\t0.030467\n training accuracy:\t\t98.92%\nIteration 763: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 763 of 1000 took 0.230s\n training loss:\t\t0.033031\n training accuracy:\t\t98.84%\nIteration 764: training...\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\nIteration 764 of 1000 took 0.219s\n training loss:\t\t0.034093\n training accuracy:\t\t98.71%\nIteration 765: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\nIteration 765 of 1000 took 0.206s\n training loss:\t\t0.022272\n training accuracy:\t\t99.28%\nIteration 766: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01_gt.nii.gz\nIteration 766 of 1000 took 0.230s\n training loss:\t\t0.025893\n training accuracy:\t\t99.11%\nIteration 767: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\nIteration 767 of 1000 took 0.191s\n training loss:\t\t0.024444\n training accuracy:\t\t99.10%\nIteration 768: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\nIteration 768 of 1000 took 0.220s\n training loss:\t\t0.025502\n training accuracy:\t\t99.05%\nIteration 769: training...\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\nIteration 769 of 1000 took 0.198s\n training loss:\t\t0.026254\n training accuracy:\t\t99.07%\nIteration 770: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 770: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient002/patient002_frame01_gt.nii.gz\nIteration 770 of 1000 took 0.251s\n training loss:\t\t0.031144\n training accuracy:\t\t98.93%\n validation loss: \t\t0.037331\n validation accuracy:\t\t98.62%\n validation Dice LV:\t\t0.788290\n validation Dice Myo:\t\t0.740942\n validation Dice RV:\t\t0.941253\n\nIteration 771: training...\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\nIteration 771 of 1000 took 0.188s\n training loss:\t\t0.025184\n training accuracy:\t\t99.09%\nIteration 772: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\nIteration 772 of 1000 took 0.234s\n training loss:\t\t0.027212\n training accuracy:\t\t99.05%\nIteration 773: training...\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 773 of 1000 took 0.226s\n training loss:\t\t0.022207\n training accuracy:\t\t99.24%\nIteration 774: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\nIteration 774 of 1000 took 0.211s\n training loss:\t\t0.029781\n training accuracy:\t\t98.90%\nIteration 775: training...\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\nIteration 775 of 1000 took 0.230s\n training loss:\t\t0.036791\n training accuracy:\t\t98.65%\nIteration 776: training...\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 776 of 1000 took 0.192s\n training loss:\t\t0.030064\n training accuracy:\t\t98.99%\nIteration 777: training...\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\nIteration 777 of 1000 took 0.286s\n training loss:\t\t0.023202\n training accuracy:\t\t99.19%\nIteration 778: training...\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\nIteration 778 of 1000 took 0.215s\n training loss:\t\t0.048822\n training accuracy:\t\t98.17%\nIteration 779: training...\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\nIteration 779 of 1000 took 0.280s\n training loss:\t\t0.051584\n training accuracy:\t\t98.16%\nIteration 780: training...\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\nIteration 780: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient062/patient062_frame01_gt.nii.gz\nIteration 780 of 1000 took 0.278s\n training loss:\t\t0.022990\n training accuracy:\t\t99.28%\n validation loss: \t\t0.037853\n validation accuracy:\t\t98.66%\n validation Dice LV:\t\t0.871771\n validation Dice Myo:\t\t0.785089\n validation Dice RV:\t\t0.964950\n\nIteration 781: training...\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\nIteration 781 of 1000 took 0.229s\n training loss:\t\t0.027318\n training accuracy:\t\t98.99%\nIteration 782: training...\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\nIteration 782 of 1000 took 0.182s\n training loss:\t\t0.062470\n training accuracy:\t\t97.78%\nIteration 783: training...\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\nIteration 783 of 1000 took 0.262s\n training loss:\t\t0.021700\n training accuracy:\t\t99.26%\nIteration 784: training...\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\nIteration 784 of 1000 took 0.189s\n training loss:\t\t0.022587\n training accuracy:\t\t99.21%\nIteration 785: training...\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\nIteration 785 of 1000 took 0.205s\n training loss:\t\t0.033626\n training accuracy:\t\t98.67%\nIteration 786: training...\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\nIteration 786 of 1000 took 0.243s\n training loss:\t\t0.052894\n training accuracy:\t\t98.01%\nIteration 787: training...\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\nIteration 787 of 1000 took 0.227s\n training loss:\t\t0.051050\n training accuracy:\t\t98.12%\nIteration 788: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\nIteration 788 of 1000 took 0.248s\n training loss:\t\t0.029049\n training accuracy:\t\t98.91%\nIteration 789: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\nIteration 789 of 1000 took 0.265s\n training loss:\t\t0.042644\n training accuracy:\t\t98.42%\nIteration 790: training...\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\nIteration 790: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient028/patient028_frame01_gt.nii.gz\nIteration 790 of 1000 took 0.284s\n training loss:\t\t0.037812\n training accuracy:\t\t98.62%\n validation loss: \t\t0.026045\n validation accuracy:\t\t99.07%\n validation Dice LV:\t\t0.865721\n validation Dice Myo:\t\t0.791648\n validation Dice RV:\t\t0.951289\n\nIteration 791: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\nIteration 791 of 1000 took 0.233s\n training loss:\t\t0.028238\n training accuracy:\t\t99.00%\nIteration 792: training...\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 792 of 1000 took 0.216s\n training loss:\t\t0.047127\n training accuracy:\t\t98.18%\nIteration 793: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 793 of 1000 took 0.233s\n training loss:\t\t0.044042\n training accuracy:\t\t98.37%\nIteration 794: training...\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient038/patient038_frame01_gt.nii.gz\nIteration 794 of 1000 took 0.203s\n training loss:\t\t0.069110\n training accuracy:\t\t97.30%\nIteration 795: training...\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\nIteration 795 of 1000 took 0.223s\n training loss:\t\t0.058598\n training accuracy:\t\t97.95%\nIteration 796: training...\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\nIteration 796 of 1000 took 0.202s\n training loss:\t\t0.049834\n training accuracy:\t\t98.20%\nIteration 797: training...\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 797 of 1000 took 0.210s\n training loss:\t\t0.032950\n training accuracy:\t\t98.76%\nIteration 798: training...\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 798 of 1000 took 0.199s\n training loss:\t\t0.026817\n training accuracy:\t\t99.02%\nIteration 799: training...\n Select /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\nIteration 799 of 1000 took 0.227s\n training loss:\t\t0.032397\n training accuracy:\t\t98.91%\nIteration 800: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\nIteration 800: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient097/patient097_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient002/patient002_frame01_gt.nii.gz\nIteration 800 of 1000 took 0.386s\n training loss:\t\t0.028298\n training accuracy:\t\t98.98%\n validation loss: \t\t0.024961\n validation accuracy:\t\t99.12%\n validation Dice LV:\t\t0.941531\n validation Dice Myo:\t\t0.814536\n validation Dice RV:\t\t0.951636\n\nIteration 801: training...\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 801 of 1000 took 0.190s\n training loss:\t\t0.029847\n training accuracy:\t\t98.88%\nIteration 802: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\nIteration 802 of 1000 took 0.233s\n training loss:\t\t0.022147\n training accuracy:\t\t99.28%\nIteration 803: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\nIteration 803 of 1000 took 0.248s\n training loss:\t\t0.035951\n training accuracy:\t\t98.69%\nIteration 804: training...\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 804 of 1000 took 0.226s\n training loss:\t\t0.035340\n training accuracy:\t\t98.66%\nIteration 805: training...\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\nIteration 805 of 1000 took 0.224s\n training loss:\t\t0.052509\n training accuracy:\t\t97.92%\nIteration 806: training...\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\nIteration 806 of 1000 took 0.235s\n training loss:\t\t0.181293\n training accuracy:\t\t93.99%\nIteration 807: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\nIteration 807 of 1000 took 0.183s\n training loss:\t\t0.043649\n training accuracy:\t\t98.40%\nIteration 808: training...\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 808 of 1000 took 0.200s\n training loss:\t\t0.031154\n training accuracy:\t\t98.98%\nIteration 809: training...\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient039/patient039_frame01_gt.nii.gz\nIteration 809 of 1000 took 0.189s\n training loss:\t\t0.037361\n training accuracy:\t\t98.78%\nIteration 810: training...\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 810: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient008/patient008_frame01_gt.nii.gz\nIteration 810 of 1000 took 0.293s\n training loss:\t\t0.038376\n training accuracy:\t\t98.61%\n validation loss: \t\t0.079426\n validation accuracy:\t\t97.16%\n validation Dice LV:\t\t0.676316\n validation Dice Myo:\t\t0.534740\n validation Dice RV:\t\t0.848013\n\nIteration 811: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\nIteration 811 of 1000 took 0.169s\n training loss:\t\t0.039582\n training accuracy:\t\t98.57%\nIteration 812: training...\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\nIteration 812 of 1000 took 0.245s\n training loss:\t\t0.038930\n training accuracy:\t\t98.63%\nIteration 813: training...\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\nIteration 813 of 1000 took 0.191s\n training loss:\t\t0.093434\n training accuracy:\t\t96.13%\nIteration 814: training...\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\nIteration 814 of 1000 took 0.211s\n training loss:\t\t0.039440\n training accuracy:\t\t98.55%\nIteration 815: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\nIteration 815 of 1000 took 0.226s\n training loss:\t\t0.030166\n training accuracy:\t\t98.98%\nIteration 816: training...\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\nIteration 816 of 1000 took 0.231s\n training loss:\t\t0.035030\n training accuracy:\t\t98.79%\nIteration 817: training...\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\nIteration 817 of 1000 took 0.167s\n training loss:\t\t0.036449\n training accuracy:\t\t98.73%\nIteration 818: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 818 of 1000 took 0.206s\n training loss:\t\t0.026674\n training accuracy:\t\t99.09%\nIteration 819: training...\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\nIteration 819 of 1000 took 0.184s\n training loss:\t\t0.045783\n training accuracy:\t\t98.39%\nIteration 820: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\nIteration 820: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient017/patient017_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient099/patient099_frame01_gt.nii.gz\nIteration 820 of 1000 took 0.301s\n training loss:\t\t0.030645\n training accuracy:\t\t98.97%\n validation loss: \t\t0.066742\n validation accuracy:\t\t97.39%\n validation Dice LV:\t\t0.570109\n validation Dice Myo:\t\t0.625628\n validation Dice RV:\t\t0.892152\n\nIteration 821: training...\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\nIteration 821 of 1000 took 0.280s\n training loss:\t\t0.030415\n training accuracy:\t\t98.90%\nIteration 822: training...\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\nIteration 822 of 1000 took 0.209s\n training loss:\t\t0.034140\n training accuracy:\t\t98.81%\nIteration 823: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\nIteration 823 of 1000 took 0.210s\n training loss:\t\t0.029161\n training accuracy:\t\t98.92%\nIteration 824: training...\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\nIteration 824 of 1000 took 0.217s\n training loss:\t\t0.032383\n training accuracy:\t\t98.86%\nIteration 825: training...\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 825 of 1000 took 0.279s\n training loss:\t\t0.041765\n training accuracy:\t\t98.44%\nIteration 826: training...\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\nIteration 826 of 1000 took 1.283s\n training loss:\t\t0.033184\n training accuracy:\t\t98.84%\nIteration 827: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 827 of 1000 took 0.200s\n training loss:\t\t0.048354\n training accuracy:\t\t98.30%\nIteration 828: training...\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\nIteration 828 of 1000 took 0.205s\n training loss:\t\t0.028390\n training accuracy:\t\t99.01%\nIteration 829: training...\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\nIteration 829 of 1000 took 0.215s\n training loss:\t\t0.028688\n training accuracy:\t\t99.00%\nIteration 830: training...\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 830: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient056/patient056_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient039/patient039_frame01_gt.nii.gz\nIteration 830 of 1000 took 0.288s\n training loss:\t\t0.024410\n training accuracy:\t\t99.13%\n validation loss: \t\t0.053300\n validation accuracy:\t\t97.85%\n validation Dice LV:\t\t0.752886\n validation Dice Myo:\t\t0.597192\n validation Dice RV:\t\t0.887538\n\nIteration 831: training...\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\nIteration 831 of 1000 took 0.228s\n training loss:\t\t0.037474\n training accuracy:\t\t98.64%\nIteration 832: training...\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\nIteration 832 of 1000 took 0.287s\n training loss:\t\t0.027255\n training accuracy:\t\t99.03%\nIteration 833: training...\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\nIteration 833 of 1000 took 0.175s\n training loss:\t\t0.020125\n training accuracy:\t\t99.35%\nIteration 834: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\nIteration 834 of 1000 took 0.201s\n training loss:\t\t0.025259\n training accuracy:\t\t99.17%\nIteration 835: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 835 of 1000 took 0.232s\n training loss:\t\t0.040646\n training accuracy:\t\t98.44%\nIteration 836: training...\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\nIteration 836 of 1000 took 0.196s\n training loss:\t\t0.028573\n training accuracy:\t\t99.01%\nIteration 837: training...\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 837 of 1000 took 0.229s\n training loss:\t\t0.031332\n training accuracy:\t\t98.89%\nIteration 838: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01_gt.nii.gz\nIteration 838 of 1000 took 0.197s\n training loss:\t\t0.042190\n training accuracy:\t\t98.59%\nIteration 839: training...\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\nIteration 839 of 1000 took 0.174s\n training loss:\t\t0.027965\n training accuracy:\t\t98.99%\nIteration 840: training...\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\nIteration 840: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient060/patient060_frame01_gt.nii.gz\nIteration 840 of 1000 took 0.274s\n training loss:\t\t0.032586\n training accuracy:\t\t98.90%\n validation loss: \t\t0.028781\n validation accuracy:\t\t98.86%\n validation Dice LV:\t\t0.854145\n validation Dice Myo:\t\t0.766093\n validation Dice RV:\t\t0.931249\n\nIteration 841: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 841 of 1000 took 0.260s\n training loss:\t\t0.027269\n training accuracy:\t\t99.07%\nIteration 842: training...\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\nIteration 842 of 1000 took 0.224s\n training loss:\t\t0.030032\n training accuracy:\t\t99.02%\nIteration 843: training...\n Select /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient047/patient047_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 843 of 1000 took 0.223s\n training loss:\t\t0.048834\n training accuracy:\t\t98.27%\nIteration 844: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 844 of 1000 took 0.178s\n training loss:\t\t0.053395\n training accuracy:\t\t98.12%\nIteration 845: training...\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\nIteration 845 of 1000 took 0.214s\n training loss:\t\t0.054607\n training accuracy:\t\t98.00%\nIteration 846: training...\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\nIteration 846 of 1000 took 0.157s\n training loss:\t\t0.027743\n training accuracy:\t\t99.00%\nIteration 847: training...\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\nIteration 847 of 1000 took 0.216s\n training loss:\t\t0.030005\n training accuracy:\t\t98.88%\nIteration 848: training...\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient082/patient082_frame01_gt.nii.gz\nIteration 848 of 1000 took 0.287s\n training loss:\t\t0.023361\n training accuracy:\t\t99.20%\nIteration 849: training...\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\nIteration 849 of 1000 took 0.241s\n training loss:\t\t0.147436\n training accuracy:\t\t94.75%\nIteration 850: training...\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\nIteration 850: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient071/patient071_frame01_gt.nii.gz\nIteration 850 of 1000 took 0.328s\n training loss:\t\t0.031504\n training accuracy:\t\t98.88%\n validation loss: \t\t0.055318\n validation accuracy:\t\t98.16%\n validation Dice LV:\t\t0.653300\n validation Dice Myo:\t\t0.552363\n validation Dice RV:\t\t0.897904\n\nIteration 851: training...\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\nIteration 851 of 1000 took 0.191s\n training loss:\t\t0.028023\n training accuracy:\t\t98.99%\nIteration 852: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01_gt.nii.gz\nIteration 852 of 1000 took 0.214s\n training loss:\t\t0.028612\n training accuracy:\t\t98.99%\nIteration 853: training...\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\nIteration 853 of 1000 took 0.235s\n training loss:\t\t0.034201\n training accuracy:\t\t98.75%\nIteration 854: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 854 of 1000 took 0.175s\n training loss:\t\t0.026835\n training accuracy:\t\t99.04%\nIteration 855: training...\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\nIteration 855 of 1000 took 0.162s\n training loss:\t\t0.039883\n training accuracy:\t\t98.62%\nIteration 856: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 856 of 1000 took 0.209s\n training loss:\t\t0.028888\n training accuracy:\t\t99.04%\nIteration 857: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\nIteration 857 of 1000 took 0.232s\n training loss:\t\t0.031150\n training accuracy:\t\t98.92%\nIteration 858: training...\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient012/patient012_frame01_gt.nii.gz\nIteration 858 of 1000 took 0.205s\n training loss:\t\t0.038834\n training accuracy:\t\t98.64%\nIteration 859: training...\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\nIteration 859 of 1000 took 0.258s\n training loss:\t\t0.033035\n training accuracy:\t\t98.97%\nIteration 860: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\nIteration 860: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient054/patient054_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient097/patient097_frame01_gt.nii.gz\nIteration 860 of 1000 took 0.293s\n training loss:\t\t0.040049\n training accuracy:\t\t98.61%\n validation loss: \t\t0.072481\n validation accuracy:\t\t97.31%\n validation Dice LV:\t\t0.573253\n validation Dice Myo:\t\t0.585716\n validation Dice RV:\t\t0.855922\n\nIteration 861: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\nIteration 861 of 1000 took 0.216s\n training loss:\t\t0.033093\n training accuracy:\t\t98.81%\nIteration 862: training...\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\nIteration 862 of 1000 took 0.286s\n training loss:\t\t0.025555\n training accuracy:\t\t99.13%\nIteration 863: training...\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\nIteration 863 of 1000 took 0.278s\n training loss:\t\t0.040099\n training accuracy:\t\t98.51%\nIteration 864: training...\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\nIteration 864 of 1000 took 0.199s\n training loss:\t\t0.033588\n training accuracy:\t\t98.81%\nIteration 865: training...\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\nIteration 865 of 1000 took 0.169s\n training loss:\t\t0.022799\n training accuracy:\t\t99.22%\nIteration 866: training...\n Select /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient054/patient054_frame01_gt.nii.gz\nIteration 866 of 1000 took 0.191s\n training loss:\t\t0.034206\n training accuracy:\t\t98.70%\nIteration 867: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\nIteration 867 of 1000 took 0.216s\n training loss:\t\t0.035560\n training accuracy:\t\t98.67%\nIteration 868: training...\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\nIteration 868 of 1000 took 0.195s\n training loss:\t\t0.033388\n training accuracy:\t\t98.70%\nIteration 869: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\nIteration 869 of 1000 took 0.208s\n training loss:\t\t0.025621\n training accuracy:\t\t99.13%\nIteration 870: training...\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\nIteration 870: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient026/patient026_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient095/patient095_frame01_gt.nii.gz\nIteration 870 of 1000 took 0.300s\n training loss:\t\t0.102781\n training accuracy:\t\t96.08%\n validation loss: \t\t0.035783\n validation accuracy:\t\t98.74%\n validation Dice LV:\t\t0.896636\n validation Dice Myo:\t\t0.797326\n validation Dice RV:\t\t0.938778\n\nIteration 871: training...\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\nIteration 871 of 1000 took 0.233s\n training loss:\t\t0.039320\n training accuracy:\t\t98.53%\nIteration 872: training...\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 872 of 1000 took 0.274s\n training loss:\t\t0.037418\n training accuracy:\t\t98.60%\nIteration 873: training...\n Select /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 873 of 1000 took 0.171s\n training loss:\t\t0.023419\n training accuracy:\t\t99.20%\nIteration 874: training...\n Select /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient042/patient042_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\nIteration 874 of 1000 took 0.212s\n training loss:\t\t0.028593\n training accuracy:\t\t99.04%\nIteration 875: training...\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\nIteration 875 of 1000 took 0.282s\n training loss:\t\t0.022619\n training accuracy:\t\t99.22%\nIteration 876: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\nIteration 876 of 1000 took 0.200s\n training loss:\t\t0.041918\n training accuracy:\t\t98.50%\nIteration 877: training...\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\nIteration 877 of 1000 took 0.190s\n training loss:\t\t0.025598\n training accuracy:\t\t99.12%\nIteration 878: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\nIteration 878 of 1000 took 0.209s\n training loss:\t\t0.025546\n training accuracy:\t\t99.07%\nIteration 879: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\nIteration 879 of 1000 took 0.186s\n training loss:\t\t0.019991\n training accuracy:\t\t99.33%\nIteration 880: training...\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\nIteration 880: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient030/patient030_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient086/patient086_frame01_gt.nii.gz\nIteration 880 of 1000 took 0.262s\n training loss:\t\t0.031772\n training accuracy:\t\t98.80%\n validation loss: \t\t0.034841\n validation accuracy:\t\t98.83%\n validation Dice LV:\t\t0.879060\n validation Dice Myo:\t\t0.750127\n validation Dice RV:\t\t0.908387\n\nIteration 881: training...\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 881 of 1000 took 0.236s\n training loss:\t\t0.141580\n training accuracy:\t\t95.48%\nIteration 882: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient077/patient077_frame01_gt.nii.gz\nIteration 882 of 1000 took 0.204s\n training loss:\t\t0.042567\n training accuracy:\t\t98.50%\nIteration 883: training...\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\nIteration 883 of 1000 took 0.259s\n training loss:\t\t0.021874\n training accuracy:\t\t99.23%\nIteration 884: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\nIteration 884 of 1000 took 0.204s\n training loss:\t\t0.198823\n training accuracy:\t\t93.97%\nIteration 885: training...\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\nIteration 885 of 1000 took 0.210s\n training loss:\t\t0.022061\n training accuracy:\t\t99.20%\nIteration 886: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\nIteration 886 of 1000 took 0.204s\n training loss:\t\t0.038075\n training accuracy:\t\t98.51%\nIteration 887: training...\n Select /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient070/patient070_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\nIteration 887 of 1000 took 0.243s\n training loss:\t\t0.031281\n training accuracy:\t\t98.93%\nIteration 888: training...\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\nIteration 888 of 1000 took 0.219s\n training loss:\t\t0.034563\n training accuracy:\t\t98.90%\nIteration 889: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 889 of 1000 took 0.200s\n training loss:\t\t0.044625\n training accuracy:\t\t98.56%\nIteration 890: training...\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient046/patient046_frame01_gt.nii.gz\nIteration 890: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient031/patient031_frame01_gt.nii.gz\nIteration 890 of 1000 took 0.304s\n training loss:\t\t0.066308\n training accuracy:\t\t97.60%\n validation loss: \t\t0.045610\n validation accuracy:\t\t98.48%\n validation Dice LV:\t\t0.820748\n validation Dice Myo:\t\t0.834042\n validation Dice RV:\t\t0.901416\n\nIteration 891: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 891 of 1000 took 0.206s\n training loss:\t\t0.045565\n training accuracy:\t\t98.30%\nIteration 892: training...\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\nIteration 892 of 1000 took 0.279s\n training loss:\t\t0.075278\n training accuracy:\t\t97.33%\nIteration 893: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\nIteration 893 of 1000 took 0.198s\n training loss:\t\t0.036380\n training accuracy:\t\t98.80%\nIteration 894: training...\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\nIteration 894 of 1000 took 0.307s\n training loss:\t\t0.035943\n training accuracy:\t\t98.84%\nIteration 895: training...\n Select /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient009/patient009_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\nIteration 895 of 1000 took 0.230s\n training loss:\t\t0.052569\n training accuracy:\t\t98.07%\nIteration 896: training...\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\nIteration 896 of 1000 took 0.180s\n training loss:\t\t0.029780\n training accuracy:\t\t99.03%\nIteration 897: training...\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\nIteration 897 of 1000 took 0.271s\n training loss:\t\t0.043368\n training accuracy:\t\t98.39%\nIteration 898: training...\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\nIteration 898 of 1000 took 0.206s\n training loss:\t\t0.054618\n training accuracy:\t\t98.05%\nIteration 899: training...\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 899 of 1000 took 0.209s\n training loss:\t\t0.042907\n training accuracy:\t\t98.53%\nIteration 900: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\nIteration 900: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient086/patient086_frame01_gt.nii.gz\nIteration 900 of 1000 took 0.270s\n training loss:\t\t0.030763\n training accuracy:\t\t98.94%\n validation loss: \t\t0.036851\n validation accuracy:\t\t98.78%\n validation Dice LV:\t\t0.888783\n validation Dice Myo:\t\t0.591823\n validation Dice RV:\t\t0.918059\n\nIteration 901: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 901 of 1000 took 0.221s\n training loss:\t\t0.069218\n training accuracy:\t\t97.52%\nIteration 902: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\nIteration 902 of 1000 took 0.200s\n training loss:\t\t0.023907\n training accuracy:\t\t99.22%\nIteration 903: training...\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient035/patient035_frame01_gt.nii.gz\nIteration 903 of 1000 took 0.253s\n training loss:\t\t0.028032\n training accuracy:\t\t98.98%\nIteration 904: training...\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\nIteration 904 of 1000 took 0.208s\n training loss:\t\t0.028442\n training accuracy:\t\t98.99%\nIteration 905: training...\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\nIteration 905 of 1000 took 0.211s\n training loss:\t\t0.023799\n training accuracy:\t\t99.17%\nIteration 906: training...\n Select /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient008/patient008_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 906 of 1000 took 0.225s\n training loss:\t\t0.027477\n training accuracy:\t\t99.06%\nIteration 907: training...\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 907 of 1000 took 0.198s\n training loss:\t\t0.068416\n training accuracy:\t\t97.44%\nIteration 908: training...\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\nIteration 908 of 1000 took 0.176s\n training loss:\t\t0.042084\n training accuracy:\t\t98.44%\nIteration 909: training...\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\nIteration 909 of 1000 took 0.232s\n training loss:\t\t0.020335\n training accuracy:\t\t99.31%\nIteration 910: training...\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\nIteration 910: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient051/patient051_frame01_gt.nii.gz\nIteration 910 of 1000 took 0.288s\n training loss:\t\t0.028790\n training accuracy:\t\t98.98%\n validation loss: \t\t0.057607\n validation accuracy:\t\t97.93%\n validation Dice LV:\t\t0.654992\n validation Dice Myo:\t\t0.638976\n validation Dice RV:\t\t0.822709\n\nIteration 911: training...\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient060/patient060_frame01_gt.nii.gz\nIteration 911 of 1000 took 0.220s\n training loss:\t\t0.058444\n training accuracy:\t\t98.00%\nIteration 912: training...\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\nIteration 912 of 1000 took 0.216s\n training loss:\t\t0.042629\n training accuracy:\t\t98.43%\nIteration 913: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient063/patient063_frame01_gt.nii.gz\nIteration 913 of 1000 took 0.180s\n training loss:\t\t0.036431\n training accuracy:\t\t98.75%\nIteration 914: training...\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\nIteration 914 of 1000 took 0.295s\n training loss:\t\t0.026755\n training accuracy:\t\t99.07%\nIteration 915: training...\n Select /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient069/patient069_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 915 of 1000 took 0.176s\n training loss:\t\t0.022275\n training accuracy:\t\t99.18%\nIteration 916: training...\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\nIteration 916 of 1000 took 0.224s\n training loss:\t\t0.030538\n training accuracy:\t\t98.98%\nIteration 917: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01_gt.nii.gz\nIteration 917 of 1000 took 0.229s\n training loss:\t\t0.026632\n training accuracy:\t\t99.02%\nIteration 918: training...\n Select /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient065/patient065_frame01_gt.nii.gz\nIteration 918 of 1000 took 0.189s\n training loss:\t\t0.024670\n training accuracy:\t\t99.13%\nIteration 919: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\nIteration 919 of 1000 took 0.181s\n training loss:\t\t0.023360\n training accuracy:\t\t99.11%\nIteration 920: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 920: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient049/patient049_frame01_gt.nii.gz\nIteration 920 of 1000 took 0.280s\n training loss:\t\t0.022197\n training accuracy:\t\t99.24%\n validation loss: \t\t0.030521\n validation accuracy:\t\t98.84%\n validation Dice LV:\t\t0.832844\n validation Dice Myo:\t\t0.828377\n validation Dice RV:\t\t0.925349\n\nIteration 921: training...\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\nIteration 921 of 1000 took 0.233s\n training loss:\t\t0.047212\n training accuracy:\t\t98.21%\nIteration 922: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\nIteration 922 of 1000 took 0.185s\n training loss:\t\t0.036885\n training accuracy:\t\t98.73%\nIteration 923: training...\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient033/patient033_frame01_gt.nii.gz\nIteration 923 of 1000 took 0.182s\n training loss:\t\t0.038151\n training accuracy:\t\t98.95%\nIteration 924: training...\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient093/patient093_frame01_gt.nii.gz\nIteration 924 of 1000 took 0.210s\n training loss:\t\t0.057573\n training accuracy:\t\t98.14%\nIteration 925: training...\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient059/patient059_frame01_gt.nii.gz\nIteration 925 of 1000 took 0.269s\n training loss:\t\t0.025373\n training accuracy:\t\t99.10%\nIteration 926: training...\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\nIteration 926 of 1000 took 0.203s\n training loss:\t\t0.030938\n training accuracy:\t\t98.84%\nIteration 927: training...\n Select /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient043/patient043_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\nIteration 927 of 1000 took 0.245s\n training loss:\t\t0.040083\n training accuracy:\t\t98.51%\nIteration 928: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\nIteration 928 of 1000 took 0.195s\n training loss:\t\t0.029726\n training accuracy:\t\t98.96%\nIteration 929: training...\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\nIteration 929 of 1000 took 0.235s\n training loss:\t\t0.118563\n training accuracy:\t\t95.42%\nIteration 930: training...\n Select /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient011/patient011_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\nIteration 930: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient015/patient015_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient046/patient046_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient046/patient046_frame01_gt.nii.gz\nIteration 930 of 1000 took 0.262s\n training loss:\t\t0.024677\n training accuracy:\t\t99.13%\n validation loss: \t\t0.026832\n validation accuracy:\t\t99.11%\n validation Dice LV:\t\t0.905768\n validation Dice Myo:\t\t0.843211\n validation Dice RV:\t\t0.964635\n\nIteration 931: training...\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient083/patient083_frame01_gt.nii.gz\nIteration 931 of 1000 took 0.151s\n training loss:\t\t0.022895\n training accuracy:\t\t99.17%\nIteration 932: training...\n Select /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient037/patient037_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\nIteration 932 of 1000 took 0.166s\n training loss:\t\t0.057091\n training accuracy:\t\t97.93%\nIteration 933: training...\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\nIteration 933 of 1000 took 0.222s\n training loss:\t\t0.090239\n training accuracy:\t\t96.63%\nIteration 934: training...\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient041/patient041_frame01_gt.nii.gz\nIteration 934 of 1000 took 0.251s\n training loss:\t\t0.030111\n training accuracy:\t\t98.95%\nIteration 935: training...\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\nIteration 935 of 1000 took 0.241s\n training loss:\t\t0.039164\n training accuracy:\t\t98.57%\nIteration 936: training...\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 936 of 1000 took 0.217s\n training loss:\t\t0.025541\n training accuracy:\t\t99.11%\nIteration 937: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\nIteration 937 of 1000 took 0.234s\n training loss:\t\t0.039072\n training accuracy:\t\t98.47%\nIteration 938: training...\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\nIteration 938 of 1000 took 0.209s\n training loss:\t\t0.026622\n training accuracy:\t\t99.11%\nIteration 939: training...\n Select /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient072/patient072_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\nIteration 939 of 1000 took 0.192s\n training loss:\t\t0.020610\n training accuracy:\t\t99.31%\nIteration 940: training...\n Select /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient022/patient022_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\nIteration 940: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient049/patient049_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient045/patient045_frame01_gt.nii.gz\nIteration 940 of 1000 took 0.254s\n training loss:\t\t0.027339\n training accuracy:\t\t99.13%\n validation loss: \t\t0.036691\n validation accuracy:\t\t98.70%\n validation Dice LV:\t\t0.828523\n validation Dice Myo:\t\t0.791603\n validation Dice RV:\t\t0.924309\n\nIteration 941: training...\n Select /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient032/patient032_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\nIteration 941 of 1000 took 0.220s\n training loss:\t\t0.031244\n training accuracy:\t\t98.80%\nIteration 942: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient029/patient029_frame01_gt.nii.gz\nIteration 942 of 1000 took 0.237s\n training loss:\t\t0.033509\n training accuracy:\t\t98.82%\nIteration 943: training...\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\nIteration 943 of 1000 took 0.264s\n training loss:\t\t0.027815\n training accuracy:\t\t98.93%\nIteration 944: training...\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\nIteration 944 of 1000 took 0.268s\n training loss:\t\t0.019885\n training accuracy:\t\t99.33%\nIteration 945: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\nIteration 945 of 1000 took 0.236s\n training loss:\t\t0.028912\n training accuracy:\t\t98.99%\nIteration 946: training...\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01_gt.nii.gz\nIteration 946 of 1000 took 0.211s\n training loss:\t\t0.023164\n training accuracy:\t\t99.19%\nIteration 947: training...\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\nIteration 947 of 1000 took 0.344s\n training loss:\t\t0.037352\n training accuracy:\t\t98.56%\nIteration 948: training...\n Select /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient076/patient076_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\nIteration 948 of 1000 took 0.219s\n training loss:\t\t0.023051\n training accuracy:\t\t99.18%\nIteration 949: training...\n Select /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient075/patient075_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient061/patient061_frame01_gt.nii.gz\nIteration 949 of 1000 took 0.265s\n training loss:\t\t0.018219\n training accuracy:\t\t99.37%\nIteration 950: training...\n Select /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient088/patient088_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient016/patient016_frame01_gt.nii.gz\nIteration 950: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient095/patient095_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient074/patient074_frame01_gt.nii.gz\nIteration 950 of 1000 took 0.388s\n training loss:\t\t0.040738\n training accuracy:\t\t98.59%\n validation loss: \t\t0.027440\n validation accuracy:\t\t98.96%\n validation Dice LV:\t\t0.880287\n validation Dice Myo:\t\t0.822658\n validation Dice RV:\t\t0.960709\n\nIteration 951: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\nIteration 951 of 1000 took 0.286s\n training loss:\t\t0.021943\n training accuracy:\t\t99.23%\nIteration 952: training...\n Select /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient031/patient031_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01_gt.nii.gz\nIteration 952 of 1000 took 0.234s\n training loss:\t\t0.026066\n training accuracy:\t\t99.06%\nIteration 953: training...\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient021/patient021_frame01_gt.nii.gz\nIteration 953 of 1000 took 0.202s\n training loss:\t\t0.031229\n training accuracy:\t\t98.79%\nIteration 954: training...\n Select /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient084/patient084_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient052/patient052_frame01_gt.nii.gz\nIteration 954 of 1000 took 0.238s\n training loss:\t\t0.031351\n training accuracy:\t\t98.74%\nIteration 955: training...\n Select /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient003/patient003_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\nIteration 955 of 1000 took 0.211s\n training loss:\t\t0.031192\n training accuracy:\t\t98.88%\nIteration 956: training...\n Select /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient094/patient094_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient002/patient002_frame01_gt.nii.gz\nIteration 956 of 1000 took 0.226s\n training loss:\t\t0.027306\n training accuracy:\t\t99.01%\nIteration 957: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient098/patient098_frame01_gt.nii.gz\nIteration 957 of 1000 took 0.171s\n training loss:\t\t0.026567\n training accuracy:\t\t99.00%\nIteration 958: training...\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\nIteration 958 of 1000 took 0.238s\n training loss:\t\t0.024318\n training accuracy:\t\t99.12%\nIteration 959: training...\n Select /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient051/patient051_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient087/patient087_frame01_gt.nii.gz\nIteration 959 of 1000 took 0.218s\n training loss:\t\t0.027971\n training accuracy:\t\t99.02%\nIteration 960: training...\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient055/patient055_frame01_gt.nii.gz\nIteration 960: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient029/patient029_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient029/patient029_frame01_gt.nii.gz\nIteration 960 of 1000 took 0.256s\n training loss:\t\t0.023431\n training accuracy:\t\t99.19%\n validation loss: \t\t0.029503\n validation accuracy:\t\t98.90%\n validation Dice LV:\t\t0.868728\n validation Dice Myo:\t\t0.833846\n validation Dice RV:\t\t0.950026\n\nIteration 961: training...\n Select /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\nIteration 961 of 1000 took 0.213s\n training loss:\t\t0.021812\n training accuracy:\t\t99.20%\nIteration 962: training...\n Select /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient074/patient074_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient048/patient048_frame01_gt.nii.gz\nIteration 962 of 1000 took 0.195s\n training loss:\t\t0.025929\n training accuracy:\t\t99.02%\nIteration 963: training...\n Select /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient064/patient064_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient034/patient034_frame01_gt.nii.gz\nIteration 963 of 1000 took 0.232s\n training loss:\t\t0.019703\n training accuracy:\t\t99.31%\nIteration 964: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient056/patient056_frame01_gt.nii.gz\nIteration 964 of 1000 took 0.227s\n training loss:\t\t0.028423\n training accuracy:\t\t98.94%\nIteration 965: training...\n Select /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient028/patient028_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient018/patient018_frame01_gt.nii.gz\nIteration 965 of 1000 took 0.208s\n training loss:\t\t0.025137\n training accuracy:\t\t99.05%\nIteration 966: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\nIteration 966 of 1000 took 0.209s\n training loss:\t\t0.022579\n training accuracy:\t\t99.23%\nIteration 967: training...\n Select /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient005/patient005_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient023/patient023_frame01_gt.nii.gz\nIteration 967 of 1000 took 0.218s\n training loss:\t\t0.024592\n training accuracy:\t\t99.07%\nIteration 968: training...\n Select /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient030/patient030_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient015/patient015_frame01_gt.nii.gz\nIteration 968 of 1000 took 0.217s\n training loss:\t\t0.028504\n training accuracy:\t\t98.97%\nIteration 969: training...\n Select /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient081/patient081_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient097/patient097_frame01_gt.nii.gz\nIteration 969 of 1000 took 0.275s\n training loss:\t\t0.020725\n training accuracy:\t\t99.29%\nIteration 970: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\nIteration 970: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient062/patient062_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient084/patient084_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient084/patient084_frame01_gt.nii.gz\nIteration 970 of 1000 took 0.288s\n training loss:\t\t0.023492\n training accuracy:\t\t99.19%\n validation loss: \t\t0.031890\n validation accuracy:\t\t98.86%\n validation Dice LV:\t\t0.849754\n validation Dice Myo:\t\t0.842884\n validation Dice RV:\t\t0.964788\n\nIteration 971: training...\n Select /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient017/patient017_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\nIteration 971 of 1000 took 0.295s\n training loss:\t\t0.025557\n training accuracy:\t\t99.07%\nIteration 972: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\nIteration 972 of 1000 took 0.205s\n training loss:\t\t0.019352\n training accuracy:\t\t99.33%\nIteration 973: training...\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\nIteration 973 of 1000 took 0.269s\n training loss:\t\t0.030603\n training accuracy:\t\t98.97%\nIteration 974: training...\n Select /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient062/patient062_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient099/patient099_frame01_gt.nii.gz\nIteration 974 of 1000 took 0.287s\n training loss:\t\t0.020249\n training accuracy:\t\t99.30%\nIteration 975: training...\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\nIteration 975 of 1000 took 0.219s\n training loss:\t\t0.032485\n training accuracy:\t\t98.86%\nIteration 976: training...\n Select /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient057/patient057_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient085/patient085_frame01_gt.nii.gz\nIteration 976 of 1000 took 0.291s\n training loss:\t\t0.048541\n training accuracy:\t\t98.15%\nIteration 977: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\nIteration 977 of 1000 took 0.234s\n training loss:\t\t0.023728\n training accuracy:\t\t99.09%\nIteration 978: training...\n Select /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient053/patient053_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient049/patient049_frame01_gt.nii.gz\nIteration 978 of 1000 took 0.165s\n training loss:\t\t0.022741\n training accuracy:\t\t99.20%\nIteration 979: training...\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient071/patient071_frame01_gt.nii.gz\nIteration 979 of 1000 took 0.232s\n training loss:\t\t0.024808\n training accuracy:\t\t99.14%\nIteration 980: training...\n Select /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient025/patient025_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient078/patient078_frame01_gt.nii.gz\nIteration 980: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient080/patient080_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient056/patient056_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient056/patient056_frame01_gt.nii.gz\nIteration 980 of 1000 took 0.268s\n training loss:\t\t0.028994\n training accuracy:\t\t98.92%\n validation loss: \t\t0.018539\n validation accuracy:\t\t99.40%\n validation Dice LV:\t\t0.950365\n validation Dice Myo:\t\t0.857228\n validation Dice RV:\t\t0.965934\n\nIteration 981: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\nIteration 981 of 1000 took 0.241s\n training loss:\t\t0.024268\n training accuracy:\t\t99.07%\nIteration 982: training...\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\nIteration 982 of 1000 took 0.222s\n training loss:\t\t0.020196\n training accuracy:\t\t99.28%\nIteration 983: training...\n Select /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient079/patient079_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient010/patient010_frame01_gt.nii.gz\nIteration 983 of 1000 took 0.222s\n training loss:\t\t0.022883\n training accuracy:\t\t99.20%\nIteration 984: training...\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient092/patient092_frame01_gt.nii.gz\nIteration 984 of 1000 took 0.281s\n training loss:\t\t0.033082\n training accuracy:\t\t98.75%\nIteration 985: training...\n Select /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient004/patient004_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\nIteration 985 of 1000 took 0.211s\n training loss:\t\t0.021214\n training accuracy:\t\t99.24%\nIteration 986: training...\n Select /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient040/patient040_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient067/patient067_frame01_gt.nii.gz\nIteration 986 of 1000 took 0.234s\n training loss:\t\t0.023321\n training accuracy:\t\t99.14%\nIteration 987: training...\n Select /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient089/patient089_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient068/patient068_frame01_gt.nii.gz\nIteration 987 of 1000 took 0.164s\n training loss:\t\t0.026112\n training accuracy:\t\t99.00%\nIteration 988: training...\n Select /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient100/patient100_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\nIteration 988 of 1000 took 0.178s\n training loss:\t\t0.021108\n training accuracy:\t\t99.25%\nIteration 989: training...\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient095/patient095_frame01_gt.nii.gz\nIteration 989 of 1000 took 0.343s\n training loss:\t\t0.019332\n training accuracy:\t\t99.34%\nIteration 990: training...\n Select /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient001/patient001_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\nIteration 990: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient023/patient023_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient023/patient023_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient035/patient035_frame01_gt.nii.gz\nIteration 990 of 1000 took 0.413s\n training loss:\t\t0.025031\n training accuracy:\t\t99.12%\n validation loss: \t\t0.017482\n validation accuracy:\t\t99.35%\n validation Dice LV:\t\t0.917901\n validation Dice Myo:\t\t0.869930\n validation Dice RV:\t\t0.954660\n\nIteration 991: training...\n Select /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient058/patient058_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient019/patient019_frame01_gt.nii.gz\nIteration 991 of 1000 took 0.242s\n training loss:\t\t0.019730\n training accuracy:\t\t99.29%\nIteration 992: training...\n Select /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient086/patient086_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 992 of 1000 took 0.175s\n training loss:\t\t0.022943\n training accuracy:\t\t99.23%\nIteration 993: training...\n Select /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient080/patient080_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient073/patient073_frame01_gt.nii.gz\nIteration 993 of 1000 took 0.157s\n training loss:\t\t0.017347\n training accuracy:\t\t99.39%\nIteration 994: training...\n Select /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient026/patient026_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient091/patient091_frame01_gt.nii.gz\nIteration 994 of 1000 took 0.202s\n training loss:\t\t0.039827\n training accuracy:\t\t98.53%\nIteration 995: training...\n Select /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient007/patient007_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient024/patient024_frame01_gt.nii.gz\nIteration 995 of 1000 took 0.208s\n training loss:\t\t0.018730\n training accuracy:\t\t99.32%\nIteration 996: training...\n Select /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient044/patient044_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient066/patient066_frame01_gt.nii.gz\nIteration 996 of 1000 took 0.205s\n training loss:\t\t0.022809\n training accuracy:\t\t99.14%\nIteration 997: training...\n Select /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient006/patient006_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\nIteration 997 of 1000 took 0.241s\n training loss:\t\t0.028870\n training accuracy:\t\t98.88%\nIteration 998: training...\n Select /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient096/patient096_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient027/patient027_frame01_gt.nii.gz\nIteration 998 of 1000 took 0.306s\n training loss:\t\t0.032750\n training accuracy:\t\t98.83%\nIteration 999: training...\n Select /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient014/patient014_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient045/patient045_frame01_gt.nii.gz\nIteration 999 of 1000 took 0.213s\n training loss:\t\t0.030488\n training accuracy:\t\t98.83%\nIteration 1000: training...\n Select /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient013/patient013_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01.nii.gz /content/ukbb_cardiac/dataset/train/patient020/patient020_frame01_gt.nii.gz\nIteration 1000: validation...\n Select /content/ukbb_cardiac/dataset/validation/patient050/patient050_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient050/patient050_frame01_gt.nii.gz\n Select /content/ukbb_cardiac/dataset/validation/patient086/patient086_frame01.nii.gz /content/ukbb_cardiac/dataset/validation/patient086/patient086_frame01_gt.nii.gz\nIteration 1000 of 1000 took 0.285s\n training loss:\t\t0.021675\n training accuracy:\t\t99.20%\n validation loss: \t\t0.026467\n validation accuracy:\t\t99.02%\n validation Dice LV:\t\t0.898092\n validation Dice Myo:\t\t0.820641\n validation Dice RV:\t\t0.965533\n\nTraining took 250.844s in total.\n\n"
]
],
[
[
"## Testing",
"_____no_output_____"
]
],
[
[
"!cp -r \"/content/drive/My Drive/tesi/20180914_Bai2018_Article_AutomatedCardiovascularMagneti_RESULTS/model\" /content/ukbb_cardiac/model",
"_____no_output_____"
],
[
"import os\nfor dir in os.listdir(\"dataset/test\"):\n if os.path.isdir(\"dataset/test/\"+dir):\n source=\"dataset/test/\"+dir+\"/*_4d.nii.gz\"\n dst=\"dataset/test/\"+dir+\"/sa.nii.gz\"\n !mv $source $dst",
"_____no_output_____"
],
[
"!python common/deploy_network.py",
"WARNING:tensorflow:From common/deploy_network.py:48: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.\n\n2020-09-14 13:26:23.770803: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n2020-09-14 13:26:23.786014: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-09-14 13:26:23.786863: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-09-14 13:26:23.787150: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-09-14 13:26:23.788820: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-09-14 13:26:23.790865: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-09-14 13:26:23.791193: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-09-14 13:26:23.793079: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-09-14 13:26:23.794204: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-09-14 13:26:23.798474: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-09-14 13:26:23.798632: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-09-14 13:26:23.799556: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-09-14 13:26:23.800281: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-09-14 13:26:23.805428: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2299995000 Hz\n2020-09-14 13:26:23.805761: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x278ca00 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n2020-09-14 13:26:23.805811: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version\n2020-09-14 13:26:23.899389: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-09-14 13:26:23.900369: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x278cbc0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n2020-09-14 13:26:23.900420: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Tesla P100-PCIE-16GB, Compute Capability 6.0\n2020-09-14 13:26:23.900625: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-09-14 13:26:23.901438: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-09-14 13:26:23.901505: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-09-14 13:26:23.901541: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-09-14 13:26:23.901558: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-09-14 13:26:23.901579: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-09-14 13:26:23.901600: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-09-14 13:26:23.901622: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-09-14 13:26:23.901643: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-09-14 13:26:23.901724: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-09-14 13:26:23.902654: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-09-14 13:26:23.903575: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-09-14 13:26:23.903657: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-09-14 13:26:23.905070: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-09-14 13:26:23.905104: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-09-14 13:26:23.905113: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-09-14 13:26:23.905279: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-09-14 13:26:23.906337: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-09-14 13:26:23.907364: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0.\n2020-09-14 13:26:23.907421: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15216 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nWARNING:tensorflow:From common/deploy_network.py:49: The name tf.global_variables_initializer is deprecated. Please use tf.compat.v1.global_variables_initializer instead.\n\nWARNING:tensorflow:From common/deploy_network.py:52: The name tf.train.import_meta_graph is deprecated. Please use tf.compat.v1.train.import_meta_graph instead.\n\nStart deployment on the data set ...\npatient101\n Reading dataset/test/patient101/sa.nii.gz ...\n Segmenting full sequence ...\n2020-09-14 13:26:26.916007: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-09-14 13:26:31.244297: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n Segmentation time = 8.402343s\n ED frame = 0, ES frame = 15\n Saving segmentation ...\npatient102\n Reading dataset/test/patient102/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.695233s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient103\n Reading dataset/test/patient103/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.863825s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient104\n Reading dataset/test/patient104/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.762623s\n ED frame = 0, ES frame = 10\n Saving segmentation ...\npatient105\n Reading dataset/test/patient105/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.948118s\n ED frame = 0, ES frame = 8\n Saving segmentation ...\npatient106\n Reading dataset/test/patient106/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.574331s\n ED frame = 0, ES frame = 15\n Saving segmentation ...\npatient107\n Reading dataset/test/patient107/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.894002s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient108\n Reading dataset/test/patient108/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.907919s\n ED frame = 0, ES frame = 9\n Saving segmentation ...\npatient109\n Reading dataset/test/patient109/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.237260s\n ED frame = 0, ES frame = 10\n Saving segmentation ...\npatient110\n Reading dataset/test/patient110/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.599114s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient111\n Reading dataset/test/patient111/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 0.731672s\n ED frame = 0, ES frame = 5\n Saving segmentation ...\npatient112\n Reading dataset/test/patient112/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 2.336087s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient113\n Reading dataset/test/patient113/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 0.750972s\n ED frame = 0, ES frame = 6\n Saving segmentation ...\npatient114\n Reading dataset/test/patient114/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 2.286752s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient115\n Reading dataset/test/patient115/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.972199s\n ED frame = 0, ES frame = 12\n Saving segmentation ...\npatient116\n Reading dataset/test/patient116/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.724626s\n ED frame = 0, ES frame = 10\n Saving segmentation ...\npatient117\n Reading dataset/test/patient117/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 2.013988s\n ED frame = 0, ES frame = 13\n Saving segmentation ...\npatient118\n Reading dataset/test/patient118/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.348134s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient119\n Reading dataset/test/patient119/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.169191s\n ED frame = 0, ES frame = 8\n Saving segmentation ...\npatient120\n Reading dataset/test/patient120/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.336699s\n ED frame = 0, ES frame = 7\n Saving segmentation ...\npatient121\n Reading dataset/test/patient121/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.384913s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient122\n Reading dataset/test/patient122/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 0.734705s\n ED frame = 0, ES frame = 7\n Saving segmentation ...\npatient123\n Reading dataset/test/patient123/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.446765s\n ED frame = 0, ES frame = 12\n Saving segmentation ...\npatient124\n Reading dataset/test/patient124/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.421747s\n ED frame = 0, ES frame = 8\n Saving segmentation ...\npatient125\n Reading dataset/test/patient125/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.157144s\n ED frame = 0, ES frame = 6\n Saving segmentation ...\npatient126\n Reading dataset/test/patient126/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.109994s\n ED frame = 0, ES frame = 7\n Saving segmentation ...\npatient127\n Reading dataset/test/patient127/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.513361s\n ED frame = 0, ES frame = 7\n Saving segmentation ...\npatient128\n Reading dataset/test/patient128/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.593299s\n ED frame = 0, ES frame = 12\n Saving segmentation ...\npatient129\n Reading dataset/test/patient129/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.275317s\n ED frame = 0, ES frame = 7\n Saving segmentation ...\npatient130\n Reading dataset/test/patient130/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.844742s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient131\n Reading dataset/test/patient131/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.467653s\n ED frame = 0, ES frame = 13\n Saving segmentation ...\npatient132\n Reading dataset/test/patient132/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 2.194606s\n ED frame = 0, ES frame = 16\n Saving segmentation ...\npatient133\n Reading dataset/test/patient133/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 0.802420s\n ED frame = 0, ES frame = 8\n Saving segmentation ...\npatient134\n Reading dataset/test/patient134/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 2.192050s\n ED frame = 0, ES frame = 16\n Saving segmentation ...\npatient135\n Reading dataset/test/patient135/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.166558s\n ED frame = 0, ES frame = 10\n Saving segmentation ...\npatient136\n Reading dataset/test/patient136/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.406351s\n ED frame = 0, ES frame = 8\n Saving segmentation ...\npatient137\n Reading dataset/test/patient137/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.613027s\n ED frame = 0, ES frame = 16\n Saving segmentation ...\npatient138\n Reading dataset/test/patient138/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.604359s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient139\n Reading dataset/test/patient139/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.119421s\n ED frame = 0, ES frame = 7\n Saving segmentation ...\npatient140\n Reading dataset/test/patient140/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.340379s\n ED frame = 0, ES frame = 8\n Saving segmentation ...\npatient141\n Reading dataset/test/patient141/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.145021s\n ED frame = 0, ES frame = 12\n Saving segmentation ...\npatient142\n Reading dataset/test/patient142/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.387146s\n ED frame = 0, ES frame = 12\n Saving segmentation ...\npatient143\n Reading dataset/test/patient143/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.824807s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient144\n Reading dataset/test/patient144/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.131454s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient145\n Reading dataset/test/patient145/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.913966s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient146\n Reading dataset/test/patient146/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.980601s\n ED frame = 0, ES frame = 8\n Saving segmentation ...\npatient147\n Reading dataset/test/patient147/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 2.430238s\n ED frame = 0, ES frame = 10\n Saving segmentation ...\npatient148\n Reading dataset/test/patient148/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.679115s\n ED frame = 0, ES frame = 11\n Saving segmentation ...\npatient149\n Reading dataset/test/patient149/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.466450s\n ED frame = 0, ES frame = 13\n Saving segmentation ...\npatient150\n Reading dataset/test/patient150/sa.nii.gz ...\n Segmenting full sequence ...\n Segmentation time = 1.423209s\n ED frame = 0, ES frame = 8\n Saving segmentation ...\nAverage segmentation time = 1.687s per sequence\nIncluding image I/O, CUDA resource allocation, it took 149.963s for processing 50 subjects (2.999s per subjects).\n"
],
[
"import os\nfor dir in os.listdir(\"dataset/test\"):\n if os.path.isdir(\"dataset/test/\"+dir):\n source=\"dataset/test/\"+dir+\"/seg_sa_ED.nii.gz\"\n dst='\"/content/drive/My Drive/tesi/20180914_Bai2018_Article_AutomatedCardiovascularMagneti_RESULTS/results/'+dir+'_ED.nii.gz\"'\n !cp $source $dst\n source=\"dataset/test/\"+dir+\"/seg_sa_ES.nii.gz\"\n dst='\"/content/drive/My Drive/tesi/20180914_Bai2018_Article_AutomatedCardiovascularMagneti_RESULTS/results/'+dir+'_ES.nii.gz\"'\n !cp $source $dst",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
ecd0b7f6e28fdc21081a3873e6549bf2788f0521 | 7,373 | ipynb | Jupyter Notebook | 0mastercopy.ipynb | odhran-o-d/Remote_Allosteric_Graphs | c0fbe2a1ef21b6bc27483faa39ab14bc97c12238 | [
"MIT"
] | 1 | 2020-08-03T13:09:19.000Z | 2020-08-03T13:09:19.000Z | 0mastercopy.ipynb | odhran-o-d/Remote_Allosteric_Graphs | c0fbe2a1ef21b6bc27483faa39ab14bc97c12238 | [
"MIT"
] | null | null | null | 0mastercopy.ipynb | odhran-o-d/Remote_Allosteric_Graphs | c0fbe2a1ef21b6bc27483faa39ab14bc97c12238 | [
"MIT"
] | 1 | 2021-01-25T05:28:05.000Z | 2021-01-25T05:28:05.000Z | 38.401042 | 1,489 | 0.586871 | [
[
[
"from models.DistMult import DistMult\nfrom models.Complex import Complex\nfrom models.ConvE import ConvE, ConvE_args\n\nfrom utils.loaders import load_data, get_onehots\nfrom utils.evaluation_metrics import SRR, auprc_auroc_ap\n\nimport torch\nimport numpy as np\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"def main(model, optimiser, train_data, val_data, epochs, batches):\n for epoch in range(epochs):\n #training stage \n model.train()\n objects, subjects, relationships = load_data(train_data, batches)\n\n for index in range(batches):\n\n obj = torch.LongTensor(objects[index])\n rel = torch.LongTensor(relationships[index])\n subj = torch.squeeze(torch.LongTensor(subjects[index]))\n\n optimiser.zero_grad()\n pred = model.forward(e1 = obj, rel = rel)\n loss = model.loss(pred, subj)\n loss.backward()\n optimiser.step()\n\n\n #evaluation stage\n model.eval()\n objects, subjects, relationships = load_data(val_data, batch_number=1)\n total_sum_reciporical_rank = torch.zeros(1)\n\n # for index in range(batches):\n # obj = torch.LongTensor(objects[index])\n # rel = torch.LongTensor(relationships[index])\n # targets = torch.LongTensor(subjects[index])\n # predictions = model.forward(e1 = obj, rel = rel)\n # srr = SRR(predictions, targets) \n # total_sum_reciporical_rank = total_sum_reciporical_rank + srr\n\n obj = torch.squeeze(torch.LongTensor(objects)).unsqueeze(1)\n rel = torch.squeeze(torch.LongTensor(relationships)).unsqueeze(1)\n targets = torch.squeeze(torch.LongTensor(subjects)).unsqueeze(1)\n\n predictions = model.forward(e1 = obj, rel = rel)\n srr = SRR(predictions, targets) \n total_sum_reciporical_rank = total_sum_reciporical_rank + srr\n \n print('mean reciporical rank is...', total_sum_reciporical_rank/ len(val_data))\n # print(total_sum_reciporical_rank / len(test_data))\n\n one_hots = get_onehots(targets, entities)\n auprc, auroc, ap = auprc_auroc_ap(one_hots, predictions)\n\n print('auroc is...', auroc)\n print('auprc is...', auprc)\n print('ap@50 is...', ap)\n\n return(total_sum_reciporical_rank, auroc, auprc, ap)\n",
"_____no_output_____"
],
[
"from utils.path_manage import get_files\n\ndata, lookup, ASD_dictionary, BCE_dictionary = get_files()\nentities = int(len(lookup)/2)",
"_____no_output_____"
],
[
"batches = 5\nepochs = 10\nx = shuffle(data)\ntest_data = x[:100] #just limit data to the first n rows",
"_____no_output_____"
],
[
"X_train, X_test = train_test_split(test_data, test_size=0.1, random_state=1)\nX_train, X_val = train_test_split(X_train, test_size=0.1111, random_state=1) ",
"_____no_output_____"
],
[
"args = ConvE_args()",
"_____no_output_____"
],
[
"# model = DistMult(num_entities = entities, embedding_dim=100, num_relations=4)\n# model = Complex(num_entities = entities, embedding_dim=100, num_relations=4)\nmodel = ConvE(args = args, embedding_dim=200, num_entities=entities, num_relations=4)\noptimiser = torch.optim.Adam(model.parameters(), lr=0.01)",
"70555 4\n"
],
[
"total_sum_reciporical_rank, auroc, auprc, ap = main(model=model, optimiser=optimiser, train_data=X_train, val_data=X_val, epochs=epochs, batches=batches)",
"mean reciporical rank is... tensor([0.0063])\nauroc is... 0.7255230036567736\nauprc is... 0.00017846182152123834\nap@50 is... 0.000325080969565733\nmean reciporical rank is... tensor([0.0202])\nauroc is... 0.7076012699492586\nauprc is... 0.00030272511232883796\nap@50 is... 0.0004978417684235109\nmean reciporical rank is... tensor([0.1029])\nauroc is... 0.7103224480539729\nauprc is... 0.0013815144285051393\nap@50 is... 0.0024002820517194934\nmean reciporical rank is... tensor([0.1335])\nauroc is... 0.7073590441364062\nauprc is... 0.0073595181265391565\nap@50 is... 0.013968976540632293\nmean reciporical rank is... tensor([0.0649])\nauroc is... 0.7248542960002268\nauprc is... 0.005333839211592712\nap@50 is... 0.009659618084023897\nmean reciporical rank is... tensor([0.0549])\nauroc is... 0.7348279332142756\nauprc is... 0.003011246852842489\nap@50 is... 0.004805235038595428\nmean reciporical rank is... tensor([0.0361])\nauroc is... 0.7416432803242906\nauprc is... 0.0019768342003107344\nap@50 is... 0.002949165744722577\nmean reciporical rank is... tensor([0.0354])\nauroc is... 0.743363664710718\nauprc is... 0.0012417756940125042\nap@50 is... 0.0019087882601044606\nmean reciporical rank is... tensor([0.0518])\nauroc is... 0.7387066643989002\nauprc is... 0.0012293535199637575\nap@50 is... 0.0019455784989141408\nmean reciporical rank is... tensor([0.0518])\nauroc is... 0.7304392380304447\nauprc is... 0.0010889113101326972\nap@50 is... 0.0017603407002413814\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecd0b92746ddeacefbd6bf4769752acd491d1047 | 2,822 | ipynb | Jupyter Notebook | notebook/numpy_broadcasting_3d.ipynb | puyopop/python-snippets | 9d70aa3b2a867dd22f5a5e6178a5c0c5081add73 | [
"MIT"
] | 174 | 2018-05-30T21:14:50.000Z | 2022-03-25T07:59:37.000Z | notebook/numpy_broadcasting_3d.ipynb | puyopop/python-snippets | 9d70aa3b2a867dd22f5a5e6178a5c0c5081add73 | [
"MIT"
] | 5 | 2019-08-10T03:22:02.000Z | 2021-07-12T20:31:17.000Z | notebook/numpy_broadcasting_3d.ipynb | puyopop/python-snippets | 9d70aa3b2a867dd22f5a5e6178a5c0c5081add73 | [
"MIT"
] | 53 | 2018-04-27T05:26:35.000Z | 2022-03-25T07:59:37.000Z | 16.125714 | 46 | 0.391921 | [
[
[
"import numpy as np",
"_____no_output_____"
],
[
"a = np.zeros((2, 3, 4), dtype=np.int)\nprint(a)",
"[[[0 0 0 0]\n [0 0 0 0]\n [0 0 0 0]]\n\n [[0 0 0 0]\n [0 0 0 0]\n [0 0 0 0]]]\n"
],
[
"print(a.shape)",
"(2, 3, 4)\n"
],
[
"b = np.arange(4)\nprint(b)",
"[0 1 2 3]\n"
],
[
"print(b.shape)",
"(4,)\n"
],
[
"print(a + b)",
"[[[0 1 2 3]\n [0 1 2 3]\n [0 1 2 3]]\n\n [[0 1 2 3]\n [0 1 2 3]\n [0 1 2 3]]]\n"
],
[
"b_1_1_4 = b.reshape(1, 1, 4)\nprint(b_1_1_4)",
"[[[0 1 2 3]]]\n"
],
[
"print(np.tile(b_1_1_4, (2, 3, 1)))",
"[[[0 1 2 3]\n [0 1 2 3]\n [0 1 2 3]]\n\n [[0 1 2 3]\n [0 1 2 3]\n [0 1 2 3]]]\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecd0c3fd8bc5b435db46dfc0717018206d5252fd | 29,875 | ipynb | Jupyter Notebook | Handling Missing Data/4_Simple_Imputer_by_Sklearn.ipynb | Jawwad-Fida/Feature-Engineering | 81e611fd7ee99ffd50cb571c09fe9e41ce8d3595 | [
"MIT"
] | 1 | 2021-06-24T17:07:56.000Z | 2021-06-24T17:07:56.000Z | Handling Missing Data/4_Simple_Imputer_by_Sklearn.ipynb | Jawwad-Fida/Feature-Engineering | 81e611fd7ee99ffd50cb571c09fe9e41ce8d3595 | [
"MIT"
] | null | null | null | Handling Missing Data/4_Simple_Imputer_by_Sklearn.ipynb | Jawwad-Fida/Feature-Engineering | 81e611fd7ee99ffd50cb571c09fe9e41ce8d3595 | [
"MIT"
] | null | null | null | 32.020364 | 187 | 0.401372 | [
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"def read_data():\n df = pd.read_csv(\"data/car-sales-extended-missing-data.csv\")\n return df\n\n# to change index of dataframe --> use reindex(d)",
"_____no_output_____"
],
[
"df = read_data()\ndf",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
],
[
"# Check how many data is present in the dataframe\nlen(df)",
"_____no_output_____"
],
[
"# Number of missing values in the dataframe\ndf.isnull().sum()",
"_____no_output_____"
]
],
[
[
"#### Then Split data into train and test set, and then fill them out seperately",
"_____no_output_____"
],
[
"## Handling Missing Values",
"_____no_output_____"
],
[
"### 4. Filling rows with missing data - SimpleImputer()\n\n* SimpleImputer() is provided by Scikit-Learn Library",
"_____no_output_____"
]
],
[
[
"# Remove rows with missing Price Values --> as price is y\ndf.dropna(subset=[\"Price\"],inplace=True)\n\ndf.isnull().sum()",
"_____no_output_____"
],
[
"X = df.drop('Price',axis=1)\ny = df['Price']",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\nnp.random.seed(42)\n\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)",
"_____no_output_____"
],
[
"X_train.shape, X_test.shape, y_train.shape, y_test.shape",
"_____no_output_____"
],
[
"# Check missing values in X (both train and test dataset)\nX.isna().sum()",
"_____no_output_____"
]
],
[
[
"Let's fill the missing values. We'll fill the training and test values separately to ensure training data stays with the training data and test data stays with the test data.\n\nNote: We use fit_transform() on the training data and transform() on the testing data. \n\nIn essence, we learn the patterns in the training set and transform it via imputation (fit, then transform). Then we take those same patterns and fill the test set (transform only).",
"_____no_output_____"
]
],
[
[
"# Fill missing values with Scikit-Learn\n\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.compose import ColumnTransformer\n\n# Fill categorical values with \"missing\" and numerical values with mean\n# Imputation --> Find the missing values and fill them\n# Define some imputers\n\n# strategy=\"constant\" = go to the categorical columns, if u find a missing value, \n# constantly fill them with the string missing, or mean or a default value\n\ncat_imputer = SimpleImputer(strategy=\"constant\",fill_value=\"missing\")\ndoor_imputer = SimpleImputer(strategy=\"constant\",fill_value=4)\nnum_imputer = SimpleImputer(strategy=\"mean\")\n\n# Define columns\ncat_features = [\"Make\",\"Colour\"] # nominal category column in dataframe\ndoor_features = [\"Doors\"] # a category column\nnum_features = [\"Odometer (KM)\"] # numerical column\n\n# Create an imputer (something that fills missing data)\n# pass in the imputations (all the different transformations to do)\n\n# Takes a list and tuples within exists multiple different transformers\nimputer = ColumnTransformer([\n # name, imputer to use, features on which to use the imputer\n (\"cat_imputer\",cat_imputer,cat_features),\n (\"door_imputer\",door_imputer,door_features),\n (\"num_imputer\",num_imputer,num_features)\n])\n\n# Transform data\n# Fill train and test values separately\nfilled_X_train = imputer.fit_transform(X_train) # fit_transform imputes the missing values from the training set and fills them simultaneously\nfilled_X_test = imputer.transform(X_test) # tranform takes the imputing missing values from the training set and fills the test set with them",
"_____no_output_____"
],
[
"# Check filled X_train\nfilled_X_train",
"_____no_output_____"
],
[
"# Check filled X_test\nfilled_X_test",
"_____no_output_____"
],
[
"# Get our transformed data array's back into DataFrame's\ntrain_df = pd.DataFrame(filled_X_train, \n columns=[\"Make\", \"Colour\", \"Doors\", \"Odometer (KM)\"])\n\ntest_df = pd.DataFrame(filled_X_test, \n columns=[\"Make\", \"Colour\", \"Doors\", \"Odometer (KM)\"])",
"_____no_output_____"
],
[
"train_df",
"_____no_output_____"
],
[
"train_df.isnull().sum()",
"_____no_output_____"
],
[
"test_df.isnull().sum()",
"_____no_output_____"
],
[
"# No need to fill y_train and y_test as they don't have any missing values",
"_____no_output_____"
]
],
[
[
"#### Now that there are no missing values\n\n#### Convert the data into numbers (numerical data) by One Hot Encoding",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
ecd0e5a632603b6f17be5547742987b630aa2d9e | 2,073 | ipynb | Jupyter Notebook | docs/python/basics/break-with-youtube-song.ipynb | mmblack4/mynotes | eef4ffb13f42e966b716c63b3dcb25b17971be47 | [
"MIT"
] | null | null | null | docs/python/basics/break-with-youtube-song.ipynb | mmblack4/mynotes | eef4ffb13f42e966b716c63b3dcb25b17971be47 | [
"MIT"
] | null | null | null | docs/python/basics/break-with-youtube-song.ipynb | mmblack4/mynotes | eef4ffb13f42e966b716c63b3dcb25b17971be47 | [
"MIT"
] | null | null | null | 19.742857 | 61 | 0.489629 | [
[
[
"---\ntitle: \"Break with youtube song\"\nauthor: \"TACT\"\ndate: 2019-04-20\ndescription: \"-\"\ntype: technical_note\ndraft: false\n---",
"_____no_output_____"
]
],
[
[
"import webbrowser\nimport time",
"_____no_output_____"
],
[
"song_list =[\n \"https://www.youtube.com/watch?v=kJQP7kiw5Fk\",\n \"https://www.youtube.com/watch?v=euCqAq6BRa4\",\n \"https://www.youtube.com/watch?v=UtF6Jej8yb4\",\n \"https://www.youtube.com/watch?v=nYh-n7EOtMA\",\n \"https://www.youtube.com/watch?v=J1OsKJW51HY\",\n]",
"_____no_output_____"
],
[
"def break_timer(interval):\n for i in song_list:\n time.sleep(interval)\n print('time to take brake')\n webbrowser.open(i)\n ",
"_____no_output_____"
],
[
"break_timer(5)",
"time to take brake\ntime to take brake\ntime to take brake\n"
]
]
] | [
"raw",
"code"
] | [
[
"raw"
],
[
"code",
"code",
"code",
"code"
]
] |
ecd0e7c16b7c5efb24e7dd1f8e0878a010b94b83 | 77,133 | ipynb | Jupyter Notebook | module1-logistic-regression/kaggle_class_comp.ipynb | RidleyLeisy/DS-Unit-2-Classification-1 | ee0a2451253c2ecb21de1871b57cfcbef55ed741 | [
"MIT"
] | null | null | null | module1-logistic-regression/kaggle_class_comp.ipynb | RidleyLeisy/DS-Unit-2-Classification-1 | ee0a2451253c2ecb21de1871b57cfcbef55ed741 | [
"MIT"
] | null | null | null | module1-logistic-regression/kaggle_class_comp.ipynb | RidleyLeisy/DS-Unit-2-Classification-1 | ee0a2451253c2ecb21de1871b57cfcbef55ed741 | [
"MIT"
] | 1 | 2019-06-05T11:49:27.000Z | 2019-06-05T11:49:27.000Z | 40.919363 | 22,668 | 0.589748 | [
[
[
"import sys\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns",
"_____no_output_____"
]
],
[
[
"## Load Data",
"_____no_output_____"
]
],
[
[
"path = '/Users/ridleyleisy/Documents/lambda/unit_two/DS-Unit-2-Classification-1/ds4-predictive-modeling-challenge/'",
"_____no_output_____"
],
[
"train = pd.read_csv(path + 'train_features.csv')\ntest = pd.read_csv(path + 'test_features.csv')\nlabels = pd.read_csv(path + 'train_labels.csv')\nsample_submission = pd.read_csv('https://drive.google.com/uc?export=download&id=1kfJewnmhowpUo381oSn3XqsQ6Eto23XV')",
"_____no_output_____"
]
],
[
[
"## clean data",
"_____no_output_____"
],
[
"### numeric",
"_____no_output_____"
]
],
[
[
"def drop_cols_rows(df):\n df.drop('num_private',axis=1,inplace=True)\n df.drop('recorded_by',axis=1,inplace=True)\n return df",
"_____no_output_____"
],
[
"train = drop_cols_rows(train)",
"_____no_output_____"
]
],
[
[
"#### replace longitude",
"_____no_output_____"
]
],
[
[
"#test whether you want to keep longitude\nlong_mean = train.loc[train['longitude'] !=0]['longitude'].mean()\ntrain['longitude'].replace(0,long_mean,inplace=True)\ntest['longitude'].replace(0,long_mean,inplace=True)",
"_____no_output_____"
]
],
[
[
"#### drop longitude",
"_____no_output_____"
]
],
[
[
"#test whether you want to drop longitude from dataset\ntrain = train.loc[train['longitude'] != 0]\ntest = test.loc[test['longitude'] != 0]",
"_____no_output_____"
]
],
[
[
"## Train construction year data",
"_____no_output_____"
],
[
"### feature engineering",
"_____no_output_____"
]
],
[
[
"from sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error\nimport seaborn as sns",
"_____no_output_____"
]
],
[
[
"#### construction year predicted by random forest",
"_____no_output_____"
]
],
[
[
"train['construction_year'] = train['construction_year'].replace(0,np.nan)\ntest['construction_year'] = test['construction_year'].replace(0,np.nan)",
"_____no_output_____"
],
[
"def transform_construction(df):\n \n df = df.select_dtypes(include=np.number)\n X = df.loc[~df['construction_year'].isna()]\n \n # can only use these featuers since they differ \n features = ['amount_tsh', 'gps_height', 'longitude', 'latitude',\n 'region_code', 'district_code', 'population']\n target = 'construction_year'\n \n X_train = X[features]\n y_train = X[target]\n \n X_train, X_test, y_train, y_test = train_test_split(X_train,y_train)\n m = RandomForestRegressor(n_estimators=20,max_depth=25)\n m.fit(X_train, y_train)\n \n vals = m.predict(df.loc[df['construction_year'].isna()][features])\n \n return vals",
"_____no_output_____"
],
[
"train.loc[train['construction_year'].isna(),'construction_year'] = transform_construction(train)\ntest.loc[test['construction_year'].isna(),'construction_year'] = transform_construction(test)\ntrain['construction_year'] = round(train['construction_year'])\ntest['construction_year'] = round(test['construction_year'])",
"_____no_output_____"
]
],
[
[
"#### construction year based on distribution",
"_____no_output_____"
]
],
[
[
"# getting distributions for construction years\ndist = train['construction_year'].value_counts(normalize=True)\ndist_test = test['construction_year'].value_counts(normalize=True)",
"_____no_output_____"
],
[
"# applying distribution of construction year to na values for train and test sets\ntrain.loc[train['construction_year'].isna(),'construction_year'] = np.random.choice(dist.index, size=train['construction_year'].isna().sum(),p=dist.values)",
"_____no_output_____"
],
[
"test.loc[test['construction_year'].isna(),'construction_year'] = np.random.choice(dist_test.index, size=test['construction_year'].isna().sum(),p=dist_test.values)",
"_____no_output_____"
]
],
[
[
"Add time since construction",
"_____no_output_____"
]
],
[
[
"def add_construction_diff(df):\n df['date_recorded'] = pd.to_datetime(df['date_recorded'])\n df['construction_year'] = pd.to_datetime(df['construction_year'],format=\"%Y\")\n df['time_since_construction'] = (df['date_recorded'] - df['construction_year']).dt.days\n df.loc[df['time_since_construction'] < 0,'time_since_construction'] = 0 \n df['construction_year'] = df['construction_year'].dt.year\n return df",
"_____no_output_____"
],
[
"test = add_construction_diff(test)\ntrain = add_construction_diff(train)",
"_____no_output_____"
]
],
[
[
"Feature engineering",
"_____no_output_____"
]
],
[
[
"def add_ratios(df):\n df['tsh_by_longitude'] = df['amount_tsh'] / df['longitude']\n df['tsh_by_latitude'] = df['amount_tsh'] / abs(df['latitude'])\n df['tsh_by_height'] = df['amount_tsh'] / df['gps_height']\n df['tsh_by_height'] = df['tsh_by_height'].replace(np.inf,0).replace(np.nan,0)\n return df",
"_____no_output_____"
],
[
"test = add_ratios(test)\ntrain = add_ratios(train)",
"_____no_output_____"
]
],
[
[
"### reduce label size to fit feature engineers",
"_____no_output_____"
]
],
[
[
"labels = labels.merge(train,on='id')[['id','status_group']]",
"_____no_output_____"
]
],
[
[
"## Encoding and Scaling Categorical Data",
"_____no_output_____"
]
],
[
[
"import category_encoders as ce\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"unique = train.describe(exclude=np.number).T.sort_values(by='unique')",
"_____no_output_____"
],
[
"cat_features = list(unique.loc[unique['unique'] < 130].index)",
"_____no_output_____"
],
[
"numeric_features = list(train.describe().columns[1:])",
"_____no_output_____"
],
[
"encode_features = cat_features\nfeatures = numeric_features + encode_features",
"_____no_output_____"
]
],
[
[
"### Pipeline",
"_____no_output_____"
]
],
[
[
"def transform_data_hot(features):\n encoder = ce.OneHotEncoder(use_cat_names=True)\n scaler = RobustScaler()\n X_train = train[features]\n y_train = labels['status_group']\n\n X_train, X_val, y_train, y_val = train_test_split(\n X_train, y_train, train_size=0.80, test_size=0.20, \n stratify=y_train, random_state=42)\n\n X_train_sub = X_train[features]\n X_val_sub = X_val[features]\n \n pipeline1 = Pipeline([('encoder',encoder),('scaler',scaler)])\n X_train_sub_encoded = pipeline1.fit_transform(X_train_sub)\n X_val_sub_encoded = pipeline1.transform(X_val_sub)\n \n test_encoded = pipeline1.transform(test[features])\n X_encode_cols = encoder.transform(X_train_sub)\n \n return X_train_sub_encoded, X_val_sub_encoded, y_train, y_val, X_encode_cols,test_encoded",
"_____no_output_____"
],
[
"def transform_data_ordinal(features):\n encoder = ce.OrdinalEncoder()\n scaler = RobustScaler()\n X_train = train[features]\n y_train = labels['status_group']\n\n X_train, X_val, y_train, y_val = train_test_split(\n X_train, y_train, train_size=0.80, test_size=0.20, \n stratify=y_train, random_state=42)\n\n X_train_sub = X_train[features]\n X_val_sub = X_val[features]\n \n pipeline1 = Pipeline([('encoder',encoder),('scaler',scaler)])\n X_train_sub_encoded = pipeline1.fit_transform(X_train_sub)\n X_val_sub_encoded = pipeline1.transform(X_val_sub)\n \n X_encode_cols = encoder.transform(X_train_sub)\n return X_train_sub_encoded, X_val_sub_encoded, y_train, y_val, X_encode_cols",
"_____no_output_____"
]
],
[
[
"## Logistical Regression",
"_____no_output_____"
]
],
[
[
"#model = LogisticRegression(solver='lbfgs', multi_class='auto', max_iter=1000)\n#model.fit(X_train_scaled, y_train)",
"_____no_output_____"
],
[
"model.score(X_val_scaled,y_val)",
"_____no_output_____"
]
],
[
[
"## Decision Tree",
"_____no_output_____"
]
],
[
[
"from sklearn.tree import DecisionTreeClassifier",
"_____no_output_____"
],
[
"m = DecisionTreeClassifier(max_depth=25)",
"_____no_output_____"
],
[
"m.fit(X_train_scaled,y_train)",
"_____no_output_____"
],
[
"m.score(X_val_scaled,y_val)",
"_____no_output_____"
],
[
"m.score(X_train_scaled,y_train)",
"_____no_output_____"
],
[
"pd.DataFrame(m.feature_importances_,X_train_sub_encoded.columns).sort_values(by=0).tail(10)",
"_____no_output_____"
]
],
[
[
"## Random Forest",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestClassifier",
"_____no_output_____"
]
],
[
[
"### ordinal",
"_____no_output_____"
]
],
[
[
"all_cats = train.describe(exclude='number').T.sort_values(by='unique').index",
"_____no_output_____"
],
[
"all_cats = all_cats.delete(all_cats.get_loc('date_recorded'))",
"_____no_output_____"
],
[
"X_train_sub_encoded, X_val_sub_encoded, y_train, y_val = transform_data_ordinal(features)",
"_____no_output_____"
]
],
[
[
"### hot encoded",
"_____no_output_____"
]
],
[
[
"X_train_sub_encoded, X_val_sub_encoded, y_train, y_val,cols, test_encoded = transform_data_hot(features)",
"_____no_output_____"
]
],
[
[
"### model",
"_____no_output_____"
]
],
[
[
"m = RandomForestClassifier(n_estimators=300,max_depth=28,max_features='auto',n_jobs=-1)",
"_____no_output_____"
],
[
"m.fit(X_train_sub_encoded,y_train)",
"_____no_output_____"
],
[
"m.score(X_val_sub_encoded,y_val)",
"_____no_output_____"
],
[
"m.score(X_train_sub_encoded,y_train)",
"_____no_output_____"
],
[
"pd.DataFrame(m.feature_importances_,cols.columns).sort_values(by=0)",
"_____no_output_____"
],
[
"preds = m.predict(test_encoded)",
"_____no_output_____"
]
],
[
[
"## Gradient Boosting",
"_____no_output_____"
]
],
[
[
"gbc.score(X_val_sub_encoded,y_val)",
"_____no_output_____"
],
[
"gbc.score(X_train_sub_encoded,y_train)",
"_____no_output_____"
]
],
[
[
"## Reduce Dimensions",
"_____no_output_____"
]
],
[
[
"feat_impt = pd.DataFrame(m.feature_importances_,encoded_cols).sort_values(by=0)",
"_____no_output_____"
],
[
"feat_impt[::-1]",
"_____no_output_____"
],
[
"cuml = np.cumsum(feat_impt[::-1])",
"_____no_output_____"
],
[
"(cuml.loc[cuml[0] < .95]).head()",
"_____no_output_____"
],
[
"cuml.loc[cuml[0] < .95].plot()\nplt.xticks(rotation=90)",
"_____no_output_____"
],
[
"reduced_features = cuml.loc[cuml[0] < .95].index",
"_____no_output_____"
],
[
"train.columns",
"_____no_output_____"
]
],
[
[
"### Random Forest Reduced Dims",
"_____no_output_____"
],
[
"## Predicting for Kaggle",
"_____no_output_____"
]
],
[
[
"submission = pd.DataFrame(test['id'])",
"_____no_output_____"
],
[
"submission['status_group'] = preds",
"_____no_output_____"
],
[
"submission.to_csv('submission-01.csv',index=False)",
"_____no_output_____"
],
[
"import pandas as pd\n\n# Filenames of your submissions you want to ensemble\nfiles = ['submission-01.csv', 'submission-02.csv', 'submission-03.csv']\n\nsubmissions = (pd.read_csv(file)[['status_group']] for file in files)\nensemble = pd.concat(submissions, axis='columns')\nmajority_vote = ensemble.mode(axis='columns')[0]\n\nsample_submission = pd.read_csv('sample_submission.csv')\nsubmission = sample_submission.copy()\nsubmission['status_group'] = majority_vote\nsubmission.to_csv('my-ultimate-ensemble-submission.csv', index=False)",
"_____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"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
ecd102513c6954cfbd6d548bbb518b45c86a754b | 30,298 | ipynb | Jupyter Notebook | Classes/learnclasses.ipynb | swap-10/LetsPython | ee8012be88ec9d4f3eb343791de832c082032ffb | [
"MIT"
] | null | null | null | Classes/learnclasses.ipynb | swap-10/LetsPython | ee8012be88ec9d4f3eb343791de832c082032ffb | [
"MIT"
] | null | null | null | Classes/learnclasses.ipynb | swap-10/LetsPython | ee8012be88ec9d4f3eb343791de832c082032ffb | [
"MIT"
] | null | null | null | 31.106776 | 92 | 0.569146 | [
[
[
"# Classes",
"_____no_output_____"
]
],
[
[
"# Just a little something for your consideration :D\r\n\r\na = [1, 2, 3, 4]\r\nb = a\r\nc = a\r\nb = b[0]-1\r\nprint(b)\r\nprint(a)\r\nc[0] = c[0]-1\r\nprint(c)\r\nprint(a)",
"0\n[1, 2, 3, 4]\n[0, 2, 3, 4]\n[0, 2, 3, 4]\n"
]
],
[
[
"<h2>Now, let's get started with Classes</h2>",
"_____no_output_____"
],
[
"<h2>Scopes and namespaces example</h2>",
"_____no_output_____"
]
],
[
[
"def scope_test():\r\n def do_local():\r\n spam = 'Local spam'\r\n\r\n def do_nonlocal():\r\n nonlocal spam\r\n spam = 'nonlocal spam'\r\n \r\n def do_global():\r\n global spam\r\n spam = 'global spam'\r\n\r\n spam = 'test spam'\r\n do_local()\r\n print('After local assignment:', spam)\r\n do_nonlocal()\r\n print('After nonlocal assignment:', spam)\r\n do_global()\r\n print('After global assignment:', spam)\r\n\r\nscope_test()\r\nprint(\"In the global scope:\", spam)",
"After local assignment: test spam\nAfter nonlocal assignment: nonlocal spam\nAfter global assignment: nonlocal spam\nIn the global scope: global spam\n"
]
],
[
[
"<h2>A First Look at Classes</h2>",
"_____no_output_____"
],
[
"<div style=\"font-size: 15px\">\r\nClass objects support two kinds of operations: attribute references and<br>\r\ninstantiation.<br>\r\n<br>\r\nAttribute references use the standard syntax used for all attribute<br>\r\nreferences in Python: obj.name. Valid attribute names are all the names<br>\r\nthat were in the class’s namespace when the class object was created. So, if<br>\r\nthe class definition looked like this:<br>\r\n</div>",
"_____no_output_____"
]
],
[
[
"class MyClass:\r\n \"\"\"A simple example class\"\"\"\r\n i=12345\r\n\r\n def f(self):\r\n return 'hello world'",
"_____no_output_____"
]
],
[
[
"<div style=\"font-size: 15px\">\r\nThen MyClass.i and MyClass.f are valid attribute references, returning<br>\r\nan integer and a function object, respectively. Class attributes can also<br>\r\nbe assigned to, so you can change the value of MyClass.i by assignment\r\n</div>",
"_____no_output_____"
]
],
[
[
"# Class instantiation uses function notation\r\nx = MyClass()\r\nprint(x.i)\r\n# Creates a new instance of the class and assigns this object to the local\r\n# variable x\r\n# The instantiation operation creates an empty object. To create objects with\r\n# instances customized to a speciic initial state, a special method named\r\n# __init__() may be defined.\r\n# For such a class, class instantiation automatically invokes __init__() for\r\n# newly created class instance.\r\n\r\nclass Complex:\r\n def __init__(self, realpart, imgpart):\r\n self.r = realpart\r\n self.i = imgpart\r\n\r\ny = Complex(3.0, -4.5)\r\nprint(y.r, y.i)",
"12345\n3.0 -4.5\n"
]
],
[
[
"<h2>Instance Objects</h2>",
"_____no_output_____"
]
],
[
[
"# The only operations understood by instance objects are attribute references\r\n# There are two kinds of valid attribute names: data attributes and methods.\r\n# Data attributes need not be declared; like local variables, they spring into\r\n# existence when they are first assigned to (but only for that instance)\r\n\r\nx.counter = 1\r\nwhile x.counter < 10:\r\n x.counter = x.counter*2\r\nprint(x.counter)\r\ndel x.counter\r\n\r\n# All attributes of a class that are function objects define corresponding\r\n# methods of its instances.\r\n\r\n# x.f is a valid method reference, since MyClass.f is a function.\r\n# But x.f is not the same thing as MyClass.f -- it is a method object, not a\r\n# function object",
"_____no_output_____"
]
],
[
[
"<h2>Method Objects</h2>",
"_____no_output_____"
]
],
[
[
"# Method objects can be stored away and called at a later time\r\nxf = x.f\r\na = 3\r\nwhile a > 0:\r\n print(xf()) # it is called like a function hence the ()\r\n a -= 1\r\n\r\n\r\n\"\"\"\r\nThe special thing about methods is that the instance object is passed as the\r\nfirst argument of the function. In our example, the call x.f() is exactly\r\nequivalent to MyClass.f(x). In general, calling a method with a list of n\r\narguments is equivalent to calling the corresponding function with an argument\r\nlist that is created by inserting the method’s instance object before the first\r\nargument.\r\n\r\n\r\n When a non-data attribute of an instance is referenced, the instance’s class\r\n is searched.\r\n If the name denotes a valid class attribute that is a function object, a method\r\n object is created by packing (pointers to) the instance object and the function\r\n object just found together in an abstract object:\r\n this is the method object. When the method object is called with an argument\r\n list, a new argument list is constructed containing the instance object and the\r\n argument list.\r\n And the function object is called with this new argument list.\r\n\"\"\"",
"hello world\nhello world\nhello world\n"
]
],
[
[
"<h2>Class and Instance variables</h2>",
"_____no_output_____"
]
],
[
[
"# Generally, instance variables are for data unique to each instance and class\r\n# variables are for attributes and methods shared by all instances of the\r\n# class\r\n\r\nclass Dog:\r\n\r\n kind = 'canine' # Class variables\r\n kinder = ['Lets see']\r\n\r\n def __init__(self, name):\r\n self.name = name # Instance variable\r\n\r\nd = Dog('Tom')\r\ne = Dog('Hercules')\r\nprint(d.kind)\r\nprint(e.kind)\r\nprint(d.name)\r\nprint(e.name)\r\nprint(\"Trying to change the immutable type object class variable\")\r\nd.kind = 'Perturbed'\r\nprint(d.kind)\r\nprint(e.kind)\r\nprint(\"Changing mutable type object class variable....surprise surprise:\")\r\nd.kinder[0] = 'Unperturbed'\r\nprint(d.kinder)\r\nprint(e.kinder)",
"canine\ncanine\nTom\nHercules\nTrying to change the immutable type object class variable\nPerturbed\ncanine\nChanging mutable type object class variable....surprise surprise:\n['Unperturbed']\n['Unperturbed']\n"
],
[
"# As the list 'kinder' is a mutable class variable, it is shared by all\r\n# objects and changes made to it by one instance are reflected in other\r\n# instances as well\r\n# This is an example why shared data should be avoided.\r\n\r\n# A better way to design this class would be\r\n\r\nclass Dog:\r\n def __init__(self, name):\r\n self.name = name\r\n self.kinder = [] # New empty list for each dog\r\n\r\n def add_kinder(self, kinder):\r\n self.kinder.append(kinder)\r\n\r\nd = Dog('Tom')\r\ne = Dog('Hercules')\r\nd.add_kinder('Perturbation')\r\ne.add_kinder('not perturbed... nopeee')\r\nprint(d.kinder)\r\nprint(e.kinder)",
"['Perturbation']\n['not perturbed... nopeee']\n"
]
],
[
[
"<h2>Random Remarks</h2>",
"_____no_output_____"
]
],
[
[
"\"\"\"\r\nData attributes may be referenced by methods as well as by ordinary users \r\n(“clients”) of an object. In other words, classes are not usable to implement\r\npure abstract data types. In fact, nothing in Python makes it possible to enforce\r\ndata hiding — it is all based upon convention.\r\n\r\nClients should use data attributes with care — clients may mess up invariants\r\nmaintained by the methods by stamping on their data attributes. Note that\r\nclients may add data attributes of their own to an instance object without\r\naffecting the validity of the methods, as long as name conflicts are\r\navoided — again, a naming convention can save a lot of headaches here.\r\n\r\nThere is no shorthand for referencing data attributes (or other methods!) from\r\nwithin methods. I find that this actually increases the readability of methods:\r\nthere is no chance of confusing local variables and instance variables when\r\nglancing through a method.\r\n\r\nOften, the first argument of a method is called self. This is nothing more than\r\na convention: the name self has absolutely no special meaning to Python. Note,\r\nhowever, that by not following the convention your code may be less readable\r\nto other Python programmers, and it is also conceivable that a class browser\r\nprogram might be written that relies upon such a convention.\r\n\r\nAny function object that is a class attribute defines a method for instances\r\nof that class. It is not necessary that the function definition is textually\r\nenclosed in the class definition: assigning a function object to a local\r\nvariable in the class is also ok.\r\n\r\n\"\"\"",
"_____no_output_____"
],
[
"# defining function outside the textual boundaries of a class\r\n\r\ndef f1(self, x, y):\r\n return min(x, x+y)\r\n\r\nclass C:\r\n f = f1\r\n def g(self):\r\n return 'hello world'\r\n\r\n h = g\r\n\r\n# Now f, g, and h are all attributes of class C, that refer to function\r\n# objects, and consequently they are all methods of instances of C - h being\r\n# exactly equivalent to g. Note that this practice usually only serves to\r\n# confuse the reader of a program\r\n\r\n# Methods may call other methods by using the self argument\r\n\r\nclass Bag:\r\n \r\n def __init__(self):\r\n self.data = []\r\n\r\n def add(self, x):\r\n self.data.append(x)\r\n\r\n def add2(self, x):\r\n self.add(x)\r\n self.add(x)\r\n",
"_____no_output_____"
]
],
[
[
"<h2>Inheritance</h2>",
"_____no_output_____"
]
],
[
[
"\"\"\"\r\nGeneral syntax:\r\n\r\nclass DerivedClassName(BaseClassName):\r\n statement1\r\n .\r\n .\r\n statementN\r\n\r\nThe name BaseClassName must be defined in a scope containing the derived class\r\ndefinition. In place of a base class name, other arbitrary expressions are also\r\nallowed. This can be useful, for example, when the base class is defined in\r\nanother module:\r\n\r\nclass DerivedClassName(module.BaseClassName):\r\n\r\n\r\nExecution of a derived class definition proceeds the same as for a base class.\r\nWhen the class object is constructed, the base class is remembered. This is\r\nused for resolving attribute references: if a requested attribute is not\r\nfound in the class, the search proceeds to look in the base class. This rule\r\nis applied recursively if the base class itself is derived from some other class.\r\n\r\nThere’s nothing special about instantiation of derived classes:\r\nDerivedClassName()creates a new instance of the class. Method references are\r\nresolved as follows: the corresponding class attribute is searched, descending\r\ndown the chain of base classes if necessary, and the method reference is valid\r\nif this yields a function object.\r\n\r\nDerived classes may override methods of their base classes. Because methods\r\nhave no special privileges when calling other methods of the same object, a\r\nmethod of a base class that calls another method defined in the same base class\r\nmay end up calling a method of a derived class that overrides it.\r\n(For C++ programmers: all methods in Python are effectively virtual.)\r\n\r\nAn overriding method in a derived class may in fact want to extend rather\r\nthan simply replace the base class method of the same name. There is a simple\r\nway to call the base class method directly: just call\r\nBaseClassName.methodname(self, arguments). This is occasionally useful to\r\nclients as well. (Note that this only works if the base class is accessible\r\nas BaseClassName in the global scope.)\r\n\r\nPython has two built-in functions that work with inheritance:\r\n•Use isinstance() to check an instance’s type: isinstance(obj, int) will be\r\nTrue only if obj.__class__ is int or some class derived from int.\r\n•Use issubclass() to check class inheritance: issubclass(bool, int) is True\r\nsince bool is a subclass of int. However, issubclass(float, int) is False\r\nsince float is not a subclass of int.\r\n\r\n\"\"\"",
"_____no_output_____"
]
],
[
[
"<h2>Multiple Inheritance</h2>",
"_____no_output_____"
]
],
[
[
"\"\"\"\r\nPython supports a form of multiple inheritance as well.\r\n\r\nclass DerivedClassName(Base1, Base2, Base3):\r\n statement1\r\n .\r\n .\r\n .\r\n statementN\r\n\r\n\r\nFor most purposes, in the simplest cases, you can think of the search for\r\nattributes inherited from a parent class as depth-first, left-to-right, not\r\nsearching twice in the same class where there is an overlap in the hierarchy.\r\nThus, if an attribute is not found in DerivedClassName, it is searched for in\r\nBase1, then (recursively) in the base classes of Base1, and if it was not\r\nfound there, it was searched for in Base2, and so on.\r\n\r\nIn fact, it is slightly more complex than that; the method resolution order\r\nchanges dynamically to support cooperative calls to super(). This approach\r\nis known in some other multiple-inheritance languages as call-next-method and\r\nis more powerful than the super call found in single-inheritance languages.\r\n\r\nDynamic ordering is necessary because all cases of multiple inheritance\r\nexhibit one or more diamond relationships (where at least one of the parent\r\nclasses can be accessed through multiple paths from the bottommost class).\r\nFor example, all classes inherit from object, so any case of multiple\r\ninheritance provides more than one path to reach object. To keep the base\r\nclasses from being accessed more than once, the dynamic algorithm linearizes\r\nthe search order in a way that preserves the left-to-right ordering specified\r\nin each class, that calls each parent only once, and that is monotonic\r\n(meaning that a class can be subclassed without affecting the precedence order\r\nof its parents). Taken together, these properties make it possible to design\r\nreliable and extensible classes with multiple inheritance.\r\n\r\n\"\"\"",
"_____no_output_____"
]
],
[
[
"<h2>Private Variables</h2>",
"_____no_output_____"
]
],
[
[
"\"\"\"\r\n“Private” instance variables that cannot be accessed except from inside an\r\nobject don’t exist in Python. However, there is a convention that is followed\r\nby most Python code: a name prefixed with an underscore (e.g. _spam) should be\r\ntreated as a non-public part of the API (whether it is a function, a method or\r\na data member). It should be considered an implementation detail and subject\r\nto change without notice.\r\n\r\nSince there is a valid use-case for class-private members (namely to avoid name\r\nclashes of names with names defined by subclasses), there is limited support for\r\nsuch a mechanism, called name mangling. Any identifier of the form __spam\r\n(at least two leading underscores, at most one trailing underscore) is textually\r\nreplaced with _classname__spam, where classname is the current class name with\r\nleading underscore(s) stripped. This mangling is done without regard to the\r\nsyntactic position of the identifier, as long as it occurs within the definition\r\nof a class.\r\n\r\nName mangling is helpful for letting subclasses override methods without\r\nbreaking intraclass method calls. For example:\r\n\r\n\"\"\"\r\n\r\nclass Mapping:\r\n def __init__(self, iterable):\r\n self.items_list = []\r\n self.__update(iterable)\r\n\r\n def update(self, iterable):\r\n for item in iterable:\r\n self.items_list.append(item)\r\n \r\n __update = update # Private copy of update() method\r\n\r\nclass MappingSubclass(Mapping):\r\n \r\n def update(self, keys, values):\r\n for item in zip(keys, values):\r\n self.items_list.append(item)\r\n\r\n\"\"\"\r\nThis example would work even if MappingSubclass were to introduce a __update\r\nidentifier since it is replaced with _Mapping__update in the Mapping class\r\nand _MappingSubclass__update in the MappingSubclass class respectively.\r\n\r\nNote that the mangling rules are designed mostly to avoid accidents; it still\r\nis possible to access or modify a variable that is considered private.\r\n\"\"\"",
"_____no_output_____"
]
],
[
[
"<h2>Odds and Ends</h2>",
"_____no_output_____"
]
],
[
[
"# An empty class definition can be used when a data type similar to the\r\n# \"struct\" data type in C is needed, bundling together a few data items\r\n\r\nclass SteveCurrey:\r\n pass\r\n\r\nthreept = SteveCurrey()\r\n\r\nthreept.rivalname = 'Boston'\r\nthreept.date = '04-June-1322'\r\nthreept.points = 66\r\n\r\n\"\"\"\r\nA piece of Python code that expects a particular abstract data type can often\r\nbe passed a class that emulates the methods of that data type instead. For\r\ninstance, if you have a function that formats some data from a file object,\r\nyou can define a class with methods read() and readline() that get the data\r\nfrom a string buffer instead and pass it as an argument.\r\n\r\nInstance method objects have attributes too: m.__self__ is the instance object\r\nwith the method m(), and m.__func__ is the function object corresponding to\r\nthe method.\r\n\"\"\"",
"_____no_output_____"
]
],
[
[
"<h2>Iterators</h2>",
"_____no_output_____"
]
],
[
[
"\"\"\"\"\r\nThe use of iterators pervades and unifies Python. Behind the scenes, the for\r\nstatement calls iter() on the container object. The function returns an iterator\r\nobject that defines the method __next__() which accesses elements in the\r\ncontainer one at a time. When there are no more elements, __next__() raises a\r\nStopIteration exception which tells the for loop to terminate. You can call the\r\n__next__() method using the next() built-in function; this example shows how it\r\nall works:\r\n\"\"\"\r\n\r\ns = 'abc'\r\nit = iter(s)\r\nit",
"_____no_output_____"
],
[
"next(it)",
"_____no_output_____"
],
[
"next(it)",
"_____no_output_____"
],
[
"next(it)",
"_____no_output_____"
],
[
"next(it)",
"_____no_output_____"
],
[
"\"\"\"\r\nAdding iterator behaviour to your classes\r\n\r\nDefine an __iter__() method which returns an object with a __next__() method.\r\nIf the class defines __next__(), then __iter__() can just return self:\r\n\"\"\"\r\n\r\nclass Reverse:\r\n \"\"\"Iterator for looping over a sequence backwards.\"\"\"\r\n\r\n def __init__(self, data):\r\n self.data = data\r\n self.index = len(data)\r\n\r\n def __iter__(self):\r\n return self\r\n\r\n def __next__(self):\r\n if self.index == 0:\r\n raise StopIteration\r\n self.index = self.index - 1\r\n return self.data[self.index]\r\n\r\nrevi = Reverse('spam')\r\n\r\nfor char in revi:\r\n print(char)",
"m\na\np\ns\n"
]
],
[
[
"<h2>Generators</h2>",
"_____no_output_____"
]
],
[
[
"\"\"\"\r\nGenerators are simple and powerful tools for creating iterators. They are\r\nwritten like regular functions but use the yield statement whenever they want\r\nto return data. Each time next() is called on it, the generator resumes where\r\nit left off (it remembers all the data values and which statement was last\r\nexecuted).\r\n\"\"\"\r\n\r\ndef reverse(data):\r\n for index in range(len(data) - 1, -1, -1): # Change the values of range\r\n yield data[index] # (unrelated)\r\n\r\nfor char in reverse('golf'):\r\n print(char)\r\nprint(\"\\n\\n\")\r\nfor i in range(len('froggie') - 1, -1, -1):\r\n print('froggie'[i])\r\n",
"f\nl\no\ng\n\n\n\ne\ni\ng\ng\no\nr\nf\n"
]
],
[
[
"<h2>Generator expressions</h2>",
"_____no_output_____"
]
],
[
[
"\"\"\"\r\nSome simple generators can be coded succinctly as expressions using a syntax\r\nsimilar to list comprehensions but with parentheses instead of square brackets.\r\nThese expressions are designed for situations where the generator is used right\r\naway by an enclosing function. \r\n\"\"\"\r\n\r\nprint(sum(i*i for i in range(10)))\r\nx_vec = [10, 20, 30]\r\ny_vec = [11, 22, 33]\r\nprint(sum(x*y for x,y in zip(x_vec, y_vec)))\r\n\r\n# uniques = set(word for line in page for word in line.split())\r\n\r\ndata = 'fwoggie'\r\nlist(data[i] for i in range(len(data)-1, -1, -1))",
"285\n1540\n"
]
],
[
[
"# Thank You",
"_____no_output_____"
],
[
"<h2>\r\nI will try my best to keep this repository updated and add other parts<br>\r\nof the Python tutorial from the docs that I did not think were immediately<br>\r\nimportant or of prime importance. However, for now, other projects call! :')<br>\r\nI would be absolutely delighted to hear from y'all and invite contributions<br>\r\nso that we can all work to make this better and more helpful for people<br>\r\nstarting out with Python!<br>\r\n<br>\r\nHope it was fun and engaging, and valuable. Most of the credit certainly<br>\r\nshould go to the Python Tutorial from the Python Docs since most of the<br>\r\ncontent in here is almost directly and exactly from that.<br>\r\nThat said, I have tried to make my own additions or omissions, either in<br>\r\nexplanations or code examples, as possible, and can only hope that it added<br>\r\nsome value to this :')<br>\r\n<br>\r\n<br>\r\n</h2>",
"_____no_output_____"
],
[
"# Congratulations and all the very best! :)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
ecd11743845968bb911e9a53b37e789419532db0 | 30,869 | ipynb | Jupyter Notebook | draw.ipynb | shane-breeze/CMS-Material-Budget | 59692657882d664be53e997cd5650a4f77e988cb | [
"MIT"
] | null | null | null | draw.ipynb | shane-breeze/CMS-Material-Budget | 59692657882d664be53e997cd5650a4f77e988cb | [
"MIT"
] | null | null | null | draw.ipynb | shane-breeze/CMS-Material-Budget | 59692657882d664be53e997cd5650a4f77e988cb | [
"MIT"
] | null | null | null | 132.484979 | 12,600 | 0.865464 | [
[
[
"import uproot\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.rcParams[\"figure.dpi\"] = 100\nplt.rcParams[\"text.usetex\"] = True",
"_____no_output_____"
],
[
"def read_tree(path, tree):\n return uproot.open(path)[tree].pandas.df()\n\ndef calc_xw(x, w, bins):\n count, _ = np.histogram(x, bins=bins)\n hist, _ = np.histogram(x, bins=bins, weights=w)\n hist /= count\n return bins[:-1], hist",
"_____no_output_____"
],
[
"bins = np.linspace(-5, 5, 201)\n\nconfigs = [\n {\n \"label\": \"BeamPipe\",\n \"path\": \"data/matbdg_det-Beam.root\",\n \"tree\": \"T1\",\n \"color\": \"#cab2d6\",\n }, {\n \"label\": \"Tracker\",\n \"path\": \"data/matbdg_det-Tracker.root\",\n \"tree\": \"T1\",\n \"color\": \"#a6cee3\",\n }, {\n \"label\": \"ECAL\",\n \"path\": \"data/matbdg_det-ECAL.root\",\n \"tree\": \"T1\",\n \"color\": \"#b2df8a\",\n }, {\n \"label\": \"HCAL\",\n \"path\": \"data/matbdg_det-HCAL.root\",\n \"tree\": \"T1\",\n \"color\": \"#fdbf6f\",\n }, {\n \"label\": \"Magnet\",\n \"path\": \"data/matbdg_det-Magnet.root\",\n \"tree\": \"T1\",\n \"color\": \"#d9d9d9\",\n }, {\n \"label\": \"Muon\",\n \"path\": \"data/matbdg_det-Muon.root\",\n \"tree\": \"T1\",\n \"color\": \"#fb9a99\",\n }\n]",
"_____no_output_____"
],
[
"for config in configs:\n df = read_tree(config[\"path\"], config[\"tree\"])\n df.to_hdf(\n \"data/matbdg.h5\", config[\"label\"],\n format='table', append=False,\n complib='zlib', complevel=9,\n )",
"_____no_output_____"
],
[
"data = {\n \"xvalue\": [],\n \"wvalue\": [],\n \"labels\": [],\n \"colors\": [],\n}\nfor config in configs:\n df = read_tree(config[\"path\"], config[\"tree\"])\n x, w = calc_xw(df[\"Particle Eta\"], df[\"MB\"], bins)\n data[\"xvalue\"].append(x)\n data[\"wvalue\"].append(w)\n data[\"labels\"].append(config[\"label\"])\n data[\"colors\"].append(config[\"color\"])\n \nplt.hist(\n data[\"xvalue\"], bins=bins, weights=data[\"wvalue\"],\n label=data[\"labels\"], color=data[\"colors\"], stacked=True,\n)\nplt.legend(\n columnspacing=1.,\n loc=9, ncol=3,\n)\nplt.xlim(-5, 5)\nplt.ylim(0, 1.4*sum(data[\"wvalue\"]).max())\nplt.xlabel('$\\eta$')\nplt.ylabel('$x/\\lambda_0$')\nplt.savefig(\n \"images/radiation_lengths.png\",\n bbox_inches='tight',\n)\npass",
"_____no_output_____"
],
[
"data = {\n \"xvalue\": [],\n \"wvalue\": [],\n \"labels\": [],\n \"colors\": [],\n}\nfor config in configs:\n df = read_tree(config[\"path\"], config[\"tree\"])\n x, w = calc_xw(df[\"Particle Eta\"], df[\"IL\"], bins)\n data[\"xvalue\"].append(x)\n data[\"wvalue\"].append(w)\n data[\"labels\"].append(config[\"label\"])\n data[\"colors\"].append(config[\"color\"])\n \nplt.hist(\n data[\"xvalue\"], bins=bins, weights=data[\"wvalue\"],\n label=data[\"labels\"], color=data[\"colors\"], stacked=True,\n)\nplt.legend(\n columnspacing=1.,\n loc=9, ncol=3,\n)\nplt.xlim(-5, 5)\nplt.ylim(0, 1.4*sum(data[\"wvalue\"]).max())\nplt.xlabel('$\\eta$')\nplt.ylabel('$x/x_0$')\nplt.savefig(\n \"images/interaction_lengths.png\",\n bbox_inches='tight',\n)\npass",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ecd11d390b0e9e8d6272312c5c6e859638dacf76 | 39,064 | ipynb | Jupyter Notebook | notebooks/02-Fundamentals.ipynb | uc-python/intro-python-datasci | 52484f9690bd8bbf42ad327b4326c2f593e6d4cf | [
"MIT"
] | 30 | 2019-02-19T02:21:01.000Z | 2022-03-09T14:19:31.000Z | notebooks/02-Fundamentals.ipynb | slibkind/intro-python-datasci | 53c0ca3e7f2b4a863b4abc362002dc42fb5eebfb | [
"MIT"
] | 45 | 2019-04-14T15:55:53.000Z | 2022-02-09T13:19:49.000Z | notebooks/02-Fundamentals.ipynb | uc-python/intro-python-datasci | 52484f9690bd8bbf42ad327b4326c2f593e6d4cf | [
"MIT"
] | 23 | 2019-05-14T22:59:47.000Z | 2022-03-30T17:51:01.000Z | 22.424799 | 367 | 0.481543 | [
[
[
"# Python Fundamentals",
"_____no_output_____"
],
[
"> Make easy things easy and hard things possible.\n> \n> \\- A slogan of Perl (a predecessor language to Python)",
"_____no_output_____"
],
[
"## Applied Review\n### Python and Jupyter",
"_____no_output_____"
],
[
"- Python is a flexible, general-purpose language that is popular in many fields, but particularly in data science.",
"_____no_output_____"
],
[
"- Jupyter is an IDE, or *Integrated Development Environment*, that lets us view and run code in notebooks.",
"_____no_output_____"
],
[
"- We are using Jupyter via Binder in this course.",
"_____no_output_____"
],
[
"## Python at Its Simplest: Basic Data Types and Math\nWhile Python can be used to write very complicated programs, one of its strengths is that easy things are still easy.\nFor example, Python can be a calculator.",
"_____no_output_____"
]
],
[
[
"1 + 2",
"_____no_output_____"
],
[
"12 * 4",
"_____no_output_____"
]
],
[
[
"Python allows you to *comment* your code -- to leave notes for yourself or others about the code.\nComments start with a `#` and are ignored by Python when it runs your code.",
"_____no_output_____"
]
],
[
[
"# The ** operator is exponentiation.\n2 ** 3",
"_____no_output_____"
]
],
[
[
"Once you start doing math, you may want to keep the values you calculate for later use.",
"_____no_output_____"
],
[
"Python allows you to do this with *variables* -- words that you choose to represent values you've stored.",
"_____no_output_____"
]
],
[
[
"# Place the result of \"5 * 2\" in a variable called \"x\".\nx = 5 * 2",
"_____no_output_____"
]
],
[
[
"This process of storing something in a variable is often called **variable assignment**, or simply \"assignment\" for short.\nYou can assign almost anything to a variable.",
"_____no_output_____"
]
],
[
[
"# \"Assign\" the value 42 to the variable \"answer\".\nanswer = 42",
"_____no_output_____"
]
],
[
[
"You can then use the stored values in new calculations.",
"_____no_output_____"
]
],
[
[
"answer + 5",
"_____no_output_____"
],
[
"ten = 10\neleven = 11\nten + eleven",
"_____no_output_____"
]
],
[
[
"Python lets you name your variables whatever you want – the only rule is that they must be composed of numbers, letters, and underscores, and they cannot begin with a number.",
"_____no_output_____"
],
[
"It's a good idea to take advantage of this flexibility and name your variables with descriptions that help you remember what they contain.",
"_____no_output_____"
],
[
"For example, calling your variables `x`, `y`, and `z` is likely to lead to forgetting what you've stored where (unless you're working with coordinates, a domain where those names have meanings).",
"_____no_output_____"
],
[
"More descriptive names, like `number_of_items` or `size_of_container`, are better.",
"_____no_output_____"
]
],
[
[
"# Perfectly good variable name\nmy_3rd_favorite_number = 18",
"_____no_output_____"
],
[
"# Legal, but undescriptive, variable name\na = 7",
"_____no_output_____"
],
[
"# Illegal variable name -- it starts with a number\n4_plus_1 = 4 + 1",
"_____no_output_____"
]
],
[
[
"If you try to name a variable something illegal, Python will gently remind you to follow the rules with a `SyntaxError` and an arrow indicating the location of the error.",
"_____no_output_____"
],
[
"<font style=\"color:#800;\">\n <strong>Caution</strong>:<br><em>Sometimes Python doesn't pinpoint the error very well, and the error will not be in the same place as the arrow.</em>\n</font>",
"_____no_output_____"
],
[
"<font class=\"your_turn\">\n Your Turn\n</font>\n\n1. 4k monitors, counterintuitively, typically have a resolution of 3840x2160. Create two variables, `width` and `height`, and store 3840 and 2160 in them (respectively).\n2. How many total pixels are in a display with this resolution? *Hint: fill in the blanks with variable names:* `pixels = ___ * ___`",
"_____no_output_____"
],
[
"## Beyond Integers\n\nFortunately, Python can handle values beyond integers.\nIt's happy to work with decimal numbers.",
"_____no_output_____"
]
],
[
[
"1 / 3",
"_____no_output_____"
],
[
"1.5 * 1.5",
"_____no_output_____"
]
],
[
[
"In computer science lingo, decimal numbers are often called **floating point numbers**, or **floats** for short.",
"_____no_output_____"
],
[
"The name refers to how such numbers are stored by a computer internally, but you don't need to worry about that.\nJust be aware that many people on the internet and in data science industry will speak in terms of \"floats\" and \"ints\" when they refer to numbers in Python.",
"_____no_output_____"
],
[
"Python also can work with text data, like words and sentences.",
"_____no_output_____"
]
],
[
[
"my_name = 'ethan'\nmy_hobbies = 'coding, reading, basketball'",
"_____no_output_____"
]
],
[
[
"In Python, these bits of text are called **strings** and are enclosed in quotation marks.\nBoth single quotes (`'`) and double quotes (`\"`) are fine, but most Pythonistas use single quotes as a matter of convention.",
"_____no_output_____"
],
[
"Conveniently, Python lets you \"add\" strings together to compose longer strings.",
"_____no_output_____"
]
],
[
[
"'Monty' + ' ' + 'Python'",
"_____no_output_____"
],
[
"first_name = 'Guido'\nlast_name = 'van Rossum'\n# Remember to add a space between words!\nfirst_name + ' ' + last_name",
"_____no_output_____"
]
],
[
[
"The last kind of value that we'll talk about is a **boolean**, or a True/False value.",
"_____no_output_____"
],
[
"Python recognizes the words `True` and `False` as **keywords** -- words that have an implicit meaning in the language.",
"_____no_output_____"
],
[
"That means you can assign them to variables as you can with other data types.",
"_____no_output_____"
]
],
[
[
"is_the_moon_made_of_cheese = False\nis_this_the_best_python_class = True",
"_____no_output_____"
]
],
[
[
"<font class=\"your_turn\">\n Your Turn\n</font>\n\n1. Overwrite the `first_name` and `last_name` variables with your name, and run `first_name + ' ' + last_name` again -- make sure it produces what you expect!\n2. What happens when you try to add together two different kinds of values, like an integer and a string? Does this behavior make sense?",
"_____no_output_____"
],
[
"## Lists and Dictionaries",
"_____no_output_____"
],
[
"So far we've worked with single values: numbers, strings, and booleans.\nBut Python also supports more complex data types, sometimes called *data structures*.",
"_____no_output_____"
],
[
"The two most common complex data types are **lists** and **dictionaries**.",
"_____no_output_____"
],
[
"### Lists",
"_____no_output_____"
],
[
"As you might expect, a list is an ordered collection of things.\nLists are represented using brackets (`[]`).",
"_____no_output_____"
]
],
[
[
"# A list of integers\nnumbers = [1, 2, 3]\nnumbers",
"_____no_output_____"
],
[
"# A list of strings\nstrings = ['abc', 'def']\nstrings",
"_____no_output_____"
]
],
[
[
"Lists are highly flexible.\nThey can contain heterogeneous data (i.e. strings, booleans, and numbers can all be in the same list) and lists can even contain other lists!",
"_____no_output_____"
]
],
[
[
"combo = ['a', 'b', 3, 4]\ncombo_2 = [True, 'True', 1, 1.0]",
"_____no_output_____"
],
[
"# Note that the last element of the list is another list!\nnested_list = [1, 2, 3, [4, 5]]\nnested_list",
"_____no_output_____"
]
],
[
[
"Individual elements of a list can be accessed by specifying a location in brackets.\nThis is called **indexing**.",
"_____no_output_____"
],
[
"Beware: Python is **zero-indexed**, so the first element is element 0!",
"_____no_output_____"
]
],
[
[
"letters = ['a', 'b', 'c']\nletters[0]",
"_____no_output_____"
],
[
"letters[2]",
"_____no_output_____"
]
],
[
[
"Specifying an invalid location will raise an error.",
"_____no_output_____"
]
],
[
[
"letters[4]",
"_____no_output_____"
]
],
[
[
"<font style=\"color:#800;\">\n <strong>Caution</strong>:<br><em>Most programming languages are zero indexed, so a list with 3 elements has valid locations [0, 1, 2]. But this means that there is no element #3 in a 3-element list! Trying to access it will cause an out-of-range error. This is a common mistake for those new to programming (and sometimes it bites the veterans too).</em>\n</font>",
"_____no_output_____"
],
[
"Not only can you read individual elements using indexing; you can also *overwrite* elements.",
"_____no_output_____"
]
],
[
[
"greek = ['alpha', 'beta', 'delta']\ngreek[2] = 'gamma'\ngreek",
"_____no_output_____"
]
],
[
[
"### Dictionaries",
"_____no_output_____"
],
[
"Dictionaries are collections of **key-value pairs**.\nThink of a real dictionary -- you look up a word (a *key*), to find its definition (a *value*).\nAny given key can have only one value.",
"_____no_output_____"
],
[
"This concept has many names depending on language: map, associative array, dictionary, and more. ",
"_____no_output_____"
],
[
"In Python, dictionaries are represented with curly braces. Colons separate a key from its value, and (like lists) commas delimit elements.",
"_____no_output_____"
]
],
[
[
"ethan = {'first_name': 'Ethan',\n 'last_name': 'Swan',\n 'alma_mater': 'Notre Dame',\n 'employer': '84.51˚',\n 'zip_code': 45208}\nethan",
"_____no_output_____"
],
[
"brad = {'first_name': 'Brad',\n 'last_name': 'Boehmke',\n 'alma_mater': 'NDSU',\n 'employer': '84.51˚',\n 'zip_code': 45385}\nbrad",
"_____no_output_____"
]
],
[
[
"Values can be looked up and set by passing a key in brackets.",
"_____no_output_____"
]
],
[
[
"ethan['zip_code']",
"_____no_output_____"
],
[
"ethan['employer']",
"_____no_output_____"
],
[
"ethan['employer'] = 'Eighty Four Fifty One'\nethan",
"_____no_output_____"
]
],
[
[
"Dictionaries, like lists, are very flexible.\nKeys are generally strings (though some other types are allowed), and values can be anything -- including lists or other dictionaries!",
"_____no_output_____"
],
[
"<font class=\"your_turn\">\n Your Turn\n</font>\n\n1. Create a list of the first 10 even numbers. Use indexing to find the 4th even number. *Remember that the 4th element is at location 3 because of zero-indexing!*\n2. Imagine you need a way to quickly determine a company's CEO given the company name. You could use a dictionary such that `ceos['Apple'] = 'Tim Cook'`. Try to add a few more keys to this starter dictionary. For example, Bob Iger is the CEO of Disney.\n\n```python\nceos = {'Apple': 'Tim Cook',\n 'Microsoft': 'Satya Nadella'}\n```\n\n*How might you approach #2 if you needed to look up both the CEO and the CFO? What data structure would you use? There are several possible solutions.*",
"_____no_output_____"
],
[
"## DataFrames\nIn data science, the most important complex data structure is the **DataFrame**.\nDataFrames are a collection of tabular data -- you might think of them as *tables* or *datasets*, depending on your background.",
"_____no_output_____"
],
[
"Let's take a look at one.",
"_____no_output_____"
]
],
[
[
"# Don't worry about this \"boilerplate\" code for now.\nimport pandas as pd\nplanes = pd.read_csv('../data/planes.csv')",
"_____no_output_____"
],
[
"# Asking for the \"head\" of a DataFrame will show you the first 5 rows.\nplanes.head()",
"_____no_output_____"
]
],
[
[
"DataFrames have **column names** (tailnum, year, type, etc) and **row indexes** (the bold numbers on the left, starting at zero).",
"_____no_output_____"
]
],
[
[
"# Asking for the \"head\" of a DataFrame will show you the first 5 rows.\nplanes.head()",
"_____no_output_____"
]
],
[
[
"The values (elements) within the DataFrame are the Python types we covered above: integers, floats, strings, and booleans.",
"_____no_output_____"
],
[
"<font style=\"color:#008;\">\n <strong>Question</strong>:<br><em>Which of these columns are strings?</em>\n</font>",
"_____no_output_____"
],
[
"Because DataFrames can hold almost any kind of data and support powerful *data wrangling* features, they have become the basic unit of data science work.",
"_____no_output_____"
],
[
"We will have a whole lesson later on DataFrames, so for now we'll move on.",
"_____no_output_____"
],
[
"## Determining What Type of Data Structure Something Is",
"_____no_output_____"
],
[
"How can you determine the type of a variable?\nPass it to the `type` function (we'll talk more about functions later).",
"_____no_output_____"
]
],
[
[
"x = 5\ntype(x)",
"_____no_output_____"
],
[
"type(planes)",
"_____no_output_____"
]
],
[
[
"You can even pass values directly to the `type` function.",
"_____no_output_____"
]
],
[
[
"type(7.2)",
"_____no_output_____"
]
],
[
[
"# Questions\n\nAre there any questions before we move on?",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
ecd1228832d14ea1015147706f71da85bda76e8f | 19,891 | ipynb | Jupyter Notebook | assignments/2021-04-17/Tony_assignment_003_marked.ipynb | qqiang00/ElementaryMathPython | 7fa723335ca342b867d51776d1f009066c50092d | [
"MIT"
] | null | null | null | assignments/2021-04-17/Tony_assignment_003_marked.ipynb | qqiang00/ElementaryMathPython | 7fa723335ca342b867d51776d1f009066c50092d | [
"MIT"
] | null | null | null | assignments/2021-04-17/Tony_assignment_003_marked.ipynb | qqiang00/ElementaryMathPython | 7fa723335ca342b867d51776d1f009066c50092d | [
"MIT"
] | null | null | null | 36.564338 | 1,464 | 0.576291 | [
[
[
"# Lecture 3:input() and condition control 接受输入和条件控制",
"_____no_output_____"
],
[
"- **Name (姓名)**: [Write Your Name Here]\n- **Date (日期)**: [Write the Date on which you completed this assignment]\n\n\n- **Score (成绩)**:**B**\n- **Comment By Teacher (评语)**: Good. For the second question, it is required that you use the `if` `else` key words to control the code flow; otherwise, it will not always give a correct output.",
"_____no_output_____"
],
[
"## Problem\nScreen and Keyboard are two main input&output devices of a computer. They are a bit like human's mouth and ears. We learned how to print out the data to screen. How does our program get data from keyboard? How can our program print out different information according to different data received from keyboard?\n\n屏幕和键盘是一个计算机的主要的输入/输出设备。他们有点像人类的嘴巴和眼睛。我们已经学习了如何把数据输出显示到屏幕。我们的程序如何能从键盘获取信息呢?我们的程序如何能根据不同的输入给出不同的输出呢?",
"_____no_output_____"
],
[
"## Objective 学习目标\n\n- Learn two data types: `string` and `int` 学习两种数据类型:\"字符串\"和\"整数型\"\n- Learn to receive data from keyboard during runtime 学习在程序运行时从键盘获得数据\n- Convert data from string to int if possible 在可能的情况下把数据从字符串转化为数字\n- Use `if` to control program to provide different output 使用if控制程序输出不同的内容\n- Write multiple lines of code in one cell and learn indentation in Python coding 在一个单元格中书写多行代码并学习Python代码中的缩进格式\n 1. start with `if`, `else` key words to start a condition control statement 使用`if`,`else`关键词来引导一句条件控制代码\n 2. use `==` to check equal 使用`==`来判断其左右两边是否相等\n 3. use `:` at the end of a `if`, `else` statement to start the code block that belongs to this statement 使用冒号`:`来结束这条条件控制语句并引导其管辖的多行代码。\n 4. codes belong to the `if`, or `else` statement should indent 4 letters compare with the `if` or `else` statement. 与`if`或`else`语句行相比较,属于`if`或`else`管辖的代码应该有4个字母长度的缩进。",
"_____no_output_____"
],
[
"## Math\n\n- Compare numbers using $\\gt$ $\\lt$ $\\ne$ $\\leq$ $\\geq$ 比较数的大小\n- Integer 整数, Decimal 小数",
"_____no_output_____"
],
[
"## Python",
"_____no_output_____"
]
],
[
[
"# Each data belongs to a Type (class) 每一个数据都属于某一个类型(类)\n# We've already met two different typs of data: string and int\n# 我们已经接触了两种数据类型:字符串和整数\n# Python automatically infer the type of a data\n# Python会自动推断一个数据的类型\n# Use type() to get a type of data\n# 使用 Type() 来获取一个数据的类型\nYunzi_name = \"Yunzi\"\nprint(type(Yunzi_name))\nYunzi_age = \"10\"\nprint(type(Yunzi_age))\nYunzi_age2 = 10\nprint(type(Yunzi_age2))",
"_____no_output_____"
],
[
"Yunzi_name = \"Yunzi\"\ntype(Yunzi_name)",
"_____no_output_____"
],
[
"Yunzi_age = \"10\"\ntype(Yunzi_age)",
"_____no_output_____"
],
[
"Yunzi_age2 = 10\ntype(Yunzi_age2)",
"_____no_output_____"
],
[
"number1 = 0\ntype(number1)",
"_____no_output_____"
],
[
"number2 = -2\ntype(number2)",
"_____no_output_____"
],
[
"number3 = 0.0\ntype(number3)",
"_____no_output_____"
],
[
"age_sophie_str = input(\"Please input Sophie's age:\")\nage_sophie = int(age_sophie)\nprint(\"Sophie's age is: \", age_sophie)\nage_tony = input(\"Please input Tony's age:\")\nage_tony = int(age_tony)\nprint(\"Tony's age is: \", age_tony)\n\nif age_sophie > age_tony:\n print(\"Sophie is older than Tony.\")\nelif age_sophie == age_tony:\n print(\"Sophie and Tony are same old.\")\nelse:\n print(\"Tony is older than Sophie.\")",
"_____no_output_____"
],
[
"age_sophie_1 = input(\"Please input Sophie's age:\")\nprint(type(age_sophie_str))\nage_sophie = int(age_sophie_1)\nprint(type(age_sophie))\nprint(type(age_sophie_1))",
"Please input Sophie's age: 1234 \n<class 'str'>\n<class 'int'>\n<class 'str'>\n"
],
[
"print(\"how old are you?\")",
"_____no_output_____"
],
[
"input(\"how old are you?\")",
"_____no_output_____"
],
[
"age = input(\"How old are you?\")",
"_____no_output_____"
],
[
"print(age)",
"_____no_output_____"
],
[
"print(\"You are\", age, \"yeas old.\")",
"_____no_output_____"
],
[
"age_celine = input(\"How are you?\")\nprint(\"You are\", age_celine, \"yeas old.\")",
"_____no_output_____"
],
[
"mood = input(\"How are you?\")\nprint(\"you are {}.\".format(mood))\n# good\n# not good.",
"_____no_output_____"
],
[
"mood = input(\"How are you?\")\nprint(\"you are {}.\".format(mood))\nif mood == \"good\": # 如果\n print(\"I am good too.\")\n print(\"I am happy to see you are good.\")\nelse: # 其它情况\n print(\"Why are you not good?\")\n print(\"Didn't you have your lunch?\")",
"How are you?happy\nyou are happy.\nWhy are you not good?\nDidn't you have your lunch?\n"
],
[
"mood = input(\"How are you?\")\nprint(\"you are {}.\".format(mood))\nif mood == \"good\" or mood == \"Good\" or mood == \"GOOD\": # 如果\n print(\"I am good too.\")\n print(\"I am happy to see you are good.\")\nelse: # 其它情况\n print(\"Why are you not good?\")\n print(\"Didn't you have your lunch?\")",
"How are you?Good\nyou are Good.\nI am good too.\nI am happy to see you are good.\n"
],
[
"mood = input(\"How are you?\")\nprint(\"you are {}.\".format(mood))\nif mood in [\"good\", \"Good\", \"GOOD\"]:\n print(\"I am good too.\")\n print(\"I am happy to see you are good.\")\nelse: # 其它情况\n print(\"Why are you not good?\")\n print(\"Didn't you have your lunch?\")",
"How are you?GOOD\nyou are GOOD.\nI am good too.\nI am happy to see you are good.\n"
]
],
[
[
"## Did you know?\n- all data in computer is represented by 1 and 0. 计算机中的所有数据都是用1和0来表示的。",
"_____no_output_____"
],
[
"## Exercise\n1. Write multi-line of Python codes in one cell to calculate and print out the sum of two integers that you input from the keyboard. 在一个代码单元格里书写多行Python代码来计算你从键盘输入的两个整数的和并将和打印输出\nRequirements: 要求:\n - the codes you write receive two number strings from keyboard 你的代码能够从键盘接受两个数字字符串\n - convert these two strings to two Integer numbers, assign them to two variables. The names of the two Integer variables can be decided as you like 将这两个字符串转化为两个整数型数字并将其赋值给两个变量,变量名可以根据你自己的喜好来设定\n - calculate the sum of the two Integer variables, assign the result to a new Variable named `result` 计算这两个整型变量的和,并将结果赋值给一个叫`result`的变量\n - print out the type of the `result` variable 打印输出变量`result`的数据类型\n - display the result on screen with a readable sentence. 打印输出一个通俗易懂的句子来显示你计算得到的结果\n \n Run and test 5 times your codes with the following inputs (num1, num2) for each test. Observe whether the result is equal to the Sum for each test 分别使用下表中的num1,num2的值作为键盘输入运行并测试你的代码共计5次,观察结果是否与对应的Sum一样\n \n **Your should run the same code on all test data; that being said, you may not change the codes between each run.** \n **你应该用同样的代码来运行所有的测试数据,也就是说,你不应该在两次测试间隙修改你的代码**\n \n | num1 | num2 | Output |\n | ----------- |:------------:| ------------------:|\n | 12 | 12 | The sum is 24 |\n | 18 | 14 | The sum is 32 |\n | 0 | 4 | The sum is 4 |\n | 1091 | 0 | The sum is 1091 |\n | 0 | 0 | The sum is 0 |\n ",
"_____no_output_____"
]
],
[
[
"Num1 = input(\"Num1 = \")\nNum1 = int(Num1)\nNum2 = input(\"Num2=\")\nNum2 = int(Num2)\nSum = Num1 + Num2\nprint (\"The sum is\",Sum)",
"_____no_output_____"
]
],
[
[
"2. Write multi-line of Python codes in one cell to calculate and print out the perimeter and area of a rectagle with the length and width provided by keyboard. 在一个代码单元格里书写多行Python代码来计算一个长方形的周长和面积,确定这个长方形的长和宽从键盘输入得到。\nRequirements: 要求:\n - the codes you write receive two number strings from keyboard indicating the length and width of a rectangle 你的代码能够从键盘接受两个数字字符串分别表示长方形的长和宽\n - convert these two strings to two Integer numbers, assign them to two variables. The names of the length and width should be easy to understand 将这两个字符串转化为两个整数型数字并将其赋值给表示长和宽的两个变量,要求这两个变量名直观易看懂\n - Check whether the length and width provided can form a rectangle. If not, print out \"Not a rectangle\"; otherwise, continue the following steps\n - calculate the perimiter and the area of this rectangle, assign the result to `perimeter` and `area` variable 计算这个长方形的周长和,并将结果分别赋值给名为`perimeter`和`area`的变量\n - print out the type of the `sum` variable 打印输出变量`result`的数据类型\n - display the result on screen with a readable sentence. 打印输出一个通俗易懂的句子来显示你计算得到的结果\n\n Run and test 5 times your codes with the following inputs (length, width) for each test. Observe whether the results are equal to the Perimeter and Area for each test 分别使用下表中的length和width的值作为键盘输入运行并测试你的代码共计5次,观察结果是否与对应的Perimiter和Area值一样\n \n **Your should run the same code on all test data; that being said, you may not change the codes between each run.** \n **你应该用同样的代码来运行所有的测试数据,也就是说,你不应该在两次测试间隙修改你的代码**\n \n Hint: use `if` to control the output\n 提示:使用`if` 来控制输出\n \n | length | width | output |\n | --------- |:----------:|:-------------------------------:|\n | 12 | 12 | perimeter is: 48, area is: 144 |\n | 18 | 14 | perimeter is: 48, area is: 144 |\n | 0 | 4 | Not a rectangle |\n | 1091 | 0 | Not a rectangle |\n | 0 | 0 | Not a rectangle |",
"_____no_output_____"
]
],
[
[
"L =input(\"L=\")\nL =int(L)\nW =input(\"W=\")\nW =int(W)\narea = W * L\nprint (\"The area is\",area)\nperimeter = (2 * L + 2 * W)\nprint (\"The perimeter is\",perimeter)",
"_____no_output_____"
]
],
[
[
"## Leave any words you like to your teacher\n(make sure this cell is a \"Markdown\" cell (not a \"Code\"), and run this cell after you complete.)\n\n[The \"if\" part I still don't understand]",
"_____no_output_____"
],
[
"## Finally\n1. Save the file and change the name of this file to \"[YourName]\\_assignment_[number]\". \n \n For example, for **Spohie** and lecture **1**, the file name should be \"Sophie_assignment_001\".\n \n\n2. Save the file, and upload it to accordingly directory in the teacher's Google Drive: https://drive.google.com/drive/folders/1DcSzsYS2ZDpzRGi3Tzo3edrj4yvf_U5I?usp=sharing\n\n For students who cannot use Google Drive, email this file to [email protected] with the file name as the email's subject.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
ecd12646645abb0aba701d18e77f2f2d36def314 | 15,483 | ipynb | Jupyter Notebook | Cluster/KMEANS.ipynb | ImYJLiu/BloomCDM | 81a6f547dc2eae593069687d8b6bdd8670433dc6 | [
"MIT"
] | null | null | null | Cluster/KMEANS.ipynb | ImYJLiu/BloomCDM | 81a6f547dc2eae593069687d8b6bdd8670433dc6 | [
"MIT"
] | null | null | null | Cluster/KMEANS.ipynb | ImYJLiu/BloomCDM | 81a6f547dc2eae593069687d8b6bdd8670433dc6 | [
"MIT"
] | null | null | null | 142.045872 | 13,116 | 0.902086 | [
[
[
"from sklearn.manifold import TSNE\nfrom sklearn.datasets import load_iris\nfrom sklearn.manifold import MDS\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\nimport numpy as np",
"_____no_output_____"
],
[
"# 加载数据集\ndef load_data(data_path):\n points = np.loadtxt(data_path)\n return points",
"_____no_output_____"
],
[
"data_PCA = load_data('../know_user_kmeans.txt')\nprint(data_PCA.shape)",
"(112, 4163)\n"
],
[
"y_pred = KMeans(n_clusters=2, random_state=9).fit_predict(data_PCA)\nplt.scatter(data_PCA[:, 0], data_PCA[:, 1], c=y_pred)\nplt.title('Estimated number of clusters: %d' % len(set(y_pred)))\nplt.savefig('img/K-MEANS.svg',dpi=1000) #指定分辨率保存\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
ecd12c2f7be09b7cb2abb38d4a595314d7988bb3 | 1,800 | ipynb | Jupyter Notebook | Determinant_of_Matrix.ipynb | Ranniellsaur/Linear-algebra-58020 | e1b73a953e6b64f1baa8efa89b32c373c6782e03 | [
"Apache-2.0"
] | null | null | null | Determinant_of_Matrix.ipynb | Ranniellsaur/Linear-algebra-58020 | e1b73a953e6b64f1baa8efa89b32c373c6782e03 | [
"Apache-2.0"
] | null | null | null | Determinant_of_Matrix.ipynb | Ranniellsaur/Linear-algebra-58020 | e1b73a953e6b64f1baa8efa89b32c373c6782e03 | [
"Apache-2.0"
] | null | null | null | 26.470588 | 251 | 0.497222 | [
[
[
"<a href=\"https://colab.research.google.com/github/Ranniellsaur/Linear-algebra-58020/blob/main/Determinant_of_Matrix.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"## Determinant of Matrix",
"_____no_output_____"
]
],
[
[
"import numpy as np # import numpy module to use all of its functions/methods\n\nA = np.array([[1,2,-1],[4,6,-2],[-1,3,3]]) # create an 3x3 array\nprint(np.linalg.det(A)) # prints the determinant of the given 3x3 array\nprint(round(np.linalg.det(A))) # prints the round up answer.",
"-13.999999999999996\n-14\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
]
] |
ecd12fa2597ca9a6f343d072c4b0cc64e513eded | 223,456 | ipynb | Jupyter Notebook | Recommendations_with_IBM.ipynb | quandtreas/recommendations_with_ibm | 3f41099576fb4717e58544b72c1a221d75e58ccb | [
"MIT"
] | null | null | null | Recommendations_with_IBM.ipynb | quandtreas/recommendations_with_ibm | 3f41099576fb4717e58544b72c1a221d75e58ccb | [
"MIT"
] | null | null | null | Recommendations_with_IBM.ipynb | quandtreas/recommendations_with_ibm | 3f41099576fb4717e58544b72c1a221d75e58ccb | [
"MIT"
] | null | null | null | 144.538163 | 37,051 | 0.688502 | [
[
[
"# Recommendations with IBM\n\nIn this notebook, you will be putting your recommendation skills to use on real data from the IBM Watson Studio platform. \n\n\nYou may either submit your notebook through the workspace here, or you may work from your local machine and submit through the next page. Either way assure that your code passes the project [RUBRIC](https://review.udacity.com/#!/rubrics/2322/view). **Please save regularly.**\n\nBy following the table of contents, you will build out a number of different methods for making recommendations that can be used for different situations. \n\n\n## Table of Contents\n\nI. [Exploratory Data Analysis](#Exploratory-Data-Analysis)<br>\nII. [Rank Based Recommendations](#Rank)<br>\nIII. [User-User Based Collaborative Filtering](#User-User)<br>\nIV. [Content Based Recommendations (EXTRA - NOT REQUIRED)](#Content-Recs)<br>\nV. [Matrix Factorization](#Matrix-Fact)<br>\nVI. [Extras & Concluding](#conclusions)\n\nAt the end of the notebook, you will find directions for how to submit your work. Let's get started by importing the necessary libraries and reading in the data.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport project_tests as t\nimport pickle\n\n%matplotlib inline\n\ndf = pd.read_csv('data/user-item-interactions.csv')\ndf_content = pd.read_csv('data/articles_community.csv')\ndel df['Unnamed: 0']\ndel df_content['Unnamed: 0']\n\n# Show df to get an idea of the data\ndf.head()",
"_____no_output_____"
],
[
"# Show df_content to get an idea of the data\ndf_content.head()",
"_____no_output_____"
]
],
[
[
"### <a class=\"anchor\" id=\"Exploratory-Data-Analysis\">Part I : Exploratory Data Analysis</a>\n\nUse the dictionary and cells below to provide some insight into the descriptive statistics of the data.\n\n`1.` What is the distribution of how many articles a user interacts with in the dataset? Provide a visual and descriptive statistics to assist with giving a look at the number of times each user interacts with an article. ",
"_____no_output_____"
]
],
[
[
"article_count_per_email_df = df.loc[:, [\"email\", \"article_id\"]].groupby(\"email\").count().sort_values(\"article_id\", ascending=False)\nplt.plot(article_count_per_email_df)\nplt.xlabel(\"users\")\nplt.ylabel(\"# of articles\")\nplt.title(\"# of articles per user\")\nplt.xticks([]);",
"_____no_output_____"
],
[
"# Fill in the median and maximum number of user_article interactios below\n\nmedian_val = article_count_per_email_df.median()[0] # 50% of individuals interact with ____ number of articles or fewer.\nmax_views_by_user = article_count_per_email_df.max()[0] # The maximum number of user-article interactions by any 1 user is ______.",
"_____no_output_____"
]
],
[
[
"`2.` Explore and remove duplicate articles from the **df_content** dataframe. ",
"_____no_output_____"
]
],
[
[
"# Find and explore duplicate articles\ndf_content.loc[df_content.duplicated(subset=\"article_id\", keep=False)]",
"_____no_output_____"
],
[
"# Remove any rows that have the same article_id - only keep the first\ndf_content = df_content.drop_duplicates(subset=\"article_id\", keep=\"first\")",
"_____no_output_____"
]
],
[
[
"`3.` Use the cells below to find:\n\n**a.** The number of unique articles that have an interaction with a user. \n**b.** The number of unique articles in the dataset (whether they have any interactions or not).<br>\n**c.** The number of unique users in the dataset. (excluding null values) <br>\n**d.** The number of user-article interactions in the dataset.",
"_____no_output_____"
]
],
[
[
"unique_articles = df.article_id.drop_duplicates().shape[0] # The number of unique articles that have at least one interaction\ntotal_articles = df_content.article_id.shape[0] # The number of unique articles on the IBM platform\nunique_users = df.email.dropna().drop_duplicates().shape[0] # The number of unique users\nuser_article_interactions = df.shape[0] # The number of user-article interactions",
"_____no_output_____"
]
],
[
[
"`4.` Use the cells below to find the most viewed **article_id**, as well as how often it was viewed. After talking to the company leaders, the `email_mapper` function was deemed a reasonable way to map users to ids. There were a small number of null values, and it was found that all of these null values likely belonged to a single user (which is how they are stored using the function below).",
"_____no_output_____"
]
],
[
[
"views_per_article = df.loc[:, [\"article_id\", \"email\"]].groupby(\"article_id\").count()",
"_____no_output_____"
],
[
"most_viewed_article_id = views_per_article.idxmax()[0].astype(str) # The most viewed article in the dataset as a string with one value following the decimal \nmax_views = views_per_article.max()[0]# The most viewed article in the dataset was viewed how many times?",
"_____no_output_____"
],
[
"## No need to change the code here - this will be helpful for later parts of the notebook\n# Run this cell to map the user email to a user_id column and remove the email column\n\ndef email_mapper():\n coded_dict = dict()\n cter = 1\n email_encoded = []\n \n for val in df['email']:\n if val not in coded_dict:\n coded_dict[val] = cter\n cter+=1\n \n email_encoded.append(coded_dict[val])\n return email_encoded\n\nemail_encoded = email_mapper()\ndel df['email']\ndf['user_id'] = email_encoded\n\n# show header\ndf.head()",
"_____no_output_____"
],
[
"## If you stored all your results in the variable names above, \n## you shouldn't need to change anything in this cell\n\nsol_1_dict = {\n '`50% of individuals have _____ or fewer interactions.`': median_val,\n '`The total number of user-article interactions in the dataset is ______.`': user_article_interactions,\n '`The maximum number of user-article interactions by any 1 user is ______.`': max_views_by_user,\n '`The most viewed article in the dataset was viewed _____ times.`': max_views,\n '`The article_id of the most viewed article is ______.`': most_viewed_article_id,\n '`The number of unique articles that have at least 1 rating ______.`': unique_articles,\n '`The number of unique users in the dataset is ______`': unique_users,\n '`The number of unique articles on the IBM platform`': total_articles\n}\n\n# Test your dictionary against the solution\nt.sol_1_test(sol_1_dict)",
"It looks like you have everything right here! Nice job!\n"
]
],
[
[
"### <a class=\"anchor\" id=\"Rank\">Part II: Rank-Based Recommendations</a>\n\nUnlike in the earlier lessons, we don't actually have ratings for whether a user liked an article or not. We only know that a user has interacted with an article. In these cases, the popularity of an article can really only be based on how often an article was interacted with.\n\n`1.` Fill in the function below to return the **n** top articles ordered with most interactions as the top. Test your function using the tests below.",
"_____no_output_____"
]
],
[
[
"df",
"_____no_output_____"
],
[
"def get_top_articles(n, df=df):\n '''\n INPUT:\n n - (int) the number of top articles to return\n df - (pandas dataframe) df as defined at the top of the notebook \n \n OUTPUT:\n top_articles - (list) A list of the top 'n' article titles \n \n '''\n top_articles = df.groupby(\"title\").count().sort_values(\"user_id\", ascending=False).index.tolist()[:n]\n \n return top_articles # Return the top article titles from df (not df_content)\n\ndef get_top_article_ids(n, df=df):\n '''\n INPUT:\n n - (int) the number of top articles to return\n df - (pandas dataframe) df as defined at the top of the notebook \n \n OUTPUT:\n top_articles - (list) A list of the top 'n' article titles \n \n '''\n top_articles = df.groupby(\"article_id\").count().sort_values(\"user_id\", ascending=False).index.tolist()[:n]\n \n return top_articles # Return the top article ids",
"_____no_output_____"
],
[
"df.groupby(\"article_id\").count().sort_values(\"user_id\", ascending=False)",
"_____no_output_____"
],
[
"print(get_top_articles(10))\nprint(get_top_article_ids(10))",
"['use deep learning for image classification', 'insights from new york car accident reports', 'visualize car data with brunel', 'use xgboost, scikit-learn & ibm watson machine learning apis', 'predicting churn with the spss random tree algorithm', 'healthcare python streaming application demo', 'finding optimal locations of new store using decision optimization', 'apache spark lab, part 1: basic concepts', 'analyze energy consumption in buildings', 'gosales transactions for logistic regression model']\n[1429.0, 1330.0, 1431.0, 1427.0, 1364.0, 1314.0, 1293.0, 1170.0, 1162.0, 1304.0]\n"
],
[
"# Test your function by returning the top 5, 10, and 20 articles\ntop_5 = get_top_articles(5)\ntop_10 = get_top_articles(10)\ntop_20 = get_top_articles(20)\n\n# Test each of your three lists from above\nt.sol_2_test(get_top_articles)",
"Your top_5 looks like the solution list! Nice job.\nYour top_10 looks like the solution list! Nice job.\nYour top_20 looks like the solution list! Nice job.\n"
]
],
[
[
"### <a class=\"anchor\" id=\"User-User\">Part III: User-User Based Collaborative Filtering</a>\n\n\n`1.` Use the function below to reformat the **df** dataframe to be shaped with users as the rows and articles as the columns. \n\n* Each **user** should only appear in each **row** once.\n\n\n* Each **article** should only show up in one **column**. \n\n\n* **If a user has interacted with an article, then place a 1 where the user-row meets for that article-column**. It does not matter how many times a user has interacted with the article, all entries where a user has interacted with an article should be a 1. \n\n\n* **If a user has not interacted with an item, then place a zero where the user-row meets for that article-column**. \n\nUse the tests to make sure the basic structure of your matrix matches what is expected by the solution.",
"_____no_output_____"
]
],
[
[
"# create the user-article matrix with 1's and 0's\n\ndef create_user_item_matrix(df):\n '''\n INPUT:\n df - pandas dataframe with article_id, title, user_id columns\n \n OUTPUT:\n user_item - user item matrix \n \n Description:\n Return a matrix with user ids as rows and article ids on the columns with 1 values where a user interacted with \n an article and a 0 otherwise\n '''\n user_item = pd.get_dummies(df.loc[:, [\"article_id\", \"user_id\"]], columns=[\"article_id\"], prefix=\"\", prefix_sep=\"\").groupby(\"user_id\").max()\n \n return user_item # return the user_item matrix \n\nuser_item = create_user_item_matrix(df)",
"_____no_output_____"
],
[
"## Tests: You should just need to run this cell. Don't change the code.\nassert user_item.shape[0] == 5149, \"Oops! The number of users in the user-article matrix doesn't look right.\"\nassert user_item.shape[1] == 714, \"Oops! The number of articles in the user-article matrix doesn't look right.\"\nassert user_item.sum(axis=1)[1] == 36, \"Oops! The number of articles seen by user 1 doesn't look right.\"\nprint(\"You have passed our quick tests! Please proceed!\")",
"You have passed our quick tests! Please proceed!\n"
]
],
[
[
"`2.` Complete the function below which should take a user_id and provide an ordered list of the most similar users to that user (from most similar to least similar). The returned result should not contain the provided user_id, as we know that each user is similar to him/herself. Because the results for each user here are binary, it (perhaps) makes sense to compute similarity as the dot product of two users. \n\nUse the tests to test your function.",
"_____no_output_____"
]
],
[
[
"def find_similar_users(user_id, user_item=user_item):\n '''\n INPUT:\n user_id - (int) a user_id\n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n OUTPUT:\n similar_users - (list) an ordered list where the closest users (largest dot product users)\n are listed first\n \n Description:\n Computes the similarity of every pair of users based on the dot product\n Returns an ordered\n \n '''\n # compute similarity of each user to the provided user\n similariy = user_item.dot(user_item.loc[user_id])\n\n # sort by similarity\n similariy_sorted = similariy.sort_values(ascending=False)\n\n # create list of just the ids\n most_similar_users = similariy_sorted.index.tolist()\n \n # remove the own user's id\n most_similar_users.remove(user_id)\n \n return most_similar_users # return a list of the users in order from most to least similar\n ",
"_____no_output_____"
],
[
"# Do a spot check of your function\nprint(\"The 10 most similar users to user 1 are: {}\".format(find_similar_users(1)[:10]))\nprint(\"The 5 most similar users to user 3933 are: {}\".format(find_similar_users(3933)[:5]))\nprint(\"The 3 most similar users to user 46 are: {}\".format(find_similar_users(46)[:3]))",
"The 10 most similar users to user 1 are: [3933, 23, 3782, 203, 4459, 131, 3870, 46, 4201, 5041]\nThe 5 most similar users to user 3933 are: [1, 23, 3782, 4459, 203]\nThe 3 most similar users to user 46 are: [4201, 23, 3782]\n"
]
],
[
[
"`3.` Now that you have a function that provides the most similar users to each user, you will want to use these users to find articles you can recommend. Complete the functions below to return the articles you would recommend to each user. ",
"_____no_output_____"
]
],
[
[
"def get_article_names(article_ids, df=df):\n '''\n INPUT:\n article_ids - (list) a list of article ids\n df - (pandas dataframe) df as defined at the top of the notebook\n \n OUTPUT:\n article_names - (list) a list of article names associated with the list of article ids \n (this is identified by the title column)\n '''\n # Your code here\n article_names = df.loc[df.article_id.isin(article_ids), \"title\"].drop_duplicates().tolist()\n \n return article_names # Return the article names associated with list of article ids\n\n\ndef get_user_articles(user_id, user_item=user_item):\n '''\n INPUT:\n user_id - (int) a user id\n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n OUTPUT:\n article_ids - (list) a list of the article ids seen by the user\n article_names - (list) a list of article names associated with the list of article ids \n (this is identified by the doc_full_name column in df_content)\n \n Description:\n Provides a list of the article_ids and article titles that have been seen by a user\n '''\n article_ids = user_item.loc[user_id, user_item.loc[user_id] > 0].index.tolist()\n article_names = get_article_names(article_ids)\n # df_content.loc[df_content.article_id.isin(article_ids, \"doc_full_name\"].tolist()\n \n return article_ids, article_names # return the ids and names\n\n\ndef user_user_recs(user_id, m=10):\n '''\n INPUT:\n user_id - (int) a user id\n m - (int) the number of recommendations you want for the user\n \n OUTPUT:\n recs - (list) a list of recommendations for the user\n \n Description:\n Loops through the users based on closeness to the input user_id\n For each user - finds articles the user hasn't seen before and provides them as recs\n Does this until m recommendations are found\n \n Notes:\n Users who are the same closeness are chosen arbitrarily as the 'next' user\n \n For the user where the number of recommended articles starts below m \n and ends exceeding m, the last items are chosen arbitrarily\n \n '''\n similar_users = find_similar_users(user_id)\n seen_articles = get_user_articles(user_id)\n recs= []\n \n for similar_user in similar_users:\n similar_user_articles, _ = get_user_articles(similar_user)\n \n for similar_user_article in similar_user_articles:\n if similar_user_article not in seen_articles:\n recs.append(similar_user_article)\n if len(recs) == m:\n return recs\n \n return recs",
"_____no_output_____"
],
[
"# Check Results\nget_article_names(user_user_recs(1, 10)) # Return 10 recommendations for user 1",
"_____no_output_____"
],
[
"# Test your functions here - No need to change this code - just run this cell\nassert set(get_article_names(['1024.0', '1176.0', '1305.0', '1314.0', '1422.0', '1427.0'])) == set(['using deep learning to reconstruct high-resolution audio', 'build a python app on the streaming analytics service', 'gosales transactions for naive bayes model', 'healthcare python streaming application demo', 'use r dataframes & ibm watson natural language understanding', 'use xgboost, scikit-learn & ibm watson machine learning apis']), \"Oops! Your the get_article_names function doesn't work quite how we expect.\"\nassert set(get_article_names(['1320.0', '232.0', '844.0'])) == set(['housing (2015): united states demographic measures','self-service data preparation with ibm data refinery','use the cloudant-spark connector in python notebook']), \"Oops! Your the get_article_names function doesn't work quite how we expect.\"\nassert set(get_user_articles(20)[0]) == set(['1320.0', '232.0', '844.0'])\nassert set(get_user_articles(20)[1]) == set(['housing (2015): united states demographic measures', 'self-service data preparation with ibm data refinery','use the cloudant-spark connector in python notebook'])\nassert set(get_user_articles(2)[0]) == set(['1024.0', '1176.0', '1305.0', '1314.0', '1422.0', '1427.0'])\nassert set(get_user_articles(2)[1]) == set(['using deep learning to reconstruct high-resolution audio', 'build a python app on the streaming analytics service', 'gosales transactions for naive bayes model', 'healthcare python streaming application demo', 'use r dataframes & ibm watson natural language understanding', 'use xgboost, scikit-learn & ibm watson machine learning apis'])\nprint(\"If this is all you see, you passed all of our tests! Nice job!\")",
"If this is all you see, you passed all of our tests! Nice job!\n"
]
],
[
[
"`4.` Now we are going to improve the consistency of the **user_user_recs** function from above. \n\n* Instead of arbitrarily choosing when we obtain users who are all the same closeness to a given user - choose the users that have the most total article interactions before choosing those with fewer article interactions.\n\n\n* Instead of arbitrarily choosing articles from the user where the number of recommended articles starts below m and ends exceeding m, choose articles with the articles with the most total interactions before choosing those with fewer total interactions. This ranking should be what would be obtained from the **top_articles** function you wrote earlier.",
"_____no_output_____"
]
],
[
[
"def get_top_sorted_users(user_id, df=df, user_item=user_item):\n '''\n INPUT:\n user_id - (int)\n df - (pandas dataframe) df as defined at the top of the notebook \n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n \n OUTPUT:\n neighbors_df - (pandas dataframe) a dataframe with:\n neighbor_id - is a neighbor user_id\n similarity - measure of the similarity of each user to the provided user_id\n num_interactions - the number of articles viewed by the user - if a u\n \n Other Details - sort the neighbors_df by the similarity and then by number of interactions where \n highest of each is higher in the dataframe\n \n '''\n\n num_interactions = df.groupby(\"user_id\").article_id.count().rename(\"num_interactions\").drop(user_id)\n\n similariy = user_item.dot(user_item.loc[user_id]).rename(\"similarity\").drop(user_id)\n\n # sort by similarity\n\n neighbors_df = (pd.concat([similariy, num_interactions], axis=1).reset_index()\n .rename(columns={\"user_id\":\"neighbor_id\"})\n .sort_values([\"similarity\", \"num_interactions\"], ascending=False))\n \n return neighbors_df # Return the dataframe specified in the doc_string\n\n\ndef user_user_recs_part2(user_id, m=10):\n '''\n INPUT:\n user_id - (int) a user id\n m - (int) the number of recommendations you want for the user\n \n OUTPUT:\n recs - (list) a list of recommendations for the user by article id\n rec_names - (list) a list of recommendations for the user by article title\n \n Description:\n Loops through the users based on closeness to the input user_id\n For each user - finds articles the user hasn't seen before and provides them as recs\n Does this until m recommendations are found\n \n Notes:\n * Choose the users that have the most total article interactions \n before choosing those with fewer article interactions.\n\n * Choose articles with the articles with the most total interactions \n before choosing those with fewer total interactions. \n \n '''\n similar_users_sorted = get_top_sorted_users(user_id).neighbor_id.tolist()\n seen_articles = get_user_articles(user_id)\n\n recs= []\n \n for similar_user in similar_users_sorted:\n similar_user_articles, _ = get_user_articles(similar_user)\n \n for similar_user_article in similar_user_articles:\n if similar_user_article not in seen_articles:\n recs.append(similar_user_article)\n if len(recs) == m:\n return recs, get_article_names(recs)\n \n return recs, get_article_names(recs)\n",
"_____no_output_____"
],
[
"# Quick spot check - don't change this code - just use it to test your functions\nrec_ids, rec_names = user_user_recs_part2(20, 10)\nprint(\"The top 10 recommendations for user 20 are the following article ids:\")\nprint(rec_ids)\nprint()\nprint(\"The top 10 recommendations for user 20 are the following article names:\")\nprint(rec_names)",
"The top 10 recommendations for user 20 are the following article ids:\n['12.0', '109.0', '125.0', '142.0', '164.0', '205.0', '232.0', '302.0', '336.0', '362.0']\n\nThe top 10 recommendations for user 20 are the following article names:\n['timeseries data analysis of iot events by using jupyter notebook', 'dsx: hybrid mode', 'accelerate your workflow with dsx', 'learn tensorflow and deep learning together and now!', \"a beginner's guide to variational methods\", 'tensorflow quick tips', 'challenges in deep learning', 'neural networks for beginners: popular types and applications', 'self-service data preparation with ibm data refinery', 'statistics for hackers']\n"
]
],
[
[
"`5.` Use your functions from above to correctly fill in the solutions to the dictionary below. Then test your dictionary against the solution. Provide the code you need to answer each following the comments below.",
"_____no_output_____"
]
],
[
[
"### Tests with a dictionary of results\n\nuser1_most_sim = find_similar_users(1)[0] # Find the user that is most similar to user 1 \nuser131_10th_sim = find_similar_users(131)[10 - 1] # Find the 10th most similar user to user 131",
"_____no_output_____"
],
[
"## Dictionary Test Here\nsol_5_dict = {\n 'The user that is most similar to user 1.': user1_most_sim, \n 'The user that is the 10th most similar to user 131': user131_10th_sim,\n}\n\nt.sol_5_test(sol_5_dict)",
"This all looks good! Nice job!\n"
]
],
[
[
"`6.` If we were given a new user, which of the above functions would you be able to use to make recommendations? Explain. Can you think of a better way we might make recommendations? Use the cell below to explain a better method for new users.",
"_____no_output_____"
],
[
"Since a new user won't have interactions with any article, she won't appear in `df` and therefore none of the functions besides `get_top_article_ids()`, which suggests the articles witht the most interactions, would work.\n\nA better method to make recommendations for a new user would be to consider features of the new user which they might have provided at sign up to find their similarity to existing users and then suggest articles they have interacted with. Another approach would be to make knowledge based recommendations by giving a new user the option to filter articles based on attributes such as 'date published', 'topic', 'author', 'number of interactions', etc.\n",
"_____no_output_____"
],
[
"`7.` Using your existing functions, provide the top 10 recommended articles you would provide for the a new user below. You can test your function against our thoughts to make sure we are all on the same page with how we might make a recommendation.",
"_____no_output_____"
]
],
[
[
"new_user = '0.0'\n\n# What would your recommendations be for this new user '0.0'? As a new user, they have no observed articles.\n# Provide a list of the top 10 article ids you would give to \nnew_user_recs = [str(article_id) for article_id in get_top_article_ids(10)]\n\n",
"_____no_output_____"
],
[
"assert set(new_user_recs) == set(['1314.0','1429.0','1293.0','1427.0','1162.0','1364.0','1304.0','1170.0','1431.0','1330.0']), \"Oops! It makes sense that in this case we would want to recommend the most popular articles, because we don't know anything about these users.\"\n\nprint(\"That's right! Nice job!\")",
"That's right! Nice job!\n"
]
],
[
[
"### <a class=\"anchor\" id=\"Content-Recs\">Part IV: Content Based Recommendations (EXTRA - NOT REQUIRED)</a>\n\nAnother method we might use to make recommendations is to perform a ranking of the highest ranked articles associated with some term. You might consider content to be the **doc_body**, **doc_description**, or **doc_full_name**. There isn't one way to create a content based recommendation, especially considering that each of these columns hold content related information. \n\n`1.` Use the function body below to create a content based recommender. Since there isn't one right answer for this recommendation tactic, no test functions are provided. Feel free to change the function inputs if you decide you want to try a method that requires more input values. The input values are currently set with one idea in mind that you may use to make content based recommendations. One additional idea is that you might want to choose the most popular recommendations that meet your 'content criteria', but again, there is a lot of flexibility in how you might make these recommendations.\n\n### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills.",
"_____no_output_____"
]
],
[
[
"def make_content_recs():\n '''\n INPUT:\n \n OUTPUT:\n \n '''",
"_____no_output_____"
]
],
[
[
"`2.` Now that you have put together your content-based recommendation system, use the cell below to write a summary explaining how your content based recommender works. Do you see any possible improvements that could be made to your function? Is there anything novel about your content based recommender?\n\n### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills.",
"_____no_output_____"
],
[
"**Write an explanation of your content based recommendation system here.**",
"_____no_output_____"
],
[
"`3.` Use your content-recommendation system to make recommendations for the below scenarios based on the comments. Again no tests are provided here, because there isn't one right answer that could be used to find these content based recommendations.\n\n### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills.",
"_____no_output_____"
]
],
[
[
"# make recommendations for a brand new user\n\n\n# make a recommendations for a user who only has interacted with article id '1427.0'\n\n",
"_____no_output_____"
]
],
[
[
"### <a class=\"anchor\" id=\"Matrix-Fact\">Part V: Matrix Factorization</a>\n\nIn this part of the notebook, you will build use matrix factorization to make article recommendations to the users on the IBM Watson Studio platform.\n\n`1.` You should have already created a **user_item** matrix above in **question 1** of **Part III** above. This first question here will just require that you run the cells to get things set up for the rest of **Part V** of the notebook. ",
"_____no_output_____"
]
],
[
[
"# Load the matrix here\nuser_item_matrix = pd.read_pickle('user_item_matrix.p')",
"_____no_output_____"
],
[
"# quick look at the matrix\nuser_item_matrix.head()",
"_____no_output_____"
]
],
[
[
"`2.` In this situation, you can use Singular Value Decomposition from [numpy](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.svd.html) on the user-item matrix. Use the cell to perform SVD, and explain why this is different than in the lesson.",
"_____no_output_____"
]
],
[
[
"# Perform SVD on the User-Item Matrix Here\nu, s, vt = np.linalg.svd(user_item_matrix) # use the built in to get the three matrices",
"_____no_output_____"
],
[
"u.shape, s.shape, vt.shape",
"_____no_output_____"
]
],
[
[
"\nIn the lessons FunkSVD was used because numpy's svd function does not support matrices with missing values. Here, this function can be used since there are no missing values in the dataframe. \n",
"_____no_output_____"
],
[
"`3.` Now for the tricky part, how do we choose the number of latent features to use? Running the below cell, you can see that as the number of latent features increases, we obtain a lower error rate on making predictions for the 1 and 0 values in the user-item matrix. Run the cell below to get an idea of how the accuracy improves as we increase the number of latent features.",
"_____no_output_____"
]
],
[
[
"num_latent_feats = np.arange(10,700+10,20)\nsum_errs = []\n\nfor k in num_latent_feats:\n # restructure with k latent features\n s_new, u_new, vt_new = np.diag(s[:k]), u[:, :k], vt[:k, :]\n \n # take dot product\n user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new))\n \n # compute error for each prediction to actual value\n diffs = np.subtract(user_item_matrix, user_item_est)\n \n # total errors and keep track of them\n err = np.sum(np.sum(np.abs(diffs)))\n sum_errs.append(err)\n \n \nplt.plot(num_latent_feats, 1 - np.array(sum_errs)/df.shape[0]);\nplt.xlabel('Number of Latent Features');\nplt.ylabel('Accuracy');\nplt.title('Accuracy vs. Number of Latent Features');",
"_____no_output_____"
]
],
[
[
"`4.` From the above, we can't really be sure how many features to use, because simply having a better way to predict the 1's and 0's of the matrix doesn't exactly give us an indication of if we are able to make good recommendations. Instead, we might split our dataset into a training and test set of data, as shown in the cell below. \n\nUse the code from question 3 to understand the impact on accuracy of the training and test sets of data with different numbers of latent features. Using the split below: \n\n* How many users can we make predictions for in the test set? \n* How many users are we not able to make predictions for because of the cold start problem?\n* How many articles can we make predictions for in the test set? \n* How many articles are we not able to make predictions for because of the cold start problem?",
"_____no_output_____"
]
],
[
[
"df_train = df.head(40000)\ndf_test = df.tail(5993)\n\ndef create_test_and_train_user_item(df_train, df_test):\n '''\n INPUT:\n df_train - training dataframe\n df_test - test dataframe\n \n OUTPUT:\n user_item_train - a user-item matrix of the training dataframe \n (unique users for each row and unique articles for each column)\n user_item_test - a user-item matrix of the testing dataframe \n (unique users for each row and unique articles for each column)\n test_idx - all of the test user ids\n test_arts - all of the test article ids\n \n '''\n user_item_train = create_user_item_matrix(df_train)\n user_item_test = create_user_item_matrix(df_test)\n\n test_idx = user_item_test.index.tolist()\n test_arts = user_item_test.columns.tolist()\n \n return user_item_train, user_item_test, test_idx, test_arts\n\nuser_item_train, user_item_test, test_idx, test_arts = create_test_and_train_user_item(df_train, df_test)",
"_____no_output_____"
],
[
"user_item_train.shape",
"_____no_output_____"
],
[
"len([user_id for user_id in test_idx if user_id in user_item_train.index.tolist()])",
"_____no_output_____"
],
[
"len([user_id for user_id in test_idx if user_id not in user_item_train.index.tolist()])",
"_____no_output_____"
],
[
"len([article_id for article_id in test_arts if article_id in user_item_train.columns.tolist()])",
"_____no_output_____"
],
[
"len([article_id for article_id in test_arts if article_id not in user_item_train.columns.tolist()])",
"_____no_output_____"
],
[
"# Replace the values in the dictionary below\na = 662 \nb = 574 \nc = 20 \nd = 0 \n\n\nsol_4_dict = {\n 'How many users can we make predictions for in the test set?': c, \n 'How many users in the test set are we not able to make predictions for because of the cold start problem?': a, \n 'How many movies can we make predictions for in the test set?': b,\n 'How many movies in the test set are we not able to make predictions for because of the cold start problem?': d\n}\n\nt.sol_4_test(sol_4_dict)",
"Awesome job! That's right! All of the test movies are in the training data, but there are only 20 test users that were also in the training set. All of the other users that are in the test set we have no data on. Therefore, we cannot make predictions for these users using SVD.\n"
]
],
[
[
"`5.` Now use the **user_item_train** dataset from above to find U, S, and V transpose using SVD. Then find the subset of rows in the **user_item_test** dataset that you can predict using this matrix decomposition with different numbers of latent features to see how many features makes sense to keep based on the accuracy on the test data. This will require combining what was done in questions `2` - `4`.\n\nUse the cells below to explore how well SVD works towards making predictions for recommendations on the test data. ",
"_____no_output_____"
]
],
[
[
"# fit SVD on the user_item_train matrix\nu_train, s_train, vt_train = np.linalg.svd(user_item_train) # fit svd similar to above then use the cells below",
"_____no_output_____"
],
[
"# Use these cells to see how well you can use the training \n# decomposition to predict on test data",
"_____no_output_____"
],
[
"u_train.shape, s_train.shape, vt_train.shape",
"_____no_output_____"
],
[
"user_id_subset = [user_id in test_idx for user_id in user_item_train.index.tolist()]\nprint(len(user_id_subset))",
"4487\n"
],
[
"article_id_subset = [article_id in test_arts for article_id in user_item_train.columns.tolist()]\nprint(len(article_id_subset))",
"714\n"
],
[
"user_item_test_subset = user_item_test.loc[[user_id for user_id in user_item_train.index.tolist() if user_id in test_idx]]",
"_____no_output_____"
],
[
"num_latent_feats = np.arange(1,700+10,10)\nsum_errs = []\n\nfor k in num_latent_feats:\n # restructure with k latent features\n s_new, u_new, vt_new = np.diag(s_train[:k]), u_train[:, :k], vt_train[:k, :]\n \n # take dot product\n user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new))[user_id_subset,:][:, article_id_subset]\n \n # compute error for each prediction to actual value\n diffs = np.subtract(user_item_test_subset, user_item_est)\n \n # total errors and keep track of them\n err = np.sum(np.sum(np.abs(diffs)))\n sum_errs.append(err)\n \n \nplt.plot(num_latent_feats, 1 - np.array(sum_errs)/df.shape[0]);\nplt.xlabel('Number of Latent Features');\nplt.ylabel('Accuracy');\nplt.title('Accuracy vs. Number of Latent Features');",
"_____no_output_____"
]
],
[
[
"`6.` Use the cell below to comment on the results you found in the previous question. Given the circumstances of your results, discuss what you might do to determine if the recommendations you make with any of the above recommendation systems are an improvement to how users currently find articles? ",
"_____no_output_____"
],
[
"The plot shows that the prediction is best the fewer latent features are used. The reason for this is that with an increasing number of latent features, the model overfits to the training data for which the SVD was performed. For a more meaningful evaluation, a larger test data subset would be preferable since here the test data subset only contains 20 user ids that are also present in the training data set.",
"_____no_output_____"
],
[
"<a id='conclusions'></a>\n### Extras\nUsing your workbook, you could now save your recommendations for each user, develop a class to make new predictions and update your results, and make a flask app to deploy your results. These tasks are beyond what is required for this project. However, from what you learned in the lessons, you certainly capable of taking these tasks on to improve upon your work here!\n\n\n## Conclusion\n\n> Congratulations! You have reached the end of the Recommendations with IBM project! \n\n> **Tip**: Once you are satisfied with your work here, check over your report to make sure that it is satisfies all the areas of the [rubric](https://review.udacity.com/#!/rubrics/2322/view). You should also probably remove all of the \"Tips\" like this one so that the presentation is as polished as possible.\n\n\n## Directions to Submit\n\n> Before you submit your project, you need to create a .html or .pdf version of this notebook in the workspace here. To do that, run the code cell below. If it worked correctly, you should get a return code of 0, and you should see the generated .html file in the workspace directory (click on the orange Jupyter icon in the upper left).\n\n> Alternatively, you can download this report as .html via the **File** > **Download as** submenu, and then manually upload it into the workspace directory by clicking on the orange Jupyter icon in the upper left, then using the Upload button.\n\n> Once you've done this, you can submit your project by clicking on the \"Submit Project\" button in the lower right here. This will create and submit a zip file with this .ipynb doc and the .html or .pdf version you created. Congratulations! ",
"_____no_output_____"
]
],
[
[
"from subprocess import call\ncall(['python', '-m', 'nbconvert', 'Recommendations_with_IBM.ipynb'])",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
ecd131bf77a5ab5097eaa58c4d6186ec6839f567 | 48,495 | ipynb | Jupyter Notebook | labs/lab4/lab4.ipynb | MITLLRacecar/racecar-mehul-rao | 15e58d160f7edd35f34bb78e07ff66a5d4e33e3f | [
"MIT"
] | null | null | null | labs/lab4/lab4.ipynb | MITLLRacecar/racecar-mehul-rao | 15e58d160f7edd35f34bb78e07ff66a5d4e33e3f | [
"MIT"
] | null | null | null | labs/lab4/lab4.ipynb | MITLLRacecar/racecar-mehul-rao | 15e58d160f7edd35f34bb78e07ff66a5d4e33e3f | [
"MIT"
] | null | null | null | 73.925305 | 6,805 | 0.795443 | [
[
[
"# Lab 4 Exploration: LIDAR\n\nIn this notebook, we will learn how to use the racecar's LIDAR to measure distance and find closest points.\n\nThroughout this notebook, **<font style=\"color:red\">text in bold red</font>** indicates a change you must make to the following code block before running it.\n\n\n## Table of Contents\n1. [Getting Started](#GettingStarted)\n1. [Gathering LIDAR Data](#GatheringLidarData)\n1. [Visualizing LIDAR Data](#VisualizingLidarData)\n1. [Handling Noise](#HandlingNoise)\n1. [Closest Point](#ClosestPoint)",
"_____no_output_____"
],
[
"<a id=\"GettingStarted\"></a>\n## 1. Getting Started\n\n**<font style=\"color:red\">If you are running the car in RacecarSim, set `isSimulation` to `True`</font>**. Leave `isSimulation` `False` if you are using a physical car.",
"_____no_output_____"
]
],
[
[
"# TODO: Update isSimulation if necessary\nisSimulation = True",
"_____no_output_____"
]
],
[
[
"Next, we will import the necessary libraries for this notebook, including Python libraries (`cv`, `numpy`, etc.) and the Racecar library (`racecar_core`).",
"_____no_output_____"
]
],
[
[
"# Import Python libraries\nimport math\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\nimport statistics\nfrom nptyping import NDArray\nfrom typing import Any, Tuple, List, Optional\n\n# Import Racecar library\nimport sys\nsys.path.append(\"../../library\")\nimport racecar_core\nimport racecar_utils as rc_utils",
"_____no_output_____"
]
],
[
[
"Finally, we will create a racecar object. If this step fails, make sure that `isSimulation` has the correct value.",
"_____no_output_____"
]
],
[
[
"# Create Racecar\nrc = racecar_core.create_racecar(isSimulation)",
"\u001b[95m>> Racecar created with the following options:\n Simulation (-s): [True]\n Headless (-h): [False]\n Initialize with display (-d): [False]\u001b[00m\n"
]
],
[
[
"<a id=\"GatheringLidarData\"></a>\n## 2. Gathering LIDAR Data\nThe racecar's LIDAR data is stored as a one-dimensional numpy array of 720 distance measurements. Each measurement is 1/2 of a degree apart, ordered clockwise, with the 0th entry directly in front of the car.\n\nIn Jupyter Notebook, we can access the car's LIDAR data using `rc.lidar.get_samples_async()`. Outside of Jupyter Notebook, we must use `rc.lidar.get_samples()` instead.",
"_____no_output_____"
]
],
[
[
"# Access the current LIDAR scan\nscan = rc.lidar.get_samples_async()",
"_____no_output_____"
]
],
[
[
"Let's access the measurements directly in front of and behind the car.",
"_____no_output_____"
]
],
[
[
"# Calculate and show the forward and rear distances\nforward_distance = scan[0]\nprint(f\"Forward distance: {forward_distance:.2f} cm\")\n\nrear_distance = scan[360]\nprint(f\"Rear distance: {rear_distance:.2f} cm\")",
"Forward distance: 63.35 cm\nRear distance: 76.65 cm\n"
]
],
[
[
"**<span style=\"color:red\">Set `left_distance` and `right_distance` in the following code block to the LIDAR measurements directly to the left and directly to the right of the car.</span>**",
"_____no_output_____"
]
],
[
[
"# TODO: Calculate and show the left and right distances\nleft_distance = scan[540]\nprint(f\"Left distance: {left_distance:.2f} cm\")\n\nright_distance = scan[180]\nprint(f\"Right distance: {right_distance:.2f} cm\")",
"Left distance: 97.78 cm\nRight distance: 85.92 cm\n"
]
],
[
[
"<a id=\"VisualizingLidarData\"></a>\n## 3. Visualizing LIDAR data\n\nIn this section, we will write a function to convert LIDAR data into a color image providing a top-down view of the data. We will use the following approach:\n\n1. Create an all-black BGR image (a 3D numpy array ordered rows, columns, color channels) of the specified radius.\n1. Denote the car by drawing a green dot at the center of the image with [`rc_utils.draw_circle`](https://mitll-racecar.readthedocs.io/en/latest/racecar_utils.html#racecar_utils.draw_circle).\n1. For each LIDAR sample, set the corresponding pixel to red. We can calculate the angle of each sample based on its index in the scan. By scaling the distance such that `max_range` is the edge of the image, we can convert this angle and distance into a row and column in the image.\n1. `highlighted_samples` contains a list of `(angle, distance)` measurements that we wish to highlight with light blue dots. These can be plotted similarly to the samples in the previous step and drawn with `rc_utils.draw_circle`.\n1. Display the color image in the Jupyter Notebook with Matplotlib.\n\nThe result should look similar to the LIDAR visualization shown in the left sidebar of RacecarSim.\n\n**<span style=\"color:red\">Finish implementing this approach in the `show_lidar` function below.</span>**",
"_____no_output_____"
]
],
[
[
"def show_lidar(\n scan: NDArray[Any, np.float32],\n radius: int = 128,\n max_range: int = 400,\n highlighted_samples: List[Tuple[int, int]] = []\n) -> None:\n \"\"\"\n Displays a visual representation of a LIDAR scan in Jupyter Notebook.\n\n Args:\n scan: The LIDAR scan to show.\n radius: Half of the width and height (in pixels) of the generated image.\n max_range: The farthest distance to show in the image in cm. Any sample past this range is not shown.\n highlighted_samples: A list of samples in (angle, distance) format to show as a blue dot.\n \"\"\"\n # Create a square black image with the requested radius\n image = np.zeros((2 * radius, 2 * radius, 3), np.uint8, \"C\")\n num_samples: int = len(scan)\n\n # TODO: Draw a green dot at the center of the image to denote the car\n # Hint: Use rc_utils.draw_circle\n CAR_DOT_RADIUS = 2\n rc_utils.draw_circle(image, (0, 0), (0, 255, 0), CAR_DOT_RADIUS)\n\n\n # TODO: Draw a red pixel for each non-zero sample less than max_range\n angle = 0\n for i in scan:\n if i < max_range:\n length = (radius * i) / max_range\n x = int(radius - round(length * np.cos(np.deg2rad(angle)), None))\n y = int(radius + round(length * np.sin(np.deg2rad(angle)), None))\n image[x][y] = (0, 0, 255)\n angle += 0.5\n # TODO: Draw a light blue dot for each point in highlighted_samples\n # Hint: Use rc_utils.draw_circle\n HIGHLIGHT_DOT_RADIUS = 2\n for i in highlighted_samples:\n length = (radius * i[1]) / max_range\n x = int(radius - round(length * np.cos(np.deg2rad(i[0])), None))\n y = int(radius + round(length * np.sin(np.deg2rad(i[0])), None))\n rc_utils.draw_circle(image, (x, y), (255, 0, 0), HIGHLIGHT_DOT_RADIUS)\n\n # Show the image with Matplotlib\n plt.imshow(cv.cvtColor(image, cv.COLOR_BGR2RGB))\n plt.show()",
"_____no_output_____"
]
],
[
[
"Let's use this function to visualize our LIDAR scan.",
"_____no_output_____"
]
],
[
[
"show_lidar(scan)",
"_____no_output_____"
]
],
[
[
"For now, we will test out the `highlighted_samples` feature by highlighting points 100 cm in each cardinal direction.",
"_____no_output_____"
]
],
[
[
"show_lidar(scan, highlighted_samples=[(0, 100), (90, 100), (180, 100), (270, 100)])",
"_____no_output_____"
]
],
[
[
"<a id=\"HandlingNoise\"></a>\n## 4. Handling Noise\n\nJust like depth images, LIDAR data is also subject to noise and null values. To help combat this, we will once again average several neighboring samples across an *angle window* instead of relying on a single measurement. For example, if we want to measure the distance at 60 degrees with a 4 degree window angle, we would average all of the samples from 58 to 62 degrees. To reduce the impact of null values, we should not consider any 0.0 measurement in our average.\n\n**<span style=\"color:red\">Implement this approach in `get_lidar_average_distance`</span>**. You may wish to use a Python [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions).",
"_____no_output_____"
]
],
[
[
"def get_lidar_average_distance(\n scan: NDArray[Any, np.float32], angle: float, window_angle: float = 4\n) -> float:\n \"\"\"\n Finds the average distance of the object at a particular angle relative to the car.\n\n Args:\n scan: The samples from a LIDAR scan\n angle: The angle (in degrees) at which to measure distance, starting at 0\n directly in front of the car and increasing clockwise.\n window_angle: The number of degrees to consider around angle.\n\n Returns:\n The average distance of the points at angle in cm.\n\n Note:\n Ignores any samples with a value of 0.0 (no data).\n Increasing window_angle reduces noise at the cost of reduced accuracy.\n \"\"\"\n # TODO: average the samples in the specified window\n sum = 0\n num_samples = 0\n start_range = (angle * 2) - window_angle\n end_range = (angle * 2) + window_angle\n if start_range < 0:\n start_range = 720 - abs(start_range)\n if start_range > 720:\n start_range = start_range - 720\n if end_range < 0:\n end_range = 720 - abs(end_range)\n if end_range > 720:\n end_range = end_range - 720\n if start_range > end_range:\n samples = scan[start_range:].tolist() + scan[0 : end_range + 1].tolist()\n else:\n samples = scan[start_range : end_range + 1].tolist()\n for i in samples:\n if i > 0:\n sum += i\n num_samples += 1\n if num_samples == 0:\n return 0\n return sum / num_samples\n",
"_____no_output_____"
]
],
[
[
"Let's try it out. Increasing the window angle will decrease noise by including more samples, but will also decrease accuracy by including less relevant samples.",
"_____no_output_____"
]
],
[
[
"WINDOW_ANGLE = 6\nrear_distance = get_lidar_average_distance(scan, 180, WINDOW_ANGLE)\nprint(f\"Rear distance ({WINDOW_ANGLE} degree window): {rear_distance:.2f} cm\")",
"Rear distance (6 degree window): 78.23 cm\n"
]
],
[
[
"`get_lidar_average_distance` must handle when the angle window passes over the edge of the array. For example, with an angle of 0 and a window angle of 6, we must consider all samples in the range 357 to 3 degrees.\n\n**<span style=\"color:red\">If you have not done so already, update `get_lidar_average_distance` to support angle windows that cross the edge of the array.</span>**.",
"_____no_output_____"
]
],
[
[
"forward_distance = get_lidar_average_distance(scan, 0, WINDOW_ANGLE)\nprint(f\"Forward distance ({WINDOW_ANGLE} degree window): {forward_distance:.2f} cm\")",
"Forward distance (6 degree window): 60.92 cm\n"
]
],
[
[
"Finally, we must handle when there is no data in the specified angle window. In this case, we should return `0.0`.\n\n**<span style=\"color:red\">If you have not done so already, update `get_lidar_average_distance` to return `0.0` when the specified range does not contain any data.</span>**.",
"_____no_output_____"
]
],
[
[
"null_scan = np.zeros(rc.lidar.get_num_samples(), np.float32)\nforward_distance = get_lidar_average_distance(null_scan, 0, WINDOW_ANGLE)\nprint(f\"Forward distance ({WINDOW_ANGLE} degree window) in null scan: {forward_distance:.2f} cm\")",
"Forward distance (6 degree window) in null scan: 0.00 cm\n"
]
],
[
[
"<a id=\"ClosestPoint\"></a>\n## 5. Closest Point\n\nWe can use the LIDAR to find the angle of the closest object in 360 degrees around the car. Just like with the depth image, we should convert null values to a large number so they are not considered for the minimum. An efficient way to do this is to shift down each value by a small amount (such as 0.01 cm) and then mod by a large number (such as 10,000 cm). This way, 0.0 becomes -0.01, which after modding becomes 9,999.99 cm, a very large distance that will not interfere with the true minimum.\n\n```\nscan = (scan - 0.01) % 10000\n```\n\nIn lecture, we saw an example of how to find the angle of the closest point using the Numpy [argmin](https://numpy.org/doc/1.19/reference/generated/numpy.argmin.html) function.\n\n```\nscan = (scan - 0.01) % 10000\nangle = np.argmin(scan) * 360 / rc.lidar.get_num_samples()\n```\n\nHowever, we may only wish to consider samples within a particular range, such as samples ranging from 30 to 150 degrees. **<span style=\"color:red\">Implement `get_closest_pixel` to find the angle and distance of the closest point within a specified window in a LIDAR scan</span>**.",
"_____no_output_____"
]
],
[
[
"def get_lidar_closest_point(\n scan: NDArray[Any, np.float32], window: Tuple[float, float] = (0, 360)\n) -> Tuple[float, float]:\n \"\"\"\n Finds the closest point from a LIDAR scan.\n\n Args:\n scan: The samples from a LIDAR scan.\n window: The degree range to consider, expressed as (min_degree, max_degree)\n\n Returns:\n The (angle, distance) of the point closest to the car within the specified\n degree window. All angles are in degrees, starting at 0 directly in front of the\n car and increasing clockwise. Distance is in cm.\n\n Note:\n Ignores any samples with a value of 0.0 (no data).\n\n In order to define a window which passes through the 360-0 degree boundary, it\n is acceptable for window min_degree to be larger than window max_degree. For\n example, (350, 10) is a 20 degree window in front of the car.\n \"\"\"\n # TODO: Return the (angle, distance) of the closest point within the specified window\n num_samples = rc.lidar.get_num_samples()\n\n scan = (scan - 0.01) % 10000\n min_degree, max_degree = window\n min_degree *= 2\n max_degree *= 2\n\n if min_degree < 0:\n min_degree = num_samples - abs(min_degree)\n if min_degree > num_samples:\n min_degree = min_degree - num_samples\n if max_degree < 0:\n max_degree = num_samples - abs(max_degree)\n if max_degree > num_samples:\n max_degree = max_degree - num_samples\n\n if min_degree > max_degree:\n samples = scan[min_degree:].tolist() + scan[0 : max_degree + 1].tolist()\n else:\n samples = scan[min_degree : max_degree + 1].tolist()\n\n min_point = np.argmin(samples)\n angle = min_degree + min_point\n if angle > num_samples:\n angle -= num_samples\n return ((angle * 360) / num_samples, samples[min_point])",
"_____no_output_____"
]
],
[
[
"Let's use `get_lidar_closest_point` to find the closest point to the right of the car.",
"_____no_output_____"
]
],
[
[
"angle, distance = get_lidar_closest_point(scan, (30, 150))\nprint(f\"Angle: {angle:.1f} degrees\")\nprint(f\"Distance: {distance:.1f} cm\")\n\nshow_lidar(scan, highlighted_samples=[(angle, distance)])",
"Angle: 86.5 degrees\nDistance: 85.8 cm\n"
]
],
[
[
"Once again, we should handle when the specified degree range passes over the edge of our array. **<span style=\"color:red\">If you have not done so already, update `get_lidar_closest_point` to support negative angles and windows that cross the edge of the array.</span>**.",
"_____no_output_____"
]
],
[
[
"angle, distance = get_lidar_closest_point(scan, (-30, 30))\nprint(f\"Angle: {angle:.1f} degrees\")\nprint(f\"Distance: {distance:.1f} cm\")\n\nshow_lidar(scan, highlighted_samples=[(angle, distance)])",
"Angle: 3.5 degrees\nDistance: 58.3 cm\n"
]
],
[
[
"You are now ready to begin on LIDAR labs `lab4a.py` and `lab4b.py`. Good luck, and don't be afraid to ask questions!",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
ecd13ad1f217c7900d51451d4dfb8bdfedfc51a4 | 6,072 | ipynb | Jupyter Notebook | notebooks/index.ipynb | slel/oscovida | ad35b5c39f940f98e49d013858f47f405e951be3 | [
"BSD-3-Clause"
] | 26 | 2020-02-01T16:51:14.000Z | 2020-06-28T18:01:05.000Z | notebooks/index.ipynb | slel/oscovida | ad35b5c39f940f98e49d013858f47f405e951be3 | [
"BSD-3-Clause"
] | 239 | 2020-07-02T07:43:37.000Z | 2022-03-29T07:55:58.000Z | notebooks/index.ipynb | slel/oscovida | ad35b5c39f940f98e49d013858f47f405e951be3 | [
"BSD-3-Clause"
] | 15 | 2020-02-02T04:07:30.000Z | 2020-06-23T09:19:48.000Z | 18.740741 | 141 | 0.513669 | [
[
[
"# Coronavirus 2020 - overview of some countries",
"_____no_output_____"
],
[
"- Please scroll down for plots.\n\n- We use data from the files at https://github.com/CSSEGISandData/COVID19/tree/master/csse_covid_19_data/csse_covid_19_time_series\n\n- Acknowledgements:\n - great tutorials from https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw\n - idea for loglog plot from https://www.youtube.com/user/minutephysics \n - Johns Hopkins University for providing the data\n - Open Source and scientific computing community for the data tools\n\n",
"_____no_output_____"
]
],
[
[
"%config InlineBackend.figure_formats = ['svg']\n%matplotlib inline\n# Alternative plotting backend for interative data exploration\n# %matplotlib notebook\n\nfrom oscovida import overview, compare_plot\n\n# If you want to edit the source in the notebook, try \"%load oscovida.py\" \n# and comment out the import statement above.",
"_____no_output_____"
]
],
[
[
"# China, South Korea, Singapore",
"_____no_output_____"
],
[
"## China",
"_____no_output_____"
]
],
[
[
"axes, cases, deaths = overview(\"China\")\ncompare_plot(\"China\");",
"_____no_output_____"
]
],
[
[
"## South Korea",
"_____no_output_____"
]
],
[
[
"axes, cases, deaths = overview(\"Korea, South\", savefig=False)\ncompare_plot(\"Korea, South\");",
"_____no_output_____"
]
],
[
[
"## Singapore",
"_____no_output_____"
]
],
[
[
"axes, cases, deaths = overview(\"Singapore\")\ncompare_plot(\"Singapore\");",
"_____no_output_____"
]
],
[
[
"# Countries with large numbers of reported infections",
"_____no_output_____"
],
[
"## United States",
"_____no_output_____"
]
],
[
[
"axes, cases, deaths = overview(\"US\")\ncompare_plot(\"US\");",
"_____no_output_____"
]
],
[
[
"## Italy",
"_____no_output_____"
]
],
[
[
"overview(\"Italy\");\ncompare_plot(\"Italy\");",
"_____no_output_____"
]
],
[
[
"## Spain",
"_____no_output_____"
]
],
[
[
"axes, cases, deaths = overview(\"Spain\")\ncompare_plot(\"Spain\");",
"_____no_output_____"
]
],
[
[
"## Germany",
"_____no_output_____"
]
],
[
[
"overview(\"Germany\");\ncompare_plot(\"Germany\");",
"_____no_output_____"
]
],
[
[
"## France",
"_____no_output_____"
]
],
[
[
"overview(\"France\");\ncompare_plot(\"France\");",
"_____no_output_____"
]
],
[
[
"## Iran",
"_____no_output_____"
]
],
[
[
"overview(\"Iran\");\ncompare_plot(\"Iran\");",
"_____no_output_____"
]
],
[
[
"## United Kingdom",
"_____no_output_____"
]
],
[
[
"overview(\"United Kingdom\");\ncompare_plot(\"United Kingdom\");",
"_____no_output_____"
]
],
[
[
"## Switzerland",
"_____no_output_____"
]
],
[
[
"overview(\"Switzerland\");\ncompare_plot(\"Switzerland\");",
"_____no_output_____"
]
],
[
[
"## Austria",
"_____no_output_____"
]
],
[
[
"overview(\"Austria\");\ncompare_plot(\"Austria\");",
"_____no_output_____"
],
[
"import oscovida\noscovida.fetch_cases_last_execution(), oscovida.fetch_deaths_last_execution()",
"_____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",
"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",
"code"
]
] |
ecd1443358796b6d77ef33f4e96796485243a458 | 76,819 | ipynb | Jupyter Notebook | AnalysisData/Step02-ImportAndClean.ipynb | kchen79427/Milestone_I | 0502e99088ddc27307ad5f94344bcfbfc049dbbb | [
"MIT"
] | null | null | null | AnalysisData/Step02-ImportAndClean.ipynb | kchen79427/Milestone_I | 0502e99088ddc27307ad5f94344bcfbfc049dbbb | [
"MIT"
] | null | null | null | AnalysisData/Step02-ImportAndClean.ipynb | kchen79427/Milestone_I | 0502e99088ddc27307ad5f94344bcfbfc049dbbb | [
"MIT"
] | null | null | null | 107.289106 | 10,710 | 0.701064 | [
[
[
"import pandas as pd\npd.set_option('max_columns', None)\nimport numpy as np\nimport json\nimport seaborn as sns\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"Create dictionaries to update column names and to help with creating new columns...",
"_____no_output_____"
]
],
[
[
"race_cols = {\"Driver\": \"Driver\", \"Car\": \"Car #\", \"AvgPos\": \"Average Position\", \"PassDiff\": \"Pass Differential\",\n \"GreenPass\": \"Green Passes\", \"GreenPassed\": \"Green Passed\", \"QualityPasses\": \"Quality Passes\",\n \"PercentQualityPasses\": \"% Quality Passes\", \"NumFastestLaps\": \"# Fastest Laps\",\n \"LapsTop15\": \"Laps in Top 15\", \"PercentLapsTop15\": \"% Laps in Top 15\", \"LapsLed\": \"Laps Led\",\n \"PercentLapsLed\": \"% Laps Led\", \"TotalLaps\": \"Total Laps\", \"DriverRating\": \"Driver Rating\",\n \"Pts\": \"Points\", \"StartPos\": \"Start\", \"MidRace\": \"Mid Race\", \"FinishPos\": \"Finish\"}\n\nrace_cols_daytona1_22 = {\"Driver\": \"Driver\", \"Car\": \"Car #\", \"AvgStart\": \"Start\", \"AvgMidRace\": \"Mid Race\", \"AvgFinish\": \"Finish\",\n \"Avg Pos\": \"Average Position\", \"PassDiff\": \"Pass Differential\", \"GreenPass\": \"Green Passes\",\n \"GreenPassed\": \"Green Passed\", \"QualityPasses\": \"Quality Passes\",\n \"PercentQualityPasses\": \"% Quality Passes\", \"NumFastestLaps\": \"# Fastest Laps\",\n \"LapsinTop15\": \"Laps in Top 15\", \"PercentLapsTop15\": \"% Laps in Top 15\", \"LapsLed\": \"Laps Led\",\n \"PercentLapsLed\": \"% Laps Led\", \"TotalLaps\": \"Total Laps\", \"DriverRating\": \"Driver Rating\",\n \"Pts\": \"Points\"}\n\ncar_nums_22 = {\"AJ Allmendinger\": 16, \"Aric Almirola\": 10, \"Christopher Bell\": 20, \"Greg Biffle\": 44,\n \"Josh Bilicki\": 77, \"Ryan Blaney\": 12, \"Alex Bowman\": 48, \"Chase Briscoe\": 14,\n \"Chris Buescher\": 17, \"Harrison Burton\": 21, \"Kurt Busch\": 45, \"Kyle Busch\": 18,\n \"William Byron\": 24, \"Landon Cassill\": 77, \"Ross Chastain\": 1, \"William Byron Jr.\": 24,\n \"Austin Cindric\": 2, \"Cole Custer\": 41, \"Austin Dillon\": 3, \"Ty Dillon\": 42,\n \"Chase Elliott\": 9, \"Todd Gilliland\": 38, \"Noah Gragson\": 16, \"Kaz Grala\": 50,\n \"Denny Hamlin\": 11, \"Joey Hand\": 15, \"Kevin Harvick\": 4, \"Justin Haley\": 31,\n \"Daniel Hemric\": 16, \"Loris Hezemans\": 27, \"Erik Jones\": 20, \"Brad Keselowski\": 6,\n \"Corey LaJoie\": 7, \"Kyle Larson\": 5, \"Joey Logano\": 22, \"BJ McLeod\": 78,\n \"Michael McDowell\": 34, \"Ryan Preece\": 15, \"David Ragan\": 15, \"Tyler Reddick\": 8,\n \"Boris Said\": 66, \"Garrett Smithley\": 15, \"Ricky Stenhouse Jr.\": 47, \"Daniel Suárez\": 99,\n \"Martin Truex Jr.\": 19, \"Jacques Villeneuve\": 27, \"Bubba Wallace\": 23, \"Cody Ware\": 51}\n\nteams_22 = {\"AJ Allmendinger\": \"Kaulig\", \"Aric Almirola\": \"SHR\", \"Christopher Bell\": \"JGR\", \"Greg Biffle\": \"NYR\",\n \"Josh Bilicki\": \"Spire\", \"Ryan Blaney\": \"Penske\", \"Alex Bowman\": \"Hendrick\", \"Chase Briscoe\": \"SHR\",\n \"Chris Buescher\": \"RFK\", \"Harrison Burton\": \"WBR\", \"Kurt Busch\": \"23X1\", \"Kyle Busch\": \"JGR\",\n \"William Byron\": \"Hendrick\", \"Landon Cassill\": \"Spire\", \"Ross Chastain\": \"Trackhouse\", \"Austin Cindric\": \"Penske\",\n \"Cole Custer\": \"SHR\", \"Austin Dillon\": \"RCR\", \"Ty Dillon\": \"PGMS\", \"Chase Elliott\": \"Hendrick\",\n \"Todd Gilliland\": \"FRM\", \"Noah Gragson\": \"Kaulig\", \"Kaz Grala\": \"TMT\", \"Denny Hamlin\": \"JGR\",\n \"Joey Hand\": \"RWR\", \"Kevin Harvick\": \"SHR\", \"Justin Haley\": \"Kaulig\", \"Daniel Hemric\": \"Kaulig\",\n \"Loris Hezemans\": \"Hezeberg\", \"Erik Jones\": \"PGMS\", \"Brad Keselowski\": \"RFK\", \"Corey LaJoie\": \"Spire\",\n \"Kyle Larson\": \"Hendrick\", \"Joey Logano\": \"Penske\", \"BJ McLeod\": \"LFM\", \"Michael McDowell\": \"FRM\",\n \"Ryan Preece\": \"RWR\", \"David Ragan\": \"RWR\", \"Tyler Reddick\": \"RCR\", \"Boris Said\": \"MBM\",\n \"Garrett Smithley\": \"RWR\", \"Ricky Stenhouse Jr.\": \"JTGD\", \"Daniel Suárez\": \"Trackhouse\", \"Martin Truex Jr.\": \"JGR\",\n \"Jacques Villeneuve\": \"Hezeberg\", \"Bubba Wallace\": \"23X1\", \"Cody Ware\": \"RWR\", \"Martin Truex Jr\": \"JGR\"}\n\nmakes = {\"23X1\": \"Toyota\", \"Beard\": \"Chevy\", \"FRM\": \"Ford\", \"Hendrick\": \"Chevy\",\n \"Hezeberg\": \"Ford\", \"JGR\": \"Toyota\", \"JTGD\": \"Chevy\", \"Kaulig\": \"Chevy\",\n \"LFM\": \"Ford\", \"MBM\": \"Ford\", \"NYR\": \"Chevy\", \"Penske\": \"Ford\",\n \"PGMS\": \"Chevy\", \"RCR\": \"Chevy\", \"RFK\": \"Ford\", \"RWR\": \"Ford\",\n \"SHR\": \"Ford\", \"Spire\": \"Chevy\", \"TMT\": \"Chevy\", \"Trackhouse\": \"Chevy\",\n \"WBR\": \"Ford\", \"GBR\": \"Toyota\", \"StarCom\": \"Chevy\"}\n\ntrack_types = {\"Auto Club\": \"Speedway\", \"Atlanta\": \"Superpeedway\", \"Bristol\": \"Short Track\", \"COTA\": \"Road Course\",\n \"Daytona\": \"Superspeedway\", \"Las Vegas\": \"Speedway\", \"Martinsville\": \"Short Track\", \"Phoenix\": \"Short Track\",\n \"Richmond\": \"Short Track\", \"Talladega\": \"Superspeedway\", \"Dover\": \"Short Track\",\n \"Darlington\": \"Speedway\", \"Kansas\": \"Speedway\", \"Charlotte\": \"Speedway\", \"Gateway\": \"Speedway\",\n \"Sonoma\": \"Road Course\", \"Nashville\": \"Speedway\", \"Road America\": \"Road Course\",\n \"Loudon\": \"Short Track\", \"Pocono\": \"Speedway\", \"Indianapolis RC\": \"Road Course\",\n \"Michigan\": \"Speedway\", \"Watkins Glen\": \"Road Course\", \"Texas\": \"Speedway\",\n \"Homestead\": \"Speedway\", \"Daytona RC\": \"Road Course\", \"Charlotte RC\": \"Road Course\"}\n\ncar_nums_21 = {'Michael McDowell': 34, 'Chase Elliott': 9, 'Austin Dillon': 3,\n 'Kevin Harvick': 4, 'Denny Hamlin': 11, 'Ryan Preece': 37, 'Ross Chastain': 42,\n 'Jamie McMurray': 40, 'Corey Lajoie': 7, 'Kyle Larson': 5, 'Cole Custer': 41,\n 'Joey Logano': 22, 'Brad Keselowski': 2, 'Kyle Busch': 18, 'Austin Cindric': 33,\n 'Christopher Bell': 20, 'Bubba Wallace': 23, 'Ricky Stenhouse Jr': 47,\n 'Chase Briscoe': 14, 'Joey Gase': 53, 'Cody Ware': 51, 'Kurt Busch': 1,\n 'BJ McLeod': 78, 'Josh Bilicki': 52, 'Martin Truex Jr': 19, 'William Byron': 24,\n 'Tyler Reddick': 8, 'Kaz Grala': 16, 'Quin Houff': 00, 'Ryan Blaney': 12,\n 'Chris Buescher': 17, 'Anthony Alfredo': 38, 'Matt DiBenedetto': 21,\n 'Aric Almirola': 10, 'Alex Bowman': 48, 'Daniel Suarez': 99, 'David Ragan': 36,\n 'Ryan Newman': 6, 'Erik Jones': 43, 'Derrike Cope': 15, 'AJ Allmendinger': 16,\n 'Ty Dillon': 96, 'James Davison': 15, 'Justin Haley': 77, 'Garrett Smithley': 53,\n 'Scott Heckert': 78, 'Timmy Hill': 66, 'Stewart Friesen': 77, 'JJ Yeley': 15,\n 'Mike Marlar': 66, 'Chris Windom': 77, 'Shane Golobic': 78, 'Harrison Burton': 96,\n 'Matt Mills': 78, 'Josh Berry': 77, 'Kyle Tilley': 78, 'David Starr': 66,\n 'Ben Rhodes': 77, 'Chad Finchum': 66, 'Justin Allgaier': 77, 'Ryan Eversley': 52,\n 'Bayley Currey': 52, 'Rc Enerson': 53, 'Andy Lally': 78, 'Landon Cassill': 77,\n 'Joey Hand': 52, 'Parker Kligerman': 96, 'Ryan Ellis': 77, \"Daniel Suárez\": 99,\n \"Martin Truex Jr.\": 19, \"Ricky Stenhouse Jr.\": 47}\n\nteams_21 = {'Michael McDowell': \"FRM\", 'Chase Elliott': \"Hendrick\", 'Austin Dillon': \"RCR\",\n 'Kevin Harvick': \"SHR\", 'Denny Hamlin': \"JGR\", 'Ryan Preece': \"JTGD\", 'Ross Chastain': \"CGR\",\n 'Jamie McMurray': \"Spire\", 'Corey Lajoie': \"Spire\", 'Kyle Larson': \"Hendrick\", 'Cole Custer': \"SHR\",\n 'Joey Logano': \"Penske\", 'Brad Keselowski': \"Penske\", 'Kyle Busch': \"JGR\", 'Austin Cindric': \"Penske\",\n 'Christopher Bell': \"JGR\", 'Bubba Wallace': \"23X1\", 'Ricky Stenhouse Jr': \"JTGD\",\n 'Chase Briscoe': \"SHR\", 'Joey Gase': \"RWR\", 'Cody Ware': \"RWR\", 'Kurt Busch': \"CGR\",\n 'BJ McLeod': \"LFM\", 'Josh Bilicki': \"RWR\", 'Martin Truex Jr': \"JGR\", 'William Byron': \"Hendrick\",\n 'Tyler Reddick': \"RCR\", 'Kaz Grala': \"Kaulig\", 'Quin Houff': \"StarCom\", 'Ryan Blaney': \"Penske\",\n 'Chris Buescher': \"RFK\", 'Anthony Alfredo': \"FRM\", 'Matt DiBenedetto': \"WBR\",\n 'Aric Almirola': \"SHR\", 'Alex Bowman': \"Hendrick\", 'Daniel Suarez': \"Trackhouse\", 'David Ragan': \"FRM\",\n 'Ryan Newman': \"RFK\", 'Erik Jones': \"PGMS\", 'Derrike Cope': \"RWR\", 'AJ Allmendinger': \"Kaulig\",\n 'Ty Dillon': \"GBR\", 'James Davison': \"RWR\", 'Justin Haley': \"Spire\", 'Garrett Smithley': \"RWR\",\n 'Scott Heckert': \"LFM\", 'Timmy Hill': \"MBM\", 'Stewart Friesen': \"Spire\", 'JJ Yeley': \"RWR\",\n 'Mike Marlar': \"MBM\", 'Chris Windom': \"Spire\", 'Shane Golobic': \"LFM\", 'Harrison Burton': \"GBR\",\n 'Matt Mills': \"LFM\", 'Josh Berry': \"Spire\", 'Kyle Tilley': \"LFM\", 'David Starr': \"MBM\",\n 'Ben Rhodes': \"Spire\", 'Chad Finchum': \"MBM\", 'Justin Allgaier': \"Spire\", 'Ryan Eversley': \"RWR\",\n 'Bayley Currey': \"RWR\", 'Rc Enerson': \"RWR\", 'Andy Lally': \"LFM\", 'Landon Cassill': \"Spire\",\n 'Joey Hand': \"RWR\", 'Parker Kligerman': \"GBR\", 'Ryan Ellis': \"Spire\", \"Daniel Suárez\": \"Trackhouse\",\n \"Martin Truex Jr.\": \"JGR\", \"Ricky Stenhouse Jr.\": \"JTGD\"}\n\nALL_2021_Drivers=['Michael McDowell', 'Chase Elliott', 'Austin Dillon',\n 'Kevin Harvick', 'Denny Hamlin', 'Ryan Preece', 'Ross Chastain',\n 'Jamie McMurray', 'Corey Lajoie', 'Kyle Larson', 'Cole Custer',\n 'Joey Logano', 'Brad Keselowski', 'Kyle Busch', 'Austin Cindric',\n 'Christopher Bell', 'Bubba Wallace', 'Ricky Stenhouse Jr',\n 'Chase Briscoe', 'Joey Gase', 'Cody Ware', 'Kurt Busch',\n 'BJ McLeod', 'Josh Bilicki', 'Martin Truex Jr', 'William Byron',\n 'Tyler Reddick', 'Kaz Grala', 'Quin Houff', 'Ryan Blaney',\n 'Chris Buescher', 'Anthony Alfredo', 'Matt DiBenedetto',\n 'Aric Almirola', 'Alex Bowman', 'Daniel Suarez', 'David Ragan',\n 'Ryan Newman', 'Erik Jones', 'Derrike Cope', 'AJ Allmendinger',\n 'Ty Dillon', 'James Davison', 'Justin Haley', 'Garrett Smithley',\n 'Scott Heckert', 'Timmy Hill', 'Stewart Friesen', 'JJ Yeley',\n 'Mike Marlar', 'Chris Windom', 'Shane Golobic', 'Harrison Burton',\n 'Matt Mills', 'Josh Berry', 'Kyle Tilley', 'David Starr',\n 'Ben Rhodes', 'Chad Finchum', 'Justin Allgaier', 'Ryan Eversley',\n 'Bayley Currey', 'Rc Enerson', 'Andy Lally', 'Landon Cassill',\n 'Joey Hand', 'Parker Kligerman', 'Ryan Ellis']\n\ncup_laps = {1: 201}",
"_____no_output_____"
]
],
[
[
"Read in all loop data from csv files. The csv files were previously downloaded from the web using code to grab the available json from urls. The web scraping code is available in our project files. The csv files are also available since these files are small enough to share.\n\nIf the data paths do not work, please note the raw data can be located in these directories: \n* data/lap_data\n* data/loop_data",
"_____no_output_____"
]
],
[
[
"# /work/Milestone_I/data/loop_TobyChristie/csv/2021\ndaytona1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210215_Daytona500.csv')\ndaytonarc_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210221_DaytonaRoadCourse.csv')\nhomestead_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210228_Homestead-MiamiSpeedway.csv')\nlasvegas1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210307_LasVegasMotorSpeedway.csv')\nphoenix1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210314_PhoenixRaceway.csv')\natlanta1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210321_AtlantaMotorSpeedway.csv')\nbristoldirt_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210329_BristolMotorSpeedwayDirt.csv')\nmartinsville1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210412_MartinsvilleSpeedway.csv')\nrichmond1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210418_RichmondRaceway.csv')\ntalladega1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210425_TalladegaSuperspeedway.csv')\nkansas1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210502_KansasSpeedway.csv')\ndarlington1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210509_DarlingtonRaceway.csv')\ndover_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210516_DoverInternationalSpeedway.csv')\ncota_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210523_CircuitofTheAmericas.csv')\ncharlotte_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210530_CharlotteMotorSpeedway.csv')\nsonoma_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210606_SonomaRaceway.csv')\nnashville_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210620_NashvilleSuperspeedway.csv')\npocono1_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210626_PoconoRaceway.csv')\npocono2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210627_PoconoRaceway.csv')\nroadamerica_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210704_RoadAmerica.csv')\natlanta2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210711_AtlantaMotorSpeedway.csv')\nloudon_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210718_NewHampshireMotorSpeedway.csv')\nwatkinsglen_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210808_WatkinsGlenInternational.csv')\nindianapolisrc_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210815_IndianapolisMotorRoadCourse.csv')\nmichigan_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210822_MichiganInternationalSpeedway.csv')\ndaytona2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210828_DaytonaInternationalSpeedway.csv')\ndarlington2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210905_DarlingtonRaceway.csv')\nrichmond2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210911_RichmondRaceway.csv')\nbristol_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210918_BristolMotorSpeedway.csv')\nlasvegas2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20210926_LasVegasMotorSpeedway.csv')\ntalladega2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20211004_TalladegaSuperspeedway.csv')\ncharlotterc_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20211010_CharlotteRoadCourse.csv')\ntexas_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20211017_TexasMotorSpeedway.csv')\nkansas2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20211024_KansasSpeedway.csv')\nmartinsville2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20211031_MartinsvilleSpeedway.csv')\nphoenix2_21_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2021/20211107_PhoenixRaceway.csv')\n\n\n# /work/Milestone_I/data/loop_TobyChristie/csv/2022\ndaytona1_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220220_Daytona500_modified.csv')\nautoclub_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220227_AutoClub.csv')\nlasvegas1_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220306_LasVegas.csv')\nphoenix1_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220313_Phoenix.csv')\natlanta1_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220322_Atlanta.csv')\ncota_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220327_COTA.csv')\nrichmond1_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220403_Richmond.csv')\nmartinsville1_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220410_MartinsvilleSpeedway.csv')\nbristoldirt_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220417_BristolMotorSpeedwayDirt.csv')\ntalladega1_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220424_TalladegaSuperspeedway.csv')\ndover_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220502_DoverMotorSpeedway.csv')\ndarlington1_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220508_DarlingtonRaceway.csv')\nkansas1_22_loop = pd.read_csv('/work/Milestone_I/data/loop_TobyChristie/csv/2022/20220515_KansasSpeedway.csv')\n\n\n#print(daytona1.columns)\n#print(autoclub.columns)\n#daytona1.head()",
"_____no_output_____"
],
[
"#bristol_21_loop",
"_____no_output_____"
],
[
"#bristoldirt_21_loop",
"_____no_output_____"
]
],
[
[
"Create function to:\n- Update some names to make them consistent across dataframes.\n- Add total number of consecutive races to the dataframes.\n\nRun the function on all race dataframes.",
"_____no_output_____"
]
],
[
[
"def add_Races(prev_df, curr_df):\n prev_df = prev_df.set_index('Driver')\n curr_df = curr_df.set_index('Driver')\n df = curr_df.copy()\n df[\"Races\"] = 1\n if \"Daniel Suarez\" in df.index:\n df = df.rename(index={'Daniel Suarez':'Daniel Suárez'})\n if \"Martin Truex Jr\" in df.index:\n df = df.rename(index={'Martin Truex Jr':'Martin Truex Jr.'}) \n if \"Ricky Stenhouse Jr\" in df.index:\n df = df.rename(index={'Ricky Stenhouse Jr':'Ricky Stenhouse Jr.'}) \n if \"William Byron Jr.\" in df.index:\n df = df.rename(index={'William Byron Jr.':'William Byron'}) \n for driver in df.index:\n if driver in prev_df.index:\n if df.loc[driver, \"TotalLaps\"] != prev_df.loc[driver, \"TotalLaps\"]:\n df.loc[driver, \"Races\"] = prev_df.loc[driver, \"Races\"] + 1\n \n df = df.reset_index(drop = False)\n return df\n\n\n#2021 data\ndaytona1_21_loop[\"Races\"] = 1\ndaytona1_21 = daytona1_21_loop\ndaytona1_21 = daytona1_21.set_index('Driver')\nif \"Daniel Suarez\" in daytona1_21.index:\n daytona1_21 = daytona1_21.rename(index={'Daniel Suarez':'Daniel Suárez'})\nif \"Martin Truex Jr\" in daytona1_21.index:\n daytona1_21 = daytona1_21.rename(index={'Martin Truex Jr':'Martin Truex Jr.'}) \nif \"Ricky Stenhouse Jr\" in daytona1_21.index:\n daytona1_21 = daytona1_21.rename(index={'Ricky Stenhouse Jr':'Ricky Stenhouse Jr.'}) \nif \"William Byron Jr.\" in daytona1_21.index:\n daytona1_21 = daytona1_21.rename(index={'William Byron Jr.':'William Byron'})\ndaytona1_21 = daytona1_21.reset_index(drop = False)\n\n# 2021 DATA\n# All of the races added/put together by Bret\ndaytonarc_21 = add_Races(daytona1_21, daytonarc_21_loop)\nhomestead_21 = add_Races(daytonarc_21, homestead_21_loop)\nlasvegas1_21 = add_Races(homestead_21, lasvegas1_21_loop)\nphoenix1_21 = add_Races(lasvegas1_21, phoenix1_21_loop)\natlanta1_21 = add_Races(phoenix1_21, atlanta1_21_loop)\nbristoldirt_21 = add_Races(atlanta1_21, bristoldirt_21_loop)\nmartinsville1_21 = add_Races(bristoldirt_21, martinsville1_21_loop)\nrichmond1_21 = add_Races(martinsville1_21, richmond1_21_loop)\ntalladega1_21 = add_Races(richmond1_21, talladega1_21_loop)\nkansas1_21 = add_Races(talladega1_21, kansas1_21_loop)\ndarlington1_21 = add_Races(kansas1_21, darlington1_21_loop)\ndover_21 = add_Races(darlington1_21, dover_21_loop)\ncota_21 = add_Races(dover_21, cota_21_loop)\ncharlotte_21 = add_Races(cota_21, charlotte_21_loop)\nsonoma_21 = add_Races(charlotte_21, sonoma_21_loop)\nnashville_21 = add_Races(sonoma_21, nashville_21_loop)\npocono1_21 = add_Races(nashville_21, pocono1_21_loop)\npocono2_21 = add_Races(pocono1_21, pocono2_21_loop)\nroadamerica_21 = add_Races(pocono2_21, roadamerica_21_loop)\natlanta2_21 = add_Races(roadamerica_21, atlanta2_21_loop)\nloudon_21 = add_Races(atlanta2_21, loudon_21_loop)\nwatkinsglen_21 = add_Races(loudon_21, watkinsglen_21_loop)\nindianapolisrc_21 = add_Races(watkinsglen_21, indianapolisrc_21_loop)\nmichigan_21 = add_Races(indianapolisrc_21, michigan_21_loop)\ndaytona2_21 = add_Races(michigan_21, daytona2_21_loop)\ndarlington2_21 = add_Races(daytona2_21, darlington2_21_loop)\nrichmond2_21 = add_Races(darlington2_21, richmond2_21_loop)\nbristol_21 = add_Races(richmond2_21, bristol_21_loop)\nlasvegas2_21 = add_Races(bristol_21, lasvegas2_21_loop)\ntalladega2_21 = add_Races(lasvegas2_21, talladega2_21_loop)\ncharlotterc_21 = add_Races(talladega2_21, charlotterc_21_loop)\ntexas_21 = add_Races(charlotterc_21, texas_21_loop)\nkansas2_21 = add_Races(texas_21, kansas2_21_loop)\nmartinsville2_21 = add_Races(kansas2_21, martinsville2_21_loop)\nphoenix2_21 = add_Races(martinsville2_21, phoenix2_21_loop)\n\n\n#2022 data\ndaytona1_22_loop[\"Races\"] = 1\ndaytona1_22 = daytona1_22_loop\nautoclub_22 = add_Races(daytona1_22, autoclub_22_loop)\nlasvegas1_22 = add_Races(autoclub_22, lasvegas1_22_loop)\nphoenix1_22 = add_Races(lasvegas1_22, phoenix1_22_loop)\natlanta1_22 = add_Races(phoenix1_22, atlanta1_22_loop)\ncota_22 = add_Races(atlanta1_22, cota_22_loop)\nrichmond1_22 = add_Races(cota_22, richmond1_22_loop)\nmartinsville1_22 = add_Races(richmond1_22, martinsville1_22_loop)\nbristoldirt_22 = add_Races(martinsville1_22, bristoldirt_22_loop)\ntalladega1_22 = add_Races(bristoldirt_22, talladega1_22_loop)\ndover_22 = add_Races(talladega1_22, dover_22_loop)\ndarlington1_22 = add_Races(dover_22, darlington1_22_loop)\nkansas1_22 = add_Races(darlington1_22, kansas1_22_loop)",
"_____no_output_____"
],
[
"daytona1_21.columns",
"_____no_output_____"
]
],
[
[
"Create function to add the \"Season\", \"Team\", \"Points Eligible\", \"Make\", \"Same Races - Race #\", \"Race #\",\"Track\", \"Track Type\", and \"Quality Passes Per Lap\" to each dataframe.\n",
"_____no_output_____"
]
],
[
[
"def add_cols(df, season, track = \"\", racenum = 0, sameracenum = 0):\n df[\"Season\"] = season\n #print(df.columns)\n df = df.rename(columns = race_cols, errors = \"raise\")\n df = df.drop(['CloserPos', 'HighPos', 'LowPos'], axis = 1)\n\n if season == 2022:\n df[\"Team\"] = df[\"Driver\"].map(teams_22)\n\n if season == 2021:\n df[\"Team\"] = df[\"Driver\"].map(teams_21)\n if track == \"Atlanta\":\n df[\"Track Type\"] = \"Speedway\"\n\n df[\"Points Eligible\"] = [1 if row > 0 else 0 for row in df[\"Points\"]]\n df[\"Make\"] = df[\"Team\"].map(makes)\n df[\"Same Races - Race #\"] = sameracenum\n df[\"Race #\"] = racenum\n df[\"Track\"] = track\n df[\"Track Type\"] = df[\"Track\"].map(track_types)\n df[\"Quality Passes Per Lap\"] = round(df[\"Quality Passes\"] / df[\"Total Laps\"], 3)\n\n \n\n return df",
"_____no_output_____"
]
],
[
[
"Run the above function on the 2021 data...",
"_____no_output_____"
]
],
[
[
"# 2021\ndaytona1_21 = add_cols(daytona1_21, 2021, \"Daytona\", 1, 1)\ndaytonarc_21 = add_cols(daytonarc_21, 2021, \"Daytona RC\", 2)\nhomestead_21 = add_cols(homestead_21, 2021, \"Homestead\", 3)\nlasvegas1_21 = add_cols(lasvegas1_21, 2021, \"Las Vegas\", 4, 2)\nphoenix1_21 = add_cols(phoenix1_21, 2021, \"Phoenix\", 5, 3)\natlanta1_21 = add_cols(atlanta1_21, 2021, \"Atlanta\", 6, 4)\nbristoldirt_21 = add_cols(bristoldirt_21, 2021, \"Bristol\", 7, 5)\nmartinsville1_21 = add_cols(martinsville1_21, 2021, \"Martinsville\", 8, 6)\nrichmond1_21 = add_cols(richmond1_21, 2021, \"Richmond\", 9, 7)\ntalladega1_21 = add_cols(talladega1_21, 2021, \"Talladega\", 10, 8)\nkansas1_21 = add_cols(kansas1_21, 2021, \"Kansas\", 11, 11)\ndarlington1_21 = add_cols(darlington1_21, 2021, \"Darlington\", 12, 9)\ndover_21 = add_cols(dover_21, 2021, \"Dover\", 13, 10)\ncota_21 = add_cols(cota_21, 2021, \"COTA\", 14, 0)\ncharlotte_21 = add_cols(charlotte_21, 2021, \"Charlotte\", 15, 0)\nsonoma_21 = add_cols(sonoma_21, 2021, \"Sonoma\", 16, 0)\nnashville_21 = add_cols(nashville_21, 2021, \"Nashville\", 17, 0)\npocono1_21 = add_cols(pocono1_21, 2021, \"Pocono\", 18, 0)\npocono2_21 = add_cols(pocono2_21, 2021, \"Pocono\", 19, 0)\nroadamerica_21 = add_cols(roadamerica_21, 2021, \"Road America\", 20, 0)\natlanta2_21 = add_cols(atlanta2_21, 2021, \"Atlanta\", 21, 0)\nloudon_21 = add_cols(loudon_21, 2021, \"Loudon\", 22, 0)\nwatkinsglen_21 = add_cols(watkinsglen_21, 2021, \"Watkins Glen\", 23, 0)\nindianapolisrc_21 = add_cols(indianapolisrc_21, 2021, \"Indianapolis RC\", 24, 0)\nmichigan_21 = add_cols(michigan_21, 2021, \"Michigan\", 25, 0)\ndaytona2_21 = add_cols(daytona2_21, 2021, \"Daytona\", 26, 0)\ndarlington2_21 = add_cols(darlington2_21, 2021, \"Darlington\", 27, 0)\nrichmond2_21 = add_cols(richmond2_21, 2021, \"Richmond\", 28, 0)\nbristol_21 = add_cols(bristol_21, 2021, \"Bristol\", 29, 0)\nlasvegas2_21 = add_cols(lasvegas2_21, 2021, \"Las Vegas\", 30, 0)\ntalladega2_21 = add_cols(talladega2_21, 2021, \"Talladega\", 31, 0)\ncharlotterc_21 = add_cols(charlotterc_21, 2021, \"Charlotte RC\", 32, 0)\ntexas_21 = add_cols(texas_21, 2021, \"Texas\", 33, 0 )\nkansas2_21 = add_cols(kansas2_21, 2021, \"Kansas\", 34, 0)\nmartinsville2_21 = add_cols(martinsville2_21, 2021, \"Martinsville\", 35, 0)\nphoenix2_21 = add_cols(phoenix2_21, 2021, \"Phoenix\", 36, 0)\n",
"_____no_output_____"
]
],
[
[
"and then run the same function on the 2022 data...",
"_____no_output_____"
]
],
[
[
"# 2022\ndaytona1_22 = add_cols(daytona1_22, 2022, \"Daytona\", 1, 1)\nautoclub_22 = add_cols(autoclub_22, 2022, \"Auto Club\", 2, 0)\nlasvegas1_22 = add_cols(lasvegas1_22, 2022, \"Las Vegas\", 3, 2)\nphoenix1_22 = add_cols(phoenix1_22, 2022, \"Phoenix\", 4, 3)\natlanta1_22 = add_cols(atlanta1_22, 2022, \"Atlanta\", 5, 4)\ncota_22 = add_cols(cota_22, 2022, \"COTA\", 6, 0)\nrichmond1_22 = add_cols(richmond1_22, 2022, \"Richmond\", 7, 5)\nmartinsville1_22 = add_cols(martinsville1_22, 2022, \"Martinsville\", 8, 6)\nbristoldirt_22 = add_cols(bristoldirt_22, 2022, \"Bristol\", 9, 7)\ntalladega1_22 = add_cols(talladega1_22, 2022, \"Talladega\", 10, 8)\ndover_22 = add_cols(dover_22, 2022, \"Dover\", 11, 9)\ndarlington1_22 = add_cols(darlington1_22, 2022, \"Darlington\", 12, 10)\nkansas1_22 = add_cols(kansas1_22, 2022, \"Kansas\", 13, 11)\n",
"_____no_output_____"
],
[
"#martinsville2_21",
"_____no_output_____"
],
[
"#daytona1_21.Driver.unique",
"_____no_output_____"
]
],
[
[
"Create a function to bring in the json file, create several derived variables and adjust names for consistency, ",
"_____no_output_____"
]
],
[
[
"def raw_laps_to_stats(json_file): # Takes lap-times.json file from Race Center, mapping lap stats to drivers\n \n f = open(json_file)\n data = json.load(f)\n \n driver_stats = {}\n fastest_fast = 1000\n fastest_median = 1000\n fastest_full_speed = 1000\n\n lap_threshold = 28\n lap_list_9 = []\n for i in data[\"laps\"]:\n if (i[\"FullName\"] == \"Chase Elliott\") or (i[\"FullName\"] == \"Chase Elliott (P)\"):\n lap_list_9 = [j[\"LapTime\"] for j in i[\"Laps\"]]\n lap_list_9 = [i for i in lap_list_9 if i]\n #print(lap_list_9)\n lap_list_9 = [i for i in lap_list_9 if i > 13]\n #print(lap_list_9)\n lap_threshold = np.min(lap_list_9) - 0.75\n \n for i in data[\"laps\"]:\n driver = i[\"FullName\"]\n if driver.startswith(\"*\") == True:\n driver = driver[2:]\n if driver.endswith(\"#\") == True:\n driver = driver[:-2]\n elif driver.endswith(\")\") == True:\n driver = driver[:-3]\n driver = driver.rstrip()\n if driver == \"William Byron Jr.\":\n driver = \"William Byron\"\n if driver == \"Daniel Suarez\":\n driver = \"Daniel Suárez\"\n if driver == \"Martin Truex\":\n driver = \"Martin Truex Jr.\"\n if driver == \"Martin Truex Jr\":\n driver = \"Martin Truex Jr.\"\n if driver == \"Ricky Stenhouse\":\n driver = \"Ricky Stenhouse Jr.\"\n #print(driver)\n \n lap_list = []\n #for j in i[\"Laps\"]:\n # lap_list.append(j[\"LapTime\"])\n lap_list = [j[\"LapTime\"] for j in i[\"Laps\"]]\n lap_list = [i for i in lap_list if i] # This removes the \"none\" values\n lap_list = [i for i in lap_list if i >= lap_threshold] # Gets rid of unrealistically small numbers\n \n if len(lap_list) >= 1:\n fast_lap = np.min(lap_list)\n if fast_lap < fastest_fast:\n fastest_fast = fast_lap\n if len(lap_list) >= 1:\n median_lap = round(np.median(lap_list),3)\n if median_lap < fastest_median:\n fastest_median = median_lap\n \n full_speed_laps = []\n for lap in lap_list:\n if lap < fast_lap*1.1:\n full_speed_laps.append(lap)\n if len(full_speed_laps) >= 1:\n average_full_speed_lap = round(np.mean(full_speed_laps),3)\n if average_full_speed_lap < fastest_full_speed:\n fastest_full_speed = average_full_speed_lap\n \n lap_dict = {\"Fastest Lap\": fast_lap, \"Median Lap\": median_lap, \"Average Full Speed Lap\": average_full_speed_lap}\n driver_stats[driver] = lap_dict\n #print(lap_threshold, lap_dict)\n\n for driver in driver_stats:\n driver_stats[driver][\"Fastest Lap % Deficit\"] = (fastest_fast - driver_stats[driver][\"Fastest Lap\"]) / fastest_fast * 100\n if driver_stats[driver][\"Fastest Lap % Deficit\"] < -10:\n print(json_file, driver, driver_stats[driver][\"Fastest Lap % Deficit\"], fastest_fast,\n driver_stats[driver][\"Fastest Lap\"])\n driver_stats[driver][\"Median Lap % Deficit\"] = (fastest_median - driver_stats[driver][\"Median Lap\"]) / fastest_median * 100\n driver_stats[driver][\"Average Full Speed Lap % Deficit\"] = (fastest_full_speed - driver_stats[driver][\"Average Full Speed Lap\"]) / fastest_full_speed * 100\n\n return driver_stats",
"_____no_output_____"
]
],
[
[
"Just a test...",
"_____no_output_____"
]
],
[
[
"test = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-richmond2.json')\ntest",
"_____no_output_____"
]
],
[
[
"Run the function for the json laps data...",
"_____no_output_____"
]
],
[
[
"#2021\ndaytona1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-daytona1.json')\ndaytonarc_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-daytonarc.json')\nhomestead_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-homestead.json')\nlasvegas1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-lasvegas1.json')\nphoenix1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-phoenix1.json')\natlanta1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-atlanta1.json')\nbristoldirt_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-bristoldirt.json')\nmartinsville1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-martinsville1.json')\nrichmond1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-richmond1.json')\ntalladega1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-talladega1.json')\nkansas1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-kansas1.json')\ndarlington1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-darlington1.json')\ndover_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-dover.json')\ncota_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-cota.json')\ncharlotte_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-charlotte.json')\nsonoma_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-sonoma.json')\nnashville_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-nashville.json')\npocono1_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-pocono1.json')\npocono2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-pocono2.json')\nroadamerica_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-roadamerica.json')\natlanta2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-atlanta2.json')\nloudon_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-loudon.json')\nwatkinsglen_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-watkinsglen.json')\nindianapolisrc_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-indianapolisrc.json')\nmichigan_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-michigan.json')\ndaytona2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-daytona2.json')\ndarlington2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-darlington2.json')\nrichmond2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-richmond2.json')\nbristol_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-bristol.json')\nlasvegas2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-lasvegas2.json')\ntalladega2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-talladega2.json')\ncharlotterc_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-charlotterc.json')\ntexas_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-texas.json')\nkansas2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-kansas2.json')\nmartinsville2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-martinsville2.json')\nphoenix2_21_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2021/lap-times-phoenix2.json')\n\n\n#2022\ndaytona1_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-daytona1.json')\nautoclub_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-autoclub.json')\nlasvegas1_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-lasvegas1.json')\nphoenix1_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-phoenix1.json')\natlanta1_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-atlanta1.json')\ncota_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-cota.json')\nrichmond1_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-richmond1.json')\nmartinsville1_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-martinsville1.json')\nbristoldirt_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-bristoldirt.json')\ntalladega1_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-talladega1.json')\ndover_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-dover.json')\ndarlington1_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-darlington1.json')\nkansas1_22_laps = raw_laps_to_stats('/work/Milestone_I/data/lap_data/2022/lap-times-kansas1.json')",
"/work/Milestone_I/data/lap_data/2021/lap-times-daytonarc.json Quin Houff -12.670625967132615 115.677 130.334\n/work/Milestone_I/data/lap_data/2021/lap-times-richmond1.json Justin Haley -145.74648895250021 22.358 54.944\n/work/Milestone_I/data/lap_data/2021/lap-times-talladega1.json Kyle Larson -15.148435184008816 47.226 54.38\n"
],
[
"#talladega2_21_laps",
"_____no_output_____"
]
],
[
[
"Create function to join hte lap stats to the loop data...",
"_____no_output_____"
]
],
[
[
"def add_lap_dict_to_df(lap_dict, main_df): # Adds the driver-mapped lap stats to our main dataframe\n \n rows = []\n \n for key, value in lap_dict.items():\n driver = key\n stats = value\n stats[\"Driver\"] = driver\n rows.append(stats)\n \n lap_df = pd.DataFrame(rows)\n #print(lap_df)\n df = pd.merge(main_df, lap_df, on=\"Driver\")\n #print(df)\n return df",
"_____no_output_____"
],
[
"rows = []\n\nfor key, value in daytona2_21_laps.items():\n driver = key\n stats = value\n stats[\"Driver\"] = driver\n rows.append(stats)\n\nlap_df = pd.DataFrame(rows)\n#print(lap_df)\n# df = pd.merge(main_df, lap_df, on=\"Driver\")\nlap_df.columns\n# return df",
"_____no_output_____"
]
],
[
[
"... and add some more derived variables...",
"_____no_output_____"
]
],
[
[
"def add_more_info(df, laps_dict):\n\n df = add_lap_dict_to_df(laps_dict, df)\n #if \"Finish\" not in df:\n # df[\"Finish\"] = df[\"FinishPos\"]\n #print(df.columns)\n\n df = df.sort_values(by=[\"Finish\"]).reset_index(drop = True)\n df.index = np.arange(1, len(df) + 1) # Makes index value equal to finish position\n\n df[\"Fastest Lap Rank\"] = df[\"Fastest Lap\"].rank(method=\"min\")\n df[\"Median Lap Rank\"] = df[\"Median Lap\"].rank(method=\"min\")\n df[\"Average Full Speed Lap Rank\"] = df[\"Average Full Speed Lap\"].rank(method=\"min\")\n\n df_contenders = df[df[\"Quality Passes\"] >= 10] # Gets rid of cars not part of draft for most of race\n #daytona1_contenders\n df_varsofinterest = df[[\"Finish\", \"Average Position\", \"Pass Differential\", \"Quality Passes\", \"% Quality Passes\",\n \"Quality Passes Per Lap\", \"Fastest Lap\", \"Median Lap\", \"Average Full Speed Lap\"]]\n df_corr = df_varsofinterest.corr()\n\n df_contenders_varsofinterest = df_contenders[[\"Finish\", \"Average Position\", \"Pass Differential\", \"Quality Passes\",\n \"% Quality Passes\", \"Quality Passes Per Lap\", \"Fastest Lap\", \"Median Lap\", \"Average Full Speed Lap\"]]\n df_contenders_corr = df_contenders_varsofinterest.corr()\n\n return df, df_contenders, df_corr, df_contenders_corr",
"_____no_output_____"
]
],
[
[
"Run the function to create the final versions of data for each race...",
"_____no_output_____"
]
],
[
[
"#2021\ndaytona1_21, daytona1_21_contenders, daytona1_21_corr, daytona1_21_contenders_corr = add_more_info(daytona1_21, daytona1_21_laps)\ndaytonarc_21, daytonarc_21_contenders, daytonarc_21_corr, daytonarc_21_contenders_corr = add_more_info(daytonarc_21, daytonarc_21_laps)\nhomestead_21, homestead_21_contenders, homestead_21_corr, homestead_21_contenders_corr = add_more_info(homestead_21, homestead_21_laps)\nlasvegas1_21, lasvegas1_21_contenders, lasvegas1_21_corr, lasvegas1_21_contenders_corr = add_more_info(lasvegas1_21, lasvegas1_21_laps)\nphoenix1_21, phoenix1_21_contenders, phoenix1_21_corr, phoenix1_21_contenders_corr = add_more_info(phoenix1_21, phoenix1_21_laps)\natlanta1_21, atlanta1_21_contenders, atlanta1_21_corr, atlanta1_21_contenders_corr = add_more_info(atlanta1_21, atlanta1_21_laps)\nbristoldirt_21, bristoldirt_21_contenders, bristoldirt_21_corr, bristoldirt_21_contenders_corr = add_more_info(bristoldirt_21, bristoldirt_21_laps)\nmartinsville1_21, martinsville1_21_contenders, martinsville1_21_corr, martinsville1_21_contenders_corr = add_more_info(martinsville1_21, martinsville1_21_laps)\nrichmond1_21, richmond1_21_contenders, richmond1_21_corr, richmond1_21_contenders_corr = add_more_info(richmond1_21, richmond1_21_laps)\ntalladega1_21, talladega1_21_contenders, talladega1_21_corr, talladega1_21_contenders_corr = add_more_info(talladega1_21, talladega1_21_laps)\nkansas1_21, kansas1_21_contenders, kansas1_21_corr, kansas1_21_contenders_corr = add_more_info(kansas1_21, kansas1_21_laps)\ndarlington1_21, darlington1_21_contenders, darlington1_21_corr, darlington1_21_contenders_corr = add_more_info(darlington1_21, darlington1_21_laps)\ndover_21, dover_21_contenders, dover_21_corr, dover_21_contenders_corr = add_more_info(dover_21, dover_21_laps)\ncota_21, cota_21_contenders, cota_21_corr, cota_21_contenders_corr = add_more_info(cota_21, cota_21_laps)\ncharlotte_21, charlotte_21_contenders, charlotte_21_corr, charlotte_21_contenders_corr = add_more_info(charlotte_21, charlotte_21_laps)\nsonoma_21, sonoma_21_contenders, sonoma_21_corr, sonoma_21_contenders_corr = add_more_info(sonoma_21, sonoma_21_laps)\nnashville_21, nashville_21_contenders, nashville_21_corr, nashville_21_contenders_corr = add_more_info(nashville_21, nashville_21_laps)\npocono1_21, pocono1_21_contenders, pocono1_21_corr, pocono1_21_contenders_corr = add_more_info(pocono1_21, pocono1_21_laps)\npocono2_21, pocono2_21_contenders, pocono2_21_corr, pocono2_21_contenders_corr = add_more_info(pocono2_21, pocono2_21_laps)\nroadamerica_21, roadamerica_21_contenders, roadamerica_21_corr, roadamerica_21_contenders_corr = add_more_info(roadamerica_21, roadamerica_21_laps)\natlanta2_21, atlanta2_21_contenders, atlanta2_21_corr, atlanta2_21_contenders_corr = add_more_info(atlanta2_21, atlanta2_21_laps)\nloudon_21, loudon_21_contenders, loudon_21_corr, loudon_21_contenders_corr = add_more_info(loudon_21, loudon_21_laps)\nwatkinsglen_21, watkinsglen_21_contenders, watkinsglen_21_corr, watkinsglen_21_contenders_corr = add_more_info(watkinsglen_21, watkinsglen_21_laps)\nindianapolisrc_21, indianapolisrc_21_contenders, indianapolisrc_21_corr, indianapolisrc_21_contenders_corr = add_more_info(indianapolisrc_21, indianapolisrc_21_laps)\nmichigan_21, michigan_21_contenders, michigan_21_corr, michigan_21_contenders_corr = add_more_info(michigan_21, michigan_21_laps)\ndaytona2_21, daytona2_21_contenders, daytona2_21_corr, daytona2_21_contenders_corr = add_more_info(daytona2_21, daytona2_21_laps)\ndarlington2_21, darlington2_21_contenders, darlington2_21_corr, darlington2_21_contenders_corr = add_more_info(darlington2_21, darlington2_21_laps)\nrichmond2_21, richmond2_21_contenders, richmond2_21_corr, richmond2_21_contenders_corr = add_more_info(richmond2_21, richmond2_21_laps)\nbristol_21, bristol_21_contenders, bristol_21_corr, bristol_21_contenders_corr = add_more_info(bristol_21, bristol_21_laps)\nlasvegas2_21, lasvegas2_21_contenders, lasvegas2_21_corr, lasvegas2_21_contenders_corr = add_more_info(lasvegas2_21, lasvegas2_21_laps)\ntalladega2_21, talladega2_21_contenders, talladega2_21_corr, talladega2_21_contenders_corr = add_more_info(talladega2_21, talladega2_21_laps)\ncharlotterc_21, charlotterc_21_contenders, charlotterc_21_corr, charlotterc_21_contenders_corr = add_more_info(charlotterc_21, charlotterc_21_laps)\ntexas_21, texas_21_contenders, texas_21_corr, texas_21_contenders_corr = add_more_info(texas_21, texas_21_laps)\nkansas2_21, kansas2_21_contenders, kansas2_21_corr, kansas2_21_contenders_corr = add_more_info(kansas2_21, kansas2_21_laps)\nmartinsville2_21, martinsville2_21_contenders, martinsville2_21_corr, martinsville2_21_contenders_corr = add_more_info(martinsville2_21, martinsville2_21_laps)\nphoenix2_21, phoenix2_21_contenders, phoenix2_21_corr, phoenix2_21_contenders_corr = add_more_info(phoenix2_21, phoenix2_21_laps)\n\n\n#2022\ndaytona1_22, daytona1_22_contenders, daytona1_22_corr, daytona1_22_contenders_corr = add_more_info(daytona1_22, daytona1_22_laps)\nautoclub_22, autoclub_22_contenders, autoclub_22_corr, autoclub_22_contenders_corr = add_more_info(autoclub_22, autoclub_22_laps)\nlasvegas1_22, lasvegas1_22_contenders, lasvegas1_22_corr, lasvegas1_22_contenders_corr = add_more_info(lasvegas1_22, lasvegas1_22_laps)\nphoenix1_22, phoenix1_22_contenders, phoenix1_22_corr, phoenix1_22_contenders_corr = add_more_info(phoenix1_22, phoenix1_22_laps)\natlanta1_22, atlanta1_22_contenders, atlanta1_22_corr, atlanta1_22_contenders_corr = add_more_info(atlanta1_22, atlanta1_22_laps)\ncota_22, cota_22_contenders, cota_22_corr, cota_22_contenders_corr = add_more_info(cota_22, cota_22_laps)\nrichmond1_22, richmond1_22_contenders, richmond1_22_corr, richmond1_22_contenders_corr = add_more_info(richmond1_22, richmond1_22_laps)\nmartinsville1_22, martinsville1_22_contenders, martinsville1_22_corr, martinsville1_22_contenders_corr = add_more_info(martinsville1_22, martinsville1_22_laps)\nbristoldirt_22, bristoldirt_22_contenders, bristoldirt_22_corr, bristoldirt_22_contenders_corr = add_more_info(bristoldirt_22, bristoldirt_22_laps)\ntalladega1_22, talladega1_22_contenders, talladega1_22_corr, talladega1_22_contenders_corr = add_more_info(talladega1_22, talladega1_22_laps)\ndover_22, dover_22_contenders, dover_22_corr, dover_22_contenders_corr = add_more_info(dover_22, dover_22_laps)\ndarlington1_22, darlington1_22_contenders, darlington1_22_corr, darlington1_22_contenders_corr = add_more_info(darlington1_22, darlington1_22_laps)\nkansas1_22, kansas1_22_contenders, kansas1_22_corr, kansas1_22_contenders_corr = add_more_info(kansas1_22, kansas1_22_laps)\n",
"_____no_output_____"
],
[
"#dover_22",
"_____no_output_____"
],
[
"#Bristol[Bristol['Driver']== 'Shane Golobic']",
"_____no_output_____"
]
],
[
[
"Create the \"Same Races\" dataframes for 2021 and 2022. The \"Same Races\" are the races that we have available that took place in both 2021 and 2022. ",
"_____no_output_____"
]
],
[
[
"#Joining 2021 and 2022 races that match\nsameraces_21 = pd.DataFrame().append([daytona1_21, lasvegas1_21, phoenix1_21, atlanta1_21, richmond1_21, \\\n martinsville1_21, bristoldirt_21, talladega1_21, dover_21, darlington1_21, kansas1_21])\n\nsameraces_22 = pd.DataFrame().append([daytona1_22, lasvegas1_22, phoenix1_22, atlanta1_22, richmond1_22, \\\n martinsville1_22, bristoldirt_22, talladega1_22, dover_22, darlington1_22, kansas1_22])\n",
"_____no_output_____"
]
],
[
[
"Create the \"All Races\" dataframes. These dataframes include all of the race data available for 2021 and 2022. There's a lot more race data for 2021 than for 2022. For some analysis we can use all of the data. For other analysis we'll want to compare only races that are the same for both years.\n",
"_____no_output_____"
]
],
[
[
"# Creating dataframes for all of the races in 2021 and 2022, respectively\nallraces_21 = pd.DataFrame().append([daytona1_21, daytonarc_21, homestead_21, lasvegas1_21, phoenix1_21,\n atlanta1_21, bristoldirt_21, martinsville1_21, richmond1_21, talladega1_21, kansas1_21, darlington1_21,\n dover_21, cota_21, charlotte_21, sonoma_21, nashville_21, pocono1_21, pocono2_21, roadamerica_21,\n atlanta2_21, loudon_21, watkinsglen_21, indianapolisrc_21, michigan_21, daytona2_21,\n darlington2_21, richmond2_21, bristol_21, lasvegas2_21, talladega2_21, charlotterc_21, texas_21,\n kansas2_21, martinsville2_21, phoenix2_21])\n\nallraces_22 = pd.DataFrame().append([daytona1_22, autoclub_22, lasvegas1_22, phoenix1_22, atlanta1_22,\n cota_22, richmond1_22, martinsville1_22, bristoldirt_22, talladega1_22, dover_22, darlington1_22,\n kansas1_22])",
"_____no_output_____"
],
[
"#races22[races22['Driver']== 'Shane Golobic']",
"_____no_output_____"
],
[
"sameraces_21_22 = pd.concat([sameraces_21, sameraces_22], ignore_index=True)",
"_____no_output_____"
]
],
[
[
"Sending the final dataframes to pickle to use for analysis in other notebooks.",
"_____no_output_____"
]
],
[
[
"sameraces_21.to_pickle(\"/work/Milestone_I/data/Races_Combined/sameraces_21.pkl\")\nsameraces_22.to_pickle(\"/work/Milestone_I/data/Races_Combined/sameraces_22.pkl\")\nsameraces_21_22.to_pickle(\"/work/Milestone_I/data/Races_Combined/sameraces_21_22.pkl\")\nallraces_21.to_pickle(\"/work/Milestone_I/data/Races_Combined/allraces_21.pkl\")\nallraces_22.to_pickle(\"/work/Milestone_I/data/Races_Combined/allraces_22.pkl\")",
"_____no_output_____"
],
[
"sameraces_21_22.shape",
"_____no_output_____"
]
],
[
[
"<a style='text-decoration:none;line-height:16px;display:flex;color:#5B5B62;padding:10px;justify-content:end;' href='https://deepnote.com?utm_source=created-in-deepnote-cell&projectId=9ef4eb23-f38f-47e8-bfb0-51d8616b0dee' target=\"_blank\">\n<img alt='Created in deepnote.com' style='display:inline;max-height:16px;margin:0px;margin-right:7.5px;' src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iODBweCIgaGVpZ2h0PSI4MHB4IiB2aWV3Qm94PSIwIDAgODAgODAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDU0LjEgKDc2NDkwKSAtIGh0dHBzOi8vc2tldGNoYXBwLmNvbSAtLT4KICAgIDx0aXRsZT5Hcm91cCAzPC90aXRsZT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGcgaWQ9IkxhbmRpbmciIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJBcnRib2FyZCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEyMzUuMDAwMDAwLCAtNzkuMDAwMDAwKSI+CiAgICAgICAgICAgIDxnIGlkPSJHcm91cC0zIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMjM1LjAwMDAwMCwgNzkuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICA8cG9seWdvbiBpZD0iUGF0aC0yMCIgZmlsbD0iIzAyNjVCNCIgcG9pbnRzPSIyLjM3NjIzNzYyIDgwIDM4LjA0NzY2NjcgODAgNTcuODIxNzgyMiA3My44MDU3NTkyIDU3LjgyMTc4MjIgMzIuNzU5MjczOSAzOS4xNDAyMjc4IDMxLjY4MzE2ODMiPjwvcG9seWdvbj4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0zNS4wMDc3MTgsODAgQzQyLjkwNjIwMDcsNzYuNDU0OTM1OCA0Ny41NjQ5MTY3LDcxLjU0MjI2NzEgNDguOTgzODY2LDY1LjI2MTk5MzkgQzUxLjExMjI4OTksNTUuODQxNTg0MiA0MS42NzcxNzk1LDQ5LjIxMjIyODQgMjUuNjIzOTg0Niw0OS4yMTIyMjg0IEMyNS40ODQ5Mjg5LDQ5LjEyNjg0NDggMjkuODI2MTI5Niw0My4yODM4MjQ4IDM4LjY0NzU4NjksMzEuNjgzMTY4MyBMNzIuODcxMjg3MSwzMi41NTQ0MjUgTDY1LjI4MDk3Myw2Ny42NzYzNDIxIEw1MS4xMTIyODk5LDc3LjM3NjE0NCBMMzUuMDA3NzE4LDgwIFoiIGlkPSJQYXRoLTIyIiBmaWxsPSIjMDAyODY4Ij48L3BhdGg+CiAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMCwzNy43MzA0NDA1IEwyNy4xMTQ1MzcsMC4yNTcxMTE0MzYgQzYyLjM3MTUxMjMsLTEuOTkwNzE3MDEgODAsMTAuNTAwMzkyNyA4MCwzNy43MzA0NDA1IEM4MCw2NC45NjA0ODgyIDY0Ljc3NjUwMzgsNzkuMDUwMzQxNCAzNC4zMjk1MTEzLDgwIEM0Ny4wNTUzNDg5LDc3LjU2NzA4MDggNTMuNDE4MjY3Nyw3MC4zMTM2MTAzIDUzLjQxODI2NzcsNTguMjM5NTg4NSBDNTMuNDE4MjY3Nyw0MC4xMjg1NTU3IDM2LjMwMzk1NDQsMzcuNzMwNDQwNSAyNS4yMjc0MTcsMzcuNzMwNDQwNSBDMTcuODQzMDU4NiwzNy43MzA0NDA1IDkuNDMzOTE5NjYsMzcuNzMwNDQwNSAwLDM3LjczMDQ0MDUgWiIgaWQ9IlBhdGgtMTkiIGZpbGw9IiMzNzkzRUYiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+' > </img>\nCreated in <span style='font-weight:600;margin-left:4px;'>Deepnote</span></a>",
"_____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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
ecd1508b63d7ddc0d54aa890759e071794c31ce3 | 797,216 | ipynb | Jupyter Notebook | tutorials/W1D1_Why_did_this_happen/W1D1_Tutorial2.ipynb | KordingLab/ENGR344 | 746c04117f5a27ca28c4bdd8ea7cb939c07afea5 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | 1 | 2022-01-26T02:39:55.000Z | 2022-01-26T02:39:55.000Z | tutorials/W1D1_Why_did_this_happen/W1D1_Tutorial2.ipynb | KordingLab/ENGR344 | 746c04117f5a27ca28c4bdd8ea7cb939c07afea5 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | 1 | 2022-01-12T21:14:24.000Z | 2022-01-12T21:14:24.000Z | tutorials/W1D1_Why_did_this_happen/W1D1_Tutorial2.ipynb | KordingLab/ENGR344 | 746c04117f5a27ca28c4bdd8ea7cb939c07afea5 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | 2 | 2022-01-14T00:26:12.000Z | 2022-01-24T15:35:36.000Z | 257.415563 | 146,038 | 0.89861 | [
[
[
"<a href=\"https://colab.research.google.com/github/KordingLab/ENGR344/blob/master/tutorials/W1D1_Why_did_this_happen/W1D1_Tutorial2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Tutorial 2: Correlations\n**Week 1: Why Did This Happen?**\n\n**Originally By Neuromatch Academy**\n\n**Content creators**: Ari Benjamin, Tony Liu, Konrad Kording\n\n**Content reviewers**: Mike X Cohen, Madineh Sarvestani, Ella Batty, Yoni Friedman, Michael Waskom\n\n**Content modifiers**: Ilenna Jones\n\n**Modified Content reviewer**: Keervani Kandala",
"_____no_output_____"
],
[
"**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**\n\n<p align='center'><img src='https://github.com/NeuromatchAcademy/widgets/blob/master/sponsors.png?raw=True'/></p>",
"_____no_output_____"
],
[
"---\n# Tutorial objectives\n\n*Estimated timing of tutorial: 45 min*\n\nThis is tutorial 2 on our week of examining causality. Below is the high level outline of what we'll cover today, with the sections we will focus on in this tutorial in bold:\n\n1. Master definitions of causality\n2. Understand that estimating causality is possible\n3. Learn 4 different methods and understand when they fail\n 1. Perturbations\n 2. **Correlations**\n 3. Simultaneous fitting/regression \n\n### Tutorial 2 objectives\n\nIn tutorial 1, we implemented and explored the dynamic system that we will be working with throughout all of the tutorials today. We also learned about the \"gold standard\" of measuring causal effects through random perturbations. As random perturbations are often not possible, we will now turn to alternative methods to attempt to measure causality. We will:\n\n- Learn how to estimate causal effects from observations only assuming **correlations approximate causation**\n- Show that this only works when the network is small\n- See the effect of confounding\n\n### Tutorial 2 setting\n\nOften, we can't interfere arbitrarily in the world but can only observe it. For example, we can not currently force neural activites or brain areas to be on or off. We just have the ability to observe. Maybe we can get the correlation between two variables -- is that good enough? The question we ask in this tutorial is **when is correlation a \"good enough\" substitute for causation?**\n\nThe answer is not \"never\", actually, but \"sometimes\", and we can understand the conditions under which it is.\n\n",
"_____no_output_____"
]
],
[
[
"# @title Tutorial slides\n\n# @markdown These are the slides for the videos in all tutorials today\nfrom IPython.display import IFrame\nIFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/gp4m9/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)",
"_____no_output_____"
]
],
[
[
"---\n# Setup",
"_____no_output_____"
]
],
[
[
"# Imports\n\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"#@title Figure Settings\nimport ipywidgets as widgets # interactive display\n%config InlineBackend.figure_format = 'retina'\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle\")",
"_____no_output_____"
],
[
"#@title Plotting Functions\n\ndef see_neurons(A, ax):\n \"\"\"\n Visualizes the connectivity matrix.\n\n Args:\n A (np.ndarray): the connectivity matrix of shape (n_neurons, n_neurons)\n ax (plt.axis): the matplotlib axis to display on\n\n Returns:\n Nothing, but visualizes A.\n \"\"\"\n A = A.T # make up for opposite connectivity\n n = len(A)\n ax.set_aspect('equal')\n thetas = np.linspace(0, np.pi * 2, n, endpoint=False)\n x, y = np.cos(thetas), np.sin(thetas),\n ax.scatter(x, y, c='k', s=150)\n A = A / A.max()\n for i in range(n):\n for j in range(n):\n if A[i, j] > 0:\n ax.arrow(x[i], y[i], x[j] - x[i], y[j] - y[i], color='k', alpha=A[i, j], head_width=.15,\n width = A[i,j] / 25, shape='right', length_includes_head=True)\n ax.axis('off')\n\ndef plot_estimation_quality_vs_n_neurons(number_of_neurons):\n \"\"\"\n A wrapper function that calculates correlation between true and estimated connectivity\n matrices for each number of neurons and plots\n\n Args:\n number_of_neurons (list): list of different number of neurons for modeling system\n corr_func (function): Function for computing correlation\n \"\"\"\n corr_data = np.zeros((n_trials, len(number_of_neurons)))\n for trial in range(n_trials):\n print(\"simulating trial {} of {}\".format(trial + 1, n_trials))\n for j, size in enumerate(number_of_neurons):\n corr = get_sys_corr(size, timesteps, trial)\n corr_data[trial, j] = corr\n\n corr_mean = corr_data.mean(axis=0)\n corr_std = corr_data.std(axis=0)\n\n plt.plot(number_of_neurons, corr_mean)\n plt.fill_between(number_of_neurons,\n corr_mean - corr_std,\n corr_mean + corr_std,\n alpha=.2)\n plt.xlabel(\"Number of neurons\")\n plt.ylabel(\"Correlation\")\n plt.title(\"Similarity between A and R as a function of network size\")\n plt.show()\n\n\ndef plot_connectivity_matrix(A, ax=None):\n \"\"\"Plot the (weighted) connectivity matrix A as a heatmap\n\n Args:\n A (ndarray): connectivity matrix (n_neurons by n_neurons)\n ax: axis on which to display connectivity matrix\n \"\"\"\n if ax is None:\n ax = plt.gca()\n lim = np.abs(A).max()\n im = ax.imshow(A, vmin=-lim, vmax=lim, cmap=\"coolwarm\")\n ax.tick_params(labelsize=10)\n ax.xaxis.label.set_size(15)\n ax.yaxis.label.set_size(15)\n cbar = ax.figure.colorbar(im, ax=ax, ticks=[0], shrink=.7)\n cbar.ax.set_ylabel(\"Connectivity Strength\", rotation=90,\n labelpad= 20, va=\"bottom\")\n ax.set(xlabel=\"Connectivity from\", ylabel=\"Connectivity to\")\n\n\ndef plot_true_vs_estimated_connectivity(estimated_connectivity, true_connectivity, selected_neuron=None):\n \"\"\"Visualize true vs estimated connectivity matrices\n\n Args:\n estimated_connectivity (ndarray): estimated connectivity (n_neurons by n_neurons)\n true_connectivity (ndarray): ground-truth connectivity (n_neurons by n_neurons)\n selected_neuron (int or None): None if plotting all connectivity, otherwise connectivity\n from selected_neuron will be shown\n\n \"\"\"\n fig, axs = plt.subplots(1, 2, figsize=(10, 5))\n\n if selected_neuron is not None:\n plot_connectivity_matrix(np.expand_dims(estimated_connectivity, axis=1), ax=axs[0])\n plot_connectivity_matrix(true_connectivity[:, [selected_neuron]], ax=axs[1])\n axs[0].set_xticks([0])\n axs[1].set_xticks([0])\n axs[0].set_xticklabels([selected_neuron])\n axs[1].set_xticklabels([selected_neuron])\n else:\n plot_connectivity_matrix(estimated_connectivity, ax=axs[0])\n plot_connectivity_matrix(true_connectivity, ax=axs[1])\n\n axs[1].set(title=\"True connectivity\")\n axs[0].set(title=\"Estimated connectivity\")",
"_____no_output_____"
],
[
"# @title Helper Functions\n\ndef sigmoid(x):\n \"\"\"\n Compute sigmoid nonlinearity element-wise on x.\n\n Args:\n x (np.ndarray): the numpy data array we want to transform\n Returns\n (np.ndarray): x with sigmoid nonlinearity applied\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\n\ndef create_connectivity(n_neurons, random_state=42, p=0.9):\n \"\"\"\n Generate our nxn causal connectivity matrix.\n\n Args:\n n_neurons (int): the number of neurons in our system.\n random_state (int): random seed for reproducibility\n\n Returns:\n A (np.ndarray): our 0.1 sparse connectivity matrix\n \"\"\"\n np.random.seed(random_state)\n A_0 = np.random.choice([0, 1], size=(n_neurons, n_neurons), p=[p, 1 - p])\n\n # set the timescale of the dynamical system to about 100 steps\n _, s_vals, _ = np.linalg.svd(A_0)\n A = A_0 / (1.01 * s_vals[0])\n\n # _, s_val_test, _ = np.linalg.svd(A)\n # assert s_val_test[0] < 1, \"largest singular value >= 1\"\n\n return A\n\n\ndef simulate_neurons(A, timesteps, random_state=42):\n \"\"\"\n Simulates a dynamical system for the specified number of neurons and timesteps.\n\n Args:\n A (np.array): the connectivity matrix\n timesteps (int): the number of timesteps to simulate our system.\n random_state (int): random seed for reproducibility\n\n Returns:\n - X has shape (n_neurons, timeteps).\n \"\"\"\n np.random.seed(random_state)\n\n n_neurons = len(A)\n X = np.zeros((n_neurons, timesteps))\n\n for t in range(timesteps - 1):\n # solution\n epsilon = np.random.multivariate_normal(np.zeros(n_neurons), np.eye(n_neurons))\n X[:, t + 1] = sigmoid(A.dot(X[:, t]) + epsilon)\n\n assert epsilon.shape == (n_neurons,)\n return X\n\n\ndef get_sys_corr(n_neurons, timesteps, random_state=42, neuron_idx=None):\n \"\"\"\n A wrapper function for our correlation calculations between A and R.\n\n Args:\n n_neurons (int): the number of neurons in our system.\n timesteps (int): the number of timesteps to simulate our system.\n random_state (int): seed for reproducibility\n neuron_idx (int): optionally provide a neuron idx to slice out\n\n Returns:\n A single float correlation value representing the similarity between A and R\n \"\"\"\n\n A = create_connectivity(n_neurons, random_state)\n X = simulate_neurons(A, timesteps)\n\n R = correlation_for_all_neurons(X)\n\n return np.corrcoef(A.flatten(), R.flatten())[0, 1]",
"_____no_output_____"
]
],
[
[
"The helper functions defined above are:\n- `sigmoid`: computes sigmoid nonlinearity element-wise on input, from Tutorial 1\n- `create_connectivity`: generates nxn causal connectivity matrix., from Tutorial 1\n- `simulate_neurons`: simulates a dynamical system for the specified number of neurons and timesteps, from Tutorial 1\n- `get_sys_corr`: a wrapper function for correlation calculations between A and R.\n",
"_____no_output_____"
],
[
"---\n# Section 1: Small systems\n\n",
"_____no_output_____"
]
],
[
[
"# @title Video 1: Correlation vs causation\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=\"BV1Ak4y1m7kk\", width=854, height=480, fs=1)\n print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=\"vjBO-S7KNPI\", width=854, height=480, fs=1, rel=0)\n print('Video available at https://youtube.com/watch?v=' + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"## Coding Exercise 1: Try to approximate causation with correlation\n\nIn the last tutorial we calculated causation by correlating the perturbation (we were setting the activity of A) with the downstream activitity. Would that also work if we do not perturb? Correlation may look like causation. Let's attempt to recover the true connectivity matrix (A) just by correlating the neural state at each timestep with the previous state: $C=\\vec{x_t}{\\vec{x_{t+1}}^T}$. \n\nComplete this function to estimate the connectivity matrix of a single neuron by calculating the correlation coefficients with every other neuron at the next timestep. That is, please correlate two vectors: 1) the activity of a selected neuron at time $t$ 2) The activity of all other neurons at time t+1.",
"_____no_output_____"
]
],
[
[
"def compute_connectivity_from_single_neuron(X, selected_neuron):\n \"\"\"\n Computes the connectivity matrix from a single neuron neurons using correlations\n\n Args:\n X (ndarray): the matrix of activities\n selected_neuron (int): the index of the selected neuron\n\n Returns:\n estimated_connectivity (ndarray): estimated connectivity for the selected neuron, of shape (n_neurons,)\n \"\"\"\n\n # Extract the current activity of selected_neuron, t\n current_activity = X[selected_neuron, :-1]\n\n # Extract the observed outcomes of all the neurons\n next_activity = X[:, 1:]\n\n # Initialize estimated connectivity matrix\n estimated_connectivity = np.zeros(n_neurons)\n\n # Loop through all neurons\n for neuron_idx in range(n_neurons):\n\n # Get the activity of neuron_idx\n this_output_activity = next_activity[neuron_idx]\n\n ########################################################################\n ## TODO: Estimate the neural correlations between\n ## this_output_activity and current_activity\n ## ------------------- ----------------\n ##\n ## Note that np.corrcoef returns the full correlation matrix; we want the\n ## top right corner, which we have already provided.\n ## FIll out function and remove\n raise NotImplementedError('Compute neural correlations')\n ########################################################################\n # Compute correlation\n correlation = np.corrcoef(...)[0, 1]\n\n # Store this neuron's correlation\n estimated_connectivity[neuron_idx] = correlation\n\n return estimated_connectivity\n\n\n# Simulate a 6 neuron system for 5000 timesteps again.\nn_neurons = 6\ntimesteps = 5000\nselected_neuron = 1\n\n# Invoke a helper function that generates our nxn causal connectivity matrix\nA = create_connectivity(n_neurons)\n\n# Invoke a helper function that simulates the neural activity\nX = simulate_neurons(A, timesteps)\n\n# Estimate connectivity\nestimated_connectivity = compute_connectivity_from_single_neuron(X, selected_neuron)\n\n# Visualize\nplot_true_vs_estimated_connectivity(estimated_connectivity, A, selected_neuron)",
"_____no_output_____"
]
],
[
[
"[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D5_NetworkCausality/solutions/W3D5_Tutorial2_Solution_c0d0fba7.py)\n\n*Example output:*\n\n<img alt='Solution hint' align='left' width=972.0 height=683.0 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W3D5_NetworkCausality/static/W3D5_Tutorial2_Solution_c0d0fba7_0.png>\n\n",
"_____no_output_____"
],
[
"Hopefully you saw that it pretty much worked - correlation (estimated connectivity) was quite similar to causation (true connectivity). We wrote a function that does what you just did but in matrix form, so it's a little faster. It also does all neurons at the same time (helper function `correlation_for_all_neurons`).\n",
"_____no_output_____"
]
],
[
[
"# @markdown Execute this cell get helper function `correlation_for_all_neurons`\n\ndef correlation_for_all_neurons(X):\n \"\"\"Computes the connectivity matrix for the all neurons using correlations\n\n Args:\n X: the matrix of activities\n\n Returns:\n estimated_connectivity (np.ndarray): estimated connectivity for the selected neuron, of shape (n_neurons,)\n \"\"\"\n n_neurons = len(X)\n S = np.concatenate([X[:, 1:], X[:, :-1]], axis=0)\n R = np.corrcoef(S)[:n_neurons, n_neurons:]\n return R",
"_____no_output_____"
],
[
"# @markdown Execute this cell to visualize full estimated vs true connectivity\n\nR = correlation_for_all_neurons(X)\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 5))\nsee_neurons(A, axs[0])\nplot_connectivity_matrix(A, ax=axs[1])\nplt.suptitle(\"True connectivity matrix A\")\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 5))\nsee_neurons(R, axs[0])\nplot_connectivity_matrix(R, ax=axs[1])\nplt.suptitle(\"Estimated connectivity matrix R\");",
"_____no_output_____"
]
],
[
[
"We again got that the (delay 1) correlation is very similar to causation. Let's quantify how similar they are. \n\nWe'll calculate the correlation coefficient between the true connectivity and the actual connectivity;",
"_____no_output_____"
]
],
[
[
"print(\"Correlation matrix of A and R:\", np.corrcoef(A.flatten(), R.flatten())[0, 1])",
"Correlation matrix of A and R: 0.9596667994046594\n"
]
],
[
[
"It *appears* in our system that correlation captures causality.",
"_____no_output_____"
]
],
[
[
"# @title Video 2: Correlation ~ causation for small systems\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=\"BV1XZ4y1u7FR\", width=854, height=480, fs=1)\n print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=\"eWLOnTUe9SM\", width=854, height=480, fs=1, rel=0)\n print('Video available at https://youtube.com/watch?v=' + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"**Video correction**: the connectivity graph plots and associated explanations in this and other videos show the wrong direction of connectivity (the arrows should be pointing the opposite direction). This has been fixed in the figures above.",
"_____no_output_____"
],
[
"---\n# Section 2: Large systems\n\n*Estimated timing to here from start of tutorial: 15 min*\n\nAs our system becomes more complex however, correlation fails to capture causality.",
"_____no_output_____"
],
[
"## Section 2.1: Failure of correlation in complex systems\n\nLet's jump to a much bigger system. Instead of 6 neurons, we will now use 100 neurons. How does the estimation quality of the connectivity matrix change? ",
"_____no_output_____"
]
],
[
[
"# @markdown Execute this cell to simulate large system, estimate connectivity matrix with correlation and return estimation quality\n\n# Simulate a 100 neuron system for 5000 timesteps.\nn_neurons = 100\ntimesteps = 5000\nrandom_state = 42\n\nA = create_connectivity(n_neurons, random_state)\nX = simulate_neurons(A, timesteps)\nR = correlation_for_all_neurons(X)\n\nprint(\"Correlation matrix of A and R:\", np.corrcoef(A.flatten(), R.flatten())[0, 1])\n\nfig, axs = plt.subplots(1, 2, figsize=(16, 8))\nplot_connectivity_matrix(A, ax=axs[0])\naxs[0].set_title(\"True connectivity matrix A\")\nplot_connectivity_matrix(R, ax=axs[1])\naxs[1].set_title(\"Estimated connectivity matrix R\");",
"Correlation matrix of A and R: 0.3629329824177816\n"
]
],
[
[
"What we see here is a phenomenon called confounding that we will talk about extensively in the next part of the tutorial. The correlation between two neurons is not only due to the influence of one neuron on another, but also due to other neurons that affect both.",
"_____no_output_____"
]
],
[
[
"# @title Video 3: Correlation vs causation in large systems\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=\"BV1uC4y1b76C\", width=854, height=480, fs=1)\n print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=\"U4sV-7g8T08\", width=854, height=480, fs=1, rel=0)\n print('Video available at https://youtube.com/watch?v=' + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"## Section 2.2: Correlation as a function of network size\n\n",
"_____no_output_____"
],
[
"### Interactive Demo 2.2.1: Connectivity estimation as a function of number of neurons\n\nInstead of looking at just a few neurons (6) or a lot of neurons (100), as above, we will now systematically vary the number of neurons and plot the resulting changes in correlation coefficient between the true and estimated connectivity matrices. ",
"_____no_output_____"
]
],
[
[
"# @markdown Execute this cell to enable demo\[email protected](n_neurons=(6, 42, 3))\ndef plot_corrs(n_neurons=6):\n fig, axs = plt.subplots(1, 3, figsize=(15, 5))\n timesteps = 2000\n random_state = 42\n A = create_connectivity(n_neurons, random_state)\n X = simulate_neurons(A, timesteps)\n R = correlation_for_all_neurons(X)\n corr = np.corrcoef(A.flatten(), R.flatten())[0, 1]\n plot_connectivity_matrix(A, ax=axs[0])\n plot_connectivity_matrix(R, ax=axs[1])\n axs[0].set_title(\"True connectivity\")\n axs[1].set_title(\"Estimated connectivity\")\n axs[2].text(0, 0.5, \"Correlation : {:.2f}\".format(corr), size=15)\n axs[2].axis('off')",
"_____no_output_____"
]
],
[
[
"Of course there is some variability due to randomness in $A$. Let's average over a few trials and find the relationship.",
"_____no_output_____"
]
],
[
[
"# @markdown Execute this cell to plot connectivity estimation as a function of network size\n\nn_trials = 5\ntimesteps = 1000 # shorter timesteps for faster running time\nnumber_of_neurons = [5, 10, 25, 50, 100]\nplot_estimation_quality_vs_n_neurons(number_of_neurons)",
"simulating trial 1 of 5\nsimulating trial 2 of 5\nsimulating trial 3 of 5\n"
]
],
[
[
"### Interactive Demo 2.2.2: Connectivity estimation as a function of the sparsity of $A$\n\nYou may rightly wonder if correlation only fails for large systems for certain types of $A$. In this interactive demo, you can examine connectivity estimation as a function of the sparsity of $A$. Does connectivity estimation get better or worse with less sparsity? Why do you think this is the case?",
"_____no_output_____"
]
],
[
[
"# @markdown Execute this cell to enable demo\[email protected](sparsity=(0.01, 0.99, .01))\ndef plot_corrs(sparsity=0.9):\n fig, axs = plt.subplots(1, 3, figsize=(15, 5))\n timesteps = 2000\n random_state = 42\n n_neurons = 25\n A = create_connectivity(n_neurons, random_state, sparsity)\n X = simulate_neurons(A, timesteps)\n R = correlation_for_all_neurons(X)\n corr=np.corrcoef(A.flatten(), R.flatten())[0, 1]\n plot_connectivity_matrix(A, ax=axs[0])\n plot_connectivity_matrix(R, ax=axs[1])\n axs[0].set_title(\"True connectivity\")\n axs[1].set_title(\"Estimated connectivity\")\n axs[2].text(0, 0.5, \"Correlation : {:.2f}\".format(corr), size=15)\n axs[2].axis('off')",
"_____no_output_____"
]
],
[
[
"---\n# Section 3: Reflecting on causality \n\n*Estimated timing to here from start of tutorial: 34 min*",
"_____no_output_____"
],
[
" ## Think! 3: Reflecting on causality \n\nPlease discuss the following questions within groups for around 10 minutes.\n\n* Think of a research paper you have recently read. Did it use previous causal knowledge (e.g. a mechanism), or ask a causal question? Try phrasing that causal relationship in the language of an intervention. (\"*If I were to force $A$ to be $A'$, $B$ would...*\")\n* What methods for interventions exist in your field of interest?\n* Think about these common \"filler\" words. Do they imply a causal relationship, in its interventional definition? (*regulates, mediates, generates, modulates, shapes, underlies, produces, encodes, induces, enables, ensures, supports, promotes, determines*)\n* Think of a big system you find interesting. Maybe the students in a class. The molecules in a cell, the neurons in a circuit, the cells in an organ. Try to conceptualize how the variables in this system relate to one another. What are the causal questions?\n\n\n\n",
"_____no_output_____"
],
[
"---\n# Summary\n\n*Estimated timing of tutorial: 45 min*",
"_____no_output_____"
]
],
[
[
"# @title Video 4: Summary\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=\"BV1KK4y1x74w\", width=854, height=480, fs=1)\n print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=\"hRyAN3yak_U\", width=854, height=480, fs=1, rel=0)\n print('Video available at https://youtube.com/watch?v=' + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)",
"_____no_output_____"
]
],
[
[
"Now for the takeaway. We know that for large systems correlation ≠ causation. But what about when we coarsely sample the large system? Do we get better at estimating the *effective* causal interaction between groups (=average of weights) from the correlation between the groups?\n\nFrom our simulation above, the answer appears to be no: as the number of neurons per group increases, we don't see any significant increase in our ability to estimate the causal interaction between groups.\n\nIf you have time after completing all tutorials and are interested, please see Bonus Section 1 below for a brief discussion of correlation as a similarity metric and Bonus Section 2 to learn about causality and correlation in low resolution systems.",
"_____no_output_____"
],
[
"---\n# Bonus\n\n",
"_____no_output_____"
],
[
"---\n## Bonus Section 1: Correlation as similarity metric\n\nWe'd like to note here that though we make use of Pearson correlation coefficients throughout all of our tutorials to measure similarity between our estimated connectivity matrix $R$ and the ground truth connectivity $A$, this is not strictly correct usage of Pearson correlations as elements of $A$ are not normally distributed (they are in fact binary).\n\nWe use Pearson correlations as they are quick and easy to compute within the Numpy framework and provide qualitatively similar results to other correlation metrics. Other ways to compute similarities:\n- [Spearman rank correlations](https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient), which does not require normally distributed data\n- dichotomizing our estimated matrix $R$ by the median and then running concordance analysis, such as computing [Cohen's kappa](https://en.wikipedia.org/wiki/Cohen%27s_kappa)\n\nAnother thing to consider: all we want is some measure of the similarity between $A$ and $R$. Element-wise comparisons are one way to do this, but are there other ways you can think of? What about matrix similarities?\n\n",
"_____no_output_____"
],
[
"---\n## Bonus Section 2: Low resolution systems\n\nA common situation in neuroscience is that you observe the *average* activity of large groups of neurons. (Think fMRI, EEG, LFP, etc.)\nWe're going to simulate this effect, and ask if correlations work to recover the average causal effect of groups of neurons or areas.\n\n**Note on the quality of the analogy**: This is not intended as a perfect analogy of the brain or fMRI. Instead, we want to ask: *in a big system in which correlations fail to estimate causality, can you at least recover average connectivity between groups?*\n\n**Some brainy differences to remember**:\nWe are assuming that the connectivity is random. In real brains, the neurons that are averaged have correlated input and output connectivities. This will improve the correspondence between correlations and causality for the average effect because the system has a lower true dimensionality. However, in real brains the system is also order of magnitudes larger than what we examine here, and the experimenter never has the fully-observed system.\n\n## Simulate a large system\n\nExecute the next cell to simulate a large system of 256 neurons for 10000 timesteps - it will take a bit of time to finish so move on as it runs.\n",
"_____no_output_____"
]
],
[
[
"# @markdown Execute this cell to simulate a large system\n\nn_neurons = 256\ntimesteps = 10000\nrandom_state = 42\n\nA = create_connectivity(n_neurons, random_state)\nX = simulate_neurons(A, timesteps)",
"_____no_output_____"
]
],
[
[
"### Bonus Section 1.1: Coarsely sample the system\n\nWe don't observe this system. Instead, we observe the average activity of groups.\n",
"_____no_output_____"
],
[
"#### Bonus Coding Exercise 1.1: Compute average activity across groups and compare resulting connectivity to the truth\n \nLet's get a new matrix `coarse_X` that has 16 groups, each reflecting the average activity of 16 neurons (since there are 256 neurons in total).\n\nWe will then define the true coarse connectivity as the average of the neuronal connection strengths between groups. We'll compute the correlation between our coarsely sampled groups to estimate the connectivity and compare with the true connectivity.",
"_____no_output_____"
]
],
[
[
"def get_coarse_corr(n_groups, X):\n \"\"\"\n A wrapper function for our correlation calculations between coarsely sampled\n A and R.\n\n Args:\n n_groups (int): the number of groups. should divide the number of neurons evenly\n X: the simulated system\n\n Returns:\n A single float correlation value representing the similarity between A and R\n ndarray: estimated connectivity matrix\n ndarray: true connectivity matrix\n \"\"\"\n\n ############################################################################\n ## TODO: Insert your code here to get coarsely sampled X\n # Fill out function then remove\n raise NotImplementedError('Student exercise: please complete get_coarse_corr')\n ############################################################################\n coarse_X = ...\n\n # Make sure coarse_X is the right shape\n assert coarse_X.shape == (n_groups, timesteps)\n\n # Estimate connectivity from coarse system\n R = correlation_for_all_neurons(coarse_X)\n\n # Compute true coarse connectivity\n coarse_A = A.reshape(n_groups, n_neurons // n_groups, n_groups, n_neurons // n_groups).mean(3).mean(1)\n\n # Compute true vs estimated connectivity correlation\n corr = np.corrcoef(coarse_A.flatten(), R.flatten())[0, 1]\n\n return corr, R, coarse_A\n\n\nn_groups = 16\n\n# Call function\ncorr, R, coarse_A = get_coarse_corr(n_groups, X)\n\n# Visualize\nplot_true_vs_estimated_connectivity(R, coarse_A)",
"_____no_output_____"
]
],
[
[
"[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D5_NetworkCausality/solutions/W3D5_Tutorial2_Solution_a032d00b.py)\n\n*Example output:*\n\n<img alt='Solution hint' align='left' width=1398.0 height=604.0 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W3D5_NetworkCausality/static/W3D5_Tutorial2_Solution_a032d00b_0.png>\n\n",
"_____no_output_____"
],
[
"How close is the estimated coarse connectivity matrix to the truth?",
"_____no_output_____"
]
],
[
[
"print(\"Correlation: {}\".format(corr))",
"_____no_output_____"
]
],
[
[
"We will now look at the estimation quality for different levels of coarseness when averaged over 3 trials.",
"_____no_output_____"
]
],
[
[
"#@markdown Execute this cell to visualize plot\n\nn_neurons = 128\ntimesteps = 5000\nn_trials = 3\ngroups = [2 ** i for i in range(2, int(np.log2(n_neurons)))]\n\ncorr_data = np.zeros((n_trials, len(groups)))\n\nfor trial in range(n_trials):\n print(\"Trial {} out of {}\".format(trial, n_trials))\n A = create_connectivity(n_neurons, random_state=trial)\n X = simulate_neurons(A, timesteps, random_state=trial)\n for j, n_groups in enumerate(groups):\n corr_data[trial, j], _, _ = get_coarse_corr(n_groups, X)\n\ncorr_mean = corr_data.mean(axis=0)\ncorr_std = corr_data.std(axis=0)\n\nplt.plot(np.divide(n_neurons, groups), corr_mean)\nplt.fill_between(np.divide(n_neurons, groups),\n corr_mean - corr_std,\n corr_mean + corr_std,\n alpha=.2)\n\nplt.ylim([-0.2, 1])\nplt.xlabel(\"Number of neurons per group ({} total neurons)\".format(n_neurons),\n fontsize=15)\nplt.ylabel(\"Correlation of estimated effective connectivity\")\nplt.title(\"Connectivity estimation performance vs coarseness of sampling\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"We know that for large systems correlation ≠ causation. Here, we have looked at what happens we coarsely sample a large system. Do we get better at estimating the *effective* causal interaction between groups (=average of weights) from the correlation between the groups?\n\nFrom our simulation above, the answer appears to be no: as the number of neurons per group increases, we don't see any significant increase in our ability to estimate the causal interaction between groups.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
ecd151ed2d4b98c41e343f8c8928340daa217a34 | 28,580 | ipynb | Jupyter Notebook | Validation.ipynb | Hegelim/PE-Validation-Fall-20 | f258a7631e126d07a7a7e1056a6f93cb7596fca4 | [
"MIT"
] | null | null | null | Validation.ipynb | Hegelim/PE-Validation-Fall-20 | f258a7631e126d07a7a7e1056a6f93cb7596fca4 | [
"MIT"
] | 1 | 2021-01-27T01:17:07.000Z | 2021-01-27T01:17:07.000Z | Validation.ipynb | Hegelim/PE-Validation-Fall-20 | f258a7631e126d07a7a7e1056a6f93cb7596fca4 | [
"MIT"
] | 1 | 2021-01-19T22:46:22.000Z | 2021-01-19T22:46:22.000Z | 39.584488 | 191 | 0.496606 | [
[
[
"# import necessary modules \n# please run this everytime you open it\nimport pandas as pd \nimport numpy as np \nimport matplotlib as plt \nimport re\nimport os\nfrom krippendorff import alpha",
"_____no_output_____"
]
],
[
[
"## Something to keep in mind!",
"_____no_output_____"
],
[
"**In Specialist csvs, one \"quiz_task_uuid\" can have multiple contributors. To uniquely identify each input, use \"quiz_taskrun_uuid**",
"_____no_output_____"
],
[
"**To construct reliability matrix, use contributor_uuid, quiz_task_uuid, answer_label** ",
"_____no_output_____"
],
[
"## Helper functions",
"_____no_output_____"
]
],
[
[
"# mapping for Triager tasks\ntriager_dic = {\"Quoted Sources\":1,\n \"Arguments\":2,\n \"Assertions\":3, \n \"Needs Fact-Check\":4, \n \"Language\":5, \n \"Reasoning\":6, \n \"Probability\":7, \n \"Evidence\":8}",
"_____no_output_____"
]
],
[
[
"## The dictionary needs to be updated based on newer versions of schema files. ",
"_____no_output_____"
]
],
[
[
"# dic for Specialists tasks\nspecialist_dic = {\"Argument relevance\": {\"mc\": {\"categorical\":[1], \"ordinal\":[2, 3]}, \"tx\":[4]},\n \"Evidence Specialist\": {\"mc\":{\"categorical\":[6, 9], \"ordinal\":[4, 5, 8, 10, 11, 12, 13, 14, 15]}, \"cl\":[1, 2], \"tx\":[3, 7, 16]},\n \"Holistic Evaluation of Article\": {\"mc\":{\"categorical\":[1, 5, 14], \"ordinal\":[7, 8, 11, 12, 13, 17, 18]}, \"cl\":[3, 6, 9, 10, 15], \"tx\":[2, 4, 16, 19]}, \n \"Language Specialist V4\": {\"mc\":{\"categorical\":[], \"ordinal\":[2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15]}, \"cl\":[1, 6], \"tx\":[7, 16]},\n \"Probability Specialist\": {\"mc\": {\"categorical\":[6], \"ordinal\":[1, 2, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15]}, \"cl\":[12], \"tx\":[16]},\n \"Reasoning Specialist\": {\"mc\": {\"categorical\":[4, 5], \"ordinal\":[7, 9, 10, 11]}, \"cl\":[1, 2, 3, 6], \"tx\":[8, 12]},\n \"Quote Source Relevance\": {\"mc\": {\"categorical\":[3, 8], \"ordinal\":[2, 9, 10, 11]}, \"cl\":[1, 4, 5, 6, 7], \"tx\":[12]}}",
"_____no_output_____"
],
[
"# decompose question_label to get the int \ndef decompose_question(question_label):\n # question_label - e.g. \"T1.Q2\"\n # return an int - e.g. 2 \n m = re.search(r'Q\\d+', question_label)\n return int(m.group(0)[1:])",
"_____no_output_____"
],
[
"def get_question_type(topic_name, question_label):\n # topic_name - e.g. \"Argument relevance\"\n # question_label - e.g. 'T1.Q12'\n # return \"mc\"/\"cl\" or None if not found\n question_int = decompose_question(question_label)\n # key - \"mc\"/\"cl\"/\"tx\"\n for key in specialist_dic[topic_name].keys():\n if key == \"mc\":\n mc_mapping = specialist_dic[topic_name][\"mc\"]\n # mc_key = \"categorical\"/\"ordinal\"\n for mc_key in mc_mapping.keys():\n cur_list = mc_mapping[mc_key]\n if question_int in cur_list: \n return key\n elif key == \"cl\":\n cur_list = specialist_dic[topic_name][\"cl\"]\n if question_int in cur_list:\n return key\n elif key == \"tx\":\n cur_list = specialist_dic[topic_name][\"tx\"]\n if question_int in cur_list:\n return key",
"_____no_output_____"
],
[
"# assuming the question_type is \"mc\"\n# return \"ordinal\"/\"categorical\"\ndef get_measurement(topic_name, question_label, mapping):\n # topic_name - e.g. \"Argument relevance\"\n # question_label - e.g. \"T1.Q1\"\n # mapping - e.g. specialist_dic, this might change\n question_int = decompose_question(question_label)\n dic = mapping[topic_name][\"mc\"]\n for key in dic.keys():\n cur_list = dic[key]\n if question_int in cur_list:\n if key == \"categorical\":\n return \"nominal\"\n if key == \"ordinal\":\n return \"ordinal\"",
"_____no_output_____"
],
[
"# check if a certain column contains any duplicate values \n# return true if all values in the column are unique\ndef check_duplicate(df, col):\n # df - any dataframe \n # col - column label \n return df[col].is_unique",
"_____no_output_____"
],
[
"# count how many Nan rows are there in a df \n# Nan rows are rows that have all missing values\ndef count_nan_rows(df):\n return df.shape[0] - df.dropna(axis=0, how='all').shape[0]",
"_____no_output_____"
],
[
"# count how many nan cols are there in a df\n# nan cols are cols where all values are missing \ndef count_nan_cols(df):\n return df.shape[1] - df.dropna(axis=1, how=\"all\").shape[1]",
"_____no_output_____"
],
[
"# only select that value, useful for constructing pivot_table\ndef select(x):\n return list(x)[0]",
"_____no_output_____"
],
[
"# return the unique values sorted in a df's column\ndef unique(df, x):\n # df - dataframe \n # x - the label of the column \n a = sorted(df[x].unique())\n return a",
"_____no_output_____"
],
[
"# convert all strings in the array to int \n# e.g. \"T1.Q1.A5\" -> 5 \ndef to_int(array):\n # array - e.g. 2-d array where some entries are \"T1.Q1.A3\"\n for i in range(array.shape[0]):\n for j in range(array.shape[1]):\n cur = array[i][j]\n # if the current value is a string\n if not pd.isnull(cur):\n try:\n array[i][j] = int(array[i][j][-1])\n except Exception as e:\n print(i, j)\n df = pd.DataFrame(array)\n return array",
"_____no_output_____"
],
[
"# construct a reliability matrix (2d array) from Specialist csv \ndef to_reliability(input_directory, fileName, question_type, question_label):\n # input_directory - e.g. \"Specialists data\"\n # fileName - e.g. \"Covid_SourceRelevancev1-2020-10-04T1838-DataHunt.csv\"\n # question_type - \"mc\"/\"cl\"\n # question_label - e.g. \"Q2\"\n name = os.path.join(input_directory, fileName)\n # read in csv \n df = pd.read_csv(name)\n # select only that question_label \n df = df[df[\"question_label\"] == question_label].copy()\n # slice \n cols = [\"quiz_task_uuid\", \"contributor_uuid\", \"question_label\", \"answer_label\"]\n df = df.reindex(columns=cols)\n if question_type == \"mc\":\n return to_reliability_mc(df)\n elif question_type == \"cl\":\n return to_reliability_cl(df)",
"_____no_output_____"
],
[
"# helper function, construct reliability matrix for mc question type\ndef to_reliability_mc(df):\n # construct a pivot_table \n df = pd.pivot_table(df, values='answer_label', index='contributor_uuid', columns='quiz_task_uuid', aggfunc=select)\n # to numpy array\n array = df.to_numpy()\n # convert string to int \n array = to_int(array)\n # return the array \n return array.astype(dtype=float)",
"_____no_output_____"
],
[
"# helper function, construct reliability matrix for cl question type\ndef to_reliability_cl(df):\n # one-hot-encode answer_label\n df = pd.get_dummies(df, columns = [\"answer_label\"])\n # combine rows \n df = df.groupby([\"quiz_task_uuid\", \"contributor_uuid\"]).agg(sum)\n # reset_index, so quiz_task_uuid and contributor_uuid become columns\n df = df.reset_index()\n # melt, prepare for pivot\n df = pd.melt(df, id_vars=[\"quiz_task_uuid\", \"contributor_uuid\"], \n var_name = \"choice\", \n value_name = \"value\")\n df[\"choice\"] = df[\"quiz_task_uuid\"].str.slice(start=0, stop=6) + \" \" + df[\"choice\"]\n pivot = pd.pivot_table(df, values='value', index='contributor_uuid', \n columns='choice', \n aggfunc=select)\n # to numpy array \n array = pivot.to_numpy()\n # return the array \n return array.astype(dtype=float)",
"_____no_output_____"
],
[
"# extract topic name (Argument/Holistic...) from df \ndef get_topic(df):\n # df - e.g. df after reading in \"Covid_Evidencev1-2020-10-04T1836-DataHunt.csv\"\n # return the first one coz that's fast than unique()\n try: \n return df[\"topic_name\"][0]\n except Exception as e:\n print(\"This dataframe is empty\")",
"_____no_output_____"
],
[
"# compute alpha values \ndef compute_alpha(input_directory, fileName, question_type, question_label, measurement, decimal_places):\n # input_directory - e.g. \"Specialist data\"\n # fileName - e.g. \"Covid_ArgumentRelevancev1.2-2020-10-04T1802-DataHunt.csv\"\n # question_type - \"mc\"/\"cl\"\n # question _label - e.g. \"T1.Q2\"\n # measurement - \"nominal\", \"ordinal\", \"interval\"\n # decimal_plaes - number of decimal places to be rounded \n array = to_reliability(input_directory, fileName, question_type, question_label)\n return np.round(alpha(reliability_data=array, level_of_measurement=measurement), decimal_places)",
"_____no_output_____"
],
[
"def get_question_types(repo, mapping):\n # repo - e.g. \"Specialists DataHuntByCase\"\n # mapping - e.g. specialist_dic\n for file in os.listdir(repo):\n name = os.path.join(repo, file)\n df = pd.read_csv(name)\n topic = get_topic(df)\n print(file)\n for question in df[\"question_label\"].unique():\n cur = get_question_type(topic, question)\n if cur == 'mc':\n measurement = get_measurement(topic, question, mapping)\n else:\n measurement = ''\n print(question, cur, measurement)",
"_____no_output_____"
],
[
"def calculate_alpha(repo, outrepo, mapping):\n # repo - e.g. \"Specialists DataHuntByCase\"\n # mapping - e.g. specialist_dic\n for file in os.listdir(repo):\n questions_list = []\n question_type_list = []\n sub_type = []\n alphas = [] \n pairable_list = []\n \n print()\n print(file)\n name = os.path.join(repo, file)\n df = pd.read_csv(name)\n try:\n topic = get_topic(df)\n # the dataframe might be empty\n except Exception as e: \n print(file, \"doesn't have any data\")\n continue\n questions = df[\"question_label\"].unique()\n # question - 'T1.Q1', 'T1.Q2'...\n for question in questions:\n # question_type - \"mc\"/\"cl\"/\"tx\"\n question_type = get_question_type(topic, question)\n if question_type == \"mc\":\n # \"categorical\"/\"ordinal\"\n try:\n reliability_array = to_reliability(repo, \n file,\n question_type, question)\n\n measurement = get_measurement(topic, question, mapping)\n pairs = count_pairable(reliability_array)\n value = alpha(reliability_data=reliability_array, level_of_measurement=measurement)\n print(question, question_type, measurement, \n 'alpha: {0}'.format(value), '# of pairable values: {0}'.format(pairs))\n # append in lists \n questions_list.append(question)\n question_type_list.append(question_type)\n sub_type.append(measurement)\n alphas.append(value) \n pairable_list.append(pairs)\n except Exception as e: \n print(question, question_type, e)\n questions_list.append(question)\n question_type_list.append(question_type)\n sub_type.append(measurement)\n alphas.append(e) \n pairable_list.append(pairs)\n elif question_type == \"cl\":\n copy = df[df[\"question_label\"] == question]\n \n cols = [\"quiz_task_uuid\", \"contributor_uuid\", \"answer_label\"]\n copy = copy.reindex(columns=cols)\n # how many answer_labels are there \n # answers - 'answer_label_T1.Q1.A1'\n answers = ['answer_label_' + answer for answer in copy[\"answer_label\"].unique()]\n # one-hot-encode\n copy = pd.get_dummies(copy, columns = [\"answer_label\"])\n # iterate through columns \n for col in answers: \n cur_col = [\"quiz_task_uuid\", \"contributor_uuid\"] + [col]\n df_slice = copy.reindex(columns=cur_col).copy()\n try:\n df_slice = pd.pivot_table(df_slice, values=col, index=\"contributor_uuid\", \n columns='quiz_task_uuid', aggfunc=lambda x: list(x)[0])\n array = df_slice.to_numpy()\n pairs = count_pairable(array)\n value = alpha(reliability_data=array, level_of_measurement=\"nominal\")\n print(question, question_type, col[13:], \n 'alpha: {0}'.format(value), '# of pairable values: {0}'.format(pairs))\n \n \n questions_list.append(question)\n question_type_list.append(question_type)\n sub_type.append(col[13:])\n alphas.append(value) \n pairable_list.append(pairs)\n except Exception as e:\n print(question, question_type, col[13:], e)\n \n questions_list.append(question)\n question_type_list.append(question_type)\n sub_type.append(col[13:])\n alphas.append(e) \n pairable_list.append(pairs)\n # write to csv \n output = pd.DataFrame({\"Question\": questions_list, \"Question_type\": question_type_list, \n \"Question_Subtype\": sub_type, \"Alpha\": alphas, \n \"Number of Pairable Elements\": pairable_list})\n path = os.path.join(outrepo, 'out'+file)\n output.to_csv(path)",
"_____no_output_____"
],
[
"def count_pairable(a):\n count = 0\n for i in range(a.shape[1]):\n col = a[:, i]\n # number of non-zero values \n true = ~pd.isnull(col)\n nozero = np.sum(true)\n count = count + nozero if nozero > 1 else count\n return count ",
"_____no_output_____"
]
],
[
[
"## Triager to uAlpha",
"_____no_output_____"
]
],
[
[
"# mapping topic_name to integers \ndef mapping(df, dic):\n # df - dataframe to be mapped \n # dic - dictionary of mapping \n df[\"topic_name\"] = df[\"topic_name\"].map(dic)\n return df \n\n\n# filter df and select only certain cols as input\ndef slice_input(df):\n cols = [\"contributor_uuid\", \"topic_name\", \"start_pos\",\n \"end_pos\", \"article_text_length\", \"article_number\", \"created\"]\n return df.reindex(columns=cols)\n\n\n# filter df and select only certain cols as output\ndef slice_output(df):\n cols = [\"contributor_uuid\", \"topic_name\", \"blank\", \n \"start_pos_adjusted\", \"end_pos_adjusted\"]\n return df.reindex(columns=cols)\n \n\n\n# read in a directory that contains Triager csvs \n# split each Triager csv to 4 other csvs based on topic_name (argument, reasoning, etc)\n# and write it as csvs in the output directory\ndef triager_split(input_directory, output_directory):\n # input_directory - e.g. \"Triager data\"\n # output_directory - e.g. \"Triager output\"\n for file in os.listdir(input_directory):\n triager_split_help(input_directory, file, output_directory)\n print(\"Triager Tranformation Done! Ready to be imported to uAlpha!\")",
"_____no_output_____"
],
[
"# resolve overlapping issues by merging overlapping rows!!!\ndef resolve_overlapping(df):\n # df - a dataframe with 5 cols {0: index, 1: user_id, 2:topic_name(as int), 3:blank, 4:start_pos, 5:end_pos}\n # this function only works when start_pos are sorted for each user!!!\n created = df[\"created\"].unique()\n # iterate through all unique user \n for time in created:\n # start and end index of that user \n start_i = df[df[\"created\"] == time].index.values[0]\n end_i = df[df[\"created\"] == time].index.values[-1]\n # iterate through the rows of that user \n i = start_i\n while i < end_i:\n # if the start_pos of next row > end_pos of this row\n # no overlap\n # 5 - the col of end_pos\n # the 10th column is end_pos_adjusted\n end_pos = df.iat[i, 10]\n # the 9th column is start_pos_adjusted\n start_pos = df.iat[i+1, 9]\n if start_pos > end_pos:\n i += 1 \n else:\n # if the article_number is the same, doesn't really matter \n # modify the end_pos of this row, merge \n if df.iat[i, 10] < df.iat[i+1 , 10]:\n df.iat[i, 10] = df.iat[i+1, 10].copy()\n # drop the next row \n df.drop(i+1, inplace=True)\n # reindex\n df.reset_index(drop=True, inplace=True)\n # decrement end_i \n end_i -= 1\n return df",
"_____no_output_____"
],
[
"# add adjusted start_pos and adjusted end_pos for df \ndef adjust(df):\n # df - a dataframe with [\"article_number\", \"article_text_length\", \"start_pos\", \"end_pos\"] cols\n article_number = df[\"article_number\"]\n article_text_length = df[\"article_text_length\"]\n start_pos = df[\"start_pos\"]\n end_pos = df[\"end_pos\"]\n # the cumulative sum of article_text_length\n cumulative = []\n start_pos_adjusted = []\n end_pos_adjusted = []\n pre_total = 0\n total = article_text_length[0]\n cur_num = article_number[0]\n for i in np.arange(len(article_number)):\n if article_number[i] == cur_num:\n total = total + 0\n cumulative.append(total)\n else:\n pre_total = total\n cur_num = article_number[i]\n total = total + article_text_length[i]\n cumulative.append(total)\n start_pos_adjusted.append(start_pos[i] + pre_total)\n end_pos_adjusted.append(end_pos[i] + pre_total)\n df[\"cumulative\"] = cumulative\n df[\"start_pos_adjusted\"] = start_pos_adjusted\n df[\"end_pos_adjusted\"] = end_pos_adjusted\n return df ",
"_____no_output_____"
],
[
"# take in a Triager csv and split it to 4 different csvs \n# based on topic_name \ndef triager_split_help(input_directory, fileName, output_directory):\n # input_directory - e.g. \"Triager data\"\n # fileName - e.g. \"Covid_Form1.0.adjudicated-2020-10-04T2314-Tags.csv\"\n # output_directory - e.g. \"Triager output\"\n name = os.path.join(input_directory, fileName)\n df = pd.read_csv(name)\n # different topic_names \n topic_names = df[\"topic_name\"].unique()\n for topic in topic_names: \n # select all rows for that specific topic name \n df_topic = df.loc[df[\"topic_name\"] == topic]\n # select only these columns \n filtered = slice_input(df_topic)\n # slice contributor_uuid with the first 6 chars \n filtered[\"contributor_uuid\"] = filtered[\"contributor_uuid\"].str[:6]\n # map topic_name to integers\n mapping(filtered, triager_dic)\n # add a blank column \n filtered.insert(loc=3, column=\"blank\", value=\"\")\n # sort\n filtered = filtered.sort_values(by=[\"article_number\", \"contributor_uuid\", \"start_pos\"])\n # re-index such that its index starts from 0 again\n filtered.reset_index(drop=True, inplace=True)\n # add modified columns\n filtered = adjust(filtered)\n # resolve overlapping issues \n filtered = resolve_overlapping(filtered)\n # filter and select only certain columns \n output = slice_output(filtered)\n # sort again by contributor\n output = output.sort_values(by=[\"contributor_uuid\", \"start_pos_adjusted\"])\n # add one column of u + str(row) and set it as index \n index = 'u' + pd.Series(filtered.index).astype(str)\n output.set_index(keys=index, inplace=True)\n # the batch_name, e.g. \"Covid\"\n batch_name = re.split(r'_', fileName)[0]\n name = '{0}-Triager-{1}.csv'.format(batch_name, topic)\n path = os.path.join(output_directory, name)\n # write to csvs\n output.to_csv(path, header=False)\n return None",
"_____no_output_____"
],
[
"# debugging function - find potential overlapping issue \ndef detect_overlapping(input_directory, fileName):\n # input directory - e.g. \"Triager output\"\n # fileName - e.g. \"Covid-Triager-Arguments.csv\"\n name = os.path.join(input_directory, fileName)\n df = pd.read_csv(name, header=None)\n # all the unique user \n users = df.iloc[:, 1].unique()\n # iterate through all unique user \n for user in users:\n # first only select the rows of that user \n # use copy to deal with the wanring\n piece = df.loc[df[1] == user].copy()\n # sort the 4th column\n piece.sort_values(by=4, inplace=True)\n # find or not\n found = False \n start_pos = np.array(piece[4])\n end_pos = np.array(piece[5])\n for i in np.arange(1, len(start_pos)):\n if start_pos[i] > end_pos[i-1]:\n continue\n else:\n found = True\n print('user {0}, start_pos {1}, end_pos {2} begin overlapping!'.format(user, start_pos[i], end_pos[i]))\n break \n return None ",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
ecd15214e6dc342f2f1ff07c7ae125ac6fc245c6 | 630,752 | ipynb | Jupyter Notebook | FFTonly/MatchedFilter.ipynb | connor-mcisaac/gw_test | 4bf59560e04aae3c0dd94f6b4df574e58a752de5 | [
"MIT"
] | null | null | null | FFTonly/MatchedFilter.ipynb | connor-mcisaac/gw_test | 4bf59560e04aae3c0dd94f6b4df574e58a752de5 | [
"MIT"
] | null | null | null | FFTonly/MatchedFilter.ipynb | connor-mcisaac/gw_test | 4bf59560e04aae3c0dd94f6b4df574e58a752de5 | [
"MIT"
] | null | null | null | 964.452599 | 137,484 | 0.951831 | [
[
[
"#Import required function\nimport numpy as np\nfrom scipy.interpolate import interp1d\nimport h5py\nimport matplotlib.pyplot as plt\nfrom pycbc.waveform import get_td_waveform\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"First import uncleaned data from Hanford during O1.",
"_____no_output_____"
]
],
[
[
"#Read a peice of strain data and make a time vector\nfilename = '../Data/H-H1_LOSC_4_V1-1126076416-4096.hdf5'\nf = h5py.File(filename, 'r')\nstrain = f['strain/Strain'][()]\ndt = f['strain/Strain'].attrs['Xspacing']\ntstart = f['meta/GPSstart'][()]\ntend = f['meta/Duration'][()] + tstart\nf.close()\n\n#Create a time vector starting at 0, and get the sampling frequency\nts = np.arange(0, tend-tstart, dt)\nfs = int(1/dt)\nprint('time =', (tend - tstart), ' nsamples =', len(strain), ' sample rate =', fs)\n\n#Plot 1 second of strain data\nplt.figure(figsize=(16, 6))\nplt.plot(ts[1000*fs:1001*fs], strain[1000*fs:1001*fs])\nplt.xlim([ts[1000*fs], ts[1001*fs]])\nplt.title('1 Second on uncleaned Hanford data')\nplt.xlabel('time - seconds')\nplt.ylabel('strain')\nplt.grid()",
"time = 4096 nsamples = 16777216 sample rate = 4096\n"
]
],
[
[
"Next generate a waveform of known parameters to input into the data for matched filtering",
"_____no_output_____"
]
],
[
[
"def Hann(n, N):\n \"\"\"Evalute a Hann window of length N at point n\"\"\"\n y = 0.5*(1-np.cos(2*np.pi*n/(N-1)))\n return y\n\n\ndef SGsignal(length, freq, freqm, max_amp):\n \"\"\"Define function that takes the required length in samples, the required freq in samples,\n the the gradient at which the frequency should increase and the max amplitude\n Return a sine function with frequency increasing with time to freq*freqm,\n starting at freq, multiplied by a gaussian with SD of length/6\"\"\"\n sd = length/6\n x = np.arange(length) - (length-length%2)/2.\n k = 2*np.pi*freq * np.linspace(1, freqm, num=length)\n y = max_amp * np.exp(-(x**2)/(2*(sd**2))) * np.sin(k*x)\n return x, y\n\n\n#Use pycbc to produce waveform, then convert to numpy array and smooth turn on\nhp0, hc0 = get_td_waveform(approximant=\"SEOBNRv4_opt\", mass1=10, mass2=10, delta_t=dt, f_lower=30, distance = 100)\ninc, theta, phi, psi = np.random.rand(1)[0]*np.pi/2, np.random.rand(1)[0]*np.pi/2, np.random.rand(1)[0]*np.pi, np.random.rand(1)[0]*np.pi\ninc, theta, phi, psi = inc.round(2), theta.round(2), phi.round(2), psi.round(2)\nfp = -0.5*(1+np.cos(theta)**2)*np.cos(2*phi)*np.cos(2*psi) - np.cos(theta)*np.sin(2*phi)*np.sin(2*psi)\nfc = 0.5*(1+np.cos(theta)**2)*np.cos(2*phi)*np.sin(2*psi) - np.cos(theta)*np.sin(2*phi)*np.cos(2*psi)\nh0 = fp*hp0*(1+np.cos(inc)**2)/2 + fc*hc0*np.cos(inc)\nh0[:100] *= Hann(np.arange(100), 200)\nh = h0.numpy()\nhp0[:100] *= Hann(np.arange(100), 200)\nhp = hp0.numpy()\nht = h0.sample_times.numpy()\n\n#Create a fake transient signal with high strain amplitude to test RSNR\nlengths_fake = 0.5 #length of signal in seconds\nfreqs_fake = 40. #freq in seconds^-1\nlength_fake, freq_fake, freqm_fake, maxa_fake = int(lengths_fake*fs), freqs_fake/fs, 2, 1e-20\nx_fake, y_fake = SGsignal(length_fake, freq_fake, freqm_fake, maxa_fake)\n\n#Plot both polarisations and the fake signal\nplt.figure(figsize=(16, 6))\nplt.subplot(1, 2, 1)\nplt.plot(ht, h)\nplt.xlim([ht[0], ht[-1]])\nplt.xlabel('time - seconds')\nplt.ylabel('strain')\nplt.grid()\nplt.subplot(1, 2, 2)\nplt.plot(x_fake*dt, y_fake)\nplt.xlim([x_fake[0]*dt, x_fake[-1]*dt])\nplt.xlabel('time - seconds')\nplt.ylabel('strain')\nplt.grid()",
"_____no_output_____"
]
],
[
[
"Next imput signal into data",
"_____no_output_____"
]
],
[
[
"#Place data within noise\neventi = int( np.random.rand(1) * (len(strain) - len(ht)) )\neventt = eventi*dt\ndata = np.zeros((len(strain)), dtype='float')\ndata[eventi:eventi+len(ht)] += h\ndata += strain\nprint('Event time =', eventt)\n\n#Place fake signal within noise\nfakei = int( np.random.rand(1) * (len(strain) - len(y_fake)) )\nfaket = fakei*dt\ndata[fakei:fakei+len(y_fake)] += y_fake\nprint('Fake time =', faket)\n\n#Plot new data time series around event\nplt.figure(figsize=(16, 6))\nplt.subplot(1, 2, 1)\nplt.plot(ts[eventi-fs:eventi+fs*4], data[eventi-fs:eventi+fs*4])\nplt.xlim([eventt-1, eventt+4])\nplt.title('Data time-series around injected event')\nplt.xlabel('time - seconds')\nplt.ylabel('strain')\nplt.grid()\nplt.subplot(1, 2, 2)\nplt.plot(ts[fakei-fs:fakei+fs*4], data[fakei-fs:fakei+fs*4])\nplt.xlim([faket-1, faket+4])\nplt.title('Data time-series around fake event')\nplt.xlabel('time - seconds')\nplt.ylabel('strain')\nplt.grid()",
"Event time = 871.65087890625\nFake time = 2985.354248046875\n"
]
],
[
[
"Now calculate the psd of the data using Welch's method, then whiten the data (whitened data won't be used in the match filtering, doing this purely for inspection).",
"_____no_output_____"
]
],
[
[
"def calcpsd(x, y, windowl, window):\n \"\"\"Calculate the PSD from the signal time series averaged from the PSDs of length windowl.\n Use given window to smooth each fft. Return the PSD as an interpolated function.\n Median correction term defined in FINDCHIRP paper.\"\"\"\n dx = x[1] - x[0]\n neach = int(windowl/dx)\n nfft = int(2 * len(y)//neach - 1)\n shift = int(np.ceil(neach/2))\n freq = np.fft.rfftfreq(neach, dx)\n asds = np.zeros((nfft, len(freq)), dtype='complex')\n psds = np.zeros((nfft, len(freq)), dtype='complex')\n mask = window(np.arange(neach), neach)\n for i in range(0, nfft):\n windowed = y[i*shift:i*shift + neach]*mask\n asds[i, :] = np.fft.rfft(windowed)*dx\n psds[i, :] = 2*(freq[1]-freq[0])*asds[i, :]*np.conj(asds[i, :])/(np.sum(mask**2)/neach)\n if nfft%2 == 0:\n median_correction = 1\n else:\n median_correction = np.sum(np.power(-1.*np.ones(nfft), np.arange(nfft)+2)/(np.arange(nfft)+1))\n psd = np.median(psds, axis=0)/median_correction\n psdi = interp1d(freq, np.real(psd), axis=0, bounds_error=False, fill_value=0)\n return psdi\n\n\ndef whiten(x, y, psd0):\n \"\"\"use interpolated psd to whiten given data\"\"\"\n dx = x[1] - x[0]\n num = np.size(x)\n fs = int(1/dx)\n freqs = np.fft.rfftfreq(num, dx)\n yft = np.fft.rfft(y)*dx\n white_yft = yft/np.sqrt(psd0(freqs))\n white_y = np.fft.irfft(white_yft)*(freqs[1]-freqs[0])*num\n return np.real(white_y)\n\n\n#Apply functions to data to find psd and whiten data\npsdcut = 4 #Length in seconds of the window used in Welch's method and truncation\npsdi = calcpsd(ts, data, psdcut, Hann)\nwhite_strain = whiten(ts, data, psdi)\n\n#Plot PSD evaluated from 30 to 1000Hz\nfplot = np.geomspace(10, 1500, num=1000, endpoint=True)\nplt.figure(figsize=(16, 6))\nplt.plot(fplot, psdi(fplot))\nplt.xlim([10, 1500])\nplt.ylim([1e-47, 1e-38])\nplt.xscale('log')\nplt.yscale('log')\nplt.title('PSD for data')\nplt.xlabel('frequency - hertz')\nplt.ylabel('Power')\nplt.grid()\n\n#Plot whitened data around event\nplt.figure(figsize=(16, 6))\nplt.subplot(1, 2, 1)\nplt.plot(ts[4*fs:-4*fs], white_strain[4*fs:-4*fs])\nplt.xlim([eventt-0.5, eventt+2.5])\nplt.ylim([-300, 300])\nplt.title('Whitened data time-series around injected event')\nplt.xlabel('time - seconds')\nplt.ylabel('whitened strain')\nplt.grid()\nplt.subplot(1, 2, 2)\nplt.plot(ts[4*fs:-4*fs], white_strain[4*fs:-4*fs])\nplt.xlim([faket-0.25, faket+0.75])\nplt.title('Whitened data time-series around fake event')\nplt.xlabel('time - seconds')\nplt.ylabel('whitened strain')\nplt.grid()",
"_____no_output_____"
]
],
[
[
"Next the psd must be inverted, inverse fourier transformed, truncated and fourier transformed to reduce the impulse response of the matched filter.",
"_____no_output_____"
]
],
[
[
"def itrunc_psd(psdi, psdcut, datax):\n \"\"\"inverts and trucates the psd for use in matched filtering.\n Evaluate the psd at the resolution of the data and invert it.\n Then inverse fourier transform the result and truncate to psdcut.\n Finally fourier transform this back to the frequency domain.\"\"\"\n dx = datax[1]-datax[0]\n fs = int(1/dx)\n freqs = np.fft.rfftfreq(len(datax), dx)\n inv_asd = 1/psdi(freqs)**0.5\n inv_asd_t = np.fft.irfft(inv_asd)*(freqs[1]-freqs[0])*len(datax)\n inv_asd_t[int(np.ceil(psdcut*fs/2)):int(np.floor(-psdcut*fs/2))] *= 0\n itrunc_a = np.fft.rfft(inv_asd_t)*dx\n itrunc = interp1d(freqs, itrunc_a*np.conj(itrunc_a), axis=0, bounds_error=False, fill_value=0)\n return itrunc\n\n\nit_psd = itrunc_psd(psdi, psdcut, ts)",
"_____no_output_____"
]
],
[
[
"The basic SNR time-series can now be calculated",
"_____no_output_____"
]
],
[
[
"def calcsnr(xdata, ydata, xtemp, ytemp, it_psd, psdcut):\n \"\"\"Perform the inner product of two signals given in the time domain\n return the resulting time-series scaled to snr. Assuming the resolutions are equal\"\"\"\n dx = xdata[1] - xdata[0]\n xft = np.fft.rfftfreq(len(xdata), dx)\n y1ft = np.fft.rfft(ydata)*dx\n if len(ytemp) < len(ydata):\n y2 = np.zeros((len(xdata)), dtype='float')\n y2[:len(ytemp)] += ytemp\n else:\n y2 = np.copy(ytemp)\n y2ft = np.fft.rfft(y2)*dx\n y2fti = y2ft*1j\n y3ft = it_psd(xft)\n innerft = y1ft*np.conj(y2ft)*y3ft\n innerfti = y1ft*np.conj(y2fti)*y3ft\n yinner = np.real(np.fft.irfft(innerft))*(xft[1]-xft[0])*len(xdata)\n yinneri = np.real(np.fft.irfft(innerfti))*(xft[1]-xft[0])*len(xdata)\n #norm0 = y3ft*np.abs(y2ft)**2\n #norm = np.real(np.sum(norm0*(xft[1]-xft[0])))\n norm0 = 0\n for i in range(0, len(y2ft)):\n norm0 += y3ft[i]*np.abs(y2ft[i])**2\n norm = np.real(norm0*(xft[1]-xft[0]))\n snr = ((yinner**2 + yinneri**2)/norm)**0.5\n dx = 1/(len(snr)*(xft[1] - xft[0]))\n cutstart = int(len(xtemp) + psdcut/dx + 1)\n cutend = int(psdcut/dx + 1)\n return xdata[cutstart:-cutend], snr[cutstart:-cutend]\n\n\ntsnr, snr = calcsnr(ts, data, ht, hp, it_psd, psdcut)\nplt.figure(figsize=(16, 6))\nplt.subplot(1, 2, 1)\nplt.plot(tsnr, snr)\nplt.xlim([tsnr[0], tsnr[-1]])\nplt.title('Simple SNR')\nplt.xlabel('time - seconds')\nplt.ylabel('SNR')\nplt.grid()\nplt.subplot(1, 2, 2)\nplt.plot(tsnr, snr)\nplt.xlim([eventt-.1, eventt+.1])\nplt.title('Simple SNR')\nplt.xlabel('time - seconds')\nplt.ylabel('SNR')\nplt.grid()\n\nprint('Max SNR at t =', tsnr[np.argmax(snr)], '\\nEvent missed by t =', np.abs(eventt-tsnr[np.argmax(snr)]),\n ' Fake missed by t =', np.abs(faket-tsnr[np.argmax(snr)]))",
"Max SNR at t = 2983.884765625 \nEvent missed by t = 2112.23388671875 Fake missed by t = 1.469482421875\n"
]
],
[
[
"Next apply a chi squared statistic by binning the template into bins of equal power and comparing the SNR of each with the data to the expected SNR.",
"_____no_output_____"
]
],
[
[
"def chi_rsnr(xdata, ydata, xtemp, ytemp, it_psd, psdcut, nbins, t, ind):\n dx = xdata[1] - xdata[0]\n xft = np.fft.rfftfreq(len(xdata), dx)\n y1ft = np.fft.rfft(ydata)*dx\n if len(ytemp) < len(ydata):\n y2 = np.zeros((len(xdata)), dtype='float')\n y2[:len(ytemp)] += ytemp\n else:\n y2 = np.copy(ytemp)\n y2ft = np.fft.rfft(y2)*dx\n y2fti = y2ft*1j\n y3ft = it_psd(xft)\n y2ftbin = np.zeros((len(y2ft), nbins), dtype='complex')\n norm0 = 0\n for i in range(0, len(y2ft)):\n norm0 += y3ft[i]*np.abs(y2ft[i])**2\n norm = np.real(norm0*(xft[1]-xft[0]))\n print(norm0)\n #power = np.sum((y3ft*np.abs(y2ft)**2))/nbins\n used = 0\n for i in range(0, nbins-1):\n pbin = 0\n count = 0\n while pbin < (norm0)/nbins:\n y2ftbin[used+count, i] += y2ft[used+count]\n pbin += (y3ft[used+count]*np.abs(y2ft[used+count])**2)\n count += 1\n print(pbin)\n used += count\n y2ftbin[used:, -1] += y2ft[used:]\n print(np.sum((y3ft*np.abs(y2ftbin[:, -1])**2)))\n y2ftbini = y2ftbin*1j\n innerft = y1ft*np.conj(y2ft)*y3ft\n innerfti = y1ft*np.conj(y2fti)*y3ft\n yinner = np.real(np.fft.irfft(innerft))*(xft[1]-xft[0])*len(xdata)\n yinneri = np.real(np.fft.irfft(innerfti))*(xft[1]-xft[0])*len(xdata)\n #norm0 = y3ft*np.abs(y2ft)**2\n #norm = np.real(np.sum(norm0*(xft[1]-xft[0])))\n snr = ((yinner**2)/norm)**0.5\n snri = ((yinneri**2)/norm)**0.5\n snrcomb = ((yinner**2 + yinneri**2)/norm)**0.5\n chibin = np.zeros((len(snrcomb), nbins), dtype='float')\n dx = 1/(len(snrcomb)*(xft[1] - xft[0]))\n plt.figure(figsize=(16, 6))\n plt.plot(xdata[ind-4000:ind+4000], snr[ind-4000:ind+4000], label='snr')\n plt.plot(xdata[ind-4000:ind+4000], snri[ind-4000:ind+4000], label='snri')\n for i in range(0, nbins):\n innerft = y1ft*np.conj(y2ftbin[:, i])*y3ft\n innerfti = y1ft*np.conj(y2ftbini[:, i])*y3ft\n yinner = np.real(np.fft.irfft(innerft))*(xft[1]-xft[0])*len(xdata)\n yinneri = np.real(np.fft.irfft(innerfti))*(xft[1]-xft[0])*len(xdata)\n snrbin = ((yinner**2)/norm)**0.5\n snrbini = ((yinneri**2)/norm)**0.5\n chibin[:, i] = (snrbin - snr/nbins)**2 + (snrbini - snri/nbins)**2\n plt.plot(xdata[ind-4000:ind+4000], snrbin[ind-4000:ind+4000], label=str(i))\n plt.plot(xdata[ind-4000:ind+4000], snrbini[ind-4000:ind+4000], label=str(i)+'i')\n plt.xlim([t-.1, t+.1])\n plt.legend()\n plt.grid()\n chi = nbins*np.sum(chibin, axis=1)/(nbins*2-2)\n rsnr = np.zeros((len(snrcomb)), dtype='float')\n for i in range(0, len(snrcomb)):\n if chi[i] > 1:\n rsnr[i] = snrcomb[i]/(((1 + chi[i]**3)/2.)**(1/6.))\n else:\n rsnr[i] = snrcomb[i]\n cutstart = int(len(xtemp) + psdcut/dx + 1)\n cutend = int(psdcut/dx + 1)\n return xdata[cutstart:-cutend], snrcomb[cutstart:-cutend], chi[cutstart:-cutend], rsnr[cutstart:-cutend]\n\n\ntchi, chisnr, chi, rsnr = chi_rsnr(ts, data, ht, hp, it_psd, psdcut, 4, eventt, eventi)\nplt.figure(figsize=(16, 6))\nplt.subplot(1, 2, 1)\nplt.plot(tchi, chi)\nplt.xlim([tchi[0], tchi[-1]])\nplt.title('Chi Squared Test')\nplt.xlabel('time - seconds')\nplt.ylabel('chi squared')\nplt.grid()\nplt.subplot(1, 2, 2)\nplt.plot(tchi, chi)\nplt.xlim([eventt-.1, eventt+.1])\nplt.ylim([0, 300])\nplt.title('Chi Squared Test')\nplt.xlabel('time - seconds')\nplt.ylabel('chi squared')\nplt.grid()\n\nplt.figure(figsize=(16, 6))\nplt.subplot(1, 2, 1)\nplt.plot(tchi, rsnr)\nplt.xlim([tchi[0], tchi[-1]])\nplt.title('Reduced SNR')\nplt.xlabel('time - seconds')\nplt.ylabel('RSNR')\nplt.grid()\nplt.subplot(1, 2, 2)\nplt.plot(tchi, rsnr)\nplt.xlim([eventt-1, eventt+1])\nplt.title('Reduced SNR')\nplt.xlabel('time - seconds')\nplt.ylabel('SNR')\nplt.grid()\n\nprint('Max RSNR at t =', tchi[np.argmax(rsnr)], '\\nEvent missed by t =', np.abs(eventt-tchi[np.argmax(rsnr)]),\n ' Fake missed by t =', np.abs(faket-tchi[np.argmax(rsnr)]))",
"(3786634.895678342+0j)\n(946660.6793759789+0j)\n(946666.460127077+0j)\n(946658.7601610867+0j)\n(946648.9960312987+0j)\nMax RSNR at t = 871.65087890625 \nEvent missed by t = 0.0 Fake missed by t = 2113.703369140625\n"
]
],
[
[
"The Chi-squared statistic helps reduced the transient signifigance.",
"_____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"
]
] |
ecd161a629c7d8735495a073b40591c15f5e231f | 36,731 | ipynb | Jupyter Notebook | Materias/MachineLearning_I/S3-RegresionLineal.ipynb | jorgeo80/UP_MDC | 1b1c484b2fcd1d0eefdce3df3a9df0ae2179a95b | [
"MIT"
] | null | null | null | Materias/MachineLearning_I/S3-RegresionLineal.ipynb | jorgeo80/UP_MDC | 1b1c484b2fcd1d0eefdce3df3a9df0ae2179a95b | [
"MIT"
] | null | null | null | Materias/MachineLearning_I/S3-RegresionLineal.ipynb | jorgeo80/UP_MDC | 1b1c484b2fcd1d0eefdce3df3a9df0ae2179a95b | [
"MIT"
] | null | null | null | 73.905433 | 14,548 | 0.840516 | [
[
[
"# Clase de Regresión",
"_____no_output_____"
]
],
[
[
"print('Hello-World')",
"Hello-World\n"
],
[
"import matplotlib.pyplot as plt\nfrom scipy import stats\n\nx = [5,7,8,7,2,17,2,9,4,11,12,9,6]\ny = [99,86,87,88,111,86,103,87,94,78,77,85,86]\n\nslope, intercept, r, p, std_err = stats.linregress(x, y)\n\ndef myfunc(x):\n return slope * x + intercept\n\nmymodel = list(map(myfunc, x))\n\nplt.scatter(x, y)\nplt.plot(x, mymodel)",
"_____no_output_____"
],
[
"mymodel",
"_____no_output_____"
],
[
"speed = myfunc(10)\nspeed",
"_____no_output_____"
],
[
"import numpy as np\n\ndiff = list(np.array(y) - np.array(mymodel)) # Diferencia entre la y observada y la y estimada\ncuadrado = [x ** 2 for x in diff] # Elevamos las diferencias al cuadrado\nerror_cuadratico_medio = (sum(cuadrado) / 13) # Hacemos la suma de los cuadrados y la dividimos entre el total de elementos\n\nprint(error_cuadratico_medio)",
"36.38976623082586\n"
],
[
"import math\n\nmath.sqrt(error_cuadratico_medio)",
"_____no_output_____"
],
[
"import numpy as np\n\nnp.square(diff).mean()",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_squared_error\n\nmse = mean_squared_error(y, mymodel)\nmse",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nfrom scipy import stats\n\nx = [89,43,36,36,95,10,66,34,38,20,26,29,48,64,6,5,36,66,72,40]\ny = [21,46,3,35,67,95,53,72,58,10,26,34,90,33,38,20,56,2,47,15]\n\nslope, intercept, r, p, std_err = stats.linregress(x, y)\n\ndef myfunc(x):\n return slope * x + intercept\n\nmymodel = list(map(myfunc, x))\n\nplt.scatter(x, y)\nplt.plot(x, mymodel)",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_squared_error\n\nmse = mean_squared_error(y, mymodel)\nmse",
"_____no_output_____"
],
[
"import numpy as np\n\ndiff = list(np.array(y) - np.array(mymodel)) # Diferencia entre la y observada y la y estimada\ncuadrado = [x ** 2 for x in diff] # Elevamos las diferencias al cuadrado\nerror_cuadratico_medio = (sum(cuadrado) / 20) # Hacemos la suma de los cuadrados y la dividimos entre el total de elementos\n\nprint(error_cuadratico_medio)",
"674.8277826085198\n"
],
[
"std_err",
"_____no_output_____"
]
],
[
[
"# Regresión Polinomial",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n\nx = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22]\ny = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100]\n\nplt.scatter(x, y)",
"_____no_output_____"
],
[
"import numpy\nimport matplotlib.pyplot as plt\n\nmymodel = numpy.poly1d(numpy.polyfit(x, y, 3))\n\nmyline = numpy.linspace(1, 22, 100)\n\nplt.scatter(x, y)\nplt.plot(myline, mymodel(myline))",
"_____no_output_____"
],
[
"speed = mymodel(25)\nspeed",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_squared_error\n\nmse = mean_squared_error(y, mymodel(np.array(y)))\nmse\n",
"_____no_output_____"
],
[
"import numpy as np\n\ndiff = list(np.array(y) - np.array(mymodel(y))) # Diferencia entre la y observada y la y estimada\ncuadrado = [x ** 2 for x in diff] # Elevamos las diferencias al cuadrado\nerror_cuadratico_medio = (sum(cuadrado) / 18) # Hacemos la suma de los cuadrados y la dividimos entre el total de elementos\n\nprint(error_cuadratico_medio)",
"109922964.46532571\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
ecd17f103693175955a1ef20cdb8d3e080ca8d23 | 218,663 | ipynb | Jupyter Notebook | apphub/adversarial_training/fgsm/fgsm.ipynb | gaurav272333/fastestimator | d49e48d7375e19416ef337b3517dcfe42bb56589 | [
"Apache-2.0"
] | 1 | 2019-10-03T00:40:12.000Z | 2019-10-03T00:40:12.000Z | apphub/adversarial_training/fgsm/fgsm.ipynb | gaurav272333/fastestimator | d49e48d7375e19416ef337b3517dcfe42bb56589 | [
"Apache-2.0"
] | null | null | null | apphub/adversarial_training/fgsm/fgsm.ipynb | gaurav272333/fastestimator | d49e48d7375e19416ef337b3517dcfe42bb56589 | [
"Apache-2.0"
] | 1 | 2020-04-28T12:16:10.000Z | 2020-04-28T12:16:10.000Z | 413.351607 | 192,296 | 0.911348 | [
[
[
"# Adversarial Training Using the Fast Gradient Sign Method (FGSM)\n\nIn this example we will demonstrate how to train a model to resist adversarial attacks constructed using the Fast Gradient Sign Method. For more background on adversarial attacks, visit: https://arxiv.org/abs/1412.6572",
"_____no_output_____"
],
[
"## Import the required libraries",
"_____no_output_____"
]
],
[
[
"import tempfile\nimport os\n\nimport numpy as np\n\nimport fastestimator as fe\nfrom fastestimator.architecture.tensorflow import LeNet\nfrom fastestimator.backend import to_tensor, argmax\nfrom fastestimator.dataset.data import cifair10\nfrom fastestimator.op.numpyop.meta import Sometimes\nfrom fastestimator.op.numpyop.multivariate import HorizontalFlip\nfrom fastestimator.op.numpyop.univariate import CoarseDropout, Normalize, Onehot\nfrom fastestimator.op.tensorop import Average\nfrom fastestimator.op.tensorop.gradient import Watch, FGSM\nfrom fastestimator.op.tensorop.loss import CrossEntropy\nfrom fastestimator.op.tensorop.model import ModelOp, UpdateOp\nfrom fastestimator.trace.io import BestModelSaver\nfrom fastestimator.trace.metric import Accuracy\nfrom fastestimator.util import ImgData, to_number",
"_____no_output_____"
],
[
"# training parameters\nepsilon=0.04 # The strength of the adversarial attack\nepochs=10\nbatch_size=50\nmax_train_steps_per_epoch=None\nmax_eval_steps_per_epoch=None\nsave_dir=tempfile.mkdtemp()",
"_____no_output_____"
]
],
[
[
"## Step 1 - Data and `Pipeline` preparation\nIn this step, we will load ciFAIR10 training and validation datasets and prepare FastEstimator's pipeline.\n\n### Load dataset \nWe use a FastEstimator API to load the ciFAIR10 dataset and then get a test set by splitting 50% of the data off of the evaluation set. ",
"_____no_output_____"
]
],
[
[
"from fastestimator.dataset.data import cifair10\n\ntrain_data, eval_data = cifair10.load_data()\ntest_data = eval_data.split(0.5)",
"_____no_output_____"
]
],
[
[
"### Prepare the `Pipeline`\nWe will use a simple pipeline that just normalizes the images",
"_____no_output_____"
]
],
[
[
"pipeline = fe.Pipeline(\n train_data=train_data,\n eval_data=eval_data,\n test_data=test_data,\n batch_size=batch_size,\n ops=[\n Normalize(inputs=\"x\", outputs=\"x\", mean=(0.4914, 0.4822, 0.4465), std=(0.2471, 0.2435, 0.2616))\n ])",
"_____no_output_____"
]
],
[
[
"## Step 2 - `Network` construction\n\n### Model Construction\nHere we will leverage the LeNet implementation built in to FastEstimator",
"_____no_output_____"
]
],
[
[
"model = fe.build(model_fn=lambda: LeNet(input_shape=(32, 32, 3)), optimizer_fn=\"adam\", model_name=\"adv_model\")",
"_____no_output_____"
]
],
[
[
"### `Network` defintion\nThis is where the adversarial attack will be implemented. To perform an FGSM attack, we first need to monitor gradients with respect to the input image. This can be accomplished in FastEstimator using the `Watch` TensorOp. We then will run the model forward once, compute the loss, and then pass the loss value into the `FGSM` TensorOp in order to create an adversarial image. We will then run the adversarial image through the model, compute the loss again, and average the two results together in order to update the model. ",
"_____no_output_____"
]
],
[
[
"network = fe.Network(ops=[\n Watch(inputs=\"x\"),\n ModelOp(model=model, inputs=\"x\", outputs=\"y_pred\"),\n CrossEntropy(inputs=(\"y_pred\", \"y\"), outputs=\"base_ce\"),\n FGSM(data=\"x\", loss=\"base_ce\", outputs=\"x_adverse\", epsilon=epsilon),\n ModelOp(model=model, inputs=\"x_adverse\", outputs=\"y_pred_adv\"),\n CrossEntropy(inputs=(\"y_pred_adv\", \"y\"), outputs=\"adv_ce\"),\n Average(inputs=(\"base_ce\", \"adv_ce\"), outputs=\"avg_ce\"),\n UpdateOp(model=model, loss_name=\"avg_ce\")\n ])",
"_____no_output_____"
]
],
[
[
"## Step 3 - `Estimator` definition and training\nIn this step, we define the `Estimator` to connect the `Network` with the `Pipeline` and set the `traces` which will compute accuracy (`Accuracy`) and save the best model (`BestModelSaver`) along the way. We will compute accuracy both with respect to the clean input images ('clean accuracy') as well as with respect to the adversarial input images ('adversarial accuracy'). At the end, we use `Estimator.fit` to trigger the training.",
"_____no_output_____"
]
],
[
[
"traces = [\n Accuracy(true_key=\"y\", pred_key=\"y_pred\", output_name=\"clean_accuracy\"),\n Accuracy(true_key=\"y\", pred_key=\"y_pred_adv\", output_name=\"adversarial_accuracy\"),\n BestModelSaver(model=model, save_dir=save_dir, metric=\"base_ce\", save_best_mode=\"min\"),\n]\nestimator = fe.Estimator(pipeline=pipeline,\n network=network,\n epochs=epochs,\n traces=traces,\n max_train_steps_per_epoch=max_train_steps_per_epoch,\n max_eval_steps_per_epoch=max_eval_steps_per_epoch,\n monitor_names=[\"base_ce\", \"adv_ce\"],\n log_steps=1000)",
"_____no_output_____"
],
[
"estimator.fit()",
" ______ __ ______ __ _ __ \n / ____/___ ______/ /_/ ____/____/ /_(_)___ ___ ____ _/ /_____ _____\n / /_ / __ `/ ___/ __/ __/ / ___/ __/ / __ `__ \\/ __ `/ __/ __ \\/ ___/\n / __/ / /_/ (__ ) /_/ /___(__ ) /_/ / / / / / / /_/ / /_/ /_/ / / \n/_/ \\__,_/____/\\__/_____/____/\\__/_/_/ /_/ /_/\\__,_/\\__/\\____/_/ \n \n\nFastEstimator-Start: step: 1; num_device: 0; logging_interval: 1000; \nFastEstimator-Train: step: 1; avg_ce: 2.3945074; adv_ce: 2.4872663; base_ce: 2.3017485; \nFastEstimator-Train: step: 1000; avg_ce: 1.3094263; adv_ce: 1.4686574; base_ce: 1.1501954; steps/sec: 25.77; \nFastEstimator-Train: step: 1000; epoch: 1; epoch_time: 42.87 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/adv_model_best_base_ce.h5\nFastEstimator-Eval: step: 1000; epoch: 1; avg_ce: 1.4899004; adv_ce: 1.6584656; base_ce: 1.3213345; clean_accuracy: 0.5408; adversarial_accuracy: 0.3734; since_best_base_ce: 0; min_base_ce: 1.3213345; \nFastEstimator-Train: step: 2000; avg_ce: 1.143224; adv_ce: 1.3376933; base_ce: 0.9487548; steps/sec: 34.22; \nFastEstimator-Train: step: 2000; epoch: 2; epoch_time: 29.22 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/adv_model_best_base_ce.h5\nFastEstimator-Eval: step: 2000; epoch: 2; avg_ce: 1.3468871; adv_ce: 1.5618094; base_ce: 1.1319652; clean_accuracy: 0.5928; adversarial_accuracy: 0.412; since_best_base_ce: 0; min_base_ce: 1.1319652; \nFastEstimator-Train: step: 3000; avg_ce: 1.379614; adv_ce: 1.6073439; base_ce: 1.1518841; steps/sec: 36.24; \nFastEstimator-Train: step: 3000; epoch: 3; epoch_time: 27.6 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/adv_model_best_base_ce.h5\nFastEstimator-Eval: step: 3000; epoch: 3; avg_ce: 1.3020732; adv_ce: 1.5298728; base_ce: 1.074274; clean_accuracy: 0.622; adversarial_accuracy: 0.4274; since_best_base_ce: 0; min_base_ce: 1.074274; \nFastEstimator-Train: step: 4000; avg_ce: 1.2436087; adv_ce: 1.4758196; base_ce: 1.0113977; steps/sec: 33.11; \nFastEstimator-Train: step: 4000; epoch: 4; epoch_time: 30.2 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/adv_model_best_base_ce.h5\nFastEstimator-Eval: step: 4000; epoch: 4; avg_ce: 1.2154673; adv_ce: 1.4576334; base_ce: 0.9733012; clean_accuracy: 0.665; adversarial_accuracy: 0.4618; since_best_base_ce: 0; min_base_ce: 0.9733012; \nFastEstimator-Train: step: 5000; avg_ce: 1.154286; adv_ce: 1.3962423; base_ce: 0.9123298; steps/sec: 32.78; \nFastEstimator-Train: step: 5000; epoch: 5; epoch_time: 30.51 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/adv_model_best_base_ce.h5\nFastEstimator-Eval: step: 5000; epoch: 5; avg_ce: 1.2138638; adv_ce: 1.4704447; base_ce: 0.9572834; clean_accuracy: 0.6696; adversarial_accuracy: 0.4552; since_best_base_ce: 0; min_base_ce: 0.9572834; \nFastEstimator-Train: step: 6000; avg_ce: 1.1946353; adv_ce: 1.4845756; base_ce: 0.904695; steps/sec: 33.34; \nFastEstimator-Train: step: 6000; epoch: 6; epoch_time: 29.99 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/adv_model_best_base_ce.h5\nFastEstimator-Eval: step: 6000; epoch: 6; avg_ce: 1.1873512; adv_ce: 1.4471037; base_ce: 0.9275986; clean_accuracy: 0.6784; adversarial_accuracy: 0.4648; since_best_base_ce: 0; min_base_ce: 0.9275986; \nFastEstimator-Train: step: 7000; avg_ce: 1.3036005; adv_ce: 1.5895638; base_ce: 1.0176373; steps/sec: 32.39; \nFastEstimator-Train: step: 7000; epoch: 7; epoch_time: 30.87 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/adv_model_best_base_ce.h5\nFastEstimator-Eval: step: 7000; epoch: 7; avg_ce: 1.1750631; adv_ce: 1.4450079; base_ce: 0.9051186; clean_accuracy: 0.6934; adversarial_accuracy: 0.4764; since_best_base_ce: 0; min_base_ce: 0.9051186; \nFastEstimator-Train: step: 8000; avg_ce: 1.1723398; adv_ce: 1.4465908; base_ce: 0.89808875; steps/sec: 32.64; \nFastEstimator-Train: step: 8000; epoch: 8; epoch_time: 30.64 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/adv_model_best_base_ce.h5\nFastEstimator-Eval: step: 8000; epoch: 8; avg_ce: 1.1422093; adv_ce: 1.4145594; base_ce: 0.869859; clean_accuracy: 0.702; adversarial_accuracy: 0.477; since_best_base_ce: 0; min_base_ce: 0.869859; \nFastEstimator-Train: step: 9000; avg_ce: 1.0794711; adv_ce: 1.3604188; base_ce: 0.7985235; steps/sec: 32.8; \nFastEstimator-Train: step: 9000; epoch: 9; epoch_time: 30.49 sec; \nFastEstimator-Eval: step: 9000; epoch: 9; avg_ce: 1.1585152; adv_ce: 1.4406301; base_ce: 0.8764003; clean_accuracy: 0.7014; adversarial_accuracy: 0.4746; since_best_base_ce: 1; min_base_ce: 0.869859; \nFastEstimator-Train: step: 10000; avg_ce: 1.2206926; adv_ce: 1.5394913; base_ce: 0.901894; steps/sec: 33.19; \nFastEstimator-Train: step: 10000; epoch: 10; epoch_time: 30.13 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/adv_model_best_base_ce.h5\nFastEstimator-Eval: step: 10000; epoch: 10; avg_ce: 1.1538234; adv_ce: 1.4526846; base_ce: 0.85496193; clean_accuracy: 0.7084; adversarial_accuracy: 0.4792; since_best_base_ce: 0; min_base_ce: 0.85496193; \nFastEstimator-Finish: step: 10000; total_time: 330.22 sec; adv_model_lr: 0.001; \n"
]
],
[
[
"## Model Testing\nLet's start by re-loading the weights from the best model, since the model may have overfit during training\n",
"_____no_output_____"
]
],
[
[
"model.load_weights(os.path.join(save_dir, \"adv_model_best_base_ce.h5\"))",
"_____no_output_____"
],
[
"estimator.test()",
"FastEstimator-Test: step: 10000; epoch: 10; clean_accuracy: 0.6962; adversarial_accuracy: 0.4758; \n"
]
],
[
[
"In spite of our training the network using adversarially crafted images, the adversarial attack is still effective at reducing the accuracy of the network. This does not, however, mean that the efforts were wasted. ",
"_____no_output_____"
],
[
"# Comparison vs Network without Adversarial Training\nTo see whether training using adversarial hardening was actually useful, we will compare it to a network which is trained without considering any adversarial images. The setup will be similar to before, but we will only use the adversarial images for evaluation purposes and so the second `CrossEntropy` Op as well as the `Average` Op can be omitted. ",
"_____no_output_____"
]
],
[
[
"clean_model = fe.build(model_fn=lambda: LeNet(input_shape=(32, 32, 3)), optimizer_fn=\"adam\", model_name=\"clean_model\")\nclean_network = fe.Network(ops=[\n Watch(inputs=\"x\"),\n ModelOp(model=clean_model, inputs=\"x\", outputs=\"y_pred\"),\n CrossEntropy(inputs=(\"y_pred\", \"y\"), outputs=\"base_ce\"),\n FGSM(data=\"x\", loss=\"base_ce\", outputs=\"x_adverse\", epsilon=epsilon, mode=\"!train\"),\n ModelOp(model=clean_model, inputs=\"x_adverse\", outputs=\"y_pred_adv\", mode=\"!train\"),\n UpdateOp(model=clean_model, loss_name=\"base_ce\")\n ])\nclean_traces = [\n Accuracy(true_key=\"y\", pred_key=\"y_pred\", output_name=\"clean_accuracy\"),\n Accuracy(true_key=\"y\", pred_key=\"y_pred_adv\", output_name=\"adversarial_accuracy\"),\n BestModelSaver(model=clean_model, save_dir=save_dir, metric=\"base_ce\", save_best_mode=\"min\"),\n]\nclean_estimator = fe.Estimator(pipeline=pipeline,\n network=clean_network,\n epochs=epochs,\n traces=clean_traces,\n max_train_steps_per_epoch=max_train_steps_per_epoch,\n max_eval_steps_per_epoch=max_eval_steps_per_epoch,\n log_steps=1000)\nclean_estimator.fit()",
" ______ __ ______ __ _ __ \n / ____/___ ______/ /_/ ____/____/ /_(_)___ ___ ____ _/ /_____ _____\n / /_ / __ `/ ___/ __/ __/ / ___/ __/ / __ `__ \\/ __ `/ __/ __ \\/ ___/\n / __/ / /_/ (__ ) /_/ /___(__ ) /_/ / / / / / / /_/ / /_/ /_/ / / \n/_/ \\__,_/____/\\__/_____/____/\\__/_/_/ /_/ /_/\\__,_/\\__/\\____/_/ \n \n\nFastEstimator-Start: step: 1; num_device: 0; logging_interval: 1000; \nFastEstimator-Train: step: 1; base_ce: 2.3599913; \nFastEstimator-Train: step: 1000; base_ce: 1.2336738; steps/sec: 81.68; \nFastEstimator-Train: step: 1000; epoch: 1; epoch_time: 12.53 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/clean_model_best_base_ce.h5\nFastEstimator-Eval: step: 1000; epoch: 1; base_ce: 1.1847152; clean_accuracy: 0.5684; adversarial_accuracy: 0.2694; since_best_base_ce: 0; min_base_ce: 1.1847152; \nFastEstimator-Train: step: 2000; base_ce: 0.81964266; steps/sec: 78.27; \nFastEstimator-Train: step: 2000; epoch: 2; epoch_time: 12.78 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/clean_model_best_base_ce.h5\nFastEstimator-Eval: step: 2000; epoch: 2; base_ce: 0.95957977; clean_accuracy: 0.6652; adversarial_accuracy: 0.2778; since_best_base_ce: 0; min_base_ce: 0.95957977; \nFastEstimator-Train: step: 3000; base_ce: 0.9629886; steps/sec: 78.25; \nFastEstimator-Train: step: 3000; epoch: 3; epoch_time: 12.78 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/clean_model_best_base_ce.h5\nFastEstimator-Eval: step: 3000; epoch: 3; base_ce: 0.8996327; clean_accuracy: 0.6946; adversarial_accuracy: 0.263; since_best_base_ce: 0; min_base_ce: 0.8996327; \nFastEstimator-Train: step: 4000; base_ce: 0.7768238; steps/sec: 77.71; \nFastEstimator-Train: step: 4000; epoch: 4; epoch_time: 12.87 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/clean_model_best_base_ce.h5\nFastEstimator-Eval: step: 4000; epoch: 4; base_ce: 0.86543256; clean_accuracy: 0.702; adversarial_accuracy: 0.2576; since_best_base_ce: 0; min_base_ce: 0.86543256; \nFastEstimator-Train: step: 5000; base_ce: 0.7760873; steps/sec: 77.93; \nFastEstimator-Train: step: 5000; epoch: 5; epoch_time: 12.83 sec; \nFastEstimator-BestModelSaver: Saved model to /var/folders/lx/drkxftt117gblvgsp1p39rlc0000gn/T/tmpmwpkk98d/clean_model_best_base_ce.h5\nFastEstimator-Eval: step: 5000; epoch: 5; base_ce: 0.7983937; clean_accuracy: 0.727; adversarial_accuracy: 0.2664; since_best_base_ce: 0; min_base_ce: 0.7983937; \nFastEstimator-Train: step: 6000; base_ce: 0.56715065; steps/sec: 78.43; \nFastEstimator-Train: step: 6000; epoch: 6; epoch_time: 12.75 sec; \nFastEstimator-Eval: step: 6000; epoch: 6; base_ce: 0.79985946; clean_accuracy: 0.7318; adversarial_accuracy: 0.2704; since_best_base_ce: 1; min_base_ce: 0.7983937; \nFastEstimator-Train: step: 7000; base_ce: 0.7633059; steps/sec: 72.81; \nFastEstimator-Train: step: 7000; epoch: 7; epoch_time: 13.74 sec; \nFastEstimator-Eval: step: 7000; epoch: 7; base_ce: 0.80506575; clean_accuracy: 0.73; adversarial_accuracy: 0.2464; since_best_base_ce: 2; min_base_ce: 0.7983937; \nFastEstimator-Train: step: 8000; base_ce: 0.57881784; steps/sec: 76.72; \nFastEstimator-Train: step: 8000; epoch: 8; epoch_time: 13.03 sec; \nFastEstimator-Eval: step: 8000; epoch: 8; base_ce: 0.8497379; clean_accuracy: 0.733; adversarial_accuracy: 0.214; since_best_base_ce: 3; min_base_ce: 0.7983937; \nFastEstimator-Train: step: 9000; base_ce: 0.61386603; steps/sec: 78.1; \nFastEstimator-Train: step: 9000; epoch: 9; epoch_time: 12.81 sec; \nFastEstimator-Eval: step: 9000; epoch: 9; base_ce: 0.84185517; clean_accuracy: 0.731; adversarial_accuracy: 0.2206; since_best_base_ce: 4; min_base_ce: 0.7983937; \nFastEstimator-Train: step: 10000; base_ce: 0.6447299; steps/sec: 77.0; \nFastEstimator-Train: step: 10000; epoch: 10; epoch_time: 12.99 sec; \nFastEstimator-Eval: step: 10000; epoch: 10; base_ce: 0.8941338; clean_accuracy: 0.7278; adversarial_accuracy: 0.1848; since_best_base_ce: 5; min_base_ce: 0.7983937; \nFastEstimator-Finish: step: 10000; total_time: 148.17 sec; clean_model_lr: 0.001; \n"
]
],
[
[
"As before, we will reload the best weights and the test the model",
"_____no_output_____"
]
],
[
[
"clean_model.load_weights(os.path.join(save_dir, \"clean_model_best_base_ce.h5\"))",
"_____no_output_____"
],
[
"print(\"Normal Network:\")\nnormal_results = clean_estimator.test(\"normal\")\nprint(\"The whitebox FGSM attack reduced accuracy by {:.2f}\".format(list(normal_results.history['test']['clean_accuracy'].values())[0] - list(normal_results.history['test']['adversarial_accuracy'].values())[0]))\nprint(\"-----------\")\nprint(\"Adversarially Trained Network:\")\nadversarial_results = estimator.test(\"adversarial\")\nprint(\"The whitebox FGSM attack reduced accuracy by {:.2f}\".format(list(adversarial_results.history['test']['clean_accuracy'].values())[0] - list(adversarial_results.history['test']['adversarial_accuracy'].values())[0]))\nprint(\"-----------\")",
"Normal Network:\nFastEstimator-Test: step: 10000; epoch: 10; clean_accuracy: 0.7178; adversarial_accuracy: 0.2674; \nThe whitebox FGSM attack reduced accuracy by 0.45\n-----------\nAdversarially Trained Network:\nFastEstimator-Test: step: 10000; epoch: 10; clean_accuracy: 0.6962; adversarial_accuracy: 0.4758; \nThe whitebox FGSM attack reduced accuracy by 0.22\n-----------\n"
]
],
[
[
"As we can see, the normal network is significantly less robust against adversarial attacks than the one which was trained to resist them. The downside is that the adversarial network requires more epochs of training to converge, and the training steps take about twice as long since they require two forward pass operations. It is also interesting to note that as the regular model was training, it actually saw progressively worse adversarial accuracy. This may be an indication that the network is developing very brittle decision boundaries. ",
"_____no_output_____"
],
[
"## Visualizing Adversarial Samples\nLets visualize some images generated by these adversarial attacks to make sure that everything is working as we would expect. The first step is to get some sample data from the pipeline:",
"_____no_output_____"
]
],
[
[
"class_dictionary = {\n 0: \"airplane\", 1: \"car\", 2: \"bird\", 3: \"cat\", 4: \"deer\", 5: \"dog\", 6: \"frog\", 7: \"horse\", 8: \"ship\", 9: \"truck\"\n}\nbatch = pipeline.get_results(mode=\"test\")",
"_____no_output_____"
]
],
[
[
"Now let's run our sample data through the network and then visualize the results",
"_____no_output_____"
]
],
[
[
"batch = clean_network.transform(batch, mode=\"test\")",
"_____no_output_____"
],
[
"n_samples = 10\ny = np.array([class_dictionary[clazz.item()] for clazz in to_number(batch[\"y\"][0:n_samples])])\ny_pred = np.array([class_dictionary[clazz.item()] for clazz in to_number(argmax(batch[\"y_pred\"], axis=1)[0:n_samples])])\ny_adv = np.array([class_dictionary[clazz.item()] for clazz in to_number(argmax(batch[\"y_pred_adv\"], axis=1)[0:n_samples])])\nimg = ImgData(x=batch[\"x\"][0:n_samples], x_adverse=batch[\"x_adverse\"][0:n_samples], y=y, y_pred=y_pred, y_adv=y_adv)\nfig = img.paint_figure()",
"_____no_output_____"
]
],
[
[
"As you can see, the adversarial images appear very similar to the unmodified images, and yet they are often able to modify the class predictions of the network. Note that if a network's prediction is already wrong, the attack is unlikely to change the incorrect prediction, but rather to increase the model's confidence in its incorrect prediction. ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.